content
stringlengths
7
1.05M
class Movie: """ This is an abstract a movie structure """ def __init__(self, leading_actor='Leonardo DiCaprio', supporting_actor='Brad Pitt', run_time=130): self.leading_actor = leading_actor self.supporting_actor = supporting_actor self.run_time = run_time def who_is_leading(self): """ Who is the star of the film """ print('The leading star is {}'.format(self.leading_actor)) def who_is_supporting(self): """ Who is the supporting actor? """ print('The supporting actor is {}'.format(self.supporting_actor)) def what_is_run_time(self): """ What is the running time? """ print('The running time is {}'.format(self.run_time))
"""f90nml.fpy ============= Module for conversion between basic data types and Fortran string representations. :copyright: Copyright 2014 Marshall Ward, see AUTHORS for details. :license: Apache License, Version 2.0, see LICENSE for details. """ def pyfloat(v_str): """Convert string repr of Fortran floating point to Python double.""" # NOTE: There is no loss of information from SP to DP floats return float(v_str.lower().replace('d', 'e')) def pycomplex(v_str): """Convert string repr of Fortran complex to Python complex.""" assert isinstance(v_str, str) if v_str[0] == '(' and v_str[-1] == ')' and len(v_str.split(',')) == 2: v_re, v_im = v_str[1:-1].split(',', 1) # NOTE: Failed float(str) will raise ValueError return complex(pyfloat(v_re), pyfloat(v_im)) else: raise ValueError('{0} must be in complex number form (x, y).' ''.format(v_str)) def pybool(v_str, strict_logical=True): """Convert string repr of Fortran logical to Python logical.""" assert isinstance(v_str, str) assert isinstance(strict_logical, bool) if strict_logical: v_bool = v_str.lower() else: try: if v_str.startswith('.'): v_bool = v_str[1].lower() else: v_bool = v_str[0].lower() except IndexError: raise ValueError('{0} is not a valid logical constant.' ''.format(v_str)) if v_bool in ('.true.', '.t.', 'true', 't'): return True elif v_bool in ('.false.', '.f.', 'false', 'f'): return False else: raise ValueError('{0} is not a valid logical constant.'.format(v_str)) def pystr(v_str): """Convert string repr of Fortran string to Python string.""" assert isinstance(v_str, str) if v_str[0] in ("'", '"') and v_str[0] == v_str[-1]: return v_str[1:-1] else: return v_str
f = input('Digite uma frase: ').lower().replace(' ', '') cont = 0 i = 0 for c in range(len(f), 0, -1): if f[i] == f[c-1]: cont += 1 i += 1 if cont == len(f): print('Temos um palíndromo') else: print('Não temos um palíndromo')
""" 104.二叉树的最大深度 时间复杂度:O(logn) 空间复杂度:O(1) """ class TreeNode: def __init__(self, val): self.val = val self.right = None self.left = None def createTreeNode(node_list): if not node_list[0]: return None root = TreeNode(node_list[0]) Nodes = [root] j = 1 for node in Nodes: if node: node.left = (TreeNode(node_list[j]) if node_list[j] else None) Nodes.append(node.left) j += 1 if len(node_list) == j: return root node.right = (TreeNode(node_list[j]) if node_list[j] else None) Nodes.append(node.right) j += 1 if len(node_list) == j: return root class Solution: def maxDepth(self, root: TreeNode) -> int: if not root: return 0 return 1 + max(self.maxDepth(root.left), self.maxDepth(root.right)) if __name__ == "__main__": node_list = [3, 9, 20, None, None, 15, 7] root = createTreeNode(node_list) s = Solution() ret = s.maxDepth(root) print(ret)
class Zone: def __init__(self) -> None: self._display_name = "" self._offset = 0 def get_display_name(self) -> str: return self._display_name def get_offset(self) -> int: return self._offset
''' Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive. The update(i, val) function modifies nums by updating the element at index i to val. Example: Given nums = [1, 3, 5] sumRange(0, 2) -> 9 update(1, 2) sumRange(0, 2) -> 8 ''' class NumArray(object): def __init__(self, array): self.size = len(array) self.tree = [0] * (self.size) for (index, num) in enumerate(array): self.increment(index, num) # Check pre-fix sum up to index (inclusive) def readSum(self, index): range_sum = 0 # convert to 1 based to fast search index += 1 while (index > 0): range_sum += self.tree[index-1] # top down index -= ( index & -index) return range_sum # Check range sum from start to end (both inclusive) def sumRange(self, start, end): return self.readSum(end) if start == 0 else self.readSum(end) - self.readSum(start-1) def readElement(self, index): if index == 0: return self.readSum(0) return self.readSum(index) - self.readSum(index-1) def update(self, index, value): orig_value = self.readElement(index) incr = value - orig_value self.increment(index, incr) def increment(self, index, incr): # convert to 1 based to fast search index += 1 while (index <= self.size): self.tree[index-1] += incr # bottom up index += (index & (-index)) # Your NumArray object will be instantiated and called as such: # numArray = NumArray(nums) # numArray.sumRange(0, 1) # numArray.update(1, 10) # numArray.sumRange(1, 2)
def is_prime(n): for x in range(2, n): if n % x == 0: return False return True def get_prime_numbers(n): for x in range(n, 1, -1): if is_prime(x): yield x def get_two_sum(primes, number): for i, q in enumerate(primes): next_values = primes[i + 1:] for p in next_values: if p <= q and p + q == number: return p, q n = int(input("> ")) numbers = [] for _ in range(n): num = int(input("> ")) primes = list(get_prime_numbers(num)) nums = get_two_sum(primes, num) numbers.append(nums) for (p, q) in numbers: print(p, q)
opcodes = { 'STOP': [0x00, 0, 0, 0], 'ADD': [0x01, 2, 1, 3], 'MUL': [0x02, 2, 1, 5], 'SUB': [0x03, 2, 1, 3], 'DIV': [0x04, 2, 1, 5], 'SDIV': [0x05, 2, 1, 5], 'MOD': [0x06, 2, 1, 5], 'SMOD': [0x07, 2, 1, 5], 'ADDMOD': [0x08, 3, 1, 8], 'MULMOD': [0x09, 3, 1, 8], 'EXP': [0x0a, 2, 1, 10], 'SIGNEXTEND': [0x0b, 2, 1, 5], 'LT': [0x10, 2, 1, 3], 'GT': [0x11, 2, 1, 3], 'SLT': [0x12, 2, 1, 3], 'SGT': [0x13, 2, 1, 3], 'EQ': [0x14, 2, 1, 3], 'ISZERO': [0x15, 1, 1, 3], 'AND': [0x16, 2, 1, 3], 'OR': [0x17, 2, 1, 3], 'XOR': [0x18, 2, 1, 3], 'NOT': [0x19, 1, 1, 3], 'BYTE': [0x1a, 2, 1, 3], 'SHA3': [0x20, 2, 1, 30], 'ADDRESS': [0x30, 0, 1, 2], 'BALANCE': [0x31, 1, 1, 400], 'ORIGIN': [0x32, 0, 1, 2], 'CALLER': [0x33, 0, 1, 2], 'CALLVALUE': [0x34, 0, 1, 2], 'CALLDATALOAD': [0x35, 1, 1, 3], 'CALLDATASIZE': [0x36, 0, 1, 2], 'CALLDATACOPY': [0x37, 3, 0, 3], 'CODESIZE': [0x38, 0, 1, 2], 'CODECOPY': [0x39, 3, 0, 3], 'GASPRICE': [0x3a, 0, 1, 2], 'EXTCODESIZE': [0x3b, 1, 1, 700], 'EXTCODECOPY': [0x3c, 4, 0, 700], 'BLOCKHASH': [0x40, 1, 1, 20], 'COINBASE': [0x41, 0, 1, 2], 'TIMESTAMP': [0x42, 0, 1, 2], 'NUMBER': [0x43, 0, 1, 2], 'DIFFICULTY': [0x44, 0, 1, 2], 'GASLIMIT': [0x45, 0, 1, 2], 'POP': [0x50, 1, 0, 2], 'MLOAD': [0x51, 1, 1, 3], 'MSTORE': [0x52, 2, 0, 3], 'MSTORE8': [0x53, 2, 0, 3], 'SLOAD': [0x54, 1, 1, 200], 'SSTORE': [0x55, 2, 0, 5000], 'JUMP': [0x56, 1, 0, 8], 'JUMPI': [0x57, 2, 0, 10], 'PC': [0x58, 0, 1, 2], 'MSIZE': [0x59, 0, 1, 2], 'GAS': [0x5a, 0, 1, 2], 'JUMPDEST': [0x5b, 0, 0, 1], 'LOG0': [0xa0, 2, 0, 375], 'LOG1': [0xa1, 3, 0, 750], 'LOG2': [0xa2, 4, 0, 1125], 'LOG3': [0xa3, 5, 0, 1500], 'LOG4': [0xa4, 6, 0, 1875], 'CREATE': [0xf0, 3, 1, 32000], 'CALL': [0xf1, 7, 1, 700], 'CALLCODE': [0xf2, 7, 1, 700], 'RETURN': [0xf3, 2, 0, 0], 'DELEGATECALL': [0xf4, 6, 1, 700], 'CALLBLACKBOX': [0xf5, 7, 1, 700], 'SELFDESTRUCT': [0xff, 1, 0, 25000], 'STATICCALL': [0xfa, 6, 1, 40], 'REVERT': [0xfd, 2, 0, 0], 'SUICIDE': [0xff, 1, 0, 5000], 'INVALID': [0xfe, 0, 0, 0], } pseudo_opcodes = { 'CLAMP': [None, 3, 1, 70], 'UCLAMPLT': [None, 2, 1, 25], 'UCLAMPLE': [None, 2, 1, 30], 'CLAMP_NONZERO': [None, 1, 1, 19], 'ASSERT': [None, 1, 0, 85], 'PASS': [None, 0, 0, 0], 'BREAK': [None, 0, 0, 20], 'SHA3_32': [None, 1, 1, 72], 'SLE': [None, 2, 1, 10], 'SGE': [None, 2, 1, 10], 'LE': [None, 2, 1, 10], 'GE': [None, 2, 1, 10], 'CEIL32': [None, 1, 1, 20], 'SET': [None, 2, 0, 20], 'NE': [None, 2, 1, 6], } comb_opcodes = {} for k in opcodes: comb_opcodes[k] = opcodes[k] for k in pseudo_opcodes: comb_opcodes[k] = pseudo_opcodes[k]
singular_to_plural_dictionary = { "1": { "access-role": "access-roles", "threat-profile": "threat-profiles", "host": "hosts", "network": "networks", "address-range": "address_ranges", "security-zone": "security-zones", "time": "times", "simple-gateway": "simple-gateways", "dynamic-object": "dynamic-objects", "trusted-client": "trusted-clients", "tags": "tags", "dns-domain": "dns-domains", "service-tcp": "services-tcp", "service-udp": "services-udp", "service-sctp": "services-sctp", "service-rpc": "services-rpc", "service-dce-rpc": "services-dce-rpc", "application-site": "applications-sites", "application-site-category": "application-site-categories", "application-site-group": "application-site-groups", "vpn-community-meshed": "vpn-communities-meshed", "vpn-community-star": "vpn-communities-star", "placeholder": "placeholders", "administrator": "administrators", "group": "groups", "group-with-exclusion": "groups-with-exclusion", "service-group": "service-groups", "time-group": "time-groups", "application-group": "application-groups", "exception-group": "exception-groups", "generic-object": "", "access-layer": "access-layers", "access-section": "access-sections", "access-rule": "access-rules", "nat-layer": "nat-layers", "nat-section": "nat-sections", "nat-rule": "nat-rules", "threat-layer": "threat-layers", "threat-rule": "threat-rules", "threat-exception-section": "threat-exception-sections", "threat-exception": "threat-exceptions" }, "1.1": { "access-role": "access-roles", "threat-profile": "threat-profiles", "host": "hosts", "network": "networks", "address-range": "address_ranges", "multicast-address-range": "multicast-address-ranges", "security-zone": "security-zones", "time": "times", "simple-gateway": "simple-gateways", "dynamic-object": "dynamic-objects", "trusted-client": "trusted-clients", "tags": "tags", "dns-domain": "dns-domains", "opsec-application": "opsec-applications", "data-center": "data-centers", "data-center-object": "data-center-objects", "service-tcp": "services-tcp", "service-udp": "services-udp", "service-icmp": "services-icmp", "service-icmp6": "services-icmp6", "service-sctp": "services-sctp", "service-rpc": "services-rpc", "service-other": "services-other", "service-dce-rpc": "services-dce-rpc", "application-site": "applications-sites", "application-site-category": "application-site-categories", "application-site-group": "application-site-groups", "vpn-community-meshed": "vpn-communities-meshed", "vpn-community-star": "vpn-communities-star", "placeholder": "placeholders", "administrator": "administrators", "group": "groups", "group-with-exclusion": "groups-with-exclusion", "service-group": "service-groups", "time-group": "time-groups", "application-group": "application-groups", "threat-protection": "threat-protections", "exception-group": "exception-groups", "generic-object": "", "access-layer": "access-layers", "access-section": "access-sections", "access-rule": "access-rules", "nat-layer": "nat-layers", "nat-section": "nat-sections", "nat-rule": "nat-rules", "threat-layer": "threat-layers", "threat-rule": "threat-rules", "threat-exception-section": "threat-exception-sections", "threat-exception": "threat-exceptions" }, "1.2": { "access-role": "access-roles", "threat-profile": "threat-profiles", "host": "hosts", "network": "networks", "address-range": "address_ranges", "multicast-address-range": "multicast-address-ranges", "security-zone": "security-zones", "time": "times", "simple-gateway": "simple-gateways", "dynamic-object": "dynamic-objects", "trusted-client": "trusted-clients", "tags": "tags", "dns-domain": "dns-domains", "opsec-application": "opsec-applications", "data-center": "data-centers", "data-center-object": "data-center-objects", "service-tcp": "services-tcp", "service-udp": "services-udp", "service-icmp": "services-icmp", "service-icmp6": "services-icmp6", "service-sctp": "services-sctp", "service-rpc": "services-rpc", "service-other": "services-other", "service-dce-rpc": "services-dce-rpc", "application-site": "applications-sites", "application-site-category": "application-site-categories", "application-site-group": "application-site-groups", "vpn-community-meshed": "vpn-communities-meshed", "vpn-community-star": "vpn-communities-star", "placeholder": "placeholders", "administrator": "administrators", "group": "groups", "group-with-exclusion": "groups-with-exclusion", "service-group": "service-groups", "time-group": "time-groups", "application-group": "application-groups", "threat-protection": "threat-protections", "exception-group": "exception-groups", "generic-object": "", "access-layer": "access-layers", "access-section": "access-sections", "access-rule": "access-rules", "nat-layer": "nat-layers", "nat-section": "nat-sections", "nat-rule": "nat-rules", "threat-layer": "threat-layers", "threat-rule": "threat-rules", "threat-exception-section": "threat-exception-sections", "threat-exception": "threat-exceptions", "wildcard": "wildcards" }, "1.3": { "access-role": "access-roles", "threat-profile": "threat-profiles", "host": "hosts", "network": "networks", "address-range": "address_ranges", "multicast-address-range": "multicast-address-ranges", "security-zone": "security-zones", "time": "times", "simple-gateway": "simple-gateways", "dynamic-object": "dynamic-objects", "trusted-client": "trusted-clients", "tags": "tags", "dns-domain": "dns-domains", "opsec-application": "opsec-applications", "data-center": "data-centers", "data-center-object": "data-center-objects", "service-tcp": "services-tcp", "service-udp": "services-udp", "service-icmp": "services-icmp", "service-icmp6": "services-icmp6", "service-sctp": "services-sctp", "service-rpc": "services-rpc", "service-other": "services-other", "service-dce-rpc": "services-dce-rpc", "application-site": "applications-sites", "application-site-category": "application-site-categories", "application-site-group": "application-site-groups", "vpn-community-meshed": "vpn-communities-meshed", "vpn-community-star": "vpn-communities-star", "placeholder": "placeholders", "administrator": "administrators", "group": "groups", "group-with-exclusion": "groups-with-exclusion", "service-group": "service-groups", "time-group": "time-groups", "application-group": "application-groups", "threat-protection": "threat-protections", "exception-group": "exception-groups", "generic-object": "", "access-layer": "access-layers", "access-section": "access-sections", "access-rule": "access-rules", "nat-layer": "nat-layers", "nat-section": "nat-sections", "nat-rule": "nat-rules", "threat-layer": "threat-layers", "threat-rule": "threat-rules", "threat-exception-section": "threat-exception-sections", "threat-exception": "threat-exceptions", "wildcard": "wildcards", "updatable-object": "updatable-objects" }, "1.4": { "access-role": "access-roles", "threat-profile": "threat-profiles", "host": "hosts", "network": "networks", "address-range": "address_ranges", "multicast-address-range": "multicast-address-ranges", "security-zone": "security-zones", "time": "times", "simple-gateway": "simple-gateways", "dynamic-object": "dynamic-objects", "trusted-client": "trusted-clients", "tags": "tags", "dns-domain": "dns-domains", "opsec-application": "opsec-applications", "data-center": "data-centers", "data-center-object": "data-center-objects", "service-tcp": "services-tcp", "service-udp": "services-udp", "service-icmp": "services-icmp", "service-icmp6": "services-icmp6", "service-sctp": "services-sctp", "service-rpc": "services-rpc", "service-other": "services-other", "service-dce-rpc": "services-dce-rpc", "application-site": "applications-sites", "application-site-category": "application-site-categories", "application-site-group": "application-site-groups", "vpn-community-meshed": "vpn-communities-meshed", "vpn-community-star": "vpn-communities-star", "placeholder": "placeholders", "administrator": "administrators", "group": "groups", "group-with-exclusion": "groups-with-exclusion", "service-group": "service-groups", "time-group": "time-groups", "application-group": "application-groups", "threat-protection": "threat-protections", "exception-group": "exception-groups", "generic-object": "", "access-layer": "access-layers", "access-section": "access-sections", "access-rule": "access-rules", "nat-layer": "nat-layers", "nat-section": "nat-sections", "nat-rule": "nat-rules", "threat-layer": "threat-layers", "threat-rule": "threat-rules", "threat-exception-section": "threat-exception-sections", "threat-exception": "threat-exceptions", "wildcard": "wildcards", "updatable-object": "updatable-objects" }, "1.5": { "access-role": "access-roles", "threat-profile": "threat-profiles", "host": "hosts", "network": "networks", "address-range": "address_ranges", "multicast-address-range": "multicast-address-ranges", "security-zone": "security-zones", "time": "times", "simple-gateway": "simple-gateways", "dynamic-object": "dynamic-objects", "trusted-client": "trusted-clients", "tags": "tags", "dns-domain": "dns-domains", "opsec-application": "opsec-applications", "data-center": "data-centers", "data-center-object": "data-center-objects", "service-tcp": "services-tcp", "service-udp": "services-udp", "service-icmp": "services-icmp", "service-icmp6": "services-icmp6", "service-sctp": "services-sctp", "service-rpc": "services-rpc", "service-other": "services-other", "service-dce-rpc": "services-dce-rpc", "application-site": "applications-sites", "application-site-category": "application-site-categories", "application-site-group": "application-site-groups", "vpn-community-meshed": "vpn-communities-meshed", "vpn-community-star": "vpn-communities-star", "placeholder": "placeholders", "administrator": "administrators", "group": "groups", "group-with-exclusion": "groups-with-exclusion", "service-group": "service-groups", "time-group": "time-groups", "application-group": "application-groups", "threat-protection": "threat-protections", "exception-group": "exception-groups", "generic-object": "", "access-layer": "access-layers", "access-section": "access-sections", "access-rule": "access-rules", "nat-layer": "nat-layers", "nat-section": "nat-sections", "nat-rule": "nat-rules", "threat-layer": "threat-layers", "threat-rule": "threat-rules", "threat-exception-section": "threat-exception-sections", "threat-exception": "threat-exceptions", "wildcard": "wildcards", "updatable-object": "updatable-objects" }, "1.6": { "access-role": "access-roles", "threat-profile": "threat-profiles", "host": "hosts", "network": "networks", "address-range": "address_ranges", "multicast-address-range": "multicast-address-ranges", "security-zone": "security-zones", "time": "times", "simple-gateway": "simple-gateways", "dynamic-object": "dynamic-objects", "trusted-client": "trusted-clients", "tags": "tags", "dns-domain": "dns-domains", "opsec-application": "opsec-applications", "data-center": "data-centers", "data-center-object": "data-center-objects", "service-tcp": "services-tcp", "service-udp": "services-udp", "service-icmp": "services-icmp", "service-icmp6": "services-icmp6", "service-sctp": "services-sctp", "service-rpc": "services-rpc", "service-other": "services-other", "service-dce-rpc": "services-dce-rpc", "application-site": "applications-sites", "application-site-category": "application-site-categories", "application-site-group": "application-site-groups", "vpn-community-meshed": "vpn-communities-meshed", "vpn-community-star": "vpn-communities-star", "placeholder": "placeholders", "administrator": "administrators", "group": "groups", "group-with-exclusion": "groups-with-exclusion", "service-group": "service-groups", "time-group": "time-groups", "application-group": "application-groups", "threat-protection": "threat-protections", "exception-group": "exception-groups", "generic-object": "", "access-layer": "access-layers", "access-section": "access-sections", "access-rule": "access-rules", "nat-layer": "nat-layers", "nat-section": "nat-sections", "nat-rule": "nat-rules", "threat-layer": "threat-layers", "threat-rule": "threat-rules", "threat-exception-section": "threat-exception-sections", "threat-exception": "threat-exceptions", "wildcard": "wildcards", "updatable-object": "updatable-objects", "https-layer": "https-layers", "https-section": "https-sections", "https-rule": "https-rules" }, "1.6.1": { "access-role": "access-roles", "threat-profile": "threat-profiles", "host": "hosts", "network": "networks", "address-range": "address_ranges", "multicast-address-range": "multicast-address-ranges", "security-zone": "security-zones", "time": "times", "simple-gateway": "simple-gateways", "dynamic-object": "dynamic-objects", "trusted-client": "trusted-clients", "tags": "tags", "dns-domain": "dns-domains", "opsec-application": "opsec-applications", "data-center": "data-centers", "data-center-object": "data-center-objects", "service-tcp": "services-tcp", "service-udp": "services-udp", "service-icmp": "services-icmp", "service-icmp6": "services-icmp6", "service-sctp": "services-sctp", "service-rpc": "services-rpc", "service-other": "services-other", "service-dce-rpc": "services-dce-rpc", "application-site": "applications-sites", "application-site-category": "application-site-categories", "application-site-group": "application-site-groups", "vpn-community-meshed": "vpn-communities-meshed", "vpn-community-star": "vpn-communities-star", "placeholder": "placeholders", "administrator": "administrators", "group": "groups", "group-with-exclusion": "groups-with-exclusion", "service-group": "service-groups", "time-group": "time-groups", "application-group": "application-groups", "threat-protection": "threat-protections", "exception-group": "exception-groups", "generic-object": "", "access-layer": "access-layers", "access-section": "access-sections", "access-rule": "access-rules", "nat-layer": "nat-layers", "nat-section": "nat-sections", "nat-rule": "nat-rules", "threat-layer": "threat-layers", "threat-rule": "threat-rules", "threat-exception-section": "threat-exception-sections", "threat-exception": "threat-exceptions", "wildcard": "wildcards", "updatable-object": "updatable-objects", "https-layer": "https-layers", "https-section": "https-sections", "https-rule": "https-rules" }, "1.7": { "access-role": "access-roles", "threat-profile": "threat-profiles", "host": "hosts", "network": "networks", "address-range": "address_ranges", "multicast-address-range": "multicast-address-ranges", "security-zone": "security-zones", "time": "times", "simple-gateway": "simple-gateways", "dynamic-object": "dynamic-objects", "trusted-client": "trusted-clients", "tags": "tags", "dns-domain": "dns-domains", "opsec-application": "opsec-applications", "data-center": "data-centers", "data-center-object": "data-center-objects", "service-tcp": "services-tcp", "service-udp": "services-udp", "service-icmp": "services-icmp", "service-icmp6": "services-icmp6", "service-sctp": "services-sctp", "service-rpc": "services-rpc", "service-other": "services-other", "service-dce-rpc": "services-dce-rpc", "application-site": "applications-sites", "application-site-category": "application-site-categories", "application-site-group": "application-site-groups", "vpn-community-meshed": "vpn-communities-meshed", "vpn-community-star": "vpn-communities-star", "placeholder": "placeholders", "administrator": "administrators", "group": "groups", "group-with-exclusion": "groups-with-exclusion", "service-group": "service-groups", "time-group": "time-groups", "application-group": "application-groups", "threat-protection": "threat-protections", "exception-group": "exception-groups", "generic-object": "", "access-layer": "access-layers", "access-section": "access-sections", "access-rule": "access-rules", "nat-layer": "nat-layers", "nat-section": "nat-sections", "nat-rule": "nat-rules", "threat-layer": "threat-layers", "threat-rule": "threat-rules", "threat-exception-section": "threat-exception-sections", "threat-exception": "threat-exceptions", "wildcard": "wildcards", "updatable-object": "updatable-objects", "https-layer": "https-layers", "https-section": "https-sections", "https-rule": "https-rules" }, "1.7.1": { "access-role": "access-roles", "threat-profile": "threat-profiles", "host": "hosts", "network": "networks", "address-range": "address_ranges", "multicast-address-range": "multicast-address-ranges", "security-zone": "security-zones", "time": "times", "simple-gateway": "simple-gateways", "dynamic-object": "dynamic-objects", "trusted-client": "trusted-clients", "tags": "tags", "dns-domain": "dns-domains", "opsec-application": "opsec-applications", "data-center": "data-centers", "data-center-object": "data-center-objects", "service-tcp": "services-tcp", "service-udp": "services-udp", "service-icmp": "services-icmp", "service-icmp6": "services-icmp6", "service-sctp": "services-sctp", "service-rpc": "services-rpc", "service-other": "services-other", "service-dce-rpc": "services-dce-rpc", "application-site": "applications-sites", "application-site-category": "application-site-categories", "application-site-group": "application-site-groups", "vpn-community-meshed": "vpn-communities-meshed", "vpn-community-star": "vpn-communities-star", "placeholder": "placeholders", "administrator": "administrators", "group": "groups", "group-with-exclusion": "groups-with-exclusion", "service-group": "service-groups", "time-group": "time-groups", "application-group": "application-groups", "threat-protection": "threat-protections", "exception-group": "exception-groups", "generic-object": "", "access-layer": "access-layers", "access-section": "access-sections", "access-rule": "access-rules", "nat-layer": "nat-layers", "nat-section": "nat-sections", "nat-rule": "nat-rules", "threat-layer": "threat-layers", "threat-rule": "threat-rules", "threat-exception-section": "threat-exception-sections", "threat-exception": "threat-exceptions", "wildcard": "wildcards", "updatable-object": "updatable-objects", "https-layer": "https-layers", "https-section": "https-sections", "https-rule": "https-rules" }, "1.8": { "access-role": "access-roles", "threat-profile": "threat-profiles", "host": "hosts", "network": "networks", "address-range": "address_ranges", "multicast-address-range": "multicast-address-ranges", "security-zone": "security-zones", "time": "times", "simple-gateway": "simple-gateways", "dynamic-object": "dynamic-objects", "trusted-client": "trusted-clients", "tags": "tags", "dns-domain": "dns-domains", "opsec-application": "opsec-applications", "data-center": "data-centers", "data-center-object": "data-center-objects", "service-tcp": "services-tcp", "service-udp": "services-udp", "service-icmp": "services-icmp", "service-icmp6": "services-icmp6", "service-sctp": "services-sctp", "service-rpc": "services-rpc", "service-other": "services-other", "service-dce-rpc": "services-dce-rpc", "application-site": "applications-sites", "application-site-category": "application-site-categories", "application-site-group": "application-site-groups", "vpn-community-meshed": "vpn-communities-meshed", "vpn-community-star": "vpn-communities-star", "placeholder": "placeholders", "administrator": "administrators", "group": "groups", "group-with-exclusion": "groups-with-exclusion", "service-group": "service-groups", "time-group": "time-groups", "application-group": "application-groups", "threat-protection": "threat-protections", "exception-group": "exception-groups", "generic-object": "", "access-layer": "access-layers", "access-section": "access-sections", "access-rule": "access-rules", "nat-layer": "nat-layers", "nat-section": "nat-sections", "nat-rule": "nat-rules", "threat-layer": "threat-layers", "threat-rule": "threat-rules", "threat-exception-section": "threat-exception-sections", "threat-exception": "threat-exceptions", "wildcard": "wildcards", "updatable-object": "updatable-objects", "https-layer": "https-layers", "https-section": "https-sections", "https-rule": "https-rules" }, } unexportable_objects_map = {} import_priority = { "vpn-community-meshed": 1, "vpn-community-star": 1, "group": 2, "group-with-exclusion": 3, "service-group": 2, "time-group": 2, "application-group": 2, } generic_objects_for_rule_fields = { "source": ["host", "ip-address"], "destination": ["host", "ip-address"], "vpn": ["vpn-community-star"], "service": ["service-tcp", "port"], "protected-scope": ["multicast-address-range", "ip-address"], } generic_objects_for_duplicates_in_group_members = { "group": ["host", "ip-address"], "service-group": ["service-tcp", "port"], "time-group": ["time"] } placeholder_type_by_obj_type = { "DataType": { "type": "com.checkpoint.management.data_awareness.objects.DataAwarenessCompound" }, "DropUserCheckInteractionScheme": { "bladeName": "APPC", "type": "com.checkpoint.objects.user_check.DropUserCheckInteractionScheme" }, "AskUserCheckInteractionScheme": { "bladeName": "APPC", "type": "com.checkpoint.objects.user_check.AskUserCheckInteractionScheme" }, "InformUserCheckInteractionScheme": { "bladeName": "APPC", "type": "com.checkpoint.objects.user_check.InformUserCheckInteractionScheme" }, "CpmiGatewayCluster": { "ipsBlade": "INSTALLED", "type": "com.checkpoint.objects.classes.dummy.CpmiGatewayCluster" }, "CpmiVsClusterNetobj": { "ipsBlade": "INSTALLED", "type": "com.checkpoint.objects.classes.dummy.CpmiGatewayCluster" }, "CpmiGatewayPlain": { "type": "com.checkpoint.objects.classes.dummy.CpmiGatewayCkp", "ipaddr": None, "vpn1": "true" }, "CpmiIcmpService": { "type": "com.checkpoint.objects.classes.dummy.CpmiIcmpService" }, "CpmiIcmp6Service": { "type": "com.checkpoint.objects.classes.dummy.CpmiIcmp6Service" }, "CpmiAppfwLimit": { "type": "com.checkpoint.objects.appfw.dummy.CpmiAppfwLimit", }, "service-other": { "type": "com.checkpoint.objects.classes.dummy.CpmiOtherService", "matchExp": "Dummy Match Expression" } } group_objects_field = { "group": ["members"], "vpn-community-star": ["center-gateways", "satellite-gateways"], "vpn-community-meshed": ["gateways"], "service-group": ["members"], "time-group": ["members"], "application-site-group": ["members"], "group-with-exclusion": [] } no_export_fields = {"type"} no_export_fields_and_subfields = ["read-only", "layer", "package", "owner", "icon", "domain", "from", "to", "rulebase", "uid", "meta-info", "parent", "groups", "type", "override-default-settings"] no_export_fields_by_api_type = { "host": ["standard-port-number", "subnet-mask", "type"], "network": ["subnet-mask"], "threat-rule": ["exceptions", "exceptions-layer"], "simple-gateway": ["forward-logs-to-log-server-schedule-name", "hardware", "dynamic-ip", "sic-name", "sic-state", "send-alerts-to-server", "send-logs-to-backup-server", "send-logs-to-server", "interfaces"], "application-site": ["application-id", "risk", "user-defined"], "application-site-category": ["user-defined"], "data-center-object": ["name-in-data-center", "data-center", "data-center-object-meta-info", "deleted", "type-in-data-center", "additional-properties"] } fields_to_change = { "alert-when-free-disk-space-below-metrics": "free-disk-space-metrics", "delete-index-files-when-index-size-above-metrics": "free-disk-space-metrics", "delete-when-free-disk-space-below-metrics": "free-disk-space-metrics", "stop-logging-when-free-disk-space-below-metrics": "free-disk-space-metrics" } fields_to_exclude_in_the_presence_of_other_fields = { "maximum-limit-for-concurrent-connections": "auto-maximum-limit-for-concurrent-connections", "maximum-memory-pool-size": "auto-calculate-connections-hash-table-size-and-memory-pool", "memory-pool-size": "auto-calculate-connections-hash-table-size-and-memory-pool" } fields_to_exclude_from_import_by_api_type_and_versions = { "network": { "broadcast": ["1"] } } partially_exportable_types = ["simple-gateway"] special_treatment_types = [ "threat-profile" ] https_blades_names_map = { "Anti-Virus": "Anti Virus", "Anti-Bot": "Anti Bot", "URL Filtering": "Url Filtering", "Data Loss Prevention": "DLP", "Content Awareness": "Data Awareness" } commands_support_batch = ['access-role', 'address-range', 'application-site-category', 'application-site-group', 'dns-domain', 'dynamic-object', 'group-with-exclusion', 'host', 'lsv-profile', 'multicast-address-range', 'network', 'package', 'security-zone', 'service-dce-rpc', 'service-group', 'service-icmp', 'service-other', 'service-sctp', 'service-tcp', 'service-udp', 'tacacs-server', 'tacacs-group', 'tag', 'time', 'time-group', 'vpn-community-meshed', 'vpn-community-star', 'wildcard'] rule_support_batch = ['access-rule', 'https-rule', 'nat-rule', 'threat-exception'] not_unique_name_with_dedicated_api = { "Unknown Traffic": "show-application-site-category" } types_not_support_tagging = ["rule", "section", "threat-exception"]
class Node: def __init__(self, node_id, lon, lat, cluster_id_belongto: int): self.node_id = int(node_id) self.lon = lon self.lat = lat self.cluster_id_belongto = cluster_id_belongto
# cook your dish here t = int(input()) # Taking the Number of Test Cases for i in range(t): # Looping over test cases n = int(input()) # Taking the length of songs input p = [int(i) for i in input().split()] # Taking the list of song length as input k = int(input()) # Taking the position of the uncle jhony song(taking indexing from 1) ele = p[k-1] # Storing that element in a variable (position was taken -1 as indexing of our list is from 0 and user entered according to indexing starting from 1) for i in range(n): # Here for sorting the list we use bubble sort algorithm j = 0 # bubble sorting program - line 10 to 14 for j in range(0, n-i-1): if p[j] > p[j+1]: p[j], p[j+1] = p[j+1], p[j] ls = (p.index(ele)) # Now geeting the position of uncle jhony song in sorted list. print(ls+1) # Printing the position + 1 as the indexing started from 0.
print("Insert a string") s = input() print("Insert the number of times it will be repeated") n = int(input()) res = "" for i in range(n): res = res + s print(res)
#Twitter API Credentials consumer_key = 'consumerkey' consumer_secret = 'consumersecret' access_token = 'accesstoken' access_secret = 'accesssecret'
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) class BerkeleyDb(AutotoolsPackage): """Oracle Berkeley DB""" homepage = "https://www.oracle.com/database/technologies/related/berkeleydb.html" # URL must remain http:// so Spack can bootstrap curl url = "http://download.oracle.com/berkeley-db/db-18.1.40.tar.gz" version("18.1.40", sha256="0cecb2ef0c67b166de93732769abdeba0555086d51de1090df325e18ee8da9c8") version('18.1.32', sha256='fa1fe7de9ba91ad472c25d026f931802597c29f28ae951960685cde487c8d654', deprecated=True) version('6.2.32', sha256='a9c5e2b004a5777aa03510cfe5cd766a4a3b777713406b02809c17c8e0e7a8fb') version('6.1.29', sha256='b3c18180e4160d97dd197ba1d37c19f6ea2ec91d31bbfaf8972d99ba097af17d') version('6.0.35', sha256='24421affa8ae436fe427ae4f5f2d1634da83d3d55a5ad6354a98eeedb825de55', deprecated=True) version('5.3.28', sha256='e0a992d740709892e81f9d93f06daf305cf73fb81b545afe72478043172c3628') variant('docs', default=False) variant('cxx', default=False, description='Build with C++ API') variant('stl', default=False, description='Build with C++ STL API') configure_directory = 'dist' build_directory = 'build_unix' patch("drop-docs.patch", when='~docs') conflicts('%clang@7:', when='@5.3.28') conflicts('%gcc@8:', when='@5.3.28') conflicts('+stl', when='~cxx', msg='+stl implies +cxx') def patch(self): # some of the docs are missing in 18.1.40 if self.spec.satisfies("@18.1.40"): filter_file(r'bdb-sql', '', 'dist/Makefile.in') filter_file(r'gsg_db_server', '', 'dist/Makefile.in') def configure_args(self): spec = self.spec config_args = [ '--disable-static', '--enable-dbm', # compat with system berkeley-db on darwin "--enable-compat185", # SSL support requires OpenSSL, but OpenSSL depends on Perl, which # depends on Berkey DB, creating a circular dependency '--with-repmgr-ssl=no', ] config_args += self.enable_or_disable('cxx') config_args += self.enable_or_disable('stl') # The default glibc provided by CentOS 7 and Red Hat 8 does not provide # proper atomic support when using the NVIDIA compilers if (spec.satisfies('%nvhpc') and (spec.satisfies('os=centos7') or spec.satisfies('os=rhel8'))): config_args.append('--disable-atomicsupport') return config_args def test(self): """Perform smoke tests on the installed package binaries.""" exes = [ 'db_checkpoint', 'db_deadlock', 'db_dump', 'db_load', 'db_printlog', 'db_stat', 'db_upgrade', 'db_verify' ] for exe in exes: reason = 'test version of {0} is {1}'.format(exe, self.spec.version) self.run_test(exe, ['-V'], [self.spec.version.string], installed=True, purpose=reason, skip_missing=True)
def findXorSum(arr, n): Sum = 0 mul = 1 for i in range(30): c_odd = 0 odd = 0 for j in range(n): if ((arr[j] & (1 << i)) > 0): odd = (~odd) if (odd): c_odd += 1 for j in range(n): Sum += (mul * c_odd)%(10**9+7) if ((arr[j] & (1 << i)) > 0): c_odd = (n - j - c_odd) mul *= 2 return Sum%(10**9+7)
#!/usr/bin/env python # -*- coding: utf-8 -*- class APIException(Exception): """ Base class for all API exceptions. """ pass class APIError(APIException): """ An API error signifies a problem with the server, a temporary issue or some other easily-repairable problem. """ pass class APIFailure(APIException): """ An API failure signifies a problem with your request (e.g.: invalid API), a problem with your data, or any error that resulted from improper use. """ pass class APIBadCall(APIFailure): """ Your API call doesn't match the API's specification. Check your arguments, service name, command & version. """ pass class APINotFound(APIFailure): """ The API you tried to call does not exist. (404) """ pass class APIUnauthorized(APIFailure): """ The API you've attempted to call either requires a key, or your key has insufficient permissions. If you're requesting user details, make sure their privacy level permits you to do so, or that you've properly authorised said user. (401) """ pass class APITooManyRequests(APIFailure): """ Too many requests has been made for your actual plan. (429) """ pass def check(response): """ :type response: requests.Response """ if response.status_code // 100 == 4: if response.status_code == 404: raise APINotFound("The function or service you tried to call does not exist.") elif response.status_code == 401: raise APIUnauthorized("This API is not accessible to you.") elif response.status_code == 429: raise APITooManyRequests("Limitations has been reached for you actual plan.") elif response.status_code == 400: raise APIBadCall("The parameters you sent didn't match this API's requirements.") else: raise APIFailure("Something is wrong with your configuration, parameters or environment.") elif response.status_code // 100 == 5: raise APIError("The API server has encountered an unknown error.") else: return
# Leia um frase completa e mostre quantas veze aparece a letra a, em qual posiçao aparece pela 1 vez # em qual posição aparece pela ultima vez frase = str(input('Digite uma frase qualquer: ')).upper().strip() print(frase.count('A')) print(frase.find('A')+1) print(frase.rfind('A')+1) # Começa da direita para esquerda
# # PySNMP MIB module CISCOSB-TBI-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCOSB-TBI-MIB # Produced by pysmi-0.3.4 at Wed May 1 12:23:42 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, ObjectIdentifier, OctetString = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsIntersection, SingleValueConstraint, ValueSizeConstraint, ConstraintsUnion, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "SingleValueConstraint", "ValueSizeConstraint", "ConstraintsUnion", "ValueRangeConstraint") switch001, = mibBuilder.importSymbols("CISCOSB-MIB", "switch001") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") NotificationType, TimeTicks, MibIdentifier, Integer32, MibScalar, MibTable, MibTableRow, MibTableColumn, ObjectIdentity, IpAddress, ModuleIdentity, Gauge32, Bits, iso, Counter32, Unsigned32, Counter64 = mibBuilder.importSymbols("SNMPv2-SMI", "NotificationType", "TimeTicks", "MibIdentifier", "Integer32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ObjectIdentity", "IpAddress", "ModuleIdentity", "Gauge32", "Bits", "iso", "Counter32", "Unsigned32", "Counter64") RowStatus, DisplayString, TextualConvention, TruthValue = mibBuilder.importSymbols("SNMPv2-TC", "RowStatus", "DisplayString", "TextualConvention", "TruthValue") rlTBIMib = ModuleIdentity((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 145)) rlTBIMib.setRevisions(('2006-02-12 00:00',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: rlTBIMib.setRevisionsDescriptions(('Time Range Infrastructure MIBs initial version. ',)) if mibBuilder.loadTexts: rlTBIMib.setLastUpdated('200604040000Z') if mibBuilder.loadTexts: rlTBIMib.setOrganization('Cisco Small Business') if mibBuilder.loadTexts: rlTBIMib.setContactInfo('Postal: 170 West Tasman Drive San Jose , CA 95134-1706 USA Website: Cisco Small Business Home http://www.cisco.com/smb>;, Cisco Small Business Support Community <http://www.cisco.com/go/smallbizsupport>') if mibBuilder.loadTexts: rlTBIMib.setDescription('Time Range Infrastructure MIBs initial version. ') rlTBITimeRangeTable = MibTable((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 145, 1), ) if mibBuilder.loadTexts: rlTBITimeRangeTable.setStatus('current') if mibBuilder.loadTexts: rlTBITimeRangeTable.setDescription('This table specifies Time Based Infra table') rlTBITimeRangeEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 145, 1, 1), ).setIndexNames((1, "CISCOSB-TBI-MIB", "rlTBITimeRangeName")) if mibBuilder.loadTexts: rlTBITimeRangeEntry.setStatus('current') if mibBuilder.loadTexts: rlTBITimeRangeEntry.setDescription('Each entry in this table describes the new time range for ACE. The index is time range name') rlTBITimeRangeName = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 145, 1, 1, 1), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))) if mibBuilder.loadTexts: rlTBITimeRangeName.setStatus('current') if mibBuilder.loadTexts: rlTBITimeRangeName.setDescription('Name of time range.') rlTBITimeRangeAbsoluteStart = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 145, 1, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 14))).setMaxAccess("readwrite") if mibBuilder.loadTexts: rlTBITimeRangeAbsoluteStart.setStatus('current') if mibBuilder.loadTexts: rlTBITimeRangeAbsoluteStart.setDescription('Time of start of absolute time range in following format: month day year hh:mm month: 01-12 (January-December) day: 01-31 year: 0-99 (2000-2099) hh: 0-23 (hours) mm: 0-59 (minutes)') rlTBITimeRangeAbsoluteEnd = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 145, 1, 1, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 14))).setMaxAccess("readwrite") if mibBuilder.loadTexts: rlTBITimeRangeAbsoluteEnd.setStatus('current') if mibBuilder.loadTexts: rlTBITimeRangeAbsoluteEnd.setDescription('Time of end of absolute time range in following format: month day year hh:mm month: 01-12 (January-December) day: 01-31 year: 0-99 (2000-2099) hh: 0-23 (hours) mm: 0-59 (minutes)') rlTBITimeRangeActiveStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 145, 1, 1, 4), TruthValue()).setMaxAccess("readonly") if mibBuilder.loadTexts: rlTBITimeRangeActiveStatus.setStatus('current') if mibBuilder.loadTexts: rlTBITimeRangeActiveStatus.setDescription('Shows whether the current time range is active according to the current clock.') rlTBITimeRangeRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 145, 1, 1, 5), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: rlTBITimeRangeRowStatus.setStatus('current') if mibBuilder.loadTexts: rlTBITimeRangeRowStatus.setDescription('Row Status. It is used for adding/deleting entries of this table.') class RlTBIWeekDayList(TextualConvention, Bits): description = 'Bitmap that includes days of week. Each bit in the bitmap associated with corresponding day of the week.' status = 'current' namedValues = NamedValues(("monday", 0), ("tuesday", 1), ("wednesday", 2), ("thursday", 3), ("friday", 4), ("saturday", 5), ("sunday", 6)) rlTBIPeriodicTable = MibTable((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 145, 2), ) if mibBuilder.loadTexts: rlTBIPeriodicTable.setStatus('current') if mibBuilder.loadTexts: rlTBIPeriodicTable.setDescription('This table specifies Time Based Infra Periodic table') rlTBIPeriodicEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 145, 2, 1), ).setIndexNames((0, "CISCOSB-TBI-MIB", "rlTBIPeriodicTimeRangeName"), (0, "CISCOSB-TBI-MIB", "rlTBIPeriodicWeekDayList"), (0, "CISCOSB-TBI-MIB", "rlTBIPeriodicStart"), (0, "CISCOSB-TBI-MIB", "rlTBIPeriodicEnd")) if mibBuilder.loadTexts: rlTBIPeriodicEntry.setStatus('current') if mibBuilder.loadTexts: rlTBIPeriodicEntry.setDescription('Each entry in this table describes periodic time range.') rlTBIPeriodicTimeRangeName = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 145, 2, 1, 1), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))) if mibBuilder.loadTexts: rlTBIPeriodicTimeRangeName.setStatus('current') if mibBuilder.loadTexts: rlTBIPeriodicTimeRangeName.setDescription('Time Range Name the periodic is defined on. ') rlTBIPeriodicWeekDayList = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 145, 2, 1, 2), RlTBIWeekDayList()).setMaxAccess("readwrite") if mibBuilder.loadTexts: rlTBIPeriodicWeekDayList.setStatus('current') if mibBuilder.loadTexts: rlTBIPeriodicWeekDayList.setDescription('The bitmap allows to user to select periodic time range for several days at once. The periodic range will be associated with specific days when corresponding bits will be set. If at least one bit has been set in the rlTBIPeriodicWeekDayList, the weekday in rlTBIPeriodicStart and rlTBIPeriodicEnd is not relevant and should be set to zero.') rlTBIPeriodicStart = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 145, 2, 1, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 7))).setMaxAccess("readwrite") if mibBuilder.loadTexts: rlTBIPeriodicStart.setStatus('current') if mibBuilder.loadTexts: rlTBIPeriodicStart.setDescription('Time of start of periodic time range in following format: weekday hh:mm weekday: 0-7 (0 means the weekday is not specified, 1-7 are weekdays from Monday to Sunday) hh: 0-23 (hours) mm: 0-59 (minutes) Weekday may be 0 only if periodic time range weekdays were specified in rlTBIPeriodicWeekDayList.') rlTBIPeriodicEnd = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 145, 2, 1, 4), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 7))).setMaxAccess("readwrite") if mibBuilder.loadTexts: rlTBIPeriodicEnd.setStatus('current') if mibBuilder.loadTexts: rlTBIPeriodicEnd.setDescription('Time of end of periodic time range in following format: weekday hh:mm weekday: 0-7 (0 means the weekday is not specified, 1-7 are weekdays from Monday to Sunday) hh: 0-23 (hours) mm: 0-59 (minutes) Weekday may be 0 only if periodic time range weekdays were specified in rlTBIPeriodicWeekDayList.') rlTBIPeriodicRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 145, 2, 1, 5), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: rlTBIPeriodicRowStatus.setStatus('current') if mibBuilder.loadTexts: rlTBIPeriodicRowStatus.setDescription('Row Status. It is used for adding/deleting entries of this table.') mibBuilder.exportSymbols("CISCOSB-TBI-MIB", rlTBIPeriodicEnd=rlTBIPeriodicEnd, PYSNMP_MODULE_ID=rlTBIMib, rlTBIPeriodicRowStatus=rlTBIPeriodicRowStatus, rlTBIPeriodicEntry=rlTBIPeriodicEntry, rlTBITimeRangeName=rlTBITimeRangeName, rlTBIPeriodicTimeRangeName=rlTBIPeriodicTimeRangeName, rlTBITimeRangeAbsoluteStart=rlTBITimeRangeAbsoluteStart, rlTBITimeRangeActiveStatus=rlTBITimeRangeActiveStatus, RlTBIWeekDayList=RlTBIWeekDayList, rlTBIPeriodicWeekDayList=rlTBIPeriodicWeekDayList, rlTBIMib=rlTBIMib, rlTBIPeriodicStart=rlTBIPeriodicStart, rlTBITimeRangeAbsoluteEnd=rlTBITimeRangeAbsoluteEnd, rlTBITimeRangeEntry=rlTBITimeRangeEntry, rlTBITimeRangeTable=rlTBITimeRangeTable, rlTBIPeriodicTable=rlTBIPeriodicTable, rlTBITimeRangeRowStatus=rlTBITimeRangeRowStatus)
n = int(input('Digite um número inteiro aqui: ')) n2 = float(input('Digite um número real ou flutuante aqui: ')) a = n + n2 b = n - n2 c = n * n2 d = n / n2 e = n // n2 f = n % n2 g = n ** n2 print('A soma desses dois números é {}. A subtração é {}. \nA multiplicação é {} e a divisão é {}. \nA divisão inteira é igual a {}. O resto da divisão é {}. E, por último, o valor da exponenciação é {}'.format(a, b, c, d, e, f, g))
def pation(nums): tmp = nums[0] nums[0] = nums[1] nums[1] = tmp return 1 def main(): nums = [3,2,1] p = pation(nums) for n in nums: print(n) if __name__ == "__main__": main()
def create_grades_dict(file_name): file_pointer = open(file_name, 'r') data = file_pointer.readlines() no_return_list = [] for item in data: no_return_list.append(item.strip('\n')) no_spaces_list =[] for item in no_return_list: no_spaces_list.append(item.replace(' ','')) list_of_lists = [] for x in no_spaces_list: list_of_lists.append(x.split(',')) tests_list=['Test_1', 'Test_2', 'Test_3', 'Test_4'] dictionary = {} #making the structure of the dictionary for student_id in list_of_lists: dictionary[student_id[0]] = [student_id[1], 0, 0, 0, 0, 0] #average calculated and saved to dictionary position for lists in list_of_lists: average = 0 for x in range(2, len(lists)): if lists[x] in tests_list: position_number = tests_list.index(lists[x])+1 dictionary[lists[0]][position_number] = int(lists[x+1]) average += int(lists[lists.index(lists[x])+1]) dictionary[lists[0]][5] = average/4 return dictionary # Your main program starts below this line def print_grades(file_name): # Call your create_grades_dict() function to create the dictionary grades_dict=create_grades_dict(file_name) #formatting and printing header header_list = ["ID", "Name", "Test_1", "Test_2", "Test_3", "Test_4", "Avg."] print("{0: ^10} | {1: ^16} | {2: ^6} | {3: ^6} | {4: ^6} | {5: ^6} | {6: ^6} |".format(header_list[0], header_list[1], header_list[2], header_list[3], header_list[4], header_list[5], header_list[6])) #converting tuple in list keys_order_list = list(grades_dict.keys()) keys_order_list.sort() ordered_list = [] for key in keys_order_list: aux_list = [key] for item in grades_dict[key]: aux_list.append(item) ordered_list.append(aux_list) #formatting and printing body for listed in ordered_list: print("{0:10s} | {1:16s} | {2:6d} | {3:6d} | {4:6d} | {5:6d} | {6:6.2f} |".format(listed[0], listed[1], listed[2], listed[3], listed[4], listed[5], listed[6])) print(print_grades('archivo.txt'))
#: docstring for CONSTANT1 CONSTANT1 = "" CONSTANT2 = ""
l, r = map(int, input().split(" ")) if l == r: print(l) else: print(2)
class Session: pass class DB: @staticmethod def get_rds_host(): return '127.0.0.1' def __init__(self, user, password, host, database) -> None: pass def getSession(self): return Session
CHAR_PLUS = ord(b'+') CHAR_NEWLINE = ord(b'\n') def buffered_blob(handle, bufsize): backlog = b'' blob = b'' while True: blob = handle.read(bufsize) if blob == b'': # Could be end of files yield backlog break if backlog != b'': blob = backlog + blob i = blob.rfind(b'\n@', 0) # Make sure no quality line was found if (blob[i-1] == CHAR_PLUS) and (blob[i-2] == CHAR_NEWLINE): i = blob.rfind(b'\n@', 0, i-2) backlog = blob[i+1:len(blob)] yield blob[0:i]
""" Mock unicornhathd module. The intention is to use this module when developing on a different computer than a Raspberry PI with the UnicornHAT attached, e.g. on a Mac laptop. In such case, this module will simply provide the same functions as the original uncornhathd module, however most of them will do absolutely nothing. """ def clear(): pass def off(): pass def show(): pass def set_pixel(x, y, r, g, b): print('UnicornHAT HD: setting pixel ({}, {}, {}, {}, {})'.format(x, y, r, g, b)) def brightness(b): print('UnicornHAT HD: setting brightness to: {}'.format(b)) pass def rotation(r): print('UnicornHAT HD: setting rotation to: {}'.format(r)) pass def get_shape(): return 16, 16
# general I/O parameters OUTPUT_TYPE = "images" LABEL_MAPPING = "pascal" VIDEO_FILE = "data/videos/Ylojarvi-gridiajo-two-guys-moving.mov" OUT_RESOLUTION = None # (3840, 2024) OUTPUT_PATH = "data/predictions/Ylojarvi-gridiajo-two-guys-moving-air-output" FRAME_OFFSET = 600 # 1560 PROCESS_NUM_FRAMES = 300 COMPRESS_VIDEO = True # detection algorithm parameters MODEL = "dauntless-sweep-2_resnet152_pascal-mob-inference.h5" BACKBONE = "resnet152" DETECT_EVERY_NTH_FRAME = 60 USE_TRACKING = True PLOT_OBJECT_SPEED = False SHOW_DETECTION_N_FRAMES = 30 USE_GPU = False PROFILE = False IMAGE_TILING_DIM = 2 IMAGE_MIN_SIDE = 1525 IMAGE_MAX_SIDE = 2025 # Results filtering settings CONFIDENCE_THRES = 0.1 MAX_DETECTIONS_PER_FRAME = 10000 # Bounding box aggregation settings MERGE_MODE = "enclose" MOB_ITERS = 3 BBA_IOU_THRES = 0.001 TOP_K=25
class Coord(object): """ Represent Cartesian coordinates. """ def __init__(self, x=0, y=0): self._x = x self._y = y class Data(object): """ Represent list of coordinates. """ def __init__(self): self._data = []
#!/usr/bin/env python globaldecls = [] globalvars = {} def add_new(decl): if decl: globaldecls.append(decl) globalvars[decl.name] = decl
class BaseClass: def __str__(self): return self.__class__.__name__ def get_params(self, deep=True): pass def set_params(self, **params): pass class BaseTFWrapperSklearn(BaseClass): def compile_graph(self, input_shapes): pass def get_tf_values(self, fetches, feed_dict): pass def save(self): pass def load(self): pass class tf_GAN(BaseTFWrapperSklearn): def fit(self, Xs): pass def generate(self, zs): pass class tf_C_GAN(BaseTFWrapperSklearn): def fit(self, Xs, Ys): pass def generate(self, zs, Ys): pass class tf_info_GAN(BaseTFWrapperSklearn): def fit(self, Xs, Ys): pass def generate(self, zs, Ys): pass class tf_AE(BaseTFWrapperSklearn): def fit(self, Xs): pass def code(self, Xs): pass def recon(self, zs): pass class tf_VAE(BaseTFWrapperSklearn): def fit(self, Xs): pass def encode(self, Xs): pass def decode(self, zs): pass class tf_AAE(BaseTFWrapperSklearn): def fit(self, Xs): pass def code(self, Xs): pass def recon(self, Xs, zs): pass class tf_AAEClassifier(BaseTFWrapperSklearn): def fit(self, Xs): pass def code(self, Xs): pass def recon(self, Xs): pass def predict(self, Xs): pass def score(self, Xs, Ys): pass def proba(self, Xs): pass class tf_MLPClassifier(BaseTFWrapperSklearn): def fit(self, Xs, Ys): pass def predict(self, Xs): pass def score(self, Xs, Ys): pass def proba(self, Xs): pass
"""Utils for time travel testings.""" def _t(rel=0.0): """Return an absolute time from the relative time given. The minimal allowed time in windows is 86400 seconds, for some reason. In stead of doing the arithmetic in the tests themselves, this function should be used. The value `86400` is exported in `time_travel.MIN_START_TIME`, but I shant use it for it is forbidden to test the code using the code that is being tested. """ return 86400.0 + rel
#!/usr/bin/python # encoding: utf-8 """ 作者:糖葫芦 创建时间:2020/3/2918:58 文件:__init__.py.py IDE:PyCharm """
# 289. Game of Life class Solution: def gameOfLife2(self, board) -> None: rows, cols = len(board), len(board[0]) nextState = [row[:] for row in board] dirs = ((0,1), (1,0), (-1,0), (0,-1), (-1,-1), (-1,1), (1,-1), (1,1)) for i in range(rows): for j in range(cols): nbrs = 0 for di, dj in dirs: if 0 <= i+di < rows and 0 <= j+dj < cols: nbrs += nextState[i+di][j+dj] if nextState[i][j] == 1 and (nbrs < 2 or nbrs > 3): board[i][j] = 0 elif nextState[i][j] == 0 and nbrs == 3: board[i][j] = 1 return board def gameOfLife(self, board) -> None: rows, cols = len(board), len(board[0]) dirs = ((0,1), (1,0), (-1,0), (0,-1), (-1,-1), (-1,1), (1,-1), (1,1)) for i in range(rows): for j in range(cols): nbrs = 0 for di, dj in dirs: if 0 <= i+di < rows and 0 <= j+dj < cols and board[i+di][j+dj] > 0: nbrs += 1 board[i][j] = nbrs+10 if board[i][j] == 1 else -nbrs for i in range(rows): for j in range(cols): if board[i][j] > 0: if 12 <= board[i][j] <= 13: board[i][j] = 1 else: board[i][j] = 0 elif board[i][j] <= 0: if board[i][j] == -3: board[i][j] = 1 else: board[i][j] = 0 return board print(Solution().gameOfLife([[1,0,0,0,0,1],[0,0,0,1,1,0],[1,0,1,0,1,0],[1,0,0,0,1,0],[1,1,1,1,0,1],[0,1,1,0,1,0],[1,0,1,0,1,1],[1,0,0,1,1,1],[1,1,0,0,0,0]]))
# Задача 3. Вариант 6. # Напишите программу, которая выводит имя "Самюэл Ленгхорн Клеменс", и запрашивает его псевдоним. Программа должна сцеплять две эти строки и выводить полученную строку, разделяя имя и псевдоним с помощью тире. # Velyan A. S. # 27.05.2016 print("Герой нашей сегодняшней программы - Сэмюэл Ленгхорн Клеменс") print("Под каким же именем мы знаем этого человека?") input("\n\nВаш ответ: Марк Твен") print("\nВсе верно: Самюэл Ленгхорн Клеменс - Марк Твен") input("\nНажмите Enter для выхода")
cache = {} def binomial_coeff(n, k): """Compute the binomial coefficient 'n choose k'. n: number of trials k: number of successes returns: int """ if k == 0: return 1 if n == 0: return 0 try: return cache[n,k] except KeyError: cache[n,k] = binomial_coeff(n-1, k-1) + binomial_coeff(n-1, k) return cache[n,k] def binomial_coeff(n, k=0): if k == 0: return 1 return 0 if n == 0 else binomial_coeff(n-1, k-1) + binomial_coeff(n-1, k) if __name__ == "__main__": print(binomial_coeff(4, 2))
'''https://leetcode.com/problems/merge-two-sorted-lists/''' # Definition for singly-linked list. class ListNode: def __init__(self, x): self.val = x self.next = None # Iterative Solution class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: head = l3 = ListNode(0) while(l1 is not None and l2 is not None): if l1.val <=l2.val: l3.next = ListNode(l1.val) l3 = l3.next l1 = l1.next else: l3.next = ListNode(l2.val) l3 = l3.next l2 = l2.next while l1: l3.next = ListNode(l1.val) l3 = l3.next l1 = l1.next while l2: l3.next = ListNode(l2.val) l3 = l3.next l2 = l2.next return head.next # Recursive Solution class Solution: def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode: if not l1 or not l2: return l1 or l2 if l1.val<l2.val: l1.next = self.mergeTwoLists(l1.next, l2) return l1 else: l2.next = self.mergeTwoLists(l1, l2.next) return l2
q = { 'get_page_id_from_frontier': "UPDATE crawldb.frontier \ SET occupied=True \ WHERE page_id=( \ SELECT page_id \ FROM crawldb.frontier as f \ LEFT JOIN crawldb.page as p \ ON f.page_id=p.id \ WHERE f.occupied=False AND p.site_id IN (\ SELECT id FROM crawldb.site WHERE next_acces<=NOW() OR next_acces IS NULL) \ ORDER BY time_added \ LIMIT 1) \ RETURNING page_id", 'get_link': "SELECT * FROM crawldb.link WHERE from_page=%s AND to_page=%s", 'get_page_by_id': "SELECT * FROM crawldb.page WHERE id=%s", 'get_site_by_domain': "SELECT * FROM crawldb.site WHERE domain=%s", 'add_to_frontier': "INSERT INTO crawldb.frontier (page_id) VALUES(%s)", 'add_new_page': "INSERT INTO crawldb.page (site_id, page_type_code, url) VALUES (%s, %s, %s) RETURNING id", 'add_pages_to_link': "INSERT INTO crawldb.link (from_page, to_page) VALUES (%s, %s)", 'remove_from_frontier': "DELETE FROM crawldb.frontier WHERE page_id=%s", 'update_page_codes': "UPDATE crawldb.page \ SET page_type_code=%s, http_status_code=%s, accessed_time=NOW() \ WHERE id=%s", 'update_frontier_page_occ&time': "UPDATE crawldb.frontier SET occupied=%s WHERE page_id=%s" }
#Faça um programa que mostre o preço de um produto, e mostre seu nvo preço com 5% de desconto. preço = float(input('Qual o preço original? R$')) desconto = preço*0.05 total = preço - desconto print('Sendo o preço original R${:.2f}, com o desconto de 5% fica a R${:.2f}'.format(preço, total )) #pode ser assim tb,[ desconto = preço - (preço * 5 / 100) ]
class NotarizerException(Exception): def __init__(self, error_code, error_message): super().__init__(error_message) self.error_code = error_code class NoSignatureFound(NotarizerException): def __init__(self, error_message): super().__init__(10, error_message) class InvalidLabelSignature(NotarizerException): def __init__(self, error_message): super().__init__(11, error_message) class VerificationFailure(NotarizerException): def __init__(self, error_message): super().__init__(12, error_message) class ImageNotFound(NotarizerException): def __init__(self, error_message): super().__init__(14, error_message) class SigningError(NotarizerException): def __init__(self, reason): super().__init__(16, "Error Creating Signed Docker Image") self.reason = reason class PublicKeyNotFound(NotarizerException): def __init__(self): super().__init__(13, "No Public Key Provided") class PrivateKeyNotFound(NotarizerException): def __init__(self): super().__init__(15, "No Private Key Provided")
#!/usr/bin/env python """ __init__ Module containing common components for creating components. """
with open("input.txt", "r") as file: numbers = list(map(int, file.readline().split(","))) boards = [] line = file.readline() # throw away while line: board = [] for i in range(5): line = file.readline() board.append(list(map(int, filter(lambda x: len(x) > 0, line.strip().split(" "))))) boards.append(board) line = file.readline() board_masks = [([([False for j in range(5)]) for i in range(5)]) for b in range(len(boards))] bingo_board = 0 numbers_until_bingo = len(numbers) for k in range(len(boards)): board = boards[k] matches = 0 for l in range(numbers_until_bingo): number = numbers[l] for i in range(5): row = board[i] for j in range(5): if row[j] == number: matches += 1 board_masks[k][i][j] = True if matches >= 5: # can't get a bingo with 4 numbers or less. current_board_bingo = False # check rows for i in range(5): row = board_masks[k][i] if sum(row) == 5: current_board_bingo = True # check columns if not current_board_bingo: for i in range(5): mask = board_masks[k] if sum([mask[0][i], mask[1][i], mask[2][i], mask[3][i], mask[4][i]]) == 5: current_board_bingo = True if current_board_bingo: if l < numbers_until_bingo: numbers_until_bingo = l bingo_board = k break last_number_called = numbers[numbers_until_bingo] sum_of_umasked_numbers = 0 for i in range(5): for j in range(5): if not board_masks[bingo_board][i][j]: sum_of_umasked_numbers += boards[bingo_board][i][j] print(sum_of_umasked_numbers * last_number_called)
# # PySNMP MIB module ELTEX-DOT3-OAM-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ELTEX-DOT3-OAM-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 18:45:44 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsUnion, ValueRangeConstraint, ConstraintsIntersection, SingleValueConstraint, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "ValueRangeConstraint", "ConstraintsIntersection", "SingleValueConstraint", "ValueSizeConstraint") eltexLtd, = mibBuilder.importSymbols("ELTEX-SMI-ACTUAL", "eltexLtd") ifIndex, = mibBuilder.importSymbols("IF-MIB", "ifIndex") PortList, = mibBuilder.importSymbols("Q-BRIDGE-MIB", "PortList") NotificationGroup, ObjectGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ObjectGroup", "ModuleCompliance") Gauge32, Unsigned32, Integer32, Counter32, Bits, ModuleIdentity, MibIdentifier, IpAddress, TimeTicks, Counter64, iso, ObjectIdentity, MibScalar, MibTable, MibTableRow, MibTableColumn, NotificationType = mibBuilder.importSymbols("SNMPv2-SMI", "Gauge32", "Unsigned32", "Integer32", "Counter32", "Bits", "ModuleIdentity", "MibIdentifier", "IpAddress", "TimeTicks", "Counter64", "iso", "ObjectIdentity", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "NotificationType") DisplayString, MacAddress, TruthValue, TextualConvention, TimeStamp = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "MacAddress", "TruthValue", "TextualConvention", "TimeStamp") eltexDot3OamMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 35265, 30)) eltexDot3OamMIB.setRevisions(('2013-02-22 00:00',)) if mibBuilder.loadTexts: eltexDot3OamMIB.setLastUpdated('201302220000Z') if mibBuilder.loadTexts: eltexDot3OamMIB.setOrganization('Eltex Ent') eltexDot3OamObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 35265, 30, 1)) eltexDot3OamClearStatistic = MibScalar((1, 3, 6, 1, 4, 1, 35265, 30, 1, 7), PortList()).setMaxAccess("readwrite") if mibBuilder.loadTexts: eltexDot3OamClearStatistic.setStatus('current') mibBuilder.exportSymbols("ELTEX-DOT3-OAM-MIB", eltexDot3OamMIB=eltexDot3OamMIB, eltexDot3OamClearStatistic=eltexDot3OamClearStatistic, eltexDot3OamObjects=eltexDot3OamObjects, PYSNMP_MODULE_ID=eltexDot3OamMIB)
# operacoes matematica x = 53 y = 42 # operacoes comuns soma = x + y mult = x * y div = x / y sub = x - y # divisao inteira div_int = x // y # resto de Divisao rest_div = x % y # potencia potencia = x ** y print (soma) print (mult) print (div) print (sub) print ("Divisao inteira") print (div_int) print ("resto divisao") print (rest_div) print ("potencia") print (potencia)
class Secret: def __init__(self): self._secret=99 self.__top_secret=100 x=Secret() x._secret x.__top_secret x._Secret__top_secret
# Normal List = 39 # Last Card = 5 List = [\ {'eng_title':"SERMONE", 'han_title':"예배 시간",\ 'description':"자신의 턴, <뱅!> 카드를 사용 금지."},\ {'eng_title':"ROULETTE RUSSA", 'han_title':"러시안 룰렛",\ 'description':"이 카드가 발동한 순간, 보완관부터 시작해 순서대로 <빗나감!> 카드를 1장씩 버림. 만약 카드를 버리지 못할 경우, 그 플레이어는 생명령 2를 깎는다."},\ {'eng_title':"DEAD MAN", 'han_title':"돌아온 망자",\ 'description':"게임에서 처음 제거된 플레이어는 생명력 2와 카드 2장을 가진 상태로 부활."},\ {'eng_title':"AGGUATO", 'han_title':"습격",\ 'description':"모든 플레이어 간의 거리는 1이 됨."},\ {'eng_title':"BENEDIZIONE", 'han_title':"축복",\ 'description':"모든 카드를 하트로 취급함."},\ {'eng_title':"NOUVA IDENTITA", 'han_title':"새로운 자아",\ 'description':"각 플레이어는 다른 플레이어의 캐릭터 카드를 확인한 후, 생명력 제한에 위배되지 않을 경우, 캐릭터를 교환할 수 있음. 교환할 경우, 생명력 2로 시작함."},\ {'eng_title':"CITTA' FANTASMA", 'han_title':"유령 마을",\ 'description':"죽은 플레이어는 각자 원래 차례에 3장을 드로우한 상태에서 부활하며, 사망하지 않음. 자신의 턴이 종료하면 유령은 게임에서 다시 퇴장."},\ {'eng_title':"CORSA ALL'ORO", 'han_title':"골드러시",\ 'description':"이번 라운드만, 카드 효과를 포함한 모든 차례가 반대 방향으로 돌아감."},\ {'eng_title':"DOROTHY RAGE", 'han_title':"도로시 레이지",\ 'description':"자신의 턴, 다른 플레이어 한 명이 특정 카드 1장을 사용하라 강요할 수 있음.(없으면 무효)"},\ {'eng_title':"BAVAGLIO", 'han_title':"재갈",\ 'description':"모든 플레이어는 말을 할 수 없음.(어길 경우 생명력 -1)"},\ {'eng_title':"CAMPOSANTO", 'han_title':"공동묘지",\ 'description':"죽은 모든 플레이어는 생명 1인채로 부활. 역할은 죽은 플레이어끼리 섞어서 나누어짐."},\ {'eng_title':"REVEREND", 'han_title':"목사",\ 'description':"이번 라운드동안 맥주를 사용할 수 없다. 주점은 가능하다."},\ {'eng_title':"CURSE", 'han_title':"저주",\ 'description':"전체 라운드 동안 모든 카드의 트럼프 무늬는 하트가 된다."},\ {'eng_title':"Doctor", 'han_title':"의사",\ 'description':" 플레이어들 중 생명점이 가장 적은 플레이어들은 체력을 1 회복."},\ {'eng_title':"Hangover", 'han_title':"만취",\ 'description':"모든 캐릭터의 특수능력이 일시적으로 사라진다."},\ {'eng_title':"Train Arrival", 'han_title':"기차 도착",\ 'description':"자신의 턴을 시작할때 카드를 받는 단계후에 카드 한 장을 더 받는다."},\ {'eng_title':"Shootout", 'han_title':"총격전",\ 'description':"턴당 뱅 카드를 쓸 수 있는 제한이 2장으로 늘어나게 된다."},\ {'eng_title':"Thirst", 'han_title':"갈증",\ 'description':"자신의 턴에 카드 한장만 가져올 수 있게 된다."},\ {'eng_title':"Handcuffs", 'han_title':"수갑",\ 'description':"(카드 가져오기) 가 끝나고, 각 플레이어는 카드 트럼프 무늬를 말한다(스페이드/다이아몬드/하트/클로버). 자신의 턴 동안에는 말한 무늬의 카드만 사용 가능하다."},\ {'eng_title':"Hard Liquor", 'han_title':"중류주",\ 'description':"각 플레이어는 페이즈 1(카드 가져오기)를 생략하는 대신 체력을 1 포인트 회복할 수 있다. "},\ {'eng_title':"Ranch", 'han_title':"목장",\ 'description':"(카드 가져오기)가 끝난 직후에, 단 한 번 원하는 수 만큼의 손 안의 카드를 버리고 같은 수의 카드를 카드더미에서 받아온다."},\ {'eng_title':"Law Of The West", 'han_title':"서부의 법칙",\ 'description':"(카드 가져오기)를 할 때, 두번째로 가져온 카드를 보여주고, 사용 가능하다면 사용해야 한다."},\ {'eng_title':"Lasso", 'han_title':"올가미",\ 'description':" 전체 라운드 동안 장착된 카드의 능력은 효과가 없다.(다이너마이트가 터져도 데미지X)"},\ {'eng_title':"Abandoned Mine", 'han_title':"폐광",\ 'description':" (카드 가져오기) 때에는 버려진 카드에서 순차적으로 2장을 가져 온다. 단, 버려진 카드의 수가 페이즈 1을 시행하기에 부족하면 정상적으로 덱에서 가져온다."},\ {'eng_title':"Judge", 'han_title':"심판",\ 'description':"전체 라운드 동안, 어느 누구에게도 카드를 장착할 수 없다."},\ {'eng_title':"Peyote", 'han_title':"피요테 선인장",\ 'description':"(카드 가져오기)를 대신해서, 카드 더미에서 한 장을 뽑기 전에 트럼프 무늬의 색깔을 맞춘다(빨강/검정). 뽑은 후에 확인하여, 맞으면 계속 같은 방법으로 진행하며, 못 맞힌 경우에는 마지막으로 뽑은 카드는 버림."},\ {'eng_title':"Blood Brothers", 'han_title':"피의 형제",\ 'description':"각 플레이어는 턴의 시작에 체력을 1 포인트(마지막 포인트 제외) 감소 시켜 원하는 (살아남은) 사람의 체력을 1 포인트 증가시킬 수 있다."},\ {'eng_title':"Ricochet", 'han_title':"튕겨내기",\ 'description':"각 플레이어는 뱅 카드를 버리고 상대방의(거리 상관 없이) 장착중인 카드를 제거할 수 있다."},\ {'eng_title':"Vendetta", 'han_title':"피의 복수",\ 'description':"각 플레이어는 턴의 끝에, 카드 펼치기를 시전한다. 하트가 나올 경우, 그는 한 번 더 턴을 진행한다."},\ {'eng_title':"Miss Susanna", 'han_title':"미스 수잔나",\ 'description':"자신의 턴에, 반드시 카드를 3장 이상 사용해야 한다. 3장을 사용하지 못하면 그 플레이어는 라이프가 1 감소한다. "},\ {'eng_title':"Lady Rose Of Texas", 'han_title':"텍사스의 레이디 로즈",\ 'description':"자신의 턴에, 자신의 오른쪽에 있는 플레이어와 자리를 바꿀 수 있다. "},\ {'eng_title':"Helena Zontero", 'han_title':"헬레나 존테로",\ 'description':"이 카드가 발동되면, 카드 펼치기를 시전한다. 펼쳐진 카드의 무늬가 하트나 다이아몬드라면(즉, 무늬가 빨간색이라면), 보안관을 제외한 모든 플레이어의 직업을 섞어 랜덤으로 다시 나눠준다."},\ {'eng_title':"Sacagaway", 'han_title':"새커거웨이",\ 'description':"모든 플레이어가 자신의 카드를 공개한 채로 진행한다."},\ {'eng_title':"Darling Valentine", 'han_title':"내 사랑 발렌타인",\ 'description':"자신의 턴을 시작할 때, 자신의 손에 있는 카드를 버리고 그 수만큼 새로 카드를 가져온다."},\ {'eng_title':"Showdown", 'han_title':"최후의 결전",\ 'description':"모든 카드는 뱅으로 여겨 사용할 수 있고, 모든 뱅은 빗나감으로만 여겨 사용할 수 있다. "},\ {'eng_title':"Haze/Cloud", 'han_title':"안개",\ 'description':"각 플레이어는 다른 플레이어를 볼 때 거리가 1 멀어진다."},\ {'eng_title':"Bucked Of", 'han_title':"낙마",\ 'description':"'야생마'를 장착하고 있는 플레이어들은 자기 차례 시작 전에 카드 펼치기를 시전한다. 그 문양이 하트가 아니었을 경우, 생명력을 1 잃고 야생마가 파괴된다."},\ {'eng_title':"Saloon Dance", 'han_title':"파티 타임",\ 'description':"이 카드가 펼쳐졌을 때, 모든 플레이어는 카드 펼치기를 시전한다. 그 후, 하트 문양이 나온 사람들은 그 사람들끼리 시계방향으로 자리를 바꾼다."},\ {'eng_title':"Betrayal", 'han_title':"배신",\ 'description':"이 카드가 펼쳐질 경우 보안관은 카드 펼치기를 한다. 스페이드 문양이 나오면 보안관을 제외한 모든 직업 카드를 섞어서 재분배한다."},\ {'eng_title':"TRADE", 'han_title':"물물교환",\ 'description':"모든 플레이어는 자신의 장착한 카드 전체를 시계 방향으로 교환한다."},\ ] Last_list = [\ {'eng_title':"PER UN PUGNO DI CARTE", 'han_title':"한 줌의 카드",\ 'description':"자신의 차례때, 자기가 든 패의 수만큼의 <뱅!> 공격을 받음."},\ {'eng_title':"Final Hour", 'han_title':"최후의 시간",\ 'description':"모든 플레이어들 사이의 기본 거리는 1이 된다. 이는 장착 카드와 캐릭터 효과로 인하여 조정 가능하다. 각 플레이어는 자신의 차례에 결과적으로 공격을 하는 카드를 사용하거나 무기를 내려놓는 것 외에 아무것도 할 수 없다."},\ {'eng_title':"Ataque Indio", 'han_title':"인디언의 대습격",\ 'description':"자신의 차례가 시작될 때 카드 펼치기를 한다. 만약 스페이드가 나오면 자신을 포함한 모든 플레이어에게 인디언의 효과가 발동된다. "},\ {'eng_title':"WILD WEST SHOW", 'han_title':"와일드 웨스트 쇼",\ 'description':"모든 플레이어의 목적이 마지막에 홀로 살아남는 것으로 변경."},\ {'eng_title':"High Noon", 'han_title':"하이 눈",\ 'description':"모든 플레이어는 자신의 턴이 시작할때 생명점을 하나를 줄이고 시작하게 된다."},\ {'eng_title':"DRECTOR'S CUT", 'han_title':"디렉터즈 컷",\ 'description':"상황 카드를 매 플레이어의 턴이 지날 때마다 계속 바꾼다. 만약 또 라스트 카드를 보게 될 경우, 다시 정지한다."},\ ]
### ML SPECIFIC FUNCTIONS ### FOR FEATURE ENGINEERING # ENCODE EVENT -- 1--event, 0--no event def bin_event(x): x=int(x) if(x!=0): return 1 else: return 0 # YES OR NO def bin_weather(x): x=float(x) if(x>0): return 1 else: return 0 # BIN PRECIPITATION TYPE def bin_ptype(x): if(x==1): # None return 0 else: # rain, snow or sleet return 0 # BIN IN d_bin SECONDS d_bin=10 def bin_delay(x): x=float(x) if(x<=0): return 0 else: return int(x/d_bin) #BIN IN t_bin DEGREES t_bin=10 def bin_temp(x): x=float(x) if(x<=0): return 0 else: return int(x/t_bin) # PEAK HOUR BIN def bin_peak(x): x=float(x) if(6<=x<=10 or 4<=x<=7): return 1 else: return 0 # WEEKDAY BIN def bin_weekday(x): x=float(x) if(x<5): return 1 # WEEKDAY else: return 0 # WEEKEND # SEASON def bin_season(x): x=float(x) if(x in {1,2,12}): return 0 # WINTER elif(x in {3,4,5}): return 1 # SPRING elif(x in {9,10,11}): return 2 # FALL elif(x in {6,7,8}): return 3 # SUMMER else: print("NOT A VALID MONTH") return -1 # WRONG
class DependencyException(Exception): def __init__(self, message, product): super(Exception, self).__init__(message) self.message = message self.product = product self.do_not_print = True class SelfUpgradeException(Exception): def __init__(self, message, parent_pid): super(Exception, self).__init__(message) self.message = message self.parent_pid = parent_pid class TaskException(Exception): def __init__(self, message, product, tb): super(Exception, self).__init__(message) self.message = message self.product = product self.traceback = tb class ProductNotFoundError(Exception): pass class FeedLoaderDownload(Exception): pass class ProductError(Exception): pass
for i in incorrect_idx: print('%d: Predicted %d True label %d' % (i, pred_y[i], test_y[i])) # Plot two dimensions _, ax = plt.subplots() for n in np.unique(test_y): idx = np.where(test_y == n)[0] ax.scatter(test_X[idx, 1], test_X[idx, 2], color=f"C{n}", label=f"Class {str(n)}") for i, marker in zip(incorrect_idx, ['x', 's', 'v']): ax.scatter(test_X[i, 1], test_X[i, 2], color="darkred", marker=marker, s=40, label=i) ax.set(xlabel='sepal width [cm]', ylabel='petal length [cm]', title="Iris Classification results") plt.legend(loc=1, scatterpoints=1);
# -*- coding: UTF-8 -*- # Given two binary strings, return their sum (also a binary string). # # For example, # a = "11" # b = "1" # Return "100". # # Python, Python 3 all accepted. # Maybe the ugliest code I have ever written since I learned Python. class AddBinary(object): def addBinary(self, a, b): """ :type a: str :type b: str :rtype: str """ if a is None or b is None: return "" if len(a) == 0: return b if len(b) == 0: return a # if it needs to plus one flag = False if len(a) >= len(b): longer = a shorter = b else: longer = b shorter = a result = "" i = len(longer) - 1 j = len(shorter) - 1 while i >= 0: if j < 0: if longer[i] == '1': if flag: result += '0' else: result += '1' else: if flag: result += '1' flag = False else: result += '0' else: if longer[i] == '1' and shorter[j] == '1': if flag: result += '1' else: result += '0' flag = True elif longer[i] == '0' and shorter[j] == '0': if flag: result += '1' else: result += '0' flag = False # (l == '1' && s == '0') || (l == '0' && s == '1') else: if flag: result += '0' flag = True else: result += '1' i -= 1 j -= 1 if flag: result += '1' return result[::-1]
# Copyright (c) 2012-2022, Mark Peek <mark@peek.org> # All rights reserved. # # See LICENSE file for full license. def validate_runtime_environment(runtime_environment): """ Validate RuntimeEnvironment for Application Property: Application.RuntimeEnvironment """ VALID_RUNTIME_ENVIRONMENTS = ("SQL-1_0", "FLINK-1_6", "FLINK-1_8", "FLINK-1_11") if runtime_environment not in VALID_RUNTIME_ENVIRONMENTS: raise ValueError( "Application RuntimeEnvironment must be one of: %s" % ", ".join(VALID_RUNTIME_ENVIRONMENTS) ) return runtime_environment
y_a = [2, 2, -2, -2, -1, -1, 1, 1] x_a = [1, -1, 1, -1, 2, -2, 2, -2] s = [] start = list(map(int, input().split())) stop = list(map(int, input().split())) q = [start, None] c = 0 def add_8_paths(p): for a in range(8): np = [p[0] + x_a[a], p[1] + y_a[a]] if np not in q and np not in s and np[0] > 0 and np[1] > 0: q.append(np) while 1: on = q.pop(0) s.append(on) if on == stop: break elif on == None: c += 1 q.append(None) else: add_8_paths(on) print(c)
# Software released under the MIT license (see project root for license file) class Header(): def __init__(self): self.version = 1 self.test_name = "not set" # ------------------------------------------------------------------------------ class Base: def __init__(self): pass class Derived1(Base): def __init__(self, i1 = 7, s2 = "Derived2"): self.i1 = i1 self.s1 = s2 class Derived2(Base): def __init__(self, i1 = 9, s2 = "Derived2"): self.i1 = i1 self.s1 = s2 class OuterG: def __init__(self): self.v = [] # ------------------------------------------------------------------------------ class A: def __init__(self, i = 0, s = ""): self.i1 = i self.s1 = s class OuterA: def __init__(self): self.v = [] class OuterB: def __init__(self): self.v = [] class OuterC: def __init__(self): self.v = [] class OuterD: def __init__(self): self.v = [] class OuterE: def __init__(self): self.v = [] class OuterF: def __init__(self): self.v = [] # ------------------------------------------------------------------------------ class IdentityScrambler: def __init__(self, base_arr = [], seed = 1): self.base_arr = base_arr def __call__(self): return self.base_arr # ------------------------------------------------------------------------------
# This is an example of staring two servo services # and showing each servo in a separate tab in the browsee # Start the servo services s1 = Runtime.createAndStart("Servo1","Servo") s2 = Runtime.createAndStart("Servo2","Servo") # Start the webgui service without starting the browser webgui = Runtime.create("WebGui","WebGui") webgui.autoStartBrowser(False) webgui.startService() # Start the browsers and show the first service ( Servo1 ) webgui.startBrowser("http://localhost:8888/#/service/Servo1") # Wait a little before executing the second startBrowser to allow # the first browser to start so that the second service will be shown # in a new tab. Without the sleep(1) you will probably get two browsers. sleep(1) webgui.startBrowser("http://localhost:8888/#/service/Servo2")
load("@halide//:halide_config.bzl", "halide_system_libs") def halide_language_copts(): _common_opts = [ "-DGOOGLE_PROTOBUF_NO_RTTI", "-fPIC", "-fno-rtti", "-std=c++11", "-Wno-conversion", "-Wno-sign-compare", ] _posix_opts = [ "$(STACK_FRAME_UNLIMITED)", "-fno-exceptions", "-funwind-tables", "-fvisibility-inlines-hidden", ] _msvc_opts = [ "-D_CRT_SECURE_NO_WARNINGS", # Linking with LLVM on Windows requires multithread+DLL CRT "/MD", ] return _common_opts + select({ "@halide//:halide_platform_config_x64_windows_msvc": _msvc_opts, "@halide//:halide_platform_config_x64_windows": ["/error_please_set_cpu_and_host_cpu_x64_windows_msvc"], "@halide//:halide_platform_config_darwin": _posix_opts, "@halide//:halide_platform_config_darwin_x86_64": _posix_opts, "//conditions:default": _posix_opts, }) def halide_language_linkopts(): _linux_opts = [ "-rdynamic", "-ldl", "-lpthread", "-lz" ] _osx_opts = [ "-Wl,-stack_size", "-Wl,1000000" ] _msvc_opts = [] return select({ "@halide//:halide_platform_config_x64_windows_msvc": _msvc_opts, "@halide//:halide_platform_config_x64_windows": ["/error_please_set_cpu_and_host_cpu_x64_windows_msvc"], "@halide//:halide_platform_config_darwin": _osx_opts, "@halide//:halide_platform_config_darwin_x86_64": _osx_opts, "//conditions:default": _linux_opts, }) + halide_system_libs().split(" ") def halide_runtime_linkopts(): _posix_opts = [ "-ldl", "-lpthread", ] _android_opts = [ "-llog", "-landroid", ] _msvc_opts = [] return select({ "@halide//:halide_config_arm_32_android": _android_opts, "@halide//:halide_config_arm_64_android": _android_opts, "@halide//:halide_config_x86_32_android": _android_opts, "@halide//:halide_config_x86_64_android": _android_opts, "@halide//:halide_config_x86_64_windows": _msvc_opts, "//conditions:default": _posix_opts, }) def halide_opengl_linkopts(): _linux_opts = ["-lGL", "-lX11"] _osx_opts = ["-framework OpenGL"] _msvc_opts = [] return select({ "@halide//:halide_config_x86_64_windows": _msvc_opts, "@halide//:halide_config_x86_32_osx": _osx_opts, "@halide//:halide_config_x86_64_osx": _osx_opts, "//conditions:default": _linux_opts, }) # (halide-target-base, cpus, android-cpu, ios-cpu) _HALIDE_TARGET_CONFIG_INFO = [ # Android ("arm-32-android", None, "armeabi-v7a", None), ("arm-64-android", None, "arm64-v8a", None), ("x86-32-android", None, "x86", None), ("x86-64-android", None, "x86_64", None), # iOS ("arm-32-ios", None, None, "armv7"), ("arm-64-ios", None, None, "arm64"), # OSX ("x86-32-osx", None, None, "i386"), ("x86-64-osx", None, None, "x86_64"), # Linux ("arm-64-linux", ["arm"], None, None), ("powerpc-64-linux", ["ppc"], None, None), ("x86-64-linux", ["k8"], None, None), ("x86-32-linux", ["piii"], None, None), # Windows ("x86-64-windows", ["x64_windows_msvc"], None, None), # Special case: Android-ARMEABI. Note that we are using an illegal Target # string for Halide; this is intentional. It allows us to add another # config_setting to match the armeabi-without-v7a required for certain build # scenarios; we special-case this in _select_multitarget to translate it # back into a legal Halide target. # # Note that this won't produce a build that is useful (it will SIGILL on # non-v7a hardware), but isn't intended to be useful for anything other # than allowing certain builds to complete. ("armeabi-32-android", ["armeabi"], "armeabi", None), ] _HALIDE_TARGET_MAP_DEFAULT = { "x86-64-osx": [ "x86-64-osx-sse41-avx-avx2-fma", "x86-64-osx-sse41-avx", "x86-64-osx-sse41", "x86-64-osx", ], "x86-64-windows": [ "x86-64-windows-sse41-avx-avx2-fma", "x86-64-windows-sse41-avx", "x86-64-windows-sse41", "x86-64-windows", ], "x86-64-linux": [ "x86-64-linux-sse41-avx-avx2-fma", "x86-64-linux-sse41-avx", "x86-64-linux-sse41", "x86-64-linux", ], "x86-32-linux": [ "x86-32-linux-sse41", "x86-32-linux", ], } def halide_library_default_target_map(): return _HALIDE_TARGET_MAP_DEFAULT _HALIDE_RUNTIME_OVERRIDES = { # Empty placeholder for now; we may add target-specific # overrides here in the future. } def halide_config_settings(): """Define config_settings for halide_library. These settings are used to distinguish build targets for halide_library() based on target CPU and configs. This is provided to allow algorithmic generation of the config_settings based on internal data structures; it should not be used outside of Halide. """ cpus = [ "darwin", "darwin_x86_64", "x64_windows_msvc", "x64_windows", ] for cpu in cpus: native.config_setting( name="halide_platform_config_%s" % cpu, values={ "cpu": cpu, }, visibility=["//visibility:public"]) for base_target, _, android_cpu, ios_cpu in _HALIDE_TARGET_CONFIG_INFO: if android_cpu == None: # "armeabi" is the default value for --android_cpu and isn't considered legal # here, so we use the value to assume we aren't building for Android. android_cpu = "armeabi" if ios_cpu == None: # The default value for --ios_cpu is "x86_64", i.e. for the 64b OS X simulator. # Assuming that the i386 version of the simulator will be used along side # arm32 apps, we consider this value to mean the flag was unspecified; this # won't work for 32 bit simulator builds for A6 or older phones. ios_cpu = "x86_64" for n, cpu in _config_setting_names_and_cpus(base_target): if cpu != None: values = { "cpu": cpu, "android_cpu": android_cpu, "ios_cpu": ios_cpu, } else: values = { "android_cpu": android_cpu, "ios_cpu": ios_cpu, } native.config_setting( name=n, values=values, visibility=["//visibility:public"]) # Config settings for Sanitizers native.config_setting( name="halide_config_asan", values={"compiler": "asan"}, visibility=["//visibility:public"]) native.config_setting( name="halide_config_msan", values={"compiler": "msan"}, visibility=["//visibility:public"]) native.config_setting( name="halide_config_tsan", values={"compiler": "tsan"}, visibility=["//visibility:public"]) # Alphabetizes the features part of the target to make sure they always match no # matter the concatenation order of the target string pieces. def _canonicalize_target(halide_target): if halide_target == "host": return halide_target if "," in halide_target: fail("Multitarget may not be specified here") tokens = halide_target.split("-") if len(tokens) < 3: fail("Illegal target: %s" % halide_target) # rejoin the tokens with the features sorted return "-".join(tokens[0:3] + sorted(tokens[3:])) # Converts comma and dash separators to underscore and alphabetizes # the features part of the target to make sure they always match no # matter the concatenation order of the target string pieces. def _halide_target_to_bazel_rule_name(multitarget): subtargets = multitarget.split(",") subtargets = [_canonicalize_target(st).replace("-", "_") for st in subtargets] return "_".join(subtargets) def _extract_base_target_pieces(halide_target): if "," in halide_target: fail("Multitarget may not be specified here: %s" % halide_target) tokens = halide_target.split("-") if len(tokens) != 3: fail("Unexpected halide_target form: %s" % halide_target) halide_arch = tokens[0] halide_bits = tokens[1] halide_os = tokens[2] return (halide_arch, halide_bits, halide_os) def _blaze_cpus_for_target(halide_target): halide_arch, halide_bits, halide_os = _extract_base_target_pieces(halide_target) key = "%s-%s-%s" % (halide_arch, halide_bits, halide_os) info = None for i in _HALIDE_TARGET_CONFIG_INFO: if i[0] == key: info = i break if info == None: fail("The target %s is not one we understand (yet)" % key) return info[1] def _config_setting_names_and_cpus(halide_target): """Take a Halide target string and converts to a unique name suitable for a Bazel config_setting.""" halide_arch, halide_bits, halide_os = _extract_base_target_pieces(halide_target) cpus = _blaze_cpus_for_target(halide_target) if cpus == None: cpus = [ None ] if len(cpus) > 1: return [("halide_config_%s_%s_%s_%s" % (halide_arch, halide_bits, halide_os, cpu), cpu) for cpu in cpus] else: return [("halide_config_%s_%s_%s" % (halide_arch, halide_bits, halide_os), cpu) for cpu in cpus] def _config_settings(halide_target): return ["@halide//:%s" % s for (s, _) in _config_setting_names_and_cpus(halide_target)] # The second argument is True if there is a separate file generated # for each subtarget of a multitarget output, False if not. _output_extensions = { "static_library": ("a", False), "o": ("o", False), "h": ("h", False), "cpp_stub": ("stub.h", False), "assembly": ("s.txt", True), "bitcode": ("bc", True), "stmt": ("stmt", True), "schedule": ("schedule", True), "html": ("html", True), "cpp": ("generated.cpp", True), } def _gengen_outputs(filename, halide_target, outputs): new_outputs = {} for o in outputs: if o not in _output_extensions: fail("Unknown output: " + o) ext, is_multiple = _output_extensions[o] if is_multiple and len(halide_target) > 1: # Special handling needed for ".s.txt" and similar: the suffix from the # is_multiple case always goes before the final . # (i.e. "filename.s_suffix.txt", not "filename_suffix.s.txt") # -- this is awkward, but is what Halide does, so we must match it. pieces = ext.rsplit(".", 1) extra = (".%s" % pieces[0]) if len(pieces) > 1 else "" ext = pieces[-1] for h in halide_target: new_outputs[o + h] = "%s%s_%s.%s" % ( filename, extra, _canonicalize_target(h).replace("-", "_"), ext) else: new_outputs[o] = "%s.%s" % (filename, ext) return new_outputs def _gengen_impl(ctx): if _has_dupes(ctx.attr.outputs): fail("Duplicate values in outputs: " + str(ctx.attr.outputs)) if not ctx.attr.generator_closure.generator_name: fail("generator_name must be specified") remaps = [".s=.s.txt,.cpp=.generated.cpp"] halide_target = ctx.attr.halide_target if "windows" in halide_target[-1] and not "mingw" in halide_target[-1]: remaps += [".obj=.o", ".lib=.a"] if ctx.attr.sanitizer: halide_target = [] for t in ctx.attr.halide_target: ct = _canonicalize_target("%s-%s" % (t, ctx.attr.sanitizer)) halide_target += [ct] remaps += ["%s=%s" % (ct.replace("-", "_"), t.replace("-", "_"))] outputs = [ ctx.actions.declare_file(f) for f in _gengen_outputs( ctx.attr.filename, ctx.attr.halide_target, # *not* halide_target ctx.attr.outputs).values() ] leafname = ctx.attr.filename.split('/')[-1] arguments = ["-o", outputs[0].dirname] if ctx.attr.generate_runtime: arguments += ["-r", leafname] if len(halide_target) > 1: fail("Only one halide_target allowed here") if ctx.attr.halide_function_name: fail("halide_function_name not allowed here") else: arguments += ["-g", ctx.attr.generator_closure.generator_name] arguments += ["-n", leafname] if ctx.attr.halide_function_name: arguments += ["-f", ctx.attr.halide_function_name] if ctx.attr.outputs: arguments += ["-e", ",".join(ctx.attr.outputs)] arguments += ["-x", ",".join(remaps)] arguments += ["target=%s" % ",".join(halide_target)] if ctx.attr.halide_generator_args: arguments += ctx.attr.halide_generator_args.split(" ") if ctx.executable.hexagon_code_signer: additional_inputs, _, input_manifests = ctx.resolve_command( tools=[ctx.attr.hexagon_code_signer]) hexagon_code_signer = ctx.executable.hexagon_code_signer.path else: additional_inputs = [] input_manifests = None hexagon_code_signer = "" progress_message = "Executing generator %s with target (%s) args (%s)." % ( ctx.attr.generator_closure.generator_name, ",".join(halide_target), ctx.attr.halide_generator_args) for o in outputs: s = o.path if s.endswith(".h") or s.endswith(".a") or s.endswith(".lib"): continue progress_message += "\nEmitting extra Halide output: %s" % s env = { "HL_DEBUG_CODEGEN": str(ctx.attr.debug_codegen_level), "HL_HEXAGON_CODE_SIGNER": hexagon_code_signer, } ctx.actions.run( # If you need to force the tools to run locally (e.g. for experimentation), # uncomment this line. # execution_requirements={"local":"1"}, arguments=arguments, env=env, executable=ctx.attr.generator_closure.generator_binary.files_to_run.executable, mnemonic="ExecuteHalideGenerator", input_manifests=input_manifests, inputs=additional_inputs, outputs=outputs, progress_message=progress_message ) _gengen = rule( implementation=_gengen_impl, attrs={ "debug_codegen_level": attr.int(), "filename": attr.string(), "generate_runtime": attr.bool(default=False), "generator_closure": attr.label( cfg="host", providers=["generator_binary", "generator_name"]), "halide_target": attr.string_list(), "halide_function_name": attr.string(), "halide_generator_args": attr.string(), "hexagon_code_signer": attr.label( executable=True, cfg="host"), "outputs": attr.string_list(), "sanitizer": attr.string(), }, outputs=_gengen_outputs, output_to_genfiles=True) def _add_target_features(target, features): if "," in target: fail("Cannot use multitarget here") new_target = target.split("-") for f in features: if f and f not in new_target: new_target += [f] return "-".join(new_target) def _has_dupes(some_list): clean = depset(some_list).to_list() return sorted(some_list) != sorted(clean) def _select_multitarget(base_target, halide_target_features, halide_target_map): if base_target == "armeabi-32-android": base_target = "arm-32-android" wildcard_target = halide_target_map.get("*") if wildcard_target: expected_base = "*" targets = wildcard_target else: expected_base = base_target targets = halide_target_map.get(base_target, [base_target]) multitarget = [] for t in targets: if not t.startswith(expected_base): fail( "target %s does not start with expected target %s for halide_target_map" % (t, expected_base)) t = t[len(expected_base):] if t.startswith("-"): t = t[1:] # Check for a "match all base targets" entry: multitarget.append(_add_target_features(base_target, t.split("-"))) # Add the extra features (if any). if halide_target_features: multitarget = [ _add_target_features(t, halide_target_features) for t in multitarget ] # Finally, canonicalize all targets multitarget = [_canonicalize_target(t) for t in multitarget] return multitarget def _gengen_closure_impl(ctx): return struct( generator_binary=ctx.attr.generator_binary, generator_name=ctx.attr.halide_generator_name) _gengen_closure = rule( implementation=_gengen_closure_impl, attrs={ "generator_binary": attr.label( executable=True, allow_files=True, mandatory=True, cfg="host"), "halide_generator_name": attr.string(), }) def _discard_useless_features(halide_target_features = []): # Discard target features which do not affect the contents of the runtime. useless_features = depset(["user_context", "no_asserts", "no_bounds_query", "profile"]) return sorted(depset([f for f in halide_target_features if f not in useless_features.to_list()]).to_list()) def _halide_library_runtime_target_name(halide_target_features = []): return "_".join(["halide_library_runtime"] + _discard_useless_features(halide_target_features)) def _define_halide_library_runtime(halide_target_features = []): target_name = _halide_library_runtime_target_name(halide_target_features) if not native.existing_rule("halide_library_runtime.generator"): halide_generator( name="halide_library_runtime.generator", srcs=[], deps=[], visibility=["//visibility:private"]) condition_deps = {} for base_target, _, _, _ in _HALIDE_TARGET_CONFIG_INFO: settings = _config_settings(base_target) # For armeabi-32-android, just generate an arm-32-android runtime halide_target = "arm-32-android" if base_target == "armeabi-32-android" else base_target halide_target_name = _halide_target_to_bazel_rule_name(base_target); _gengen( name="%s_%s" % (halide_target_name, target_name), filename="%s/%s" % (halide_target_name, target_name), generate_runtime=True, generator_closure="halide_library_runtime.generator_closure", halide_target=["-".join([halide_target] + _discard_useless_features(halide_target_features))], sanitizer=select({ "@halide//:halide_config_asan": "asan", "@halide//:halide_config_msan": "msan", "@halide//:halide_config_tsan": "tsan", "//conditions:default": "", }), outputs=["o"], tags=["manual"], visibility=[ "@halide//:__subpackages__", ] ) for s in settings: condition_deps[s] = ["%s/%s.o" % (halide_target_name, target_name)] native.cc_library( name=target_name, linkopts=halide_runtime_linkopts(), srcs=select(condition_deps), tags=["manual"], visibility=["//visibility:public"]) return target_name def _standard_library_runtime_features(): standard_features = [ [], ["asan"], ["c_plus_plus_name_mangling"], ["cuda"], ["cuda", "matlab"], ["hvx_64"], ["hvx_128"], ["matlab"], ["metal"], ["opengl"], ] return [f for f in standard_features] + [f + ["debug"] for f in standard_features] def _standard_library_runtime_names(): return depset([_halide_library_runtime_target_name(f) for f in _standard_library_runtime_features()]) def halide_library_runtimes(): runtime_package = "" if PACKAGE_NAME != runtime_package: fail("halide_library_runtimes can only be used from package '%s' (this is %s)" % (runtime_package, PACKAGE_NAME)) unused = [_define_halide_library_runtime(f) for f in _standard_library_runtime_features()] unused = unused # unused variable def halide_generator(name, srcs, copts=[], deps=[], generator_name="", includes=[], tags=[], visibility=None): if not name.endswith(".generator"): fail("halide_generator rules must end in .generator") if not generator_name: generator_name = name[:-10] # strip ".generator" suffix native.cc_library( name="%s_library" % name, srcs=srcs, alwayslink=1, copts=copts + halide_language_copts(), deps=depset([ "@halide//:language" ] + deps), tags=["manual"] + tags, visibility=["//visibility:private"]) native.cc_binary( name="%s_binary" % name, copts=copts + halide_language_copts(), linkopts=halide_language_linkopts(), deps=[ ":%s_library" % name, "@halide//:gengen", ], tags=["manual"] + tags, visibility=["//visibility:private"]) _gengen_closure( name="%s_closure" % name, generator_binary="%s_binary" % name, halide_generator_name=generator_name, visibility=["//visibility:private"]) # If srcs is empty, we're building the halide-library-runtime, # which has no stub: just skip it. stub_gen_hdrs_target = [] if srcs: # The specific target doesn't matter (much), but we need # something that is valid, so uniformly choose first entry # so that build product cannot vary by build host stub_header_target = _select_multitarget( base_target=_HALIDE_TARGET_CONFIG_INFO[0][0], halide_target_features=[], halide_target_map={}) _gengen( name="%s_stub_gen" % name, filename=name[:-10], # strip ".generator" suffix generator_closure=":%s_closure" % name, halide_target=stub_header_target, sanitizer=select({ "@halide//:halide_config_asan": "asan", "@halide//:halide_config_msan": "msan", "@halide//:halide_config_tsan": "tsan", "//conditions:default": "", }), outputs=["cpp_stub"], tags=tags, visibility=["//visibility:private"]) stub_gen_hdrs_target = [":%s_stub_gen" % name] native.cc_library( name=name, alwayslink=1, hdrs=stub_gen_hdrs_target, deps=[ ":%s_library" % name, "@halide//:language" ], copts=copts + halide_language_copts(), includes=includes, visibility=visibility, tags=["manual"] + tags) def halide_library_from_generator(name, generator, debug_codegen_level=0, deps=[], extra_outputs=[], function_name=None, generator_args=[], halide_target_features=[], halide_target_map=halide_library_default_target_map(), hexagon_code_signer=None, includes=[], namespace=None, tags=[], visibility=None): if not function_name: function_name = name if namespace: function_name = "%s::%s" % (namespace, function_name) # For generator_args, we support both arrays of strings, and space separated strings if type(generator_args) != type(""): generator_args = " ".join(generator_args); # Escape backslashes and double quotes. generator_args = generator_args.replace("\\", '\\\\"').replace('"', '\\"') if _has_dupes(halide_target_features): fail("Duplicate values in halide_target_features: %s" % str(halide_target_features)) if _has_dupes(extra_outputs): fail("Duplicate values in extra_outputs: %s" % str(extra_outputs)) full_halide_target_features = sorted(depset(halide_target_features + ["c_plus_plus_name_mangling", "no_runtime"]).to_list()) user_halide_target_features = sorted(depset(halide_target_features).to_list()) if "cpp" in extra_outputs: fail("halide_library('%s') doesn't support 'cpp' in extra_outputs; please depend on '%s_cc' instead." % (name, name)) for san in ["asan", "msan", "tsan"]: if san in halide_target_features: fail("halide_library('%s') doesn't support '%s' in halide_target_features; please build with --config=%s instead." % (name, san, san)) generator_closure = "%s_closure" % generator outputs = ["static_library", "h"] + extra_outputs condition_deps = {} condition_hdrs = {} for base_target, _, _, _ in _HALIDE_TARGET_CONFIG_INFO: multitarget = _select_multitarget( base_target=base_target, halide_target_features=full_halide_target_features, halide_target_map=halide_target_map) base_target_name = _halide_target_to_bazel_rule_name(base_target) _gengen( name="%s_%s" % (base_target_name, name), filename="%s/%s" % (base_target_name, name), halide_generator_args=generator_args, generator_closure=generator_closure, halide_target=multitarget, halide_function_name=function_name, sanitizer=select({ "@halide//:halide_config_asan": "asan", "@halide//:halide_config_msan": "msan", "@halide//:halide_config_tsan": "tsan", "//conditions:default": "", }), debug_codegen_level=debug_codegen_level, hexagon_code_signer=hexagon_code_signer, tags=["manual"] + tags, outputs=outputs) libname = "halide_internal_%s_%s" % (name, base_target_name) native.cc_library( name=libname, srcs=["%s/%s.a" % (base_target_name, name)], hdrs=["%s/%s.h" % (base_target_name, name)], tags=["manual"] + tags, visibility=["//visibility:private"]) for s in _config_settings(base_target): condition_deps[s] = [":%s" % libname] condition_hdrs[s] = ["%s/%s.h" % (base_target_name, name)] # Copy the header file so that include paths are correct native.genrule( name="%s_h" % name, srcs=select(condition_hdrs), outs=["%s.h" % name], cmd="for i in $(SRCS); do cp $$i $(@D); done", tags=tags, visibility=visibility ) # Create a _cc target for (unusual) applications that want C++ source output; # we don't support this via extra_outputs=["cpp"] because it can end up being # compiled by Bazel, producing duplicate symbols; also, targets that want this # sometimes want to compile it via a separate tool (e.g., XCode to produce # certain bitcode variants). Note that this deliberately does not produce # a cc_library() output. # Use a canonical target to build CC, regardless of config detected cc_target = _select_multitarget( base_target=_HALIDE_TARGET_CONFIG_INFO[0][0], halide_target_features=full_halide_target_features, halide_target_map=halide_target_map) if len(cc_target) > 1: # This can happen if someone uses halide_target_map # to force everything to be multitarget. In that # case, just use the first entry. cc_target = [cc_target[0]] _gengen( name="%s_cc" % name, filename=name, halide_generator_args=generator_args, generator_closure=generator_closure, halide_target=cc_target, sanitizer=select({ "@halide//:halide_config_asan": "asan", "@halide//:halide_config_msan": "msan", "@halide//:halide_config_tsan": "tsan", "//conditions:default": "", }), halide_function_name=function_name, outputs=["cpp"], tags=["manual"] + tags) runtime_library = _halide_library_runtime_target_name(user_halide_target_features) if runtime_library in _standard_library_runtime_names().to_list(): runtime_library = "@halide//:%s" % runtime_library else: if not native.existing_rule(runtime_library): _define_halide_library_runtime(user_halide_target_features) # Note to maintainers: if this message is reported, you probably want to add # feature combination as an item in _standard_library_runtime_features() # in this file. (Failing to do so will only cause potentially-redundant # runtime library building, but no correctness problems.) print("\nCreating Halide runtime library for feature set combination: " + str(_discard_useless_features(user_halide_target_features)) + "\n" + "If you see this message, there is no need to take any action; " + "however, please forward this message to halide-dev@lists.csail.mit.edu " + "so that we can include this case to reduce build times.") runtime_library = ":%s" % runtime_library native.cc_library( name=name, hdrs=[":%s_h" % name], # Order matters: runtime_library must come *after* condition_deps, so that # they will be presented to the linker in this order, and we want # unresolved symbols in the generated code (in condition_deps) to be # resolved in the runtime library. deps=select(condition_deps) + deps + ["@halide//:runtime", runtime_library], includes=includes, tags=tags, visibility=visibility) # Although "#include SOME_MACRO" is legal C/C++, it doesn't work in all environments. # So, instead, we'll make a local copy of the .cpp file and use sed to # put the include path in directly. native.genrule( name = "%s_RunGenStubs" % name, srcs = [ "@halide//:tools/RunGenStubs.cpp" ], cmd = "cat $(location @halide//:tools/RunGenStubs.cpp) | " + "sed -e 's|HL_RUNGEN_FILTER_HEADER|\"%s%s%s.h\"|g' > $@" % (PACKAGE_NAME, "/" if PACKAGE_NAME else "", name), outs = [ "%s_RunGenStubs.cpp" % name, ], tags=["manual", "notap"] + tags, visibility=["//visibility:private"] ) # Note that the .rungen targets are tagged as manual+notap, as some # extant Generators don't (yet) have the proper generator_deps # or filter_deps configured. ("notap" is used internally by # certain Google test systems; it is ignored in public Bazel builds.) # # (Of course, this requires that we have some explicit build-and-link tests # elsewhere to verify that at least some expected-to-work Generators # stay working.) native.cc_binary( name="%s.rungen" % name, srcs=[":%s_RunGenStubs" % name], deps=[ "@halide//:rungen", ":%s" % name, ], tags=["manual", "notap"] + tags, visibility=["//visibility:private"]) # Return the fully-qualified built target name. return "//%s:%s" % (PACKAGE_NAME, name) def halide_library(name, srcs, copts=[], debug_codegen_level=0, extra_outputs=[], # "stmt" and/or "assembly" are useful for debugging filter_deps=[], function_name=None, generator_args=[], generator_deps=[], generator_name=None, halide_target_features=[], halide_target_map=halide_library_default_target_map(), hexagon_code_signer=None, includes=[], namespace=None, visibility=None): halide_generator( name="%s.generator" % name, srcs=srcs, generator_name=generator_name, deps=generator_deps, includes=includes, copts=copts, visibility=visibility) return halide_library_from_generator( name=name, generator=":%s.generator" % name, deps=filter_deps, visibility=visibility, namespace=namespace, includes=includes, function_name=function_name, generator_args=generator_args, debug_codegen_level=debug_codegen_level, halide_target_features=halide_target_features, halide_target_map=halide_target_map, hexagon_code_signer=hexagon_code_signer, extra_outputs=extra_outputs)
# pylint: disable=missing-function-docstring, missing-module-docstring/ def compare_str_isnot() : n = 'hello world' a = 'hello world' return n is not a
def calcOccurrences(itemset: list) -> int: return len(list(filter(lambda x: x == 1, itemset))) def calcOccurrencesOfBoth(itemset1: list, itemset2: list) -> int: count: int = 0 for i in range(len(itemset1)): if itemset1[i] == 1 and itemset2[i] == 1: count += 1 return count def support(*itemsets) -> float: occurrencesOfItem: float = 0 if len(itemsets) == 1: occurrencesOfItem = calcOccurrences(itemsets[0]) elif len(itemsets) == 2: occurrencesOfItem = calcOccurrencesOfBoth(itemsets[0], itemsets[1]) return occurrencesOfItem / len(itemsets[0]) def confidence(itemset1: list, itemset2: list) -> float: supportOfBoth: float = support(itemset1, itemset2) return supportOfBoth / support(itemset1) def lift(itemset1: list, itemset2: list): supportOfBoth = support(itemset1, itemset2) return supportOfBoth / (support(itemset1) * support(itemset2)) def main(): basket: dict = { 'milk': [1, 1, 1, 0], 'eggs': [1, 1, 0, 1], 'apples': [0, 0, 0, 1], 'bread': [1, 0, 1, 0] } print(f'Support {support(basket["milk"])}') print(f'Confidence {confidence(basket["milk"], basket["eggs"])}') print(f'Lift {lift(basket["milk"], basket["eggs"])}') if __name__ == '__main__': main()
# names = ['LHL','YB','ZSH','LY','DYC'] # # print(str(x[0]) + str(x[1]) + str(x[2]) + str(x[3]) + str(x[4])); # for name in names: # print(name.lower().title()); # print("SB:" + name); # for name in names: # print(name.lower().title()); # print("SB:" + name); # for name in names: # print(name.lower().title()); # print("SB:" + name); # x = 0; # print(x); provinces = [['Kunming','Anning','Dali'],['Beijing'],['Shenzhen','GuangZhou','ZhuHai','Shantou']] # [Kunming,Anning,Dali] for province in provinces: for city in province: print(city);
""" Version information for Lackey module """ __version__ = "0.7.4" __sikuli_version__ = "1.1.0"
''' @author: zhzj Scrivere un programma che legge un intero positivo n da stdin e verifica se n è un numero mancante, perfetto o abbondante. Chiamiamo S(n) la somma di tutti i divisori propri di n (1 incluso, n escluso). Un numero n si dice perfetto se n = S(n), mancante se n > S(n), abbondante se n < S(n). Esempio: 10: MANCANTE 12: ABBONDANTE 28: PERFETTO ''' def main() : n = int(input("Inserisci un numero: ")) somma = 0 for i in range(1, n) : if n % i == 0 : # se è un divisore somma += i if n == somma : print("Perfetto") elif n > somma : print("Mancante") else : print("Abbondante")
# Source : https://leetcode.com/problems/minimum-moves-to-convert-string/ # Author : foxfromworld # Date : 10/12/2021 # First attempt class Solution: def minimumMoves(self, s: str) -> int: index = 0 ret = 0 while index < len(s): if s[index] == 'X': ret += 1 index += 3 else: index += 1 return ret
def fact(n): return 1 if n == 0 else n*fact(n-1) def comb(n, x): return fact(n) / (fact(x) * fact(n-x)) def b(x, n, p): return comb(n, x) * p**x * (1-p)**(n-x) l, r = list(map(float, input().split(" "))) odds = l / r print(round(sum([b(i, 6, odds / (1 + odds)) for i in range(3, 7)]), 3))
n, m = map(int, input().split()) for _ in range(n): if input().find('LOVE') != -1: print('YES') exit() print('NO')
# Created byMartin.cz # Copyright (c) Martin Strohalm. All rights reserved. class Enum(object): """ Defines a generic enum type, where values are provided as key:value pairs. The key can be used to access the value like from dict (e.g. enum[key]) or as property (e.g. enum.key). Each value must be unique. Note that unlike the normal dict, the Enum __contains__ method is not checking for keys but for values. """ def __init__(self, **kwargs): """Initializes a new instance of Enum.""" # get named values self._map = kwargs # get all values values = list(kwargs.values()) self._values = set(values) # check values if len(values) != len(self._values): message = "Enum values are not unique! -> %s" % ", ".join(str(v) for v in values) raise AttributeError(message) def __contains__(self, value): """Checks whether value exists.""" return value in self._values def __getattr__(self, name): """Gets value by its name.""" if name in self._map: return self._map[name] raise AttributeError(name) def __getitem__(self, name): """Gets value by its name.""" if name in self._map: return self._map[name] raise KeyError(name) def __iter__(self): """Gets values iterator.""" return self._values.__iter__()
# base path to YOLO directory MODEL_PATH = "yolo-coco" # initialize minimum probability to filter weak detections along with # the threshold when applying non-maxima suppression MIN_CONF = 0.3 NMS_THRESH = 0.3 # boolean indicating if NVIDIA CUDA GPU should be used USE_GPU = True # define the minimum safe distance (in pixels) that two people can be # from each other MIN_DISTANCE = 50 FLOWMAP_DISTANCE = 25 FLOWMAP_SIZE = 1000 FLOWMAP_BATCH = 100 BLOCKSIZE_X = 30 BLOCKSIZE_Y = BLOCKSIZE_X OUTPUT_X = 960 OUTPUT_Y = 540
# server.py flask configuration # To use this file first export this path as SERVER_SETTINGS, before running # the flask server. i.e. export SERVER_SETTINGS=config.py LIRC_PATH = "/dev/lirc0" SAVE_STATE_PATH = "/tmp/heatpump.state"
cx = 0 cy = 0 fsize = 0 counter = 0 class FunnyRect(): def setCenter(self, x,y): self.cx = x self.cy = y def setSize(self, size): self.size = size def render(self): rect(self.cx, self.cy, self.size, self.size) funnyRect0b = FunnyRect() funnyRect0b1 = FunnyRect() def setup(): size(600,600) smooth() noStroke() # rectMode(CENTER) funnyRect0b.setSize(50) funnyRect0b1.setSize(20) def draw(): global counter background(255) fill(50) obX = mouseX + sin( counter )*150 obY = mouseY + cos( counter )*150 funnyRect0b.setCenter(mouseX, mouseY) funnyRect0b.render() funnyRect0b1.setCenter(obX, obY) funnyRect0b1.render() counter+=0.05
# # PySNMP MIB module DVMRP-STD-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DVMRP-STD-MIB # Produced by pysmi-0.3.4 at Wed May 1 11:17:27 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) # OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsIntersection, ConstraintsUnion, ValueRangeConstraint, ValueSizeConstraint, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ConstraintsUnion", "ValueRangeConstraint", "ValueSizeConstraint", "SingleValueConstraint") InterfaceIndexOrZero, InterfaceIndex = mibBuilder.importSymbols("IF-MIB", "InterfaceIndexOrZero", "InterfaceIndex") SnmpAdminString, = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString") NotificationGroup, ModuleCompliance, ObjectGroup = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance", "ObjectGroup") IpAddress, Integer32, iso, experimental, Bits, Gauge32, ObjectIdentity, NotificationType, MibIdentifier, Counter64, ModuleIdentity, Counter32, TimeTicks, Unsigned32, MibScalar, MibTable, MibTableRow, MibTableColumn = mibBuilder.importSymbols("SNMPv2-SMI", "IpAddress", "Integer32", "iso", "experimental", "Bits", "Gauge32", "ObjectIdentity", "NotificationType", "MibIdentifier", "Counter64", "ModuleIdentity", "Counter32", "TimeTicks", "Unsigned32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn") DisplayString, TextualConvention, RowStatus = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention", "RowStatus") dvmrpStdMIB = ModuleIdentity((1, 3, 6, 1, 3, 62)) dvmrpStdMIB.setRevisions(('2001-11-21 12:00',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: dvmrpStdMIB.setRevisionsDescriptions(('Initial version, published as RFC xxxx (to be filled in by RFC-Editor).',)) if mibBuilder.loadTexts: dvmrpStdMIB.setLastUpdated('200111211200Z') if mibBuilder.loadTexts: dvmrpStdMIB.setOrganization('IETF IDMR Working Group.') if mibBuilder.loadTexts: dvmrpStdMIB.setContactInfo(' Dave Thaler Microsoft One Microsoft Way Redmond, WA 98052-6399 EMail: dthaler@microsoft.com') if mibBuilder.loadTexts: dvmrpStdMIB.setDescription('The MIB module for management of DVMRP routers.') dvmrpMIBObjects = MibIdentifier((1, 3, 6, 1, 3, 62, 1)) dvmrp = MibIdentifier((1, 3, 6, 1, 3, 62, 1, 1)) dvmrpScalar = MibIdentifier((1, 3, 6, 1, 3, 62, 1, 1, 1)) dvmrpVersionString = MibScalar((1, 3, 6, 1, 3, 62, 1, 1, 1, 1), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: dvmrpVersionString.setStatus('current') if mibBuilder.loadTexts: dvmrpVersionString.setDescription("The router's DVMRP version information. Similar to sysDescr in MIB-II, this is a free-form field which can be used to display vendor-specific information.") dvmrpNumRoutes = MibScalar((1, 3, 6, 1, 3, 62, 1, 1, 1, 3), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dvmrpNumRoutes.setStatus('current') if mibBuilder.loadTexts: dvmrpNumRoutes.setDescription('The number of entries in the routing table. This can be used to monitor the routing table size.') dvmrpReachableRoutes = MibScalar((1, 3, 6, 1, 3, 62, 1, 1, 1, 4), Gauge32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dvmrpReachableRoutes.setStatus('current') if mibBuilder.loadTexts: dvmrpReachableRoutes.setDescription('The number of entries in the routing table with non infinite metrics. This can be used to detect network partitions by observing the ratio of reachable routes to total routes.') dvmrpInterfaceTable = MibTable((1, 3, 6, 1, 3, 62, 1, 1, 2), ) if mibBuilder.loadTexts: dvmrpInterfaceTable.setStatus('current') if mibBuilder.loadTexts: dvmrpInterfaceTable.setDescription("The (conceptual) table listing the router's multicast- capable interfaces.") dvmrpInterfaceEntry = MibTableRow((1, 3, 6, 1, 3, 62, 1, 1, 2, 1), ).setIndexNames((0, "DVMRP-STD-MIB", "dvmrpInterfaceIndex")) if mibBuilder.loadTexts: dvmrpInterfaceEntry.setStatus('current') if mibBuilder.loadTexts: dvmrpInterfaceEntry.setDescription('An entry (conceptual row) in the dvmrpInterfaceTable. This row augments ipMRouteInterfaceEntry in the IP Multicast MIB, where the threshold object resides.') dvmrpInterfaceIndex = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 2, 1, 1), InterfaceIndex()) if mibBuilder.loadTexts: dvmrpInterfaceIndex.setStatus('current') if mibBuilder.loadTexts: dvmrpInterfaceIndex.setDescription('The ifIndex value of the interface for which DVMRP is enabled.') dvmrpInterfaceLocalAddress = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 2, 1, 2), IpAddress()).setMaxAccess("readcreate") if mibBuilder.loadTexts: dvmrpInterfaceLocalAddress.setStatus('current') if mibBuilder.loadTexts: dvmrpInterfaceLocalAddress.setDescription('The IP address this system will use as a source address on this interface. On unnumbered interfaces, it must be the same value as dvmrpInterfaceLocalAddress for some interface on the system.') dvmrpInterfaceMetric = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 2, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 31)).clone(1)).setMaxAccess("readcreate") if mibBuilder.loadTexts: dvmrpInterfaceMetric.setStatus('current') if mibBuilder.loadTexts: dvmrpInterfaceMetric.setDescription('The distance metric for this interface which is used to calculate distance vectors.') dvmrpInterfaceStatus = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 2, 1, 4), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: dvmrpInterfaceStatus.setStatus('current') if mibBuilder.loadTexts: dvmrpInterfaceStatus.setDescription('The status of this entry. Creating the entry enables DVMRP on the virtual interface; destroying the entry or setting it to notInService disables DVMRP on the virtual interface.') dvmrpInterfaceRcvBadPkts = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 2, 1, 5), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dvmrpInterfaceRcvBadPkts.setStatus('current') if mibBuilder.loadTexts: dvmrpInterfaceRcvBadPkts.setDescription('The number of DVMRP messages received on the interface by the DVMRP process which were subsequently discarded as invalid (e.g. invalid packet format, or a route report from an unknown neighbor).') dvmrpInterfaceRcvBadRoutes = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 2, 1, 6), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dvmrpInterfaceRcvBadRoutes.setStatus('current') if mibBuilder.loadTexts: dvmrpInterfaceRcvBadRoutes.setDescription('The number of routes, in valid DVMRP packets, which were ignored because the entry was invalid.') dvmrpInterfaceSentRoutes = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 2, 1, 7), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dvmrpInterfaceSentRoutes.setStatus('current') if mibBuilder.loadTexts: dvmrpInterfaceSentRoutes.setDescription('The number of routes, in DVMRP Report packets, which have been sent on this interface. Together with dvmrpNeighborRcvRoutes at a peer, this object is useful for detecting routes being lost.') dvmrpInterfaceKey = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 2, 1, 8), SnmpAdminString()).setMaxAccess("readcreate") if mibBuilder.loadTexts: dvmrpInterfaceKey.setStatus('current') if mibBuilder.loadTexts: dvmrpInterfaceKey.setDescription('The (shared) key for authenticating neighbors on this interface. This object is intended solely for the purpose of setting the interface key, and MUST be accessible only via requests using both authentication and privacy. The agent MAY report an empty string in response to get, get- next, get-bulk requests.') dvmrpInterfaceKeyVersion = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 2, 1, 9), Integer32()).setMaxAccess("readcreate") if mibBuilder.loadTexts: dvmrpInterfaceKeyVersion.setStatus('current') if mibBuilder.loadTexts: dvmrpInterfaceKeyVersion.setDescription('The highest version number of all known interface keys for this interface used for authenticating neighbors.') dvmrpInterfaceGenerationId = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 2, 1, 10), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dvmrpInterfaceGenerationId.setStatus('current') if mibBuilder.loadTexts: dvmrpInterfaceGenerationId.setDescription('The generation identifier for the interface. This is used by neighboring routers to detect whether the DVMRP routing table should be resent.') dvmrpNeighborTable = MibTable((1, 3, 6, 1, 3, 62, 1, 1, 3), ) if mibBuilder.loadTexts: dvmrpNeighborTable.setStatus('current') if mibBuilder.loadTexts: dvmrpNeighborTable.setDescription("The (conceptual) table listing the router's DVMRP neighbors, as discovered by receiving DVMRP messages.") dvmrpNeighborEntry = MibTableRow((1, 3, 6, 1, 3, 62, 1, 1, 3, 1), ).setIndexNames((0, "DVMRP-STD-MIB", "dvmrpNeighborIfIndex"), (0, "DVMRP-STD-MIB", "dvmrpNeighborAddress")) if mibBuilder.loadTexts: dvmrpNeighborEntry.setStatus('current') if mibBuilder.loadTexts: dvmrpNeighborEntry.setDescription('An entry (conceptual row) in the dvmrpNeighborTable.') dvmrpNeighborIfIndex = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 3, 1, 1), InterfaceIndex()) if mibBuilder.loadTexts: dvmrpNeighborIfIndex.setStatus('current') if mibBuilder.loadTexts: dvmrpNeighborIfIndex.setDescription('The value of ifIndex for the virtual interface used to reach this DVMRP neighbor.') dvmrpNeighborAddress = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 3, 1, 2), IpAddress()) if mibBuilder.loadTexts: dvmrpNeighborAddress.setStatus('current') if mibBuilder.loadTexts: dvmrpNeighborAddress.setDescription('The IP address of the DVMRP neighbor for which this entry contains information.') dvmrpNeighborUpTime = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 3, 1, 3), TimeTicks()).setMaxAccess("readonly") if mibBuilder.loadTexts: dvmrpNeighborUpTime.setStatus('current') if mibBuilder.loadTexts: dvmrpNeighborUpTime.setDescription('The time since this DVMRP neighbor (last) became a neighbor of the local router.') dvmrpNeighborExpiryTime = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 3, 1, 4), TimeTicks()).setMaxAccess("readonly") if mibBuilder.loadTexts: dvmrpNeighborExpiryTime.setStatus('current') if mibBuilder.loadTexts: dvmrpNeighborExpiryTime.setDescription('The minimum time remaining before this DVMRP neighbor will be aged out.') dvmrpNeighborGenerationId = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 3, 1, 5), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dvmrpNeighborGenerationId.setStatus('current') if mibBuilder.loadTexts: dvmrpNeighborGenerationId.setDescription("The neighboring router's generation identifier.") dvmrpNeighborMajorVersion = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 3, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 255))).setMaxAccess("readonly") if mibBuilder.loadTexts: dvmrpNeighborMajorVersion.setStatus('current') if mibBuilder.loadTexts: dvmrpNeighborMajorVersion.setDescription("The neighboring router's major DVMRP version number.") dvmrpNeighborMinorVersion = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 3, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 255))).setMaxAccess("readonly") if mibBuilder.loadTexts: dvmrpNeighborMinorVersion.setStatus('current') if mibBuilder.loadTexts: dvmrpNeighborMinorVersion.setDescription("The neighboring router's minor DVMRP version number.") dvmrpNeighborCapabilities = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 3, 1, 8), Bits().clone(namedValues=NamedValues(("leaf", 0), ("prune", 1), ("generationID", 2), ("mtrace", 3)))).setMaxAccess("readonly") if mibBuilder.loadTexts: dvmrpNeighborCapabilities.setStatus('current') if mibBuilder.loadTexts: dvmrpNeighborCapabilities.setDescription("This object describes the neighboring router's capabilities. The leaf bit indicates that the neighbor has only one interface with neighbors. The prune bit indicates that the neighbor supports pruning. The generationID bit indicates that the neighbor sends its generationID in Probe messages. The mtrace bit indicates that the neighbor can handle mtrace requests.") dvmrpNeighborRcvRoutes = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 3, 1, 9), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dvmrpNeighborRcvRoutes.setStatus('current') if mibBuilder.loadTexts: dvmrpNeighborRcvRoutes.setDescription('The total number of routes received in valid DVMRP packets received from this neighbor. This can be used to diagnose problems such as unicast route injection, as well as giving an indication of the level of DVMRP route exchange activity.') dvmrpNeighborRcvBadPkts = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 3, 1, 10), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dvmrpNeighborRcvBadPkts.setStatus('current') if mibBuilder.loadTexts: dvmrpNeighborRcvBadPkts.setDescription('The number of packet received from this neighbor which were discarded as invalid.') dvmrpNeighborRcvBadRoutes = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 3, 1, 11), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dvmrpNeighborRcvBadRoutes.setStatus('current') if mibBuilder.loadTexts: dvmrpNeighborRcvBadRoutes.setDescription('The number of routes, in valid DVMRP packets received from this neighbor, which were ignored because the entry was invalid.') dvmrpNeighborState = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 3, 1, 12), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("oneway", 1), ("active", 2), ("ignoring", 3), ("down", 4)))).setMaxAccess("readonly") if mibBuilder.loadTexts: dvmrpNeighborState.setStatus('current') if mibBuilder.loadTexts: dvmrpNeighborState.setDescription('State of the neighbor adjacency.') dvmrpRouteTable = MibTable((1, 3, 6, 1, 3, 62, 1, 1, 4), ) if mibBuilder.loadTexts: dvmrpRouteTable.setStatus('current') if mibBuilder.loadTexts: dvmrpRouteTable.setDescription('The table of routes learned through DVMRP route exchange.') dvmrpRouteEntry = MibTableRow((1, 3, 6, 1, 3, 62, 1, 1, 4, 1), ).setIndexNames((0, "DVMRP-STD-MIB", "dvmrpRouteSource"), (0, "DVMRP-STD-MIB", "dvmrpRouteSourceMask")) if mibBuilder.loadTexts: dvmrpRouteEntry.setStatus('current') if mibBuilder.loadTexts: dvmrpRouteEntry.setDescription('An entry (conceptual row) containing the multicast routing information used by DVMRP in place of the unicast routing information.') dvmrpRouteSource = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 4, 1, 1), IpAddress()) if mibBuilder.loadTexts: dvmrpRouteSource.setStatus('current') if mibBuilder.loadTexts: dvmrpRouteSource.setDescription('The network address which when combined with the corresponding value of dvmrpRouteSourceMask identifies the sources for which this entry contains multicast routing information.') dvmrpRouteSourceMask = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 4, 1, 2), IpAddress()) if mibBuilder.loadTexts: dvmrpRouteSourceMask.setStatus('current') if mibBuilder.loadTexts: dvmrpRouteSourceMask.setDescription('The network mask which when combined with the corresponding value of dvmrpRouteSource identifies the sources for which this entry contains multicast routing information.') dvmrpRouteUpstreamNeighbor = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 4, 1, 3), IpAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: dvmrpRouteUpstreamNeighbor.setStatus('current') if mibBuilder.loadTexts: dvmrpRouteUpstreamNeighbor.setDescription('The address of the upstream neighbor (e.g., RPF neighbor) from which IP datagrams from these sources are received.') dvmrpRouteIfIndex = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 4, 1, 4), InterfaceIndexOrZero()).setMaxAccess("readonly") if mibBuilder.loadTexts: dvmrpRouteIfIndex.setStatus('current') if mibBuilder.loadTexts: dvmrpRouteIfIndex.setDescription('The value of ifIndex for the interface on which IP datagrams sent by these sources are received. A value of 0 typically means the route is an aggregate for which no next- hop interface exists.') dvmrpRouteMetric = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 4, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 32))).setMaxAccess("readonly") if mibBuilder.loadTexts: dvmrpRouteMetric.setStatus('current') if mibBuilder.loadTexts: dvmrpRouteMetric.setDescription('The distance in hops to the source subnet.') dvmrpRouteExpiryTime = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 4, 1, 6), TimeTicks()).setMaxAccess("readonly") if mibBuilder.loadTexts: dvmrpRouteExpiryTime.setStatus('current') if mibBuilder.loadTexts: dvmrpRouteExpiryTime.setDescription('The minimum amount of time remaining before this entry will be aged out.') dvmrpRouteUpTime = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 4, 1, 7), TimeTicks()).setMaxAccess("readonly") if mibBuilder.loadTexts: dvmrpRouteUpTime.setStatus('current') if mibBuilder.loadTexts: dvmrpRouteUpTime.setDescription('The time since the route represented by this entry was learned by the router.') dvmrpRouteNextHopTable = MibTable((1, 3, 6, 1, 3, 62, 1, 1, 5), ) if mibBuilder.loadTexts: dvmrpRouteNextHopTable.setStatus('current') if mibBuilder.loadTexts: dvmrpRouteNextHopTable.setDescription('The (conceptual) table containing information on the next hops on outgoing interfaces for routing IP multicast datagrams.') dvmrpRouteNextHopEntry = MibTableRow((1, 3, 6, 1, 3, 62, 1, 1, 5, 1), ).setIndexNames((0, "DVMRP-STD-MIB", "dvmrpRouteNextHopSource"), (0, "DVMRP-STD-MIB", "dvmrpRouteNextHopSourceMask"), (0, "DVMRP-STD-MIB", "dvmrpRouteNextHopIfIndex")) if mibBuilder.loadTexts: dvmrpRouteNextHopEntry.setStatus('current') if mibBuilder.loadTexts: dvmrpRouteNextHopEntry.setDescription('An entry (conceptual row) in the list of next hops on outgoing interfaces to which IP multicast datagrams from particular sources are routed.') dvmrpRouteNextHopSource = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 5, 1, 1), IpAddress()) if mibBuilder.loadTexts: dvmrpRouteNextHopSource.setStatus('current') if mibBuilder.loadTexts: dvmrpRouteNextHopSource.setDescription('The network address which when combined with the corresponding value of dvmrpRouteNextHopSourceMask identifies the sources for which this entry specifies a next hop on an outgoing interface.') dvmrpRouteNextHopSourceMask = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 5, 1, 2), IpAddress()) if mibBuilder.loadTexts: dvmrpRouteNextHopSourceMask.setStatus('current') if mibBuilder.loadTexts: dvmrpRouteNextHopSourceMask.setDescription('The network mask which when combined with the corresponding value of dvmrpRouteNextHopSource identifies the sources for which this entry specifies a next hop on an outgoing interface.') dvmrpRouteNextHopIfIndex = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 5, 1, 3), InterfaceIndex()) if mibBuilder.loadTexts: dvmrpRouteNextHopIfIndex.setStatus('current') if mibBuilder.loadTexts: dvmrpRouteNextHopIfIndex.setDescription('The ifIndex value of the interface for the outgoing interface for this next hop.') dvmrpRouteNextHopType = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 5, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("leaf", 1), ("branch", 2)))).setMaxAccess("readonly") if mibBuilder.loadTexts: dvmrpRouteNextHopType.setStatus('current') if mibBuilder.loadTexts: dvmrpRouteNextHopType.setDescription('Type is leaf if no downstream dependent neighbors exist on the outgoing virtual interface. Otherwise, type is branch.') dvmrpPruneTable = MibTable((1, 3, 6, 1, 3, 62, 1, 1, 6), ) if mibBuilder.loadTexts: dvmrpPruneTable.setStatus('current') if mibBuilder.loadTexts: dvmrpPruneTable.setDescription("The (conceptual) table listing the router's upstream prune state.") dvmrpPruneEntry = MibTableRow((1, 3, 6, 1, 3, 62, 1, 1, 6, 1), ).setIndexNames((0, "DVMRP-STD-MIB", "dvmrpPruneGroup"), (0, "DVMRP-STD-MIB", "dvmrpPruneSource"), (0, "DVMRP-STD-MIB", "dvmrpPruneSourceMask")) if mibBuilder.loadTexts: dvmrpPruneEntry.setStatus('current') if mibBuilder.loadTexts: dvmrpPruneEntry.setDescription('An entry (conceptual row) in the dvmrpPruneTable.') dvmrpPruneGroup = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 6, 1, 1), IpAddress()) if mibBuilder.loadTexts: dvmrpPruneGroup.setStatus('current') if mibBuilder.loadTexts: dvmrpPruneGroup.setDescription('The group address which has been pruned.') dvmrpPruneSource = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 6, 1, 2), IpAddress()) if mibBuilder.loadTexts: dvmrpPruneSource.setStatus('current') if mibBuilder.loadTexts: dvmrpPruneSource.setDescription('The address of the source or source network which has been pruned.') dvmrpPruneSourceMask = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 6, 1, 3), IpAddress()) if mibBuilder.loadTexts: dvmrpPruneSourceMask.setStatus('current') if mibBuilder.loadTexts: dvmrpPruneSourceMask.setDescription("The address of the source or source network which has been pruned. The mask must either be all 1's, or else dvmrpPruneSource and dvmrpPruneSourceMask must match dvmrpRouteSource and dvmrpRouteSourceMask for some entry in the dvmrpRouteTable.") dvmrpPruneExpiryTime = MibTableColumn((1, 3, 6, 1, 3, 62, 1, 1, 6, 1, 4), TimeTicks()).setMaxAccess("readonly") if mibBuilder.loadTexts: dvmrpPruneExpiryTime.setStatus('current') if mibBuilder.loadTexts: dvmrpPruneExpiryTime.setDescription("The amount of time remaining before this prune should expire at the upstream neighbor. This value should be the minimum of the default prune lifetime and the remaining prune lifetimes of the local router's downstream neighbors, if any.") dvmrpTraps = MibIdentifier((1, 3, 6, 1, 3, 62, 1, 1, 7)) dvmrpNeighborLoss = NotificationType((1, 3, 6, 1, 3, 62, 1, 1, 7, 1)).setObjects(("DVMRP-STD-MIB", "dvmrpInterfaceLocalAddress"), ("DVMRP-STD-MIB", "dvmrpNeighborState")) if mibBuilder.loadTexts: dvmrpNeighborLoss.setStatus('current') if mibBuilder.loadTexts: dvmrpNeighborLoss.setDescription('A dvmrpNeighborLoss trap signifies the loss of a 2-way adjacency with a neighbor. This trap should be generated when the neighbor state changes from active to one-way, ignoring, or down. The trap should be generated only if the router has no other neighbors on the same interface with a lower IP address than itself.') dvmrpNeighborNotPruning = NotificationType((1, 3, 6, 1, 3, 62, 1, 1, 7, 2)).setObjects(("DVMRP-STD-MIB", "dvmrpInterfaceLocalAddress"), ("DVMRP-STD-MIB", "dvmrpNeighborCapabilities")) if mibBuilder.loadTexts: dvmrpNeighborNotPruning.setStatus('current') if mibBuilder.loadTexts: dvmrpNeighborNotPruning.setDescription('A dvmrpNeighborNotPruning trap signifies that a non-pruning neighbor has been detected (in an implementation-dependent manner). This trap should be generated at most once per generation ID of the neighbor. For example, it should be generated at the time a neighbor is first heard from if the prune bit is not set in its capabilities. It should also be generated if the local system has the ability to tell that a neighbor which sets the the prune bit in its capabilities is not pruning any branches over an extended period of time. The trap should be generated only if the router has no other neighbors on the same interface with a lower IP address than itself.') dvmrpMIBConformance = MibIdentifier((1, 3, 6, 1, 3, 62, 2)) dvmrpMIBCompliances = MibIdentifier((1, 3, 6, 1, 3, 62, 2, 1)) dvmrpMIBGroups = MibIdentifier((1, 3, 6, 1, 3, 62, 2, 2)) dvmrpMIBCompliance = ModuleCompliance((1, 3, 6, 1, 3, 62, 2, 1, 1)).setObjects(("DVMRP-STD-MIB", "dvmrpGeneralGroup"), ("DVMRP-STD-MIB", "dvmrpInterfaceGroup"), ("DVMRP-STD-MIB", "dvmrpNeighborGroup"), ("DVMRP-STD-MIB", "dvmrpRoutingGroup"), ("DVMRP-STD-MIB", "dvmrpTreeGroup"), ("DVMRP-STD-MIB", "dvmrpSecurityGroup")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): dvmrpMIBCompliance = dvmrpMIBCompliance.setStatus('current') if mibBuilder.loadTexts: dvmrpMIBCompliance.setDescription('The compliance statement for the DVMRP MIB.') dvmrpGeneralGroup = ObjectGroup((1, 3, 6, 1, 3, 62, 2, 2, 2)).setObjects(("DVMRP-STD-MIB", "dvmrpVersionString"), ("DVMRP-STD-MIB", "dvmrpNumRoutes"), ("DVMRP-STD-MIB", "dvmrpReachableRoutes")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): dvmrpGeneralGroup = dvmrpGeneralGroup.setStatus('current') if mibBuilder.loadTexts: dvmrpGeneralGroup.setDescription('A collection of objects used to describe general DVMRP configuration information.') dvmrpInterfaceGroup = ObjectGroup((1, 3, 6, 1, 3, 62, 2, 2, 3)).setObjects(("DVMRP-STD-MIB", "dvmrpInterfaceLocalAddress"), ("DVMRP-STD-MIB", "dvmrpInterfaceMetric"), ("DVMRP-STD-MIB", "dvmrpInterfaceStatus"), ("DVMRP-STD-MIB", "dvmrpInterfaceGenerationId"), ("DVMRP-STD-MIB", "dvmrpInterfaceRcvBadPkts"), ("DVMRP-STD-MIB", "dvmrpInterfaceRcvBadRoutes"), ("DVMRP-STD-MIB", "dvmrpInterfaceSentRoutes")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): dvmrpInterfaceGroup = dvmrpInterfaceGroup.setStatus('current') if mibBuilder.loadTexts: dvmrpInterfaceGroup.setDescription('A collection of objects used to describe DVMRP interface configuration and statistics.') dvmrpNeighborGroup = ObjectGroup((1, 3, 6, 1, 3, 62, 2, 2, 4)).setObjects(("DVMRP-STD-MIB", "dvmrpNeighborUpTime"), ("DVMRP-STD-MIB", "dvmrpNeighborExpiryTime"), ("DVMRP-STD-MIB", "dvmrpNeighborGenerationId"), ("DVMRP-STD-MIB", "dvmrpNeighborMajorVersion"), ("DVMRP-STD-MIB", "dvmrpNeighborMinorVersion"), ("DVMRP-STD-MIB", "dvmrpNeighborCapabilities"), ("DVMRP-STD-MIB", "dvmrpNeighborRcvRoutes"), ("DVMRP-STD-MIB", "dvmrpNeighborRcvBadPkts"), ("DVMRP-STD-MIB", "dvmrpNeighborRcvBadRoutes"), ("DVMRP-STD-MIB", "dvmrpNeighborState")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): dvmrpNeighborGroup = dvmrpNeighborGroup.setStatus('current') if mibBuilder.loadTexts: dvmrpNeighborGroup.setDescription('A collection of objects used to describe DVMRP peer configuration and statistics.') dvmrpRoutingGroup = ObjectGroup((1, 3, 6, 1, 3, 62, 2, 2, 5)).setObjects(("DVMRP-STD-MIB", "dvmrpRouteUpstreamNeighbor"), ("DVMRP-STD-MIB", "dvmrpRouteIfIndex"), ("DVMRP-STD-MIB", "dvmrpRouteMetric"), ("DVMRP-STD-MIB", "dvmrpRouteExpiryTime"), ("DVMRP-STD-MIB", "dvmrpRouteUpTime"), ("DVMRP-STD-MIB", "dvmrpRouteNextHopType")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): dvmrpRoutingGroup = dvmrpRoutingGroup.setStatus('current') if mibBuilder.loadTexts: dvmrpRoutingGroup.setDescription('A collection of objects used to store the DVMRP routing table.') dvmrpSecurityGroup = ObjectGroup((1, 3, 6, 1, 3, 62, 2, 2, 6)).setObjects(("DVMRP-STD-MIB", "dvmrpInterfaceKey"), ("DVMRP-STD-MIB", "dvmrpInterfaceKeyVersion")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): dvmrpSecurityGroup = dvmrpSecurityGroup.setStatus('current') if mibBuilder.loadTexts: dvmrpSecurityGroup.setDescription('A collection of objects used to store information related to DVMRP security.') dvmrpTreeGroup = ObjectGroup((1, 3, 6, 1, 3, 62, 2, 2, 7)).setObjects(("DVMRP-STD-MIB", "dvmrpPruneExpiryTime")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): dvmrpTreeGroup = dvmrpTreeGroup.setStatus('current') if mibBuilder.loadTexts: dvmrpTreeGroup.setDescription('A collection of objects used to store information related to DVMRP prune state.') dvmrpNotificationGroup = NotificationGroup((1, 3, 6, 1, 3, 62, 2, 2, 8)).setObjects(("DVMRP-STD-MIB", "dvmrpNeighborLoss"), ("DVMRP-STD-MIB", "dvmrpNeighborNotPruning")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): dvmrpNotificationGroup = dvmrpNotificationGroup.setStatus('current') if mibBuilder.loadTexts: dvmrpNotificationGroup.setDescription('A collection of notifications for signaling important DVMRP events.') mibBuilder.exportSymbols("DVMRP-STD-MIB", dvmrpStdMIB=dvmrpStdMIB, dvmrpRouteUpstreamNeighbor=dvmrpRouteUpstreamNeighbor, dvmrpInterfaceLocalAddress=dvmrpInterfaceLocalAddress, dvmrpGeneralGroup=dvmrpGeneralGroup, dvmrpRouteNextHopEntry=dvmrpRouteNextHopEntry, dvmrpNumRoutes=dvmrpNumRoutes, dvmrpRouteNextHopSourceMask=dvmrpRouteNextHopSourceMask, dvmrpRouteNextHopSource=dvmrpRouteNextHopSource, dvmrpNeighborMinorVersion=dvmrpNeighborMinorVersion, dvmrpRouteIfIndex=dvmrpRouteIfIndex, dvmrpNeighborRcvRoutes=dvmrpNeighborRcvRoutes, dvmrpRouteMetric=dvmrpRouteMetric, dvmrpScalar=dvmrpScalar, dvmrpNeighborGenerationId=dvmrpNeighborGenerationId, dvmrpPruneTable=dvmrpPruneTable, dvmrpPruneGroup=dvmrpPruneGroup, dvmrpPruneSourceMask=dvmrpPruneSourceMask, dvmrp=dvmrp, dvmrpNeighborCapabilities=dvmrpNeighborCapabilities, dvmrpMIBConformance=dvmrpMIBConformance, dvmrpInterfaceMetric=dvmrpInterfaceMetric, dvmrpInterfaceKey=dvmrpInterfaceKey, dvmrpNeighborAddress=dvmrpNeighborAddress, dvmrpReachableRoutes=dvmrpReachableRoutes, dvmrpRouteTable=dvmrpRouteTable, dvmrpRouteSource=dvmrpRouteSource, dvmrpRouteSourceMask=dvmrpRouteSourceMask, dvmrpNeighborState=dvmrpNeighborState, dvmrpNeighborGroup=dvmrpNeighborGroup, dvmrpRoutingGroup=dvmrpRoutingGroup, dvmrpPruneSource=dvmrpPruneSource, dvmrpTraps=dvmrpTraps, dvmrpNeighborRcvBadPkts=dvmrpNeighborRcvBadPkts, dvmrpInterfaceRcvBadPkts=dvmrpInterfaceRcvBadPkts, dvmrpNeighborTable=dvmrpNeighborTable, dvmrpNeighborLoss=dvmrpNeighborLoss, dvmrpNeighborNotPruning=dvmrpNeighborNotPruning, dvmrpInterfaceTable=dvmrpInterfaceTable, dvmrpMIBGroups=dvmrpMIBGroups, dvmrpInterfaceGroup=dvmrpInterfaceGroup, PYSNMP_MODULE_ID=dvmrpStdMIB, dvmrpNeighborMajorVersion=dvmrpNeighborMajorVersion, dvmrpVersionString=dvmrpVersionString, dvmrpRouteNextHopType=dvmrpRouteNextHopType, dvmrpInterfaceEntry=dvmrpInterfaceEntry, dvmrpPruneEntry=dvmrpPruneEntry, dvmrpInterfaceKeyVersion=dvmrpInterfaceKeyVersion, dvmrpNeighborRcvBadRoutes=dvmrpNeighborRcvBadRoutes, dvmrpInterfaceIndex=dvmrpInterfaceIndex, dvmrpNeighborUpTime=dvmrpNeighborUpTime, dvmrpNeighborEntry=dvmrpNeighborEntry, dvmrpRouteExpiryTime=dvmrpRouteExpiryTime, dvmrpMIBObjects=dvmrpMIBObjects, dvmrpNeighborIfIndex=dvmrpNeighborIfIndex, dvmrpInterfaceStatus=dvmrpInterfaceStatus, dvmrpTreeGroup=dvmrpTreeGroup, dvmrpInterfaceSentRoutes=dvmrpInterfaceSentRoutes, dvmrpNeighborExpiryTime=dvmrpNeighborExpiryTime, dvmrpInterfaceRcvBadRoutes=dvmrpInterfaceRcvBadRoutes, dvmrpMIBCompliances=dvmrpMIBCompliances, dvmrpRouteNextHopIfIndex=dvmrpRouteNextHopIfIndex, dvmrpSecurityGroup=dvmrpSecurityGroup, dvmrpRouteEntry=dvmrpRouteEntry, dvmrpRouteUpTime=dvmrpRouteUpTime, dvmrpRouteNextHopTable=dvmrpRouteNextHopTable, dvmrpPruneExpiryTime=dvmrpPruneExpiryTime, dvmrpNotificationGroup=dvmrpNotificationGroup, dvmrpMIBCompliance=dvmrpMIBCompliance, dvmrpInterfaceGenerationId=dvmrpInterfaceGenerationId)
class Solution(object): def combinationSum2(self, candidates, target): result = [] self.combinationSumRecu(sorted(candidates), result, 0, [], target) return result def combinationSumRecu(self, candidates, result, start, intermediate, target): if target == 0: result.append(list(intermediate)) prev = 0 while start < len(candidates) and candidates[start] <= target: if prev != candidates[start]: intermediate.append(candidates[start]) self.combinationSumRecu(candidates, result, start + 1, intermediate, target - candidates[start]) intermediate.pop() prev = candidates[start] start += 1 candidates = [10,1,2,7,6,1,5] target = 8 res = Solution().combinationSum2(candidates, target) print(res)
print('==Analisador de uma Progressão Aritmética==') a1 = int(input('Digite o primeiro termo: ')) r = int(input('Digite a razão: ')) print('Os 10 primeiros termos dessa PA são: ') cont = 0 termo = a1 while cont != 10: cont += 1 if cont == 1: print('{}, '.format(a1), end='') else: termo += r print('{}, '.format(termo) if cont != 10 else '{}.'.format(termo), end='')
"""This file provides the PEP0249 compliant variables for this module. See https://www.python.org/dev/peps/pep-0249 for more information on these. """ # Copyright 2012, Google Inc. All rights reserved. # Use of this source code is governed by a BSD-style license that can # be found in the LICENSE file. # Follows the Python Database API 2.0. apilevel = '2.0' # Threads may share the module, but not connections. # (we store session information in the conection now, that should be in the # cursor but are not for historical reasons). threadsafety = 2 # Named style, e.g. ...WHERE name=:name. # # Note we also provide a function in dbapi to convert from 'pyformat' # to 'named', and prune unused bind variables in the SQL query. # # Also, we use an extension to bind variables to handle lists: # Using the '::name' syntax (instead of ':name') will indicate a list bind # variable. The type then has to be a list, set or tuple. paramstyle = 'named'
_EVT_INIT = 'INITIALIZE' EVT_START = 'START' EVT_READY = 'READY' EVT_CLOSE = 'CLOSE' EVT_STOP = 'STOP' EVT_APP_LOAD = 'APP_LOAD' EVT_APP_UNLOAD = 'APP_UNLOAD' EVT_INTENT_SUBSCRIBE = 'INTENT_SUBSCRIBE' EVT_INTENT_START = 'INTENT_START' EVT_INTENT_END = 'INTENT_END' EVT_ANY = '*' _META_EVENTS = ( _EVT_INIT, EVT_APP_LOAD, EVT_APP_UNLOAD, EVT_INTENT_SUBSCRIBE, EVT_INTENT_START, EVT_INTENT_END )
# # PySNMP MIB module ADTRAN-AOS-DESKTOP-AUDITING (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ADTRAN-AOS-DESKTOP-AUDITING # Produced by pysmi-0.3.4 at Wed May 1 11:13:58 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) # adGenAOSConformance, adGenAOSSwitch = mibBuilder.importSymbols("ADTRAN-AOS", "adGenAOSConformance", "adGenAOSSwitch") adIdentity, = mibBuilder.importSymbols("ADTRAN-MIB", "adIdentity") Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") SingleValueConstraint, ValueRangeConstraint, ConstraintsIntersection, ValueSizeConstraint, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ValueRangeConstraint", "ConstraintsIntersection", "ValueSizeConstraint", "ConstraintsUnion") ObjectGroup, NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "ObjectGroup", "NotificationGroup", "ModuleCompliance") Counter32, NotificationType, ObjectIdentity, Gauge32, iso, Counter64, Integer32, Bits, MibIdentifier, ModuleIdentity, TimeTicks, Unsigned32, MibScalar, MibTable, MibTableRow, MibTableColumn, IpAddress = mibBuilder.importSymbols("SNMPv2-SMI", "Counter32", "NotificationType", "ObjectIdentity", "Gauge32", "iso", "Counter64", "Integer32", "Bits", "MibIdentifier", "ModuleIdentity", "TimeTicks", "Unsigned32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "IpAddress") DateAndTime, TimeStamp, TruthValue, DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DateAndTime", "TimeStamp", "TruthValue", "DisplayString", "TextualConvention") adGenAOSDesktopAuditingMib = ModuleIdentity((1, 3, 6, 1, 4, 1, 664, 6, 10000, 53, 4, 1)) if mibBuilder.loadTexts: adGenAOSDesktopAuditingMib.setLastUpdated('200912140000Z') if mibBuilder.loadTexts: adGenAOSDesktopAuditingMib.setOrganization('ADTRAN, Inc.') if mibBuilder.loadTexts: adGenAOSDesktopAuditingMib.setContactInfo('Technical Support Dept. Postal: ADTRAN, Inc. 901 Explorer Blvd. Huntsville, AL 35806 Tel: +1 800 726-8663 Fax: +1 256 963 6217 E-mail: support@adtran.com') if mibBuilder.loadTexts: adGenAOSDesktopAuditingMib.setDescription('First Draft of ADTRAN-AOS-DESKTOP-AUDITING MIB module.') adGenDesktopAuditing = MibIdentifier((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2)) adGenNapClients = MibIdentifier((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0)) adGenNapClientsTable = MibTable((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1), ) if mibBuilder.loadTexts: adGenNapClientsTable.setStatus('current') if mibBuilder.loadTexts: adGenNapClientsTable.setDescription('The NAP client table displays NAP information of NAP capable clients. It displays information such as clients firewall, antivirus, antispyware, and security states. ') adGenNapClientsEntry = MibTableRow((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1), ).setIndexNames((0, "ADTRAN-AOS-DESKTOP-AUDITING", "adNapClientMac"), (0, "ADTRAN-AOS-DESKTOP-AUDITING", "adNapClientVlanId")) if mibBuilder.loadTexts: adGenNapClientsEntry.setStatus('current') if mibBuilder.loadTexts: adGenNapClientsEntry.setDescription('NAP information of the client') adNapClientMac = MibTableColumn((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 1), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: adNapClientMac.setStatus('current') if mibBuilder.loadTexts: adNapClientMac.setDescription('NAP clients MAC address. This is unique to the Desktop Auditing MIB.') adNapClientVlanId = MibTableColumn((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 2), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: adNapClientVlanId.setStatus('current') if mibBuilder.loadTexts: adNapClientVlanId.setDescription('NAP clients VLAN ID. This ID is unique to the Desktop Auditing MIB.') adNapClientIp = MibTableColumn((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 3), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: adNapClientIp.setStatus('current') if mibBuilder.loadTexts: adNapClientIp.setDescription('NAP clients IP address.') adNapClientHostname = MibTableColumn((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 4), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: adNapClientHostname.setStatus('current') if mibBuilder.loadTexts: adNapClientHostname.setDescription('NAP clients hostname.') adNapClientSrcPortIfId = MibTableColumn((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 5), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: adNapClientSrcPortIfId.setStatus('current') if mibBuilder.loadTexts: adNapClientSrcPortIfId.setDescription('NAP clients source port interface ID.') adNapClientSrcPortIfType = MibTableColumn((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 6), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: adNapClientSrcPortIfType.setStatus('current') if mibBuilder.loadTexts: adNapClientSrcPortIfType.setDescription('NAP clients source port interface type.') adNapServerMac = MibTableColumn((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 7), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: adNapServerMac.setStatus('current') if mibBuilder.loadTexts: adNapServerMac.setDescription('NAP servers MAC address.') adNapServerIp = MibTableColumn((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 8), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: adNapServerIp.setStatus('current') if mibBuilder.loadTexts: adNapServerIp.setDescription('NAP servers IP address.') adNapCollectionMethod = MibTableColumn((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 9), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: adNapCollectionMethod.setStatus('current') if mibBuilder.loadTexts: adNapCollectionMethod.setDescription('Method by which the NAP information is collected.') adNapCollectionTime = MibTableColumn((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 10), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: adNapCollectionTime.setStatus('current') if mibBuilder.loadTexts: adNapCollectionTime.setDescription('Time when the NAP information was collected.') adNapCapableClient = MibTableColumn((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 11), TruthValue()).setMaxAccess("readonly") if mibBuilder.loadTexts: adNapCapableClient.setStatus('current') if mibBuilder.loadTexts: adNapCapableClient.setDescription('Client is NAP capable.') adNapCapableServer = MibTableColumn((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 12), TruthValue()).setMaxAccess("readonly") if mibBuilder.loadTexts: adNapCapableServer.setStatus('current') if mibBuilder.loadTexts: adNapCapableServer.setDescription('Server is NAP capable.') adNapClientOsVersion = MibTableColumn((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 13), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: adNapClientOsVersion.setStatus('current') if mibBuilder.loadTexts: adNapClientOsVersion.setDescription('NAP clients OS version.') adNapClientOsServicePk = MibTableColumn((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 14), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: adNapClientOsServicePk.setStatus('current') if mibBuilder.loadTexts: adNapClientOsServicePk.setDescription('NAP clients service pack.') adNapClientOsProcessorArc = MibTableColumn((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 15), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: adNapClientOsProcessorArc.setStatus('current') if mibBuilder.loadTexts: adNapClientOsProcessorArc.setDescription('NAP clients processor architecture.') adNapClientLastSecurityUpdate = MibTableColumn((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 16), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: adNapClientLastSecurityUpdate.setStatus('current') if mibBuilder.loadTexts: adNapClientLastSecurityUpdate.setDescription('Last time the NAP clients security was updated.') adNapClientSecurityUpdateServer = MibTableColumn((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 17), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: adNapClientSecurityUpdateServer.setStatus('current') if mibBuilder.loadTexts: adNapClientSecurityUpdateServer.setDescription('NAP clients security update server.') adNapClientRequiresRemediation = MibTableColumn((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 18), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("unknown", 1), ("true", 2), ("false", 3)))).setMaxAccess("readonly") if mibBuilder.loadTexts: adNapClientRequiresRemediation.setStatus('current') if mibBuilder.loadTexts: adNapClientRequiresRemediation.setDescription('NAP clients requires remediation.') adNapClientLocalPolicyViolator = MibTableColumn((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 19), TruthValue()).setMaxAccess("readonly") if mibBuilder.loadTexts: adNapClientLocalPolicyViolator.setStatus('current') if mibBuilder.loadTexts: adNapClientLocalPolicyViolator.setDescription('NAP clients violates local policies.') adNapClientFirewallState = MibTableColumn((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 20), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16))).clone(namedValues=NamedValues(("unknown", 1), ("notInstalled", 2), ("wscServiceDown", 3), ("wscNotStarted", 4), ("notEnaNotUTD", 5), ("micsftNotEnaNotUTD", 6), ("notEnaUTD", 7), ("micsftNotEnaUTD", 8), ("enaNotUTDSn", 9), ("micsftEnaNotUTDSn", 10), ("enaNotUTDNotSn", 11), ("micsftEnaNotUTDNotSn", 12), ("enaUTDSn", 13), ("micsftEnaUTDSn", 14), ("enaUTDNotSn", 15), ("micsftEnaUTDNotSn", 16)))).setMaxAccess("readonly") if mibBuilder.loadTexts: adNapClientFirewallState.setStatus('current') if mibBuilder.loadTexts: adNapClientFirewallState.setDescription('NAP clients firewall state.') adNapClientFirewall = MibTableColumn((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 21), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: adNapClientFirewall.setStatus('current') if mibBuilder.loadTexts: adNapClientFirewall.setDescription('NAP clients firewall.') adNapClientAntivirusState = MibTableColumn((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 22), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16))).clone(namedValues=NamedValues(("unknown", 1), ("notInstalled", 2), ("wscServiceDown", 3), ("wscNotStarted", 4), ("notEnaNotUTD", 5), ("micsftNotEnaNotUTD", 6), ("notEnaUTD", 7), ("micsftNotEnaUTD", 8), ("enaNotUTDSn", 9), ("micsftEnaNotUTDSn", 10), ("enaNotUTDNotSn", 11), ("micsftEnaNotUTDNotSn", 12), ("enaUTDSn", 13), ("micsftEnaUTDSn", 14), ("enaUTDNotSn", 15), ("micsftEnaUTDNotSn", 16)))).setMaxAccess("readonly") if mibBuilder.loadTexts: adNapClientAntivirusState.setStatus('current') if mibBuilder.loadTexts: adNapClientAntivirusState.setDescription('NAP clients antivirus state.') adNapClientAntivirus = MibTableColumn((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 23), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: adNapClientAntivirus.setStatus('current') if mibBuilder.loadTexts: adNapClientAntivirus.setDescription('NAP clients antivirus.') adNapClientAntispywareState = MibTableColumn((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 24), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16))).clone(namedValues=NamedValues(("unknown", 1), ("notInstalled", 2), ("wscServiceDown", 3), ("wscNotStarted", 4), ("notEnaNotUTD", 5), ("micsftNotEnaNotUTD", 6), ("notEnaUTD", 7), ("micsftNotEnaUTD", 8), ("enaNotUTDSn", 9), ("micsftEnaNotUTDSn", 10), ("enaNotUTDNotSn", 11), ("micsftEnaNotUTDNotSn", 12), ("enaUTDSn", 13), ("micsftEnaUTDSn", 14), ("enaUTDNotSn", 15), ("micsftEnaUTDNotSn", 16)))).setMaxAccess("readonly") if mibBuilder.loadTexts: adNapClientAntispywareState.setStatus('current') if mibBuilder.loadTexts: adNapClientAntispywareState.setDescription('NAP clients antispyware state.') adNapClientAntispyware = MibTableColumn((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 25), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: adNapClientAntispyware.setStatus('current') if mibBuilder.loadTexts: adNapClientAntispyware.setDescription('NAP clients antispyware.') adNapClientAutoupdateState = MibTableColumn((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 26), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9))).clone(namedValues=NamedValues(("unknown", 1), ("notInstalled", 2), ("wscServiceDown", 3), ("wscNotStarted", 4), ("notEna", 5), ("enaCkUpdateOnly", 6), ("enaDownload", 7), ("enaDownloadInstall", 8), ("neverConfigured", 9)))).setMaxAccess("readonly") if mibBuilder.loadTexts: adNapClientAutoupdateState.setStatus('current') if mibBuilder.loadTexts: adNapClientAutoupdateState.setDescription('NAP clients auto update state.') adNapClientSecurityupdateState = MibTableColumn((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 27), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9))).clone(namedValues=NamedValues(("unknown", 1), ("noMissingUpdate", 2), ("missingUpdate", 3), ("noWUS", 4), ("noClientID", 5), ("wuaServiceDisabled", 6), ("wuaCommFailed", 7), ("updateInsNeedReboot", 8), ("wuaNotStarted", 9)))).setMaxAccess("readonly") if mibBuilder.loadTexts: adNapClientSecurityupdateState.setStatus('current') if mibBuilder.loadTexts: adNapClientSecurityupdateState.setDescription('NAP clients security update state.') adNapClientSecuritySeverity = MibTableColumn((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 28), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6))).clone(namedValues=NamedValues(("unknown", 1), ("unspecified", 2), ("low", 3), ("moderate", 4), ("important", 5), ("critical", 6)))).setMaxAccess("readonly") if mibBuilder.loadTexts: adNapClientSecuritySeverity.setStatus('current') if mibBuilder.loadTexts: adNapClientSecuritySeverity.setDescription('NAP clients security update severity.') adNapClientConnectionState = MibTableColumn((1, 3, 6, 1, 4, 1, 664, 5, 53, 4, 2, 0, 1, 1, 29), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("unknown", 1), ("notRestricted", 2), ("notResMaybeLater", 3), ("restricted", 4)))).setMaxAccess("readonly") if mibBuilder.loadTexts: adNapClientConnectionState.setStatus('current') if mibBuilder.loadTexts: adNapClientConnectionState.setDescription('NAP clients network connection state.') adGenAOSDesktopAuditingConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 664, 5, 53, 99, 10)) adGenAOSDesktopAuditingGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 664, 5, 53, 99, 10, 1)) adGenAOSDesktopAuditingCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 664, 5, 53, 99, 10, 2)) adGenAOSDesktopAuditingFullCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 664, 5, 53, 99, 10, 2, 1)).setObjects(("ADTRAN-AOS-DESKTOP-AUDITING", "adGenNapClientsGroup")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): adGenAOSDesktopAuditingFullCompliance = adGenAOSDesktopAuditingFullCompliance.setStatus('current') if mibBuilder.loadTexts: adGenAOSDesktopAuditingFullCompliance.setDescription('The compliance statement for SNMP entities which implement version 1 of the adGenAosDesktopAuditing MIB. When this MIB is implemented with support for read-only, then such an implementation can claim full compliance. ') adGenNapClientsGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 664, 5, 53, 99, 10, 1, 1)).setObjects(("ADTRAN-AOS-DESKTOP-AUDITING", "adNapClientMac"), ("ADTRAN-AOS-DESKTOP-AUDITING", "adNapClientVlanId"), ("ADTRAN-AOS-DESKTOP-AUDITING", "adNapClientIp"), ("ADTRAN-AOS-DESKTOP-AUDITING", "adNapClientHostname"), ("ADTRAN-AOS-DESKTOP-AUDITING", "adNapClientSrcPortIfId"), ("ADTRAN-AOS-DESKTOP-AUDITING", "adNapClientSrcPortIfType"), ("ADTRAN-AOS-DESKTOP-AUDITING", "adNapServerMac"), ("ADTRAN-AOS-DESKTOP-AUDITING", "adNapServerIp"), ("ADTRAN-AOS-DESKTOP-AUDITING", "adNapCollectionMethod"), ("ADTRAN-AOS-DESKTOP-AUDITING", "adNapCollectionTime"), ("ADTRAN-AOS-DESKTOP-AUDITING", "adNapCapableClient"), ("ADTRAN-AOS-DESKTOP-AUDITING", "adNapCapableServer"), ("ADTRAN-AOS-DESKTOP-AUDITING", "adNapClientOsVersion"), ("ADTRAN-AOS-DESKTOP-AUDITING", "adNapClientOsServicePk"), ("ADTRAN-AOS-DESKTOP-AUDITING", "adNapClientOsProcessorArc"), ("ADTRAN-AOS-DESKTOP-AUDITING", "adNapClientLastSecurityUpdate"), ("ADTRAN-AOS-DESKTOP-AUDITING", "adNapClientSecurityUpdateServer"), ("ADTRAN-AOS-DESKTOP-AUDITING", "adNapClientRequiresRemediation"), ("ADTRAN-AOS-DESKTOP-AUDITING", "adNapClientLocalPolicyViolator"), ("ADTRAN-AOS-DESKTOP-AUDITING", "adNapClientFirewallState"), ("ADTRAN-AOS-DESKTOP-AUDITING", "adNapClientFirewall"), ("ADTRAN-AOS-DESKTOP-AUDITING", "adNapClientAntivirusState"), ("ADTRAN-AOS-DESKTOP-AUDITING", "adNapClientAntivirus"), ("ADTRAN-AOS-DESKTOP-AUDITING", "adNapClientAntispywareState"), ("ADTRAN-AOS-DESKTOP-AUDITING", "adNapClientAntispyware"), ("ADTRAN-AOS-DESKTOP-AUDITING", "adNapClientAutoupdateState"), ("ADTRAN-AOS-DESKTOP-AUDITING", "adNapClientSecurityupdateState"), ("ADTRAN-AOS-DESKTOP-AUDITING", "adNapClientSecuritySeverity"), ("ADTRAN-AOS-DESKTOP-AUDITING", "adNapClientConnectionState")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): adGenNapClientsGroup = adGenNapClientsGroup.setStatus('current') if mibBuilder.loadTexts: adGenNapClientsGroup.setDescription('The adGenNapClientGroup group contains read-only NAP information of clients in the network that are NAP capable.') mibBuilder.exportSymbols("ADTRAN-AOS-DESKTOP-AUDITING", adNapClientSecurityupdateState=adNapClientSecurityupdateState, adNapClientFirewall=adNapClientFirewall, PYSNMP_MODULE_ID=adGenAOSDesktopAuditingMib, adGenNapClientsTable=adGenNapClientsTable, adGenAOSDesktopAuditingGroups=adGenAOSDesktopAuditingGroups, adNapServerMac=adNapServerMac, adNapServerIp=adNapServerIp, adNapClientMac=adNapClientMac, adNapCollectionMethod=adNapCollectionMethod, adNapClientIp=adNapClientIp, adNapClientSecurityUpdateServer=adNapClientSecurityUpdateServer, adNapClientVlanId=adNapClientVlanId, adNapClientConnectionState=adNapClientConnectionState, adGenAOSDesktopAuditingConformance=adGenAOSDesktopAuditingConformance, adNapClientAntispywareState=adNapClientAntispywareState, adGenAOSDesktopAuditingCompliances=adGenAOSDesktopAuditingCompliances, adGenDesktopAuditing=adGenDesktopAuditing, adNapCollectionTime=adNapCollectionTime, adNapClientOsProcessorArc=adNapClientOsProcessorArc, adGenAOSDesktopAuditingFullCompliance=adGenAOSDesktopAuditingFullCompliance, adNapClientRequiresRemediation=adNapClientRequiresRemediation, adNapClientAutoupdateState=adNapClientAutoupdateState, adNapClientAntivirusState=adNapClientAntivirusState, adNapClientFirewallState=adNapClientFirewallState, adNapClientOsServicePk=adNapClientOsServicePk, adNapClientLocalPolicyViolator=adNapClientLocalPolicyViolator, adNapClientAntivirus=adNapClientAntivirus, adNapClientSrcPortIfType=adNapClientSrcPortIfType, adGenNapClientsEntry=adGenNapClientsEntry, adNapClientSecuritySeverity=adNapClientSecuritySeverity, adNapClientOsVersion=adNapClientOsVersion, adNapCapableServer=adNapCapableServer, adNapCapableClient=adNapCapableClient, adNapClientHostname=adNapClientHostname, adGenNapClients=adGenNapClients, adNapClientAntispyware=adNapClientAntispyware, adGenNapClientsGroup=adGenNapClientsGroup, adGenAOSDesktopAuditingMib=adGenAOSDesktopAuditingMib, adNapClientLastSecurityUpdate=adNapClientLastSecurityUpdate, adNapClientSrcPortIfId=adNapClientSrcPortIfId)
try: raise ValueError("invalid!") except ValueError as error: print(str(error) + " input") finally: print("Finishd")
''' Crie uma tupla preenchida com os 20 primeiros colocados da Tabela do Campeonato Brasileiro de Futebol, na ordem de colocação. Depois mostre: A) Apenas os 5 primeiros colocados. B) Os últimos 4 colocados da tabela. C) Uma lista com os times em ordem alfabética. D) Em que posição na tabela está o time da Chapecoense. ''' times = ('Flamengo', 'Santos', 'Palmeiras', 'Grêmio', 'Athletico Paranaense', 'São Paulo', 'Internacional', 'Corinthians', 'Fortaleza', 'Goiás', 'Bahia', 'Vasco da Gama', 'Atlético', 'Fluminense', 'Botafogo', 'Ceará', 'Cruzeiro', 'Csa', 'Chapecoense', 'Avaí') print('5 primeiros colocados:') print(times[:5]) print('\n4 últimos colocados:') print(times[16:])#ou times[-4] print('\nTimes em Ordem Alfabética:') print(sorted(times)) print(f'\nA Chapecoense está na {times.index("Chapecoense") + 1}ª posição')
if __name__ == "__main__": a = [1,2,3] i = -1 print(a[-1]) for i in range(-1,-4,-1): print(a[i])
# Copyright (c) 2013 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Presubmit script for build/chromeos/. See http://dev.chromium.org/developers/how-tos/depottools/presubmit-scripts for details on the presubmit API built into depot_tools. """ def CommonChecks(input_api, output_api): results = [] results += input_api.canned_checks.RunPylint( input_api, output_api, pylintrc='pylintrc') tests = input_api.canned_checks.GetUnitTestsInDirectory( input_api, output_api, '.', [r'^.+_test\.py$']) results += input_api.RunTests(tests) return results def CheckChangeOnUpload(input_api, output_api): return CommonChecks(input_api, output_api) def CheckChangeOnCommit(input_api, output_api): return CommonChecks(input_api, output_api)
N, W = map(int, input().split()) vw = [list(map(int, input().split())) for _ in range(N)] dp = [[0] * W for _ in range(N)] for i in range(N): for w in range(W): if w >= vw[i][1]: dp[i + 1][w] = max(dp[i][w - vw[i][1]] + vw[i][0], dp[i][w])
valor = int(input("Informe um valor: ")) triplo = valor * 3 contador = 0 while contador<5: print(triplo) contador = contador + 1 print("Acabou!")
class IBindingList: """ Provides the features required to support both complex and simple scenarios when binding to a data source. """ def ZZZ(self): """hardcoded/mock instance of the class""" return IBindingList() instance=ZZZ() """hardcoded/returns an instance of the class""" def AddIndex(self,property): """ AddIndex(self: IBindingList,property: PropertyDescriptor) Adds the System.ComponentModel.PropertyDescriptor to the indexes used for searching. property: The System.ComponentModel.PropertyDescriptor to add to the indexes used for searching. """ pass def AddNew(self): """ AddNew(self: IBindingList) -> object Adds a new item to the list. Returns: The item added to the list. """ pass def ApplySort(self,property,direction): """ ApplySort(self: IBindingList,property: PropertyDescriptor,direction: ListSortDirection) Sorts the list based on a System.ComponentModel.PropertyDescriptor and a System.ComponentModel.ListSortDirection. property: The System.ComponentModel.PropertyDescriptor to sort by. direction: One of the System.ComponentModel.ListSortDirection values. """ pass def Find(self,property,key): """ Find(self: IBindingList,property: PropertyDescriptor,key: object) -> int Returns the index of the row that has the given System.ComponentModel.PropertyDescriptor. property: The System.ComponentModel.PropertyDescriptor to search on. key: The value of the property parameter to search for. Returns: The index of the row that has the given System.ComponentModel.PropertyDescriptor. """ pass def RemoveIndex(self,property): """ RemoveIndex(self: IBindingList,property: PropertyDescriptor) Removes the System.ComponentModel.PropertyDescriptor from the indexes used for searching. property: The System.ComponentModel.PropertyDescriptor to remove from the indexes used for searching. """ pass def RemoveSort(self): """ RemoveSort(self: IBindingList) Removes any sort applied using System.ComponentModel.IBindingList.ApplySort(System.ComponentModel.PropertyDescriptor,System.ComponentModel.ListSortDirection). """ pass def __contains__(self,*args): """ __contains__(self: IList,value: object) -> bool Determines whether the System.Collections.IList contains a specific value. value: The object to locate in the System.Collections.IList. Returns: true if the System.Object is found in the System.Collections.IList; otherwise,false. """ pass def __init__(self,*args): """ x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """ pass def __iter__(self,*args): """ __iter__(self: IEnumerable) -> object """ pass def __len__(self,*args): """ x.__len__() <==> len(x) """ pass AllowEdit=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets whether you can update items in the list. Get: AllowEdit(self: IBindingList) -> bool """ AllowNew=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets whether you can add items to the list using System.ComponentModel.IBindingList.AddNew. Get: AllowNew(self: IBindingList) -> bool """ AllowRemove=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets whether you can remove items from the list,using System.Collections.IList.Remove(System.Object) or System.Collections.IList.RemoveAt(System.Int32). Get: AllowRemove(self: IBindingList) -> bool """ IsSorted=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets whether the items in the list are sorted. Get: IsSorted(self: IBindingList) -> bool """ SortDirection=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets the direction of the sort. Get: SortDirection(self: IBindingList) -> ListSortDirection """ SortProperty=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets the System.ComponentModel.PropertyDescriptor that is being used for sorting. Get: SortProperty(self: IBindingList) -> PropertyDescriptor """ SupportsChangeNotification=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets whether a System.ComponentModel.IBindingList.ListChanged event is raised when the list changes or an item in the list changes. Get: SupportsChangeNotification(self: IBindingList) -> bool """ SupportsSearching=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets whether the list supports searching using the System.ComponentModel.IBindingList.Find(System.ComponentModel.PropertyDescriptor,System.Object) method. Get: SupportsSearching(self: IBindingList) -> bool """ SupportsSorting=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets whether the list supports sorting. Get: SupportsSorting(self: IBindingList) -> bool """ ListChanged=None
__author__ = 'alse' def content_length_test(train_metas, test_examples): max_length = 0.0 min_length = 1000.0 for metadata in train_metas: if max_length < metadata.length * 1.0 / metadata.size: max_length = metadata.length * 1.0 / metadata.size if min_length > metadata.length * 1.0 / metadata.size: min_length = metadata.length * 1.0 / metadata.size avg_length = (min_length + max_length) / 2 sum_length = 0 sum_length += len(" ".join(test_examples).split()) return abs(sum_length * 1.0 / len(test_examples) - avg_length) def jaccard_similarity(x, y): intersection_cardinality = len(set.intersection(*[set(x), set(y)])) union_cardinality = len(set.union(*[set(x), set(y)])) return intersection_cardinality / float(union_cardinality) def get_n_grams(sentence, n): return [sentence[i:i + n] for i in xrange(len(sentence) - n)] def label_text_test(train_metas, test_label): # TODO check if this is right return max([jaccard_similarity(get_n_grams(x, 2), get_n_grams(test_label, 2)) for x in train_metas])
while True: op = input("Digite o Operador: ") result = 0 if (op != '+') and (op != '-') and (op != '*') and (op != '/') and (op != '#'): print("Operador invalido!") else: if op == '#': print("Encerrando!") break n1 = float(input("Digite o valor 1: ")) n2 = float(input("Digite o valor 2: ")) if op == '+': result = n1 + n2 elif op == '-': result = n1 - n2 elif op == '*': result = n1 * n2 elif op == '/': if n2 == 0: print("Operacao invalida (Divisao por 0)") else: result = n1 / n2 print(f"O resultado eh {result}")
input = """ % Bug in rewrinting. Count is eliminated as it is considered isolated. % Instead it must be considered as a false literal as the aggregate is % always violated, and bug shouldn't be true. c(1). b(1). bug :- c(Y), Y < #sum{ V:b(V) }. """ output = """ {b(1), c(1)} """
class Solution: def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]: nums_copy = nums.copy() ret = [] count = 0 for i in range(len(nums)): nums.pop(i) nums.insert(0, nums_copy[i]) count = 0 j = 1 while j < len(nums) : if nums[0] > nums[j]: count += 1 j += 1 ret.append(count) return ret
""" Misc. code helper """ def _generate_unique_attribute(fun): return "__init_%s_%s" % (fun.func_name, str(id(fun))) def init_function_attrs(fun, **vars): """ Add the variables with values as attributes to the function fun if they do not exist and return the function. Usage: self = init_function_attr(myFun, a = 2, b = 3) Results in: self = myFun, self.a = 2, self.b = 3 """ unique_attr = _generate_unique_attribute(fun) try: getattr(fun, unique_attr) except AttributeError: for (key, val) in vars.items(): setattr(fun, key, val) setattr(fun, unique_attr, True) return fun def reset_function_attrs(fun): try: getattr(fun, _generate_unique_attribute(fun)) except AttributeError: pass else: delattr(fun, _generate_unique_attribute(fun))
#!/usr/bin/python3 # https://practice.geeksforgeeks.org/problems/betting-game/0 def sol(s): """ Update rules as per the statement """ ba = 1 n = len(s) i = 0 t = 4 while i < n: if t < ba: return -1 if s[i] == "W": t = t + ba ba = 1 else: t = t - ba ba = 2*ba i+=1 return t
############################################################# # rename or copy this file to config.py if you make changes # ############################################################# # change this to your fully-qualified domain name to run a # remote server. The default value of localhost will # only allow connections from the same computer. # # for remote (cloud) deployments, it is advised to remove # the "local" data_sources item below, and to serve static # files using a standard webserver # # if use_redis is False, server will use in-memory cache. # TODO: Convert this to JSON file in web-accesible ('static') # directory. config = { # ssl_args for https serving the rpc # ssl_args = {"keyfile": None, "certfile": None} # Cache engines are diskcache, redis, or memory if not specified "cache": { "engine": "diskcache", "params": {"size_limit": int(4*2**30)} }, "data_sources": [ { "name": "local", "url": "file:///", "start_path": "", }, { "name": "ncnr", "url": "http://ncnr.nist.gov/pub/", "start_path": "ncnrdata", "file_helper_url": "https://ncnr.nist.gov/ncnrdata/listftpfiles_json.php", }, { "name": "charlotte", "url": "http://charlotte.ncnr.nist.gov/pub", "start_path": "", "file_helper_url": "http://charlotte.ncnr.nist.gov/ncnrdata/listftpfiles_json.php", }, # set start_path for local files to usr/local/nice/server_data/experiments # for instrument installs { "name": "ncnr_DOI", "DOI": "10.18434/T4201B", "file_helper_url": "https://ncnr.nist.gov/ncnrdata/listncnrdatafiles_json.php" }, ], # if not set, will instantiate all instruments. "instruments": ["refl", "ospec", "sans"] }
# Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST. # According to the definition of LCA on Wikipedia: “The lowest common ancestor is defined between two nodes p and q as the lowest node in T that has both p and q as descendants (where we allow a node to be a descendant of itself).” # Given binary search tree: root = [6,2,8,0,4,7,9,null,null,3,5] # _______6______ # / \ # ___2__ ___8__ # / \ / \ # 0 _4 7 9 # / \ # 3 5 # Example 1: # Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 8 # Output: 6 # Explanation: The LCA of nodes 2 and 8 is 6. # Example 2: # Input: root = [6,2,8,0,4,7,9,null,null,3,5], p = 2, q = 4 # Output: 2 # Explanation: The LCA of nodes 2 and 4 is 2, since a node can be a descendant of itself # according to the LCA definition. # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def lowestCommonAncestor(self, root, p, q): """ :type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode """ node = root while node: if node.val > q.val and node.val > p.val: node = node.left elif node.val < q.val and node.val < p.val: node = node.right else: return node # Time: O(n+m) # Space: O(1) # Difficulty: easy
#住所録追加 def addAddress(name,address,tel,mail): item = [name,address,tel,mail] addressList.append(item) print("登録しました。") print() #住所録表示 def showAddress(addressNum): obj = addressList[addressNum-1] print("名前:" + obj[0]) print("住所:" + obj[1]) print("電話番号:" + obj[2]) print("メールアドレス:" + obj[3]) print() #住所録検索 def searchAddress(search): addressListCnt = len(addressList) count = 0 if addressListCnt == 0: print("住所録が未登録です。") return for i in range(addressListCnt): checkFlg = False for j in range(len(addressList[i])): if search in addressList[i][j]: checkFlg = True if checkFlg == True: print("名前:"+ addressList[i][0]) print("住所:"+ addressList[i][1]) print("電話番号:"+ addressList[i][2]) print("メールアドレス:"+ addressList[i][3]) print() count += 1 if count > 0: print(str(count) + "件のデータが見つかりました。") print() else: print("入力された「 " +str(search) +" 」が含まれるデータは見つかりませんでした。") print() print("住所管理アプリケーションへようこそ。") addressList = [] while True: print("**********メニュー**********") menu = input("1)住所録追加 2)住所録表示 3)住所録検索 9)終了:") if menu == '1': print("住所録に登録するデータを入力してください。") name = input("名前:") address = input("住所:") tel = input("電話番号:") mail = input("メールアドレス:") addAddress(name,address,tel,mail) continue elif menu == '2': addressListCnt = str(len(addressList)) if addressListCnt == '0': print("住所録が未登録です。") print() continue else: addressNum = int(input("表示するアドレスの番号を入力してください。(1-" + addressListCnt + "):")) print() showAddress(addressNum) continue elif menu == '3': search = input("検索するデータを入力してください:") print() searchAddress(search) continue else: print("ありがとうございました。") break
# Kernel config c.IPKernelApp.pylab = 'inline' # if you want plotting support always in your notebook c = get_config() c.NotebookApp.ip = '*' c.NotebookApp.port = 8888 c.NotebookApp.open_browser = False c.NotebookApp.token = '' c.NotebookApp.password = u'' c.notebookApp.open_browser = True
""" 给定一个单词列表,我们将这个列表编码成一个索引字符串 S 与一个索引列表 A。 例如,如果这个列表是 ["time", "me", "bell"],我们就可以将其表示为 S = "time#bell#" 和 indexes = [0, 2, 5]。 对于每一个索引,我们可以通过从字符串 S 中索引的位置开始读取字符串,直到 "#" 结束,来恢复我们之前的单词列表。 那么成功对给定单词列表进行编码的最小字符串长度是多少呢?   示例: 输入: words = ["time", "me", "bell"] 输出: 10 说明: S = "time#bell#" , indexes = [0, 2, 5] 。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/short-encoding-of-words 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ # TIME OUT class Solution: def minimumLengthEncoding(self, words) -> int: '''Solution A compressed string should be in the end of another longer string The final length should be the all_string_length - compressed_string_length + nums_of_unique_string unique_string_length + nums_of_unique_string First sort the words by length Second find unique string ''' if not words : return 0 final_length = 0 nums_unique = 0 word_length_dict = {} for word in words: word_length_dict.update({word:len(word)}) # print(word_length_dict) sorted_words_set = sorted(word_length_dict.items() ,key=lambda x: x[1]) sorted_words = [x[0] for x in sorted_words_set ] # print(sorted_words) for i in range(len(sorted_words)-1): # print(sorted_words[i]) final_length += len(sorted_words[i]) nums_unique += 1 for j in range(i+1,len(sorted_words)): if not self.judge_unique(sorted_words[i],sorted_words[j]): # print(sorted_words[i],sorted_words[j]) final_length -= len(sorted_words[i]) nums_unique -= 1 break return final_length+nums_unique+len(sorted_words[-1])+1 def judge_unique(self,s1,s2): '''Judge whether s1 can be hidden in s2's end output: False means s1 is not unique ''' # print('judge:',s1,s2) for i in range(1,len(s1)+1): if s1[-i] != s2[-i]: return True return False if __name__ == "__main__": s = Solution() words = ['time','me','bell','ell','xcedr'] # print(s.judge_unique('me','time')) print(s.minimumLengthEncoding(words))
# 3. Для чисел в пределах от 20 до 240 найти числа, кратные 20 или 21. # Необходимо решить задание в одну строку. # Подсказка: использовать функцию range() и генератор. lister = [elem for elem in range(20, 241) if elem % 20 == 0 or elem % 21 == 0] print(f"Результат {lister}")
def check_parity(a: int, b: int, c: int) -> bool: return a%2 == b%2 == c%2 def print_result(result: bool) -> None: if result: print("WIN") else: print("FAIL") a, b, c = map(int, input().strip().split()) print_result(check_parity(a, b, c))
class employee: def __init__(self,first,last,pay): self.first = first self.last = last self.pay = pay self.email = first + '.' +last + '@gmail.com' def fullname(self): return '{} {}'.format(self.first,self.last) #instance variables contain data that is unique to each instances emp1 = employee('corey','schafer',50000) emp2 = employee('baken','henry',40000) # print(emp1) # print(emp2) print(emp1.email) print(emp2.email) # print('{} {}'.format(emp1.first,emp1.last)) print(emp1.fullname())
class Solution: def findDuplicate(self, nums): """ :type nums: List[int] :rtype: int """ low, high, mid = 0, len(nums)-1, len(nums)-1 // 2 while high - low > 1: count, mid = 0, (high + low) // 2 for k in nums: if mid < k <= high: count += 1 if count > high - mid: low = mid else: high = mid return high
# @Title: 路径总和 III (Path Sum III) # @Author: 18015528893 # @Date: 2021-02-08 12:46:49 # @Runtime: 756 ms # @Memory: 16 MB # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: ret = 0 def pathSum(self, root: TreeNode, sum: int) -> int: if root is None: return self.ret self.helper(root, sum) self.pathSum(root.left, sum) self.pathSum(root.right, sum) return self.ret def helper(self, root, s): def dfs(root, s): if root is None: return s -= root.val if s == 0: self.ret += 1 dfs(root.left, s) dfs(root.right, s) dfs(root, s)
def combinations(n, buttons): """ Известно в каком порядке были нажаты кнопки телефона, без учета повторов. Напечатайте все комбинации букв, которые можно набрать такой последовательностью нажатий. """ if n == '': return [''] new = [] # s = numbers[n[-1]] for i in combinations(n[:-1:], buttons): for x in buttons[n[-1]]: new.append(i + x) return new if __name__ == '__main__': n = input() buttons = { '2': 'abc', '3': 'def', '4': 'ghi', '5': 'jkl', '6': 'mno', '7': 'pqrs', '8': 'tuv', '9': 'wxyz' } result = combinations(n, buttons) print(*result)
""" The `gcp_hpo.test` module contains some scripts to test how GCP behaves. ### Regression The regression folder tests GCP on regression tasks. While `display_branin_function.py` and `simple_test.py` are mostly there to visualize what is happening, `full_test.py` can be used to quantify its accuracy. More precisely, this enables to test GCP for regression on different functions (see the file `function_utils.py`) and to measure the likelihood of the fit as well as the mean squared errors of the predictions. ### Acquisition functions In GCP-based Bayezian optimization, a GCP is fitted on an unknown function and the fit is used to compute some acquisition function. The folder `acquisition_functions` folder contains two scripts to see the behaviors of the Expected Improvement and the confidence bounds with GCP. """
# Copyright (c) 2013, Tomohiro Kusumi # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # # 1. Redistributions of source code must retain the above copyright notice, this # list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright notice, # this list of conditions and the following disclaimer in the documentation # and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR # ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; # LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND # ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # RELEASE is basically always 1. # It was added only to sync with RPM versioning. # Everytime a batch of new commits is pushed to GitHub, MINOR2 gets incremented. # RPM patches within the same fileobj version may or may not increment RELEASE. MAJOR = 0 MINOR1 = 7 MINOR2 = 106 RELEASE = 1 def get_version(): return MAJOR, MINOR1, MINOR2 def get_release(): return MAJOR, MINOR1, MINOR2, RELEASE def get_version_string(): return "{0}.{1}.{2}".format(*get_version()) def get_release_string(): return "{0}.{1}.{2}-{3}".format(*get_release()) def get_tag_string(): return "v" + get_version_string() try: __version__ = get_version_string() except Exception: __version__ = "???" # .format() unsupported
''' Given a string S of lowercase letters, a duplicate removal consists of choosing two adjacent and equal letters, and removing them. We repeatedly make duplicate removals on S until we no longer can. Return the final string after all such duplicate removals have been made. It is guaranteed the answer is unique. Example 1: Input: "abbaca" Output: "ca" Explanation: For example, in "abbaca" we could remove "bb" since the letters are adjacent and equal, and this is the only possible move. The result of this move is that the string is "aaca", of which only "aa" is possible, so the final string is "ca". Note: 1 <= S.length <= 20000 S consists only of English lowercase letters. ''' class Solution(object): def removeDuplicates(self, S): """ :type S: str :rtype: str """ stack = [] if not S: return "" for char in S: if not stack: stack.append(char) else: first = stack[-1] if first == char: stack.pop() else: stack.append(char) if not stack: return "" return ''.join(stack)
while True: try: fruit_name = input("입력하고 싶은 숫자가 뭐에요?") fruit_name = int(fruit_name) if fruit_name < 10: print("10보다 작은 숫자가 입력이 되었습니다") else: print("10보다 큰 숫자가 입력이 되었습니다.") break except: print("숫자를 입력해주세요 ㅠㅠ") continue