content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
def most_common(lst): return max(lst, key=lst.count)
def most_common(lst): return max(lst, key=lst.count)
# https://leetcode.com/problems/defanging-an-ip-address class Solution: def defangIPaddr(self, address): if not address: return "" ls = address.split(".") return "[.]".join(ls)
class Solution: def defang_i_paddr(self, address): if not address: return '' ls = address.split('.') return '[.]'.join(ls)
BOT = "b" EMPTY = "-" DIRT = "d" def dist(pos1, pos2): return abs(pos1[0] - pos2[0]) + abs(pos1[1] - pos2[1]) def is_dirt(pos, board): if min(pos) < 0: return False if pos[0] >= len(board): return False if pos[1] >= len(board[0]): return False if board[pos[0]][pos[1]] != DIRT: return False return True def find_closest_dirt(pos, board, max_distance=0): if not max_distance: max_distance = len(board) + len(board[0]) n_moves = 1 start = (pos[0] + n_moves, pos[1]) curr = list(start) dx, dy = -1, 1 while n_moves <= max_distance: if is_dirt(curr, board): return curr curr[0] += dx curr[1] += dy if curr[0] == pos[0]: dy = -dy if curr[1] == pos[1]: dx = -dx if curr == list(start): n_moves += 1 start = (pos[0] + n_moves, pos[1]) curr = list(start) def _next_move(pos, board): if board[pos[0]][pos[1]] == DIRT: return "CLEAN" closest = find_closest_dirt(pos, board) vector = [closest[0] - pos[0], closest[1] - pos[1]] dir = "" if vector[0]: dir = "DOWN" if vector[0] > 0 else "UP" else: dir = "RIGHT" if vector[1] > 0 else "LEFT" return dir
bot = 'b' empty = '-' dirt = 'd' def dist(pos1, pos2): return abs(pos1[0] - pos2[0]) + abs(pos1[1] - pos2[1]) def is_dirt(pos, board): if min(pos) < 0: return False if pos[0] >= len(board): return False if pos[1] >= len(board[0]): return False if board[pos[0]][pos[1]] != DIRT: return False return True def find_closest_dirt(pos, board, max_distance=0): if not max_distance: max_distance = len(board) + len(board[0]) n_moves = 1 start = (pos[0] + n_moves, pos[1]) curr = list(start) (dx, dy) = (-1, 1) while n_moves <= max_distance: if is_dirt(curr, board): return curr curr[0] += dx curr[1] += dy if curr[0] == pos[0]: dy = -dy if curr[1] == pos[1]: dx = -dx if curr == list(start): n_moves += 1 start = (pos[0] + n_moves, pos[1]) curr = list(start) def _next_move(pos, board): if board[pos[0]][pos[1]] == DIRT: return 'CLEAN' closest = find_closest_dirt(pos, board) vector = [closest[0] - pos[0], closest[1] - pos[1]] dir = '' if vector[0]: dir = 'DOWN' if vector[0] > 0 else 'UP' else: dir = 'RIGHT' if vector[1] > 0 else 'LEFT' return dir
SMALL = 1 MEDIUM = 2 LARGE = 3 ORDER_SIZE = ( (SMALL, u'Small'), (MEDIUM, u'Medium'), (LARGE, u'Large') ) MARGARITA = 1 MARINARA = 2 SALAMI = 3 ORDER_TITLE = ( (1, u'margarita'), (2, u'marinara'), (3, u'salami') ) RECEIVED = 1 IN_PROCESS = 2 OUT_FOR_DELIVERY = 3 DELIVERED = 4 RETURNED = 5 ORDER_STATUS = ( (RECEIVED, u'Received'), (IN_PROCESS, u'In Process'), (OUT_FOR_DELIVERY, u'Out For Delivery'), (DELIVERED, u'Delivered'), (RETURNED, u'Returned') )
small = 1 medium = 2 large = 3 order_size = ((SMALL, u'Small'), (MEDIUM, u'Medium'), (LARGE, u'Large')) margarita = 1 marinara = 2 salami = 3 order_title = ((1, u'margarita'), (2, u'marinara'), (3, u'salami')) received = 1 in_process = 2 out_for_delivery = 3 delivered = 4 returned = 5 order_status = ((RECEIVED, u'Received'), (IN_PROCESS, u'In Process'), (OUT_FOR_DELIVERY, u'Out For Delivery'), (DELIVERED, u'Delivered'), (RETURNED, u'Returned'))
def fatorial(n): num = 1 while n >= 1: num = num * n n = n - 1 return num digit = int(input('numero para mostra o fatorial ')) print(fatorial(digit))
def fatorial(n): num = 1 while n >= 1: num = num * n n = n - 1 return num digit = int(input('numero para mostra o fatorial ')) print(fatorial(digit))
#!/usr/bin/python3 cars = ['bmw', 'audi', 'toyota', 'subaru'] cars.sort() print(cars) cars.sort(reverse=True) print(cars) print("\nHere is the sorted list:") print(sorted(cars)) print("\nHere is the sorted list(reverse=True):") print(sorted(cars, reverse = True)) print("\nHere is the original list:") print(cars) print(len(cars))
cars = ['bmw', 'audi', 'toyota', 'subaru'] cars.sort() print(cars) cars.sort(reverse=True) print(cars) print('\nHere is the sorted list:') print(sorted(cars)) print('\nHere is the sorted list(reverse=True):') print(sorted(cars, reverse=True)) print('\nHere is the original list:') print(cars) print(len(cars))
# # PySNMP MIB module CISCO-CBP-TARGET-TC-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-CBP-TARGET-TC-MIB # Produced by pysmi-0.3.4 at Wed May 1 11:52:40 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") ValueRangeConstraint, ConstraintsIntersection, ValueSizeConstraint, SingleValueConstraint, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ConstraintsIntersection", "ValueSizeConstraint", "SingleValueConstraint", "ConstraintsUnion") ciscoMgmt, = mibBuilder.importSymbols("CISCO-SMI", "ciscoMgmt") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") Counter32, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, ModuleIdentity, IpAddress, NotificationType, Gauge32, Integer32, Unsigned32, iso, Bits, ObjectIdentity, MibIdentifier, Counter64 = mibBuilder.importSymbols("SNMPv2-SMI", "Counter32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "TimeTicks", "ModuleIdentity", "IpAddress", "NotificationType", "Gauge32", "Integer32", "Unsigned32", "iso", "Bits", "ObjectIdentity", "MibIdentifier", "Counter64") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") ciscoCbpTargetTCMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 9, 9, 511)) ciscoCbpTargetTCMIB.setRevisions(('2006-03-24 00:00',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: ciscoCbpTargetTCMIB.setRevisionsDescriptions(('Initial version.',)) if mibBuilder.loadTexts: ciscoCbpTargetTCMIB.setLastUpdated('200603240000Z') if mibBuilder.loadTexts: ciscoCbpTargetTCMIB.setOrganization('Cisco Systems, Inc.') if mibBuilder.loadTexts: ciscoCbpTargetTCMIB.setContactInfo(' Cisco Systems Customer Service Postal: 170 W. Tasman Drive San Jose, CA 95134-1706 USA Tel: +1 800 553-NETS E-mail: [email protected], [email protected]') if mibBuilder.loadTexts: ciscoCbpTargetTCMIB.setDescription('This MIB module defines Textual Conventions for representing targets which have class based policy mappings. A target can be any logical interface or entity to which a class based policy is able to be associated.') class CcbptTargetType(TextualConvention, Integer32): description = 'A Textual Convention that represents a type of target. genIf(1) A target of type interface defined by CcbptTargetIdIf Textual Convention. atmPvc(2) A target of type ATM PVC defined by the CcbptTargetIdAtmPvc Textual Convention. frDlci(3) A target of type Frame Relay DLCI defined by the CcbptTargetIdFrDlci Textual Convention. entity(4) A target of type entity defined by the CcbptTargetIdEntity Textual Convention. This target type is used to indicate the attachment of a Class Based Policy to a physical entity. fwZone(5) A target of type Firewall Security Zone defined by the CcbptTargetIdNameString Textual Convention. fwZonePair(6) A target of type Firewall Security Zone defined by the CcbptTargetIdNameString Textual Convention. aaaSession(7) A target of type AAA Session define by the CcbptTargetIdAaaSession Textual Convention. ' status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7)) namedValues = NamedValues(("genIf", 1), ("atmPvc", 2), ("frDlci", 3), ("entity", 4), ("fwZone", 5), ("fwZonePair", 6), ("aaaSession", 7)) class CcbptTargetDirection(TextualConvention, Integer32): description = 'A Textual Convention that represents a direction for a target. undirected(1) Indicates that direction has no meaning relative to the target. input(2) Refers to the input direction relative to the target. output(3) Refers to the output direction relative to the target. inOut(4) Refers to both the input and output directions relative to the target. ' status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4)) namedValues = NamedValues(("undirected", 1), ("input", 2), ("output", 3), ("inOut", 4)) class CcbptTargetId(TextualConvention, OctetString): description = 'Denotes a generic target ID. A CcbptTargetId value is always interpreted within the context of an CcbptTargetType value. Every usage of the CcbptTargetId Textual Convention is required to specify the CcbptTargetType object which provides the context. It is suggested that the CcbptTargetType object is logically registered before the object(s) which use the CcbptTargetId Textual Convention if they appear in the same logical row. The value of an CcbptTargetId object must always be consistent with the value of the associated CcbptTargetType object. Attempts to set a CcbptTargetId object to a value which is inconsistent with the associated targetType must fail with an inconsistentValue error. ' status = 'current' subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(0, 64) class CcbptTargetIdIf(TextualConvention, OctetString): description = 'Represents an interface target: octets contents encoding 1-4 ifIndex network-byte order ' status = 'current' displayHint = '4d' subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(4, 4) fixedLength = 4 class CcbptTargetIdAtmPvc(TextualConvention, OctetString): description = 'Represents an ATM PVC target: octets contents encoding 1-4 ifIndex network-byte order 5-6 atmVclVpi network-byte order 7-8 atmVclVci network-byte order ' status = 'current' displayHint = '4d:2d:2d' subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(8, 8) fixedLength = 8 class CcbptTargetIdFrDlci(TextualConvention, OctetString): description = 'Represents a Frame Relay DLCI target: octets contents encoding 1-4 ifIndex network-byte order 5-6 DlciNumber network-byte order ' status = 'current' displayHint = '4d:2d' subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(6, 6) fixedLength = 6 class CcbptTargetIdEntity(TextualConvention, OctetString): description = 'Represents the entPhysicalIndex of the physical entity target: octets contents encoding 1-4 entPhysicalIndex network-byte order ' status = 'current' displayHint = '4d' subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(4, 4) fixedLength = 4 class CcbptTargetIdNameString(TextualConvention, OctetString): description = 'Represents a target identified by a name string. This is the ASCII name identifying this target. ' status = 'current' subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(0, 64) class CcbptTargetIdAaaSession(TextualConvention, OctetString): description = 'Represents a AAA Session target: octets contents encoding 1-4 casnSessionId network-byte order ' status = 'current' displayHint = '4d' subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(4, 4) fixedLength = 4 class CcbptPolicySourceType(TextualConvention, Integer32): description = 'This Textual Convention represents the types of sources of policies. ciscoCbQos(1) Cisco Class Based QOS policy source. The source of the policy is Cisco Class Based QOS specific. ciscoCbpCommon(2) Cisco Common Class Based Policy type. The source of the policy is Cisco Common Class Based. ' status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2)) namedValues = NamedValues(("ciscoCbQos", 1), ("ciscoCbpBase", 2)) class CcbptPolicyIdentifier(TextualConvention, Unsigned32): description = 'A type specific, arbitrary identifier uniquely given to a policy-map attachment to a target. ' status = 'current' subtypeSpec = Unsigned32.subtypeSpec + ValueRangeConstraint(1, 4294967295) class CcbptPolicyIdentifierOrZero(TextualConvention, Unsigned32): description = 'This refers to CcbptPolicyIdentifier values, as applies, or 0. The behavior of the value of 0 should be described in the description of objects using this type. ' status = 'current' subtypeSpec = Unsigned32.subtypeSpec + ValueRangeConstraint(0, 4294967295) mibBuilder.exportSymbols("CISCO-CBP-TARGET-TC-MIB", PYSNMP_MODULE_ID=ciscoCbpTargetTCMIB, CcbptTargetIdEntity=CcbptTargetIdEntity, CcbptPolicySourceType=CcbptPolicySourceType, CcbptTargetDirection=CcbptTargetDirection, CcbptTargetIdAaaSession=CcbptTargetIdAaaSession, ciscoCbpTargetTCMIB=ciscoCbpTargetTCMIB, CcbptTargetIdIf=CcbptTargetIdIf, CcbptTargetIdFrDlci=CcbptTargetIdFrDlci, CcbptTargetId=CcbptTargetId, CcbptTargetIdNameString=CcbptTargetIdNameString, CcbptTargetType=CcbptTargetType, CcbptTargetIdAtmPvc=CcbptTargetIdAtmPvc, CcbptPolicyIdentifierOrZero=CcbptPolicyIdentifierOrZero, CcbptPolicyIdentifier=CcbptPolicyIdentifier)
(integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_range_constraint, constraints_intersection, value_size_constraint, single_value_constraint, constraints_union) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueRangeConstraint', 'ConstraintsIntersection', 'ValueSizeConstraint', 'SingleValueConstraint', 'ConstraintsUnion') (cisco_mgmt,) = mibBuilder.importSymbols('CISCO-SMI', 'ciscoMgmt') (module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup') (counter32, mib_scalar, mib_table, mib_table_row, mib_table_column, time_ticks, module_identity, ip_address, notification_type, gauge32, integer32, unsigned32, iso, bits, object_identity, mib_identifier, counter64) = mibBuilder.importSymbols('SNMPv2-SMI', 'Counter32', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'TimeTicks', 'ModuleIdentity', 'IpAddress', 'NotificationType', 'Gauge32', 'Integer32', 'Unsigned32', 'iso', 'Bits', 'ObjectIdentity', 'MibIdentifier', 'Counter64') (textual_convention, display_string) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'DisplayString') cisco_cbp_target_tcmib = module_identity((1, 3, 6, 1, 4, 1, 9, 9, 511)) ciscoCbpTargetTCMIB.setRevisions(('2006-03-24 00:00',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: ciscoCbpTargetTCMIB.setRevisionsDescriptions(('Initial version.',)) if mibBuilder.loadTexts: ciscoCbpTargetTCMIB.setLastUpdated('200603240000Z') if mibBuilder.loadTexts: ciscoCbpTargetTCMIB.setOrganization('Cisco Systems, Inc.') if mibBuilder.loadTexts: ciscoCbpTargetTCMIB.setContactInfo(' Cisco Systems Customer Service Postal: 170 W. Tasman Drive San Jose, CA 95134-1706 USA Tel: +1 800 553-NETS E-mail: [email protected], [email protected]') if mibBuilder.loadTexts: ciscoCbpTargetTCMIB.setDescription('This MIB module defines Textual Conventions for representing targets which have class based policy mappings. A target can be any logical interface or entity to which a class based policy is able to be associated.') class Ccbpttargettype(TextualConvention, Integer32): description = 'A Textual Convention that represents a type of target. genIf(1) A target of type interface defined by CcbptTargetIdIf Textual Convention. atmPvc(2) A target of type ATM PVC defined by the CcbptTargetIdAtmPvc Textual Convention. frDlci(3) A target of type Frame Relay DLCI defined by the CcbptTargetIdFrDlci Textual Convention. entity(4) A target of type entity defined by the CcbptTargetIdEntity Textual Convention. This target type is used to indicate the attachment of a Class Based Policy to a physical entity. fwZone(5) A target of type Firewall Security Zone defined by the CcbptTargetIdNameString Textual Convention. fwZonePair(6) A target of type Firewall Security Zone defined by the CcbptTargetIdNameString Textual Convention. aaaSession(7) A target of type AAA Session define by the CcbptTargetIdAaaSession Textual Convention. ' status = 'current' subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(1, 2, 3, 4, 5, 6, 7)) named_values = named_values(('genIf', 1), ('atmPvc', 2), ('frDlci', 3), ('entity', 4), ('fwZone', 5), ('fwZonePair', 6), ('aaaSession', 7)) class Ccbpttargetdirection(TextualConvention, Integer32): description = 'A Textual Convention that represents a direction for a target. undirected(1) Indicates that direction has no meaning relative to the target. input(2) Refers to the input direction relative to the target. output(3) Refers to the output direction relative to the target. inOut(4) Refers to both the input and output directions relative to the target. ' status = 'current' subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(1, 2, 3, 4)) named_values = named_values(('undirected', 1), ('input', 2), ('output', 3), ('inOut', 4)) class Ccbpttargetid(TextualConvention, OctetString): description = 'Denotes a generic target ID. A CcbptTargetId value is always interpreted within the context of an CcbptTargetType value. Every usage of the CcbptTargetId Textual Convention is required to specify the CcbptTargetType object which provides the context. It is suggested that the CcbptTargetType object is logically registered before the object(s) which use the CcbptTargetId Textual Convention if they appear in the same logical row. The value of an CcbptTargetId object must always be consistent with the value of the associated CcbptTargetType object. Attempts to set a CcbptTargetId object to a value which is inconsistent with the associated targetType must fail with an inconsistentValue error. ' status = 'current' subtype_spec = OctetString.subtypeSpec + value_size_constraint(0, 64) class Ccbpttargetidif(TextualConvention, OctetString): description = 'Represents an interface target: octets contents encoding 1-4 ifIndex network-byte order ' status = 'current' display_hint = '4d' subtype_spec = OctetString.subtypeSpec + value_size_constraint(4, 4) fixed_length = 4 class Ccbpttargetidatmpvc(TextualConvention, OctetString): description = 'Represents an ATM PVC target: octets contents encoding 1-4 ifIndex network-byte order 5-6 atmVclVpi network-byte order 7-8 atmVclVci network-byte order ' status = 'current' display_hint = '4d:2d:2d' subtype_spec = OctetString.subtypeSpec + value_size_constraint(8, 8) fixed_length = 8 class Ccbpttargetidfrdlci(TextualConvention, OctetString): description = 'Represents a Frame Relay DLCI target: octets contents encoding 1-4 ifIndex network-byte order 5-6 DlciNumber network-byte order ' status = 'current' display_hint = '4d:2d' subtype_spec = OctetString.subtypeSpec + value_size_constraint(6, 6) fixed_length = 6 class Ccbpttargetidentity(TextualConvention, OctetString): description = 'Represents the entPhysicalIndex of the physical entity target: octets contents encoding 1-4 entPhysicalIndex network-byte order ' status = 'current' display_hint = '4d' subtype_spec = OctetString.subtypeSpec + value_size_constraint(4, 4) fixed_length = 4 class Ccbpttargetidnamestring(TextualConvention, OctetString): description = 'Represents a target identified by a name string. This is the ASCII name identifying this target. ' status = 'current' subtype_spec = OctetString.subtypeSpec + value_size_constraint(0, 64) class Ccbpttargetidaaasession(TextualConvention, OctetString): description = 'Represents a AAA Session target: octets contents encoding 1-4 casnSessionId network-byte order ' status = 'current' display_hint = '4d' subtype_spec = OctetString.subtypeSpec + value_size_constraint(4, 4) fixed_length = 4 class Ccbptpolicysourcetype(TextualConvention, Integer32): description = 'This Textual Convention represents the types of sources of policies. ciscoCbQos(1) Cisco Class Based QOS policy source. The source of the policy is Cisco Class Based QOS specific. ciscoCbpCommon(2) Cisco Common Class Based Policy type. The source of the policy is Cisco Common Class Based. ' status = 'current' subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(1, 2)) named_values = named_values(('ciscoCbQos', 1), ('ciscoCbpBase', 2)) class Ccbptpolicyidentifier(TextualConvention, Unsigned32): description = 'A type specific, arbitrary identifier uniquely given to a policy-map attachment to a target. ' status = 'current' subtype_spec = Unsigned32.subtypeSpec + value_range_constraint(1, 4294967295) class Ccbptpolicyidentifierorzero(TextualConvention, Unsigned32): description = 'This refers to CcbptPolicyIdentifier values, as applies, or 0. The behavior of the value of 0 should be described in the description of objects using this type. ' status = 'current' subtype_spec = Unsigned32.subtypeSpec + value_range_constraint(0, 4294967295) mibBuilder.exportSymbols('CISCO-CBP-TARGET-TC-MIB', PYSNMP_MODULE_ID=ciscoCbpTargetTCMIB, CcbptTargetIdEntity=CcbptTargetIdEntity, CcbptPolicySourceType=CcbptPolicySourceType, CcbptTargetDirection=CcbptTargetDirection, CcbptTargetIdAaaSession=CcbptTargetIdAaaSession, ciscoCbpTargetTCMIB=ciscoCbpTargetTCMIB, CcbptTargetIdIf=CcbptTargetIdIf, CcbptTargetIdFrDlci=CcbptTargetIdFrDlci, CcbptTargetId=CcbptTargetId, CcbptTargetIdNameString=CcbptTargetIdNameString, CcbptTargetType=CcbptTargetType, CcbptTargetIdAtmPvc=CcbptTargetIdAtmPvc, CcbptPolicyIdentifierOrZero=CcbptPolicyIdentifierOrZero, CcbptPolicyIdentifier=CcbptPolicyIdentifier)
o = c50 = c20 = c10 = r = 0 while True: o = int(input('Quanto voce deseja sacar? ')) r = o while r >= 50: c50 += 1 r = r - 50 while r >= 20: c20 += 1 r = r - 20 while r > 10: c10 += 1 r = r - 10 if r < 10: break print(f'Para o valor de R$ {o}') if c50 >0: print(f'Foram emitidas {c50} cedulas de R$ 50') if c20>0: print(f'Foram emitidas {c20} cedulas de R$ 20') if c10>0: print(f'Foram emitidas {c10} cedulas de R$ 10') if r>0: print(f'Foram emitidas {r} cedulas de R$ 1')
o = c50 = c20 = c10 = r = 0 while True: o = int(input('Quanto voce deseja sacar? ')) r = o while r >= 50: c50 += 1 r = r - 50 while r >= 20: c20 += 1 r = r - 20 while r > 10: c10 += 1 r = r - 10 if r < 10: break print(f'Para o valor de R$ {o}') if c50 > 0: print(f'Foram emitidas {c50} cedulas de R$ 50') if c20 > 0: print(f'Foram emitidas {c20} cedulas de R$ 20') if c10 > 0: print(f'Foram emitidas {c10} cedulas de R$ 10') if r > 0: print(f'Foram emitidas {r} cedulas de R$ 1')
__version__ = "3.12.1" CTX_PROFILE = "PROFILE" CTX_DEFAULT_PROFILE = "default"
__version__ = '3.12.1' ctx_profile = 'PROFILE' ctx_default_profile = 'default'
class Query: def __init__(self, data, res={}): self.res = res self.data = data def clear(self): self.res = {} def get(self): return self.res def documentAtTime(self, query, model): self.data.clearScore() # pLists = {} query = query.split() queryTermCount = {} # pointer = {} for term in query: if term in queryTermCount: queryTermCount[term] += 1 else: queryTermCount[term] = 1 # def skipTo(maxDocId, pointer, term): # while pointer[term] < len(pLists[term]) and pLists[term][pointer[term]].getDocId() < maxDocId: # pointer[term] += 1 for doc in sorted(self.data.documents.values(), key=lambda x: x.docId): score = 0 for term in query: if doc.docId in self.data.invertedIndex.db[term] : score += model(term, doc, self.data, queryTermCount) doc.score = score return list(sorted(self.data.documents.values(), key=lambda x: x.score, reverse=True))
class Query: def __init__(self, data, res={}): self.res = res self.data = data def clear(self): self.res = {} def get(self): return self.res def document_at_time(self, query, model): self.data.clearScore() query = query.split() query_term_count = {} for term in query: if term in queryTermCount: queryTermCount[term] += 1 else: queryTermCount[term] = 1 for doc in sorted(self.data.documents.values(), key=lambda x: x.docId): score = 0 for term in query: if doc.docId in self.data.invertedIndex.db[term]: score += model(term, doc, self.data, queryTermCount) doc.score = score return list(sorted(self.data.documents.values(), key=lambda x: x.score, reverse=True))
''' __init__.py ColorPy is a Python package to convert physical descriptions of light: spectra of light intensity vs. wavelength - into RGB colors that can be drawn on a computer screen. It provides a nice set of attractive plots that you can make of such spectra, and some other color related functions as well. License: Copyright (C) 2008 Mark Kness Author - Mark Kness - [email protected] This file is part of ColorPy. ColorPy is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. ColorPy is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with ColorPy. If not, see <http://www.gnu.org/licenses/>. ''' # This file only needs to exist to indicate that this is a package.
""" __init__.py ColorPy is a Python package to convert physical descriptions of light: spectra of light intensity vs. wavelength - into RGB colors that can be drawn on a computer screen. It provides a nice set of attractive plots that you can make of such spectra, and some other color related functions as well. License: Copyright (C) 2008 Mark Kness Author - Mark Kness - [email protected] This file is part of ColorPy. ColorPy is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. ColorPy is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with ColorPy. If not, see <http://www.gnu.org/licenses/>. """
# run python from an operating system command prmpt # type the following: msg = "Hello World" print(msg) # write it into a file called hello.py # open a command prompt and type "python hello.py" # this should run the script and print "Hello World" # vscode alternative; Run the following in a terminal # by selecting the two lines and pressing Shift+Enter # vscode alternative 2; you can right click and select # "Run selection/line in Python terminal" from the context menu # You'll notice that the terminal window is still open, you can also type # code there that will be immediately interpreted (i.e. try a different message) # N.B. the underscore (this only makes sense on an interpreter command line) # an underscore represents the result of the last unassigned statement on the # command line: # 3 + 5 # print(_) <-- will be 8
msg = 'Hello World' print(msg)
# Backtracking # def totalNQueens(self, n: int) -> int: # diag1 = set() # diag2 = set() # used_cols = set() # # return self.helper(n, diag1, diag2, used_cols, 0) # # # def helper(self, n, diag1, diag2, used_cols, row): # if row == n: # return 1 # # solutions = 0 # # for col in range(n): # if row + col in diag1 or row - col in diag2 or col in used_cols: # continue # # diag1.add(row + col) # diag2.add(row - col) # used_cols.add(col) # # solutions += self.helper(n, diag1, diag2, used_cols, row + 1) # # diag1.remove(row + col) # diag2.remove(row - col) # used_cols.remove(col) # # return solutions # DFS def totalNQueens(self, n): self.res = 0 self.dfs([-1] * n, 0) return self.res def dfs(self, nums, index): if index == len(nums): self.res += 1 return # backtracking for i in range(len(nums)): nums[index] = i if self.valid(nums, index): self.dfs(nums, index + 1) def valid(self, nums, n): for i in range(n): if nums[i] == nums[n] or abs(nums[n] - nums[i]) == n - i: return False return True
def total_n_queens(self, n): self.res = 0 self.dfs([-1] * n, 0) return self.res def dfs(self, nums, index): if index == len(nums): self.res += 1 return for i in range(len(nums)): nums[index] = i if self.valid(nums, index): self.dfs(nums, index + 1) def valid(self, nums, n): for i in range(n): if nums[i] == nums[n] or abs(nums[n] - nums[i]) == n - i: return False return True
######################### # EECS1015: Lab 9 # Name: Mahfuz Rahman # Student ID: 217847518 # Email: [email protected] ######################### class MinMaxList: def __init__(self, initializeList): self.listData = initializeList self.listData.sort() def insertItem(self, item, printResult=False/True): if len(self.listData) == 0: # Inserting item if list is empty self.listData.append(item) print(f"Item ({item}) inserted at location 0") MinMaxList.printList(self) elif item >= self.listData[-1]: # Inserting item at the last index if item is largest in the list self.listData.append(item) print(f"Item ({item}) inserted at location {len(self.listData)-1}") MinMaxList.printList(self) else: for i in range(len(self.listData)+1): # Extracting each item in the list and comparing it if item <= self.listData[i]: self.listData.insert(i, item) if printResult == True: print(f"Item ({item}) inserted at location {i}") MinMaxList.printList(self) break def getMin(self): result = self.listData[0] del self.listData[0] return result def getMax(self): result = self.listData[-1] del self.listData[-1] return result def printList(self): print(self.listData)
class Minmaxlist: def __init__(self, initializeList): self.listData = initializeList self.listData.sort() def insert_item(self, item, printResult=False / True): if len(self.listData) == 0: self.listData.append(item) print(f'Item ({item}) inserted at location 0') MinMaxList.printList(self) elif item >= self.listData[-1]: self.listData.append(item) print(f'Item ({item}) inserted at location {len(self.listData) - 1}') MinMaxList.printList(self) else: for i in range(len(self.listData) + 1): if item <= self.listData[i]: self.listData.insert(i, item) if printResult == True: print(f'Item ({item}) inserted at location {i}') MinMaxList.printList(self) break def get_min(self): result = self.listData[0] del self.listData[0] return result def get_max(self): result = self.listData[-1] del self.listData[-1] return result def print_list(self): print(self.listData)
''' 1560. Most Visited Sector in a Circular Track Given an integer n and an integer array rounds. We have a circular track which consists of n sectors labeled from 1 to n. A marathon will be held on this track, the marathon consists of m rounds. The ith round starts at sector rounds[i - 1] and ends at sector rounds[i]. For example, round 1 starts at sector rounds[0] and ends at sector rounds[1] Return an array of the most visited sectors sorted in ascending order. Notice that you circulate the track in ascending order of sector numbers in the counter-clockwise direction (See the first example). Example 1: Input: n = 4, rounds = [1,3,1,2] Output: [1,2] Explanation: The marathon starts at sector 1. The order of the visited sectors is as follows: 1 --> 2 --> 3 (end of round 1) --> 4 --> 1 (end of round 2) --> 2 (end of round 3 and the marathon) We can see that both sectors 1 and 2 are visited twice and they are the most visited sectors. Sectors 3 and 4 are visited only once. Example 2: Input: n = 2, rounds = [2,1,2,1,2,1,2,1,2] Output: [2] Example 3: Input: n = 7, rounds = [1,3,5,7] Output: [1,2,3,4,5,6,7] Constraints: 2 <= n <= 100 1 <= m <= 100 rounds.length == m + 1 1 <= rounds[i] <= n rounds[i] != rounds[i + 1] for 0 <= i < m ''' class Solution: def mostVisited(self, n: int, rounds: List[int]) -> List[int]: arr = [0] * n for i in range(1, len(rounds)): end = rounds[i] beg = rounds[i-1] + ( 0 if i == 1 else 1 ) if end < beg: end = end + n for j in range(beg, end+1): arr[ j%n -1 ] += 1 # print( arr ) ret = [] maxNum = max(arr) for i in range(len(arr)): if arr[i] == maxNum: ret.append(i+1) return ret ''' 4 [1,3,1,2] 2 [2,1,2,1,2,1,2,1,2] 7 [1,3,5,7] '''
""" 1560. Most Visited Sector in a Circular Track Given an integer n and an integer array rounds. We have a circular track which consists of n sectors labeled from 1 to n. A marathon will be held on this track, the marathon consists of m rounds. The ith round starts at sector rounds[i - 1] and ends at sector rounds[i]. For example, round 1 starts at sector rounds[0] and ends at sector rounds[1] Return an array of the most visited sectors sorted in ascending order. Notice that you circulate the track in ascending order of sector numbers in the counter-clockwise direction (See the first example). Example 1: Input: n = 4, rounds = [1,3,1,2] Output: [1,2] Explanation: The marathon starts at sector 1. The order of the visited sectors is as follows: 1 --> 2 --> 3 (end of round 1) --> 4 --> 1 (end of round 2) --> 2 (end of round 3 and the marathon) We can see that both sectors 1 and 2 are visited twice and they are the most visited sectors. Sectors 3 and 4 are visited only once. Example 2: Input: n = 2, rounds = [2,1,2,1,2,1,2,1,2] Output: [2] Example 3: Input: n = 7, rounds = [1,3,5,7] Output: [1,2,3,4,5,6,7] Constraints: 2 <= n <= 100 1 <= m <= 100 rounds.length == m + 1 1 <= rounds[i] <= n rounds[i] != rounds[i + 1] for 0 <= i < m """ class Solution: def most_visited(self, n: int, rounds: List[int]) -> List[int]: arr = [0] * n for i in range(1, len(rounds)): end = rounds[i] beg = rounds[i - 1] + (0 if i == 1 else 1) if end < beg: end = end + n for j in range(beg, end + 1): arr[j % n - 1] += 1 ret = [] max_num = max(arr) for i in range(len(arr)): if arr[i] == maxNum: ret.append(i + 1) return ret ' \n4\n[1,3,1,2]\n2\n[2,1,2,1,2,1,2,1,2]\n7\n[1,3,5,7]\n'
while True: X, Y = map(int, input().split()) if X == 0 or Y == 0: break else: if X > 0 and Y > 0: print('primeiro') elif X > 0 and Y < 0: print('quarto') elif X < 0 and Y < 0: print('terceiro') else: print('segundo')
while True: (x, y) = map(int, input().split()) if X == 0 or Y == 0: break elif X > 0 and Y > 0: print('primeiro') elif X > 0 and Y < 0: print('quarto') elif X < 0 and Y < 0: print('terceiro') else: print('segundo')
# A Caesar cypher is a weak form on encryption: # It involves "rotating" each letter by a number (shift it through the alphabet) # # Example: # A rotated by 3 is D; Z rotated by 1 is A # In a SF movie the computer is called HAL, which is IBM rotated by -1 # # Our function rotate_word() uses: # ord (char to code_number) # chr (code to char) def encrypt(word, no): rotated = "" for i in range(len(word)): j = ord(word[i]) + no rotated = rotated + chr(j) return rotated def decrypt(word, no): return encrypt(word, -no) assert encrypt("abc", 3) == "def" # pass assert encrypt("IBM", -1) == "HAL" # pass assert decrypt("def", 3) == "abc" # pass assert decrypt("HAL", -1) == "IBM" # pass
def encrypt(word, no): rotated = '' for i in range(len(word)): j = ord(word[i]) + no rotated = rotated + chr(j) return rotated def decrypt(word, no): return encrypt(word, -no) assert encrypt('abc', 3) == 'def' assert encrypt('IBM', -1) == 'HAL' assert decrypt('def', 3) == 'abc' assert decrypt('HAL', -1) == 'IBM'
expected_output = { "chassis_mac_address": "4ce1.7592.a700", "mac_wait_time": "Indefinite", "redun_port_type": "FIBRE", "chassis_index": { 1: { "role": "Active", "mac_address": "4ce1.7592.a700", "priority": 2, "hw_version": "V02", "current_state": "Ready", "ip_address": "169.254.138.6", "rmi_ip": "10.8.138.6" }, 2: { "role": "Standby", "mac_address": "4ce1.7592.9000", "priority": 1, "hw_version": "V02", "current_state": "Ready", "ip_address": "169.254.138.7", "rmi_ip": "10.8.138.7" } } }
expected_output = {'chassis_mac_address': '4ce1.7592.a700', 'mac_wait_time': 'Indefinite', 'redun_port_type': 'FIBRE', 'chassis_index': {1: {'role': 'Active', 'mac_address': '4ce1.7592.a700', 'priority': 2, 'hw_version': 'V02', 'current_state': 'Ready', 'ip_address': '169.254.138.6', 'rmi_ip': '10.8.138.6'}, 2: {'role': 'Standby', 'mac_address': '4ce1.7592.9000', 'priority': 1, 'hw_version': 'V02', 'current_state': 'Ready', 'ip_address': '169.254.138.7', 'rmi_ip': '10.8.138.7'}}}
def read_instance(f): print(f) file = open(f) width = int(file.readline()) n_circuits = int(file.readline()) DX = [] DY = [] for i in range(n_circuits): piece = file.readline() split_piece = piece.strip().split(" ") DX.append(int(split_piece[0])) DY.append(int(split_piece[1])) return width, n_circuits, DX, DY def write_instance(width, n_circuits, DX, DY, out_path="./file.dzn"): file = open(out_path, mode="w") file.write(f"width = {width};\n") file.write(f"n = {n_circuits};\n") file.write(f"DX = {DX};\n") file.write(f"DY = {DY};") file.close()
def read_instance(f): print(f) file = open(f) width = int(file.readline()) n_circuits = int(file.readline()) dx = [] dy = [] for i in range(n_circuits): piece = file.readline() split_piece = piece.strip().split(' ') DX.append(int(split_piece[0])) DY.append(int(split_piece[1])) return (width, n_circuits, DX, DY) def write_instance(width, n_circuits, DX, DY, out_path='./file.dzn'): file = open(out_path, mode='w') file.write(f'width = {width};\n') file.write(f'n = {n_circuits};\n') file.write(f'DX = {DX};\n') file.write(f'DY = {DY};') file.close()
n = 1024 while n > 0: print(n) n //= 2
n = 1024 while n > 0: print(n) n //= 2
#!/usr/bin/env python3 title: str = 'Lady' name: str = 'Gaga' # Lady Gaga is an American actress, singer and songwriter. # String concatination at its worst print(title + ' ' + name + ' is an American actress, singer and songwriter.') # Legacy example print('%s %s is an American actress, singer and songwriter.' % (title, name)) # Python 3 (and 2.7) encourages str.format() function. print('{} {} is an American actress, singer and songwriter.'.format(title, name)) # noqa E501 print('{0} {1} is an American actress, singer and songwriter.'.format(title, name)) # noqa E501 print('{title} {name} is an American actress, singer and songwriter.'.format(title=title, name=name)) # noqa E501 print('{title} {name} is an American actress, singer and songwriter.'.format(name=name, title=title)) # noqa E501 # From Python 3.6 onwards you can use String interpolation aka f-strings. # So now, this is the recommended way to format strings. print(f'{title} {name} is an American actress, singer and songwriter.') # f-string also works with inline code six: int = 6 seven: int = 7 print(f'What do you get if you multiply {six} by {seven}?: {six * seven}')
title: str = 'Lady' name: str = 'Gaga' print(title + ' ' + name + ' is an American actress, singer and songwriter.') print('%s %s is an American actress, singer and songwriter.' % (title, name)) print('{} {} is an American actress, singer and songwriter.'.format(title, name)) print('{0} {1} is an American actress, singer and songwriter.'.format(title, name)) print('{title} {name} is an American actress, singer and songwriter.'.format(title=title, name=name)) print('{title} {name} is an American actress, singer and songwriter.'.format(name=name, title=title)) print(f'{title} {name} is an American actress, singer and songwriter.') six: int = 6 seven: int = 7 print(f'What do you get if you multiply {six} by {seven}?: {six * seven}')
class Solution: def mySqrt(self, x: int) -> int: if x == 0: return 0 ans: float = x tolerance = 0.00000001 while abs(ans - x/ans) > tolerance: ans = (ans + x/ans) / 2 return int(ans) tests = [ ( (4,), 2, ), ( (8,), 2, ), ]
class Solution: def my_sqrt(self, x: int) -> int: if x == 0: return 0 ans: float = x tolerance = 1e-08 while abs(ans - x / ans) > tolerance: ans = (ans + x / ans) / 2 return int(ans) tests = [((4,), 2), ((8,), 2)]
if traffic_light == 'green': pass # to implement else: stop()
if traffic_light == 'green': pass else: stop()
if window.get_active_title() == "Terminal": keyboard.send_keys("<super>+z") else: keyboard.send_keys("<ctrl>+z")
if window.get_active_title() == 'Terminal': keyboard.send_keys('<super>+z') else: keyboard.send_keys('<ctrl>+z')
def naive_4() : it = 0 def get_w() : fan_in = 1 fan_out = 1 limit = np.sqrt(6 / (fan_in + fan_out)) return np.random.uniform(low =-limit , high = limit , size = (784 , 10)) w_init = get_w() b_init = np,zeros(shape(10,)) last_score = 0.0 learnin_rate = 0.1 while True : w = w_init + learning_rate * get_w() model.set_weights(weights = [w,b_init] ) score = mode.evalute(x_test ,y_test , verbose = 0 ) [1] if score > last_score : w_init = w last_sccore = score print(it , "Best Acc" , score ) score = model.evalute(x_test , y_test , verbose = 0 ) [1] if score > last_score : b_init = b last_sccore = score print(it , "Best Acc" , score ) it +=1
def naive_4(): it = 0 def get_w(): fan_in = 1 fan_out = 1 limit = np.sqrt(6 / (fan_in + fan_out)) return np.random.uniform(low=-limit, high=limit, size=(784, 10)) w_init = get_w() b_init = (np, zeros(shape(10))) last_score = 0.0 learnin_rate = 0.1 while True: w = w_init + learning_rate * get_w() model.set_weights(weights=[w, b_init]) score = mode.evalute(x_test, y_test, verbose=0)[1] if score > last_score: w_init = w last_sccore = score print(it, 'Best Acc', score) score = model.evalute(x_test, y_test, verbose=0)[1] if score > last_score: b_init = b last_sccore = score print(it, 'Best Acc', score) it += 1
n = int(input()) for _ in range(n): recording = input() sounds = [] s = input() while s != "what does the fox say?": sounds.append(s.split(' ')[-1]) s = input() fox_says = "" for sound in recording.split(' '): if sound not in sounds: fox_says += " " + sound print(fox_says.strip())
n = int(input()) for _ in range(n): recording = input() sounds = [] s = input() while s != 'what does the fox say?': sounds.append(s.split(' ')[-1]) s = input() fox_says = '' for sound in recording.split(' '): if sound not in sounds: fox_says += ' ' + sound print(fox_says.strip())
count = 0 while count != 5: count += 1 print(count) print('--------') counter = 0 while counter <= 20: counter = counter + 3 print(counter) print('--------') countersito = 20 while countersito >= 0: countersito -= 3 print(countersito)
count = 0 while count != 5: count += 1 print(count) print('--------') counter = 0 while counter <= 20: counter = counter + 3 print(counter) print('--------') countersito = 20 while countersito >= 0: countersito -= 3 print(countersito)
def netmiko_command(device, command=None, ckwargs={}, **kwargs): if command: output = device['nc'].send_command(command, **ckwargs) else: output = 'No command to run.' return output
def netmiko_command(device, command=None, ckwargs={}, **kwargs): if command: output = device['nc'].send_command(command, **ckwargs) else: output = 'No command to run.' return output
# ---------------------------------------------------------------------- # # Brad T. Aagaard, U.S. Geological Survey # # This code was developed as part of the Computational Infrastructure # for Geodynamics (http://geodynamics.org). # # Copyright (c) 2010-2017 University of California, Davis # # See COPYING for license information. # # ---------------------------------------------------------------------- # # @file spatialdata/geocoords/__init__.py # # @brief Python spatialdata geocoords module initialization. __all__ = [ 'CoordSys', 'CSCart', 'CSGeo', 'Converter', ] # End of file
__all__ = ['CoordSys', 'CSCart', 'CSGeo', 'Converter']
######## # PART 1 def read(filename): with open("event2021/day25/" + filename, "r") as file: rows = [line.strip() for line in file.readlines()] return [ch for row in rows for ch in row], len(rows[0]), len(rows) def draw(region_data): region, width, height = region_data for y in range(height): for x in range(width): print(region[(y * width) + x], end="") print() print() def find_standstill(region_data, debug = False, should_draw = None, max_steps = -1): region, width, height = region_data steps = 0 while True: if debug: print("step", steps) if should_draw and should_draw(steps): draw((region, width, height)) if steps == max_steps: return None stepped = False new_region = region[:] for y in range(height): for x in range(width): ch = region[(y * width) + x] if ch == '>': if region[(y * width) + ((x + 1) % width)] == '.': new_region[(y * width) + x] = '.' new_region[(y * width) + ((x + 1) % width)] = '>' stepped = True region = new_region new_region = region[:] for y in range(height): for x in range(width): ch = region[(y * width) + x] if ch == 'v': if region[((y + 1) % height) * width + x] == '.': new_region[(y * width) + x] = '.' new_region[((y + 1) % height) * width + x] = 'v' stepped = True steps += 1 if not stepped: break region = new_region return steps #ex1 = read("example1.txt") #find_standstill(ex1, True, lambda _: True, max_steps=4) ex2 = read("example2.txt") assert find_standstill(ex2, True, lambda x: x in [0, 1, 2, 3, 4, 5, 10, 20, 30, 40, 50, 55, 56, 57, 58, 59], 60) == 58 inp = read("input.txt") answer = find_standstill(inp) print("Part 1 =", answer) assert answer == 456 # check with accepted answer
def read(filename): with open('event2021/day25/' + filename, 'r') as file: rows = [line.strip() for line in file.readlines()] return ([ch for row in rows for ch in row], len(rows[0]), len(rows)) def draw(region_data): (region, width, height) = region_data for y in range(height): for x in range(width): print(region[y * width + x], end='') print() print() def find_standstill(region_data, debug=False, should_draw=None, max_steps=-1): (region, width, height) = region_data steps = 0 while True: if debug: print('step', steps) if should_draw and should_draw(steps): draw((region, width, height)) if steps == max_steps: return None stepped = False new_region = region[:] for y in range(height): for x in range(width): ch = region[y * width + x] if ch == '>': if region[y * width + (x + 1) % width] == '.': new_region[y * width + x] = '.' new_region[y * width + (x + 1) % width] = '>' stepped = True region = new_region new_region = region[:] for y in range(height): for x in range(width): ch = region[y * width + x] if ch == 'v': if region[(y + 1) % height * width + x] == '.': new_region[y * width + x] = '.' new_region[(y + 1) % height * width + x] = 'v' stepped = True steps += 1 if not stepped: break region = new_region return steps ex2 = read('example2.txt') assert find_standstill(ex2, True, lambda x: x in [0, 1, 2, 3, 4, 5, 10, 20, 30, 40, 50, 55, 56, 57, 58, 59], 60) == 58 inp = read('input.txt') answer = find_standstill(inp) print('Part 1 =', answer) assert answer == 456
# This sample tests the "reportPrivateUsage" feature. class _TestClass(object): pass class TestClass(object): def __init__(self): self._priv1 = 1
class _Testclass(object): pass class Testclass(object): def __init__(self): self._priv1 = 1
class Solution: def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]: ''' min_list = [] for i in range(len(nums)): count = 0 for j in range(len(nums)): if nums[j] < nums[i]: count = count + 1 min_list.append(count) return min_list ''' min_list = sorted(nums) # index method returns the first match of i return [min_list.index(i) for i in nums]
class Solution: def smaller_numbers_than_current(self, nums: List[int]) -> List[int]: """ min_list = [] for i in range(len(nums)): count = 0 for j in range(len(nums)): if nums[j] < nums[i]: count = count + 1 min_list.append(count) return min_list """ min_list = sorted(nums) return [min_list.index(i) for i in nums]
# def parse_ranges(input_string): # # output = [] # ranges = [item.strip() for item in input_string.split(',')] # # for item in ranges: # start, end = [int(i) for i in item.split('-')] # output.extend(range(start, end + 1)) # # return output # def parse_ranges(input_string): # # ranges = [item.strip() for item in input_string.split(',')] # # for item in ranges: # start, end = [int(i) for i in item.split('-')] # yield from range(start, end + 1) # def parse_ranges(input_string): # # ranges = [range_.strip() for range_ in input_string.split(',')] # # for item in ranges: # if '-' in item: # start, end = [int(i) for i in item.split('-')] # yield from range(start, end + 1) # else: # yield int(item) def parse_ranges(input_string): ranges = [range_.strip() for range_ in input_string.split(',')] for item in ranges: if '->' in item: yield int(item.split('-')[0]) elif '-' in item: start, end = [int(i) for i in item.split('-')] yield from range(start, end + 1) else: yield int(item)
def parse_ranges(input_string): ranges = [range_.strip() for range_ in input_string.split(',')] for item in ranges: if '->' in item: yield int(item.split('-')[0]) elif '-' in item: (start, end) = [int(i) for i in item.split('-')] yield from range(start, end + 1) else: yield int(item)
for row in range(4): for col in range(4): if col%3==0 and row<3 or row==3 and col>0: print('*', end = ' ') else: print(' ', end = ' ') print()
for row in range(4): for col in range(4): if col % 3 == 0 and row < 3 or (row == 3 and col > 0): print('*', end=' ') else: print(' ', end=' ') print()
def power(integer1, integer2=3): result = 1 for i in range(integer2): result = result * integer1 return result print(power(3)) print(power(3,2))
def power(integer1, integer2=3): result = 1 for i in range(integer2): result = result * integer1 return result print(power(3)) print(power(3, 2))
#The values G,m1,m2,f and d stands for Gravitational constant, initial mass,final mass,force and distance respectively G = 6.67 * 10 ** -11 m1 = float(input("The value of the initial mass: ")) m2 = float(input("The value of the final mass: ")) d = float(input("The distance between the bodies: ")) F = (G * m1 * m2)/(d ** 2) print("The magnitude of the attractive force: " ,F)
g = 6.67 * 10 ** (-11) m1 = float(input('The value of the initial mass: ')) m2 = float(input('The value of the final mass: ')) d = float(input('The distance between the bodies: ')) f = G * m1 * m2 / d ** 2 print('The magnitude of the attractive force: ', F)
# Copyright (c) 2019-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # def f_gold ( arr , n ) : s = [ ] j = 0 ans = 0 for i in range ( n ) : while ( j < n and ( arr [ j ] not in s ) ) : s.append ( arr [ j ] ) j += 1 ans += ( ( j - i ) * ( j - i + 1 ) ) // 2 s.remove ( arr [ i ] ) return ans #TOFILL if __name__ == '__main__': param = [ ([3, 4, 5, 6, 12, 15, 16, 17, 20, 20, 22, 24, 24, 27, 28, 34, 37, 39, 39, 41, 43, 49, 49, 51, 55, 62, 63, 67, 71, 74, 74, 74, 77, 84, 84, 89, 89, 97, 99],24,), ([-8, 54, -22, 18, 20, 44, 0, 54, 90, -4, 4, 40, -74, -16],13,), ([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],28,), ([36, 71, 36, 58, 38, 90, 17],4,), ([-90, -32, -16, 18, 38, 82],5,), ([1, 0, 1],2,), ([3, 11, 21, 25, 28, 28, 38, 42, 48, 53, 55, 55, 55, 58, 71, 75, 79, 80, 80, 94, 96, 99],20,), ([-16, -52, -4, -46, 54, 0, 8, -64, -82, -10, -62, -10, 58, 44, -28, 86, -24, 16, 44, 22, -28, -42, -52, 8, 76, -44, -34, 2, 88, -88, -14, -84, -36, -68, 76, 20, 20, -50],35,), ([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],27,), ([19, 13, 61, 32, 92, 90, 12, 81, 52],5,) ] n_success = 0 for i, parameters_set in enumerate(param): if f_filled(*parameters_set) == f_gold(*parameters_set): n_success+=1 print("#Results: %i, %i" % (n_success, len(param)))
def f_gold(arr, n): s = [] j = 0 ans = 0 for i in range(n): while j < n and arr[j] not in s: s.append(arr[j]) j += 1 ans += (j - i) * (j - i + 1) // 2 s.remove(arr[i]) return ans if __name__ == '__main__': param = [([3, 4, 5, 6, 12, 15, 16, 17, 20, 20, 22, 24, 24, 27, 28, 34, 37, 39, 39, 41, 43, 49, 49, 51, 55, 62, 63, 67, 71, 74, 74, 74, 77, 84, 84, 89, 89, 97, 99], 24), ([-8, 54, -22, 18, 20, 44, 0, 54, 90, -4, 4, 40, -74, -16], 13), ([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], 28), ([36, 71, 36, 58, 38, 90, 17], 4), ([-90, -32, -16, 18, 38, 82], 5), ([1, 0, 1], 2), ([3, 11, 21, 25, 28, 28, 38, 42, 48, 53, 55, 55, 55, 58, 71, 75, 79, 80, 80, 94, 96, 99], 20), ([-16, -52, -4, -46, 54, 0, 8, -64, -82, -10, -62, -10, 58, 44, -28, 86, -24, 16, 44, 22, -28, -42, -52, 8, 76, -44, -34, 2, 88, -88, -14, -84, -36, -68, 76, 20, 20, -50], 35), ([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], 27), ([19, 13, 61, 32, 92, 90, 12, 81, 52], 5)] n_success = 0 for (i, parameters_set) in enumerate(param): if f_filled(*parameters_set) == f_gold(*parameters_set): n_success += 1 print('#Results: %i, %i' % (n_success, len(param)))
var1 = 6 var2 = 3 if var1 >= 10: print("Bigger than 10") #mind about the indent here (can be created by pressing tab button) else: print("Smaller or equal to 10") # all the codes written under a section wth tab belongs to that section if var1 == var2: print("var1 and 2 are equal") else: print("not equal") if var1 > 5 and var1 < 7: print("Between") elif var1 <= 5: print("Smaller than 5") else: print("Bigger than or equal to 7") if var1 > 5: if var2 < 5: print("in good condition") else: print("var2 breaks the condition") else: print("var1 breaks the condition")
var1 = 6 var2 = 3 if var1 >= 10: print('Bigger than 10') else: print('Smaller or equal to 10') if var1 == var2: print('var1 and 2 are equal') else: print('not equal') if var1 > 5 and var1 < 7: print('Between') elif var1 <= 5: print('Smaller than 5') else: print('Bigger than or equal to 7') if var1 > 5: if var2 < 5: print('in good condition') else: print('var2 breaks the condition') else: print('var1 breaks the condition')
class KNN(): def fit(self, X_train, y_train): self.X_train = X_train self.y_train = y_train def predict(self, X_test, k=3): predictions = np.zeros(X_test.shape[0]) for i, point in enumerate(X_test): distances = self._get_distances(point) k_nearest = self._get_k_nearest(distances, k) prediction = self._get_predicted_value(k_nearest) predictions[i] = prediction return predictions #helper functions def _get_distances(self, x): '''Take an single point and return an array of distances to every point in our dataset''' distances = np.zeros(self.X_train.shape[0]) for i, point in enumerate(self.X_train): distances[i] = euc(x, point) return distances def _get_k_nearest(self, distances, k): '''Take in the an array of distances and return the indices of the k nearest points''' nearest = np.argsort(distances)[:k] return nearest def _get_predicted_value(self, k_nearest): '''Takes in the indices of the k nearest points and returns the mean of their target values''' return np.mean(self.y_train[k_nearest])
class Knn: def fit(self, X_train, y_train): self.X_train = X_train self.y_train = y_train def predict(self, X_test, k=3): predictions = np.zeros(X_test.shape[0]) for (i, point) in enumerate(X_test): distances = self._get_distances(point) k_nearest = self._get_k_nearest(distances, k) prediction = self._get_predicted_value(k_nearest) predictions[i] = prediction return predictions def _get_distances(self, x): """Take an single point and return an array of distances to every point in our dataset""" distances = np.zeros(self.X_train.shape[0]) for (i, point) in enumerate(self.X_train): distances[i] = euc(x, point) return distances def _get_k_nearest(self, distances, k): """Take in the an array of distances and return the indices of the k nearest points""" nearest = np.argsort(distances)[:k] return nearest def _get_predicted_value(self, k_nearest): """Takes in the indices of the k nearest points and returns the mean of their target values""" return np.mean(self.y_train[k_nearest])
__title__ = 'alpha-vantage-py' __description__ = 'Alpha Vantage Python package.' __url__ = 'https://github.com/wstolk/alpha-vantage' __version__ = '0.0.4' __build__ = 0x022501 __author__ = 'Wouter Stolk' __author_email__ = '[email protected]' __license__ = 'Apache 2.0' __copyright__ = 'Copyright 2021 Wouter Stolk' __cake__ = u'\u2728 \U0001f370 \u2728'
__title__ = 'alpha-vantage-py' __description__ = 'Alpha Vantage Python package.' __url__ = 'https://github.com/wstolk/alpha-vantage' __version__ = '0.0.4' __build__ = 140545 __author__ = 'Wouter Stolk' __author_email__ = '[email protected]' __license__ = 'Apache 2.0' __copyright__ = 'Copyright 2021 Wouter Stolk' __cake__ = u'✨ 🍰 ✨'
LANGUAGES = [ {"English": "English", "alpha2": "en"}, {"English": "Italian", "alpha2": "it"}, ]
languages = [{'English': 'English', 'alpha2': 'en'}, {'English': 'Italian', 'alpha2': 'it'}]
def max_profit(prices) -> int: if not prices: return 0 minPrice = prices[0] maxPrice = 0 for i in range(1, len(prices)): minPrice = min(prices[i], minPrice) maxPrice = max(prices[i],maxPrice) return maxPrice arr = [100, 180, 260, 310, 40, 535, 695] print(max_profit(arr))
def max_profit(prices) -> int: if not prices: return 0 min_price = prices[0] max_price = 0 for i in range(1, len(prices)): min_price = min(prices[i], minPrice) max_price = max(prices[i], maxPrice) return maxPrice arr = [100, 180, 260, 310, 40, 535, 695] print(max_profit(arr))
# Paula Daly Solution to Problem 4 March 2019 # Collatz - particular sequence always reaches 1 # Defining the function def collatz(number): # looping through and if number found is even divide it by 2 if number % 2 == 0: print(number // 2) return number // 2 # looping through and if the number is odd multiply it by 3 and add 1 elif number % 2 != 0: result = 3 * number + 1 print(result) return result try: # ask the user to enter a number n = input("Enter number: ") # running the function while n != 1: n = collatz(int(n)) # what to do if the user inputs a negative integer except ValueError: print('Please enter a positive integer')
def collatz(number): if number % 2 == 0: print(number // 2) return number // 2 elif number % 2 != 0: result = 3 * number + 1 print(result) return result try: n = input('Enter number: ') while n != 1: n = collatz(int(n)) except ValueError: print('Please enter a positive integer')
class ConfigBase: def __init__(self): self.zookeeper = "" self.brokers = "" self.topic = "" def __str__(self): return str(self.zookeeper + ";" + self.brokers + ";" + self.topic) def set_zookeeper(self, conf): self.zookeeper = conf def set_brokers(self, conf): self.brokers = conf def set_topic(self, conf): self.topic = conf
class Configbase: def __init__(self): self.zookeeper = '' self.brokers = '' self.topic = '' def __str__(self): return str(self.zookeeper + ';' + self.brokers + ';' + self.topic) def set_zookeeper(self, conf): self.zookeeper = conf def set_brokers(self, conf): self.brokers = conf def set_topic(self, conf): self.topic = conf
''' Created on May 13, 2016 @author: david ''' if __name__ == '__main__': pass
""" Created on May 13, 2016 @author: david """ if __name__ == '__main__': pass
# numbers_list = [int(x) for x in input().split(", ")] def find_sum(numbers_list): result = 1 for i in range(len(numbers_list)): number = numbers_list[i] if number <= 5: result *= number elif number <= 10: result /= number return result print(find_sum([1, 4, 5]), 20) print(find_sum([4, 5, 6, 1, 3]), 20) print(find_sum([2, 5, 10]), 20)
def find_sum(numbers_list): result = 1 for i in range(len(numbers_list)): number = numbers_list[i] if number <= 5: result *= number elif number <= 10: result /= number return result print(find_sum([1, 4, 5]), 20) print(find_sum([4, 5, 6, 1, 3]), 20) print(find_sum([2, 5, 10]), 20)
# post to the array-connections/connection-key endpoint to get a connection key res = client.post_array_connections_connection_key() print(res) if type(res) == pypureclient.responses.ValidResponse: print(list(res.items))
res = client.post_array_connections_connection_key() print(res) if type(res) == pypureclient.responses.ValidResponse: print(list(res.items))
BOT_CONFIG = 'default' CONFIGS_DIR_NAME = 'configs' BOTS_LOG_ROOT = 'bots' LOG_FILE = 'bots.log' LOOP_INTERVAL = 60 SETTINGS = 'settings.yml,secrets.yml' VERBOSITY = 1
bot_config = 'default' configs_dir_name = 'configs' bots_log_root = 'bots' log_file = 'bots.log' loop_interval = 60 settings = 'settings.yml,secrets.yml' verbosity = 1
class BotLogic: def BotExit(Nachricht): print("Say Goodbye to the Bot") # Beim Bot abmelden def BotStart(Nachricht): print("Say Hello to the Bot") # Beim Bot anmelden
class Botlogic: def bot_exit(Nachricht): print('Say Goodbye to the Bot') def bot_start(Nachricht): print('Say Hello to the Bot')
# class => module MODULE_MAP = { 'ShuffleRerankPlugin': 'plugins.rerank.shuffle', 'PtTransformersRerankPlugin': 'plugins.rerank.transformers', 'PtDistilBertQAModelPlugin': 'plugins.qa.distilbert' } # image => directory IMAGE_MAP = { 'alpine': '../Dockerfiles/alpine', 'pt': '../Dockerfiles/pt' } INDEXER_MAP = { 'ESIndexer': 'indexers.es' }
module_map = {'ShuffleRerankPlugin': 'plugins.rerank.shuffle', 'PtTransformersRerankPlugin': 'plugins.rerank.transformers', 'PtDistilBertQAModelPlugin': 'plugins.qa.distilbert'} image_map = {'alpine': '../Dockerfiles/alpine', 'pt': '../Dockerfiles/pt'} indexer_map = {'ESIndexer': 'indexers.es'}
''' This file was used in an earlier version; geodata does not currently use SQLAlchemy. --- This file ensures all other files use the same SQLAlchemy session and Base. Other files should import engine, session, and Base when needed. Use: from initialize_sqlalchemy import Base, session, engine ''' # # The engine # from sqlalchemy import create_engine # engine = create_engine('sqlite:///:memory:') # # The session # from sqlalchemy.orm import sessionmaker # Session = sessionmaker(bind=engine) # session = Session() # # The Base # from sqlalchemy.ext.declarative import declarative_base # Base = declarative_base()
""" This file was used in an earlier version; geodata does not currently use SQLAlchemy. --- This file ensures all other files use the same SQLAlchemy session and Base. Other files should import engine, session, and Base when needed. Use: from initialize_sqlalchemy import Base, session, engine """
# The authors of this work have released all rights to it and placed it # in the public domain under the Creative Commons CC0 1.0 waiver # (http://creativecommons.org/publicdomain/zero/1.0/). # # 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. # # Retrieved from: http://en.literateprograms.org/Generating_all_integer_lattice_points_(Python)?oldid=17065 # Modified for VLC project '''Code for creating mappings that are used to place symbols in the matrix.''' def _distance(p): return p[0]**2 + p[1]**2 def _may_use(vu, shape): '''Returns true if the entry v, u may be used in a conjugate symmetric matrix. In other words, the function returns false for v, u pairs that must be their own conjugate. These pairs cannot be used to store complex symbols. `shape` is the shape of the matrix into which the symbols are packed. ''' n, m = shape m = (m/2) + 1 v, u = vu if v < 0: v = n+v # May not use DC component if u == 0 and v == 0: return False # May not use lower half of 0 colument max_v_u0 = n/2 if n % 2 == 1 else n/2-1 if u == 0 and v > max_v_u0: return False # Perform some additional bounds checking here. # Raise an exception if the check fails, as it is # a programming error. max_u = m-1 if shape[1] % 2 == 1 else m-2 if u > max_u: raise IndexError('Mapping tries to set illegal entry. ' '(Are you trying to pack too many symbols?)') return True def halfring_generator(shape, limit=None): '''Generates a sequence of (v,u) tuples that describe a halfring.''' # TODO Bounds checking for the shape ymax = [0] d = 0 while limit is None or d <= limit: yieldable = [] while 1: batch = [] for x in range(d+1): y = ymax[x] if _distance((x, y)) <= d**2: # Note: distance squared batch.append((y, x)) if y != 0: batch.append((-y, x)) ymax[x] += 1 if not batch: break yieldable += batch yieldable.sort(key=_distance) for p in yieldable: if _may_use(p, shape): yield p d += 1 ymax.append(0) # Extend to make room for column[d] def halfring(n, shape): '''Returns a list (v,u) tuples that describe a halfring.''' g = halfring_generator(shape) return [next(g) for _ in xrange(n)]
"""Code for creating mappings that are used to place symbols in the matrix.""" def _distance(p): return p[0] ** 2 + p[1] ** 2 def _may_use(vu, shape): """Returns true if the entry v, u may be used in a conjugate symmetric matrix. In other words, the function returns false for v, u pairs that must be their own conjugate. These pairs cannot be used to store complex symbols. `shape` is the shape of the matrix into which the symbols are packed. """ (n, m) = shape m = m / 2 + 1 (v, u) = vu if v < 0: v = n + v if u == 0 and v == 0: return False max_v_u0 = n / 2 if n % 2 == 1 else n / 2 - 1 if u == 0 and v > max_v_u0: return False max_u = m - 1 if shape[1] % 2 == 1 else m - 2 if u > max_u: raise index_error('Mapping tries to set illegal entry. (Are you trying to pack too many symbols?)') return True def halfring_generator(shape, limit=None): """Generates a sequence of (v,u) tuples that describe a halfring.""" ymax = [0] d = 0 while limit is None or d <= limit: yieldable = [] while 1: batch = [] for x in range(d + 1): y = ymax[x] if _distance((x, y)) <= d ** 2: batch.append((y, x)) if y != 0: batch.append((-y, x)) ymax[x] += 1 if not batch: break yieldable += batch yieldable.sort(key=_distance) for p in yieldable: if _may_use(p, shape): yield p d += 1 ymax.append(0) def halfring(n, shape): """Returns a list (v,u) tuples that describe a halfring.""" g = halfring_generator(shape) return [next(g) for _ in xrange(n)]
class EntityForm(django.forms.ModelForm): class Meta: model = Entity exclude = (u'homepage', u'image')
class Entityform(django.forms.ModelForm): class Meta: model = Entity exclude = (u'homepage', u'image')
''' Simpler to just do the math than iterating. Break each number from 1 to 20 into its prime components. The find the maximum times each unique prime occurs in any of the numbers. Include the prime that number of times. For instance, 9 is ( 3 * 3 ) and 18 is ( 3 * 3 * 2 ), both of which are the most number of times 3 shows up. So include 3 twice. Cheaper to do so using 9 since we already get a 2 from other numbers. This works since primes can be recombined to form any of the numbers, but you need to have enough of the primes to actually do so. You can use 5 and 2 to make 10, but you need to include another 2 to make 20, for instance. ''' print(16 * 17 * 5 * 13 * 9 * 11 * 19 * 7) # 232792560 # print( # (2 * 2 * 2 * 2) * (17) * (5) * (13) * (3 * 3) * (11) * (19) * (7) # )
""" Simpler to just do the math than iterating. Break each number from 1 to 20 into its prime components. The find the maximum times each unique prime occurs in any of the numbers. Include the prime that number of times. For instance, 9 is ( 3 * 3 ) and 18 is ( 3 * 3 * 2 ), both of which are the most number of times 3 shows up. So include 3 twice. Cheaper to do so using 9 since we already get a 2 from other numbers. This works since primes can be recombined to form any of the numbers, but you need to have enough of the primes to actually do so. You can use 5 and 2 to make 10, but you need to include another 2 to make 20, for instance. """ print(16 * 17 * 5 * 13 * 9 * 11 * 19 * 7)
n, k = map(int, input().split()) arr = list(map(int, input().split())) arr_find = list(map(int, input().split())) def bin_search(arr, el): left = -1 right = len(arr) while right - left > 1: mid = (right + left) // 2 if arr[mid] >= el: right = mid else: left = mid return left, right for el in arr_find: left, right = bin_search(arr, el) print(left, right) if arr[left] == el: print('YES') else: print('NO')
(n, k) = map(int, input().split()) arr = list(map(int, input().split())) arr_find = list(map(int, input().split())) def bin_search(arr, el): left = -1 right = len(arr) while right - left > 1: mid = (right + left) // 2 if arr[mid] >= el: right = mid else: left = mid return (left, right) for el in arr_find: (left, right) = bin_search(arr, el) print(left, right) if arr[left] == el: print('YES') else: print('NO')
n = int(input()) current = 1 bigger = False for i in range(1, n + 1): for j in range(1, i + 1): if current > n: bigger = True break print(str(current) + " ", end="") current += 1 if bigger: break print()
n = int(input()) current = 1 bigger = False for i in range(1, n + 1): for j in range(1, i + 1): if current > n: bigger = True break print(str(current) + ' ', end='') current += 1 if bigger: break print()
n = int(input()) d = list() for i in range(2): k=list(map(int,input().split())) d.append(k) c = list(zip(*d)) p = [] for i in range(len(c)): p.append(c[i][0] * c[i][1]) number=sum(p)/sum(d[1]) print("{:.1f}".format(number))
n = int(input()) d = list() for i in range(2): k = list(map(int, input().split())) d.append(k) c = list(zip(*d)) p = [] for i in range(len(c)): p.append(c[i][0] * c[i][1]) number = sum(p) / sum(d[1]) print('{:.1f}'.format(number))
def reader(): with open('day3/puzzle_input.txt', 'r') as f: return f.read().splitlines() def tree(right, down): count = 0 index = 0 lines = reader() for i in range(0, len(lines), down): line = lines[i] if line[index] == '#': count += 1 remainder = len(line) - index - 1 index = ( index + right if remainder > right - 1 else right - 1 - remainder ) return count multiply = 1 for right, down in ((1, 1), (3, 1), (5, 1), (7, 1), (1, 2)): multiply *= tree(right, down) print(multiply)
def reader(): with open('day3/puzzle_input.txt', 'r') as f: return f.read().splitlines() def tree(right, down): count = 0 index = 0 lines = reader() for i in range(0, len(lines), down): line = lines[i] if line[index] == '#': count += 1 remainder = len(line) - index - 1 index = index + right if remainder > right - 1 else right - 1 - remainder return count multiply = 1 for (right, down) in ((1, 1), (3, 1), (5, 1), (7, 1), (1, 2)): multiply *= tree(right, down) print(multiply)
class FPyCompare: def __readFile(self, fileName): with open(fileName) as f: lines = f.read().splitlines() return lines def __writeFile(self, resultList, fileName): with open(fileName, "w") as outfile: outfile.write("\n".join(resultList)) print(fileName + " completed!") def initializeList(self): fileNameOne = input("First File Name: ") self.listOne = set(self.__readFile(fileNameOne)) fileNameTwo = input("Second File Name: ") self.listTwo = set(self.__readFile(fileNameTwo)) def interset(self, printResult=True): intersect = list(self.listOne.intersection(self.listTwo)) print(intersect) if printResult else self.__writeFile(intersect, "result_intersect.txt") def union(self, printResult=True): union = list(self.listOne.union(self.listTwo)) print(union) if printResult else self.__writeFile(union, "result_union.txt") def differenceListOne(self, printResult=True): subtract = list(self.listOne.difference(self.listTwo)) print(subtract) if printResult else self.__writeFile(subtract, "result_DifferenceOne.txt") def differenceListTwo(self, printResult=True): subtract = list(self.listTwo.difference(self.listOne)) print(subtract) if printResult else self.__writeFile(subtract, "result_DifferenceTwo.txt") fCompare = FPyCompare() fCompare.initializeList() fCompare.interset(False) fCompare.union(False) fCompare.differenceListOne(False) fCompare.differenceListTwo(False)
class Fpycompare: def __read_file(self, fileName): with open(fileName) as f: lines = f.read().splitlines() return lines def __write_file(self, resultList, fileName): with open(fileName, 'w') as outfile: outfile.write('\n'.join(resultList)) print(fileName + ' completed!') def initialize_list(self): file_name_one = input('First File Name: ') self.listOne = set(self.__readFile(fileNameOne)) file_name_two = input('Second File Name: ') self.listTwo = set(self.__readFile(fileNameTwo)) def interset(self, printResult=True): intersect = list(self.listOne.intersection(self.listTwo)) print(intersect) if printResult else self.__writeFile(intersect, 'result_intersect.txt') def union(self, printResult=True): union = list(self.listOne.union(self.listTwo)) print(union) if printResult else self.__writeFile(union, 'result_union.txt') def difference_list_one(self, printResult=True): subtract = list(self.listOne.difference(self.listTwo)) print(subtract) if printResult else self.__writeFile(subtract, 'result_DifferenceOne.txt') def difference_list_two(self, printResult=True): subtract = list(self.listTwo.difference(self.listOne)) print(subtract) if printResult else self.__writeFile(subtract, 'result_DifferenceTwo.txt') f_compare = f_py_compare() fCompare.initializeList() fCompare.interset(False) fCompare.union(False) fCompare.differenceListOne(False) fCompare.differenceListTwo(False)
print(() == ()) print(() > ()) print(() < ()) print(() == (1,)) print((1,) == ()) print(() > (1,)) print((1,) > ()) print(() < (1,)) print((1,) < ()) print(() >= (1,)) print((1,) >= ()) print(() <= (1,)) print((1,) <= ()) print((1,) == (1,)) print((1,) != (1,)) print((1,) == (2,)) print((1,) == (1, 0,)) print((1,) > (1,)) print((1,) > (2,)) print((2,) > (1,)) print((1, 0,) > (1,)) print((1, -1,) > (1,)) print((1,) > (1, 0,)) print((1,) > (1, -1,)) print((1,) < (1,)) print((2,) < (1,)) print((1,) < (2,)) print((1,) < (1, 0,)) print((1,) < (1, -1,)) print((1, 0,) < (1,)) print((1, -1,) < (1,)) print((1,) >= (1,)) print((1,) >= (2,)) print((2,) >= (1,)) print((1, 0,) >= (1,)) print((1, -1,) >= (1,)) print((1,) >= (1, 0,)) print((1,) >= (1, -1,)) print((1,) <= (1,)) print((2,) <= (1,)) print((1,) <= (2,)) print((1,) <= (1, 0,)) print((1,) <= (1, -1,)) print((1, 0,) <= (1,)) print((1, -1,) <= (1,)) print((10, 0) > (1, 1)) print((10, 0) < (1, 1)) print((0, 0, 10, 0) > (0, 0, 1, 1)) print((0, 0, 10, 0) < (0, 0, 1, 1))
print(() == ()) print(() > ()) print(() < ()) print(() == (1,)) print((1,) == ()) print(() > (1,)) print((1,) > ()) print(() < (1,)) print((1,) < ()) print(() >= (1,)) print((1,) >= ()) print(() <= (1,)) print((1,) <= ()) print((1,) == (1,)) print((1,) != (1,)) print((1,) == (2,)) print((1,) == (1, 0)) print((1,) > (1,)) print((1,) > (2,)) print((2,) > (1,)) print((1, 0) > (1,)) print((1, -1) > (1,)) print((1,) > (1, 0)) print((1,) > (1, -1)) print((1,) < (1,)) print((2,) < (1,)) print((1,) < (2,)) print((1,) < (1, 0)) print((1,) < (1, -1)) print((1, 0) < (1,)) print((1, -1) < (1,)) print((1,) >= (1,)) print((1,) >= (2,)) print((2,) >= (1,)) print((1, 0) >= (1,)) print((1, -1) >= (1,)) print((1,) >= (1, 0)) print((1,) >= (1, -1)) print((1,) <= (1,)) print((2,) <= (1,)) print((1,) <= (2,)) print((1,) <= (1, 0)) print((1,) <= (1, -1)) print((1, 0) <= (1,)) print((1, -1) <= (1,)) print((10, 0) > (1, 1)) print((10, 0) < (1, 1)) print((0, 0, 10, 0) > (0, 0, 1, 1)) print((0, 0, 10, 0) < (0, 0, 1, 1))
# Copyright 2012 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. { 'variables': { 'chromium_code': 1, }, 'targets': [ { 'target_name': 'timed_decomposer_lib', 'type': 'static_library', 'sources': [ 'timed_decomposer_app.cc', 'timed_decomposer_app.h', ], 'dependencies': [ '<(src)/syzygy/pe/pe.gyp:pe_lib', '<(src)/syzygy/common/common.gyp:syzygy_version', ], }, { 'target_name': 'timed_decomposer', 'type': 'executable', 'sources': [ 'timed_decomposer_main.cc', ], 'dependencies': [ 'timed_decomposer_lib', ], 'run_as': { 'action': [ '$(TargetPath)', '--image=$(OutDir)\\test_dll.dll', '--csv=$(OutDir)\\decomposition_times_for_test_dll.csv', '--iterations=20', ], }, }, ], }
{'variables': {'chromium_code': 1}, 'targets': [{'target_name': 'timed_decomposer_lib', 'type': 'static_library', 'sources': ['timed_decomposer_app.cc', 'timed_decomposer_app.h'], 'dependencies': ['<(src)/syzygy/pe/pe.gyp:pe_lib', '<(src)/syzygy/common/common.gyp:syzygy_version']}, {'target_name': 'timed_decomposer', 'type': 'executable', 'sources': ['timed_decomposer_main.cc'], 'dependencies': ['timed_decomposer_lib'], 'run_as': {'action': ['$(TargetPath)', '--image=$(OutDir)\\test_dll.dll', '--csv=$(OutDir)\\decomposition_times_for_test_dll.csv', '--iterations=20']}}]}
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def reverseBetween(self, head: ListNode, left: int, right: int) -> ListNode: dummy_head = sublist_head = ListNode(0,head) for _ in range(1,left): sublist_head=sublist_head.next #Reversal sublist_iter = sublist_head.next for _ in range(right-left): temp=sublist_iter.next print(sublist_head) sublist_iter.next , temp.next , sublist_head.next = temp.next , sublist_head.next , temp print(sublist_head) return dummy_head.next
class Solution: def reverse_between(self, head: ListNode, left: int, right: int) -> ListNode: dummy_head = sublist_head = list_node(0, head) for _ in range(1, left): sublist_head = sublist_head.next sublist_iter = sublist_head.next for _ in range(right - left): temp = sublist_iter.next print(sublist_head) (sublist_iter.next, temp.next, sublist_head.next) = (temp.next, sublist_head.next, temp) print(sublist_head) return dummy_head.next
# Height in cm --> feet and inches # (just for ya fookin 'muricans) cm = float(input("Enter height in cm: ")) inches = cm/2.54 ft = int(inches//12) inches = int(round(inches % 12)) print("Height is about {}'{}\".".format(ft, inches))
cm = float(input('Enter height in cm: ')) inches = cm / 2.54 ft = int(inches // 12) inches = int(round(inches % 12)) print('Height is about {}\'{}".'.format(ft, inches))
# writing to a file : # To write to a file you need to create file stream = open('output.txt', 'wt') print('\n Can I write to this file : ' + str(stream.writable())) stream.write('H') # write a single string ... stream.writelines(['ello',' ', 'Susan']) # write multiple strings stream.write('\n') # write a new line # You can pass for writelines a list of strings names = ['Alen', 'Chris', 'Sausan'] # Here is how to write to a file using a list, and then you can use a neat feature so you can separate them using whatever you want using join stream.writelines(','.join(names)) stream.writelines('\n'.join(names)) stream.close() # flush stream and close
stream = open('output.txt', 'wt') print('\n Can I write to this file : ' + str(stream.writable())) stream.write('H') stream.writelines(['ello', ' ', 'Susan']) stream.write('\n') names = ['Alen', 'Chris', 'Sausan'] stream.writelines(','.join(names)) stream.writelines('\n'.join(names)) stream.close()
an_int = 2 a_float = 2.1 print(an_int + 3) # prints 5 # Define the release and runtime integer variables below: release_year = 15 runtime = 20 # Define the rating_out_of_10 float variable below: rating_out_of_10 = 3.5
an_int = 2 a_float = 2.1 print(an_int + 3) release_year = 15 runtime = 20 rating_out_of_10 = 3.5
N = int(input()) s = [input() for _ in range(5)] a = [ '.###..#..###.###.#.#.###.###.###.###.###.', '.#.#.##....#...#.#.#.#...#.....#.#.#.#.#.', '.#.#..#..###.###.###.###.###...#.###.###.', '.#.#..#..#.....#...#...#.#.#...#.#.#...#.', '.###.###.###.###...#.###.###...#.###.###.' ] result = [] for i in range(N): t = [s[j][i * 4:(i + 1) * 4] for j in range(5)] for j in range(10): for k in range(5): if t[k] != a[k][j * 4:(j + 1) * 4]: break else: result.append(j) break print(''.join(str(i) for i in result))
n = int(input()) s = [input() for _ in range(5)] a = ['.###..#..###.###.#.#.###.###.###.###.###.', '.#.#.##....#...#.#.#.#...#.....#.#.#.#.#.', '.#.#..#..###.###.###.###.###...#.###.###.', '.#.#..#..#.....#...#...#.#.#...#.#.#...#.', '.###.###.###.###...#.###.###...#.###.###.'] result = [] for i in range(N): t = [s[j][i * 4:(i + 1) * 4] for j in range(5)] for j in range(10): for k in range(5): if t[k] != a[k][j * 4:(j + 1) * 4]: break else: result.append(j) break print(''.join((str(i) for i in result)))
# Numpy is imported; seed is set # Initialize all_walks (don't change this line) all_walks = [] # Simulate random walk 10 times for i in range(10) : # Code from before random_walk = [0] for x in range(100) : step = random_walk[-1] dice = np.random.randint(1,7) if dice <= 2: step = max(0, step - 1) elif dice <= 5: step = step + 1 else: step = step + np.random.randint(1,7) random_walk.append(step) # Append random_walk to all_walks all_walks.append(random_walk) # Print all_walks print(all_walks) # numpy and matplotlib imported, seed set. # initialize and populate all_walks all_walks = [] for i in range(10) : random_walk = [0] for x in range(100) : step = random_walk[-1] dice = np.random.randint(1,7) if dice <= 2: step = max(0, step - 1) elif dice <= 5: step = step + 1 else: step = step + np.random.randint(1,7) random_walk.append(step) all_walks.append(random_walk) # Convert all_walks to Numpy array: np_aw np_aw = np.array(all_walks) # Plot np_aw and show plt.plot(np_aw) plt.show() # Clear the figure plt.clf() # Transpose np_aw: np_aw_t np_aw_t = np.transpose(np_aw) # Plot np_aw_t and show plt.plot(np_aw_t) plt.show() # numpy and matplotlib imported, seed set # Simulate random walk 250 times all_walks = [] for i in range(250) : random_walk = [0] for x in range(100) : step = random_walk[-1] dice = np.random.randint(1,7) if dice <= 2: step = max(0, step - 1) elif dice <= 5: step = step + 1 else: step = step + np.random.randint(1,7) # Implement clumsiness if np.random.rand() <= 0.001 : step = 0 random_walk.append(step) all_walks.append(random_walk) # Create and plot np_aw_t np_aw_t = np.transpose(np.array(all_walks)) plt.plot(np_aw_t) plt.show() # numpy and matplotlib imported, seed set # Simulate random walk 500 times all_walks = [] for i in range(500) : random_walk = [0] for x in range(100) : step = random_walk[-1] dice = np.random.randint(1,7) if dice <= 2: step = max(0, step - 1) elif dice <= 5: step = step + 1 else: step = step + np.random.randint(1,7) if np.random.rand() <= 0.001 : step = 0 random_walk.append(step) all_walks.append(random_walk) # Create and plot np_aw_t np_aw_t = np.transpose(np.array(all_walks)) # Select last row from np_aw_t: ends ends = np_aw_t[-1,:] # Plot histogram of ends, display plot plt.hist(ends) plt.show()
all_walks = [] for i in range(10): random_walk = [0] for x in range(100): step = random_walk[-1] dice = np.random.randint(1, 7) if dice <= 2: step = max(0, step - 1) elif dice <= 5: step = step + 1 else: step = step + np.random.randint(1, 7) random_walk.append(step) all_walks.append(random_walk) print(all_walks) all_walks = [] for i in range(10): random_walk = [0] for x in range(100): step = random_walk[-1] dice = np.random.randint(1, 7) if dice <= 2: step = max(0, step - 1) elif dice <= 5: step = step + 1 else: step = step + np.random.randint(1, 7) random_walk.append(step) all_walks.append(random_walk) np_aw = np.array(all_walks) plt.plot(np_aw) plt.show() plt.clf() np_aw_t = np.transpose(np_aw) plt.plot(np_aw_t) plt.show() all_walks = [] for i in range(250): random_walk = [0] for x in range(100): step = random_walk[-1] dice = np.random.randint(1, 7) if dice <= 2: step = max(0, step - 1) elif dice <= 5: step = step + 1 else: step = step + np.random.randint(1, 7) if np.random.rand() <= 0.001: step = 0 random_walk.append(step) all_walks.append(random_walk) np_aw_t = np.transpose(np.array(all_walks)) plt.plot(np_aw_t) plt.show() all_walks = [] for i in range(500): random_walk = [0] for x in range(100): step = random_walk[-1] dice = np.random.randint(1, 7) if dice <= 2: step = max(0, step - 1) elif dice <= 5: step = step + 1 else: step = step + np.random.randint(1, 7) if np.random.rand() <= 0.001: step = 0 random_walk.append(step) all_walks.append(random_walk) np_aw_t = np.transpose(np.array(all_walks)) ends = np_aw_t[-1, :] plt.hist(ends) plt.show()
# A file to test if pyvm works from the command line. def it_works(): print("Success!") it_works()
def it_works(): print('Success!') it_works()
n = "Hello" # Your function here! def string_function(s): return s + 'world' print(string_function(n))
n = 'Hello' def string_function(s): return s + 'world' print(string_function(n))
# Final Exam, Problem 4 - 2 def longestRun(L): ''' Assumes L is a non-empty list Returns the length of the longest monotonically increasing ''' maxRun = 0 tempRun = 0 for i in range(len(L) - 1): if L[i + 1] >= L[i]: tempRun += 1 if tempRun > maxRun: maxRun = tempRun else: tempRun = 0 return maxRun + 1
def longest_run(L): """ Assumes L is a non-empty list Returns the length of the longest monotonically increasing """ max_run = 0 temp_run = 0 for i in range(len(L) - 1): if L[i + 1] >= L[i]: temp_run += 1 if tempRun > maxRun: max_run = tempRun else: temp_run = 0 return maxRun + 1
# # @lc app=leetcode id=415 lang=python3 # # [415] Add Strings # # https://leetcode.com/problems/add-strings/description/ # # algorithms # Easy (51.34%) # Likes: 2772 # Dislikes: 495 # Total Accepted: 421.8K # Total Submissions: 820.4K # Testcase Example: '"11"\n"123"' # # Given two non-negative integers, num1 and num2 represented as string, return # the sum of num1 and num2 as a string. # # You must solve the problem without using any built-in library for handling # large integers (such as BigInteger). You must also not convert the inputs to # integers directly. # # # Example 1: # # # Input: num1 = "11", num2 = "123" # Output: "134" # # # Example 2: # # # Input: num1 = "456", num2 = "77" # Output: "533" # # # Example 3: # # # Input: num1 = "0", num2 = "0" # Output: "0" # # # # Constraints: # # # 1 <= num1.length, num2.length <= 10^4 # num1 and num2 consist of only digits. # num1 and num2 don't have any leading zeros except for the zero itself. # # # # @lc code=start class Solution: def addStrings(self, num1: str, num2: str) -> str: ans = int(num1) + int(num2) return str(ans) # @lc code=end
class Solution: def add_strings(self, num1: str, num2: str) -> str: ans = int(num1) + int(num2) return str(ans)
def landscaper(f, generations): seen_states = {} states = [] state = f.readline().strip().split(' ')[-1] f.readline() rules = {} idx = 0 prev_sum = None for rule in f.readlines(): keys, _, res = rule.strip().split(' ') if res == '#': rules[keys] = True for i in range(0, generations): first_hash = state.index('#') if first_hash < 5: adds = 5 - first_hash state = '.' * adds + state idx -= adds last_hash = state.rindex('#') if last_hash > (len(state) - 5): state += '.' * (6 - abs(last_hash - len(state))) output = state[:2] for x in range(2, len(state) - 2): output += '#' if state[x-2:x+3] in rules else '.' output += state[len(state) - 2:] state = output k = state.strip('.') if k in seen_states: current = sum_state(state, idx) if prev_sum: diff = current - prev_sum return current + diff * (generations - seen_states[k][0] - 2) prev_sum = current seen_states[k] = (i, idx) states.append(state) return sum_state(state, idx) def sum_state(state, idx): s = 0 for i in range(0, len(state)): add = (i + idx) if state[i] == '#' else 0 s += add return s def test_landscaper(): assert landscaper(open('input/12.test'), 20) == 325 if __name__ == '__main__': print(landscaper(open('input/12'), 20)) print(landscaper(open('input/12'), 128)) print(landscaper(open('input/12'), 50_000_000_000))
def landscaper(f, generations): seen_states = {} states = [] state = f.readline().strip().split(' ')[-1] f.readline() rules = {} idx = 0 prev_sum = None for rule in f.readlines(): (keys, _, res) = rule.strip().split(' ') if res == '#': rules[keys] = True for i in range(0, generations): first_hash = state.index('#') if first_hash < 5: adds = 5 - first_hash state = '.' * adds + state idx -= adds last_hash = state.rindex('#') if last_hash > len(state) - 5: state += '.' * (6 - abs(last_hash - len(state))) output = state[:2] for x in range(2, len(state) - 2): output += '#' if state[x - 2:x + 3] in rules else '.' output += state[len(state) - 2:] state = output k = state.strip('.') if k in seen_states: current = sum_state(state, idx) if prev_sum: diff = current - prev_sum return current + diff * (generations - seen_states[k][0] - 2) prev_sum = current seen_states[k] = (i, idx) states.append(state) return sum_state(state, idx) def sum_state(state, idx): s = 0 for i in range(0, len(state)): add = i + idx if state[i] == '#' else 0 s += add return s def test_landscaper(): assert landscaper(open('input/12.test'), 20) == 325 if __name__ == '__main__': print(landscaper(open('input/12'), 20)) print(landscaper(open('input/12'), 128)) print(landscaper(open('input/12'), 50000000000))
# printing out a string print("lol") # printing out a space betwin them (\n) print("Hello\nWorld") # if you want to put a (") inside do this: print("Hello\"World\"") # if you want to put a (\) inside just type: print("Hello\World") # you can also print a variable like this; lol = "Hello World" print(lol) # you can also do something called cencatenation who is putting a string whit some text like this; lol = "Hello World" print(lol + " Hello World") # you can also use fonctions to change info or to know info about a sring. exemple of fonctions; lol = "Hello World" # puts every thing small or decapitelize print(lol.lower()) # capitelize everything print(lol.upper()) # boolean is it all cap. print(lol.isupper()) # 2 same time print(lol.upper().isupper()) # tells you lhe length print(len(lol)) # this fonction shows a letter of the string(0 for "H", 1 for "e" exetera). lol = "Hello World" print(lol[0]) print(lol[1]) # you can return the index (the position of a letter)by doing this: print(lol.index("d")) # you can also replace a word in your string like this: print(lol.replace("World", "dude"))
print('lol') print('Hello\nWorld') print('Hello"World"') print('Hello\\World') lol = 'Hello World' print(lol) lol = 'Hello World' print(lol + ' Hello World') lol = 'Hello World' print(lol.lower()) print(lol.upper()) print(lol.isupper()) print(lol.upper().isupper()) print(len(lol)) lol = 'Hello World' print(lol[0]) print(lol[1]) print(lol.index('d')) print(lol.replace('World', 'dude'))
def funcao(x = 1,y = 1): return 2*x+y print(funcao(2,3)) print(funcao(3,2)) print(funcao(1,2))
def funcao(x=1, y=1): return 2 * x + y print(funcao(2, 3)) print(funcao(3, 2)) print(funcao(1, 2))
''' author: Iuri Freire e-mail: iuricostafreire at gmail dot com local date : 2021-01-07 local time : 20:47 '''
""" author: Iuri Freire e-mail: iuricostafreire at gmail dot com local date : 2021-01-07 local time : 20:47 """
name = 'exit' usage = 'EXIT' description = 'Exits Diplomat.' def execute(query): return 'Exiting Diplomat.'
name = 'exit' usage = 'EXIT' description = 'Exits Diplomat.' def execute(query): return 'Exiting Diplomat.'
success = { "uuid": "8bf7e570-67cd-4670-a37c-0999fd07f9bf", "action": "EventsRouter", "result": { "success": True }, "tid": 1, "type": "rpc", "method": "detail" } fail = { "uuid": "8bf7e570-67cd-4670-a37c-0999fd07f9bf", "action": "EventsRouter", "result": { "msg": "ServiceResponseError: Not Found", "type": "exception", "success": False }, "tid": 1, "type": "rpc", "method": "detail" } events_query = { "uuid": "eadafce3-12ba-44ed-b1aa-e6ffdf6e98c6", "action": "EventsRouter", "result": { "totalCount": 50, "events": [ { "prodState": "Production", "firstTime": 1505865565.822, "facility": None, "eventClassKey": "csm.sessionFailed", "agent": "zenpython", "dedupid": "test.example.com|test-01|/Status|ZenPacks.zenoss.NetAppMonitor.datasource_plugins.NetAppMonitorCmodeEventsDataSourcePlugin.NetAppMonitorCmodeEventsDataSourcePlugin|60|3", "Location": [ { "uid": "/zport/dmd/Locations/Moon Base Alpha", "name": "/Moon Base Alpha" } ], "ownerid": "zenoss", "eventClass": { "text": "/Status", "uid": "/zport/dmd/Events/Status" }, "id": "02420a11-0015-98b9-11e7-9d96ae351999", "DevicePriority": "Normal", "monitor": "localhost", "priority": None, "details": { "node": [ "test-01" ], "recvtime": [ "1508797427" ], "zenoss.device.location": [ "/Moon Base Alpha" ], "zenoss.device.priority": [ "3" ], "zenoss.device.device_class": [ "/Storage/NetApp/C-Mode" ], "seq-num": [ "647604" ], "source": [ "CsmMpAgentThread" ], "manager": [ "13a1a22ff067" ], "message-name": [ "csm.sessionFailed" ], "resolution": [ "If you can reach the storage failover (SFO) partner of the target appliance, initiate a storage failover (takeover) of any aggregates on the target appliance. Then perform a 'sendhome' operation on these aggregates after the target appliance is operational again. Examine the network between the initiating appliance and the target appliance for problems. " ], "eventClassMapping": [ "/Status/failureNoFrames" ], "time": [ "1508797427" ], "zenoss.device.production_state": [ "1000" ], "zenoss.device.ip_address": [ "1.2.3.4" ], "event": [ "csm.sessionFailed: Cluster interconnect session (req=test-01:dblade, rsp=test-01:dblade, uniquifier=11055c3e278e5cc8) failed with record state ACTIVE and error CSM_CONNABORTED. " ] }, "DeviceClass": [ { "uid": "/zport/dmd/Devices/Storage/NetApp/C-Mode", "name": "/Storage/NetApp/C-Mode" } ], "eventKey": "ZenPacks.zenoss.NetAppMonitor.datasource_plugins.NetAppMonitorCmodeEventsDataSourcePlugin.NetAppMonitorCmodeEventsDataSourcePlug", "evid": "02420a11-0015-98b9-11e7-9d96ae351999", "eventClassMapping": { "uuid": "1337d66f-d5fa-4c3b-8198-bcfedf83d040", "name": "failureNoFrames" }, "component": { "url": "/zport/dmd/goto?guid=08c40deb-1009-4634-a529-d66631391733", "text": "test-01", "uid": "/zport/dmd/Devices/Storage/NetApp/C-Mode/devices/test.example.com/systemnodes/test-01", "uuid": "08c40deb-1009-4634-a529-d66631391733" }, "clearid": None, "DeviceGroups": [], "eventGroup": None, "device": { "url": "/zport/dmd/goto?guid=02e21618-b30a-47bf-8591-471c70570932", "text": "test.example.com", "uuid": "02e21618-b30a-47bf-8591-471c70570932", "uid": "/zport/dmd/Devices/Storage/NetApp/C-Mode/devices/test.example.com" }, "message": "csm.sessionFailed: Cluster interconnect session (req=test-01:dblade, rsp=test-01:dblade, uniquifier=11055c3e278e5cc8) failed with record state ACTIVE and error CSM_CONNABORTED. \nResolution: If you can reach the storage failover (SFO) partner of the target appliance, initiate a storage failover (takeover) of any aggregates on the target appliance. Then perform a 'sendhome' operation on these aggregates after the target appliance is operational again. Examine the network between the initiating appliance and the target appliance for problems. ", "severity": 3, "count": 66, "stateChange": 1507054918.83, "ntevid": None, "summary": "csm.sessionFailed: Cluster interconnect session (req=test-01:dblade, rsp=test-01:dblade, uniquifier=11055c3e278e5cc8) failed with record state ACTIVE and error CSM_CONNABORTED. ", "eventState": "Acknowledged", "lastTime": 1508797479.194, "ipAddress": [ "1.2.3.4" ], "Systems": [] } ], "success": True, "asof": 1508797504.409547 }, "tid": 1, "type": "rpc", "method": "query" } events_query_evid = { "uuid": "eadafce3-12ba-44ed-b1aa-e6ffdf6e98c6", "action": "EventsRouter", "result": { "totalCount": 50, "events": [ { "evid": "02420a11-0015-98b9-11e7-9d96ae351999" } ], "success": True, "asof": 1508797504.409547 }, "tid": 1, "type": "rpc", "method": "query" } event_detail = { "uuid": "23f0bbd9-b6a3-46bb-909f-aa53891dfbf5", "action": "EventsRouter", "result": { "event": [ { "prodState": "Production", "firstTime": 1505865565.822, "device_uuid": "02e21618-b30a-47bf-8591-471c70570932", "eventClassKey": "smc.snapmir.unexpected.err", "agent": "zenpython", "dedupid": "test.example.com|test-01|/Status|ZenPacks.zenoss.NetAppMonitor.datasource_plugins.NetAppMonitorCmodeEventsDataSourcePlugin.NetAppMonitorCmodeEventsDataSourcePlugin|60|3", "Location": [ { "uid": "/zport/dmd/Locations/Moon Base Alpha", "name": "/Moon Base Alpha" } ], "component_url": "/zport/dmd/goto?guid=08c40deb-1009-4634-a529-d66631391733", "ownerid": "zenoss", "eventClassMapping_url": "/zport/dmd/goto?guid=1337d66f-d5fa-4c3b-8198-bcfedf83d040", "eventClass": "/Status", "id": "02420a11-0015-98b9-11e7-9d96ae351999", "device_title": "test.example.com", "DevicePriority": "Normal", "log": [ [ "zenoss", 1507054918830, "state changed to Acknowledged" ] ], "facility": None, "eventClass_url": "/zport/dmd/Events/Status", "monitor": "localhost", "priority": None, "device_url": "/zport/dmd/goto?guid=02e21618-b30a-47bf-8591-471c70570932", "details": [ { "key": "event", "value": "smc.snapmir.unexpected.err: SnapMirror unexpected error 'Destination volume \"cg_name_wildcard\" was not found. It may have been moved.(Failed to get volume attributes for twoaggrdav.(Volume is not known or has been moved))'. Relationship UUID ' '. " }, { "key": "eventClassMapping", "value": "/Status/failureNoFrames" }, { "key": "manager", "value": "13a1a22ff067" }, { "key": "message-name", "value": "smc.snapmir.unexpected.err" }, { "key": "node", "value": "test-01" }, { "key": "recvtime", "value": "1508798161" }, { "key": "resolution", "value": "If the problem persists, contact NetApp technical support. " }, { "key": "seq-num", "value": "647654" }, { "key": "source", "value": "sm_logger_main" }, { "key": "time", "value": "1508798161" }, { "key": "zenoss.device.device_class", "value": "/Storage/NetApp/C-Mode" }, { "key": "zenoss.device.ip_address", "value": "1.2.3.4" }, { "key": "zenoss.device.location", "value": "/Moon Base Alpha" }, { "key": "zenoss.device.priority", "value": "3" }, { "key": "zenoss.device.production_state", "value": "1000" } ], "DeviceClass": [ { "uid": "/zport/dmd/Devices/Storage/NetApp/C-Mode", "name": "/Storage/NetApp/C-Mode" } ], "eventKey": "ZenPacks.zenoss.NetAppMonitor.datasource_plugins.NetAppMonitorCmodeEventsDataSourcePlugin.NetAppMonitorCmodeEventsDataSourcePlug", "evid": "02420a11-0015-98b9-11e7-9d96ae351999", "eventClassMapping": "failureNoFrames", "component": "test-01", "clearid": None, "DeviceGroups": [], "eventGroup": None, "device": "test.example.com", "Systems": [], "component_title": "test-01", "severity": 3, "count": 66, "stateChange": 1507054918.83, "ntevid": None, "summary": "smc.snapmir.unexpected.err: SnapMirror unexpected error 'Destination volume \"cg_name_wildcard\" was not found. It may have been moved.(Failed to get volume attributes for twoaggrdav.(Volume is not known or has been moved))'. Relationship UUID ' '. ", "message": "smc.snapmir.unexpected.err: SnapMirror unexpected error 'Destination volume \"cg_name_wildcard\" was not found. It may have been moved.(Failed to get volume attributes for twoaggrdav.(Volume is not known or has been moved))'. Relationship UUID ' '. \nResolution: If the problem persists, contact NetApp technical support. ", "eventState": "Acknowledged", "lastTime": 1508798199.186, "ipAddress": [ "1.2.3.4" ], "component_uuid": "08c40deb-1009-4634-a529-d66631391733" } ], "success": True }, "tid": 1, "type": "rpc", "method": "detail" } events_config = { "uuid": "7f7109f2-1a6f-41f5-a12f-bbd95f280b9c", "action": "EventsRouter", "result": { "data": [ { "xtype": "eventageseverity", "defaultValue": 4, "id": "event_age_disable_severity", "value": 4, "name": "Don't Age This Severity and Above" }, { "defaultValue": False, "id": "event_age_severity_inclusive", "value": False, "xtype": "hidden" } ], "success": True }, "tid": 1, "type": "rpc", "method": "getConfig" } add_event_evid_query = { "uuid": "6700ab59-c559-42ec-959b-ebc33bc52257", "action": "EventsRouter", "result": { "totalCount": 1, "events": [ { "evid": "02420a11-000c-a561-11e7-ba9b510182b3", } ], "success": True, "asof": 1509056503.945677 }, "tid": 1, "type": "rpc", "method": "query" } add_event_detail = { "uuid": "c54074e8-af8b-4e40-a679-7dbe314709ed", "action": "EventsRouter", "result": { "event": [ { "prodState": None, "firstTime": 1509056189.91, "device_uuid": None, "eventClassKey": None, "agent": None, "dedupid": "Heart of Gold|Arthur Dent|/Status|3|Out of Tea", "Location": [], "component_url": None, "ownerid": None, "eventClassMapping_url": None, "eventClass": "/Status", "id": "02420a11-000c-a561-11e7-ba9b510182b3", "device_title": "Heart of Gold", "DevicePriority": None, "log": [ [ "zenoss", 1509057815980, "<p>Test log entry</p>" ] ], "facility": None, "eventClass_url": "/zport/dmd/Events/Status", "monitor": None, "priority": None, "device_url": None, "details": [], "DeviceClass": [], "eventKey": "", "evid": "02420a11-000c-a561-11e7-ba9b510182b3", "eventClassMapping": None, "component": "Arthur Dent", "clearid": None, "DeviceGroups": [], "eventGroup": None, "device": "Heart of Gold", "Systems": [], "component_title": "Arthur Dent", "severity": 3, "count": 1, "stateChange": 1509056189.91, "ntevid": None, "summary": "Out of Tea", "message": "Out of Tea", "eventState": "New", "lastTime": 1509056189.91, "ipAddress": "", "component_uuid": None } ], "success": True }, "tid": 1, "type": "rpc", "method": "detail" }
success = {'uuid': '8bf7e570-67cd-4670-a37c-0999fd07f9bf', 'action': 'EventsRouter', 'result': {'success': True}, 'tid': 1, 'type': 'rpc', 'method': 'detail'} fail = {'uuid': '8bf7e570-67cd-4670-a37c-0999fd07f9bf', 'action': 'EventsRouter', 'result': {'msg': 'ServiceResponseError: Not Found', 'type': 'exception', 'success': False}, 'tid': 1, 'type': 'rpc', 'method': 'detail'} events_query = {'uuid': 'eadafce3-12ba-44ed-b1aa-e6ffdf6e98c6', 'action': 'EventsRouter', 'result': {'totalCount': 50, 'events': [{'prodState': 'Production', 'firstTime': 1505865565.822, 'facility': None, 'eventClassKey': 'csm.sessionFailed', 'agent': 'zenpython', 'dedupid': 'test.example.com|test-01|/Status|ZenPacks.zenoss.NetAppMonitor.datasource_plugins.NetAppMonitorCmodeEventsDataSourcePlugin.NetAppMonitorCmodeEventsDataSourcePlugin|60|3', 'Location': [{'uid': '/zport/dmd/Locations/Moon Base Alpha', 'name': '/Moon Base Alpha'}], 'ownerid': 'zenoss', 'eventClass': {'text': '/Status', 'uid': '/zport/dmd/Events/Status'}, 'id': '02420a11-0015-98b9-11e7-9d96ae351999', 'DevicePriority': 'Normal', 'monitor': 'localhost', 'priority': None, 'details': {'node': ['test-01'], 'recvtime': ['1508797427'], 'zenoss.device.location': ['/Moon Base Alpha'], 'zenoss.device.priority': ['3'], 'zenoss.device.device_class': ['/Storage/NetApp/C-Mode'], 'seq-num': ['647604'], 'source': ['CsmMpAgentThread'], 'manager': ['13a1a22ff067'], 'message-name': ['csm.sessionFailed'], 'resolution': ["If you can reach the storage failover (SFO) partner of the target appliance, initiate a storage failover (takeover) of any aggregates on the target appliance. Then perform a 'sendhome' operation on these aggregates after the target appliance is operational again. Examine the network between the initiating appliance and the target appliance for problems. "], 'eventClassMapping': ['/Status/failureNoFrames'], 'time': ['1508797427'], 'zenoss.device.production_state': ['1000'], 'zenoss.device.ip_address': ['1.2.3.4'], 'event': ['csm.sessionFailed: Cluster interconnect session (req=test-01:dblade, rsp=test-01:dblade, uniquifier=11055c3e278e5cc8) failed with record state ACTIVE and error CSM_CONNABORTED. ']}, 'DeviceClass': [{'uid': '/zport/dmd/Devices/Storage/NetApp/C-Mode', 'name': '/Storage/NetApp/C-Mode'}], 'eventKey': 'ZenPacks.zenoss.NetAppMonitor.datasource_plugins.NetAppMonitorCmodeEventsDataSourcePlugin.NetAppMonitorCmodeEventsDataSourcePlug', 'evid': '02420a11-0015-98b9-11e7-9d96ae351999', 'eventClassMapping': {'uuid': '1337d66f-d5fa-4c3b-8198-bcfedf83d040', 'name': 'failureNoFrames'}, 'component': {'url': '/zport/dmd/goto?guid=08c40deb-1009-4634-a529-d66631391733', 'text': 'test-01', 'uid': '/zport/dmd/Devices/Storage/NetApp/C-Mode/devices/test.example.com/systemnodes/test-01', 'uuid': '08c40deb-1009-4634-a529-d66631391733'}, 'clearid': None, 'DeviceGroups': [], 'eventGroup': None, 'device': {'url': '/zport/dmd/goto?guid=02e21618-b30a-47bf-8591-471c70570932', 'text': 'test.example.com', 'uuid': '02e21618-b30a-47bf-8591-471c70570932', 'uid': '/zport/dmd/Devices/Storage/NetApp/C-Mode/devices/test.example.com'}, 'message': "csm.sessionFailed: Cluster interconnect session (req=test-01:dblade, rsp=test-01:dblade, uniquifier=11055c3e278e5cc8) failed with record state ACTIVE and error CSM_CONNABORTED. \nResolution: If you can reach the storage failover (SFO) partner of the target appliance, initiate a storage failover (takeover) of any aggregates on the target appliance. Then perform a 'sendhome' operation on these aggregates after the target appliance is operational again. Examine the network between the initiating appliance and the target appliance for problems. ", 'severity': 3, 'count': 66, 'stateChange': 1507054918.83, 'ntevid': None, 'summary': 'csm.sessionFailed: Cluster interconnect session (req=test-01:dblade, rsp=test-01:dblade, uniquifier=11055c3e278e5cc8) failed with record state ACTIVE and error CSM_CONNABORTED. ', 'eventState': 'Acknowledged', 'lastTime': 1508797479.194, 'ipAddress': ['1.2.3.4'], 'Systems': []}], 'success': True, 'asof': 1508797504.409547}, 'tid': 1, 'type': 'rpc', 'method': 'query'} events_query_evid = {'uuid': 'eadafce3-12ba-44ed-b1aa-e6ffdf6e98c6', 'action': 'EventsRouter', 'result': {'totalCount': 50, 'events': [{'evid': '02420a11-0015-98b9-11e7-9d96ae351999'}], 'success': True, 'asof': 1508797504.409547}, 'tid': 1, 'type': 'rpc', 'method': 'query'} event_detail = {'uuid': '23f0bbd9-b6a3-46bb-909f-aa53891dfbf5', 'action': 'EventsRouter', 'result': {'event': [{'prodState': 'Production', 'firstTime': 1505865565.822, 'device_uuid': '02e21618-b30a-47bf-8591-471c70570932', 'eventClassKey': 'smc.snapmir.unexpected.err', 'agent': 'zenpython', 'dedupid': 'test.example.com|test-01|/Status|ZenPacks.zenoss.NetAppMonitor.datasource_plugins.NetAppMonitorCmodeEventsDataSourcePlugin.NetAppMonitorCmodeEventsDataSourcePlugin|60|3', 'Location': [{'uid': '/zport/dmd/Locations/Moon Base Alpha', 'name': '/Moon Base Alpha'}], 'component_url': '/zport/dmd/goto?guid=08c40deb-1009-4634-a529-d66631391733', 'ownerid': 'zenoss', 'eventClassMapping_url': '/zport/dmd/goto?guid=1337d66f-d5fa-4c3b-8198-bcfedf83d040', 'eventClass': '/Status', 'id': '02420a11-0015-98b9-11e7-9d96ae351999', 'device_title': 'test.example.com', 'DevicePriority': 'Normal', 'log': [['zenoss', 1507054918830, 'state changed to Acknowledged']], 'facility': None, 'eventClass_url': '/zport/dmd/Events/Status', 'monitor': 'localhost', 'priority': None, 'device_url': '/zport/dmd/goto?guid=02e21618-b30a-47bf-8591-471c70570932', 'details': [{'key': 'event', 'value': 'smc.snapmir.unexpected.err: SnapMirror unexpected error \'Destination volume "cg_name_wildcard" was not found. It may have been moved.(Failed to get volume attributes for twoaggrdav.(Volume is not known or has been moved))\'. Relationship UUID \' \'. '}, {'key': 'eventClassMapping', 'value': '/Status/failureNoFrames'}, {'key': 'manager', 'value': '13a1a22ff067'}, {'key': 'message-name', 'value': 'smc.snapmir.unexpected.err'}, {'key': 'node', 'value': 'test-01'}, {'key': 'recvtime', 'value': '1508798161'}, {'key': 'resolution', 'value': 'If the problem persists, contact NetApp technical support. '}, {'key': 'seq-num', 'value': '647654'}, {'key': 'source', 'value': 'sm_logger_main'}, {'key': 'time', 'value': '1508798161'}, {'key': 'zenoss.device.device_class', 'value': '/Storage/NetApp/C-Mode'}, {'key': 'zenoss.device.ip_address', 'value': '1.2.3.4'}, {'key': 'zenoss.device.location', 'value': '/Moon Base Alpha'}, {'key': 'zenoss.device.priority', 'value': '3'}, {'key': 'zenoss.device.production_state', 'value': '1000'}], 'DeviceClass': [{'uid': '/zport/dmd/Devices/Storage/NetApp/C-Mode', 'name': '/Storage/NetApp/C-Mode'}], 'eventKey': 'ZenPacks.zenoss.NetAppMonitor.datasource_plugins.NetAppMonitorCmodeEventsDataSourcePlugin.NetAppMonitorCmodeEventsDataSourcePlug', 'evid': '02420a11-0015-98b9-11e7-9d96ae351999', 'eventClassMapping': 'failureNoFrames', 'component': 'test-01', 'clearid': None, 'DeviceGroups': [], 'eventGroup': None, 'device': 'test.example.com', 'Systems': [], 'component_title': 'test-01', 'severity': 3, 'count': 66, 'stateChange': 1507054918.83, 'ntevid': None, 'summary': 'smc.snapmir.unexpected.err: SnapMirror unexpected error \'Destination volume "cg_name_wildcard" was not found. It may have been moved.(Failed to get volume attributes for twoaggrdav.(Volume is not known or has been moved))\'. Relationship UUID \' \'. ', 'message': 'smc.snapmir.unexpected.err: SnapMirror unexpected error \'Destination volume "cg_name_wildcard" was not found. It may have been moved.(Failed to get volume attributes for twoaggrdav.(Volume is not known or has been moved))\'. Relationship UUID \' \'. \nResolution: If the problem persists, contact NetApp technical support. ', 'eventState': 'Acknowledged', 'lastTime': 1508798199.186, 'ipAddress': ['1.2.3.4'], 'component_uuid': '08c40deb-1009-4634-a529-d66631391733'}], 'success': True}, 'tid': 1, 'type': 'rpc', 'method': 'detail'} events_config = {'uuid': '7f7109f2-1a6f-41f5-a12f-bbd95f280b9c', 'action': 'EventsRouter', 'result': {'data': [{'xtype': 'eventageseverity', 'defaultValue': 4, 'id': 'event_age_disable_severity', 'value': 4, 'name': "Don't Age This Severity and Above"}, {'defaultValue': False, 'id': 'event_age_severity_inclusive', 'value': False, 'xtype': 'hidden'}], 'success': True}, 'tid': 1, 'type': 'rpc', 'method': 'getConfig'} add_event_evid_query = {'uuid': '6700ab59-c559-42ec-959b-ebc33bc52257', 'action': 'EventsRouter', 'result': {'totalCount': 1, 'events': [{'evid': '02420a11-000c-a561-11e7-ba9b510182b3'}], 'success': True, 'asof': 1509056503.945677}, 'tid': 1, 'type': 'rpc', 'method': 'query'} add_event_detail = {'uuid': 'c54074e8-af8b-4e40-a679-7dbe314709ed', 'action': 'EventsRouter', 'result': {'event': [{'prodState': None, 'firstTime': 1509056189.91, 'device_uuid': None, 'eventClassKey': None, 'agent': None, 'dedupid': 'Heart of Gold|Arthur Dent|/Status|3|Out of Tea', 'Location': [], 'component_url': None, 'ownerid': None, 'eventClassMapping_url': None, 'eventClass': '/Status', 'id': '02420a11-000c-a561-11e7-ba9b510182b3', 'device_title': 'Heart of Gold', 'DevicePriority': None, 'log': [['zenoss', 1509057815980, '<p>Test log entry</p>']], 'facility': None, 'eventClass_url': '/zport/dmd/Events/Status', 'monitor': None, 'priority': None, 'device_url': None, 'details': [], 'DeviceClass': [], 'eventKey': '', 'evid': '02420a11-000c-a561-11e7-ba9b510182b3', 'eventClassMapping': None, 'component': 'Arthur Dent', 'clearid': None, 'DeviceGroups': [], 'eventGroup': None, 'device': 'Heart of Gold', 'Systems': [], 'component_title': 'Arthur Dent', 'severity': 3, 'count': 1, 'stateChange': 1509056189.91, 'ntevid': None, 'summary': 'Out of Tea', 'message': 'Out of Tea', 'eventState': 'New', 'lastTime': 1509056189.91, 'ipAddress': '', 'component_uuid': None}], 'success': True}, 'tid': 1, 'type': 'rpc', 'method': 'detail'}
settings = { # add provider-specific survey settings here # e.g. how to abbreviate questions }
settings = {}
# coding: utf-8 s = "The string ends in escape: " s += chr(27) # add an escape character at the end of $str print(repr(s))
s = 'The string ends in escape: ' s += chr(27) print(repr(s))
SERVICE_NAME = "org.bluez" AGENT_IFACE = SERVICE_NAME + '.Agent1' ADAPTER_IFACE = SERVICE_NAME + ".Adapter1" DEVICE_IFACE = SERVICE_NAME + ".Device1" PLAYER_IFACE = SERVICE_NAME + '.MediaPlayer1' TRANSPORT_IFACE = SERVICE_NAME + '.MediaTransport1' OBJECT_IFACE = "org.freedesktop.DBus.ObjectManager" PROPERTIES_IFACE = "org.freedesktop.DBus.Properties" INTROSPECT_IFACE = "org.freedesktop.DBus.Introspectable"
service_name = 'org.bluez' agent_iface = SERVICE_NAME + '.Agent1' adapter_iface = SERVICE_NAME + '.Adapter1' device_iface = SERVICE_NAME + '.Device1' player_iface = SERVICE_NAME + '.MediaPlayer1' transport_iface = SERVICE_NAME + '.MediaTransport1' object_iface = 'org.freedesktop.DBus.ObjectManager' properties_iface = 'org.freedesktop.DBus.Properties' introspect_iface = 'org.freedesktop.DBus.Introspectable'
class Cliente: def __init__(self, nome): self.__nome = nome @property def nome(self): return self.__nome.title() def get_nome(self): print('[INFO] Getting value...') print('[INFO] Name "{}" getted sucessfully'.format(self.__nome)) return self.__nome.title() @nome.setter def nome(self, value): print('[INFO] Setting new value...') self.__nome = value print('[INFO] New value: {}'.format(value)) if __name__ == '__main__': cliente = Cliente('thiago') cliente.nome cliente.nome = 'Thiago Kasper'
class Cliente: def __init__(self, nome): self.__nome = nome @property def nome(self): return self.__nome.title() def get_nome(self): print('[INFO] Getting value...') print('[INFO] Name "{}" getted sucessfully'.format(self.__nome)) return self.__nome.title() @nome.setter def nome(self, value): print('[INFO] Setting new value...') self.__nome = value print('[INFO] New value: {}'.format(value)) if __name__ == '__main__': cliente = cliente('thiago') cliente.nome cliente.nome = 'Thiago Kasper'
class ChartModel: def score_keywords(self, dep_keywords): #mock (@todo: update after integrating training a model) keyword_scores = [] for kw in dep_keywords: keyword_scores.append({ 'keyword': kw, 'score': 0.7 }) return keyword_scores
class Chartmodel: def score_keywords(self, dep_keywords): keyword_scores = [] for kw in dep_keywords: keyword_scores.append({'keyword': kw, 'score': 0.7}) return keyword_scores
def word_permutation(s): return word_permutation_helper(list(s)) def word_permutation_helper(input_list): if len(input_list) ==0: return '' ret = [] for i in range(len(input_list)): base = input_list[i] remainder = input_list[:i]+input_list[i+1:] out = word_permutation_helper(remainder) if isinstance(out,list): ret.extend([out[i]+base for i in range(len(out))]) continue else: out+=base ret.append(out) return ret
def word_permutation(s): return word_permutation_helper(list(s)) def word_permutation_helper(input_list): if len(input_list) == 0: return '' ret = [] for i in range(len(input_list)): base = input_list[i] remainder = input_list[:i] + input_list[i + 1:] out = word_permutation_helper(remainder) if isinstance(out, list): ret.extend([out[i] + base for i in range(len(out))]) continue else: out += base ret.append(out) return ret
def solution(participant, completion): answer = "" temp = 0 dic = {} for p in participant: dic[hash(p)] = p temp += hash(p) for c in completion: temp -= hash(c) return dic[temp]
def solution(participant, completion): answer = '' temp = 0 dic = {} for p in participant: dic[hash(p)] = p temp += hash(p) for c in completion: temp -= hash(c) return dic[temp]
class Solution: def generateMatrix(self, n: int) -> List[List[int]]: mat = [[0] * n for _ in range(n)] left, top, right, bottom = 0, 0, n, n val = 1 while left < right and top < bottom: for i in range(left, right): mat[top][i] = val val += 1 top += 1 for i in range(top, bottom): mat[i][right - 1] = val val += 1 right -= 1 for i in range(right - 1, left - 1, -1): mat[bottom - 1][i] = val val += 1 bottom -= 1 for i in range(bottom - 1, top - 1, -1): mat[i][left] = val val += 1 left += 1 return mat
class Solution: def generate_matrix(self, n: int) -> List[List[int]]: mat = [[0] * n for _ in range(n)] (left, top, right, bottom) = (0, 0, n, n) val = 1 while left < right and top < bottom: for i in range(left, right): mat[top][i] = val val += 1 top += 1 for i in range(top, bottom): mat[i][right - 1] = val val += 1 right -= 1 for i in range(right - 1, left - 1, -1): mat[bottom - 1][i] = val val += 1 bottom -= 1 for i in range(bottom - 1, top - 1, -1): mat[i][left] = val val += 1 left += 1 return mat
class Solution(object): def findCircleNum(self, M): def dfs(node): visited.add(node) for person, is_friend in enumerate(M[node]): if is_friend and person not in visited: dfs(person) circle = 0 visited = set() for node in range(len(M)): if node not in visited: circle += 1 dfs(node) return circle
class Solution(object): def find_circle_num(self, M): def dfs(node): visited.add(node) for (person, is_friend) in enumerate(M[node]): if is_friend and person not in visited: dfs(person) circle = 0 visited = set() for node in range(len(M)): if node not in visited: circle += 1 dfs(node) return circle
a = [1,5,4,6,8,11,3,12] even = list(filter(lambda x: (x%2 == 0), a)) print(even) third = list(filter(lambda x: (x%3 == 0), a)) print(third) b = [[0,1,8],[7,2,2],[5,3,10],[1,4,5]] b.sort(key = lambda x: x[2]) print(b) b.sort(key = lambda x: x[0]+x[1]) print(b)
a = [1, 5, 4, 6, 8, 11, 3, 12] even = list(filter(lambda x: x % 2 == 0, a)) print(even) third = list(filter(lambda x: x % 3 == 0, a)) print(third) b = [[0, 1, 8], [7, 2, 2], [5, 3, 10], [1, 4, 5]] b.sort(key=lambda x: x[2]) print(b) b.sort(key=lambda x: x[0] + x[1]) print(b)
def word(str): j=len(str)-1 for i in range(int(len(str)/2)): if str[i]!=str[j]: return False j=j-1 return True str=input("Enter the string :") ans=word(str) if(ans): print("string is palindrome") else: print("string is not palindrome")
def word(str): j = len(str) - 1 for i in range(int(len(str) / 2)): if str[i] != str[j]: return False j = j - 1 return True str = input('Enter the string :') ans = word(str) if ans: print('string is palindrome') else: print('string is not palindrome')
class RowMenuItem: def __init__(self, widget): # Item can have an optional id self.id = None # Item may specify a parent id (for rendering purposes, like display = 'with-parent,' perhaps) self.parent_id = None # If another item chooses to display with this item, then that other item (the with-parent item) # becomes a "friend" of this item (sharing focus and blur events) self.friend_ids = [] # The widget container within this RowMenuItem self.item = widget # I typically track visibility within the lowest level widgets (<label />, etc.). # For RowMenuItems, though, I'll permit this wrapper to also have a "visibility" setting, # separate from the standard "display" attribute of low-level widgets. self.visibility = "visible" # An item may be entirely hidden from view (no height, no rendering, nothing) # Primarily used for static dialogue panels, etc., to serve as a "hidden input" field # (i.e. key listener) self.hidden = False # An item might not be selectable by the user self.disabled = False # Perhaps the single item (within a group) has an individual border? self.individual_border = False # Shrinkwrap to rnder only necessary border width? self.shrinkwrap = False # Perhaps we'll render a glowing highlight behind the text of the active selection? self.glow = False # Occasionally we'll hard-code the height for a given item self.explicit_height = None # Sometimes a row menu item will have a tooltip (which is basically a simple GridMenuCell) self.tooltip = None # A RowMenuItem may have other special properties if they begin with a - self.additional_properties = {} def configure(self, options): if ( "id" in options ): self.id = options["id"] if ( "parent-id" in options ): self.parent_id = options["parent-id"] if ( "visibility" in options ): self.visibility = options["visibility"] if ( "hidden" in options ): self.hidden = options["hidden"] if ( "disabled" in options ): self.disabled = int( options["disabled"] ) if ( "individual-border" in options ): self.individual_border = int( options["individual-border"] ) if ( "shrinkwrap" in options ): self.shrinkwrap = int( options["shrinkwrap"] ) if ( "glow" in options ): self.glow = int( options["glow"] ) if ( "explicit-height" in options ): self.explicit_height = int( options["explicit-height"] ) # Check for special additional properties for key in options: # Must start with a - if ( key.startswith("-") ): # Save it self.additional_properties[key] = options[key] #print "..." #print options #print self.additional_properties #print 5/0 # For chaining return self # Get a special property def get_property(self, key): # Validate if (key in self.additional_properties): return self.additional_properties[key] else: return None def get_widget_container(self): return self.item # Event callbacks def while_awake(self): # Forward message self.get_widget().while_awake() def while_asleep(self): # Forward message self.get_widget().while_asleep() def on_blur(self): # Forward message self.get_widget().on_blur() def get_widget(self): return self.item # used in widget height calculations (e.g. overall RowMenu height) def get_box_height(self, text_renderer): # Hidden items have no height if (self.hidden): return 0 elif (self.explicit_height != None): return (self.explicit_height) else: #print "Advance, check box height for %s" % self.item return (self.item.get_box_height(text_renderer)) # Used to determine render region for backgrounds and the like def get_render_height(self, text_renderer): # Hidden items have no height if (self.hidden): return 0 elif (self.explicit_height != None): return self.explicit_height else: return self.item.get_render_height(text_renderer) def get_min_x(self, text_renderer): return self.item.get_min_x(text_renderer) def add_tooltip(self):#, width, align, delay, lifespan, margin_x = 20, margin_y = 0): self.tooltip = RowMenuTooltip()#RowMenuItemTooltip(width, align, delay = delay, lifespan = lifespan, margin_x = margin_x, margin_y = margin_y) return self.tooltip
class Rowmenuitem: def __init__(self, widget): self.id = None self.parent_id = None self.friend_ids = [] self.item = widget self.visibility = 'visible' self.hidden = False self.disabled = False self.individual_border = False self.shrinkwrap = False self.glow = False self.explicit_height = None self.tooltip = None self.additional_properties = {} def configure(self, options): if 'id' in options: self.id = options['id'] if 'parent-id' in options: self.parent_id = options['parent-id'] if 'visibility' in options: self.visibility = options['visibility'] if 'hidden' in options: self.hidden = options['hidden'] if 'disabled' in options: self.disabled = int(options['disabled']) if 'individual-border' in options: self.individual_border = int(options['individual-border']) if 'shrinkwrap' in options: self.shrinkwrap = int(options['shrinkwrap']) if 'glow' in options: self.glow = int(options['glow']) if 'explicit-height' in options: self.explicit_height = int(options['explicit-height']) for key in options: if key.startswith('-'): self.additional_properties[key] = options[key] return self def get_property(self, key): if key in self.additional_properties: return self.additional_properties[key] else: return None def get_widget_container(self): return self.item def while_awake(self): self.get_widget().while_awake() def while_asleep(self): self.get_widget().while_asleep() def on_blur(self): self.get_widget().on_blur() def get_widget(self): return self.item def get_box_height(self, text_renderer): if self.hidden: return 0 elif self.explicit_height != None: return self.explicit_height else: return self.item.get_box_height(text_renderer) def get_render_height(self, text_renderer): if self.hidden: return 0 elif self.explicit_height != None: return self.explicit_height else: return self.item.get_render_height(text_renderer) def get_min_x(self, text_renderer): return self.item.get_min_x(text_renderer) def add_tooltip(self): self.tooltip = row_menu_tooltip() return self.tooltip
nome = str(input('Digite seu nome completo: ')).strip() print(nome.upper()) print(nome.lower()) print(len(nome))
nome = str(input('Digite seu nome completo: ')).strip() print(nome.upper()) print(nome.lower()) print(len(nome))
#!/usr/bin/env python # encoding=utf-8 def test(): print('utils_gao, making for ml')
def test(): print('utils_gao, making for ml')
def _gen_k8s_file(ctx): odir = ctx.actions.declare_directory("tmp") ctx.actions.run( inputs = [], outputs = [odir], arguments = [], progress_message = "Converting", env = { "CDK8S_OUTDIR": odir.path, }, executable = ctx.executable.tool, tools = [ctx.executable.tool], ) runfiles = ctx.runfiles( files = [odir, ctx.executable._concat], ) ctx.actions.run( inputs = [odir], outputs = [ctx.outputs.out], arguments = [odir.path, ctx.outputs.out.path], executable = ctx.executable._concat, tools = [ctx.executable._concat], ) gen_to_stdout = ctx.actions.declare_file(ctx.label.name + ".gen") ctx.actions.write( output = gen_to_stdout, content = "%s %s" % (ctx.executable._concat.short_path, odir.short_path), is_executable = True, ) # gen_to_file = ctx.actions.declare_file("gen_to_file") # ctx.actions.write( # output = gen_to_file, # content = (base_gen_cmd + "> %s") % (odir.path, ctx.outputs.out.path), # is_executable = True, # ) # ctx.actions.run( # inputs = [odir, gen_to_stdout], # executable = gen_to_file, # outputs = [ctx.outputs.out], # ) return [DefaultInfo( files = depset([ctx.outputs.out]), runfiles = runfiles, executable = gen_to_stdout, )] gen_k8s_file = rule( _gen_k8s_file, attrs = { "tool": attr.label( executable = True, allow_files = True, cfg = "exec", ), "_concat": attr.label( executable = True, allow_single_file = True, cfg = "exec", default = "//rules:concat.sh", ) }, executable = True, outputs = { "out": "%{name}.yaml", }, )
def _gen_k8s_file(ctx): odir = ctx.actions.declare_directory('tmp') ctx.actions.run(inputs=[], outputs=[odir], arguments=[], progress_message='Converting', env={'CDK8S_OUTDIR': odir.path}, executable=ctx.executable.tool, tools=[ctx.executable.tool]) runfiles = ctx.runfiles(files=[odir, ctx.executable._concat]) ctx.actions.run(inputs=[odir], outputs=[ctx.outputs.out], arguments=[odir.path, ctx.outputs.out.path], executable=ctx.executable._concat, tools=[ctx.executable._concat]) gen_to_stdout = ctx.actions.declare_file(ctx.label.name + '.gen') ctx.actions.write(output=gen_to_stdout, content='%s %s' % (ctx.executable._concat.short_path, odir.short_path), is_executable=True) return [default_info(files=depset([ctx.outputs.out]), runfiles=runfiles, executable=gen_to_stdout)] gen_k8s_file = rule(_gen_k8s_file, attrs={'tool': attr.label(executable=True, allow_files=True, cfg='exec'), '_concat': attr.label(executable=True, allow_single_file=True, cfg='exec', default='//rules:concat.sh')}, executable=True, outputs={'out': '%{name}.yaml'})
# # This file contains the Python code from Program 2.9 of # "Data Structures and Algorithms # with Object-Oriented Design Patterns in Python" # by Bruno R. Preiss. # # Copyright (c) 2003 by Bruno R. Preiss, P.Eng. All rights reserved. # # http://www.brpreiss.com/books/opus7/programs/pgm02_09.txt # def geometricSeriesSum(x, n): return (power(x, n + 1) - 1) / (x - 1)
def geometric_series_sum(x, n): return (power(x, n + 1) - 1) / (x - 1)
N, K = map(int, input().split()) a_list = list(map(int, input().split())) sum_list = [] for i in range(N): for j in range(i, N): sum_list.append(sum(a_list[i:j+1])) ans = 0 count = 0 tmp = [] for i in range(40, -1, -1): for s in sum_list: check_num = 1 << i logical_and = check_num & s if logical_and != 0: count += 1 if count >= K: ans += 1 << i tmp = [x for x in sum_list if (1 << i) & x != 0] sum_list = tmp[:] count = 0 print(ans)
(n, k) = map(int, input().split()) a_list = list(map(int, input().split())) sum_list = [] for i in range(N): for j in range(i, N): sum_list.append(sum(a_list[i:j + 1])) ans = 0 count = 0 tmp = [] for i in range(40, -1, -1): for s in sum_list: check_num = 1 << i logical_and = check_num & s if logical_and != 0: count += 1 if count >= K: ans += 1 << i tmp = [x for x in sum_list if 1 << i & x != 0] sum_list = tmp[:] count = 0 print(ans)
# Reads config/config.ini and performs sanity checks class Config(object): config = None def __init__(self, path='config/config.ini'): if not self.config: print("[WARNING] Loading placeholder config") # this has to be replaced by reading the actual .ini config file with open(path, 'r') as cfg: token = cfg.readline().rstrip() initial_channel = cfg.readline().rstrip() default_playlist = cfg.readline().rstrip() Config.config = { 'token': token, 'initial_channel': initial_channel, 'default_playlist': default_playlist } def __getattr__(self, name): return self.config[name] def __setattr__(self, name, value): print("[WARNING] Overriding config value") self.config[name] = value conf = Config()
class Config(object): config = None def __init__(self, path='config/config.ini'): if not self.config: print('[WARNING] Loading placeholder config') with open(path, 'r') as cfg: token = cfg.readline().rstrip() initial_channel = cfg.readline().rstrip() default_playlist = cfg.readline().rstrip() Config.config = {'token': token, 'initial_channel': initial_channel, 'default_playlist': default_playlist} def __getattr__(self, name): return self.config[name] def __setattr__(self, name, value): print('[WARNING] Overriding config value') self.config[name] = value conf = config()
''' Set data type lst = [varname, varname1, varname2] dictionary = { "key": "value", } ''' set = {"Item1", "Item2", "Item3"} print(set) # {'Item1', 'Item2', 'Item3'} # Sets do not care about the order # {'Item2', 'Item3', 'Item1'} # Sets do not care about the order s = {"Item1", "Item2", "Item2", "Item3"} print(s) # {'Item3', 'Item2', 'Item1'} ## Second item2 considered a duplicate s.add("item 4") print(s) #{'Item2', 'Item1', 'item 4', 'Item3'} s.remove("item 4") print(s) # {'Item1', 'Item2', 'Item3'}
""" Set data type lst = [varname, varname1, varname2] dictionary = { "key": "value", } """ set = {'Item1', 'Item2', 'Item3'} print(set) s = {'Item1', 'Item2', 'Item2', 'Item3'} print(s) s.add('item 4') print(s) s.remove('item 4') print(s)
class SlidingAverage: def __init__(self, window_size): self.index = 0 self.values = [0] * window_size def _previous(self): return self.values[(self.index + len(self.values) - 1) % len(self.values)] def update(self, value): self.values[self.index] = self._previous() + value self.index = (self.index + 1) % len(self.values) def get(self): return (self._previous() - self.values[self.index]) / (len(self.values) - 1)
class Slidingaverage: def __init__(self, window_size): self.index = 0 self.values = [0] * window_size def _previous(self): return self.values[(self.index + len(self.values) - 1) % len(self.values)] def update(self, value): self.values[self.index] = self._previous() + value self.index = (self.index + 1) % len(self.values) def get(self): return (self._previous() - self.values[self.index]) / (len(self.values) - 1)
palavras = ('Doidera', 'Calipso', 'Yoda', 'Axt', 'Jovirone', 'Matilda', 'Schwarzenneger', 'Mustefaga', 'Instinct', 'Kobayashi', 'Ludgero', 'Salcicha', 'Scooby', 'Turtle', 'Lily', 'Toast') for palavra in palavras: print(f'Na palavra {palavra.upper()} temos ', end='') for c in range(0, len(palavra)): if palavra[c] in 'AaEeIiOoUu': print(palavra[c].lower(), end=' ') print()
palavras = ('Doidera', 'Calipso', 'Yoda', 'Axt', 'Jovirone', 'Matilda', 'Schwarzenneger', 'Mustefaga', 'Instinct', 'Kobayashi', 'Ludgero', 'Salcicha', 'Scooby', 'Turtle', 'Lily', 'Toast') for palavra in palavras: print(f'Na palavra {palavra.upper()} temos ', end='') for c in range(0, len(palavra)): if palavra[c] in 'AaEeIiOoUu': print(palavra[c].lower(), end=' ') print()
def specificSummator(): counter = 0 for i in range(0, 10000): if (i % 7) == 0: counter += i elif (i % 9) == 0: counter += i return counter print(specificSummator())
def specific_summator(): counter = 0 for i in range(0, 10000): if i % 7 == 0: counter += i elif i % 9 == 0: counter += i return counter print(specific_summator())
# WAP to accept a file from user and print shortest and longest line from that file. def PrintShortestLongestLines(inputFile): line = inputFile.readline() maxLine = line minLine = line while line != "": line = inputFile.readline() if line == "\n" or line == "": continue if len(line) < len(minLine): minLine = line elif len(line) > len(maxLine): maxLine = line return minLine, maxLine def PrintShortestLongestLinesDict(inputFile): line = inputFile.readline() maxline = len(line) minline = len(line) resultDict = dict({ "MinLen": line, "MaxLen": line }) while line != '': line = inputFile.readline() if line == '\n' or line == '': continue if len(line) < minline: resultDict["MinLen"] = line elif len(line) > maxline: resultDict["MaxLen"] = line return resultDict def main(): inputFilePath = input("Please enter a filename to be read: ") fd = open(inputFilePath) if fd != None: # print(PrintShortestLongestLines(fd)) minLenLin, maxLenLine = PrintShortestLongestLines(fd) print("Min Length {}\nMax Length {}".format(minLenLin, maxLenLine)) else: print("File does not exist") if __name__ == "__main__": main()
def print_shortest_longest_lines(inputFile): line = inputFile.readline() max_line = line min_line = line while line != '': line = inputFile.readline() if line == '\n' or line == '': continue if len(line) < len(minLine): min_line = line elif len(line) > len(maxLine): max_line = line return (minLine, maxLine) def print_shortest_longest_lines_dict(inputFile): line = inputFile.readline() maxline = len(line) minline = len(line) result_dict = dict({'MinLen': line, 'MaxLen': line}) while line != '': line = inputFile.readline() if line == '\n' or line == '': continue if len(line) < minline: resultDict['MinLen'] = line elif len(line) > maxline: resultDict['MaxLen'] = line return resultDict def main(): input_file_path = input('Please enter a filename to be read: ') fd = open(inputFilePath) if fd != None: (min_len_lin, max_len_line) = print_shortest_longest_lines(fd) print('Min Length {}\nMax Length {}'.format(minLenLin, maxLenLine)) else: print('File does not exist') if __name__ == '__main__': main()