content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
helpstring = "voice <nick>" arguments = ["self", "info", "args"] minlevel = 3 def main(connection, info, args) : """Voices a user""" for person in args[1:] : connection.rawsend("MODE %s +v %s\n" % (info["channel"], person))
helpstring = 'voice <nick>' arguments = ['self', 'info', 'args'] minlevel = 3 def main(connection, info, args): """Voices a user""" for person in args[1:]: connection.rawsend('MODE %s +v %s\n' % (info['channel'], person))
# # PySNMP MIB module CISCO-ZS-EXT-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-ZS-EXT-MIB # Produced by pysmi-0.3.4 at Wed May 1 12:21:44 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueSizeConstraint, ValueRangeConstraint, ConstraintsIntersection, SingleValueConstraint, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "ValueRangeConstraint", "ConstraintsIntersection", "SingleValueConstraint", "ConstraintsUnion") ciscoMgmt, = mibBuilder.importSymbols("CISCO-SMI", "ciscoMgmt") vsanIndex, = mibBuilder.importSymbols("CISCO-VSAN-MIB", "vsanIndex") ModuleCompliance, NotificationGroup, ObjectGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup", "ObjectGroup") ObjectIdentity, IpAddress, Gauge32, ModuleIdentity, MibScalar, MibTable, MibTableRow, MibTableColumn, iso, NotificationType, Integer32, TimeTicks, Unsigned32, Counter64, Bits, Counter32, MibIdentifier = mibBuilder.importSymbols("SNMPv2-SMI", "ObjectIdentity", "IpAddress", "Gauge32", "ModuleIdentity", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "iso", "NotificationType", "Integer32", "TimeTicks", "Unsigned32", "Counter64", "Bits", "Counter32", "MibIdentifier") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") ciscoZsExtMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 9, 9, 427)) ciscoZsExtMIB.setRevisions(('2006-01-03 00:00', '2004-08-11 00:00',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: ciscoZsExtMIB.setRevisionsDescriptions(('Added objects czseGlobalDefaultZoneBehaviour and czseGlobalPropagationMode.', 'Initial version of this MIB.',)) if mibBuilder.loadTexts: ciscoZsExtMIB.setLastUpdated('200601030000Z') if mibBuilder.loadTexts: ciscoZsExtMIB.setOrganization('Cisco Systems Inc.') if mibBuilder.loadTexts: ciscoZsExtMIB.setContactInfo(' Cisco Systems Customer Service Postal: 170 W Tasman Drive San Jose, CA 95134 USA Tel: +1 800 553 -NETS E-mail: cs-san@cisco.com') if mibBuilder.loadTexts: ciscoZsExtMIB.setDescription("The MIB module for the management of zoning within the framework of Cisco's Zoning Server (ZS) Archi- tecture which realizes the FC-GS4/SW3 requirements for Zone Server. This MIB is an extension to the CISCO-ZS-MIB, which is for managing zoning conforming to FC-GS3/SW2. The FC-GS4 specification is Fibre-Channel - Generic Services - 4 T11/ Project 1505-D/Rev 7.8. The SW3 specification is Fibre-Channel - Switch Fabric - 3 T11/Project 1508- D/Rev 6.6. GS4/SW3 allows zoning to operate in either basic or enhanced mode of operation. Basic mode is essentially GS3/SW2 compatible mode (as modelled by CISCO-ZS-MIB). Enhanced mode of operation provides additional capabilities. In enhanced mode of operation, all the configuration should be done within the scope of a session. The current 'Running Configuration' on the local device for zone server is called the 'effective' database. When the first configuration command on the zone server data is received, a snapshot of the current 'effective database' is taken on the local device. This snapshot is called the 'copy' database. An implicit session is started by the Zone Server on the local device and all subsequent SET operations take place in the context of this session. The 'copy' database is used for all further modifications in the session. There can be only one session active in the entire Fibre Channel fabric. The user who initiates the creation of this 'copy', is called the owner of session. When a session has been created on a device in the Fibre Channel fabric, if an attempt is made to start a session from any other device in the fabric, it results in error. Once the modifications to the 'copy' are done, a 'commit' operation can be done. The 'commit' done on the local device, results in the local 'effective database' being overwritten with the 'copy' and then the new local 'effective database' is distributed to all other devices in the Fibre Channel fabric. The successful 'commit' operation also results in destroying the 'copy' on the local device. The 'commit' can only be performed by the owner of the session. The 'copy' can optionally be destroyed without any distribution. This can be done by performing a 'clear' operation. Glossary of terms used in this MIB ---------------------------------- VSAN - Virtual Storage Area Network.") ciscoZsExtMIBNotifs = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 427, 0)) ciscoZsExtMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 427, 1)) ciscoZsExtMIBConform = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 427, 2)) czseConfiguration = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 427, 1, 1)) czseStats = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 427, 1, 2)) class CzseSessOwnerType(TextualConvention, Integer32): description = 'Represents the type of owner of a GS4 session. other - other type of owner. cli - Command Line Interface (CLI) is the owner. gs4client - Fibre Channel GS4 services client. snmp - SNMP is the owner.' status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4)) namedValues = NamedValues(("other", 1), ("cli", 2), ("gs4client", 3), ("snmp", 4)) czseCapabilityTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 427, 1, 1, 1), ) if mibBuilder.loadTexts: czseCapabilityTable.setStatus('current') if mibBuilder.loadTexts: czseCapabilityTable.setDescription('This table lists the capabilities of the Zone Server on the local device. This information is maintained on a per VSAN basis.') czseCapabilityEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 427, 1, 1, 1, 1), ).setIndexNames((0, "CISCO-VSAN-MIB", "vsanIndex")) if mibBuilder.loadTexts: czseCapabilityEntry.setStatus('current') if mibBuilder.loadTexts: czseCapabilityEntry.setDescription('An entry represents the capability of the Zone Server on the local device on a VSAN.') czseCapabilityObject = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 427, 1, 1, 1, 1, 1), Bits().clone(namedValues=NamedValues(("enhancedMode", 0), ("zsetDb", 1), ("dirAct", 2), ("hardZoning", 3)))).setMaxAccess("readonly") if mibBuilder.loadTexts: czseCapabilityObject.setReference('Fibre-Channel - Switch fabric - 3 T11/ Project 1505-D/Rev 6.6 Section 6.1.22.4.4') if mibBuilder.loadTexts: czseCapabilityObject.setStatus('current') if mibBuilder.loadTexts: czseCapabilityObject.setDescription("This bitmap represents the capability of the local Zone Server on this VSAN. If 'enhancedMode(0)' bit is set, the local Zone Server is capable of supporting enhanced Zoning mode of operation. If this bit is reset, it does not have this capability. If 'zsetDb(1)' bit is set, the local Zone Server supports maintaining of zoneset database. If this bit is reset, the local Zone Server does not allow maintaining of zoneset database. If 'dirAct(2)' bit is set, the local Zone Server supports direct activation command. If this bit is reset, the local Zone Server does not support this. If 'hardZoning(3)' bit is set, the local Zone Server supports hard zoning. If this bit is reset, the local Zone Server does not support hard zoning.") czseModeTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 427, 1, 1, 2), ) if mibBuilder.loadTexts: czseModeTable.setStatus('current') if mibBuilder.loadTexts: czseModeTable.setDescription('A table containing information on the mode of operation of the zone server on all VSANs on the local device.') czseModeEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 427, 1, 1, 2, 1), ).setIndexNames((0, "CISCO-VSAN-MIB", "vsanIndex")) if mibBuilder.loadTexts: czseModeEntry.setStatus('current') if mibBuilder.loadTexts: czseModeEntry.setDescription('An entry represents the mode of operation of the local zone server on a VSAN. The mode can be modified on a VSAN and the outcome of the operation obtained.') czseOperationMode = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 427, 1, 1, 2, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("basic", 1), ("enhanced", 2))).clone('basic')).setMaxAccess("readwrite") if mibBuilder.loadTexts: czseOperationMode.setReference('Fibre-Channel - Generic Services - 4 T11/ Project 1505-D/Rev 7.8 Section 6.4.7. Fibre-Channel - Switch fabric - 3 T11/ Project 1505-D/Rev 6.6 Section 10.6') if mibBuilder.loadTexts: czseOperationMode.setStatus('current') if mibBuilder.loadTexts: czseOperationMode.setDescription("This object when set to 'basic(1)', results in the zone server operating in the basic mode as defined by FC-GS4 standards. This object when set to 'enhanced(2)', results in the zone server operating in the enhanced mode as defined by FC-GS4 standards. The local zone server can move to the enhanced mode of operation only if all devices in the Fibre Channel fabric are capable of working in enhanced mode. Otherwise, the set operation trying to set this object to 'enhanced(2)' will fail.") czseOperationModeResult = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 427, 1, 1, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("success", 1), ("failure", 2), ("inProgress", 3)))).setMaxAccess("readonly") if mibBuilder.loadTexts: czseOperationModeResult.setStatus('current') if mibBuilder.loadTexts: czseOperationModeResult.setDescription('The outcome of setting the mode of operation of the local Zone Server on this VSAN.') czseReadFrom = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 427, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("effectiveDB", 1), ("copyDB", 2))).clone('effectiveDB')).setMaxAccess("readwrite") if mibBuilder.loadTexts: czseReadFrom.setStatus('current') if mibBuilder.loadTexts: czseReadFrom.setDescription("This object specifies whether the management station wishes to read from the 'effective database' or from the 'copy' database.") czseSessionTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 427, 1, 1, 4), ) if mibBuilder.loadTexts: czseSessionTable.setStatus('current') if mibBuilder.loadTexts: czseSessionTable.setDescription("A table containing information on sessions on the local device on all VSANs. Operations are permitted on this table only when the zone server is running in 'enhanced' mode.") czseSessionEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 427, 1, 1, 4, 1), ).setIndexNames((0, "CISCO-VSAN-MIB", "vsanIndex")) if mibBuilder.loadTexts: czseSessionEntry.setStatus('current') if mibBuilder.loadTexts: czseSessionEntry.setDescription('An entry contains information on the owner of a session on a VSAN. It also assists in performing commit/clear operations on the session.') czseSessionOwnerType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 427, 1, 1, 4, 1, 1), CzseSessOwnerType()).setMaxAccess("readonly") if mibBuilder.loadTexts: czseSessionOwnerType.setStatus('current') if mibBuilder.loadTexts: czseSessionOwnerType.setDescription('This object specifies the owner type for this session.') czseSessionOwner = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 427, 1, 1, 4, 1, 2), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 64))).setMaxAccess("readonly") if mibBuilder.loadTexts: czseSessionOwner.setStatus('current') if mibBuilder.loadTexts: czseSessionOwner.setDescription("This object specifies the owner for this session. If the value of the corresponding instance of czseSessionOwnerType object is 'cli', this object will contain the user name of the CLI (Command Line Interface) user, who is the owner of the session on this VSAN. If the value of the corresponding instance of czseSessionOwnerType is 'gs4client', this object will contain the FCID of the GS4 management station, which is the owner of the session on this VSAN. If the value of the corresponding instance of czseSessionOwnerType is 'snmp', this object will contain the IP address of the management station, which is the owner of the session on this VSAN.") czseSessionCntl = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 427, 1, 1, 4, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("commitChanges", 1), ("cleanup", 2), ("noop", 3)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: czseSessionCntl.setStatus('current') if mibBuilder.loadTexts: czseSessionCntl.setDescription("This object assists in committing or clearing the contents of the 'copy' database on this session. No action is taken if this object is set to 'noop(3)'. The value of this object when read is always 'noop(3)'. The above operation can only be performed by the owner of the session.") czseSessionCntlResult = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 427, 1, 1, 4, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("commitSuccess", 1), ("commitFailure", 2), ("inProgress", 3)))).setMaxAccess("readonly") if mibBuilder.loadTexts: czseSessionCntlResult.setStatus('current') if mibBuilder.loadTexts: czseSessionCntlResult.setDescription("This object indicates the outcome of setting the corresponding instance of czseSessionCntl object to 'commitChanges(1)'.") czseMergeControlTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 427, 1, 1, 5), ) if mibBuilder.loadTexts: czseMergeControlTable.setStatus('current') if mibBuilder.loadTexts: czseMergeControlTable.setDescription("A table containing information on zone merge control policy on all VSANs in the entire fabric. Operations on this table are permitted only when the zone server is running in 'enhanced' mode.") czseMergeControlEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 427, 1, 1, 5, 1), ).setIndexNames((0, "CISCO-VSAN-MIB", "vsanIndex")) if mibBuilder.loadTexts: czseMergeControlEntry.setReference('Fibre-Channel - Switch fabric - 3 T11/ Project 1505-D/Rev 6.6 Section 10.5.2.2') if mibBuilder.loadTexts: czseMergeControlEntry.setStatus('current') if mibBuilder.loadTexts: czseMergeControlEntry.setDescription('An entry contains information on the Merge Control policy on a VSAN. The policy can be modified on a per VSAN basis by making use of czseMergeContolRestrict object.') czseMergeControlRestrict = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 427, 1, 1, 5, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("allow", 1), ("restrict", 2))).clone('allow')).setMaxAccess("readwrite") if mibBuilder.loadTexts: czseMergeControlRestrict.setStatus('current') if mibBuilder.loadTexts: czseMergeControlRestrict.setDescription("This object controls the zone merge behavior. If this object is set to 'allow', then the merge takes place according to the merge rules. If this object is set to 'restrict', then if the merging databases are not exactly identical, the Inter-Switch Link (ISL) between the devices is isolated.") czseGlobalDefaultZoneBehaviour = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 427, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("permit", 1), ("deny", 2))).clone('deny')).setMaxAccess("readwrite") if mibBuilder.loadTexts: czseGlobalDefaultZoneBehaviour.setStatus('current') if mibBuilder.loadTexts: czseGlobalDefaultZoneBehaviour.setDescription("This object represents the initial value for default zone behaviour on a VSAN when it is created. If a VSAN were to be deleted and re-created again, the default zone behaviour will be set to the value specified for this object. The semantics of setting this object to 'permit' or 'deny' are described in the description for zoneDefaultZoneBehaviour object in CISCO-ZS-MIB. After a VSAN has been created, if the value for default zone behaviour for that VSAN has to be changed, the zoneDefaultZoneBehaviour object in CISCO-ZS-MIB has to be used.") czseGlobalPropagationMode = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 427, 1, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("fullZoneset", 1), ("activeZoneset", 2))).clone('activeZoneset')).setMaxAccess("readwrite") if mibBuilder.loadTexts: czseGlobalPropagationMode.setStatus('current') if mibBuilder.loadTexts: czseGlobalPropagationMode.setDescription("This object represents the initial value for zone set propagation mode on a VSAN when it is created. If a VSAN were to be deleted and re-created again, the zone set propagation mode will be set to the value specified for this object. The semantics of setting this object to 'fullZoneset' or 'activeZoneset' are described in the description for zoneSetPropagationMode object in CISCO-ZS-MIB. After a VSAN has been created, if the value for zone set propagation mode has to be changed for that particular VSAN, the zoneSetPropagationMode object in CISCO-ZS-MIB has to be used.") ciscoZsExtMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 427, 2, 1)) ciscoZsExtMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 427, 2, 2)) ciscoZsExtMIBCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 427, 2, 1, 1)).setObjects(("CISCO-ZS-EXT-MIB", "ciscoZsExtConfigGroup")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoZsExtMIBCompliance = ciscoZsExtMIBCompliance.setStatus('deprecated') if mibBuilder.loadTexts: ciscoZsExtMIBCompliance.setDescription('The compliance statement for entities which implement the Zone Server conforming to FC-GS4/SW3.') ciscoZsExtMIBComplianceRev1 = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 427, 2, 1, 2)).setObjects(("CISCO-ZS-EXT-MIB", "ciscoZsExtConfigGroup"), ("CISCO-ZS-EXT-MIB", "ciscoZsExtConfigGroupSup1")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoZsExtMIBComplianceRev1 = ciscoZsExtMIBComplianceRev1.setStatus('current') if mibBuilder.loadTexts: ciscoZsExtMIBComplianceRev1.setDescription('The compliance statement for entities which implement the Zone Server conforming to FC-GS4/SW3.') ciscoZsExtConfigGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 427, 2, 2, 1)).setObjects(("CISCO-ZS-EXT-MIB", "czseCapabilityObject"), ("CISCO-ZS-EXT-MIB", "czseOperationMode"), ("CISCO-ZS-EXT-MIB", "czseOperationModeResult"), ("CISCO-ZS-EXT-MIB", "czseReadFrom"), ("CISCO-ZS-EXT-MIB", "czseSessionOwnerType"), ("CISCO-ZS-EXT-MIB", "czseSessionOwner"), ("CISCO-ZS-EXT-MIB", "czseSessionCntl"), ("CISCO-ZS-EXT-MIB", "czseSessionCntlResult"), ("CISCO-ZS-EXT-MIB", "czseMergeControlRestrict")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoZsExtConfigGroup = ciscoZsExtConfigGroup.setStatus('current') if mibBuilder.loadTexts: ciscoZsExtConfigGroup.setDescription('A collection of object(s) for configuring and displaying Zone Server conforming with FC-GS4/SW3.') ciscoZsExtConfigGroupSup1 = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 427, 2, 2, 2)).setObjects(("CISCO-ZS-EXT-MIB", "czseGlobalDefaultZoneBehaviour"), ("CISCO-ZS-EXT-MIB", "czseGlobalPropagationMode")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoZsExtConfigGroupSup1 = ciscoZsExtConfigGroupSup1.setStatus('current') if mibBuilder.loadTexts: ciscoZsExtConfigGroupSup1.setDescription('A collection of objects for configuring global zoning policies.') mibBuilder.exportSymbols("CISCO-ZS-EXT-MIB", czseOperationMode=czseOperationMode, czseSessionEntry=czseSessionEntry, czseMergeControlTable=czseMergeControlTable, czseSessionOwnerType=czseSessionOwnerType, czseMergeControlEntry=czseMergeControlEntry, PYSNMP_MODULE_ID=ciscoZsExtMIB, czseOperationModeResult=czseOperationModeResult, czseCapabilityTable=czseCapabilityTable, ciscoZsExtMIBCompliance=ciscoZsExtMIBCompliance, ciscoZsExtMIB=ciscoZsExtMIB, czseModeEntry=czseModeEntry, czseModeTable=czseModeTable, czseSessionCntlResult=czseSessionCntlResult, czseCapabilityObject=czseCapabilityObject, czseSessionOwner=czseSessionOwner, czseCapabilityEntry=czseCapabilityEntry, ciscoZsExtMIBComplianceRev1=ciscoZsExtMIBComplianceRev1, ciscoZsExtMIBConform=ciscoZsExtMIBConform, czseStats=czseStats, ciscoZsExtMIBGroups=ciscoZsExtMIBGroups, czseSessionTable=czseSessionTable, ciscoZsExtConfigGroupSup1=ciscoZsExtConfigGroupSup1, ciscoZsExtMIBCompliances=ciscoZsExtMIBCompliances, czseGlobalPropagationMode=czseGlobalPropagationMode, ciscoZsExtConfigGroup=ciscoZsExtConfigGroup, czseSessionCntl=czseSessionCntl, czseReadFrom=czseReadFrom, czseMergeControlRestrict=czseMergeControlRestrict, czseConfiguration=czseConfiguration, ciscoZsExtMIBObjects=ciscoZsExtMIBObjects, CzseSessOwnerType=CzseSessOwnerType, czseGlobalDefaultZoneBehaviour=czseGlobalDefaultZoneBehaviour, ciscoZsExtMIBNotifs=ciscoZsExtMIBNotifs)
(integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_size_constraint, value_range_constraint, constraints_intersection, single_value_constraint, constraints_union) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueSizeConstraint', 'ValueRangeConstraint', 'ConstraintsIntersection', 'SingleValueConstraint', 'ConstraintsUnion') (cisco_mgmt,) = mibBuilder.importSymbols('CISCO-SMI', 'ciscoMgmt') (vsan_index,) = mibBuilder.importSymbols('CISCO-VSAN-MIB', 'vsanIndex') (module_compliance, notification_group, object_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup', 'ObjectGroup') (object_identity, ip_address, gauge32, module_identity, mib_scalar, mib_table, mib_table_row, mib_table_column, iso, notification_type, integer32, time_ticks, unsigned32, counter64, bits, counter32, mib_identifier) = mibBuilder.importSymbols('SNMPv2-SMI', 'ObjectIdentity', 'IpAddress', 'Gauge32', 'ModuleIdentity', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'iso', 'NotificationType', 'Integer32', 'TimeTicks', 'Unsigned32', 'Counter64', 'Bits', 'Counter32', 'MibIdentifier') (display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention') cisco_zs_ext_mib = module_identity((1, 3, 6, 1, 4, 1, 9, 9, 427)) ciscoZsExtMIB.setRevisions(('2006-01-03 00:00', '2004-08-11 00:00')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: ciscoZsExtMIB.setRevisionsDescriptions(('Added objects czseGlobalDefaultZoneBehaviour and czseGlobalPropagationMode.', 'Initial version of this MIB.')) if mibBuilder.loadTexts: ciscoZsExtMIB.setLastUpdated('200601030000Z') if mibBuilder.loadTexts: ciscoZsExtMIB.setOrganization('Cisco Systems Inc.') if mibBuilder.loadTexts: ciscoZsExtMIB.setContactInfo(' Cisco Systems Customer Service Postal: 170 W Tasman Drive San Jose, CA 95134 USA Tel: +1 800 553 -NETS E-mail: cs-san@cisco.com') if mibBuilder.loadTexts: ciscoZsExtMIB.setDescription("The MIB module for the management of zoning within the framework of Cisco's Zoning Server (ZS) Archi- tecture which realizes the FC-GS4/SW3 requirements for Zone Server. This MIB is an extension to the CISCO-ZS-MIB, which is for managing zoning conforming to FC-GS3/SW2. The FC-GS4 specification is Fibre-Channel - Generic Services - 4 T11/ Project 1505-D/Rev 7.8. The SW3 specification is Fibre-Channel - Switch Fabric - 3 T11/Project 1508- D/Rev 6.6. GS4/SW3 allows zoning to operate in either basic or enhanced mode of operation. Basic mode is essentially GS3/SW2 compatible mode (as modelled by CISCO-ZS-MIB). Enhanced mode of operation provides additional capabilities. In enhanced mode of operation, all the configuration should be done within the scope of a session. The current 'Running Configuration' on the local device for zone server is called the 'effective' database. When the first configuration command on the zone server data is received, a snapshot of the current 'effective database' is taken on the local device. This snapshot is called the 'copy' database. An implicit session is started by the Zone Server on the local device and all subsequent SET operations take place in the context of this session. The 'copy' database is used for all further modifications in the session. There can be only one session active in the entire Fibre Channel fabric. The user who initiates the creation of this 'copy', is called the owner of session. When a session has been created on a device in the Fibre Channel fabric, if an attempt is made to start a session from any other device in the fabric, it results in error. Once the modifications to the 'copy' are done, a 'commit' operation can be done. The 'commit' done on the local device, results in the local 'effective database' being overwritten with the 'copy' and then the new local 'effective database' is distributed to all other devices in the Fibre Channel fabric. The successful 'commit' operation also results in destroying the 'copy' on the local device. The 'commit' can only be performed by the owner of the session. The 'copy' can optionally be destroyed without any distribution. This can be done by performing a 'clear' operation. Glossary of terms used in this MIB ---------------------------------- VSAN - Virtual Storage Area Network.") cisco_zs_ext_mib_notifs = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 427, 0)) cisco_zs_ext_mib_objects = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 427, 1)) cisco_zs_ext_mib_conform = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 427, 2)) czse_configuration = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 427, 1, 1)) czse_stats = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 427, 1, 2)) class Czsesessownertype(TextualConvention, Integer32): description = 'Represents the type of owner of a GS4 session. other - other type of owner. cli - Command Line Interface (CLI) is the owner. gs4client - Fibre Channel GS4 services client. snmp - SNMP is the owner.' status = 'current' subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(1, 2, 3, 4)) named_values = named_values(('other', 1), ('cli', 2), ('gs4client', 3), ('snmp', 4)) czse_capability_table = mib_table((1, 3, 6, 1, 4, 1, 9, 9, 427, 1, 1, 1)) if mibBuilder.loadTexts: czseCapabilityTable.setStatus('current') if mibBuilder.loadTexts: czseCapabilityTable.setDescription('This table lists the capabilities of the Zone Server on the local device. This information is maintained on a per VSAN basis.') czse_capability_entry = mib_table_row((1, 3, 6, 1, 4, 1, 9, 9, 427, 1, 1, 1, 1)).setIndexNames((0, 'CISCO-VSAN-MIB', 'vsanIndex')) if mibBuilder.loadTexts: czseCapabilityEntry.setStatus('current') if mibBuilder.loadTexts: czseCapabilityEntry.setDescription('An entry represents the capability of the Zone Server on the local device on a VSAN.') czse_capability_object = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 427, 1, 1, 1, 1, 1), bits().clone(namedValues=named_values(('enhancedMode', 0), ('zsetDb', 1), ('dirAct', 2), ('hardZoning', 3)))).setMaxAccess('readonly') if mibBuilder.loadTexts: czseCapabilityObject.setReference('Fibre-Channel - Switch fabric - 3 T11/ Project 1505-D/Rev 6.6 Section 6.1.22.4.4') if mibBuilder.loadTexts: czseCapabilityObject.setStatus('current') if mibBuilder.loadTexts: czseCapabilityObject.setDescription("This bitmap represents the capability of the local Zone Server on this VSAN. If 'enhancedMode(0)' bit is set, the local Zone Server is capable of supporting enhanced Zoning mode of operation. If this bit is reset, it does not have this capability. If 'zsetDb(1)' bit is set, the local Zone Server supports maintaining of zoneset database. If this bit is reset, the local Zone Server does not allow maintaining of zoneset database. If 'dirAct(2)' bit is set, the local Zone Server supports direct activation command. If this bit is reset, the local Zone Server does not support this. If 'hardZoning(3)' bit is set, the local Zone Server supports hard zoning. If this bit is reset, the local Zone Server does not support hard zoning.") czse_mode_table = mib_table((1, 3, 6, 1, 4, 1, 9, 9, 427, 1, 1, 2)) if mibBuilder.loadTexts: czseModeTable.setStatus('current') if mibBuilder.loadTexts: czseModeTable.setDescription('A table containing information on the mode of operation of the zone server on all VSANs on the local device.') czse_mode_entry = mib_table_row((1, 3, 6, 1, 4, 1, 9, 9, 427, 1, 1, 2, 1)).setIndexNames((0, 'CISCO-VSAN-MIB', 'vsanIndex')) if mibBuilder.loadTexts: czseModeEntry.setStatus('current') if mibBuilder.loadTexts: czseModeEntry.setDescription('An entry represents the mode of operation of the local zone server on a VSAN. The mode can be modified on a VSAN and the outcome of the operation obtained.') czse_operation_mode = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 427, 1, 1, 2, 1, 1), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('basic', 1), ('enhanced', 2))).clone('basic')).setMaxAccess('readwrite') if mibBuilder.loadTexts: czseOperationMode.setReference('Fibre-Channel - Generic Services - 4 T11/ Project 1505-D/Rev 7.8 Section 6.4.7. Fibre-Channel - Switch fabric - 3 T11/ Project 1505-D/Rev 6.6 Section 10.6') if mibBuilder.loadTexts: czseOperationMode.setStatus('current') if mibBuilder.loadTexts: czseOperationMode.setDescription("This object when set to 'basic(1)', results in the zone server operating in the basic mode as defined by FC-GS4 standards. This object when set to 'enhanced(2)', results in the zone server operating in the enhanced mode as defined by FC-GS4 standards. The local zone server can move to the enhanced mode of operation only if all devices in the Fibre Channel fabric are capable of working in enhanced mode. Otherwise, the set operation trying to set this object to 'enhanced(2)' will fail.") czse_operation_mode_result = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 427, 1, 1, 2, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('success', 1), ('failure', 2), ('inProgress', 3)))).setMaxAccess('readonly') if mibBuilder.loadTexts: czseOperationModeResult.setStatus('current') if mibBuilder.loadTexts: czseOperationModeResult.setDescription('The outcome of setting the mode of operation of the local Zone Server on this VSAN.') czse_read_from = mib_scalar((1, 3, 6, 1, 4, 1, 9, 9, 427, 1, 1, 3), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('effectiveDB', 1), ('copyDB', 2))).clone('effectiveDB')).setMaxAccess('readwrite') if mibBuilder.loadTexts: czseReadFrom.setStatus('current') if mibBuilder.loadTexts: czseReadFrom.setDescription("This object specifies whether the management station wishes to read from the 'effective database' or from the 'copy' database.") czse_session_table = mib_table((1, 3, 6, 1, 4, 1, 9, 9, 427, 1, 1, 4)) if mibBuilder.loadTexts: czseSessionTable.setStatus('current') if mibBuilder.loadTexts: czseSessionTable.setDescription("A table containing information on sessions on the local device on all VSANs. Operations are permitted on this table only when the zone server is running in 'enhanced' mode.") czse_session_entry = mib_table_row((1, 3, 6, 1, 4, 1, 9, 9, 427, 1, 1, 4, 1)).setIndexNames((0, 'CISCO-VSAN-MIB', 'vsanIndex')) if mibBuilder.loadTexts: czseSessionEntry.setStatus('current') if mibBuilder.loadTexts: czseSessionEntry.setDescription('An entry contains information on the owner of a session on a VSAN. It also assists in performing commit/clear operations on the session.') czse_session_owner_type = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 427, 1, 1, 4, 1, 1), czse_sess_owner_type()).setMaxAccess('readonly') if mibBuilder.loadTexts: czseSessionOwnerType.setStatus('current') if mibBuilder.loadTexts: czseSessionOwnerType.setDescription('This object specifies the owner type for this session.') czse_session_owner = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 427, 1, 1, 4, 1, 2), octet_string().subtype(subtypeSpec=value_size_constraint(0, 64))).setMaxAccess('readonly') if mibBuilder.loadTexts: czseSessionOwner.setStatus('current') if mibBuilder.loadTexts: czseSessionOwner.setDescription("This object specifies the owner for this session. If the value of the corresponding instance of czseSessionOwnerType object is 'cli', this object will contain the user name of the CLI (Command Line Interface) user, who is the owner of the session on this VSAN. If the value of the corresponding instance of czseSessionOwnerType is 'gs4client', this object will contain the FCID of the GS4 management station, which is the owner of the session on this VSAN. If the value of the corresponding instance of czseSessionOwnerType is 'snmp', this object will contain the IP address of the management station, which is the owner of the session on this VSAN.") czse_session_cntl = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 427, 1, 1, 4, 1, 3), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('commitChanges', 1), ('cleanup', 2), ('noop', 3)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: czseSessionCntl.setStatus('current') if mibBuilder.loadTexts: czseSessionCntl.setDescription("This object assists in committing or clearing the contents of the 'copy' database on this session. No action is taken if this object is set to 'noop(3)'. The value of this object when read is always 'noop(3)'. The above operation can only be performed by the owner of the session.") czse_session_cntl_result = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 427, 1, 1, 4, 1, 4), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('commitSuccess', 1), ('commitFailure', 2), ('inProgress', 3)))).setMaxAccess('readonly') if mibBuilder.loadTexts: czseSessionCntlResult.setStatus('current') if mibBuilder.loadTexts: czseSessionCntlResult.setDescription("This object indicates the outcome of setting the corresponding instance of czseSessionCntl object to 'commitChanges(1)'.") czse_merge_control_table = mib_table((1, 3, 6, 1, 4, 1, 9, 9, 427, 1, 1, 5)) if mibBuilder.loadTexts: czseMergeControlTable.setStatus('current') if mibBuilder.loadTexts: czseMergeControlTable.setDescription("A table containing information on zone merge control policy on all VSANs in the entire fabric. Operations on this table are permitted only when the zone server is running in 'enhanced' mode.") czse_merge_control_entry = mib_table_row((1, 3, 6, 1, 4, 1, 9, 9, 427, 1, 1, 5, 1)).setIndexNames((0, 'CISCO-VSAN-MIB', 'vsanIndex')) if mibBuilder.loadTexts: czseMergeControlEntry.setReference('Fibre-Channel - Switch fabric - 3 T11/ Project 1505-D/Rev 6.6 Section 10.5.2.2') if mibBuilder.loadTexts: czseMergeControlEntry.setStatus('current') if mibBuilder.loadTexts: czseMergeControlEntry.setDescription('An entry contains information on the Merge Control policy on a VSAN. The policy can be modified on a per VSAN basis by making use of czseMergeContolRestrict object.') czse_merge_control_restrict = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 427, 1, 1, 5, 1, 1), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('allow', 1), ('restrict', 2))).clone('allow')).setMaxAccess('readwrite') if mibBuilder.loadTexts: czseMergeControlRestrict.setStatus('current') if mibBuilder.loadTexts: czseMergeControlRestrict.setDescription("This object controls the zone merge behavior. If this object is set to 'allow', then the merge takes place according to the merge rules. If this object is set to 'restrict', then if the merging databases are not exactly identical, the Inter-Switch Link (ISL) between the devices is isolated.") czse_global_default_zone_behaviour = mib_scalar((1, 3, 6, 1, 4, 1, 9, 9, 427, 1, 1, 6), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('permit', 1), ('deny', 2))).clone('deny')).setMaxAccess('readwrite') if mibBuilder.loadTexts: czseGlobalDefaultZoneBehaviour.setStatus('current') if mibBuilder.loadTexts: czseGlobalDefaultZoneBehaviour.setDescription("This object represents the initial value for default zone behaviour on a VSAN when it is created. If a VSAN were to be deleted and re-created again, the default zone behaviour will be set to the value specified for this object. The semantics of setting this object to 'permit' or 'deny' are described in the description for zoneDefaultZoneBehaviour object in CISCO-ZS-MIB. After a VSAN has been created, if the value for default zone behaviour for that VSAN has to be changed, the zoneDefaultZoneBehaviour object in CISCO-ZS-MIB has to be used.") czse_global_propagation_mode = mib_scalar((1, 3, 6, 1, 4, 1, 9, 9, 427, 1, 1, 7), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('fullZoneset', 1), ('activeZoneset', 2))).clone('activeZoneset')).setMaxAccess('readwrite') if mibBuilder.loadTexts: czseGlobalPropagationMode.setStatus('current') if mibBuilder.loadTexts: czseGlobalPropagationMode.setDescription("This object represents the initial value for zone set propagation mode on a VSAN when it is created. If a VSAN were to be deleted and re-created again, the zone set propagation mode will be set to the value specified for this object. The semantics of setting this object to 'fullZoneset' or 'activeZoneset' are described in the description for zoneSetPropagationMode object in CISCO-ZS-MIB. After a VSAN has been created, if the value for zone set propagation mode has to be changed for that particular VSAN, the zoneSetPropagationMode object in CISCO-ZS-MIB has to be used.") cisco_zs_ext_mib_compliances = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 427, 2, 1)) cisco_zs_ext_mib_groups = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 427, 2, 2)) cisco_zs_ext_mib_compliance = module_compliance((1, 3, 6, 1, 4, 1, 9, 9, 427, 2, 1, 1)).setObjects(('CISCO-ZS-EXT-MIB', 'ciscoZsExtConfigGroup')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): cisco_zs_ext_mib_compliance = ciscoZsExtMIBCompliance.setStatus('deprecated') if mibBuilder.loadTexts: ciscoZsExtMIBCompliance.setDescription('The compliance statement for entities which implement the Zone Server conforming to FC-GS4/SW3.') cisco_zs_ext_mib_compliance_rev1 = module_compliance((1, 3, 6, 1, 4, 1, 9, 9, 427, 2, 1, 2)).setObjects(('CISCO-ZS-EXT-MIB', 'ciscoZsExtConfigGroup'), ('CISCO-ZS-EXT-MIB', 'ciscoZsExtConfigGroupSup1')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): cisco_zs_ext_mib_compliance_rev1 = ciscoZsExtMIBComplianceRev1.setStatus('current') if mibBuilder.loadTexts: ciscoZsExtMIBComplianceRev1.setDescription('The compliance statement for entities which implement the Zone Server conforming to FC-GS4/SW3.') cisco_zs_ext_config_group = object_group((1, 3, 6, 1, 4, 1, 9, 9, 427, 2, 2, 1)).setObjects(('CISCO-ZS-EXT-MIB', 'czseCapabilityObject'), ('CISCO-ZS-EXT-MIB', 'czseOperationMode'), ('CISCO-ZS-EXT-MIB', 'czseOperationModeResult'), ('CISCO-ZS-EXT-MIB', 'czseReadFrom'), ('CISCO-ZS-EXT-MIB', 'czseSessionOwnerType'), ('CISCO-ZS-EXT-MIB', 'czseSessionOwner'), ('CISCO-ZS-EXT-MIB', 'czseSessionCntl'), ('CISCO-ZS-EXT-MIB', 'czseSessionCntlResult'), ('CISCO-ZS-EXT-MIB', 'czseMergeControlRestrict')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): cisco_zs_ext_config_group = ciscoZsExtConfigGroup.setStatus('current') if mibBuilder.loadTexts: ciscoZsExtConfigGroup.setDescription('A collection of object(s) for configuring and displaying Zone Server conforming with FC-GS4/SW3.') cisco_zs_ext_config_group_sup1 = object_group((1, 3, 6, 1, 4, 1, 9, 9, 427, 2, 2, 2)).setObjects(('CISCO-ZS-EXT-MIB', 'czseGlobalDefaultZoneBehaviour'), ('CISCO-ZS-EXT-MIB', 'czseGlobalPropagationMode')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): cisco_zs_ext_config_group_sup1 = ciscoZsExtConfigGroupSup1.setStatus('current') if mibBuilder.loadTexts: ciscoZsExtConfigGroupSup1.setDescription('A collection of objects for configuring global zoning policies.') mibBuilder.exportSymbols('CISCO-ZS-EXT-MIB', czseOperationMode=czseOperationMode, czseSessionEntry=czseSessionEntry, czseMergeControlTable=czseMergeControlTable, czseSessionOwnerType=czseSessionOwnerType, czseMergeControlEntry=czseMergeControlEntry, PYSNMP_MODULE_ID=ciscoZsExtMIB, czseOperationModeResult=czseOperationModeResult, czseCapabilityTable=czseCapabilityTable, ciscoZsExtMIBCompliance=ciscoZsExtMIBCompliance, ciscoZsExtMIB=ciscoZsExtMIB, czseModeEntry=czseModeEntry, czseModeTable=czseModeTable, czseSessionCntlResult=czseSessionCntlResult, czseCapabilityObject=czseCapabilityObject, czseSessionOwner=czseSessionOwner, czseCapabilityEntry=czseCapabilityEntry, ciscoZsExtMIBComplianceRev1=ciscoZsExtMIBComplianceRev1, ciscoZsExtMIBConform=ciscoZsExtMIBConform, czseStats=czseStats, ciscoZsExtMIBGroups=ciscoZsExtMIBGroups, czseSessionTable=czseSessionTable, ciscoZsExtConfigGroupSup1=ciscoZsExtConfigGroupSup1, ciscoZsExtMIBCompliances=ciscoZsExtMIBCompliances, czseGlobalPropagationMode=czseGlobalPropagationMode, ciscoZsExtConfigGroup=ciscoZsExtConfigGroup, czseSessionCntl=czseSessionCntl, czseReadFrom=czseReadFrom, czseMergeControlRestrict=czseMergeControlRestrict, czseConfiguration=czseConfiguration, ciscoZsExtMIBObjects=ciscoZsExtMIBObjects, CzseSessOwnerType=CzseSessOwnerType, czseGlobalDefaultZoneBehaviour=czseGlobalDefaultZoneBehaviour, ciscoZsExtMIBNotifs=ciscoZsExtMIBNotifs)
class Solution: def minCostClimbingStairs(self, cost: List[int]) -> int: n = len(cost) dp = [cost[0], cost[1], 0] for i in range(2, n): dp[i % 3] = cost[i] + min(dp[(i - 1) % 3], dp[(i - 2) % 3]) return min(dp[(n - 1) % 3], dp[(n - 2) % 3])
class Solution: def min_cost_climbing_stairs(self, cost: List[int]) -> int: n = len(cost) dp = [cost[0], cost[1], 0] for i in range(2, n): dp[i % 3] = cost[i] + min(dp[(i - 1) % 3], dp[(i - 2) % 3]) return min(dp[(n - 1) % 3], dp[(n - 2) % 3])
""" Do not import anything from the rest of Kolibri in this module, it's crucial that it can be loaded without the settings/configuration/django stack! """
""" Do not import anything from the rest of Kolibri in this module, it's crucial that it can be loaded without the settings/configuration/django stack! """
# Copyright (c) 2018 PrimeVR # All rights Reserved ############################################################################### # print helpers ############################################################################### CHILL_WHITE = '\x1b[0;37;40m' CHILL_PURPLE = '\x1b[0;35;40m' CHILL_LIGHT_BLUE = '\x1b[0;36;40m' CHILL_BLUE = '\x1b[0;34;40m' MEGA_WHITE = '\x1b[1;37;40m' LIGHT_BLUE = '\x1b[1;36;40m' BLUE = '\x1b[1;34;40m' GREEN = '\x1b[1;32;40m' CHILL_GREEN = '\x1b[0;32;40m' RED = '\x1b[1;31;40m' YELLOW = '\x1b[1;33;40m' CHILL_YELLOW = '\x1b[0;33;40m' FANCY_BLUE = '\x1b[1;37;44m' ANNOYING = '\x1b[5;31;44m' ENDC = '\x1b[0m' def print_red(string): print(RED + string + ENDC) def print_green(string): print(GREEN + string + ENDC) def print_chill_green(string): print(CHILL_GREEN + string + ENDC) def print_light_blue(string): print(LIGHT_BLUE + string + ENDC) def print_fancy_blue(string): print(FANCY_BLUE + string + ENDC) def print_blue(string): print(BLUE + string + ENDC) def print_yellow(string): print(YELLOW + string + ENDC) def print_chill_yellow(string): print(CHILL_YELLOW + string + ENDC) def print_chill_white(string): print(CHILL_WHITE + string + ENDC) def print_chill_purple(string): print(CHILL_PURPLE + string + ENDC) def print_chill_light_blue(string): print(CHILL_LIGHT_BLUE + string + ENDC) def print_chill_blue(string): print(CHILL_BLUE + string + ENDC) def print_mega_white(string): print(MEGA_WHITE + string + ENDC) def print_annoying(string): print(ANNOYING + string + ENDC) ################################################################## def red_str(string): return RED + string + ENDC def chill_green_str(string): return CHILL_GREEN + string + ENDC def light_blue_str(string): return LIGHT_BLUE + string + ENDC def fancy_blue_str(string): return FANCY_BLUE + string + ENDC def blue_str(string): return BLUE + string + ENDC def yellow_str(string): return YELLOW + string + ENDC def chill_yellow_str(string): return CHILL_YELLOW + string + ENDC def chill_white_str(string): return CHILL_WHITE + string + ENDC def chill_purple_str(string): return CHILL_PURPLE + string + ENDC def chill_light_blue_str(string): return CHILL_LIGHT_BLUE + string + ENDC def chill_blue_str(string): return CHILL_BLUE + string + ENDC def mega_white_str(string): return MEGA_WHITE + string + ENDC def annoying_str(string): return ANNOYING + string + ENDC
chill_white = '\x1b[0;37;40m' chill_purple = '\x1b[0;35;40m' chill_light_blue = '\x1b[0;36;40m' chill_blue = '\x1b[0;34;40m' mega_white = '\x1b[1;37;40m' light_blue = '\x1b[1;36;40m' blue = '\x1b[1;34;40m' green = '\x1b[1;32;40m' chill_green = '\x1b[0;32;40m' red = '\x1b[1;31;40m' yellow = '\x1b[1;33;40m' chill_yellow = '\x1b[0;33;40m' fancy_blue = '\x1b[1;37;44m' annoying = '\x1b[5;31;44m' endc = '\x1b[0m' def print_red(string): print(RED + string + ENDC) def print_green(string): print(GREEN + string + ENDC) def print_chill_green(string): print(CHILL_GREEN + string + ENDC) def print_light_blue(string): print(LIGHT_BLUE + string + ENDC) def print_fancy_blue(string): print(FANCY_BLUE + string + ENDC) def print_blue(string): print(BLUE + string + ENDC) def print_yellow(string): print(YELLOW + string + ENDC) def print_chill_yellow(string): print(CHILL_YELLOW + string + ENDC) def print_chill_white(string): print(CHILL_WHITE + string + ENDC) def print_chill_purple(string): print(CHILL_PURPLE + string + ENDC) def print_chill_light_blue(string): print(CHILL_LIGHT_BLUE + string + ENDC) def print_chill_blue(string): print(CHILL_BLUE + string + ENDC) def print_mega_white(string): print(MEGA_WHITE + string + ENDC) def print_annoying(string): print(ANNOYING + string + ENDC) def red_str(string): return RED + string + ENDC def chill_green_str(string): return CHILL_GREEN + string + ENDC def light_blue_str(string): return LIGHT_BLUE + string + ENDC def fancy_blue_str(string): return FANCY_BLUE + string + ENDC def blue_str(string): return BLUE + string + ENDC def yellow_str(string): return YELLOW + string + ENDC def chill_yellow_str(string): return CHILL_YELLOW + string + ENDC def chill_white_str(string): return CHILL_WHITE + string + ENDC def chill_purple_str(string): return CHILL_PURPLE + string + ENDC def chill_light_blue_str(string): return CHILL_LIGHT_BLUE + string + ENDC def chill_blue_str(string): return CHILL_BLUE + string + ENDC def mega_white_str(string): return MEGA_WHITE + string + ENDC def annoying_str(string): return ANNOYING + string + ENDC
#%% """ - Search in Rotated Sorted Array - https://leetcode.com/problems/search-in-rotated-sorted-array/ - Medium Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). You are given a target value to search. If found in the array return its index, otherwise return -1. You may assume no duplicate exists in the array. Your algorithm's runtime complexity must be in the order of O(log n). Example 1: Input: nums = [4,5,6,7,0,1,2], target = 0 Output: 4 Example 2: Input: nums = [4,5,6,7,0,1,2], target = 3 Output: -1 """ #%% class S1: def search(self, nums, target): if target in nums: return nums.index(target) else: return -1 #%% class S2: def search(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ l, r = 0, len(nums) - 1 while l <= r: mid = l + ((r-l) >> 2) if nums[mid] == target: return mid if nums[mid] < nums[r]: if nums[mid] < target <= nums[r]: l = mid + 1 else: r = mid - 1 else: if nums[l] <= target < nums[mid]: r = mid - 1 else: l = mid + 1 return -1
""" - Search in Rotated Sorted Array - https://leetcode.com/problems/search-in-rotated-sorted-array/ - Medium Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e., [0,1,2,4,5,6,7] might become [4,5,6,7,0,1,2]). You are given a target value to search. If found in the array return its index, otherwise return -1. You may assume no duplicate exists in the array. Your algorithm's runtime complexity must be in the order of O(log n). Example 1: Input: nums = [4,5,6,7,0,1,2], target = 0 Output: 4 Example 2: Input: nums = [4,5,6,7,0,1,2], target = 3 Output: -1 """ class S1: def search(self, nums, target): if target in nums: return nums.index(target) else: return -1 class S2: def search(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ (l, r) = (0, len(nums) - 1) while l <= r: mid = l + (r - l >> 2) if nums[mid] == target: return mid if nums[mid] < nums[r]: if nums[mid] < target <= nums[r]: l = mid + 1 else: r = mid - 1 elif nums[l] <= target < nums[mid]: r = mid - 1 else: l = mid + 1 return -1
def jonSnowParents(dad, mom): if dad == 'Rhaegar Targaryen' and mom == 'Lyanna Stark': return 'Jon Snow you deserve the throne' return 'Jon Snow, you know nothing'
def jon_snow_parents(dad, mom): if dad == 'Rhaegar Targaryen' and mom == 'Lyanna Stark': return 'Jon Snow you deserve the throne' return 'Jon Snow, you know nothing'
""" Test Suite for UMAP to ensure things are working as expected. The test suite comprises multiple testing modules, including multiple test cases related to a specific set of UMAP features under test. Backend ------- pytest is the reference backend for testing environment and execution, also integrating with pre-existent nose-based tests Shared Testing code ------------------- Whenever needed, each module includes a set of _utility_ functions that specify shared (and repeated) testing operations. Fixtures -------- All data dependency has been implemented as test fixtures (preferred to shared global variables). All the fixtures shared by multiple test cases are defined in the `conftest.py` module. Fixtures allow the execution of each test module in isolation, as well as within the whole test suite. Modules in Tests (to keep up to date) ------------------------------------- - conftest: pytrest fixtures - test_plot: basic tests for umap.plot - test_umap_df_validation_params: Tests on parameters validation for DataFrameUMAP - test_umap_metrics: Tests for UMAP metrics - spatial, binary, and sparse - test_umap_nn: Tests for NearestNeighbours - test_umap_on_iris: Tests for UMAP on Iris Dataset - test_umap_ops: Tests for general UMAP ops (e.g. clusterability, transform stability) - test_umap_repeated_data: UMAP tests on repeated data (sparse|dense; spatial|binary) - test_umap_trustworthiness: Tests on UMAP Trustworthiness - test_umap_validation_params: Tests for fit parameters validation """
""" Test Suite for UMAP to ensure things are working as expected. The test suite comprises multiple testing modules, including multiple test cases related to a specific set of UMAP features under test. Backend ------- pytest is the reference backend for testing environment and execution, also integrating with pre-existent nose-based tests Shared Testing code ------------------- Whenever needed, each module includes a set of _utility_ functions that specify shared (and repeated) testing operations. Fixtures -------- All data dependency has been implemented as test fixtures (preferred to shared global variables). All the fixtures shared by multiple test cases are defined in the `conftest.py` module. Fixtures allow the execution of each test module in isolation, as well as within the whole test suite. Modules in Tests (to keep up to date) ------------------------------------- - conftest: pytrest fixtures - test_plot: basic tests for umap.plot - test_umap_df_validation_params: Tests on parameters validation for DataFrameUMAP - test_umap_metrics: Tests for UMAP metrics - spatial, binary, and sparse - test_umap_nn: Tests for NearestNeighbours - test_umap_on_iris: Tests for UMAP on Iris Dataset - test_umap_ops: Tests for general UMAP ops (e.g. clusterability, transform stability) - test_umap_repeated_data: UMAP tests on repeated data (sparse|dense; spatial|binary) - test_umap_trustworthiness: Tests on UMAP Trustworthiness - test_umap_validation_params: Tests for fit parameters validation """
# -*- coding: utf-8 -*- """This module contains the Food Ordering Blueprint Application""" NLP_CONFIG = { "resolve_entities_using_nbest_transcripts": [], "system_entity_recognizer": {}, } INTENT_MODEL_CONFIG = { "model_type": "text", "model_settings": {"classifier_type": "logreg"}, "param_selection": { "type": "k-fold", "k": 5, "grid": { "fit_intercept": [True, False], "C": [0.01, 1, 10, 100], "class_bias": [0.7, 0.3, 0], }, }, "features": { "bag-of-words": {"lengths": [1, 2]}, "edge-ngrams": {"lengths": [1, 2]}, "in-gaz": {}, "exact": {"scaling": 10}, "gaz-freq": {}, "freq": {"bins": 5}, }, } DOMAIN_MODEL_CONFIG = { "model_type": "text", "model_settings": {"classifier_type": "logreg"}, "params": { "C": 10, }, "features": { "bag-of-words": {"lengths": [1, 2]}, "edge-ngrams": {"lengths": [1, 2]}, "in-gaz": {}, "exact": {"scaling": 10}, "gaz-freq": {}, "freq": {"bins": 5}, "average-token-length": {}, # Custom feature }, } MAX_HISTORY_LEN = 5
"""This module contains the Food Ordering Blueprint Application""" nlp_config = {'resolve_entities_using_nbest_transcripts': [], 'system_entity_recognizer': {}} intent_model_config = {'model_type': 'text', 'model_settings': {'classifier_type': 'logreg'}, 'param_selection': {'type': 'k-fold', 'k': 5, 'grid': {'fit_intercept': [True, False], 'C': [0.01, 1, 10, 100], 'class_bias': [0.7, 0.3, 0]}}, 'features': {'bag-of-words': {'lengths': [1, 2]}, 'edge-ngrams': {'lengths': [1, 2]}, 'in-gaz': {}, 'exact': {'scaling': 10}, 'gaz-freq': {}, 'freq': {'bins': 5}}} domain_model_config = {'model_type': 'text', 'model_settings': {'classifier_type': 'logreg'}, 'params': {'C': 10}, 'features': {'bag-of-words': {'lengths': [1, 2]}, 'edge-ngrams': {'lengths': [1, 2]}, 'in-gaz': {}, 'exact': {'scaling': 10}, 'gaz-freq': {}, 'freq': {'bins': 5}, 'average-token-length': {}}} max_history_len = 5
if node.os != 'ubuntu' and node.os != 'raspbian': raise Exception('{} {} is not supported by this bundle'.format(node.os, node.os_version)) pkg_apt = {} files = {} actions = { } if node.metadata.get('grub', {}).get('enabled', False): pkg_apt['grub2-common'] = {} actions['update-grub'] = { 'command': 'update-grub', 'triggered': True, 'cascade_skip': False, } name = '' if node.os == 'ubuntu': name = 'Ubuntu' if node.os == 'debian': name = 'Debian' if node.os == 'raspbian': name = 'Raspbian' if len(name) == 0: raise Exception('can not find name for grub files') files['/etc/default/grub'] = { 'source': 'default-grub', 'content_type': 'mako', 'mode': '0644', 'owner': 'root', 'group': 'root', 'context': { 'name': name, 'default': node.metadata.get('grub', {}).get('default', ''), 'cmd_args': node.metadata.get('grub', {}).get('cmd_args', {}), 'serial': node.metadata.get('grub', {}).get('serial', False), }, 'triggers': ['action:update-grub'], 'needs': ['pkg_apt:grub2-common'], }
if node.os != 'ubuntu' and node.os != 'raspbian': raise exception('{} {} is not supported by this bundle'.format(node.os, node.os_version)) pkg_apt = {} files = {} actions = {} if node.metadata.get('grub', {}).get('enabled', False): pkg_apt['grub2-common'] = {} actions['update-grub'] = {'command': 'update-grub', 'triggered': True, 'cascade_skip': False} name = '' if node.os == 'ubuntu': name = 'Ubuntu' if node.os == 'debian': name = 'Debian' if node.os == 'raspbian': name = 'Raspbian' if len(name) == 0: raise exception('can not find name for grub files') files['/etc/default/grub'] = {'source': 'default-grub', 'content_type': 'mako', 'mode': '0644', 'owner': 'root', 'group': 'root', 'context': {'name': name, 'default': node.metadata.get('grub', {}).get('default', ''), 'cmd_args': node.metadata.get('grub', {}).get('cmd_args', {}), 'serial': node.metadata.get('grub', {}).get('serial', False)}, 'triggers': ['action:update-grub'], 'needs': ['pkg_apt:grub2-common']}
""" aiida_nanotech_empa AiiDA plugin containing plugins/work chains developed at nanotech@surfaces group from Empa. """ __version__ = "0.4.1"
""" aiida_nanotech_empa AiiDA plugin containing plugins/work chains developed at nanotech@surfaces group from Empa. """ __version__ = '0.4.1'
class FileSystemInfo(MarshalByRefObject,ISerializable): """ Provides the base class for both System.IO.FileInfo and System.IO.DirectoryInfo objects. """ def Delete(self): """ Delete(self: FileSystemInfo) Deletes a file or directory. """ pass def GetObjectData(self,info,context): """ GetObjectData(self: FileSystemInfo,info: SerializationInfo,context: StreamingContext) Sets the System.Runtime.Serialization.SerializationInfo object with the file name and additional exception information. info: The System.Runtime.Serialization.SerializationInfo that holds the serialized object data about the exception being thrown. context: The System.Runtime.Serialization.StreamingContext that contains contextual information about the source or destination. """ pass def MemberwiseClone(self,*args): """ MemberwiseClone(self: MarshalByRefObject,cloneIdentity: bool) -> MarshalByRefObject Creates a shallow copy of the current System.MarshalByRefObject object. cloneIdentity: false to delete the current System.MarshalByRefObject object's identity,which will cause the object to be assigned a new identity when it is marshaled across a remoting boundary. A value of false is usually appropriate. true to copy the current System.MarshalByRefObject object's identity to its clone,which will cause remoting client calls to be routed to the remote server object. Returns: A shallow copy of the current System.MarshalByRefObject object. MemberwiseClone(self: object) -> object Creates a shallow copy of the current System.Object. Returns: A shallow copy of the current System.Object. """ pass def Refresh(self): """ Refresh(self: FileSystemInfo) Refreshes the state of the object. """ pass def __init__(self,*args): """ x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """ pass @staticmethod def __new__(self,*args): #cannot find CLR constructor """ __new__(cls: type) __new__(cls: type,info: SerializationInfo,context: StreamingContext) """ pass def __reduce_ex__(self,*args): pass Attributes=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets or sets the attributes for the current file or directory. Get: Attributes(self: FileSystemInfo) -> FileAttributes Set: Attributes(self: FileSystemInfo)=value """ CreationTime=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets or sets the creation time of the current file or directory. Get: CreationTime(self: FileSystemInfo) -> DateTime Set: CreationTime(self: FileSystemInfo)=value """ CreationTimeUtc=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets or sets the creation time,in coordinated universal time (UTC),of the current file or directory. Get: CreationTimeUtc(self: FileSystemInfo) -> DateTime Set: CreationTimeUtc(self: FileSystemInfo)=value """ Exists=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets a value indicating whether the file or directory exists. Get: Exists(self: FileSystemInfo) -> bool """ Extension=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets the string representing the extension part of the file. Get: Extension(self: FileSystemInfo) -> str """ FullName=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets the full path of the directory or file. Get: FullName(self: FileSystemInfo) -> str """ LastAccessTime=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets or sets the time the current file or directory was last accessed. Get: LastAccessTime(self: FileSystemInfo) -> DateTime Set: LastAccessTime(self: FileSystemInfo)=value """ LastAccessTimeUtc=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets or sets the time,in coordinated universal time (UTC),that the current file or directory was last accessed. Get: LastAccessTimeUtc(self: FileSystemInfo) -> DateTime Set: LastAccessTimeUtc(self: FileSystemInfo)=value """ LastWriteTime=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets or sets the time when the current file or directory was last written to. Get: LastWriteTime(self: FileSystemInfo) -> DateTime Set: LastWriteTime(self: FileSystemInfo)=value """ LastWriteTimeUtc=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets or sets the time,in coordinated universal time (UTC),when the current file or directory was last written to. Get: LastWriteTimeUtc(self: FileSystemInfo) -> DateTime Set: LastWriteTimeUtc(self: FileSystemInfo)=value """ Name=property(lambda self: object(),lambda self,v: None,lambda self: None) """For files,gets the name of the file. For directories,gets the name of the last directory in the hierarchy if a hierarchy exists. Otherwise,the Name property gets the name of the directory. Get: Name(self: FileSystemInfo) -> str """ FullPath=None OriginalPath=None
class Filesysteminfo(MarshalByRefObject, ISerializable): """ Provides the base class for both System.IO.FileInfo and System.IO.DirectoryInfo objects. """ def delete(self): """ Delete(self: FileSystemInfo) Deletes a file or directory. """ pass def get_object_data(self, info, context): """ GetObjectData(self: FileSystemInfo,info: SerializationInfo,context: StreamingContext) Sets the System.Runtime.Serialization.SerializationInfo object with the file name and additional exception information. info: The System.Runtime.Serialization.SerializationInfo that holds the serialized object data about the exception being thrown. context: The System.Runtime.Serialization.StreamingContext that contains contextual information about the source or destination. """ pass def memberwise_clone(self, *args): """ MemberwiseClone(self: MarshalByRefObject,cloneIdentity: bool) -> MarshalByRefObject Creates a shallow copy of the current System.MarshalByRefObject object. cloneIdentity: false to delete the current System.MarshalByRefObject object's identity,which will cause the object to be assigned a new identity when it is marshaled across a remoting boundary. A value of false is usually appropriate. true to copy the current System.MarshalByRefObject object's identity to its clone,which will cause remoting client calls to be routed to the remote server object. Returns: A shallow copy of the current System.MarshalByRefObject object. MemberwiseClone(self: object) -> object Creates a shallow copy of the current System.Object. Returns: A shallow copy of the current System.Object. """ pass def refresh(self): """ Refresh(self: FileSystemInfo) Refreshes the state of the object. """ pass def __init__(self, *args): """ x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """ pass @staticmethod def __new__(self, *args): """ __new__(cls: type) __new__(cls: type,info: SerializationInfo,context: StreamingContext) """ pass def __reduce_ex__(self, *args): pass attributes = property(lambda self: object(), lambda self, v: None, lambda self: None) 'Gets or sets the attributes for the current file or directory.\n\n\n\nGet: Attributes(self: FileSystemInfo) -> FileAttributes\n\n\n\nSet: Attributes(self: FileSystemInfo)=value\n\n' creation_time = property(lambda self: object(), lambda self, v: None, lambda self: None) 'Gets or sets the creation time of the current file or directory.\n\n\n\nGet: CreationTime(self: FileSystemInfo) -> DateTime\n\n\n\nSet: CreationTime(self: FileSystemInfo)=value\n\n' creation_time_utc = property(lambda self: object(), lambda self, v: None, lambda self: None) 'Gets or sets the creation time,in coordinated universal time (UTC),of the current file or directory.\n\n\n\nGet: CreationTimeUtc(self: FileSystemInfo) -> DateTime\n\n\n\nSet: CreationTimeUtc(self: FileSystemInfo)=value\n\n' exists = property(lambda self: object(), lambda self, v: None, lambda self: None) 'Gets a value indicating whether the file or directory exists.\n\n\n\nGet: Exists(self: FileSystemInfo) -> bool\n\n\n\n' extension = property(lambda self: object(), lambda self, v: None, lambda self: None) 'Gets the string representing the extension part of the file.\n\n\n\nGet: Extension(self: FileSystemInfo) -> str\n\n\n\n' full_name = property(lambda self: object(), lambda self, v: None, lambda self: None) 'Gets the full path of the directory or file.\n\n\n\nGet: FullName(self: FileSystemInfo) -> str\n\n\n\n' last_access_time = property(lambda self: object(), lambda self, v: None, lambda self: None) 'Gets or sets the time the current file or directory was last accessed.\n\n\n\nGet: LastAccessTime(self: FileSystemInfo) -> DateTime\n\n\n\nSet: LastAccessTime(self: FileSystemInfo)=value\n\n' last_access_time_utc = property(lambda self: object(), lambda self, v: None, lambda self: None) 'Gets or sets the time,in coordinated universal time (UTC),that the current file or directory was last accessed.\n\n\n\nGet: LastAccessTimeUtc(self: FileSystemInfo) -> DateTime\n\n\n\nSet: LastAccessTimeUtc(self: FileSystemInfo)=value\n\n' last_write_time = property(lambda self: object(), lambda self, v: None, lambda self: None) 'Gets or sets the time when the current file or directory was last written to.\n\n\n\nGet: LastWriteTime(self: FileSystemInfo) -> DateTime\n\n\n\nSet: LastWriteTime(self: FileSystemInfo)=value\n\n' last_write_time_utc = property(lambda self: object(), lambda self, v: None, lambda self: None) 'Gets or sets the time,in coordinated universal time (UTC),when the current file or directory was last written to.\n\n\n\nGet: LastWriteTimeUtc(self: FileSystemInfo) -> DateTime\n\n\n\nSet: LastWriteTimeUtc(self: FileSystemInfo)=value\n\n' name = property(lambda self: object(), lambda self, v: None, lambda self: None) 'For files,gets the name of the file. For directories,gets the name of the last directory in the hierarchy if a hierarchy exists. Otherwise,the Name property gets the name of the directory.\n\n\n\nGet: Name(self: FileSystemInfo) -> str\n\n\n\n' full_path = None original_path = None
# coding=utf-8 """ Helper methods to access xml elements """ def get_module_name(module): return next(module.iter("ModuleName")).text def get_module_tracked_methods(module): return next(module.iter("TrackedMethods")) def get_module_classes(module): return next(module.iter("Classes")) def get_module_files(module): return next(module.iter("Files")) def get_class_methods(clazz): return next(clazz.iter("Methods")) def get_method_name(method): return next(method.iter("Name")).text def get_method_file_ref(method): return next(method.iter("FileRef"), None) def get_method_coverage(method): # Get method point tag method_point = next(method.iter("MethodPoint"), None) if method_point is None or not list(method_point): return [None, None] # Look at tracked method refs tracked_refs = method_point[0] if not list(tracked_refs): return [None, None] # Return uids of tests that visit the 1st sequence point tests_uids = list(map(lambda x: x.attrib["uid"], tracked_refs)) return [get_method_name(method), tests_uids]
""" Helper methods to access xml elements """ def get_module_name(module): return next(module.iter('ModuleName')).text def get_module_tracked_methods(module): return next(module.iter('TrackedMethods')) def get_module_classes(module): return next(module.iter('Classes')) def get_module_files(module): return next(module.iter('Files')) def get_class_methods(clazz): return next(clazz.iter('Methods')) def get_method_name(method): return next(method.iter('Name')).text def get_method_file_ref(method): return next(method.iter('FileRef'), None) def get_method_coverage(method): method_point = next(method.iter('MethodPoint'), None) if method_point is None or not list(method_point): return [None, None] tracked_refs = method_point[0] if not list(tracked_refs): return [None, None] tests_uids = list(map(lambda x: x.attrib['uid'], tracked_refs)) return [get_method_name(method), tests_uids]
def myif(test, trueval, falseval): if test: return trueval else: return falseval myif(True, "hello", "goodbye")
def myif(test, trueval, falseval): if test: return trueval else: return falseval myif(True, 'hello', 'goodbye')
def apply_async(func, args, *, callback): result = func(*args) callback(result) def print_result(result): print('Got:', result) def add(x, y): return (x + y) apply_async(add, (2, 3), callback=print_result) apply_async(add, ("hello", "world"), callback=print_result) def make_handler(): sequence = 0 def handler(result): nonlocal sequence sequence += 1 print('[{}] Got: {}'.format(sequence, result)) return handler handler = make_handler() apply_async(add, (2, 3), callback=handler) apply_async(add, ("hello", "world"), callback=handler)
def apply_async(func, args, *, callback): result = func(*args) callback(result) def print_result(result): print('Got:', result) def add(x, y): return x + y apply_async(add, (2, 3), callback=print_result) apply_async(add, ('hello', 'world'), callback=print_result) def make_handler(): sequence = 0 def handler(result): nonlocal sequence sequence += 1 print('[{}] Got: {}'.format(sequence, result)) return handler handler = make_handler() apply_async(add, (2, 3), callback=handler) apply_async(add, ('hello', 'world'), callback=handler)
class Solution: def __init__(self): self.dic_no_circle = {} def rob_no_circle(self, nums: List[int], start, end) -> int: n = len(nums) if (start,end) in self.dic_no_circle: return self.dic_no_circle[start,end] if n == 0: return 0 if n == 1: self.dic_no_circle[start,end] = nums[0] return nums[0] if n == 2: self.dic_no_circle[start,end] = max(nums[0], nums[1]) return self.dic_no_circle[start,end] ans = max(self.rob_no_circle(nums[:-2], start, end-2)+nums[-1],self.rob_no_circle(nums[:-1], start, end-1)) self.dic_no_circle[start,end] = ans return ans def rob(self, nums: List[int]) -> int: n = len(nums) if n <= 2: return self.rob_no_circle(nums, 0, n) if n == 3: return max(nums[0], nums[1], nums[2]) # if the robber robs at the last (n-1 th) house, you cannot rob from index 0 and n-2. profit = self.rob_no_circle(nums[1:-2], 1, n-2) + nums[-1] # if the robber robs as the first (0 th) house, you cannot rob from index 1 and n-1. profit = max(profit, self.rob_no_circle(nums[2:-1], 2, n-1) + nums[0]) # what if we choose neither index 0 nor index n-1? profit = max(profit, self.rob_no_circle(nums[1:-1], 1, n-1)) return profit
class Solution: def __init__(self): self.dic_no_circle = {} def rob_no_circle(self, nums: List[int], start, end) -> int: n = len(nums) if (start, end) in self.dic_no_circle: return self.dic_no_circle[start, end] if n == 0: return 0 if n == 1: self.dic_no_circle[start, end] = nums[0] return nums[0] if n == 2: self.dic_no_circle[start, end] = max(nums[0], nums[1]) return self.dic_no_circle[start, end] ans = max(self.rob_no_circle(nums[:-2], start, end - 2) + nums[-1], self.rob_no_circle(nums[:-1], start, end - 1)) self.dic_no_circle[start, end] = ans return ans def rob(self, nums: List[int]) -> int: n = len(nums) if n <= 2: return self.rob_no_circle(nums, 0, n) if n == 3: return max(nums[0], nums[1], nums[2]) profit = self.rob_no_circle(nums[1:-2], 1, n - 2) + nums[-1] profit = max(profit, self.rob_no_circle(nums[2:-1], 2, n - 1) + nums[0]) profit = max(profit, self.rob_no_circle(nums[1:-1], 1, n - 1)) return profit
# t = True # count= 0 # sum = 0 # while t==True: # x = int(input()) # if x >=0: # count+=1 # sum+=x # if x<0: # t = False # print(sum) # print(f'{sum/count:.2f}') t = True count= 0 sum = 0 while t==True: x = int(input()) if x<=0: t = False else: count+=1 sum+=x print(sum) print(f'{sum/count:.2f}')
t = True count = 0 sum = 0 while t == True: x = int(input()) if x <= 0: t = False else: count += 1 sum += x print(sum) print(f'{sum / count:.2f}')
class Files(object): def __init__(self): return @staticmethod def save_output(filename, content): try: with open('./' + filename, 'w') as out_file: out_file.write('\n'.join(content) + '\n') out_file.close() except IOError as err: print('Error writing file')
class Files(object): def __init__(self): return @staticmethod def save_output(filename, content): try: with open('./' + filename, 'w') as out_file: out_file.write('\n'.join(content) + '\n') out_file.close() except IOError as err: print('Error writing file')
#!/usr/bin/env python3 '''This is Example module''' print("useless script")
"""This is Example module""" print('useless script')
class Node: def __init__(self, x): self.val = x self.next = None def __str__(self): string = "[" node = self while node: string += "{} ->".format(node.val) node = node.next string += "None]" return string def get_nodes(values): next_node = None for value in values[::-1]: node = Node(value) node.next = next_node next_node = node return next_node def get_list(head): node = head nodes = list() while node: nodes.append(node.val) node = node.next return nodes def partition(llist, k): head = llist prev, curr = head, head.next while curr: if curr.val < k: prev.next = curr.next curr.next = head head = curr curr = prev.next else: prev = curr curr = curr.next return head # Tests assert get_list(partition(get_nodes([5, 1, 8, 0, 3]), 3)) == [0, 1, 5, 8, 3]
class Node: def __init__(self, x): self.val = x self.next = None def __str__(self): string = '[' node = self while node: string += '{} ->'.format(node.val) node = node.next string += 'None]' return string def get_nodes(values): next_node = None for value in values[::-1]: node = node(value) node.next = next_node next_node = node return next_node def get_list(head): node = head nodes = list() while node: nodes.append(node.val) node = node.next return nodes def partition(llist, k): head = llist (prev, curr) = (head, head.next) while curr: if curr.val < k: prev.next = curr.next curr.next = head head = curr curr = prev.next else: prev = curr curr = curr.next return head assert get_list(partition(get_nodes([5, 1, 8, 0, 3]), 3)) == [0, 1, 5, 8, 3]
common_urls_http = [ 'http://www.youtube.com' 'http://www.facebook.com' 'http://www.baidu.com' 'http://www.yahoo.com' 'http://www.amazon.com' 'http://www.wikipedia.org' 'http://www.qq.com' 'http://www.google.co.in' 'http://www.twitter.com' 'http://www.live.com' 'http://www.taobao.com' 'http://www.bing.com' 'http://www.instagram.com' 'http://www.weibo.com' 'http://www.sina.com.cn' 'http://www.linkedin.com' 'http://www.yahoo.co.jp' 'http://www.msn.com' 'http://www.vk.com' 'http://www.google.de' 'http://www.yandex.ru' 'http://www.hao123.com' 'http://www.google.co.uk' 'http://www.reddit.com' 'http://www.ebay.com' 'http://www.google.fr' 'http://www.t.co' 'http://www.tmall.com' 'http://www.google.com.br' 'http://www.360.cn' 'http://www.sohu.com' 'http://www.amazon.co.jp' 'http://www.pinterest.com' 'http://www.netflix.com' 'http://www.google.it' 'http://www.google.ru' 'http://www.microsoft.com' 'http://www.google.es' 'http://www.wordpress.com' 'http://www.gmw.cn' 'http://www.tumblr.com' 'http://www.paypal.com' 'http://www.blogspot.com' 'http://www.imgur.com' 'http://www.stackoverflow.com' 'http://www.aliexpress.com' 'http://www.naver.com' 'http://www.ok.ru' 'http://www.apple.com' 'http://www.github.com' 'http://www.chinadaily.com.cn' 'http://www.imdb.com' 'http://www.google.co.kr' 'http://www.fc2.com' 'http://www.jd.com' 'http://www.blogger.com' 'http://www.163.com' 'http://www.google.ca' 'http://www.whatsapp.com' 'http://www.amazon.in' 'http://www.office.com' 'http://www.tianya.cn' 'http://www.google.co.id' 'http://www.youku.com' 'http://www.rakuten.co.jp' 'http://www.craigslist.org' 'http://www.amazon.de' 'http://www.nicovideo.jp' 'http://www.google.pl' 'http://www.soso.com' 'http://www.bilibili.com' 'http://www.dropbox.com' 'http://www.xinhuanet.com' 'http://www.outbrain.com' 'http://www.pixnet.net' 'http://www.alibaba.com' 'http://www.alipay.com' 'http://www.microsoftonline.com' 'http://www.booking.com' 'http://www.googleusercontent.com' 'http://www.google.com.au' 'http://www.popads.net' 'http://www.cntv.cn' 'http://www.zhihu.com' 'http://www.amazon.co.uk' 'http://www.diply.com' 'http://www.coccoc.com' 'http://www.cnn.com' 'http://www.bbc.co.uk' 'http://www.twitch.tv' 'http://www.wikia.com' 'http://www.google.co.th' 'http://www.go.com' 'http://www.google.com.ph' 'http://www.doubleclick.net' 'http://www.onet.pl' 'http://www.googleadservices.com' 'http://www.accuweather.com' 'http://www.googleweblight.com' 'http://www.answers.yahoo.com' 'http://www.sans.org' ] common_urls_https = [ 'https://www.youtube.com', 'https://www.facebook.com', 'https://www.baidu.com', 'https://www.yahoo.com', 'https://www.amazon.com', 'https://www.wikipedia.org', 'https://www.qq.com', 'https://www.google.co.in', 'https://www.twitter.com', 'https://www.live.com', 'https://www.taobao.com', 'https://www.bing.com', 'https://www.instagram.com', 'https://www.weibo.com', 'https://www.sina.com.cn', 'https://www.linkedin.com', 'https://www.yahoo.co.jp', 'https://www.msn.com', 'https://www.vk.com', 'https://www.google.de', 'https://www.yandex.ru', 'https://www.hao123.com', 'https://www.google.co.uk', 'https://www.reddit.com', 'https://www.ebay.com', 'https://www.google.fr', 'https://www.t.com', 'https://www.tmall.com', 'https://www.google.com.br', 'https://www.360.cn', 'https://www.sohu.com', 'https://www.amazon.co.jp', 'https://www.pinterest.com', 'https://www.netflix.com', 'https://www.google.it', 'https://www.google.ru', 'https://www.microsoft.com', 'https://www.google.es', 'https://www.wordpress.com', 'https://www.gmw.cn', 'https://www.tumblr.com', 'https://www.paypal.com', 'https://www.blogspot.com', 'https://www.imgur.com', 'https://www.stackoverflow.com', 'https://www.aliexpress.com', 'https://www.naver.com', 'https://www.ok.ru', 'https://www.apple.com', 'https://www.github.com', 'https://www.chinadaily.com.cn', 'https://www.imdb.com', 'https://www.google.co.kr', 'https://www.fc2.com', 'https://www.jd.com', 'https://www.blogger.com', 'https://www.163.com', 'https://www.google.ca', 'https://www.whatsapp.com', 'https://www.amazon.in', 'https://www.office.com', 'https://www.tianya.cn', 'https://www.google.co.id', 'https://www.youku.com', 'https://www.rakuten.co.jp', 'https://www.craigslist.org', 'https://www.amazon.de', 'https://www.nicovideo.jp', 'https://www.google.pl', 'https://www.soso.com', 'https://www.bilibili.com', 'https://www.dropbox.com', 'https://www.xinhuanet.com', 'https://www.outbrain.com', 'https://www.pixnet.net', 'https://www.alibaba.com', 'https://www.alipay.com', 'https://www.microsoftonline.com', 'https://www.booking.com', 'https://www.googleusercontent.com', 'https://www.google.com.au', 'https://www.popads.net', 'https://www.cntv.cn', 'https://www.zhihu.com', 'https://www.amazon.co.uk', 'https://www.diply.com', 'https://www.coccoc.com', 'https://www.cnn.com', 'https://www.bbc.co.uk', 'https://www.twitch.tv', 'https://www.wikia.com', 'https://www.google.co.th', 'https://www.go.com', 'https://www.google.com.ph', 'https://www.doubleclick.net', 'https://www.onet.pl', 'https://www.googleadservices.com', 'https://www.accuweather.com', 'https://www.googleweblight.com', 'https://www.answers.yahoo.com', 'https://www.sans.org', 'https://support.google.com', 'https://www.adobe.com', 'https://www.gulf-times.com', ]
common_urls_http = ['http://www.youtube.comhttp://www.facebook.comhttp://www.baidu.comhttp://www.yahoo.comhttp://www.amazon.comhttp://www.wikipedia.orghttp://www.qq.comhttp://www.google.co.inhttp://www.twitter.comhttp://www.live.comhttp://www.taobao.comhttp://www.bing.comhttp://www.instagram.comhttp://www.weibo.comhttp://www.sina.com.cnhttp://www.linkedin.comhttp://www.yahoo.co.jphttp://www.msn.comhttp://www.vk.comhttp://www.google.dehttp://www.yandex.ruhttp://www.hao123.comhttp://www.google.co.ukhttp://www.reddit.comhttp://www.ebay.comhttp://www.google.frhttp://www.t.cohttp://www.tmall.comhttp://www.google.com.brhttp://www.360.cnhttp://www.sohu.comhttp://www.amazon.co.jphttp://www.pinterest.comhttp://www.netflix.comhttp://www.google.ithttp://www.google.ruhttp://www.microsoft.comhttp://www.google.eshttp://www.wordpress.comhttp://www.gmw.cnhttp://www.tumblr.comhttp://www.paypal.comhttp://www.blogspot.comhttp://www.imgur.comhttp://www.stackoverflow.comhttp://www.aliexpress.comhttp://www.naver.comhttp://www.ok.ruhttp://www.apple.comhttp://www.github.comhttp://www.chinadaily.com.cnhttp://www.imdb.comhttp://www.google.co.krhttp://www.fc2.comhttp://www.jd.comhttp://www.blogger.comhttp://www.163.comhttp://www.google.cahttp://www.whatsapp.comhttp://www.amazon.inhttp://www.office.comhttp://www.tianya.cnhttp://www.google.co.idhttp://www.youku.comhttp://www.rakuten.co.jphttp://www.craigslist.orghttp://www.amazon.dehttp://www.nicovideo.jphttp://www.google.plhttp://www.soso.comhttp://www.bilibili.comhttp://www.dropbox.comhttp://www.xinhuanet.comhttp://www.outbrain.comhttp://www.pixnet.nethttp://www.alibaba.comhttp://www.alipay.comhttp://www.microsoftonline.comhttp://www.booking.comhttp://www.googleusercontent.comhttp://www.google.com.auhttp://www.popads.nethttp://www.cntv.cnhttp://www.zhihu.comhttp://www.amazon.co.ukhttp://www.diply.comhttp://www.coccoc.comhttp://www.cnn.comhttp://www.bbc.co.ukhttp://www.twitch.tvhttp://www.wikia.comhttp://www.google.co.thhttp://www.go.comhttp://www.google.com.phhttp://www.doubleclick.nethttp://www.onet.plhttp://www.googleadservices.comhttp://www.accuweather.comhttp://www.googleweblight.comhttp://www.answers.yahoo.comhttp://www.sans.org'] common_urls_https = ['https://www.youtube.com', 'https://www.facebook.com', 'https://www.baidu.com', 'https://www.yahoo.com', 'https://www.amazon.com', 'https://www.wikipedia.org', 'https://www.qq.com', 'https://www.google.co.in', 'https://www.twitter.com', 'https://www.live.com', 'https://www.taobao.com', 'https://www.bing.com', 'https://www.instagram.com', 'https://www.weibo.com', 'https://www.sina.com.cn', 'https://www.linkedin.com', 'https://www.yahoo.co.jp', 'https://www.msn.com', 'https://www.vk.com', 'https://www.google.de', 'https://www.yandex.ru', 'https://www.hao123.com', 'https://www.google.co.uk', 'https://www.reddit.com', 'https://www.ebay.com', 'https://www.google.fr', 'https://www.t.com', 'https://www.tmall.com', 'https://www.google.com.br', 'https://www.360.cn', 'https://www.sohu.com', 'https://www.amazon.co.jp', 'https://www.pinterest.com', 'https://www.netflix.com', 'https://www.google.it', 'https://www.google.ru', 'https://www.microsoft.com', 'https://www.google.es', 'https://www.wordpress.com', 'https://www.gmw.cn', 'https://www.tumblr.com', 'https://www.paypal.com', 'https://www.blogspot.com', 'https://www.imgur.com', 'https://www.stackoverflow.com', 'https://www.aliexpress.com', 'https://www.naver.com', 'https://www.ok.ru', 'https://www.apple.com', 'https://www.github.com', 'https://www.chinadaily.com.cn', 'https://www.imdb.com', 'https://www.google.co.kr', 'https://www.fc2.com', 'https://www.jd.com', 'https://www.blogger.com', 'https://www.163.com', 'https://www.google.ca', 'https://www.whatsapp.com', 'https://www.amazon.in', 'https://www.office.com', 'https://www.tianya.cn', 'https://www.google.co.id', 'https://www.youku.com', 'https://www.rakuten.co.jp', 'https://www.craigslist.org', 'https://www.amazon.de', 'https://www.nicovideo.jp', 'https://www.google.pl', 'https://www.soso.com', 'https://www.bilibili.com', 'https://www.dropbox.com', 'https://www.xinhuanet.com', 'https://www.outbrain.com', 'https://www.pixnet.net', 'https://www.alibaba.com', 'https://www.alipay.com', 'https://www.microsoftonline.com', 'https://www.booking.com', 'https://www.googleusercontent.com', 'https://www.google.com.au', 'https://www.popads.net', 'https://www.cntv.cn', 'https://www.zhihu.com', 'https://www.amazon.co.uk', 'https://www.diply.com', 'https://www.coccoc.com', 'https://www.cnn.com', 'https://www.bbc.co.uk', 'https://www.twitch.tv', 'https://www.wikia.com', 'https://www.google.co.th', 'https://www.go.com', 'https://www.google.com.ph', 'https://www.doubleclick.net', 'https://www.onet.pl', 'https://www.googleadservices.com', 'https://www.accuweather.com', 'https://www.googleweblight.com', 'https://www.answers.yahoo.com', 'https://www.sans.org', 'https://support.google.com', 'https://www.adobe.com', 'https://www.gulf-times.com']
# Implement a quicksort items = [20, 6, 8, 53, 56, 23, 87, 41, 49, 19] def quickSort(dataset, first, last): if first < last: # calculate the split point pivotIdx = partition(dataset, first, last) # now sort the two partitions quickSort(dataset, first, pivotIdx-1) quickSort(dataset, pivotIdx+1, last) def partition(datavalues, first, last): # choose the first item as the pivot value pivotvalue = datavalues[first] # establish the upper and lower indexes lower = first + 1 upper = last # start searching for the crossing point done = False while not done: # advance the lower index while lower <= upper and datavalues[lower] <= pivotvalue: lower += 1 # advance the upper index while datavalues[upper] >= pivotvalue and upper >= lower: upper -= 1 # if the two indexes cross, we have found the split point if upper < lower: done = True else: # exchange the two values temp = datavalues[lower] datavalues[lower] = datavalues[upper] datavalues[upper] = temp # when the split point is found, exchange the pivot value temp = datavalues[first] datavalues[first] = datavalues[upper] datavalues[upper] = temp # return the split point index return upper # test the merge sort with data print(items) quickSort(items, 0, len(items)-1) print(items)
items = [20, 6, 8, 53, 56, 23, 87, 41, 49, 19] def quick_sort(dataset, first, last): if first < last: pivot_idx = partition(dataset, first, last) quick_sort(dataset, first, pivotIdx - 1) quick_sort(dataset, pivotIdx + 1, last) def partition(datavalues, first, last): pivotvalue = datavalues[first] lower = first + 1 upper = last done = False while not done: while lower <= upper and datavalues[lower] <= pivotvalue: lower += 1 while datavalues[upper] >= pivotvalue and upper >= lower: upper -= 1 if upper < lower: done = True else: temp = datavalues[lower] datavalues[lower] = datavalues[upper] datavalues[upper] = temp temp = datavalues[first] datavalues[first] = datavalues[upper] datavalues[upper] = temp return upper print(items) quick_sort(items, 0, len(items) - 1) print(items)
FOUND_PYTORCH = True # TODO check using code CONFIG = "config_file" BASELOGFOLDER = 'base_log_folder' SEED = 'seed' DEVICE = None
found_pytorch = True config = 'config_file' baselogfolder = 'base_log_folder' seed = 'seed' device = None
def is_palindrome(n): s, r = str(n), str(n)[::-1] return s == r def solve(d): n, m, largest = 10 ** (d - 1), 10 ** d, 0 for i in range(n, m): for j in range(i + 1, m): p = i * j if largest < p and is_palindrome(p): largest = p return largest # d = 2 d = 3 print(solve(d))
def is_palindrome(n): (s, r) = (str(n), str(n)[::-1]) return s == r def solve(d): (n, m, largest) = (10 ** (d - 1), 10 ** d, 0) for i in range(n, m): for j in range(i + 1, m): p = i * j if largest < p and is_palindrome(p): largest = p return largest d = 3 print(solve(d))
# TC: O(n) | SC: O(n) def solution_1(price): profit = [0]*len(price) # right to left max_price = price[-1] for i in range(len(price)-2, -1, -1): if price[i] > max_price: max_price = price[i] profit[i] = max(profit[i+1], (max_price-price[i])) # left to right min_price = price[0] for i in range(1, len(price)): if min_price > price[i]: min_price = price[i] profit[i] = max(profit[i-1], profit[i]+(price[i]-min_price)) return profit[-1] if __name__ == '__main__': price = [10, 22, 5, 75, 65, 80] # 87 # price = [2, 30, 15, 10, 8, 25, 80] # 100 # price = [100, 30, 15, 10, 8, 25, 80] # 72 # price = [90, 80, 70, 60, 50] # 0 print('solution_1: ', solution_1(price))
def solution_1(price): profit = [0] * len(price) max_price = price[-1] for i in range(len(price) - 2, -1, -1): if price[i] > max_price: max_price = price[i] profit[i] = max(profit[i + 1], max_price - price[i]) min_price = price[0] for i in range(1, len(price)): if min_price > price[i]: min_price = price[i] profit[i] = max(profit[i - 1], profit[i] + (price[i] - min_price)) return profit[-1] if __name__ == '__main__': price = [10, 22, 5, 75, 65, 80] print('solution_1: ', solution_1(price))
input_string = input('Please input a number: ') if input_string.isnumeric(): print('The number is accepted') else: print('The input is invalid')
input_string = input('Please input a number: ') if input_string.isnumeric(): print('The number is accepted') else: print('The input is invalid')
input() S=input() dot=S.count(".") ans=dot sharp=0 for s in S: if s=="#":sharp+=1 else:dot-=1 ans=min(ans,sharp+dot) print(ans)
input() s = input() dot = S.count('.') ans = dot sharp = 0 for s in S: if s == '#': sharp += 1 else: dot -= 1 ans = min(ans, sharp + dot) print(ans)
# Project Quex (http://quex.sourceforge.net); License: MIT; # (C) 2005-2020 Frank-Rene Schaefer; #_______________________________________________________________________________ __debug_recursion_depth = -1 __debug_output_enabled_f = False # True / False def __debug_print(msg, msg2="", msg3=""): global __debug_recursion_depth if not __debug_output_enabled_f: return if type(msg2) != str: msg2 = repr(msg2) if type(msg3) != str: msg3 = repr(msg3) txt = "##" + " " * __debug_recursion_depth + msg + " " + msg2 + " " + msg3 txt = txt.replace("\n", "\n " + " " * __debug_recursion_depth) print(txt) def __debug_exit(result, stream): global __debug_recursion_depth __debug_recursion_depth -= 1 if __debug_output_enabled_f: pos = stream.tell() txt = stream.read(64).replace("\n", "\\n") stream.seek(pos) __debug_print("##exit: [%s], remainder = \"%s\"" % (type(result), txt)) return result def __debug_entry(function_name, stream): global __debug_recursion_depth __debug_recursion_depth += 1 if __debug_output_enabled_f: pos = stream.tell() txt = stream.read(64).replace("\n", "\\n") stream.seek(pos) __debug_print("##entry: %s, remainder = \"%s\"" % (function_name, txt)) def __debug_print_stream(Prefix, stream): pos = stream.tell() print("#%s: [%s]" % (Prefix, stream.read(64).replace("\n", "\\n"))) stream.seek(pos)
__debug_recursion_depth = -1 __debug_output_enabled_f = False def __debug_print(msg, msg2='', msg3=''): global __debug_recursion_depth if not __debug_output_enabled_f: return if type(msg2) != str: msg2 = repr(msg2) if type(msg3) != str: msg3 = repr(msg3) txt = '##' + ' ' * __debug_recursion_depth + msg + ' ' + msg2 + ' ' + msg3 txt = txt.replace('\n', '\n ' + ' ' * __debug_recursion_depth) print(txt) def __debug_exit(result, stream): global __debug_recursion_depth __debug_recursion_depth -= 1 if __debug_output_enabled_f: pos = stream.tell() txt = stream.read(64).replace('\n', '\\n') stream.seek(pos) __debug_print('##exit: [%s], remainder = "%s"' % (type(result), txt)) return result def __debug_entry(function_name, stream): global __debug_recursion_depth __debug_recursion_depth += 1 if __debug_output_enabled_f: pos = stream.tell() txt = stream.read(64).replace('\n', '\\n') stream.seek(pos) __debug_print('##entry: %s, remainder = "%s"' % (function_name, txt)) def __debug_print_stream(Prefix, stream): pos = stream.tell() print('#%s: [%s]' % (Prefix, stream.read(64).replace('\n', '\\n'))) stream.seek(pos)
dollar_bill = 10 if dollar_bill < 1000: print('bill exist') else: print ('bill does not exist') # dollar_bill = 1000 # # if dollar_bill < 800: # print ('bill exist') # else: # print ('bill does not exist') # # dollar_bill = 1000 # if dollar_bill > 500: # print ('bill exist') # else: # print ('bill does not exist') # # dollar_bill = 1000 # if dollar_bill > 500: # print('bill exist') # else: # print('bill does not exist') jKDK
dollar_bill = 10 if dollar_bill < 1000: print('bill exist') else: print('bill does not exist') jKDK
def abc() : print('a') print('b') print('c') def get_vat(price) : percent = 0.1 return price*percent p = 1000 answer = get_vat(p) print(answer)
def abc(): print('a') print('b') print('c') def get_vat(price): percent = 0.1 return price * percent p = 1000 answer = get_vat(p) print(answer)
class CreateOrderController: def __init__(self, create_order_use_case): self.create_order_use_case = create_order_use_case def route(self, body): if body is not None: consumed_in = body["consumed_in"] if "consumed_in" in body else None table = body["table"] if "table" in body else None payment_method = body["payment_method"] if "payment_method" in body else None obs = body["obs"] if "obs" in body else None response = self.create_order_use_case.create_order( consumed_in=consumed_in, table=table, payment_method=payment_method, obs=obs) return response return {"data": None, "status": 400, "errors": ["Invalid request"]}
class Createordercontroller: def __init__(self, create_order_use_case): self.create_order_use_case = create_order_use_case def route(self, body): if body is not None: consumed_in = body['consumed_in'] if 'consumed_in' in body else None table = body['table'] if 'table' in body else None payment_method = body['payment_method'] if 'payment_method' in body else None obs = body['obs'] if 'obs' in body else None response = self.create_order_use_case.create_order(consumed_in=consumed_in, table=table, payment_method=payment_method, obs=obs) return response return {'data': None, 'status': 400, 'errors': ['Invalid request']}
################################################################## # this function will print any AST that follows the # # (TYPE [, child1, child2,...]) # # tuple format for tree nodes. def dumpast(node): _dumpast(node) print('') def _dumpast(node, level=0): if isinstance(node, tuple): indent(level) nchildren = len(node) - 1 print("(%s" % node[0], end='') if nchildren > 0: print(" ", end='') for c in range(nchildren): _dumpast(node[c+1], level+1) if c != nchildren-1: print(' ', end='') print(")", end='') elif isinstance(node, list): indent(level) nchildren = len(node) print("[", end='') if nchildren > 0: print(" ", end='') for c in range(nchildren): _dumpast(node[c], level+1) if c != nchildren-1: print(' ', end='') print("]", end='') else: print("%s" % str(node), end='') def indent(level): print('') for i in range(level): print(' |',end='')
def dumpast(node): _dumpast(node) print('') def _dumpast(node, level=0): if isinstance(node, tuple): indent(level) nchildren = len(node) - 1 print('(%s' % node[0], end='') if nchildren > 0: print(' ', end='') for c in range(nchildren): _dumpast(node[c + 1], level + 1) if c != nchildren - 1: print(' ', end='') print(')', end='') elif isinstance(node, list): indent(level) nchildren = len(node) print('[', end='') if nchildren > 0: print(' ', end='') for c in range(nchildren): _dumpast(node[c], level + 1) if c != nchildren - 1: print(' ', end='') print(']', end='') else: print('%s' % str(node), end='') def indent(level): print('') for i in range(level): print(' |', end='')
class FlameLabel(QtWidgets.QLabel): """ Custom Qt Flame Label Widget For different label looks set label_type as: 'normal', 'background', or 'outline' To use: label = FlameLabel('Label Name', 'normal', window) """ def __init__(self, label_name, label_type, parent_window, *args, **kwargs): super(FlameLabel, self).__init__(*args, **kwargs) self.setText(label_name) self.setParent(parent_window) self.setMinimumSize(110, 28) self.setMaximumHeight(28) self.setFocusPolicy(QtCore.Qt.NoFocus) # Set label stylesheet based on label_type if label_type == 'normal': self.setStyleSheet('QLabel {color: #9a9a9a; border-bottom: 1px inset #282828; font: 14px "Discreet"}' 'QLabel:disabled {color: #6a6a6a}') elif label_type == 'background': self.setAlignment(QtCore.Qt.AlignCenter) self.setStyleSheet('color: #9a9a9a; background-color: #393939; font: 14px "Discreet"') elif label_type == 'outline': self.setAlignment(QtCore.Qt.AlignCenter) self.setStyleSheet('color: #9a9a9a; background-color: #212121; border: 1px solid #404040; font: 14px "Discreet"')
class Flamelabel(QtWidgets.QLabel): """ Custom Qt Flame Label Widget For different label looks set label_type as: 'normal', 'background', or 'outline' To use: label = FlameLabel('Label Name', 'normal', window) """ def __init__(self, label_name, label_type, parent_window, *args, **kwargs): super(FlameLabel, self).__init__(*args, **kwargs) self.setText(label_name) self.setParent(parent_window) self.setMinimumSize(110, 28) self.setMaximumHeight(28) self.setFocusPolicy(QtCore.Qt.NoFocus) if label_type == 'normal': self.setStyleSheet('QLabel {color: #9a9a9a; border-bottom: 1px inset #282828; font: 14px "Discreet"}QLabel:disabled {color: #6a6a6a}') elif label_type == 'background': self.setAlignment(QtCore.Qt.AlignCenter) self.setStyleSheet('color: #9a9a9a; background-color: #393939; font: 14px "Discreet"') elif label_type == 'outline': self.setAlignment(QtCore.Qt.AlignCenter) self.setStyleSheet('color: #9a9a9a; background-color: #212121; border: 1px solid #404040; font: 14px "Discreet"')
""" This module provides a wrapper for dict and list items that exposes dict entries as it's attributes - Example:: # import from obj import to_obj # initialize object = to_obj({ 'foo': 'bar' }) array = to_obj([{ 'baz': 'qux' }]) # provides accessors object.foo # provdes deep array[0].baz # in the iterator item.baz for item in array """ __version__ = "1.0.0" __docformat__ = "reStructuredText" class Obj(dict): """ Wrap `dict` to `Obj` Overwrite accessor methods to provide wrapped value """ def __getitem__(self, name): return to_obj(super().__getitem__(name)) def __getattr__(self, name): return to_obj(super().__getitem__(name)) def __setattr__(self, name, value): self[name] = value def __delattr__(self, name): if name in self: del self[name] else: raise AttributeError("No such attribute: " + name) def copy(self): return Obj(super().copy()) def fromkeys(self, value): """ Overwrite built-in `fromkeys` to return a wrapped value """ return Obj(super().fromkeys(value)) def get(self, value, default=None): return to_obj(super().get(value, default)) def pop(self, value): return to_obj(super().pop(value)) def popitem(self): value = super().popitem() return (value[0], to_obj(value[1])) class Arr(list): """ Wrap `list` to `Arr` Overwrite accessor methods to provide wrapped value """ def __getitem__(self, index): # if isinstance(index, slice): # for item in super().__getitem__(index): # return to_obj(item) # else: return to_obj(super().__getitem__(index)) def __iter__(self): for value in list.__iter__(self): yield to_obj(value) def copy(self): return to_obj(super().copy()) def pop(self, value=0): return to_obj(super().pop(value)) def to_obj(value): """ Wrap `dict` to `Obj` Wrap `list` to `Arr` otherwise return original value """ if isinstance(value, dict): return Obj(value) if isinstance(value, list): return Arr(value) return value
""" This module provides a wrapper for dict and list items that exposes dict entries as it's attributes - Example:: # import from obj import to_obj # initialize object = to_obj({ 'foo': 'bar' }) array = to_obj([{ 'baz': 'qux' }]) # provides accessors object.foo # provdes deep array[0].baz # in the iterator item.baz for item in array """ __version__ = '1.0.0' __docformat__ = 'reStructuredText' class Obj(dict): """ Wrap `dict` to `Obj` Overwrite accessor methods to provide wrapped value """ def __getitem__(self, name): return to_obj(super().__getitem__(name)) def __getattr__(self, name): return to_obj(super().__getitem__(name)) def __setattr__(self, name, value): self[name] = value def __delattr__(self, name): if name in self: del self[name] else: raise attribute_error('No such attribute: ' + name) def copy(self): return obj(super().copy()) def fromkeys(self, value): """ Overwrite built-in `fromkeys` to return a wrapped value """ return obj(super().fromkeys(value)) def get(self, value, default=None): return to_obj(super().get(value, default)) def pop(self, value): return to_obj(super().pop(value)) def popitem(self): value = super().popitem() return (value[0], to_obj(value[1])) class Arr(list): """ Wrap `list` to `Arr` Overwrite accessor methods to provide wrapped value """ def __getitem__(self, index): return to_obj(super().__getitem__(index)) def __iter__(self): for value in list.__iter__(self): yield to_obj(value) def copy(self): return to_obj(super().copy()) def pop(self, value=0): return to_obj(super().pop(value)) def to_obj(value): """ Wrap `dict` to `Obj` Wrap `list` to `Arr` otherwise return original value """ if isinstance(value, dict): return obj(value) if isinstance(value, list): return arr(value) return value
def read_passports(): with open('input.txt') as fh: lines = fh.readlines() pp_chunks = [] chunk = "" for li in range(len(lines)): if lines[li].strip(): chunk += lines[li].strip() + " " else: pp_chunks.append(chunk) chunk = "" # I added 2 newlines at the end of the input so this will catch the last one. HAX. print(len(pp_chunks), pp_chunks) # each chunk is a one-line string containing all fields passports = [] for chunk in pp_chunks: p = dict() try: for tok in chunk.strip().split(' '): if not tok.strip(): # could have multiple spaces, no biggie continue k, v = tok.split(':') # might error if bad token p[k] = v except Exception: # invalid - skip. print("skipping chunk:", chunk) continue passports.append(p) print(len(passports,), passports) return passports def check_required_fields_present(p): # cid not actually required min_fields = {'byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid'} for field in min_fields: if field not in p: print("p missing", field, len(p), ":", p) return False return True def main(): pps = read_passports() valid_pps = [] for p in pps: if not check_required_fields_present(p): continue valid_pps.append(p) print(len(valid_pps)) if __name__ == '__main__': # 225 - too low # 235 - too high, so the idea's roughly right. main()
def read_passports(): with open('input.txt') as fh: lines = fh.readlines() pp_chunks = [] chunk = '' for li in range(len(lines)): if lines[li].strip(): chunk += lines[li].strip() + ' ' else: pp_chunks.append(chunk) chunk = '' print(len(pp_chunks), pp_chunks) passports = [] for chunk in pp_chunks: p = dict() try: for tok in chunk.strip().split(' '): if not tok.strip(): continue (k, v) = tok.split(':') p[k] = v except Exception: print('skipping chunk:', chunk) continue passports.append(p) print(len(passports), passports) return passports def check_required_fields_present(p): min_fields = {'byr', 'iyr', 'eyr', 'hgt', 'hcl', 'ecl', 'pid'} for field in min_fields: if field not in p: print('p missing', field, len(p), ':', p) return False return True def main(): pps = read_passports() valid_pps = [] for p in pps: if not check_required_fields_present(p): continue valid_pps.append(p) print(len(valid_pps)) if __name__ == '__main__': main()
""" Copyright (c) 2014-2015 F-Secure See LICENSE for details """
""" Copyright (c) 2014-2015 F-Secure See LICENSE for details """
#Brian Condon # 28/02/18 Week 5 formatting exercise # prints the headings # opens the data file print("petal length, petal width, sepal length, sepal width") with open("data/iris.csv") as data_file: # loops through the data file # prints and formats the data using the line split for line in data_file: print('{:13} {:12} {:13} {:8}'.format(line.split(',')[0], line.split(',')[1], line.split(',')[2], line.split(',')[3]))
print('petal length, petal width, sepal length, sepal width') with open('data/iris.csv') as data_file: for line in data_file: print('{:13} {:12} {:13} {:8}'.format(line.split(',')[0], line.split(',')[1], line.split(',')[2], line.split(',')[3]))
classification_file = open('classifications.csv') new_class_file = open('new_class.csv', mode='w') new_class_file.write(classification_file.readline()) for line in classification_file: line = line.strip().split(',') new_class_file.write(line[0] + ',') new_class_file.write(('1' if line[1] == 'True' else '0') + '\n')
classification_file = open('classifications.csv') new_class_file = open('new_class.csv', mode='w') new_class_file.write(classification_file.readline()) for line in classification_file: line = line.strip().split(',') new_class_file.write(line[0] + ',') new_class_file.write(('1' if line[1] == 'True' else '0') + '\n')
class Solution: def scoreOfParentheses(self, S): stack, res = [], 0 for c in S: if c == "(": stack.append(0) else: add = 2 * stack.pop() or 1 if stack: stack[-1] += add else: res += add return res
class Solution: def score_of_parentheses(self, S): (stack, res) = ([], 0) for c in S: if c == '(': stack.append(0) else: add = 2 * stack.pop() or 1 if stack: stack[-1] += add else: res += add return res
#!/usr/bin/python #template collection _file = open("basic_template.html") basic_template = _file.read() index = "<br><p>Welcome to this beautiful library at this nice day.</p><p>Today it is the <i><?= date ?></i>. On the left you can see the interactive menu with all the functions you need. </p><p>If you need any assistance either contact the library master or don't hesitate to ask the programmer (murph@gmx.net) for assistance." successful = "Your action has been done successfully!" error = "Sorry for the inconvenience, but an error occured: <br><p><?= msg ?></p>" ###back from javascript should be included! ########################################### ########################################### ### Persons call_add_person = """<p><table><tr><form action='/do_add_person'></tr> <tr><td>Student ID</td><td><input name='person_id' type='text'></input></td></tr> <tr><td>First Name</td><td><input name='firstname' type='text'></input></td></tr> <tr><td>Surname</td><td><input name='surname' type='text'></input></td></tr> <tr><td>Class</td><td><input name='_class' type='text'></input></td></tr> <tr><td>Semester</td><td><input name='semester' type='text'></input></td></tr> <tr><td>Cellphone Number</td><td><input name='cellphone' type='text'></input></td></tr> <tr><td></td></tr> <tr><td><input lable='submit' type='submit'></td></td></form></table></p>""" call_edit_person = """<p>Please specify which student should be edited<br><table><tr><form action='/do_edit_person'></tr> <tr><td>Student ID</td><td><input name='person_id' type='text'></input></td></tr> <tr><td></td></tr> <tr><td><input lable='submit' type='submit'></td></td></form></table></p> <i>If the student's ID is supposed to be changed delete the student and add him/her again.</i>""" do_edit_person = """<table><tr><form action='/do_edit_person_2'></tr> <tr><td>Student ID</td><td><?= person_id?><input name='person_id' type='hidden' value='<?= person_id ?>'></input></td></tr> <tr><td>First Name</td><td><input name='firstname' type='text' value='<?= firstname ?>'></input></td></tr> <tr><td>Surname</td><td><input name='surname' type='text' value='<?= surname ?>'></input></td></tr> <tr><td>Cellphone Number</td><td><input name='cellphone' type='text' value='<?= cellphone ?>'></input></td></tr> <tr><td>Class</td><td><input name='_class' type='text' value='<?= _class ?>'></input></td></tr> <tr><td>Semester</td><td><input name='semester' type='text' value='<?= semester ?>'></input></td></tr> <tr><td></td></tr> <tr><td><input lable='submit' type='submit'></td></td></form></table></p><br> The student ID cannot be changed. If that is necissary delete the student and add a new one.""" call_delete_person = """<p>Please specify which student should be <b>deleted</b><br><table><tr><form action='/do_delete_person'></tr> <tr><td>Student ID</td><td><input name='person_id' type='text'></input></td></tr> <tr><td></td></tr> <tr><td><input lable='submit' type='submit'></td></td></form></table></p>""" call_show_persons_none = """<p>In the Library System following students are registered:<br> <p>No students are in the database</p> """ call_show_persons = """<p>In the Library System following students are registered:<br><br></p> <table border=1> <tr><td><b>Student ID</b></td><td><b>First Name</b></td><td><b>Surname</b></td><td><b>Class</b></td><td><b>Semester</b></td><td><b>Cellphone</b></td></tr> <? for student_set in res: ?> <tr> <? for el in student_set: ?> <td WIDTH=27% HEIGHT=19><?= el ?></td> <? end ?> </tr> <? end ?> </table> """ call_search_person = """<p>Please enter some keywords<table><tr><form action='/do_search_person'></tr> <tr><td>Student ID</td><td><input name='person_id' type='text'></input></td></tr> <tr><td>First Name</td><td><input name='firstname' type='text' </input></td></tr> <tr><td>Surname</td><td><input name='surname' type='text'></input></td></tr> <tr><td>Class</td><td><input name='_class' type='text'></input></td></tr> <tr><td>Semester</td><td><input name='semester' type='text'></input></td></tr> <tr><td>Cellphone Number</td><td><input name='cellphone' type='text'></input></td></tr> <tr><td></td></tr> <tr><td><input lable='submit' type='submit'></td></td></form></table></p> """ do_search_person = """<p>The result of the search was as follows:<br><br></p> <table border=1> <tr><td><b>Student ID</b></td><td><b>First Name</b></td><td><b>Surname</b></td><td><b>Class</b></td><td><b>Semester</b></td><td><b>Cellphone</b></td></tr> <? for student_set in res: ?> <tr><? for el in student_set: ?> <td WIDTH=27% HEIGHT=19><?= el ?></td> <? end ?></tr> <? end ?> <? end ?></table> """ do_search_person_none = """<p>The result of the search was as follows:<br> <p>No students could be found</p> """ #################################################### #################################################### ### BOOKS ###################################### call_add_book = """<p><table><tr><form action='/do_add_book'></tr> <tr><td>Author</td><td><input name='author' type='text'></input></td></tr> <tr><td>Title</td><td><input name='title' type='text'></input></td></tr> <tr><td>Amount</td><td><input name='amount' type='text'></input></td></tr> <tr><td>Tags</td><td><input name='tags' type='text'></input></td></tr> <tr><td></td></tr> <tr><td><input lable='submit' type='submit'></td></td></form></table></p><br> Please seperate the tags by colons (',')""" call_edit_book = """<p>Please specify which book should be edited<br><table><tr><form action='/do_edit_book'></tr> <tr><td>Book ID</td><td><input name='book_id' type='text'></input></td></tr> <tr><td></td></tr> <tr><td><input lable='submit' type='submit'></td></td></form></table></p> """ do_edit_book = """<p><table><tr><form action='/do_edit_book_2'></tr> <tr><td>Book ID</td><td><?= book_id?><input name='book_id' type='hidden' value='<?= book_id ?>'></td></tr> <tr><td>Author</td><td><input name='author' type='text' value='<?= author ?>'></input></td></tr> <tr><td>Title</td><td><input name='title' type='text' value='<?= title?>'></input></td></tr> <tr><td>Amount</td><td><input name='amount' type='text' value='<?= amount ?>'></input></td></tr> <tr><td>Tags</td><td><input name='tags' type='text' value='<?= tags ?>'></input></td></tr> <tr><td></td></tr> <tr><td><input lable='submit' type='submit'></td></td></form></table></p><br> Please seperate the tags by colons (',')<br> The Book ID cannot be edited. Please delete the book and add it again if a new ID is nessicary.""" call_delete_book = """<p>Please specify which book should be <b>deleted</b><br><table><tr><form action='/do_delete_book'></tr> <tr><td>Book ID</td><td><input name='book_id' type='text'></input></td></tr> <tr><td></td></tr> <tr><td><input lable='submit' type='submit'></td></td></form></table></p>""" call_show_books_none = """<p>In the Library System following books are registered:<br> <p>No books are in the database</p> """ call_show_books = """<p>In the Library System following books are registered:<br><br></p> <table border=1> <tr><td><b>Book ID</b></td> <td><b>Author</b></td> <td><b>Title</b></td> <td><b>Amount</b></td> <td><b>Tags</b></td></tr> <? for student_set in res: ?> <tr><? for el in student_set: ?> <td WIDTH=24% HEIGHT=19><? if el: ?><?= el ?><? end ?><? if not el: ?><i>None</i><? end ?></td> <? end ?></tr> <? end ?> <? end ?></table> """ call_search_book = """<p>Please enter some keywords<table><tr><form action='/do_search_book'></tr> <tr><td>Book ID</td><td><input name='book_id' type='text'></input></td></tr> <tr><td>Author</td><td><input name='author' type='text'></input></td></tr> <tr><td>Title</td><td><input name='title' type='text'></input></td></tr> <tr><td>Tags</td><td><input name='tags' type='text'></input></td></tr> <tr><td></td></tr> <tr><td><input lable='submit' type='submit'></td></td></form></table></p><br> Please seperate the tags by colons (',') """ do_search_book = """<p>The result of the search was as follows:<br><br></p> <table border=1> <tr><td><b>Book ID</b></td> <td><b>Author</b></td> <td><b>Title</b></td> <td><b>Amount</b></td> <td><b>Tags</b></td></tr> <? for row in res: ?> <tr><? for el in row: ?> <td WIDTH=27% HEIGHT=19><?= el ?></td> <? end ?></tr> <? end ?> <? end ?></table> """ do_search_book_none = """<p>The result of the search was as follows:<br> <p>No books could be found</p> """ ############################################ ############################################ ###Library call_lend_book = """Please specify which book will be lent to whom:<br><br> <table><form action='/do_lend_book'> <tr><td>Student ID</td><td><input name='person_id' type='text'></input></td></tr> <tr><td>Book ID</td><td><input name='book_id' type='text'></input></td></tr> <tr><td>Amount</td><td><input name='amount' type='text'></input></td></tr> <tr><td></td></tr> <tr><td><input lable='submit' type='submit'></td></td></form></table></p> """ call_return_book = """Please specify who wants to return which book<br><br> <table><form action='/do_return_book'> <tr><td>Student ID</td><td><input name='person_id' type='text'></input></td></tr> <tr><td>Book ID</td><td><input name='book_id' type='text'></input></td></tr> <tr><td>Amount</td><td><input name='amount' type='text'></input></td></tr> <tr><td></td></tr> <tr><td><input lable='submit' type='submit'></td></td></form></table></p> """ call_show_lent_books = """<p>The result of the search was as follows:<br><br></p> <table border=1> <tr><td><b>Lend ID</b></td> <td><b>Student ID</b></td> <td><b>First name</b></td> <td><b>Surname</b></td> <td><b>Book ID</b></td> <td><b>Author</b></td> <td><b>Title</b></td> <td><b>Amount</b></td> <td><b>Return Date</b></td></tr> <? for student_set in res: ?> <tr><? for el in student_set: ?> <td WIDTH=16% HEIGHT=19><?= el ?></td> <? end ?></tr> <? end ?> <? end ?></table> """ call_show_lent_books_none = """<p>The result of the search was as follows:<br> <p>No lent books could be found</p> """ call_lent_books_to = """<p>Please specify for which student you want to have the list of the books to return<br><table><tr><form action='/do_lent_books_to'></tr> <tr><td>Student ID</td><td><input name='person_id' type='text'></input></td></tr> <tr><td></td></tr> <tr><td><input lable='submit' type='submit'></td></td></form></table></p> """ call_show_lent_books_to = """<p>The result for student '<?= person_id ?>' was as follows:<br><br></p> <table border=1> <tr><td><b>Lend ID</b></td> <td><b>Book ID</b></td> <td><b>Author</b></td> <td><b>Title</b></td> <td><b>Amount</b></td> <td><b>Return Date</b></td></tr> <? for student_set in res: ?> <tr><? for el in student_set: ?> <td WIDTH=16% HEIGHT=19><?= el ?></td> <? end ?></tr> <? end ?> <? end ?></table> """ call_show_lent_books_to_when_deleting = """<p>The student '<?= person_id ?>' could not be deleted because s/he still possesses books of the library:<br><br></p> <table border=1> <tr><td><b>Lend ID</b></td><td><b>Book ID</b></td><td><b>Author</b></td><td><b>Title</b></td><td><b>Amount</b></td><td><b>Return Date</b></td></tr> <? for student_set in res: ?> <tr><? for el in student_set: ?> <td WIDTH=16% HEIGHT=19><?= el ?></td> <? end ?></tr> <? end ?> <? end ?></table> """ call_show_lent_books_to_none = """<p>The result of the search was as follows:<br> <p>No lent books could be found</p> """ call_lent_books_none = """<p>The result of the search was as follows:<br> <p>No lent books could be found</p> """ call_show_books_over_limit = """ "<p>The result of the search was as follows:<br><br></p> <table border=1> <tr><td><b>Lend ID</b></td> <td><b>Student ID</b></td> <td><b>First name</b></td> <td><b>Surname</b></td> <td><b>Book ID</b></td> <td><b>Author</b></td> <td><b>Title</b></td></tr> <? for student_set in res: ?> <tr><? for el in student_set: ?> <td WIDTH=16% HEIGHT=19><?= el ?></td> <? end ?></tr> <? end ?> <? end ?></table> """ call_show_books_over_limit_none = """<p>The result of the search was as follows:<br> <p>No lent books over limit could be found</p> """ call_backup = """<p>Welcome to the backup function</p><br> <table> <tr> <td> For creating a backup, please press: </td> <td> <a href='/create_backup'>HERE</a></td> </tr> <tr> <td> For inserting an old backup: </td> <td> <form action='/upload_backup' method="post" enctype="multipart/form-data"><input type="file" name="myFile" /><br /> <input type="submit" value="INSERT BACKUP" /> </td> </tr> </table> """
_file = open('basic_template.html') basic_template = _file.read() index = "<br><p>Welcome to this beautiful library at this nice day.</p><p>Today it is the <i><?= date ?></i>. On the left you can see the interactive menu with all the functions you need. </p><p>If you need any assistance either contact the library master or don't hesitate to ask the programmer (murph@gmx.net) for assistance." successful = 'Your action has been done successfully!' error = 'Sorry for the inconvenience, but an error occured: <br><p><?= msg ?></p>' call_add_person = "<p><table><tr><form action='/do_add_person'></tr>\n<tr><td>Student ID</td><td><input name='person_id' type='text'></input></td></tr>\n<tr><td>First Name</td><td><input name='firstname' type='text'></input></td></tr>\n<tr><td>Surname</td><td><input name='surname' type='text'></input></td></tr>\n<tr><td>Class</td><td><input name='_class' type='text'></input></td></tr>\n<tr><td>Semester</td><td><input name='semester' type='text'></input></td></tr>\n<tr><td>Cellphone Number</td><td><input name='cellphone' type='text'></input></td></tr>\n<tr><td></td></tr>\n<tr><td><input lable='submit' type='submit'></td></td></form></table></p>" call_edit_person = "<p>Please specify which student should be edited<br><table><tr><form action='/do_edit_person'></tr>\n<tr><td>Student ID</td><td><input name='person_id' type='text'></input></td></tr>\n<tr><td></td></tr>\n<tr><td><input lable='submit' type='submit'></td></td></form></table></p>\n<i>If the student's ID is supposed to be changed delete the student and add him/her again.</i>" do_edit_person = "<table><tr><form action='/do_edit_person_2'></tr>\n<tr><td>Student ID</td><td><?= person_id?><input name='person_id' type='hidden' value='<?= person_id ?>'></input></td></tr>\n<tr><td>First Name</td><td><input name='firstname' type='text' value='<?= firstname ?>'></input></td></tr>\n<tr><td>Surname</td><td><input name='surname' type='text' value='<?= surname ?>'></input></td></tr>\n<tr><td>Cellphone Number</td><td><input name='cellphone' type='text' value='<?= cellphone ?>'></input></td></tr>\n<tr><td>Class</td><td><input name='_class' type='text' value='<?= _class ?>'></input></td></tr>\n<tr><td>Semester</td><td><input name='semester' type='text' value='<?= semester ?>'></input></td></tr>\n<tr><td></td></tr>\n<tr><td><input lable='submit' type='submit'></td></td></form></table></p><br>\nThe student ID cannot be changed. If that is necissary delete the student and add a new one." call_delete_person = "<p>Please specify which student should be <b>deleted</b><br><table><tr><form action='/do_delete_person'></tr>\n<tr><td>Student ID</td><td><input name='person_id' type='text'></input></td></tr>\n<tr><td></td></tr>\n<tr><td><input lable='submit' type='submit'></td></td></form></table></p>" call_show_persons_none = '<p>In the Library System following students are registered:<br>\n <p>No students are in the database</p>\n' call_show_persons = '<p>In the Library System following students are registered:<br><br></p>\n <table border=1>\n <tr><td><b>Student ID</b></td><td><b>First Name</b></td><td><b>Surname</b></td><td><b>Class</b></td><td><b>Semester</b></td><td><b>Cellphone</b></td></tr>\n <? for student_set in res: ?>\n <tr>\n <? for el in student_set: ?>\n <td WIDTH=27% HEIGHT=19><?= el ?></td>\n <? end ?>\n </tr>\n <? end ?>\n</table> \n' call_search_person = "<p>Please enter some keywords<table><tr><form action='/do_search_person'></tr>\n<tr><td>Student ID</td><td><input name='person_id' type='text'></input></td></tr>\n<tr><td>First Name</td><td><input name='firstname' type='text' </input></td></tr>\n<tr><td>Surname</td><td><input name='surname' type='text'></input></td></tr>\n<tr><td>Class</td><td><input name='_class' type='text'></input></td></tr>\n<tr><td>Semester</td><td><input name='semester' type='text'></input></td></tr>\n<tr><td>Cellphone Number</td><td><input name='cellphone' type='text'></input></td></tr>\n<tr><td></td></tr>\n<tr><td><input lable='submit' type='submit'></td></td></form></table></p>\n" do_search_person = '<p>The result of the search was as follows:<br><br></p>\n <table border=1>\n <tr><td><b>Student ID</b></td><td><b>First Name</b></td><td><b>Surname</b></td><td><b>Class</b></td><td><b>Semester</b></td><td><b>Cellphone</b></td></tr>\n <? for student_set in res: ?>\n <tr><? for el in student_set: ?>\n <td WIDTH=27% HEIGHT=19><?= el ?></td>\n <? end ?></tr>\n <? end ?>\n<? end ?></table> \n' do_search_person_none = '<p>The result of the search was as follows:<br>\n <p>No students could be found</p>\n' call_add_book = "<p><table><tr><form action='/do_add_book'></tr>\n<tr><td>Author</td><td><input name='author' type='text'></input></td></tr>\n<tr><td>Title</td><td><input name='title' type='text'></input></td></tr>\n<tr><td>Amount</td><td><input name='amount' type='text'></input></td></tr>\n<tr><td>Tags</td><td><input name='tags' type='text'></input></td></tr>\n<tr><td></td></tr>\n<tr><td><input lable='submit' type='submit'></td></td></form></table></p><br>\nPlease seperate the tags by colons (',')" call_edit_book = "<p>Please specify which book should be edited<br><table><tr><form action='/do_edit_book'></tr>\n<tr><td>Book ID</td><td><input name='book_id' type='text'></input></td></tr>\n<tr><td></td></tr>\n<tr><td><input lable='submit' type='submit'></td></td></form></table></p>\n" do_edit_book = "<p><table><tr><form action='/do_edit_book_2'></tr>\n<tr><td>Book ID</td><td><?= book_id?><input name='book_id' type='hidden' value='<?= book_id ?>'></td></tr>\n<tr><td>Author</td><td><input name='author' type='text' value='<?= author ?>'></input></td></tr>\n<tr><td>Title</td><td><input name='title' type='text' value='<?= title?>'></input></td></tr>\n<tr><td>Amount</td><td><input name='amount' type='text' value='<?= amount ?>'></input></td></tr>\n<tr><td>Tags</td><td><input name='tags' type='text' value='<?= tags ?>'></input></td></tr>\n<tr><td></td></tr>\n<tr><td><input lable='submit' type='submit'></td></td></form></table></p><br>\nPlease seperate the tags by colons (',')<br>\nThe Book ID cannot be edited. Please delete the book and add it again if a new ID is nessicary." call_delete_book = "<p>Please specify which book should be <b>deleted</b><br><table><tr><form action='/do_delete_book'></tr>\n<tr><td>Book ID</td><td><input name='book_id' type='text'></input></td></tr>\n<tr><td></td></tr>\n<tr><td><input lable='submit' type='submit'></td></td></form></table></p>" call_show_books_none = '<p>In the Library System following books are registered:<br>\n <p>No books are in the database</p>\n' call_show_books = '<p>In the Library System following books are registered:<br><br></p>\n <table border=1>\n<tr><td><b>Book ID</b></td>\n<td><b>Author</b></td>\n<td><b>Title</b></td>\n<td><b>Amount</b></td>\n<td><b>Tags</b></td></tr>\n <? for student_set in res: ?>\n <tr><? for el in student_set: ?>\n <td WIDTH=24% HEIGHT=19><? if el: ?><?= el ?><? end ?><? if not el: ?><i>None</i><? end ?></td>\n <? end ?></tr>\n <? end ?>\n<? end ?></table> \n' call_search_book = "<p>Please enter some keywords<table><tr><form action='/do_search_book'></tr>\n<tr><td>Book ID</td><td><input name='book_id' type='text'></input></td></tr>\n<tr><td>Author</td><td><input name='author' type='text'></input></td></tr>\n<tr><td>Title</td><td><input name='title' type='text'></input></td></tr>\n<tr><td>Tags</td><td><input name='tags' type='text'></input></td></tr>\n<tr><td></td></tr>\n<tr><td><input lable='submit' type='submit'></td></td></form></table></p><br>\nPlease seperate the tags by colons (',')\n" do_search_book = '<p>The result of the search was as follows:<br><br></p>\n <table border=1>\n<tr><td><b>Book ID</b></td>\n<td><b>Author</b></td>\n<td><b>Title</b></td>\n<td><b>Amount</b></td>\n<td><b>Tags</b></td></tr>\n <? for row in res: ?>\n <tr><? for el in row: ?>\n <td WIDTH=27% HEIGHT=19><?= el ?></td>\n <? end ?></tr>\n <? end ?>\n<? end ?></table> \n' do_search_book_none = '<p>The result of the search was as follows:<br>\n <p>No books could be found</p>\n' call_lend_book = "Please specify which book will be lent to whom:<br><br>\n<table><form action='/do_lend_book'>\n<tr><td>Student ID</td><td><input name='person_id' type='text'></input></td></tr>\n<tr><td>Book ID</td><td><input name='book_id' type='text'></input></td></tr>\n<tr><td>Amount</td><td><input name='amount' type='text'></input></td></tr>\n<tr><td></td></tr>\n<tr><td><input lable='submit' type='submit'></td></td></form></table></p>\n" call_return_book = "Please specify who wants to return which book<br><br>\n<table><form action='/do_return_book'>\n<tr><td>Student ID</td><td><input name='person_id' type='text'></input></td></tr>\n<tr><td>Book ID</td><td><input name='book_id' type='text'></input></td></tr>\n<tr><td>Amount</td><td><input name='amount' type='text'></input></td></tr>\n<tr><td></td></tr>\n<tr><td><input lable='submit' type='submit'></td></td></form></table></p>\n" call_show_lent_books = '<p>The result of the search was as follows:<br><br></p>\n <table border=1>\n <tr><td><b>Lend ID</b></td> \n <td><b>Student ID</b></td>\n <td><b>First name</b></td>\n <td><b>Surname</b></td>\n <td><b>Book ID</b></td>\n <td><b>Author</b></td>\n <td><b>Title</b></td>\n <td><b>Amount</b></td>\n <td><b>Return Date</b></td></tr>\n <? for student_set in res: ?>\n <tr><? for el in student_set: ?>\n <td WIDTH=16% HEIGHT=19><?= el ?></td>\n <? end ?></tr>\n <? end ?>\n<? end ?></table> \n' call_show_lent_books_none = '<p>The result of the search was as follows:<br>\n <p>No lent books could be found</p>\n' call_lent_books_to = "<p>Please specify for which student you want to have the list of the books to return<br><table><tr><form action='/do_lent_books_to'></tr>\n<tr><td>Student ID</td><td><input name='person_id' type='text'></input></td></tr>\n<tr><td></td></tr>\n<tr><td><input lable='submit' type='submit'></td></td></form></table></p>\n" call_show_lent_books_to = "<p>The result for student '<?= person_id ?>' was as follows:<br><br></p>\n <table border=1>\n<tr><td><b>Lend ID</b></td>\n<td><b>Book ID</b></td>\n<td><b>Author</b></td>\n<td><b>Title</b></td>\n<td><b>Amount</b></td>\n<td><b>Return Date</b></td></tr>\n <? for student_set in res: ?>\n <tr><? for el in student_set: ?>\n <td WIDTH=16% HEIGHT=19><?= el ?></td>\n <? end ?></tr>\n <? end ?>\n<? end ?></table> \n" call_show_lent_books_to_when_deleting = "<p>The student '<?= person_id ?>' could not be deleted because s/he still possesses books of the library:<br><br></p>\n <table border=1>\n<tr><td><b>Lend ID</b></td><td><b>Book ID</b></td><td><b>Author</b></td><td><b>Title</b></td><td><b>Amount</b></td><td><b>Return Date</b></td></tr>\n <? for student_set in res: ?>\n <tr><? for el in student_set: ?>\n <td WIDTH=16% HEIGHT=19><?= el ?></td>\n <? end ?></tr>\n <? end ?>\n<? end ?></table> \n" call_show_lent_books_to_none = '<p>The result of the search was as follows:<br>\n <p>No lent books could be found</p>\n' call_lent_books_none = '<p>The result of the search was as follows:<br>\n <p>No lent books could be found</p>\n' call_show_books_over_limit = '\n"<p>The result of the search was as follows:<br><br></p>\n <table border=1>\n <tr><td><b>Lend ID</b></td> \n <td><b>Student ID</b></td>\n <td><b>First name</b></td>\n <td><b>Surname</b></td>\n <td><b>Book ID</b></td>\n <td><b>Author</b></td>\n <td><b>Title</b></td></tr>\n <? for student_set in res: ?>\n <tr><? for el in student_set: ?>\n <td WIDTH=16% HEIGHT=19><?= el ?></td>\n <? end ?></tr>\n <? end ?>\n<? end ?></table> \n' call_show_books_over_limit_none = '<p>The result of the search was as follows:<br>\n <p>No lent books over limit could be found</p>\n' call_backup = '<p>Welcome to the backup function</p><br>\n<table>\n <tr>\n <td>\n For creating a backup, please press:\n </td>\n <td>\n <a href=\'/create_backup\'>HERE</a></td>\n </tr>\n <tr>\n <td>\n For inserting an old backup:\n </td>\n <td>\n <form action=\'/upload_backup\' method="post" enctype="multipart/form-data"><input type="file" name="myFile" /><br />\n <input type="submit" value="INSERT BACKUP" />\n </td>\n </tr>\n</table>\n'
# Colors (Fixed Color Graph Indices) # Returns (red, green, blue, opacity) colors = [ "EEEEEE", # White (1, n) "FF0000", # Red (i, s) "00FF00", # Green (j, t) "0000FF", # Blue (k, u) "DDDDDD", # Gray (L, N) "00FFFF", # Cyan (I, S) "FF00FF", # Magenta (J, T) "FFFF00", # Yellow (K, U) "CCCCCC", # Gray (m, o) "FF8000", # Orange (p, v) "FF0080", # Pink (q, w) "80FF00", # Lime (r, x) "BBBBBB", # Gray (M, O) "FF8000", # Teal (P, V) "8000FF", # Purple (Q, W) "0080FF", # Blue (R, X) ] * 2 def color(order, id): negative = True if id >= 2**order else False id -= 2**order if negative else 0 color = colors[id] out = [0, 0, 0, 1] for i in range(3): hex = color[i * 2 : i * 2 + 2] out[i] = int(hex, 16) / 0xFF if negative: out[i] *= 0.50 # Color 50% Darker If Negative return tuple(out) # Location (Fixed Location Graph Indices) # Returns [Horizontal, Vertical] # Left / Top := [-, -] # Left / Bottom := [-, +] # Right / Bottom := [+, +] # Right / Top := [+, -] # Center := [0, 0] locations = [ [1, 0], [0, -1], # 1, i, Complex [2, 2], [2, -2], # j, k, Quaternion [-1.5, -4], [-4, -1.5], [-4, 1.5], [-1.5, 4], # L, I, J, K Octonion [-2, -6], [-5, -6], [-6, -5], [-6, -2], # m, p, q, r Sedenion [-6, 2], [-6, 5], [-5, 6], [-2, 6], # M, P, Q, R Sedenion [-6, -9], [-8, -9], [-9, -8], [-9, -6], # n, s, t, u Pathion [-9, 6], [-9, 8], [-8, 9], [-6, +9], # N, S, T, U Pathion [-9, 4], [-11, 3], [-11, -3], [-9, -4], # o, v, w, x Pathion [4, 9], [3, 11], [-3, 11], [-4, 9], # O, V, W, X Pathion ] def location(order, id): negative = True if id >= 2**order else False id -= 2**order if negative else 0 location = locations[id] for i in range(2): if negative: location[i] *= -1 # Reversed Location If Negative return location
colors = ['EEEEEE', 'FF0000', '00FF00', '0000FF', 'DDDDDD', '00FFFF', 'FF00FF', 'FFFF00', 'CCCCCC', 'FF8000', 'FF0080', '80FF00', 'BBBBBB', 'FF8000', '8000FF', '0080FF'] * 2 def color(order, id): negative = True if id >= 2 ** order else False id -= 2 ** order if negative else 0 color = colors[id] out = [0, 0, 0, 1] for i in range(3): hex = color[i * 2:i * 2 + 2] out[i] = int(hex, 16) / 255 if negative: out[i] *= 0.5 return tuple(out) locations = [[1, 0], [0, -1], [2, 2], [2, -2], [-1.5, -4], [-4, -1.5], [-4, 1.5], [-1.5, 4], [-2, -6], [-5, -6], [-6, -5], [-6, -2], [-6, 2], [-6, 5], [-5, 6], [-2, 6], [-6, -9], [-8, -9], [-9, -8], [-9, -6], [-9, 6], [-9, 8], [-8, 9], [-6, +9], [-9, 4], [-11, 3], [-11, -3], [-9, -4], [4, 9], [3, 11], [-3, 11], [-4, 9]] def location(order, id): negative = True if id >= 2 ** order else False id -= 2 ** order if negative else 0 location = locations[id] for i in range(2): if negative: location[i] *= -1 return location
def set_default(default_dict, result_dict): """Sets default values for a dictionary recursively. :param default_dict: The template dictionary to use to set values :param result_dict: The dictionary to load the template values into :rtype: dict """ # Iterate through default values for tag in default_dict: # If the tag does not exist in the result dictionary, add it if tag not in result_dict: result_dict[tag] = default_dict[tag] # Tag exists in guild dict, see if tag is a dictionary else: if type(result_dict[tag]) == dict: result_dict[tag] = set_default(default_dict[tag], result_dict[tag]) return result_dict
def set_default(default_dict, result_dict): """Sets default values for a dictionary recursively. :param default_dict: The template dictionary to use to set values :param result_dict: The dictionary to load the template values into :rtype: dict """ for tag in default_dict: if tag not in result_dict: result_dict[tag] = default_dict[tag] elif type(result_dict[tag]) == dict: result_dict[tag] = set_default(default_dict[tag], result_dict[tag]) return result_dict
# HEAD # DataType - Strings with Sequence/Tuples behaviour # DESCRIPTION # Describes how strings behave as a list or a sequence # Strings can be referenced per character using indexes like lists # String indexing also starts from 0/Zero # Strings can be looped like lists # RESOURCES # name = 'Zophie' print(name[0]) # 'Z' print(name[-2]) # 'i' print(name[0:4]) # 'Zoph' print('Zo' in name) # True print('z' in name) # False print('p' not in name) # False for i in name: print('* * * ' + i + ' * * *')
name = 'Zophie' print(name[0]) print(name[-2]) print(name[0:4]) print('Zo' in name) print('z' in name) print('p' not in name) for i in name: print('* * * ' + i + ' * * *')
APPLICATION_NAME = "Actuator Updater" APP_AUTHOR_DIR = "FarSite" APP_NAME_DIR = "ActuatorUpdater" # MENU_DISCONNECTED = "Connect to site..." MENU_DISCONNECTED = "Connect/disconnect" MENU_CONNECTED = "Disconnect from site"
application_name = 'Actuator Updater' app_author_dir = 'FarSite' app_name_dir = 'ActuatorUpdater' menu_disconnected = 'Connect/disconnect' menu_connected = 'Disconnect from site'
''' This is a first name / last name dictionary & retrieval system Try this: 1. Add your name 2. Use the difflib tricks in Challenge0 to match SIMILAR names (instead of exact names) ''' database = { 'Luke':'Skywalker', 'Leia':'Skywalker', 'Han':'Solo', 'Chewie':'Chewbacca', 'Finn':'FN-2187', } # in case you forgot to type the keys (prompts) as all lower case for key in dict(database): if key != key.lower(): # if some upper case characters # Add an extra entry with all lower case characters in prompt database[key.lower()] = database[key] def sorry(): print('Sorry, no records found matching that name!') while True: typ = input('Search By First Name or Last Name? (type "first" or "last") >> ') if typ.lower() == 'first': name = input('First Name? >> ') name = name.lower() if name in database.keys(): print('Last Name Is', database[name]) else: sorry() elif typ.lower() == 'last': name = input('Last Name? >> ') name = name.lower() if name in database.values(): for first, last in database.items(): if last == name: print('First Name Is', first) break # quit this for loop else: sorry()
""" This is a first name / last name dictionary & retrieval system Try this: 1. Add your name 2. Use the difflib tricks in Challenge0 to match SIMILAR names (instead of exact names) """ database = {'Luke': 'Skywalker', 'Leia': 'Skywalker', 'Han': 'Solo', 'Chewie': 'Chewbacca', 'Finn': 'FN-2187'} for key in dict(database): if key != key.lower(): database[key.lower()] = database[key] def sorry(): print('Sorry, no records found matching that name!') while True: typ = input('Search By First Name or Last Name? (type "first" or "last") >> ') if typ.lower() == 'first': name = input('First Name? >> ') name = name.lower() if name in database.keys(): print('Last Name Is', database[name]) else: sorry() elif typ.lower() == 'last': name = input('Last Name? >> ') name = name.lower() if name in database.values(): for (first, last) in database.items(): if last == name: print('First Name Is', first) break else: sorry()
pkgname = "icu" pkgver = "70.1" pkgrel = 0 build_wrksrc = "source" build_style = "gnu_configure" configure_args = [ "--with-data-packaging=archive", "--enable-static", ] make_cmd = "gmake" hostmakedepends = ["gmake", "pkgconf"] checkdepends = ["python"] pkgdesc = "Robust and fully-featured Unicode libraries" maintainer = "q66 <q66@chimera-linux.org>" license = "ICU" url = "https://home.unicode.org" source = f"https://github.com/unicode-org/{pkgname}/releases/download/release-{pkgver.replace('.', '-')}/icu4c-{pkgver.replace('.', '_')}-src.tgz" sha256 = "8d205428c17bf13bb535300669ed28b338a157b1c01ae66d31d0d3e2d47c3fd5" tool_flags = {"CFLAGS": ["-fPIC"], "CXXFLAGS": ["-fPIC"]} def init_configure(self): if not self.profile().cross: return # we build special host icu for cross self.configure_args.append( "--with-cross-build=" + str(self.chroot_cwd / "icu-host") ) def pre_configure(self): if not self.profile().cross: return # host build; first clean up potential old stuff self.rm("build-host", recursive = True, force = True) self.rm("icu-host", recursive = True, force = True) self.mkdir("build-host") # override most build-related environment self.do( self.chroot_cwd / "configure", "--prefix=/", "--sbindir=/bin", wrksrc = "build-host", env = { "CC": "cc", "LD": "ld", "CXX": "c++", "AR": "ar", "AS": "cc", "RANLIB": "ranlib", "STRIP": "strip", "CFLAGS": "-Os", "CXXFLAGS": "-Os", "LDFLAGS": "", } ) self.make.build(wrksrc = "build-host") self.mkdir("icu-host/config", parents = True) # copy over icucross for f in (self.cwd / "build-host/config").glob("icucross.*"): self.cp(f, "icu-host/config") # finally install host icu into special prefix self.make.install( ["DESTDIR=" + str(self.chroot_cwd / "icu-host")], wrksrc = "build-host", default_args = False ) def post_install(self): # FIXME: check if cross-endian icudt is still busted later self.install_license(self.builddir / self.wrksrc / "LICENSE") @subpackage("icu-libs") def _libs(self): return self.default_libs(extra = [ f"usr/share/icu/{pkgver}/icudt*.dat" ]) @subpackage("icu-devel") def _devel(self): return self.default_devel(extra = ["usr/share/icu", "usr/lib/icu"])
pkgname = 'icu' pkgver = '70.1' pkgrel = 0 build_wrksrc = 'source' build_style = 'gnu_configure' configure_args = ['--with-data-packaging=archive', '--enable-static'] make_cmd = 'gmake' hostmakedepends = ['gmake', 'pkgconf'] checkdepends = ['python'] pkgdesc = 'Robust and fully-featured Unicode libraries' maintainer = 'q66 <q66@chimera-linux.org>' license = 'ICU' url = 'https://home.unicode.org' source = f"https://github.com/unicode-org/{pkgname}/releases/download/release-{pkgver.replace('.', '-')}/icu4c-{pkgver.replace('.', '_')}-src.tgz" sha256 = '8d205428c17bf13bb535300669ed28b338a157b1c01ae66d31d0d3e2d47c3fd5' tool_flags = {'CFLAGS': ['-fPIC'], 'CXXFLAGS': ['-fPIC']} def init_configure(self): if not self.profile().cross: return self.configure_args.append('--with-cross-build=' + str(self.chroot_cwd / 'icu-host')) def pre_configure(self): if not self.profile().cross: return self.rm('build-host', recursive=True, force=True) self.rm('icu-host', recursive=True, force=True) self.mkdir('build-host') self.do(self.chroot_cwd / 'configure', '--prefix=/', '--sbindir=/bin', wrksrc='build-host', env={'CC': 'cc', 'LD': 'ld', 'CXX': 'c++', 'AR': 'ar', 'AS': 'cc', 'RANLIB': 'ranlib', 'STRIP': 'strip', 'CFLAGS': '-Os', 'CXXFLAGS': '-Os', 'LDFLAGS': ''}) self.make.build(wrksrc='build-host') self.mkdir('icu-host/config', parents=True) for f in (self.cwd / 'build-host/config').glob('icucross.*'): self.cp(f, 'icu-host/config') self.make.install(['DESTDIR=' + str(self.chroot_cwd / 'icu-host')], wrksrc='build-host', default_args=False) def post_install(self): self.install_license(self.builddir / self.wrksrc / 'LICENSE') @subpackage('icu-libs') def _libs(self): return self.default_libs(extra=[f'usr/share/icu/{pkgver}/icudt*.dat']) @subpackage('icu-devel') def _devel(self): return self.default_devel(extra=['usr/share/icu', 'usr/lib/icu'])
def intersection(start_i, end_i, start_j, end_j): i0 = max(start_i, start_j) i1 = min(end_i, end_j) if i0 >= i1: return 0 else: return i1 - i0 def percentage_intervention(doc, shot_start, shot_end): interventions = doc.getElementsByTagName("Intervention") case_size = shot_end - shot_start percentage = {'long': 0, 'short': 0} for intervention in interventions: intervention_start = float(intervention.getAttribute('start')) intervention_end = float(intervention.getAttribute('end')) intervention_type = intervention.getAttribute('type') intersect = intersection(shot_start, shot_end, intervention_start, intervention_end) percentage[intervention_type] = percentage[intervention_type] + intersect # print "intervention_start: " + str(intervention_start) # print "intervention_end: " + str(intervention_end) # print "shot_start: " + str(shot_start) # print "shot_end: " + str(shot_end) # print "shot_end: " + str(percentage[intervention_type]) percentage['long'] = round(percentage['long'] * 100 / case_size, 2) percentage['short'] = round(percentage['short'] * 100 / case_size, 2) return percentage
def intersection(start_i, end_i, start_j, end_j): i0 = max(start_i, start_j) i1 = min(end_i, end_j) if i0 >= i1: return 0 else: return i1 - i0 def percentage_intervention(doc, shot_start, shot_end): interventions = doc.getElementsByTagName('Intervention') case_size = shot_end - shot_start percentage = {'long': 0, 'short': 0} for intervention in interventions: intervention_start = float(intervention.getAttribute('start')) intervention_end = float(intervention.getAttribute('end')) intervention_type = intervention.getAttribute('type') intersect = intersection(shot_start, shot_end, intervention_start, intervention_end) percentage[intervention_type] = percentage[intervention_type] + intersect percentage['long'] = round(percentage['long'] * 100 / case_size, 2) percentage['short'] = round(percentage['short'] * 100 / case_size, 2) return percentage
# -*- Python -*- # Copyright 2017-2021 The Verible Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Bazel rule to run bison toolchain """ # Adapter rule around the @rules_bison toolchain. def genyacc( name, src, header_out, source_out, extra_options = [], extra_outs = []): """Build rule for generating C or C++ sources with Bison. """ native.genrule( name = name, srcs = [src], outs = [header_out, source_out] + extra_outs, cmd = select({ "@platforms//os:windows": "$(BISON) --defines=$(location " + header_out + ") --output-file=$(location " + source_out + ") " + " ".join(extra_options) + " $<", "//conditions:default": "M4=$(M4) $(BISON) --defines=$(location " + header_out + ") --output-file=$(location " + source_out + ") " + " ".join(extra_options) + " $<", }), toolchains = select({ "@platforms//os:windows": ["@rules_bison//bison:current_bison_toolchain"], "//conditions:default": [ "@rules_bison//bison:current_bison_toolchain", "@rules_m4//m4:current_m4_toolchain", ], }), )
"""Bazel rule to run bison toolchain """ def genyacc(name, src, header_out, source_out, extra_options=[], extra_outs=[]): """Build rule for generating C or C++ sources with Bison. """ native.genrule(name=name, srcs=[src], outs=[header_out, source_out] + extra_outs, cmd=select({'@platforms//os:windows': '$(BISON) --defines=$(location ' + header_out + ') --output-file=$(location ' + source_out + ') ' + ' '.join(extra_options) + ' $<', '//conditions:default': 'M4=$(M4) $(BISON) --defines=$(location ' + header_out + ') --output-file=$(location ' + source_out + ') ' + ' '.join(extra_options) + ' $<'}), toolchains=select({'@platforms//os:windows': ['@rules_bison//bison:current_bison_toolchain'], '//conditions:default': ['@rules_bison//bison:current_bison_toolchain', '@rules_m4//m4:current_m4_toolchain']}))
def factorial(x): """This is a recursive function to find the factorial of an integer""" if x == 1: return 1 else: return (x * factorial(x-1)) num = 3 print("The factorial of", num, "is", factorial(num))
def factorial(x): """This is a recursive function to find the factorial of an integer""" if x == 1: return 1 else: return x * factorial(x - 1) num = 3 print('The factorial of', num, 'is', factorial(num))
# -------------- #Code starts here #Function to check for palindrome def palindrome_check(num): num=str(num) return (num[::-1]==num) #Function to find the smallest palindrome def palindrome(num): while(1): num=num+1 if palindrome_check(num): return num #Code ends here # -------------- #Code starts here #Function to find anagram of one word in another def a_scramble(str_1,str_2): result=True for i in (str_2.lower()): if i not in (str_1.lower()): result=False break str_1=str_1.replace(i,'',1) #Removing the letters from str_1 that are already checked return (result) #Code ends here # -------------- #Code starts here def check_fib(num): a,b = 0,1 L = [0,1] c = a + b for i in range(2,num+1): L.append(c) a = b b = c c = a + b if num in L: return True else: return False # -------------- #Code starts here def compress(word): count,index,i = 0,1,0 word = word.lower() new_word = "" while (i < len(word)): w = word[i] for j in range(i,len(word)): if w == word[j]: count += 1 else: break new_word = new_word+w+str(count) i = i+count count=0 print(new_word) return new_word # -------------- #Code starts here def k_distinct(string,k): string = string.lower() L = [] for i in range(len(string)): if string[i] not in L: L.append(string[i]) else: continue if len(L) >=k: return True else: return False
def palindrome_check(num): num = str(num) return num[::-1] == num def palindrome(num): while 1: num = num + 1 if palindrome_check(num): return num def a_scramble(str_1, str_2): result = True for i in str_2.lower(): if i not in str_1.lower(): result = False break str_1 = str_1.replace(i, '', 1) return result def check_fib(num): (a, b) = (0, 1) l = [0, 1] c = a + b for i in range(2, num + 1): L.append(c) a = b b = c c = a + b if num in L: return True else: return False def compress(word): (count, index, i) = (0, 1, 0) word = word.lower() new_word = '' while i < len(word): w = word[i] for j in range(i, len(word)): if w == word[j]: count += 1 else: break new_word = new_word + w + str(count) i = i + count count = 0 print(new_word) return new_word def k_distinct(string, k): string = string.lower() l = [] for i in range(len(string)): if string[i] not in L: L.append(string[i]) else: continue if len(L) >= k: return True else: return False
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Tue Oct 9 14:35:41 2018 @author: misskeisha """ passw = input() if (any(x.isupper() for x in passw) and any(x.islower() for x in passw) and (passw.isalnum() == False) and len(passw) >= 8) and any(x.isdigit() for x in passw): print('good password') else: print('poor password')
""" Created on Tue Oct 9 14:35:41 2018 @author: misskeisha """ passw = input() if (any((x.isupper() for x in passw)) and any((x.islower() for x in passw)) and (passw.isalnum() == False) and (len(passw) >= 8)) and any((x.isdigit() for x in passw)): print('good password') else: print('poor password')
class ChainingTimeStampF1D: def __init__(self): pass def __call__(self, inter): pass class Curvature2DAngleF0D: def __init__(self): pass def __call__(self, it): pass class Curvature2DAngleF1D: def __init__(self, integration_type=IntegrationType.MEAN): pass def __call__(self, inter): pass class CurveMaterialF0D: pass class CurveNatureF0D: def __init__(self): pass def __call__(self, it): pass class CurveNatureF1D: def __init__(self, integration_type=IntegrationType.MEAN): pass def __call__(self, inter): pass class DensityF0D: def __init__(self, sigma=2.0): pass def __call__(self, it): pass class DensityF1D: def __init__(self, sigma=2.0, integration_type=IntegrationType.MEAN, sampling=2.0): pass def __call__(self, inter): pass class GetCompleteViewMapDensityF1D: def __init__(self, level, integration_type=IntegrationType.MEAN, sampling=2.0): pass def __call__(self, inter): pass class GetCurvilinearAbscissaF0D: def __init__(self): pass def __call__(self, it): pass class GetDirectionalViewMapDensityF1D: def __init__(self, orientation, level, integration_type=IntegrationType.MEAN, sampling=2.0): pass def __call__(self, inter): pass class GetOccludeeF0D: def __init__(self): pass def __call__(self, it): pass class GetOccludeeF1D: def __init__(self): pass def __call__(self, inter): pass class GetOccludersF0D: def __init__(self): pass def __call__(self, it): pass class GetOccludersF1D: def __init__(self): pass def __call__(self, inter): pass class GetParameterF0D: def __init__(self): pass def __call__(self, it): pass class GetProjectedXF0D: def __init__(self): pass def __call__(self, it): pass class GetProjectedXF1D: def __init__(self, integration_type=IntegrationType.MEAN): pass def __call__(self, inter): pass class GetProjectedYF0D: def __init__(self): pass def __call__(self, it): pass class GetProjectedYF1D: def __init__(self, integration_type=IntegrationType.MEAN): pass def __call__(self, inter): pass class GetProjectedZF0D: def __init__(self): pass def __call__(self, it): pass class GetProjectedZF1D: def __init__(self, integration_type=IntegrationType.MEAN): pass def __call__(self, inter): pass class GetShapeF0D: def __init__(self): pass def __call__(self, it): pass class GetShapeF1D: def __init__(self): pass def __call__(self, inter): pass class GetSteerableViewMapDensityF1D: def __init__(self, level, integration_type=IntegrationType.MEAN, sampling=2.0): pass def __call__(self, inter): pass class GetViewMapGradientNormF0D: def __init__(self, level): pass def __call__(self, it): pass class GetViewMapGradientNormF1D: def __init__(self, level, integration_type=IntegrationType.MEAN, sampling=2.0): pass def __call__(self, inter): pass class GetXF0D: def __init__(self): pass def __call__(self, it): pass class GetXF1D: def __init__(self, integration_type=IntegrationType.MEAN): pass def __call__(self, inter): pass class GetYF0D: def __init__(self): pass def __call__(self, it): pass class GetYF1D: def __init__(self, integration_type=IntegrationType.MEAN): pass def __call__(self, inter): pass class GetZF0D: def __init__(self): pass def __call__(self, it): pass class GetZF1D: def __init__(self, integration_type=IntegrationType.MEAN): pass def __call__(self, inter): pass class IncrementChainingTimeStampF1D: def __init__(self): pass def __call__(self, inter): pass class LocalAverageDepthF0D: def __init__(self, mask_size=5.0): pass def __call__(self, it): pass class LocalAverageDepthF1D: def __init__(self, sigma, integration_type=IntegrationType.MEAN): pass def __call__(self, inter): pass class MaterialF0D: def __init__(self): pass def __call__(self, it): pass class Normal2DF0D: def __init__(self): pass def __call__(self, it): pass class Normal2DF1D: def __init__(self, integration_type=IntegrationType.MEAN): pass def __call__(self, inter): pass class Orientation2DF1D: def __init__(self, integration_type=IntegrationType.MEAN): pass def __call__(self, inter): pass class Orientation3DF1D: def __init__(self, integration_type=IntegrationType.MEAN): pass def __call__(self, inter): pass class QuantitativeInvisibilityF0D: def __init__(self): pass def __call__(self, it): pass class QuantitativeInvisibilityF1D: def __init__(self, integration_type=IntegrationType.MEAN): pass def __call__(self, inter): pass class ReadCompleteViewMapPixelF0D: def __init__(self, level): pass def __call__(self, it): pass class ReadMapPixelF0D: def __init__(self, map_name, level): pass def __call__(self, it): pass class ReadSteerableViewMapPixelF0D: def __init__(self, orientation, level): pass def __call__(self, it): pass class ShapeIdF0D: def __init__(self): pass def __call__(self, it): pass class TimeStampF1D: def __init__(self): pass def __call__(self, inter): pass class VertexOrientation2DF0D: def __init__(self): pass def __call__(self, it): pass class VertexOrientation3DF0D: def __init__(self): pass def __call__(self, it): pass class ZDiscontinuityF0D: def __init__(self): pass def __call__(self, it): pass class ZDiscontinuityF1D: def __init__(self, integration_type=IntegrationType.MEAN): pass def __call__(self, inter): pass class pyCurvilinearLengthF0D: pass class pyDensityAnisotropyF0D: pass class pyDensityAnisotropyF1D: pass class pyGetInverseProjectedZF1D: pass class pyGetSquareInverseProjectedZF1D: pass class pyInverseCurvature2DAngleF0D: pass class pyViewMapGradientNormF0D: pass class pyViewMapGradientNormF1D: pass class pyViewMapGradientVectorF0D: def __init__(self, level): pass
class Chainingtimestampf1D: def __init__(self): pass def __call__(self, inter): pass class Curvature2Danglef0D: def __init__(self): pass def __call__(self, it): pass class Curvature2Danglef1D: def __init__(self, integration_type=IntegrationType.MEAN): pass def __call__(self, inter): pass class Curvematerialf0D: pass class Curvenaturef0D: def __init__(self): pass def __call__(self, it): pass class Curvenaturef1D: def __init__(self, integration_type=IntegrationType.MEAN): pass def __call__(self, inter): pass class Densityf0D: def __init__(self, sigma=2.0): pass def __call__(self, it): pass class Densityf1D: def __init__(self, sigma=2.0, integration_type=IntegrationType.MEAN, sampling=2.0): pass def __call__(self, inter): pass class Getcompleteviewmapdensityf1D: def __init__(self, level, integration_type=IntegrationType.MEAN, sampling=2.0): pass def __call__(self, inter): pass class Getcurvilinearabscissaf0D: def __init__(self): pass def __call__(self, it): pass class Getdirectionalviewmapdensityf1D: def __init__(self, orientation, level, integration_type=IntegrationType.MEAN, sampling=2.0): pass def __call__(self, inter): pass class Getoccludeef0D: def __init__(self): pass def __call__(self, it): pass class Getoccludeef1D: def __init__(self): pass def __call__(self, inter): pass class Getoccludersf0D: def __init__(self): pass def __call__(self, it): pass class Getoccludersf1D: def __init__(self): pass def __call__(self, inter): pass class Getparameterf0D: def __init__(self): pass def __call__(self, it): pass class Getprojectedxf0D: def __init__(self): pass def __call__(self, it): pass class Getprojectedxf1D: def __init__(self, integration_type=IntegrationType.MEAN): pass def __call__(self, inter): pass class Getprojectedyf0D: def __init__(self): pass def __call__(self, it): pass class Getprojectedyf1D: def __init__(self, integration_type=IntegrationType.MEAN): pass def __call__(self, inter): pass class Getprojectedzf0D: def __init__(self): pass def __call__(self, it): pass class Getprojectedzf1D: def __init__(self, integration_type=IntegrationType.MEAN): pass def __call__(self, inter): pass class Getshapef0D: def __init__(self): pass def __call__(self, it): pass class Getshapef1D: def __init__(self): pass def __call__(self, inter): pass class Getsteerableviewmapdensityf1D: def __init__(self, level, integration_type=IntegrationType.MEAN, sampling=2.0): pass def __call__(self, inter): pass class Getviewmapgradientnormf0D: def __init__(self, level): pass def __call__(self, it): pass class Getviewmapgradientnormf1D: def __init__(self, level, integration_type=IntegrationType.MEAN, sampling=2.0): pass def __call__(self, inter): pass class Getxf0D: def __init__(self): pass def __call__(self, it): pass class Getxf1D: def __init__(self, integration_type=IntegrationType.MEAN): pass def __call__(self, inter): pass class Getyf0D: def __init__(self): pass def __call__(self, it): pass class Getyf1D: def __init__(self, integration_type=IntegrationType.MEAN): pass def __call__(self, inter): pass class Getzf0D: def __init__(self): pass def __call__(self, it): pass class Getzf1D: def __init__(self, integration_type=IntegrationType.MEAN): pass def __call__(self, inter): pass class Incrementchainingtimestampf1D: def __init__(self): pass def __call__(self, inter): pass class Localaveragedepthf0D: def __init__(self, mask_size=5.0): pass def __call__(self, it): pass class Localaveragedepthf1D: def __init__(self, sigma, integration_type=IntegrationType.MEAN): pass def __call__(self, inter): pass class Materialf0D: def __init__(self): pass def __call__(self, it): pass class Normal2Df0D: def __init__(self): pass def __call__(self, it): pass class Normal2Df1D: def __init__(self, integration_type=IntegrationType.MEAN): pass def __call__(self, inter): pass class Orientation2Df1D: def __init__(self, integration_type=IntegrationType.MEAN): pass def __call__(self, inter): pass class Orientation3Df1D: def __init__(self, integration_type=IntegrationType.MEAN): pass def __call__(self, inter): pass class Quantitativeinvisibilityf0D: def __init__(self): pass def __call__(self, it): pass class Quantitativeinvisibilityf1D: def __init__(self, integration_type=IntegrationType.MEAN): pass def __call__(self, inter): pass class Readcompleteviewmappixelf0D: def __init__(self, level): pass def __call__(self, it): pass class Readmappixelf0D: def __init__(self, map_name, level): pass def __call__(self, it): pass class Readsteerableviewmappixelf0D: def __init__(self, orientation, level): pass def __call__(self, it): pass class Shapeidf0D: def __init__(self): pass def __call__(self, it): pass class Timestampf1D: def __init__(self): pass def __call__(self, inter): pass class Vertexorientation2Df0D: def __init__(self): pass def __call__(self, it): pass class Vertexorientation3Df0D: def __init__(self): pass def __call__(self, it): pass class Zdiscontinuityf0D: def __init__(self): pass def __call__(self, it): pass class Zdiscontinuityf1D: def __init__(self, integration_type=IntegrationType.MEAN): pass def __call__(self, inter): pass class Pycurvilinearlengthf0D: pass class Pydensityanisotropyf0D: pass class Pydensityanisotropyf1D: pass class Pygetinverseprojectedzf1D: pass class Pygetsquareinverseprojectedzf1D: pass class Pyinversecurvature2Danglef0D: pass class Pyviewmapgradientnormf0D: pass class Pyviewmapgradientnormf1D: pass class Pyviewmapgradientvectorf0D: def __init__(self, level): pass
def bubblesort(A): for i in range(len(A)): for k in range(len(A) - 1, i, -1): if (A[k] < A[k - 1]): swap(A,k,k-1) def swap(A,x,y): temp = A[x] A[x] = A[y] A[y] = temp A= [534,689,235,124,525,216,134,356] bubblesort(A) print(A)
def bubblesort(A): for i in range(len(A)): for k in range(len(A) - 1, i, -1): if A[k] < A[k - 1]: swap(A, k, k - 1) def swap(A, x, y): temp = A[x] A[x] = A[y] A[y] = temp a = [534, 689, 235, 124, 525, 216, 134, 356] bubblesort(A) print(A)
BACKGROUND = "red" FONT_NAME = "Consolas" FONT_SIZE = 19 DEFAULT_FONT = (FONT_NAME, FONT_SIZE) HEADER_FONT = (FONT_NAME, int(FONT_SIZE*1.3))
background = 'red' font_name = 'Consolas' font_size = 19 default_font = (FONT_NAME, FONT_SIZE) header_font = (FONT_NAME, int(FONT_SIZE * 1.3))
'''Developed by Jakub21 in June 2018 License: MIT Python version: 3.6.5 ''' class Chunk: '''Chunk Class Contains methods inherited by ProvGroup and Province classes ''' def __init__(self, parent, name, type): '''Constructor''' self.parent, self.name, self.type = parent, name, type self.marked = False self.pixels = [] def __repr__(self): '''Generates repr string of the object''' i = ' '*4 text = 'Chunk "'+str(self.name)+'"\n' text += i + 'Type: '+str(self.type)+'\n' text += i + 'Is marked: '+str(self.marked)+'\n' text += i + 'Pixels count: '+str(len(self.pixels))+'\n' try: text += i+'Colors: '+str([self.color, self.g_clr, self.m_clr])+'\n' except AttributeError: text += i + 'Colors not set\n' return text def set_pixels(self, pixels): '''Sets pixels of the chunk''' self.pixels = pixels def set_color(self, color): '''Sets chunk colors. Pass identifier color as a parameter. Marked and Grayed colors are calculated by helper methods. ''' self.color = color self.g_clr = self._get_gray(color) self.m_clr = self._get_marked(color) def mark(self, modify_map=True, force=None): '''Marks or Unmarks the chunk. To skip map update set modify_map to False. To force state of marked attr. use force parameter. ''' color = { True: self.m_clr, False: self.g_clr, } if force in (True, False): self.marked = force else: self.marked = not self.marked if modify_map == True: self.parent.mark_chunk(self.pixels, color[self.marked]) elif modify_map == 'provs': self.parent.mark_src_map(self.pixels, color[self.marked]) # set_color helper methods def _get_gray(self, color): r, g, b = color r = (r+100)//4 g = (g+100)//4 b = (b+100)//4 return r, g, b def _get_marked(self, color): r, g, b = color r = (r+510)//3 g = (g+510)//3 b = (b+510)//3 return r, g, b
"""Developed by Jakub21 in June 2018 License: MIT Python version: 3.6.5 """ class Chunk: """Chunk Class Contains methods inherited by ProvGroup and Province classes """ def __init__(self, parent, name, type): """Constructor""" (self.parent, self.name, self.type) = (parent, name, type) self.marked = False self.pixels = [] def __repr__(self): """Generates repr string of the object""" i = ' ' * 4 text = 'Chunk "' + str(self.name) + '"\n' text += i + 'Type: ' + str(self.type) + '\n' text += i + 'Is marked: ' + str(self.marked) + '\n' text += i + 'Pixels count: ' + str(len(self.pixels)) + '\n' try: text += i + 'Colors: ' + str([self.color, self.g_clr, self.m_clr]) + '\n' except AttributeError: text += i + 'Colors not set\n' return text def set_pixels(self, pixels): """Sets pixels of the chunk""" self.pixels = pixels def set_color(self, color): """Sets chunk colors. Pass identifier color as a parameter. Marked and Grayed colors are calculated by helper methods. """ self.color = color self.g_clr = self._get_gray(color) self.m_clr = self._get_marked(color) def mark(self, modify_map=True, force=None): """Marks or Unmarks the chunk. To skip map update set modify_map to False. To force state of marked attr. use force parameter. """ color = {True: self.m_clr, False: self.g_clr} if force in (True, False): self.marked = force else: self.marked = not self.marked if modify_map == True: self.parent.mark_chunk(self.pixels, color[self.marked]) elif modify_map == 'provs': self.parent.mark_src_map(self.pixels, color[self.marked]) def _get_gray(self, color): (r, g, b) = color r = (r + 100) // 4 g = (g + 100) // 4 b = (b + 100) // 4 return (r, g, b) def _get_marked(self, color): (r, g, b) = color r = (r + 510) // 3 g = (g + 510) // 3 b = (b + 510) // 3 return (r, g, b)
# AUTOGENERATED BY NBDEV! DO NOT EDIT! __all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {"log_it": "00_tspecscores.ipynb", "tsi": "00_tspecscores.ipynb", "spm": "00_tspecscores.ipynb", "zscore": "00_tspecscores.ipynb", "tau": "00_tspecscores.ipynb", "ts_func": "00_tspecscores.ipynb", "calc_ts": "00_tspecscores.ipynb"} modules = ["tspecscores.py"] doc_url = "https://morriso1.github.io/tspecscores/" git_url = "https://github.com/morriso1/tspecscores/tree/main/" def custom_doc_links(name): return None
__all__ = ['index', 'modules', 'custom_doc_links', 'git_url'] index = {'log_it': '00_tspecscores.ipynb', 'tsi': '00_tspecscores.ipynb', 'spm': '00_tspecscores.ipynb', 'zscore': '00_tspecscores.ipynb', 'tau': '00_tspecscores.ipynb', 'ts_func': '00_tspecscores.ipynb', 'calc_ts': '00_tspecscores.ipynb'} modules = ['tspecscores.py'] doc_url = 'https://morriso1.github.io/tspecscores/' git_url = 'https://github.com/morriso1/tspecscores/tree/main/' def custom_doc_links(name): return None
class Sample(): """ A sample for a song, composed of slices (parts). """ def __init__(self, slices, song, size, index): self.slices = slices self.song = song self.size = size self.index = index class Slice(): """ A sample of the smallest size, used to construct longer samples. """ def __init__(self, file): self.file = file
class Sample: """ A sample for a song, composed of slices (parts). """ def __init__(self, slices, song, size, index): self.slices = slices self.song = song self.size = size self.index = index class Slice: """ A sample of the smallest size, used to construct longer samples. """ def __init__(self, file): self.file = file
n = int(input()) s = set(map(int, input().split())) for x in range(int(input())): method, *args = input().split() getattr(s, method)(*map(int, args)) print(sum(s))
n = int(input()) s = set(map(int, input().split())) for x in range(int(input())): (method, *args) = input().split() getattr(s, method)(*map(int, args)) print(sum(s))
# Copyright (c) 2011 Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. { 'includes': [ 'mini_chromium/build/common.gypi', ], 'targets': [ { 'target_name': 'csfde', 'type': 'executable', 'include_dirs': [ 'mini_chromium', ], 'sources': [ 'csfde.mm', 'mini_chromium/base/basictypes.h', 'mini_chromium/base/compiler_specific.h', 'mini_chromium/base/logging.h', 'mini_chromium/base/logging.cc', 'mini_chromium/base/mac/scoped_cftyperef.h', 'mini_chromium/base/mac/scoped_nsautorelease_pool.h', 'mini_chromium/base/mac/scoped_nsautorelease_pool.mm', 'mini_chromium/base/memory/scoped_nsobject.h', 'mini_chromium/base/safe_strerror_posix.h', 'mini_chromium/base/safe_strerror_posix.cc', 'mini_chromium/build/build_config.h', 'mini_chromium/chrome/browser/mac/scoped_ioobject.h', ], 'libraries': [ '$(SDKROOT)/System/Library/Frameworks/CoreFoundation.framework', '$(SDKROOT)/System/Library/Frameworks/DiskArbitration.framework', '$(SDKROOT)/System/Library/Frameworks/Foundation.framework', '$(SDKROOT)/System/Library/Frameworks/IOKit.framework', '$(SDKROOT)/System/Library/Frameworks/OpenDirectory.framework', '$(SDKROOT)/System/Library/PrivateFrameworks/DiskManagement.framework', '$(SDKROOT)/System/Library/PrivateFrameworks/EFILogin.framework', '$(SDKROOT)/usr/lib/libcsfde.dylib', ], 'xcode_settings': { 'ARCHS': [ 'x86_64', 'i386', ], 'FRAMEWORK_SEARCH_PATHS': [ '$(SDKROOT)/System/Library/PrivateFrameworks', ], }, }, ], }
{'includes': ['mini_chromium/build/common.gypi'], 'targets': [{'target_name': 'csfde', 'type': 'executable', 'include_dirs': ['mini_chromium'], 'sources': ['csfde.mm', 'mini_chromium/base/basictypes.h', 'mini_chromium/base/compiler_specific.h', 'mini_chromium/base/logging.h', 'mini_chromium/base/logging.cc', 'mini_chromium/base/mac/scoped_cftyperef.h', 'mini_chromium/base/mac/scoped_nsautorelease_pool.h', 'mini_chromium/base/mac/scoped_nsautorelease_pool.mm', 'mini_chromium/base/memory/scoped_nsobject.h', 'mini_chromium/base/safe_strerror_posix.h', 'mini_chromium/base/safe_strerror_posix.cc', 'mini_chromium/build/build_config.h', 'mini_chromium/chrome/browser/mac/scoped_ioobject.h'], 'libraries': ['$(SDKROOT)/System/Library/Frameworks/CoreFoundation.framework', '$(SDKROOT)/System/Library/Frameworks/DiskArbitration.framework', '$(SDKROOT)/System/Library/Frameworks/Foundation.framework', '$(SDKROOT)/System/Library/Frameworks/IOKit.framework', '$(SDKROOT)/System/Library/Frameworks/OpenDirectory.framework', '$(SDKROOT)/System/Library/PrivateFrameworks/DiskManagement.framework', '$(SDKROOT)/System/Library/PrivateFrameworks/EFILogin.framework', '$(SDKROOT)/usr/lib/libcsfde.dylib'], 'xcode_settings': {'ARCHS': ['x86_64', 'i386'], 'FRAMEWORK_SEARCH_PATHS': ['$(SDKROOT)/System/Library/PrivateFrameworks']}}]}
''' Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). For example: Given binary tree [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 return its level order traversal as: [ [3], [9,20], [15,7] ] ''' # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def levelOrder(self, root: TreeNode) -> List[List[int]]: stack = [[root]] self.final = [] while stack: cur_list = [] onelist = stack.pop() tmp_list = [] for x in onelist: if x != None: tmp_list.append(x.val) if x.left != None: cur_list.append(x.left) if x.right != None: cur_list.append(x.right) if len(cur_list) > 0: stack.append(cur_list) if len(tmp_list) > 0: self.final.append(tmp_list) return self.final
""" Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). For example: Given binary tree [3,9,20,null,null,15,7], 3 / 9 20 / 15 7 return its level order traversal as: [ [3], [9,20], [15,7] ] """ class Solution: def level_order(self, root: TreeNode) -> List[List[int]]: stack = [[root]] self.final = [] while stack: cur_list = [] onelist = stack.pop() tmp_list = [] for x in onelist: if x != None: tmp_list.append(x.val) if x.left != None: cur_list.append(x.left) if x.right != None: cur_list.append(x.right) if len(cur_list) > 0: stack.append(cur_list) if len(tmp_list) > 0: self.final.append(tmp_list) return self.final
""" Version information for `pip-audit`. """ __version__ = "1.1.1"
""" Version information for `pip-audit`. """ __version__ = '1.1.1'
# model model = Model() i1 = Input("op1", "TENSOR_QUANT8_ASYMM", "{3,4}, 0.5f, 1") # a vector of input k = Int32Scalar("k", 2) i2 = Output("op2", "TENSOR_QUANT8_ASYMM", "{3,2}, 0.5f, 1") # values of output i3 = Output("op3", "TENSOR_INT32", "{3,2}") # indexes of output model = model.Operation("TOPK_V2", i1, k).To([i2, i3]) # Example 1. Input in operand 0, input0 = {i1: # input 0 [3, 4, 5, 6, 7, 8, 9, 1, 2, 18, 19, 11]} output0 = {i2: # output 0 [6, 5, 9, 8, 19, 18], i3: # output 1 [3, 2, 2, 1, 2, 1]} # Instantiate an example Example((input0, output0))
model = model() i1 = input('op1', 'TENSOR_QUANT8_ASYMM', '{3,4}, 0.5f, 1') k = int32_scalar('k', 2) i2 = output('op2', 'TENSOR_QUANT8_ASYMM', '{3,2}, 0.5f, 1') i3 = output('op3', 'TENSOR_INT32', '{3,2}') model = model.Operation('TOPK_V2', i1, k).To([i2, i3]) input0 = {i1: [3, 4, 5, 6, 7, 8, 9, 1, 2, 18, 19, 11]} output0 = {i2: [6, 5, 9, 8, 19, 18], i3: [3, 2, 2, 1, 2, 1]} example((input0, output0))
def memmove(data, dest, src, n): '''Copy data in the array from ``src`` to ``dest``. Like ``memmove(3)`` in C, the source and destination may overlap. Arguments: data (list): The list being manipulated. dest (int): The destination index of the copy. src (int): The source index of the copy. n (int): The number of elements to copy. ''' if dest < src: for i in range(n): data[dest + i] = data[src + i] else: for i in range(n): data[dest + n - i - 1] = data[src + n - i - 1] def test_memmove(): data = ['_', '_', 'A', 'B', 'C', '_', '_', '_'] data1 = data.copy() memmove(data1, 5, 2, 3) assert data1 == ['_', '_', 'A', 'B', 'C', 'A', 'B', 'C'] data2 = data.copy() memmove(data2, 3, 2, 3) assert data2 == ['_', '_', 'A', 'A', 'B', 'C', '_', '_'] data3 = data.copy() memmove(data3, 1, 2, 3) assert data3 == ['_', 'A', 'B', 'C', 'C', '_', '_', '_'] data4 = data.copy() memmove(data4, 2, 2, 3) assert data4 == ['_', '_', 'A', 'B', 'C', '_', '_', '_']
def memmove(data, dest, src, n): """Copy data in the array from ``src`` to ``dest``. Like ``memmove(3)`` in C, the source and destination may overlap. Arguments: data (list): The list being manipulated. dest (int): The destination index of the copy. src (int): The source index of the copy. n (int): The number of elements to copy. """ if dest < src: for i in range(n): data[dest + i] = data[src + i] else: for i in range(n): data[dest + n - i - 1] = data[src + n - i - 1] def test_memmove(): data = ['_', '_', 'A', 'B', 'C', '_', '_', '_'] data1 = data.copy() memmove(data1, 5, 2, 3) assert data1 == ['_', '_', 'A', 'B', 'C', 'A', 'B', 'C'] data2 = data.copy() memmove(data2, 3, 2, 3) assert data2 == ['_', '_', 'A', 'A', 'B', 'C', '_', '_'] data3 = data.copy() memmove(data3, 1, 2, 3) assert data3 == ['_', 'A', 'B', 'C', 'C', '_', '_', '_'] data4 = data.copy() memmove(data4, 2, 2, 3) assert data4 == ['_', '_', 'A', 'B', 'C', '_', '_', '_']
def insertion_sort(arr): for i in range(len(arr)): cursor = arr[i] pos = i while pos > 0 and arr[pos - 1] > cursor: arr[pos] = arr[pos - 1] pos = pos - 1 arr[pos] = cursor return arr a = insertion_sort([3, 2, 5, 4, 1, 0]) print(a)
def insertion_sort(arr): for i in range(len(arr)): cursor = arr[i] pos = i while pos > 0 and arr[pos - 1] > cursor: arr[pos] = arr[pos - 1] pos = pos - 1 arr[pos] = cursor return arr a = insertion_sort([3, 2, 5, 4, 1, 0]) print(a)
''' Juan Ivan Medina Martinez Exercise 5.6 ''' def stepLife(yourAge): if isinstance(yourAge,int): if(yourAge>=0): if(yourAge<2): print("Yo are an baby.") elif(4>yourAge>=2): print("You are an toddler.") elif(13>yourAge>=4): print("You are an kid.") elif(20>yourAge>=13): print("You are an teenager.") elif(65>yourAge>=20): print("You are an adult.") else: print("You are an elder.") else: print("Sorry, only positives.") else: print("Sorry, only 'int'.") if __name__ == '__main__': print(" *** Welcome to stageLife.py ***") age=input("Please enter your age: ") #if isinstance(age,int): # stepLife(age)
""" Juan Ivan Medina Martinez Exercise 5.6 """ def step_life(yourAge): if isinstance(yourAge, int): if yourAge >= 0: if yourAge < 2: print('Yo are an baby.') elif 4 > yourAge >= 2: print('You are an toddler.') elif 13 > yourAge >= 4: print('You are an kid.') elif 20 > yourAge >= 13: print('You are an teenager.') elif 65 > yourAge >= 20: print('You are an adult.') else: print('You are an elder.') else: print('Sorry, only positives.') else: print("Sorry, only 'int'.") if __name__ == '__main__': print(' *** Welcome to stageLife.py ***') age = input('Please enter your age: ')
class TestUser(object): """Wraps a user data dictionary.""" # Private attributes: # dict<basestring, mixed> _data - The data dictionary. def __init__(self, data): self._data = data def favorite_food(self): return self._data['favoriteFood']
class Testuser(object): """Wraps a user data dictionary.""" def __init__(self, data): self._data = data def favorite_food(self): return self._data['favoriteFood']
for i in range(10): n=int(input()) if(n< 1): n = 1 print("X[%d] = %d" % (i, n))
for i in range(10): n = int(input()) if n < 1: n = 1 print('X[%d] = %d' % (i, n))
class GithubRequest(): def clone(self): raise NotImplementedError() def auth(self): raise NotImplementedError() def execute(self): raise NotImplementedError()
class Githubrequest: def clone(self): raise not_implemented_error() def auth(self): raise not_implemented_error() def execute(self): raise not_implemented_error()
# AUTOGENERATED BY NBDEV! DO NOT EDIT! __all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {"h3.libh3.experimentalH3ToLocalIj.restype": "00_core.ipynb", "h3.libh3.experimentalH3ToLocalIj.argtypes": "00_core.ipynb", "local_ij_delta": "00_core.ipynb", "local_ij_delta_to_class": "00_core.ipynb", "coordinatesToH3IndexSequence": "00_core.ipynb", "window": "00_core.ipynb", "generate_sequences_with_next_hex_class": "00_core.ipynb", "generate_sequences_with_next_hex_class_from_path": "00_core.ipynb", "parse_strava_gpx": "00_core.ipynb"} modules = ["core.py"] doc_url = "https://jaredwinick.github.io/h3_sequence/" git_url = "https://github.com/jaredwinick/h3_sequence/tree/master/" def custom_doc_links(name): return None
__all__ = ['index', 'modules', 'custom_doc_links', 'git_url'] index = {'h3.libh3.experimentalH3ToLocalIj.restype': '00_core.ipynb', 'h3.libh3.experimentalH3ToLocalIj.argtypes': '00_core.ipynb', 'local_ij_delta': '00_core.ipynb', 'local_ij_delta_to_class': '00_core.ipynb', 'coordinatesToH3IndexSequence': '00_core.ipynb', 'window': '00_core.ipynb', 'generate_sequences_with_next_hex_class': '00_core.ipynb', 'generate_sequences_with_next_hex_class_from_path': '00_core.ipynb', 'parse_strava_gpx': '00_core.ipynb'} modules = ['core.py'] doc_url = 'https://jaredwinick.github.io/h3_sequence/' git_url = 'https://github.com/jaredwinick/h3_sequence/tree/master/' def custom_doc_links(name): return None
#!/usr/bin/env python ###################################################################################### ## Copyright (c) 2010-2011 The Department of Arts and Culture, ## ## The Government of the Republic of South Africa. ## ## ## ## Contributors: Meraka Institute, CSIR, South Africa. ## ## ## ## Permission is hereby granted, free of charge, to any person obtaining a copy ## ## of this software and associated documentation files (the "Software"), to deal ## ## in the Software without restriction, including without limitation the rights ## ## to use, copy, modify, merge, publish, distribute, sublicense, and#or sell ## ## copies of the Software, and to permit persons to whom the Software is ## ## furnished to do so, subject to the following conditions: ## ## The above copyright notice and this permission notice shall be included in ## ## all copies or substantial portions of the Software. ## ## ## ## THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR ## ## IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, ## ## FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE ## ## AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER ## ## LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, ## ## OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN ## ## THE SOFTWARE. ## ## ## ###################################################################################### ## ## ## AUTHOR : Daniel van Niekerk, Aby Louw ## ## DATE : October 2010 ## ## ## ###################################################################################### ## ## ## A rule rewriting module, can be used for G2P, syllabification, etc... ## ## ## ## ## ## ## ###################################################################################### class RewriteRule(object): """ Simply keeps rule info together... Rules are: LC [ A ] RC => B """ def __init__(self, LC, A, RC, B, ordinal): # fix LC if LC != None: tmp = list() skip = False for i in range(0, len(LC)): if skip: skip = False continue if (i < len(LC) - 1) and ((LC[i + 1] == "*") or (LC[i + 1] == "+")): tmp.append(LC[i + 1]) skip = True tmp.append(LC[i]) tmp.reverse() self.LC = tmp else: self.LC = LC self.A = A self.RC = RC self.B = B self.ordinal = ordinal def __str__(self): """Print in 'semicolon format'... """ ### PYTHON2 ### return ";".join([str(self.LC), str(self.A), str(self.RC), str(self.B), str(self.ordinal)]) ### PYTHON2 ### def _itemMatch(self, PATT, THING, sets): if PATT == THING: return True if sets is None: return False if not PATT in sets: return False if not THING in sets[PATT]: return False return True def getRightHandSide(self): return self.B def _contextMatch(self, pattern, string, sets): """ Returns True if this rule matches the given context... """ # pattern is rule left or right context # string is itape if len(pattern) == 0: # rule context is none, so match return True elif len(string) == 0: # rule context is not none and itape context is none return False elif len(pattern) > 1 and pattern[1] == "*": r = self._contextMatch(pattern[2:], string, sets) tmp = pattern[2:] tmp.insert(0, pattern[0]) s = self._contextMatch(tmp, string, sets) t = self._itemMatch(pattern[0], string[0], sets) and self._contextMatch(pattern, string[1:], sets) return (r or s or t) elif len(pattern) > 1 and pattern[1] == "+": r = self._itemMatch(pattern[0], string[0], sets) tmp = pattern[2:] tmp.insert(0, "*") tmp.insert(0, pattern[0]) s = self._contextMatch(tmp, string[1:], sets) return (r and s) elif self._itemMatch(pattern[0], string[0], sets): return self._contextMatch(pattern[1:], string[1:], sets) else: return False def ruleMatches(self, LC, RC, sets): """ Returns this rule if it matches the given context... """ # right context (actually A + RC) must be at least as long as rule's A if len(RC) < len(self.A): return None # check if [ A ] matches counter = 0 a_match = [] for c1, c2 in zip(self.A, RC): if not self._itemMatch(c1, c2, sets): return None, None a_match.append(c2) counter += 1 # Check LC: LC may have some limited regex stuff rLC = list(LC) rLC.reverse() if (self._contextMatch(self.LC, rLC,sets) and self._contextMatch(self.RC, RC[counter:],sets)): return a_match, RC[counter:] else: return None, None class Rewrites(object): """ Class to contain and implement the application of rewrite rules to predict pronunciations of isolated words... ruleset is a dict of lists where the each list contains all RewriteRules associated with a specific grapheme... """ def __init__(self, sets=None): self.ruleset = {} self.sets = sets def _add_rule(self, index, rule): try: self.ruleset[index].append(rule) except KeyError: self.ruleset[index] = [] self.ruleset[index].append(rule) def addRule(self, index, rule): if index in self.sets: for set_entry in self.sets[index]: self._add_rule(set_entry, rule) else: self._add_rule(index, rule) def itemMatch(self, PATT, THING, sets): if PATT == THING: return True if sets is None: return False if not PATT in sets: return False if not THING in sets[PATT]: return False return True def get_otape(self, rRHS, am): new_otape = [] ruleRHS = list(rRHS) ruleRHS.reverse() a_match = list(am) a_match.reverse() while len(ruleRHS) > 0: p = ruleRHS.pop() if p == "-": new_otape.append(p) else: r = a_match.pop() new_otape.append(r) return new_otape def rewrite(self, itape): """ Run rules on itape (LC A RC) to create rewrites otape (B) :param itape: Input tape consisting of LC A RC :type itape: List :return: Output tape B :rtype: List """ LC = itape[0:1] RC = itape[1:] otape = list() while len(RC) > 1: found_rule = False # search through rewrite rules to find matching one for rule in self.ruleset[RC[0]]: a_match, newRC = rule.ruleMatches(LC, RC, self.sets) if newRC is not None: found_rule = True break if not found_rule: res = "Failed to find rewrite rule for itape sequence '" + str(itape) + "'" raise RuntimeError(res) otape += self.get_otape(rule.getRightHandSide(), a_match) LC = LC + RC[0:len(RC) - len(newRC)] RC = newRC return otape
class Rewriterule(object): """ Simply keeps rule info together... Rules are: LC [ A ] RC => B """ def __init__(self, LC, A, RC, B, ordinal): if LC != None: tmp = list() skip = False for i in range(0, len(LC)): if skip: skip = False continue if i < len(LC) - 1 and (LC[i + 1] == '*' or LC[i + 1] == '+'): tmp.append(LC[i + 1]) skip = True tmp.append(LC[i]) tmp.reverse() self.LC = tmp else: self.LC = LC self.A = A self.RC = RC self.B = B self.ordinal = ordinal def __str__(self): """Print in 'semicolon format'... """ return ';'.join([str(self.LC), str(self.A), str(self.RC), str(self.B), str(self.ordinal)]) def _item_match(self, PATT, THING, sets): if PATT == THING: return True if sets is None: return False if not PATT in sets: return False if not THING in sets[PATT]: return False return True def get_right_hand_side(self): return self.B def _context_match(self, pattern, string, sets): """ Returns True if this rule matches the given context... """ if len(pattern) == 0: return True elif len(string) == 0: return False elif len(pattern) > 1 and pattern[1] == '*': r = self._contextMatch(pattern[2:], string, sets) tmp = pattern[2:] tmp.insert(0, pattern[0]) s = self._contextMatch(tmp, string, sets) t = self._itemMatch(pattern[0], string[0], sets) and self._contextMatch(pattern, string[1:], sets) return r or s or t elif len(pattern) > 1 and pattern[1] == '+': r = self._itemMatch(pattern[0], string[0], sets) tmp = pattern[2:] tmp.insert(0, '*') tmp.insert(0, pattern[0]) s = self._contextMatch(tmp, string[1:], sets) return r and s elif self._itemMatch(pattern[0], string[0], sets): return self._contextMatch(pattern[1:], string[1:], sets) else: return False def rule_matches(self, LC, RC, sets): """ Returns this rule if it matches the given context... """ if len(RC) < len(self.A): return None counter = 0 a_match = [] for (c1, c2) in zip(self.A, RC): if not self._itemMatch(c1, c2, sets): return (None, None) a_match.append(c2) counter += 1 r_lc = list(LC) rLC.reverse() if self._contextMatch(self.LC, rLC, sets) and self._contextMatch(self.RC, RC[counter:], sets): return (a_match, RC[counter:]) else: return (None, None) class Rewrites(object): """ Class to contain and implement the application of rewrite rules to predict pronunciations of isolated words... ruleset is a dict of lists where the each list contains all RewriteRules associated with a specific grapheme... """ def __init__(self, sets=None): self.ruleset = {} self.sets = sets def _add_rule(self, index, rule): try: self.ruleset[index].append(rule) except KeyError: self.ruleset[index] = [] self.ruleset[index].append(rule) def add_rule(self, index, rule): if index in self.sets: for set_entry in self.sets[index]: self._add_rule(set_entry, rule) else: self._add_rule(index, rule) def item_match(self, PATT, THING, sets): if PATT == THING: return True if sets is None: return False if not PATT in sets: return False if not THING in sets[PATT]: return False return True def get_otape(self, rRHS, am): new_otape = [] rule_rhs = list(rRHS) ruleRHS.reverse() a_match = list(am) a_match.reverse() while len(ruleRHS) > 0: p = ruleRHS.pop() if p == '-': new_otape.append(p) else: r = a_match.pop() new_otape.append(r) return new_otape def rewrite(self, itape): """ Run rules on itape (LC A RC) to create rewrites otape (B) :param itape: Input tape consisting of LC A RC :type itape: List :return: Output tape B :rtype: List """ lc = itape[0:1] rc = itape[1:] otape = list() while len(RC) > 1: found_rule = False for rule in self.ruleset[RC[0]]: (a_match, new_rc) = rule.ruleMatches(LC, RC, self.sets) if newRC is not None: found_rule = True break if not found_rule: res = "Failed to find rewrite rule for itape sequence '" + str(itape) + "'" raise runtime_error(res) otape += self.get_otape(rule.getRightHandSide(), a_match) lc = LC + RC[0:len(RC) - len(newRC)] rc = newRC return otape
class Datacenter(object): def __init__(self, name=None, location=None, # pylint: disable=unused-argument description=None, volumes=None, servers=None, lans=None, loadbalancers=None): """ The Datacenter class initializer. :param name: The data center name.. :type name: ``str`` :param location: The data center geographical location. :type location: ``str`` :param description: Optional description. :type description: ``str`` :param volumes: List of volume dicts. :type volumes: ``list`` :param servers: List of server dicts. :type servers: ``list`` :param lans: List of LAN dicts. :type lans: ``list`` :param loadbalancers: List of load balancer dicts. :type loadbalancers: ``list`` """ if volumes is None: volumes = [] if servers is None: servers = [] if lans is None: lans = [] if loadbalancers is None: loadbalancers = [] self.name = name self.description = description self.location = location self.servers = servers self.volumes = volumes self.lans = lans self.loadbalancers = loadbalancers def __repr__(self): return (('<Datacenter: name=%s, location=%s, description=%s> ...>') % (self.name, self.location, self.description))
class Datacenter(object): def __init__(self, name=None, location=None, description=None, volumes=None, servers=None, lans=None, loadbalancers=None): """ The Datacenter class initializer. :param name: The data center name.. :type name: ``str`` :param location: The data center geographical location. :type location: ``str`` :param description: Optional description. :type description: ``str`` :param volumes: List of volume dicts. :type volumes: ``list`` :param servers: List of server dicts. :type servers: ``list`` :param lans: List of LAN dicts. :type lans: ``list`` :param loadbalancers: List of load balancer dicts. :type loadbalancers: ``list`` """ if volumes is None: volumes = [] if servers is None: servers = [] if lans is None: lans = [] if loadbalancers is None: loadbalancers = [] self.name = name self.description = description self.location = location self.servers = servers self.volumes = volumes self.lans = lans self.loadbalancers = loadbalancers def __repr__(self): return '<Datacenter: name=%s, location=%s, description=%s> ...>' % (self.name, self.location, self.description)
#!/usr/bin/python coins = [1,5,6,8] target = 51 def cons(e, xs): ys = xs.copy() ys.append(e) return ys # DP solution find the least number of coins for a given total # minCoins[i] is list of coins needed to make i # O(c * y) compared to O(c ^ n) def search(): minCoins = [[]] * (target + 1) for i in range(1, target+1): for c in coins: if i == c: minCoins[i] = [c] elif i > c: prev = len(minCoins[i-c]) curr = len(minCoins[i]) if prev > 0 and (curr == 0 or prev + 1 < curr): minCoins[i] = cons(c, minCoins[i-c]) # print(minCoins) return minCoins[target] soln = search() print(f'min coins {len(soln)}') print(soln)
coins = [1, 5, 6, 8] target = 51 def cons(e, xs): ys = xs.copy() ys.append(e) return ys def search(): min_coins = [[]] * (target + 1) for i in range(1, target + 1): for c in coins: if i == c: minCoins[i] = [c] elif i > c: prev = len(minCoins[i - c]) curr = len(minCoins[i]) if prev > 0 and (curr == 0 or prev + 1 < curr): minCoins[i] = cons(c, minCoins[i - c]) return minCoins[target] soln = search() print(f'min coins {len(soln)}') print(soln)
#! /usr/bin/env python # -*- coding: utf-8 -*- # Copyright 2016 Google Inc. 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. """MPEG-4 constants.""" TRAK_TYPE_VIDE = "vide" # Leaf types. TAG_STCO = "stco" TAG_CO64 = "co64" TAG_FREE = "free" TAG_MDAT = "mdat" TAG_XML = "xml " TAG_HDLR = "hdlr" TAG_FTYP = "ftyp" TAG_ESDS = "esds" TAG_SOUN = "soun" TAG_SA3D = "SA3D" # Container types. TAG_MOOV = "moov" TAG_UDTA = "udta" TAG_META = "meta" TAG_TRAK = "trak" TAG_MDIA = "mdia" TAG_MINF = "minf" TAG_STBL = "stbl" TAG_STSD = "stsd" TAG_UUID = "uuid" TAG_WAVE = "wave" # Sound sample descriptions. TAG_NONE = "NONE" TAG_RAW_ = "raw " TAG_TWOS = "twos" TAG_SOWT = "sowt" TAG_FL32 = "fl32" TAG_FL64 = "fl64" TAG_IN24 = "in24" TAG_IN32 = "in32" TAG_ULAW = "ulaw" TAG_ALAW = "alaw" TAG_LPCM = "lpcm" TAG_MP4A = "mp4a" SOUND_SAMPLE_DESCRIPTIONS = frozenset([ TAG_NONE, TAG_RAW_, TAG_TWOS, TAG_SOWT, TAG_FL32, TAG_FL64, TAG_IN24, TAG_IN32, TAG_ULAW, TAG_ALAW, TAG_LPCM, TAG_MP4A, ]) CONTAINERS_LIST = frozenset([ TAG_MDIA, TAG_MINF, TAG_MOOV, TAG_STBL, TAG_STSD, TAG_TRAK, TAG_UDTA, TAG_WAVE, ]).union(SOUND_SAMPLE_DESCRIPTIONS)
"""MPEG-4 constants.""" trak_type_vide = 'vide' tag_stco = 'stco' tag_co64 = 'co64' tag_free = 'free' tag_mdat = 'mdat' tag_xml = 'xml ' tag_hdlr = 'hdlr' tag_ftyp = 'ftyp' tag_esds = 'esds' tag_soun = 'soun' tag_sa3_d = 'SA3D' tag_moov = 'moov' tag_udta = 'udta' tag_meta = 'meta' tag_trak = 'trak' tag_mdia = 'mdia' tag_minf = 'minf' tag_stbl = 'stbl' tag_stsd = 'stsd' tag_uuid = 'uuid' tag_wave = 'wave' tag_none = 'NONE' tag_raw_ = 'raw ' tag_twos = 'twos' tag_sowt = 'sowt' tag_fl32 = 'fl32' tag_fl64 = 'fl64' tag_in24 = 'in24' tag_in32 = 'in32' tag_ulaw = 'ulaw' tag_alaw = 'alaw' tag_lpcm = 'lpcm' tag_mp4_a = 'mp4a' sound_sample_descriptions = frozenset([TAG_NONE, TAG_RAW_, TAG_TWOS, TAG_SOWT, TAG_FL32, TAG_FL64, TAG_IN24, TAG_IN32, TAG_ULAW, TAG_ALAW, TAG_LPCM, TAG_MP4A]) containers_list = frozenset([TAG_MDIA, TAG_MINF, TAG_MOOV, TAG_STBL, TAG_STSD, TAG_TRAK, TAG_UDTA, TAG_WAVE]).union(SOUND_SAMPLE_DESCRIPTIONS)
#! /usr/bin/python3 def a(k, x1, x2, x3, x4, x5): def b(): def c(): return a(k, x1, x2, x3, x4, x5) nonlocal k k -= 1 return a(k, c(), x1, x2, x3, x4) return x4 + x5 if k <= 0 else b() for i in range(0,8): print(a(i,1,-1,-1,1,0))
def a(k, x1, x2, x3, x4, x5): def b(): def c(): return a(k, x1, x2, x3, x4, x5) nonlocal k k -= 1 return a(k, c(), x1, x2, x3, x4) return x4 + x5 if k <= 0 else b() for i in range(0, 8): print(a(i, 1, -1, -1, 1, 0))
""" 57. Insert Interval Example 1: Input: intervals = [[1,3],[6,9]], newInterval = [2,5] Output: [[1,5],[6,9]] Example 2: Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8] Output: [[1,2],[3,10],[12,16]] Explanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10]. """ # Definition for an interval. # class Interval: # def __init__(self, s=0, e=0): # self.start = s # self.end = e class Solution: def insert(self, intervals, newInterval): """ :type intervals: List[Interval] :type newInterval: Interval :rtype: List[Interval] """ out = [] i, n = 0, len(intervals) while i<n and intervals[i].end < newInterval.start: out+=[intervals[i]] i+=1 while i<n and intervals[i].start<=newInterval.end: newInterval.start = min(newInterval.start, intervals[i].start) newInterval.end = max(newInterval.end, intervals[i].end) i+=1 out+=[newInterval] if i<n: out += intervals[i:] return out class Solution: def insert(self, intervals, newInterval): """ :type intervals: List[Interval] :type newInterval: Interval :rtype: List[Interval] """ s, e = newInterval.start, newInterval.end left, right = [], [] for i in intervals: if i.end < s: left += i, elif i.start > e: right += i, else: s = min(s, i.start) e = max(e, i.end) return left + [Interval(s, e)] + right def insert(self, intervals, newInterval): s, e = newInterval.start, newInterval.end parts = merge, left, right = [], [], [] for i in intervals: parts[(i.end < s) - (i.start > e)].append(i) if merge: s = min(s, merge[0].start) e = max(e, merge[-1].end) return left + [Interval(s, e)] + right
""" 57. Insert Interval Example 1: Input: intervals = [[1,3],[6,9]], newInterval = [2,5] Output: [[1,5],[6,9]] Example 2: Input: intervals = [[1,2],[3,5],[6,7],[8,10],[12,16]], newInterval = [4,8] Output: [[1,2],[3,10],[12,16]] Explanation: Because the new interval [4,8] overlaps with [3,5],[6,7],[8,10]. """ class Solution: def insert(self, intervals, newInterval): """ :type intervals: List[Interval] :type newInterval: Interval :rtype: List[Interval] """ out = [] (i, n) = (0, len(intervals)) while i < n and intervals[i].end < newInterval.start: out += [intervals[i]] i += 1 while i < n and intervals[i].start <= newInterval.end: newInterval.start = min(newInterval.start, intervals[i].start) newInterval.end = max(newInterval.end, intervals[i].end) i += 1 out += [newInterval] if i < n: out += intervals[i:] return out class Solution: def insert(self, intervals, newInterval): """ :type intervals: List[Interval] :type newInterval: Interval :rtype: List[Interval] """ (s, e) = (newInterval.start, newInterval.end) (left, right) = ([], []) for i in intervals: if i.end < s: left += (i,) elif i.start > e: right += (i,) else: s = min(s, i.start) e = max(e, i.end) return left + [interval(s, e)] + right def insert(self, intervals, newInterval): (s, e) = (newInterval.start, newInterval.end) parts = (merge, left, right) = ([], [], []) for i in intervals: parts[(i.end < s) - (i.start > e)].append(i) if merge: s = min(s, merge[0].start) e = max(e, merge[-1].end) return left + [interval(s, e)] + right
class Solution: def fizzBuzz(self, n): """ :type n: int :rtype: List[str] """ list = [] for i in range(1, n + 1): div3 = i % 3 == 0 div5 = i % 5 == 0 if div3 and div5: list.append("FizzBuzz") elif div3: list.append("Fizz") elif div5: list.append("Buzz") else: list.append(str(i)) return list if __name__ == '__main__': sol = Solution() print(sol.fizzBuzz(15))
class Solution: def fizz_buzz(self, n): """ :type n: int :rtype: List[str] """ list = [] for i in range(1, n + 1): div3 = i % 3 == 0 div5 = i % 5 == 0 if div3 and div5: list.append('FizzBuzz') elif div3: list.append('Fizz') elif div5: list.append('Buzz') else: list.append(str(i)) return list if __name__ == '__main__': sol = solution() print(sol.fizzBuzz(15))
""" * Create Image. * * The createImage() function provides a fresh buffer of pixels to play with. * This example creates an image gradient. """ def setup(): size(640, 360) global img img = createImage(230, 230, ARGB) pixCount = len(img.pixels) for i in range(pixCount): a = map(i, 0, pixCount, 255, 0) img.pixels[i] = color(0, 153, 204, a) def draw(): background(0) image(img, 90, 80) image(img, mouseX - img.width / 2, mouseY - img.height / 2)
""" * Create Image. * * The createImage() function provides a fresh buffer of pixels to play with. * This example creates an image gradient. """ def setup(): size(640, 360) global img img = create_image(230, 230, ARGB) pix_count = len(img.pixels) for i in range(pixCount): a = map(i, 0, pixCount, 255, 0) img.pixels[i] = color(0, 153, 204, a) def draw(): background(0) image(img, 90, 80) image(img, mouseX - img.width / 2, mouseY - img.height / 2)
class Match(): def __init__(self, span, value): self.span = span self.token = span.text self.value = value self.start = span[0].idx self.end = span[0].idx + len(span.text) def contains(self, other): return self.start <= other.start and self.end >= other.end def __repr__(self): return 'Match (%s, %d, %d)' % \ (self.value, self.start, self.end)
class Match: def __init__(self, span, value): self.span = span self.token = span.text self.value = value self.start = span[0].idx self.end = span[0].idx + len(span.text) def contains(self, other): return self.start <= other.start and self.end >= other.end def __repr__(self): return 'Match (%s, %d, %d)' % (self.value, self.start, self.end)
class Mapping(): # TODO: add support for one_of=str(group) which extends required # It should be used to group multiple mappings together and only one of # the mapping of the group can and has to be set. Mappings of one_of # cannot have default value. def __init__(self, name, source=None, required=True, default=None, inherited=False, func=None, allowed_types=str): self.name = name self.source = source if source is not None else name self.required = required self.default = default self.inherited = inherited self.func = func self.allowed_types = allowed_types if not isinstance(allowed_types, tuple): self.allowed_types = (self.allowed_types, ) if self.required == False and self.default is None and type(None) not in self.allowed_types: self.allowed_types = self.allowed_types + (type(None), ) # Enable using mapping in dict constructor def __iter__(self): yield self.name yield self
class Mapping: def __init__(self, name, source=None, required=True, default=None, inherited=False, func=None, allowed_types=str): self.name = name self.source = source if source is not None else name self.required = required self.default = default self.inherited = inherited self.func = func self.allowed_types = allowed_types if not isinstance(allowed_types, tuple): self.allowed_types = (self.allowed_types,) if self.required == False and self.default is None and (type(None) not in self.allowed_types): self.allowed_types = self.allowed_types + (type(None),) def __iter__(self): yield self.name yield self
# generated from genmsg/cmake/pkg-genmsg.context.in messages_str = "/home/ubuntu/catkin_ws/src/navigation/costmap_2d/msg/VoxelGrid.msg" services_str = "" pkg_name = "costmap_2d" dependencies_str = "std_msgs;geometry_msgs;map_msgs" langs = "gencpp;genlisp;genpy" dep_include_paths_str = "costmap_2d;/home/ubuntu/catkin_ws/src/navigation/costmap_2d/msg;std_msgs;/opt/ros/indigo/share/std_msgs/cmake/../msg;geometry_msgs;/opt/ros/indigo/share/geometry_msgs/cmake/../msg;map_msgs;/opt/ros/indigo/share/map_msgs/cmake/../msg;sensor_msgs;/opt/ros/indigo/share/sensor_msgs/cmake/../msg;nav_msgs;/opt/ros/indigo/share/nav_msgs/cmake/../msg;actionlib_msgs;/opt/ros/indigo/share/actionlib_msgs/cmake/../msg" PYTHON_EXECUTABLE = "/usr/bin/python" package_has_static_sources = '' == 'TRUE' genmsg_check_deps_script = "/opt/ros/indigo/share/genmsg/cmake/../../../lib/genmsg/genmsg_check_deps.py"
messages_str = '/home/ubuntu/catkin_ws/src/navigation/costmap_2d/msg/VoxelGrid.msg' services_str = '' pkg_name = 'costmap_2d' dependencies_str = 'std_msgs;geometry_msgs;map_msgs' langs = 'gencpp;genlisp;genpy' dep_include_paths_str = 'costmap_2d;/home/ubuntu/catkin_ws/src/navigation/costmap_2d/msg;std_msgs;/opt/ros/indigo/share/std_msgs/cmake/../msg;geometry_msgs;/opt/ros/indigo/share/geometry_msgs/cmake/../msg;map_msgs;/opt/ros/indigo/share/map_msgs/cmake/../msg;sensor_msgs;/opt/ros/indigo/share/sensor_msgs/cmake/../msg;nav_msgs;/opt/ros/indigo/share/nav_msgs/cmake/../msg;actionlib_msgs;/opt/ros/indigo/share/actionlib_msgs/cmake/../msg' python_executable = '/usr/bin/python' package_has_static_sources = '' == 'TRUE' genmsg_check_deps_script = '/opt/ros/indigo/share/genmsg/cmake/../../../lib/genmsg/genmsg_check_deps.py'
# Language: Python 3 i = 4 d = 4.0 s = 'HackerRank ' int2 = int(input()) double2 = float(input()) string2 = input() int2_i = i + int2 double2_d = d + double2 string2_s = s + string2 print(int2_i, double2_d, string2_s, sep="\n")
i = 4 d = 4.0 s = 'HackerRank ' int2 = int(input()) double2 = float(input()) string2 = input() int2_i = i + int2 double2_d = d + double2 string2_s = s + string2 print(int2_i, double2_d, string2_s, sep='\n')
a = list(map(int,input().split())) def heapsort(arr,e): i=1 while i<e: upheap(arr,i) i+=1 i-=1 while i>0: tmp=arr[0] arr[0]=arr[i] arr[i]=tmp i-=1 downheap(arr,i) def leftC(i): return int(((i) + 1) * 2 - 1) def rightC(i): return int(((i) + 1) * 2) def parent(i): return int(((i) + 1) / 2 - 1) def upheap(arr,n): while n>0: m = parent(n) if arr[m]<arr[n]: tmp=arr[m] arr[m]=arr[n] arr[n]=tmp else: break n=m def downheap(arr,n): m=0 tmp=0 while True: lc=leftC(m) rc=rightC(m) if lc>=n: break if arr[lc]>arr[tmp]: tmp=lc if rc<n and arr[rc]>arr[tmp]: tmp=rc if tmp==m: break swp=arr[tmp] arr[tmp]=arr[m] arr[m]=swp m=tmp heapsort(a,len(a)) #print(a)
a = list(map(int, input().split())) def heapsort(arr, e): i = 1 while i < e: upheap(arr, i) i += 1 i -= 1 while i > 0: tmp = arr[0] arr[0] = arr[i] arr[i] = tmp i -= 1 downheap(arr, i) def left_c(i): return int((i + 1) * 2 - 1) def right_c(i): return int((i + 1) * 2) def parent(i): return int((i + 1) / 2 - 1) def upheap(arr, n): while n > 0: m = parent(n) if arr[m] < arr[n]: tmp = arr[m] arr[m] = arr[n] arr[n] = tmp else: break n = m def downheap(arr, n): m = 0 tmp = 0 while True: lc = left_c(m) rc = right_c(m) if lc >= n: break if arr[lc] > arr[tmp]: tmp = lc if rc < n and arr[rc] > arr[tmp]: tmp = rc if tmp == m: break swp = arr[tmp] arr[tmp] = arr[m] arr[m] = swp m = tmp heapsort(a, len(a))
fname = input('Enter the file name') try: f = open(fname) except: print('The file could not be opened') quit() total = 0 count = 0 for line in f: if 'X-DSPAM-Confidence' in line: print(line) i = line.find(': ') + 1 total += float(line[i:len(line)]) count += 1 print('Average spam confidence:', total / count)
fname = input('Enter the file name') try: f = open(fname) except: print('The file could not be opened') quit() total = 0 count = 0 for line in f: if 'X-DSPAM-Confidence' in line: print(line) i = line.find(': ') + 1 total += float(line[i:len(line)]) count += 1 print('Average spam confidence:', total / count)
# -*- coding: utf-8 -*- # @Author : Ecohnoch(xcy) # @File : configs.py # @Function : TODO app_redis_hostname = 'my_redis' app_redis_port = 6379 app_info_key = 'INFO_KEY' app_response_key = 'RESPONSE_KEY' app_error_key = 'ERROR_KEY' app_kafka_host = 'my_kafka:9092' app_kafka_topic = 'user_queue' app_kafka_key = 'user_requests' app_group_id = 'calculator' app_web_host = 'http://face_storage:12350' app_file_interface = '/get_image_file' call_interval = 1 sleep_interval = 7
app_redis_hostname = 'my_redis' app_redis_port = 6379 app_info_key = 'INFO_KEY' app_response_key = 'RESPONSE_KEY' app_error_key = 'ERROR_KEY' app_kafka_host = 'my_kafka:9092' app_kafka_topic = 'user_queue' app_kafka_key = 'user_requests' app_group_id = 'calculator' app_web_host = 'http://face_storage:12350' app_file_interface = '/get_image_file' call_interval = 1 sleep_interval = 7
# DROP TABLES songplay_table_drop = "DROP TABLE IF EXISTS songplays" user_table_drop = "DROP TABLE IF EXISTS users" song_table_drop = "DROP TABLE IF EXISTS songs" artist_table_drop = "DROP TABLE IF EXISTS artists" time_table_drop = "DROP TABLE IF EXISTS time" # CREATE TABLES songplay_table_create = ("""CREATE TABLE IF NOT EXISTS songplays (songplay_id SERIAL PRIMARY KEY, start_time bigint NOT NULL, user_id int NOT NULL, level varchar NOT NULL, song_id varchar, artist_id varchar, session_id int NOT NULL, location varchar NOT NULL, user_agent varchar NOT NULL) """) user_table_create = ("""CREATE TABLE IF NOT EXISTS users ( user_id int PRIMARY KEY, first_name varchar NOT NULL, last_name varchar NOT NULL, gender varchar NOT NULL, level varchar NOT NULL) """) song_table_create = ("""CREATE TABLE IF NOT EXISTS songs ( song_id varchar PRIMARY KEY, title varchar NOT NULL, artist_id varchar NOT NULL, year int, duration float) """) artist_table_create = ("""CREATE TABLE IF NOT EXISTS artists ( artist_id varchar PRIMARY KEY, name varchar NOT NULL, location varchar, latitude float, longitude float) """) time_table_create = ("""CREATE TABLE IF NOT EXISTS time ( start_time bigint NOT NULL, hour int NOT NULL, day int NOT NULL, week int NOT NULL, month int NOT NULL, year int NOT NULL, weekday int NOT NULL) """) # INSERT RECORDS songplay_table_insert = ("""INSERT INTO songplays (start_time, user_id, level, song_id, artist_id, session_id, location, user_agent) VALUES (%s, %s, %s, %s, %s, %s, %s, %s) ON CONFLICT DO NOTHING """) user_table_insert = ("""INSERT INTO users (user_id, first_name, last_name, gender, level) VALUES (%s, %s, %s, %s, %s) ON CONFLICT(user_id) DO UPDATE SET level = excluded.level """) song_table_insert = ("""INSERT INTO songs (song_id, title, artist_id, year, duration) VALUES (%s, %s, %s, %s, %s) ON CONFLICT DO NOTHING """) artist_table_insert = ("""INSERT INTO artists (artist_id, name, location, latitude, longitude) VALUES (%s, %s, %s, %s, %s) ON CONFLICT DO NOTHING """) time_table_insert = ("""INSERT INTO time (start_time, hour, day, week, month, year, weekday) VALUES (%s, %s, %s, %s, %s, %s, %s) ON CONFLICT DO NOTHING """) # FIND SONGS song_select = ("""SELECT song_id, artists.artist_id FROM songs JOIN artists ON songs.artist_id=artists.artist_id WHERE title = %s AND name = %s AND duration = %s """) # QUERY LISTS create_table_queries = [songplay_table_create, user_table_create, song_table_create, artist_table_create, time_table_create] drop_table_queries = [songplay_table_drop, user_table_drop, song_table_drop, artist_table_drop, time_table_drop]
songplay_table_drop = 'DROP TABLE IF EXISTS songplays' user_table_drop = 'DROP TABLE IF EXISTS users' song_table_drop = 'DROP TABLE IF EXISTS songs' artist_table_drop = 'DROP TABLE IF EXISTS artists' time_table_drop = 'DROP TABLE IF EXISTS time' songplay_table_create = 'CREATE TABLE IF NOT EXISTS songplays \n (songplay_id SERIAL PRIMARY KEY,\n start_time bigint NOT NULL,\n user_id int NOT NULL,\n level varchar NOT NULL,\n song_id varchar,\n artist_id varchar,\n session_id int NOT NULL,\n location varchar NOT NULL,\n user_agent varchar NOT NULL)\n ' user_table_create = 'CREATE TABLE IF NOT EXISTS users (\n user_id int PRIMARY KEY,\n first_name varchar NOT NULL,\n last_name varchar NOT NULL,\n gender varchar NOT NULL,\n level varchar NOT NULL)\n ' song_table_create = 'CREATE TABLE IF NOT EXISTS songs (\n song_id varchar PRIMARY KEY,\n title varchar NOT NULL,\n artist_id varchar NOT NULL,\n year int,\n duration float)\n' artist_table_create = 'CREATE TABLE IF NOT EXISTS artists (\n artist_id varchar PRIMARY KEY,\n name varchar NOT NULL,\n location varchar,\n latitude float,\n longitude float)\n' time_table_create = 'CREATE TABLE IF NOT EXISTS time (\n start_time bigint NOT NULL,\n hour int NOT NULL,\n day int NOT NULL,\n week int NOT NULL,\n month int NOT NULL,\n year int NOT NULL,\n weekday int NOT NULL)\n' songplay_table_insert = 'INSERT INTO songplays \n(start_time, user_id, level, song_id, artist_id, session_id, location, user_agent)\nVALUES (%s, %s, %s, %s, %s, %s, %s, %s)\nON CONFLICT DO NOTHING\n' user_table_insert = 'INSERT INTO users \n(user_id, first_name, last_name, gender, level)\nVALUES (%s, %s, %s, %s, %s)\nON CONFLICT(user_id) DO UPDATE SET level = excluded.level\n' song_table_insert = 'INSERT INTO songs \n(song_id, title, artist_id, year, duration)\nVALUES (%s, %s, %s, %s, %s)\nON CONFLICT DO NOTHING\n' artist_table_insert = 'INSERT INTO artists \n(artist_id, name, location, latitude, longitude)\nVALUES (%s, %s, %s, %s, %s)\nON CONFLICT DO NOTHING\n' time_table_insert = 'INSERT INTO time \n(start_time, hour, day, week, month, year, weekday)\nVALUES (%s, %s, %s, %s, %s, %s, %s)\nON CONFLICT DO NOTHING\n' song_select = 'SELECT song_id, artists.artist_id \nFROM songs JOIN artists ON songs.artist_id=artists.artist_id \nWHERE title = %s AND name = %s AND duration = %s\n' create_table_queries = [songplay_table_create, user_table_create, song_table_create, artist_table_create, time_table_create] drop_table_queries = [songplay_table_drop, user_table_drop, song_table_drop, artist_table_drop, time_table_drop]
""" * * Author: Juarez Paulino(coderemite) * Email: juarez.paulino@gmail.com * """ for _ in [0]*int(input()): n,x,*a=map(int,input().split()) a=sorted(a) b=a[0]-a[1] print(min(x,n-1+b)-b)
""" * * Author: Juarez Paulino(coderemite) * Email: juarez.paulino@gmail.com * """ for _ in [0] * int(input()): (n, x, *a) = map(int, input().split()) a = sorted(a) b = a[0] - a[1] print(min(x, n - 1 + b) - b)
""" pierre de fermat 17th frensh mathematician century: * a^p -a --> a is all numbers from 1 to p not including p * if all the outcome from the quation are divisble by p then p is a prime * note:we dont need to include the number it self because the outcome will be always divisble by the number """ number = 5 def fermate(number): for i in range(1, number): m = i ** number - i print(m) if m % number == 0: continue else: return False return True x = fermate(number) print(x) #-->ture
""" pierre de fermat 17th frensh mathematician century: * a^p -a --> a is all numbers from 1 to p not including p * if all the outcome from the quation are divisble by p then p is a prime * note:we dont need to include the number it self because the outcome will be always divisble by the number """ number = 5 def fermate(number): for i in range(1, number): m = i ** number - i print(m) if m % number == 0: continue else: return False return True x = fermate(number) print(x)
class DjangoUser(object): def dangerous_method(self): pass def safe_method(self): pass def get_user(): # without an inference tip, this will be un-inferrable return DjangoUser.objects.get(id=1337) user = get_user() # dangerous_method call #1 user.dangerous_method() def get_users(): return DjangoUser.objects.bulk_create() # dangerous_method call #2 users = get_users() for user in users: user.dangerous_method() # dangerous_method call #3 # Chained call all_users = DjangoUser.objects.all() all_users.latest().dangerous_method() # dangerous_method call #4 all_users.filter().order_by().all().first().dangerous_method() # dangerous_method call #5 # vanilla python method call DjangoUser().dangerous_method() # not a call DjangoUser.dangerous_method def dangerous_method(): pass # not a call on DjangoUser dangerous_method() DjangoUser().safe_method()
class Djangouser(object): def dangerous_method(self): pass def safe_method(self): pass def get_user(): return DjangoUser.objects.get(id=1337) user = get_user() user.dangerous_method() def get_users(): return DjangoUser.objects.bulk_create() users = get_users() for user in users: user.dangerous_method() all_users = DjangoUser.objects.all() all_users.latest().dangerous_method() all_users.filter().order_by().all().first().dangerous_method() django_user().dangerous_method() DjangoUser.dangerous_method def dangerous_method(): pass dangerous_method() django_user().safe_method()
[ i+j for i in range(1) for j in range(2) ] { x * x for x in seq } { y.attr : z() for y, z in mapping }
[i + j for i in range(1) for j in range(2)] {x * x for x in seq} {y.attr: z() for (y, z) in mapping}
# Adding a new method during runtime: class A: def foo(self): print('A.foo()') x = A() y = A() x.foo() # A.foo() y.foo() # A.foo() def foo2(self): print('A.foo2()') A.foo2 = foo2 x.foo2() # A.foo2() y.foo2() # A.foo2()
class A: def foo(self): print('A.foo()') x = a() y = a() x.foo() y.foo() def foo2(self): print('A.foo2()') A.foo2 = foo2 x.foo2() y.foo2()
#!/usr/bin/python3.7+ # -*- coding:utf-8 -*- """ @auth: cml @date: 2021/2/23 @desc: ... """
""" @auth: cml @date: 2021/2/23 @desc: ... """
# -*- coding: utf-8 -*- def main(): a = int(input()) b = int(input()) c = int(input()) d = int(input()) p = int(input()) print(min(a * p, b + max(0, (p - c)) * d)) if __name__ == '__main__': main()
def main(): a = int(input()) b = int(input()) c = int(input()) d = int(input()) p = int(input()) print(min(a * p, b + max(0, p - c) * d)) if __name__ == '__main__': main()
score_configs = { 'CHEAT' : 1, 'TRUST' : -1, 'single_cheat' : 3, 'single_trust' : -1, 'both_trust' : 2, 'both_cheat' : 0, } players_configs = { 'Bot': 3, 'Follower': 3, 'Gambler': 3, 'Pink': 3, 'Follower_2': 3, 'Black': 3, 'Single_Mind': 3, 'Sherlock': 3, } total_num = 0 for v in players_configs.values(): total_num += v game_configs = { 'total_player_num': total_num, 'each_game_num': 10, 'update_player_num': 5, 'mistake_prob': 5, 'total_rounds': 15, }
score_configs = {'CHEAT': 1, 'TRUST': -1, 'single_cheat': 3, 'single_trust': -1, 'both_trust': 2, 'both_cheat': 0} players_configs = {'Bot': 3, 'Follower': 3, 'Gambler': 3, 'Pink': 3, 'Follower_2': 3, 'Black': 3, 'Single_Mind': 3, 'Sherlock': 3} total_num = 0 for v in players_configs.values(): total_num += v game_configs = {'total_player_num': total_num, 'each_game_num': 10, 'update_player_num': 5, 'mistake_prob': 5, 'total_rounds': 15}
class PillowtopCheckpointReset(Exception): pass class PillowNotFoundError(Exception): pass class PillowtopIndexingError(Exception): pass class PillowConfigError(Exception): pass class BulkDocException(Exception): pass
class Pillowtopcheckpointreset(Exception): pass class Pillownotfounderror(Exception): pass class Pillowtopindexingerror(Exception): pass class Pillowconfigerror(Exception): pass class Bulkdocexception(Exception): pass
"""Configuration file for mapping counting and detection tasks.""" file_mapping_counting = { "Columbus_CSUAV_AFRL": "COWC_Counting_Columbus_CSUAV_AFRL.tbz", "Potsdam_ISPRS": "COWC_Counting_Potsdam_ISPRS.tbz", "Selwyn_LINZ": "COWC_Counting_Selwyn_LINZ.tbz", "Toronto_ISPRS": "COWC_Counting_Toronto_ISPRS.tbz", "Utah_AGRC": "COWC_Counting_Utah_AGRC.tbz", "Vaihingen_ISPRS": "COWC_Counting_Vaihingen_ISPRS.tbz", } file_mapping_detection = { "Columbus_CSUAV_AFRL": "COWC_Detection_Columbus_CSUAV_AFRL.tbz", "Potsdam_ISPRS": "COWC_Detection_Potsdam_ISPRS.tbz", "Selwyn_LINZ": "COWC_Detection_Selwyn_LINZ.tbz", "Toronto_ISPRS": "COWC_Detection_Toronto_ISPRS.tbz", "Utah_AGRC": "COWC_Detection_Utah_AGRC.tbz", "Vaihingen_ISPRS": "COWC_Detection_Vaihingen_ISPRS.tbz", }
"""Configuration file for mapping counting and detection tasks.""" file_mapping_counting = {'Columbus_CSUAV_AFRL': 'COWC_Counting_Columbus_CSUAV_AFRL.tbz', 'Potsdam_ISPRS': 'COWC_Counting_Potsdam_ISPRS.tbz', 'Selwyn_LINZ': 'COWC_Counting_Selwyn_LINZ.tbz', 'Toronto_ISPRS': 'COWC_Counting_Toronto_ISPRS.tbz', 'Utah_AGRC': 'COWC_Counting_Utah_AGRC.tbz', 'Vaihingen_ISPRS': 'COWC_Counting_Vaihingen_ISPRS.tbz'} file_mapping_detection = {'Columbus_CSUAV_AFRL': 'COWC_Detection_Columbus_CSUAV_AFRL.tbz', 'Potsdam_ISPRS': 'COWC_Detection_Potsdam_ISPRS.tbz', 'Selwyn_LINZ': 'COWC_Detection_Selwyn_LINZ.tbz', 'Toronto_ISPRS': 'COWC_Detection_Toronto_ISPRS.tbz', 'Utah_AGRC': 'COWC_Detection_Utah_AGRC.tbz', 'Vaihingen_ISPRS': 'COWC_Detection_Vaihingen_ISPRS.tbz'}
class Solution: def licenseKeyFormatting(self, S: str, K: int) -> str: result = [] for c in reversed(S): if c != '-': if len(result) % (K + 1) == K: result.append('-') result.append(c.upper()) return ''.join(reversed(result))
class Solution: def license_key_formatting(self, S: str, K: int) -> str: result = [] for c in reversed(S): if c != '-': if len(result) % (K + 1) == K: result.append('-') result.append(c.upper()) return ''.join(reversed(result))
class Solution: def myAtoi(self, str: str) -> int: s = str if not s: return 0 s = s.strip() print(s) if s == "": return 0 multiplier = 1 if s[0] == '+': multiplier = 1 s = s[1:] elif s[0] == '-': multiplier = -1 s = s[1:] elif not s[0].isdigit(): return 0 result = "" print (s) for char in s: if char.isdigit(): result = result+char else: break if result != "": int_max = (2**31) - 1 int_min = -(2**31) number = int(result) * multiplier if number > int_max: return int_max elif number < int_min : return int_min else: return number else: return 0
class Solution: def my_atoi(self, str: str) -> int: s = str if not s: return 0 s = s.strip() print(s) if s == '': return 0 multiplier = 1 if s[0] == '+': multiplier = 1 s = s[1:] elif s[0] == '-': multiplier = -1 s = s[1:] elif not s[0].isdigit(): return 0 result = '' print(s) for char in s: if char.isdigit(): result = result + char else: break if result != '': int_max = 2 ** 31 - 1 int_min = -2 ** 31 number = int(result) * multiplier if number > int_max: return int_max elif number < int_min: return int_min else: return number else: return 0
def isprime(n): c=0 for i in range(1,n+1): if n%i==0: c+=1 if c==2: print("prime number") else: print("not a prime number") def factorial(n): f=1 for i in range(1,n+1): f*=i print(f)
def isprime(n): c = 0 for i in range(1, n + 1): if n % i == 0: c += 1 if c == 2: print('prime number') else: print('not a prime number') def factorial(n): f = 1 for i in range(1, n + 1): f *= i print(f)
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode: def postdfs(stop): if postorder and inorder[-1] != stop: root = TreeNode(postorder.pop()) root.right = postdfs(root.val) inorder.pop() root.left = postdfs(stop) return root return postdfs(None)
class Solution: def build_tree(self, inorder: List[int], postorder: List[int]) -> TreeNode: def postdfs(stop): if postorder and inorder[-1] != stop: root = tree_node(postorder.pop()) root.right = postdfs(root.val) inorder.pop() root.left = postdfs(stop) return root return postdfs(None)
SYSTEMS = "root.properties.systems" ITEMS = f"{SYSTEMS}.items" ID = f"{SYSTEMS}.items.properties.id" NAME = f"{SYSTEMS}.items.properties.name" VENDOR = f"{SYSTEMS}.items.properties.vendor" MODEL = f"{SYSTEMS}.items.properties.model" TYPE = f"{SYSTEMS}.items.properties.type" SERIAL_NUMBER = f"{SYSTEMS}.items.properties.serial_number" FIRMWARE = f"{SYSTEMS}.items.properties.firmware" FIRMWARE_ITEMS = f"{FIRMWARE}.items" FIRMWARE_NAME = f"{FIRMWARE}.items.properties.name" FIRMWARE_VERSION = f"{FIRMWARE}.items.properties.version" FIRMWARE_LAST_UPDATE = f"{FIRMWARE}.items.properties.last_updated_timestamp" SOFTWARE = f"{SYSTEMS}.items.properties.software" SOFTWARE_ITEMS = f"{SOFTWARE}.items" SOFTWARE_NAME = f"{SOFTWARE}.items.properties.name" SOFTWARE_VERSION = f"{SOFTWARE}.items.properties.version" SOFTWARE_SERIAL_NUMBER = f"{SOFTWARE}.items.properties.serial_number" SOFTWARE_LAST_UPDATE = f"{SOFTWARE}.items.properties.last_updated_timestamp" systems_rules = { SYSTEMS: { "type": "array", "min_properties": [ "vendor", "model", "type", ], }, ITEMS: { "type": "object", "min_required": ["vendor", "model", "type"], }, ID: {"type": ["string", "null"]}, NAME: {"type": ["string", "null"]}, VENDOR: {"type": ["string", "null"]}, MODEL: {"type": ["string", "null"]}, TYPE: {"type": ["string", "null"]}, SERIAL_NUMBER: {"type": ["string", "null"]}, FIRMWARE: { "type": "array", "min_properties": [ "name", "version", ], }, FIRMWARE_ITEMS: { "type": "object", "min_required": ["name", "version"], }, FIRMWARE_NAME: {"type": ["string", "null"]}, FIRMWARE_VERSION: {"type": ["string", "null"]}, FIRMWARE_LAST_UPDATE: {"type": ["string", "null"]}, SOFTWARE: { "type": "array", "min_properties": [ "name", "version", ], }, SOFTWARE_ITEMS: { "type": "object", "min_required": ["name", "version"], }, SOFTWARE_NAME: {"type": ["string", "null"]}, SOFTWARE_VERSION: {"type": ["null", "string"]}, SOFTWARE_LAST_UPDATE: {"type": ["string", "null"]}, }
systems = 'root.properties.systems' items = f'{SYSTEMS}.items' id = f'{SYSTEMS}.items.properties.id' name = f'{SYSTEMS}.items.properties.name' vendor = f'{SYSTEMS}.items.properties.vendor' model = f'{SYSTEMS}.items.properties.model' type = f'{SYSTEMS}.items.properties.type' serial_number = f'{SYSTEMS}.items.properties.serial_number' firmware = f'{SYSTEMS}.items.properties.firmware' firmware_items = f'{FIRMWARE}.items' firmware_name = f'{FIRMWARE}.items.properties.name' firmware_version = f'{FIRMWARE}.items.properties.version' firmware_last_update = f'{FIRMWARE}.items.properties.last_updated_timestamp' software = f'{SYSTEMS}.items.properties.software' software_items = f'{SOFTWARE}.items' software_name = f'{SOFTWARE}.items.properties.name' software_version = f'{SOFTWARE}.items.properties.version' software_serial_number = f'{SOFTWARE}.items.properties.serial_number' software_last_update = f'{SOFTWARE}.items.properties.last_updated_timestamp' systems_rules = {SYSTEMS: {'type': 'array', 'min_properties': ['vendor', 'model', 'type']}, ITEMS: {'type': 'object', 'min_required': ['vendor', 'model', 'type']}, ID: {'type': ['string', 'null']}, NAME: {'type': ['string', 'null']}, VENDOR: {'type': ['string', 'null']}, MODEL: {'type': ['string', 'null']}, TYPE: {'type': ['string', 'null']}, SERIAL_NUMBER: {'type': ['string', 'null']}, FIRMWARE: {'type': 'array', 'min_properties': ['name', 'version']}, FIRMWARE_ITEMS: {'type': 'object', 'min_required': ['name', 'version']}, FIRMWARE_NAME: {'type': ['string', 'null']}, FIRMWARE_VERSION: {'type': ['string', 'null']}, FIRMWARE_LAST_UPDATE: {'type': ['string', 'null']}, SOFTWARE: {'type': 'array', 'min_properties': ['name', 'version']}, SOFTWARE_ITEMS: {'type': 'object', 'min_required': ['name', 'version']}, SOFTWARE_NAME: {'type': ['string', 'null']}, SOFTWARE_VERSION: {'type': ['null', 'string']}, SOFTWARE_LAST_UPDATE: {'type': ['string', 'null']}}