content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
#show function logs all attempts on console and in out.txt file out = open("out.txt", 'w+') def show(line): li = "" for i in line: for j in i: li += str(j) + " " li += "\n" print(li) out.write(li) out.write("\n")
out = open('out.txt', 'w+') def show(line): li = '' for i in line: for j in i: li += str(j) + ' ' li += '\n' print(li) out.write(li) out.write('\n')
print() print("-- RELATIONS ------------------------------") print() print("GRAPH 1:\n0 0 0\n0 0 0\n0 0 0") g1 = Graph(3) print("REFLEXIVITA: " + str(is_reflexive(g1)) + " -> spravna odpoved: False") print("SYMETRIE: " + str(is_symmetric(g1)) + " -> spravna odpoved: True") print("ANTISYMETRIE: " + str(is_antisymmetric(g1)) + " -> spravna odpoved: True") print("TRANZITIVITA: " + str(is_transitive(g1)) + " -> spravna odpoved: True") print("-------------------------------------------") print("GRAPH 2:\n1 0 0\n0 1 0\n0 0 1") g2 = Graph(3) g2.matrix[0][0] = True g2.matrix[1][1] = True g2.matrix[2][2] = True print("REFLEXIVITA: " + str(is_reflexive(g2)) + " -> spravna odpoved: True") print("SYMETRIE: " + str(is_symmetric(g2)) + " -> spravna odpoved: True") print("ANTISYMETRIE: " + str(is_antisymmetric(g2)) + " -> spravna odpoved: False") print("TRANZITIVITA: " + str(is_transitive(g2)) + " -> spravna odpoved: True") print("- GOOD GRAPHS -----------------------------") print("GRAPH 3:\n0 0 0\n0 1 0\n0 1 1") g3 = Graph(3) g3.matrix[1][1] = True g3.matrix[2][1] = True g3.matrix[2][2] = True print("REFLEXIVITA: " + str(is_reflexive(g3)) + " -> spravna odpoved: False") print("SYMETRIE: " + str(is_symmetric(g3)) + " -> spravna odpoved: False") print("ANTISYMETRIE: " + str(is_antisymmetric(g3)) + " -> spravna odpoved: True") print("TRANZITIVITA: " + str(is_transitive(g3)) + " -> spravna odpoved: True") print("-------------------------------------------") print("GRAPH 4:\n0 1 1\n0 1 1\n0 0 1") g4 = Graph(3) g4.matrix[0][1] = True g4.matrix[0][2] = True g4.matrix[1][1] = True g4.matrix[1][2] = True g4.matrix[2][2] = True print("REFLEXIVITA: " + str(is_reflexive(g4)) + " -> spravna odpoved: False") print("SYMETRIE: " + str(is_symmetric(g4)) + " -> spravna odpoved: False") print("ANTISYMETRIE: " + str(is_antisymmetric(g4)) + " -> spravna odpoved: True") print("TRANZITIVITA: " + str(is_transitive(g4)) + " -> spravna odpoved: True") print("-------------------------------------------") print("GRAPH 5:\n1 0 0\n0 0 0\n1 0 0") g5 = Graph(3) g5.matrix[0][0] = True g5.matrix[2][0] = True print("REFLEXIVITA: " + str(is_reflexive(g5)) + " -> spravna odpoved: False") print("SYMETRIE: " + str(is_symmetric(g5)) + " -> spravna odpoved: False") print("ANTISYMETRIE: " + str(is_antisymmetric(g5)) + " -> spravna odpoved: True") print("TRANZITIVITA: " + str(is_transitive(g5)) + " -> spravna odpoved: True") print("-------------------------------------------") print("GRAPH 6:\n1 0 0\n1 1 0\n0 1 1") g6 = Graph(3) g6.matrix[0][0] = True g6.matrix[1][0] = True g6.matrix[1][1] = True g6.matrix[2][1] = True g6.matrix[2][2] = True print("REFLEXIVITA: " + str(is_reflexive(g6)) + " -> spravna odpoved: True") print("SYMETRIE: " + str(is_symmetric(g6)) + " -> spravna odpoved: False") print("ANTISYMETRIE: " + str(is_antisymmetric(g6)) + " -> spravna odpoved: True") print("TRANZITIVITA: " + str(is_transitive(g6)) + " -> spravna odpoved: False") print() print("- TRANSITIVE CLOSURE -------------------------") print() print("GRAPH 7:\n1 0 0\n1 1 0\n0 1 1") g7 = Graph(3) g7.matrix[0][0] = True g7.matrix[1][0] = True g7.matrix[1][1] = True g7.matrix[2][1] = True g7.matrix[2][2] = True print("TRANZITIVITA: " + str(is_transitive(g7)) + " -> spravna odpoved: False") transitive_closure(g7) print(str(g7.matrix)) print("TRANZITIVITA: " + str(is_transitive(g7)) + " -> spravna odpoved: True")
print() print('-- RELATIONS ------------------------------') print() print('GRAPH 1:\n0 0 0\n0 0 0\n0 0 0') g1 = graph(3) print('REFLEXIVITA: ' + str(is_reflexive(g1)) + ' -> spravna odpoved: False') print('SYMETRIE: ' + str(is_symmetric(g1)) + ' -> spravna odpoved: True') print('ANTISYMETRIE: ' + str(is_antisymmetric(g1)) + ' -> spravna odpoved: True') print('TRANZITIVITA: ' + str(is_transitive(g1)) + ' -> spravna odpoved: True') print('-------------------------------------------') print('GRAPH 2:\n1 0 0\n0 1 0\n0 0 1') g2 = graph(3) g2.matrix[0][0] = True g2.matrix[1][1] = True g2.matrix[2][2] = True print('REFLEXIVITA: ' + str(is_reflexive(g2)) + ' -> spravna odpoved: True') print('SYMETRIE: ' + str(is_symmetric(g2)) + ' -> spravna odpoved: True') print('ANTISYMETRIE: ' + str(is_antisymmetric(g2)) + ' -> spravna odpoved: False') print('TRANZITIVITA: ' + str(is_transitive(g2)) + ' -> spravna odpoved: True') print('- GOOD GRAPHS -----------------------------') print('GRAPH 3:\n0 0 0\n0 1 0\n0 1 1') g3 = graph(3) g3.matrix[1][1] = True g3.matrix[2][1] = True g3.matrix[2][2] = True print('REFLEXIVITA: ' + str(is_reflexive(g3)) + ' -> spravna odpoved: False') print('SYMETRIE: ' + str(is_symmetric(g3)) + ' -> spravna odpoved: False') print('ANTISYMETRIE: ' + str(is_antisymmetric(g3)) + ' -> spravna odpoved: True') print('TRANZITIVITA: ' + str(is_transitive(g3)) + ' -> spravna odpoved: True') print('-------------------------------------------') print('GRAPH 4:\n0 1 1\n0 1 1\n0 0 1') g4 = graph(3) g4.matrix[0][1] = True g4.matrix[0][2] = True g4.matrix[1][1] = True g4.matrix[1][2] = True g4.matrix[2][2] = True print('REFLEXIVITA: ' + str(is_reflexive(g4)) + ' -> spravna odpoved: False') print('SYMETRIE: ' + str(is_symmetric(g4)) + ' -> spravna odpoved: False') print('ANTISYMETRIE: ' + str(is_antisymmetric(g4)) + ' -> spravna odpoved: True') print('TRANZITIVITA: ' + str(is_transitive(g4)) + ' -> spravna odpoved: True') print('-------------------------------------------') print('GRAPH 5:\n1 0 0\n0 0 0\n1 0 0') g5 = graph(3) g5.matrix[0][0] = True g5.matrix[2][0] = True print('REFLEXIVITA: ' + str(is_reflexive(g5)) + ' -> spravna odpoved: False') print('SYMETRIE: ' + str(is_symmetric(g5)) + ' -> spravna odpoved: False') print('ANTISYMETRIE: ' + str(is_antisymmetric(g5)) + ' -> spravna odpoved: True') print('TRANZITIVITA: ' + str(is_transitive(g5)) + ' -> spravna odpoved: True') print('-------------------------------------------') print('GRAPH 6:\n1 0 0\n1 1 0\n0 1 1') g6 = graph(3) g6.matrix[0][0] = True g6.matrix[1][0] = True g6.matrix[1][1] = True g6.matrix[2][1] = True g6.matrix[2][2] = True print('REFLEXIVITA: ' + str(is_reflexive(g6)) + ' -> spravna odpoved: True') print('SYMETRIE: ' + str(is_symmetric(g6)) + ' -> spravna odpoved: False') print('ANTISYMETRIE: ' + str(is_antisymmetric(g6)) + ' -> spravna odpoved: True') print('TRANZITIVITA: ' + str(is_transitive(g6)) + ' -> spravna odpoved: False') print() print('- TRANSITIVE CLOSURE -------------------------') print() print('GRAPH 7:\n1 0 0\n1 1 0\n0 1 1') g7 = graph(3) g7.matrix[0][0] = True g7.matrix[1][0] = True g7.matrix[1][1] = True g7.matrix[2][1] = True g7.matrix[2][2] = True print('TRANZITIVITA: ' + str(is_transitive(g7)) + ' -> spravna odpoved: False') transitive_closure(g7) print(str(g7.matrix)) print('TRANZITIVITA: ' + str(is_transitive(g7)) + ' -> spravna odpoved: True')
# Task 03. Statistics def add_to_dict(product: str, quantity: int): if product not in stock: stock[product] = quantity else: stock[product] += quantity cmd = input() stock = {} while not cmd == "statistics": key = cmd.split(': ')[0] value = cmd.split(': ')[1] add_to_dict(key, int(value)) cmd = input() print("Products in stock:") for product in stock: print(f"- {product}: {stock[product]}") print(f"Total Products: {len(stock)}") print(f"Total Quantity: {sum(stock.values())}")
def add_to_dict(product: str, quantity: int): if product not in stock: stock[product] = quantity else: stock[product] += quantity cmd = input() stock = {} while not cmd == 'statistics': key = cmd.split(': ')[0] value = cmd.split(': ')[1] add_to_dict(key, int(value)) cmd = input() print('Products in stock:') for product in stock: print(f'- {product}: {stock[product]}') print(f'Total Products: {len(stock)}') print(f'Total Quantity: {sum(stock.values())}')
''' This problem was asked by Stripe. Given an array of integers, find the first missing positive integer in linear time and constant space. In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well. For example, the input [3, 4, -1, 1] should give 2. The input [1, 2, 0] should give 3. You can modify the input array in-place. ''' def findLowestPositiveInteger(array): array.sort() nextNumber = 1 for x in array: if x > nextNumber and x > 0: break elif x > 0: nextNumber += 1 print(nextNumber) findLowestPositiveInteger([3,4,-1,-1]) findLowestPositiveInteger([1, 2, 0])
""" This problem was asked by Stripe. Given an array of integers, find the first missing positive integer in linear time and constant space. In other words, find the lowest positive integer that does not exist in the array. The array can contain duplicates and negative numbers as well. For example, the input [3, 4, -1, 1] should give 2. The input [1, 2, 0] should give 3. You can modify the input array in-place. """ def find_lowest_positive_integer(array): array.sort() next_number = 1 for x in array: if x > nextNumber and x > 0: break elif x > 0: next_number += 1 print(nextNumber) find_lowest_positive_integer([3, 4, -1, -1]) find_lowest_positive_integer([1, 2, 0])
#Main class class Characters: def __init__(self, name, lastname, age, hp, title, language, race, weakness ): # instance variable unique to each instance self.__name = name self.__lastname = lastname self.__age = age self.__hp = hp self.__title = title self.__race = race self.__weakness = weakness self.__language = language def character_info(self): return f"ID:{self.__name} {self.__lastname}\n" \ f"age:{self.__age}\n" \ f"Hp:{self.__hp} \n" \ f"race:{self.__race}\n" \ f"title:{self.__title}\n" \ f"weakness:{self.__weakness}\n" \ f"language:{self.__language}\n" \ f"that's all buddy" def attributeone(self): return f"{self.__name}" def attributetwo(self): return F"{self.__hp}" #These classes are inheritors of the main class class WarriorPerson(Characters): def __init__(self, name="none", lastname="none", age="none", hp="150", title="none", language="none", race="human or unknown", weakness="none"): super().__init__(name, lastname, age, hp, title, language, race, weakness) class RegularHumanPerson(Characters): def __init__(self, name="none", lastname="", age="none", hp="50", title="The man who be normal", language="English", race="human or unknown", weakness="nearly everything"): super().__init__(name, lastname, age, hp, title, language, race, weakness) class WitchPerson(Characters): def __init__(self, name="none", lastname="none", age="none", hp="896", title="none", language="none", race="human or unknown", weakness="none"): super().__init__(name, lastname, age, hp, title, language, race, weakness) class VampirePerson(Characters): def __init__(self, name="none", lastname="", age="none", hp="500", title="none", language="none", race="human or unknown", weakness="none"): super().__init__(name, lastname, age, hp, title, language, race, weakness) regular_human = RegularHumanPerson( name="john", lastname="smith", age="45", hp="50", ) regular_humans_sidekick = RegularHumanPerson( name="robin", age="20", hp="32", ) old_warrior = WarriorPerson( name="Berserker", lastname="", age="345", hp="500", title="old warrior", language="English and old vikings language", race="Human", weakness="Science" ) old_which = WitchPerson( name="Sarah", lastname="", age="600", hp="659", title="Girl of beast", language="She knows little bit old english and witch language", race="Human", weakness="Science and light of angel" ) young_Vampire = VampirePerson( name="Deacon", lastname="", age="783", hp="800", language="She knows little bit old english and new english", race="vampire", weakness="stake" )
class Characters: def __init__(self, name, lastname, age, hp, title, language, race, weakness): self.__name = name self.__lastname = lastname self.__age = age self.__hp = hp self.__title = title self.__race = race self.__weakness = weakness self.__language = language def character_info(self): return f"ID:{self.__name} {self.__lastname}\nage:{self.__age}\nHp:{self.__hp} \nrace:{self.__race}\ntitle:{self.__title}\nweakness:{self.__weakness}\nlanguage:{self.__language}\nthat's all buddy" def attributeone(self): return f'{self.__name}' def attributetwo(self): return f'{self.__hp}' class Warriorperson(Characters): def __init__(self, name='none', lastname='none', age='none', hp='150', title='none', language='none', race='human or unknown', weakness='none'): super().__init__(name, lastname, age, hp, title, language, race, weakness) class Regularhumanperson(Characters): def __init__(self, name='none', lastname='', age='none', hp='50', title='The man who be normal', language='English', race='human or unknown', weakness='nearly everything'): super().__init__(name, lastname, age, hp, title, language, race, weakness) class Witchperson(Characters): def __init__(self, name='none', lastname='none', age='none', hp='896', title='none', language='none', race='human or unknown', weakness='none'): super().__init__(name, lastname, age, hp, title, language, race, weakness) class Vampireperson(Characters): def __init__(self, name='none', lastname='', age='none', hp='500', title='none', language='none', race='human or unknown', weakness='none'): super().__init__(name, lastname, age, hp, title, language, race, weakness) regular_human = regular_human_person(name='john', lastname='smith', age='45', hp='50') regular_humans_sidekick = regular_human_person(name='robin', age='20', hp='32') old_warrior = warrior_person(name='Berserker', lastname='', age='345', hp='500', title='old warrior', language='English and old vikings language', race='Human', weakness='Science') old_which = witch_person(name='Sarah', lastname='', age='600', hp='659', title='Girl of beast', language='She knows little bit old english and witch language', race='Human', weakness='Science and light of angel') young__vampire = vampire_person(name='Deacon', lastname='', age='783', hp='800', language='She knows little bit old english and new english', race='vampire', weakness='stake')
n = int(input()) b = list(map(int, input().split(' '))) x = [0] a = [] a.append(b[0]) x.append(a[0]) i = 1 while i < n: a.append(b[i]+x[i]) if a[i] > x[i]: x.append(a[i]) else: x.append(x[i]) i += 1 str_a = [str(ele) for ele in a] print(' '.join(str_a))
n = int(input()) b = list(map(int, input().split(' '))) x = [0] a = [] a.append(b[0]) x.append(a[0]) i = 1 while i < n: a.append(b[i] + x[i]) if a[i] > x[i]: x.append(a[i]) else: x.append(x[i]) i += 1 str_a = [str(ele) for ele in a] print(' '.join(str_a))
def valida(digitos): # digitos = [4,5,7,5,0,8,0,0,0] # digitos = [11] * 9 i = 1 soma = 0 for x in digitos: soma = soma +(i * x) i += 1 return bool( soma % 11 == 0) print(valida(1))
def valida(digitos): i = 1 soma = 0 for x in digitos: soma = soma + i * x i += 1 return bool(soma % 11 == 0) print(valida(1))
{ "targets": [{ "target_name": "OpenSSL_EVP_BytesToKey", "sources": [ "./test/main.cc", ], "cflags": [ "-Wall", "-Wno-maybe-uninitialized", "-Wno-uninitialized", "-Wno-unused-function", "-Wextra" ], "cflags_cc+": [ "-std=c++0x" ], "include_dirs": [ "/usr/local/include", "<!(node -e \"require('nan')\")" ], "conditions": [ [ "OS=='mac'", { "libraries": [ "-L/usr/local/lib" ], "xcode_settings": { "MACOSX_DEPLOYMENT_TARGET": "10.7", "OTHER_CPLUSPLUSFLAGS": [ "-stdlib=libc++" ] } } ] ] }] }
{'targets': [{'target_name': 'OpenSSL_EVP_BytesToKey', 'sources': ['./test/main.cc'], 'cflags': ['-Wall', '-Wno-maybe-uninitialized', '-Wno-uninitialized', '-Wno-unused-function', '-Wextra'], 'cflags_cc+': ['-std=c++0x'], 'include_dirs': ['/usr/local/include', '<!(node -e "require(\'nan\')")'], 'conditions': [["OS=='mac'", {'libraries': ['-L/usr/local/lib'], 'xcode_settings': {'MACOSX_DEPLOYMENT_TARGET': '10.7', 'OTHER_CPLUSPLUSFLAGS': ['-stdlib=libc++']}}]]}]}
def catalan_number(n): nm = dm = 1 for k in range(2, n+1): nm, dm = ( nm*(n+k), dm*k ) return nm/dm print([catalan_number(n) for n in range(1, 16)]) [1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796, 58786, 208012, 742900, 2674440, 9694845]
def catalan_number(n): nm = dm = 1 for k in range(2, n + 1): (nm, dm) = (nm * (n + k), dm * k) return nm / dm print([catalan_number(n) for n in range(1, 16)]) [1, 2, 5, 14, 42, 132, 429, 1430, 4862, 16796, 58786, 208012, 742900, 2674440, 9694845]
NAME = 'weather.py' ORIGINAL_AUTHORS = [ 'Gabriele Ron' ] ABOUT = ''' A plugin to get the weather of a location ''' COMMANDS = ''' >>> .weather <city> <country code> returns the weather ''' WEBSITE = ''
name = 'weather.py' original_authors = ['Gabriele Ron'] about = '\nA plugin to get the weather of a location\n' commands = '\n>>> .weather <city> <country code>\nreturns the weather\n' website = ''
class Node: def __init__(self, value): self.value = value self.next = None class LinkList: def __init__(self, value): node = Node(value) self.head = node self.tail = node self.length = 1 def append(self, value): node = Node(value) if self.length == 0: self.head = node self.tail = node else: self.tail.next = node self.tail = node self.length += 1 return True def prepend(self, value): node = Node(value) if self.length == 0: self.head = node self.tail = node else: node.next = self.head self.head = node self.length += 1 return True def pop(self): if self.length == 0: return None if self.length == 1: temp = self.head self.head = None self.tail = None self.length -= 1 return temp temp = self.head while temp.next != self.tail: temp = temp.next pop = self.tail self.tail = temp self.tail.next = None self.length -= 1 return pop def pop_first(self): if self.length == 0: return None if self.length == 1: temp = self.head self.head = None self.tail = None self.length -= 1 return temp temp = self.head self.head = temp.next temp.next = None self.length -= 1 return temp def get(self, index): if index < 0 or index >= self.length: return None temp = self.head for _ in range(index): temp = temp.next return temp def set_value(self, value, index): temp = self.get(index) if temp: temp.value = value return True return False def insert(self, value, index): if index < 0 or index > self.length: return False if index == 0: return self.prepend(value) node = Node(value) temp = self.get(index - 1) node.next = temp.next temp.next = node self.length += 1 return True def remove(self, index): if index < 0 or index >= self.length: return None if index == 0: return self.pop_first() temp = self.get(index - 1) node = temp.next temp.next = node.next node.next = None self.length -= 1 return node def reverse(self): temp = self.head self.head = self.tail self.tail = temp before = None after = temp.next for _ in range(self.length): after = temp.next temp.next = before before = temp temp = after return True def __str__(self): answer = str() temp = self.head while temp: answer += str(temp.value) + " " temp = temp.next return answer
class Node: def __init__(self, value): self.value = value self.next = None class Linklist: def __init__(self, value): node = node(value) self.head = node self.tail = node self.length = 1 def append(self, value): node = node(value) if self.length == 0: self.head = node self.tail = node else: self.tail.next = node self.tail = node self.length += 1 return True def prepend(self, value): node = node(value) if self.length == 0: self.head = node self.tail = node else: node.next = self.head self.head = node self.length += 1 return True def pop(self): if self.length == 0: return None if self.length == 1: temp = self.head self.head = None self.tail = None self.length -= 1 return temp temp = self.head while temp.next != self.tail: temp = temp.next pop = self.tail self.tail = temp self.tail.next = None self.length -= 1 return pop def pop_first(self): if self.length == 0: return None if self.length == 1: temp = self.head self.head = None self.tail = None self.length -= 1 return temp temp = self.head self.head = temp.next temp.next = None self.length -= 1 return temp def get(self, index): if index < 0 or index >= self.length: return None temp = self.head for _ in range(index): temp = temp.next return temp def set_value(self, value, index): temp = self.get(index) if temp: temp.value = value return True return False def insert(self, value, index): if index < 0 or index > self.length: return False if index == 0: return self.prepend(value) node = node(value) temp = self.get(index - 1) node.next = temp.next temp.next = node self.length += 1 return True def remove(self, index): if index < 0 or index >= self.length: return None if index == 0: return self.pop_first() temp = self.get(index - 1) node = temp.next temp.next = node.next node.next = None self.length -= 1 return node def reverse(self): temp = self.head self.head = self.tail self.tail = temp before = None after = temp.next for _ in range(self.length): after = temp.next temp.next = before before = temp temp = after return True def __str__(self): answer = str() temp = self.head while temp: answer += str(temp.value) + ' ' temp = temp.next return answer
class node: def __init__(self,val): self.val = val self.next = None self.prev = None class mylinkedlist: def __init__(self): self.head = None self.tail = None self.size = 0 def get(self,index): if index < 0 or index >= self.size: return -1 cur = self.head while index != 0: cur = cur.next index = index -1 return cur.val def addathead(self,val): new_node = node(val) if self.head is None: self.head = new_node self.tail = new_node else: new_node.next = self.head self.head.prev = new_node self.head = new_node self.size = self.size + 1 def addatTail(self,val): new_node = node(val) if self.tail is None: self.head = new_node self.tail = new_node else: new_node.prev = self.tail self.tail.next = new_node self.tail = new_node self.size = self.size + 1 def addatIndex(self,index,val): if index < 0 or index >= self.size: return -1 elif index ==0: self.addathead(val) elif index == self.size: self.addatTail(val) else: cur = self.head while index-1 != 0: cur = cur.next index -= 1 new_node = node(val) new_node.next = cur.next cur.next.prev = new_node cur.next = new_node new_node.prev = cur self.size = self.size +1 def deleteatIndex(self,index,val): if index < 0 or index >= self.size: return -1 elif index == 0: cur = self.head.next if cur: cur.prev = None self.head = self.head.next self.size -= 1 if self.size == 0: self.tail = None elif index == self.size-1: cur = self.tail.prev if cur: cur.next = None self.tail = self.tail.prev size -= 1 if self.size == 0: self.head = None else: cur = self.head while index-1 != 0: cur = cur.next index -= 1 cur.next = cur.next.next cur.next.prev = cur self.size -=1
class Node: def __init__(self, val): self.val = val self.next = None self.prev = None class Mylinkedlist: def __init__(self): self.head = None self.tail = None self.size = 0 def get(self, index): if index < 0 or index >= self.size: return -1 cur = self.head while index != 0: cur = cur.next index = index - 1 return cur.val def addathead(self, val): new_node = node(val) if self.head is None: self.head = new_node self.tail = new_node else: new_node.next = self.head self.head.prev = new_node self.head = new_node self.size = self.size + 1 def addat_tail(self, val): new_node = node(val) if self.tail is None: self.head = new_node self.tail = new_node else: new_node.prev = self.tail self.tail.next = new_node self.tail = new_node self.size = self.size + 1 def addat_index(self, index, val): if index < 0 or index >= self.size: return -1 elif index == 0: self.addathead(val) elif index == self.size: self.addatTail(val) else: cur = self.head while index - 1 != 0: cur = cur.next index -= 1 new_node = node(val) new_node.next = cur.next cur.next.prev = new_node cur.next = new_node new_node.prev = cur self.size = self.size + 1 def deleteat_index(self, index, val): if index < 0 or index >= self.size: return -1 elif index == 0: cur = self.head.next if cur: cur.prev = None self.head = self.head.next self.size -= 1 if self.size == 0: self.tail = None elif index == self.size - 1: cur = self.tail.prev if cur: cur.next = None self.tail = self.tail.prev size -= 1 if self.size == 0: self.head = None else: cur = self.head while index - 1 != 0: cur = cur.next index -= 1 cur.next = cur.next.next cur.next.prev = cur self.size -= 1
#declaring variable as string phrase = str(input('Type a phrase: ')) #saving the phrase in lowercase phrase = phrase.lower() #presenting amount of lettters 'a' print('Amount of letters "a": ', phrase.count('a')) #presenting the position of firt 'a' print('Firt "A" in position: ', phrase.find('a')) #presenting the position of last 'a' whith 'right find' print('Last "A" in postion: ',phrase.rfind('a'))
phrase = str(input('Type a phrase: ')) phrase = phrase.lower() print('Amount of letters "a": ', phrase.count('a')) print('Firt "A" in position: ', phrase.find('a')) print('Last "A" in postion: ', phrase.rfind('a'))
{ "targets": [ { "target_name": "json", "product_name": "json", "variables": { "json_dir%": "../" }, 'cflags!': [ '-fno-exceptions' ], 'cflags_cc!': [ '-fno-exceptions' ], 'conditions': [ ['OS=="mac"', { 'xcode_settings': { 'GCC_ENABLE_CPP_EXCEPTIONS': 'YES' } }] ], "type": "static_library", "include_dirs": [ "<(json_dir)/", "<(json_dir)/JSON", "<(json_dir)/JSON/src" ], "sources": [ "<(json_dir)/JSON/json.h", "<(json_dir)/JSON/src/autolink.h", "<(json_dir)/JSON/src/config.h", "<(json_dir)/JSON/src/features.h", "<(json_dir)/JSON/src/forwards.h", "<(json_dir)/JSON/src/json_batchallocator.h", "<(json_dir)/JSON/src/json_tool.h", "<(json_dir)/JSON/src/reader.h", "<(json_dir)/JSON/src/value.h", "<(json_dir)/JSON/src/writer.h", "<(json_dir)/JSON/src/json_internalarray.inl", "<(json_dir)/JSON/src/json_internalmap.inl", "<(json_dir)/JSON/src/json_valueiterator.inl", "<(json_dir)/JSON/src/json_reader.cpp", "<(json_dir)/JSON/src/json_value.cpp", "<(json_dir)/JSON/src/json_writer.cpp" ], "all_dependent_settings": { "include_dirs": [ "<(json_dir)/JSON" ] } } ], "variables": { "conditions": [ [ "OS == 'mac'", { "target_arch%": "x64" }, { "target_arch%": "ia32" } ] ] }, "target_defaults": { "default_configuration": "Release", "defines": [ ], "conditions": [ [ "OS == 'mac'", { "defines": [ "DARWIN" ] }, { "defines": [ "LINUX" ] } ], [ "OS == 'mac' and target_arch == 'x64'", { "xcode_settings": { "ARCHS": [ "x86_64" ] } } ] ], "configurations": { "Debug": { "cflags": [ "-g", "-O0" ], "xcode_settings": { "OTHER_CFLAGS": [ "-g", "-O0" ], "OTHER_CPLUSPLUSFLAGS": [ "-g", "-O0" ] } }, "Release": { "cflags": [ "-O3" ], "defines": [ "NDEBUG" ], "xcode_settings": { "OTHER_CFLAGS": [ "-O3" ], "OTHER_CPLUSPLUSFLAGS": [ "-O3", "-DNDEBUG" ] } } } } }
{'targets': [{'target_name': 'json', 'product_name': 'json', 'variables': {'json_dir%': '../'}, 'cflags!': ['-fno-exceptions'], 'cflags_cc!': ['-fno-exceptions'], 'conditions': [['OS=="mac"', {'xcode_settings': {'GCC_ENABLE_CPP_EXCEPTIONS': 'YES'}}]], 'type': 'static_library', 'include_dirs': ['<(json_dir)/', '<(json_dir)/JSON', '<(json_dir)/JSON/src'], 'sources': ['<(json_dir)/JSON/json.h', '<(json_dir)/JSON/src/autolink.h', '<(json_dir)/JSON/src/config.h', '<(json_dir)/JSON/src/features.h', '<(json_dir)/JSON/src/forwards.h', '<(json_dir)/JSON/src/json_batchallocator.h', '<(json_dir)/JSON/src/json_tool.h', '<(json_dir)/JSON/src/reader.h', '<(json_dir)/JSON/src/value.h', '<(json_dir)/JSON/src/writer.h', '<(json_dir)/JSON/src/json_internalarray.inl', '<(json_dir)/JSON/src/json_internalmap.inl', '<(json_dir)/JSON/src/json_valueiterator.inl', '<(json_dir)/JSON/src/json_reader.cpp', '<(json_dir)/JSON/src/json_value.cpp', '<(json_dir)/JSON/src/json_writer.cpp'], 'all_dependent_settings': {'include_dirs': ['<(json_dir)/JSON']}}], 'variables': {'conditions': [["OS == 'mac'", {'target_arch%': 'x64'}, {'target_arch%': 'ia32'}]]}, 'target_defaults': {'default_configuration': 'Release', 'defines': [], 'conditions': [["OS == 'mac'", {'defines': ['DARWIN']}, {'defines': ['LINUX']}], ["OS == 'mac' and target_arch == 'x64'", {'xcode_settings': {'ARCHS': ['x86_64']}}]], 'configurations': {'Debug': {'cflags': ['-g', '-O0'], 'xcode_settings': {'OTHER_CFLAGS': ['-g', '-O0'], 'OTHER_CPLUSPLUSFLAGS': ['-g', '-O0']}}, 'Release': {'cflags': ['-O3'], 'defines': ['NDEBUG'], 'xcode_settings': {'OTHER_CFLAGS': ['-O3'], 'OTHER_CPLUSPLUSFLAGS': ['-O3', '-DNDEBUG']}}}}}
todos = [] impar = [] par = [] while True: todos.append(int(input('Digite um valor: '))) soun = str(input('Quer adicionar mais ? [S/N] ')).strip()[0] if soun in 'Nn': break for n in todos: if n % 2 == 0: par.append(n) for v in todos: if v % 2 != 0: impar.append(v) print('=' * 40) print(f'Os numeros digitados sao estes {todos}') print(f'Os pares sao {par}.\nE os impares sao {impar}.')
todos = [] impar = [] par = [] while True: todos.append(int(input('Digite um valor: '))) soun = str(input('Quer adicionar mais ? [S/N] ')).strip()[0] if soun in 'Nn': break for n in todos: if n % 2 == 0: par.append(n) for v in todos: if v % 2 != 0: impar.append(v) print('=' * 40) print(f'Os numeros digitados sao estes {todos}') print(f'Os pares sao {par}.\nE os impares sao {impar}.')
def print_formatted(N): width = len(bin(N)[2:]) for i in range(1, N + 1): print(' '.join(map(lambda x: x.rjust(width), [str(i), oct(i)[2:], hex(i)[2:].upper(), bin(i)[2:]]))) if __name__ == '__main__': n = int(input()) print_formatted(n)
def print_formatted(N): width = len(bin(N)[2:]) for i in range(1, N + 1): print(' '.join(map(lambda x: x.rjust(width), [str(i), oct(i)[2:], hex(i)[2:].upper(), bin(i)[2:]]))) if __name__ == '__main__': n = int(input()) print_formatted(n)
class File: def __init__(self, hash, realName, extension, url): self.hash = hash self.realName = realName self.extension = extension self.url = url @staticmethod def from_DB(record): return File(record[0], record[1], record[2], record[3])
class File: def __init__(self, hash, realName, extension, url): self.hash = hash self.realName = realName self.extension = extension self.url = url @staticmethod def from_db(record): return file(record[0], record[1], record[2], record[3])
class Vertex: def __init__(self, id): self.id = id self.edges = set() def outgoing_edges(self): for edge in self.edges: successor = edge.get_successor(self) if successor is not None: yield edge
class Vertex: def __init__(self, id): self.id = id self.edges = set() def outgoing_edges(self): for edge in self.edges: successor = edge.get_successor(self) if successor is not None: yield edge
# -*- coding: UTF-8 -*- light = input('input a light') if light == 'red': print('GoGoGO') elif light == 'green': print('stop')
light = input('input a light') if light == 'red': print('GoGoGO') elif light == 'green': print('stop')
''' Resources/other/contact _______________________ Contact information for XL Discoverer. :copyright: (c) 2015 The Regents of the University of California. :license: GNU GPL, see licenses/GNU GPLv3.txt for more details. ''' __all__ = [ 'AUTHOR', 'AUTHOR_EMAIL', 'MAINTAINER', 'MAINTAINER_EMAIL' ] # EMAIL # ----- AUTHOR_EMAIL = 'ahuszagh@gmail.com' MAINTAINER_EMAIL = 'crosslinkdiscoverer@gmail.com' # PEOPLE # ------ AUTHOR = 'Alex Huszagh' MAINTAINER = 'Alex Huszagh'
""" Resources/other/contact _______________________ Contact information for XL Discoverer. :copyright: (c) 2015 The Regents of the University of California. :license: GNU GPL, see licenses/GNU GPLv3.txt for more details. """ __all__ = ['AUTHOR', 'AUTHOR_EMAIL', 'MAINTAINER', 'MAINTAINER_EMAIL'] author_email = 'ahuszagh@gmail.com' maintainer_email = 'crosslinkdiscoverer@gmail.com' author = 'Alex Huszagh' maintainer = 'Alex Huszagh'
# Binary Tree Level Order Traversal - Breadth First Search 1 # Given the root of a binary tree, return the level order traversal of its nodes' values. (i.e., from left to right, level by level). class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def levelTraverse(self, node, level): if (level == len(self.levels)): self.levels.append([]) self.levels[level].append(node.val) if (node.left): self.levelTraverse(node.left, level + 1) if (node.right): self.levelTraverse(node.right, level + 1) def levelOrder(self, root): if not root: return [] self.levels = [] self.levelTraverse(root, 0) return self.levels # Time Complexity: O(N) # Space Complexity: O(N)
class Treenode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def level_traverse(self, node, level): if level == len(self.levels): self.levels.append([]) self.levels[level].append(node.val) if node.left: self.levelTraverse(node.left, level + 1) if node.right: self.levelTraverse(node.right, level + 1) def level_order(self, root): if not root: return [] self.levels = [] self.levelTraverse(root, 0) return self.levels
# Seasons.py -- Hass helper python_script to turn a Climate entity into a smart # thermostat, with support for multiple thermostats each having their own # schedule. # # INPUTS: # * climate_unit (required): The Climate entity to be controlled # * global_mode (required): an entity whose state is the desired global climate # mode (usually an input_select) # * state_entity (required): an input_text entity, unique to this climate_unit, # where the script can store some information between runs. # * at_home_sensor (optional): an entity that represents whether anyone is home # (usually a binary_sensor) # * from_timer (optional): whether the script was triggered by timer. If true, # only changes that modify the last-set operation mode or setpoint take # effect. This is done so that manual changes are left alone until the next # schedule switch. # # The last input is the 'seasons' dictionary as defined below, which defines the # scheduled behavior for each global mode / climate unit combination. It's a # dictionary keyed by a tuple of global mode and climate unit. Each entry is a # list of schedules, where each schedule has the following fields: # * title: Used only for logging and to help you find the right entry for edits # * time_on / time_off (optional): Start and stop of this schedule, 24-hour # hours:minutes. If not given, this schedule is always active (though see # window and if_away/if_home below) # * days: (optional): String defining days of week this schedule is active, matched # on the schedule's start time. Seven characters, dash or dot if not active, any # other character if active. You can use 0123456 or MTWTFSS or whatever you like. # Monday is first, following Python datetime convention. # * operation (required): The operating mode for this schedule, one of the modes # supported by your climate entity. # * setpoint (optional): The desired temperature for this schedule. Some modes # (e.g. 'dry' dehumidifaction) don't require a setpoint so it's optional # * window (optional): If given, if this entity's state is 'on' (i.e. the given # window is open), the schedule will act as if its operation mode is 'off'. # This is so you don't attempt to heat/cool the great outdoors if you left the # window open for some fresh air. # * if_away / if_home (optional): If present, this schedule will only apply if # the at_home_sensor state matches (true meaning someone is home). If no # at_home_sensor is given, these are both always false. # * humidity_sensor (optional): See if_humid. Note: could also be some other # type of sensor, like dewpoint. # * if_humid (optional): Percentage. If present, this schedule will only apply # if the humidity reported by the humidity_sensor is above this value at the # beginning of the period. # # Put this script in <config>/python_scripts (create the directory if needed) # and activate it as described at # https://www.home-assistant.io/components/python_script/ . # You should set up automations to call service python_script.seasons for each # relevant climate unit for the each of the following events: # * your global_mode entity changes (all climate units) # * your at_home_sensor changes (all climate units) # * your window sensor(s) change(s) (relevant climate units) # * on a time_interval, suggested every 15 minutes. (all climate units). This # interval is the resolution of your scheduled changes, so make it more or # less frequent as required. SEASONS = { ('Cold Winter', 'climate.first_floor_heat'): [ { 'title': 'Ecobee schedule', 'operation': 'heat' } ], ('Cold Winter', 'climate.second_floor'): [ { 'title': 'Ecobee schedule', 'operation': 'heat' } ], ('Cold Winter', 'climate.loft_heat'): [ { 'title': 'Ecobee schedule', 'operation': 'heat' } ], ('Winter', 'climate.first_floor_heat'): [ { 'title': 'Ecobee schedule', 'operation': 'heat' } ], ('Winter', 'climate.second_floor'): [ { 'title': 'Ecobee schedule', 'operation': 'heat' } ], ('Winter', 'climate.master_br'): [ { 'title': 'Winter Sleeping', 'time_on': '21:29', 'time_off': '07:59', 'operation': 'heat', 'setpoint': 64 } ], ('Winter', 'climate.loft_heat'): [ { 'title': 'Ecobee schedule', 'operation': 'heat' } ], ('Cold Shoulder', 'climate.first_floor_heat'): [ { 'title': 'Ecobee schedule', 'operation': 'heat' } ], ('Cold Shoulder', 'climate.master_br'): [ { 'title': 'Morning (weekday)', 'days': 'MTWTF..', 'time_on': '05:44', 'time_off': '07:59', 'operation': 'heat', 'window': 'binary_sensor.bedroom_window', 'setpoint': 67 }, { 'title': 'Morning (weekend)', 'days': '.....SS', 'time_on': '07:29', 'time_off': '08:59', 'operation': 'heat', 'window': 'binary_sensor.bedroom_window', 'setpoint': 68 }, { 'title': 'Sleeping', 'time_on': '21:59', 'time_off': '08:59', 'operation': 'heat', 'window': 'binary_sensor.bedroom_window', 'setpoint': 64 }, { 'title': 'Day (Away)', 'time_on': '07:59', 'time_off': '16:29', 'if_away': True, 'operation': 'heat', 'window': 'binary_sensor.bedroom_window', 'setpoint': 62 }, { 'title': 'Day (Home)', 'time_on': '07:59', 'time_off': '17:59', 'operation': 'heat', 'window': 'binary_sensor.bedroom_window', 'setpoint': 68 }, { 'title': 'Evening (Away)', 'time_on': '17:59', 'time_off': '21:44', 'operation': 'heat', 'window': 'binary_sensor.bedroom_window', 'if_away': True, 'setpoint': 62 }, { 'title': 'Evening (Home)', 'time_on': '15:59', 'time_off': '21:44', 'operation': 'heat', 'window': 'binary_sensor.bedroom_window', 'setpoint': 68 } ], ('Cold Shoulder', 'climate.loft_heat'): [ { 'title': 'Morning Boost', 'operation': 'heat', 'time_on': '06:59', 'time_off': '07:44', 'window': 'binary_sensor.skylight', 'setpoint': 68 } ], ('Cold Shoulder', 'climate.loft'): [ { 'title': 'Night', 'operation': 'heat', 'time_on': '00:04', 'time_off': '07:14', 'window': 'binary_sensor.skylight', 'setpoint': 61 }, { 'title': 'Day (Weekday)', 'days': 'MTWTF..', 'operation': 'heat', 'time_on': '07:14', 'time_off': '16:59', 'window': 'binary_sensor.skylight', 'setpoint': 68 }, { 'title': 'Day (Weekend)', 'days': '.....SS', 'operation': 'heat', 'time_on': '08:59', 'time_off': '16:59', 'window': 'binary_sensor.skylight', 'setpoint': 62 }, { 'title': 'Evening', 'operation': 'heat', 'time_on': '16:59', 'time_off': '00:04', 'window': 'binary_sensor.skylight', 'setpoint': 63 } ], ('Warm Shoulder', 'climate.first_floor'): [ { 'title': 'Morning (weekday)', 'days': 'MTWTF..', 'time_on': '05:44', 'time_off': '07:59', 'operation': 'heat', 'setpoint': 68 }, { 'title': 'Morning (weekend)', 'days': '.....SS', 'time_on': '07:29', 'time_off': '08:59', 'operation': 'heat', 'setpoint': 68 }, { 'title': 'Pre-Sleeping', 'time_on': '21:44', 'time_off': '21:59', 'operation': 'heat', 'setpoint': 62 }, { 'title': 'Sleeping', 'time_on': '21:59', 'time_off': '08:59', 'operation': 'heat', 'setpoint': 62 }, { 'title': 'Day (Away)', 'time_on': '08:59', 'time_off': '16:29', 'if_away': True, 'operation': 'heat', 'setpoint': 62 }, { 'title': 'Day (Home)', 'time_on': '08:59', 'time_off': '17:59', 'operation': 'heat', 'setpoint': 68 }, { 'title': 'Evening (Away)', 'time_on': '17:59', 'time_off': '21:44', 'operation': 'heat', 'if_away': True, 'setpoint': 62 }, { 'title': 'Evening (Home)', 'time_on': '15:59', 'time_off': '21:44', 'operation': 'heat', 'setpoint': 69 } ], ('Warm Shoulder', 'climate.master_br'): [ { 'title': 'Morning (weekday)', 'days': 'MTWTF..', 'time_on': '05:44', 'time_off': '07:59', 'operation': 'heat', 'setpoint': 67 }, { 'title': 'Morning (weekend)', 'days': '.....SS', 'time_on': '07:29', 'time_off': '08:59', 'operation': 'heat', 'setpoint': 68 }, { 'title': 'Pre-Sleeping', 'time_on': '21:44', 'time_off': '21:59', 'operation': 'heat', 'setpoint': 64 }, { 'title': 'Sleeping', 'time_on': '21:59', 'time_off': '08:59', 'operation': 'heat', 'setpoint': 64 }, { 'title': 'Day (Away)', 'time_on': '08:59', 'time_off': '16:29', 'if_away': True, 'operation': 'heat', 'setpoint': 62 }, { 'title': 'Day (Home)', 'time_on': '08:59', 'time_off': '17:59', 'operation': 'heat', 'setpoint': 68 }, { 'title': 'Evening (Away)', 'time_on': '17:59', 'time_off': '21:44', 'operation': 'heat', 'if_away': True, 'setpoint': 62 }, { 'title': 'Evening (Home)', 'time_on': '15:59', 'time_off': '21:44', 'operation': 'heat', 'setpoint': 68 } ], ('Warm Shoulder', 'climate.loft'): [ { 'title': 'Night', 'operation': 'heat', 'time_on': '00:04', 'time_off': '07:29', 'window': 'binary_sensor.skylight', 'setpoint': 61 }, { 'title': 'Day (Weekday)', 'days': 'MTWTF..', 'operation': 'heat', 'time_on': '07:29', 'time_off': '17:59', 'window': 'binary_sensor.skylight', 'setpoint': 68 }, { 'title': 'Day (Weekend)', 'days': '.....SS', 'operation': 'heat', 'time_on': '08:59', 'time_off': '17:59', 'window': 'binary_sensor.skylight', 'setpoint': 62 }, { 'title': 'Evening', 'operation': 'heat', 'time_on': '17:59', 'time_off': '00:04', 'window': 'binary_sensor.skylight', 'setpoint': 63 } ], ('Normal Summer', 'climate.master_br'): [ { 'title': 'Dehumidify', 'time_on': '19:59', 'time_off': '20:59', 'operation': 'dry', 'humidity_sensor': 'sensor.dewpoint_mbr', 'if_humid': 63, 'window': 'binary_sensor.bedroom_window', }, { 'title': 'Sleeping-early', 'time_on': '20:59', 'time_off': '02:59', 'operation': 'cool', 'window': 'binary_sensor.bedroom_window', 'setpoint': 73 }, { 'title': 'Sleeping-late', 'time_on': '02:59', 'time_off': '07:59', 'operation': 'cool', 'window': 'binary_sensor.bedroom_window', 'setpoint': 74 }, ], ('Hot Summer', 'climate.master_br'): [ { 'title': 'Dehumidify', 'time_on': '19:59', 'time_off': '20:59', 'operation': 'dry', 'humidity_sensor': 'sensor.dewpoint_mbr', 'if_humid': 63, 'window': 'binary_sensor.bedroom_window', }, { 'title': 'Sleeping-early', 'time_on': '20:59', 'time_off': '02:59', 'operation': 'cool', 'window': 'binary_sensor.bedroom_window', 'setpoint': 73 }, { 'title': 'Sleeping-late', 'time_on': '02:59', 'time_off': '07:59', 'operation': 'cool', 'window': 'binary_sensor.bedroom_window', 'setpoint': 74 }, { 'title': 'Day (Away)', 'time_on': '08:29', 'time_off': '19:44', 'operation': 'cool', 'window': 'binary_sensor.bedroom_window', 'if_away': True, 'setpoint': 78 }, { 'title': 'Day (Home)', 'time_on': '08:29', 'time_off': '19:44', 'operation': 'cool', 'window': 'binary_sensor.bedroom_window', 'setpoint': 76 }, ], ('Hot Summer', 'climate.loft'): [ { 'title': 'Night', 'operation': 'cool', 'time_on': '00:04', 'time_off': '08:59', 'window': 'binary_sensor.skylight', 'setpoint': 83 }, { 'title': 'Day (away)', 'operation': 'cool', 'time_on': '08:59', 'time_off': '17:59', 'if_away': True, 'window': 'binary_sensor.skylight', 'setpoint': 85 }, { 'title': 'Day', 'operation': 'cool', 'time_on': '08:59', 'time_off': '17:59', 'window': 'binary_sensor.skylight', 'setpoint': 80 }, { 'title': 'Evening', 'operation': 'cool', 'time_on': '17:59', 'time_off': '00:04', 'window': 'binary_sensor.skylight', 'setpoint': 81 } ], ('Hot Summer', 'climate.first_floor'): [ { 'title': 'Sleeping', 'time_on': '21:59', 'time_off': '05:59', 'window': 'binary_sensor.first_floor_windows', 'operation': 'cool', 'setpoint': 78 }, { 'title': 'Day (Away)', 'time_on': '07:59', 'time_off': '15:59', 'operation': 'cool', 'window': 'binary_sensor.first_floor_windows', 'if_away': True, 'setpoint': 78 }, { 'title': 'Day (Home)', 'time_on': '05:59', 'time_off': '15:59', 'window': 'binary_sensor.first_floor_windows', 'operation': 'cool', 'setpoint': 75 }, { 'title': 'Evening (Away)', 'time_on': '17:59', 'time_off': '21:44', 'operation': 'cool', 'window': 'binary_sensor.first_floor_windows', 'if_away': True, 'setpoint': 78 }, { 'title': 'Evening (Home)', 'time_on': '15:59', 'time_off': '21:44', 'window': 'binary_sensor.first_floor_windows', 'operation': 'cool', 'setpoint': 75 } ] } def is_time_between(begin_time, end_time, check_time): if begin_time < end_time: return begin_time <= check_time <= end_time # crosses midnight return check_time >= begin_time or check_time <= end_time def time_offset(orig_time, offset): hour = orig_time.hour minute = orig_time.minute minute = minute + offset if minute < 0: hour = hour - 1 minute = minute + 60 if minute > 60: hour = hour + 1 minute = minute - 60 if hour < 0: hour = hour + 24 if hour > 24: hour = hour - 24 return datetime.time(hour=hour, minute=minute) def day_of_start(start_time, end_time, check_time): today = datetime.datetime.now().weekday() # today if doesn't cross midnight or no actual times given if (not start_time) or (not end_time) or start_time <= end_time: return today # today if we're between start and midnight if start_time <= check_time: return today # Otherwise, yesterday return 6 if today == 0 else today - 1 saved_state = hass.states.get(data.get('state_entity')).state climate_unit = data.get('climate_unit', 'climate.master_br') current_mode = hass.states.get(data.get('global_mode')).state from_timer = data.get('from_timer', False) at_home_sensor = data.get('at_home_sensor') is_home = False is_away = False if at_home_sensor: is_home = hass.states.get(at_home_sensor).state == 'on' is_away = not is_home now = datetime.datetime.now().time() key = (current_mode, climate_unit) schedules = SEASONS.get(key) matched = False setpoint = None turn_on = False turn_off = False desired_operation = None title = None next_state = None if not schedules: logger.info("No schedules for {}".format(key)) else: for schedule in schedules: time_on_str = schedule.get('time_on') time_off_str = schedule.get('time_off') time_on = None time_off = None if time_on_str: time_on = datetime.datetime.strptime(time_on_str, '%H:%M').time() if time_off_str: time_off = datetime.datetime.strptime(time_off_str, '%H:%M').time() start_day = day_of_start(time_on, time_off, now) day_match = True days = schedule.get('days') if days and len(days) == 7: day_match = days[start_day] != '-' and days[start_day] != '.' in_interval = day_match and (((not time_on) or (not time_off) or is_time_between(time_on, time_off, now))) home_away_match = True if schedule.get('if_home'): home_away_match = is_home if schedule.get('if_away'): home_away_match = not is_home dry_exclude = False hs = schedule.get('humidity_sensor') if hs and schedule.get('if_humid'): dry_exclude = float(hass.states.get(hs).state) < float(schedule['if_humid']) if in_interval and home_away_match and not dry_exclude: # When we get here, we have schedules for this unit and # global mode and we're in this schedule's interval. # We will obey this schedule and ignore subsequent matches if not time_on: time_on = datetime.datetime.strptime('00:00', '%H:%M').time() window_open = False if schedule.get('window'): window_open = hass.states.get(schedule['window']).state == 'on' else: window_open = False decided = False matched = True next_state = "%s-%s" % (str(schedule.get('operation')), str(schedule.get('setpoint'))) same_next_state = (next_state == saved_state) if window_open: # Off if window is open turn_off = True title = schedule.get('title') + ' (Window open)' decided = True if (not decided) and from_timer and (not same_next_state): desired_operation = schedule.get('operation') if desired_operation == 'off': turn_off = True else: turn_on = True setpoint = schedule.get('setpoint') title = schedule.get('title') decided = True if not decided and (not from_timer): desired_operation = schedule.get('operation') if desired_operation == 'off': turn_off = True else: turn_on = True setpoint = schedule.get('setpoint') title = schedule.get('title') decided = True break if not matched and current_mode != "Manual": # If no schedules matched, turn off except in Manual next_state = "off-None" same_next_state = (next_state == saved_state) if (not from_timer) or (not same_next_state): turn_off = True title = 'Default (Off)' if turn_off: desired_operation = 'off' if desired_operation: logger.info("Setting {} to mode {} target {} from schedule {}".format( climate_unit, desired_operation, setpoint, title)) service_data = { "entity_id": climate_unit, "hvac_mode": desired_operation } hass.services.call('climate', 'set_hvac_mode', service_data, False) if setpoint: time.sleep(2.0) if '.' in str(setpoint): setpoint_num = float(setpoint) else: setpoint_num = int(setpoint) service_data = { "entity_id": climate_unit, "temperature": setpoint_num, "hvac_mode": desired_operation } hass.services.call('climate', 'set_temperature', service_data, False) if next_state: hass.states.set(data.get('state_entity'), next_state)
seasons = {('Cold Winter', 'climate.first_floor_heat'): [{'title': 'Ecobee schedule', 'operation': 'heat'}], ('Cold Winter', 'climate.second_floor'): [{'title': 'Ecobee schedule', 'operation': 'heat'}], ('Cold Winter', 'climate.loft_heat'): [{'title': 'Ecobee schedule', 'operation': 'heat'}], ('Winter', 'climate.first_floor_heat'): [{'title': 'Ecobee schedule', 'operation': 'heat'}], ('Winter', 'climate.second_floor'): [{'title': 'Ecobee schedule', 'operation': 'heat'}], ('Winter', 'climate.master_br'): [{'title': 'Winter Sleeping', 'time_on': '21:29', 'time_off': '07:59', 'operation': 'heat', 'setpoint': 64}], ('Winter', 'climate.loft_heat'): [{'title': 'Ecobee schedule', 'operation': 'heat'}], ('Cold Shoulder', 'climate.first_floor_heat'): [{'title': 'Ecobee schedule', 'operation': 'heat'}], ('Cold Shoulder', 'climate.master_br'): [{'title': 'Morning (weekday)', 'days': 'MTWTF..', 'time_on': '05:44', 'time_off': '07:59', 'operation': 'heat', 'window': 'binary_sensor.bedroom_window', 'setpoint': 67}, {'title': 'Morning (weekend)', 'days': '.....SS', 'time_on': '07:29', 'time_off': '08:59', 'operation': 'heat', 'window': 'binary_sensor.bedroom_window', 'setpoint': 68}, {'title': 'Sleeping', 'time_on': '21:59', 'time_off': '08:59', 'operation': 'heat', 'window': 'binary_sensor.bedroom_window', 'setpoint': 64}, {'title': 'Day (Away)', 'time_on': '07:59', 'time_off': '16:29', 'if_away': True, 'operation': 'heat', 'window': 'binary_sensor.bedroom_window', 'setpoint': 62}, {'title': 'Day (Home)', 'time_on': '07:59', 'time_off': '17:59', 'operation': 'heat', 'window': 'binary_sensor.bedroom_window', 'setpoint': 68}, {'title': 'Evening (Away)', 'time_on': '17:59', 'time_off': '21:44', 'operation': 'heat', 'window': 'binary_sensor.bedroom_window', 'if_away': True, 'setpoint': 62}, {'title': 'Evening (Home)', 'time_on': '15:59', 'time_off': '21:44', 'operation': 'heat', 'window': 'binary_sensor.bedroom_window', 'setpoint': 68}], ('Cold Shoulder', 'climate.loft_heat'): [{'title': 'Morning Boost', 'operation': 'heat', 'time_on': '06:59', 'time_off': '07:44', 'window': 'binary_sensor.skylight', 'setpoint': 68}], ('Cold Shoulder', 'climate.loft'): [{'title': 'Night', 'operation': 'heat', 'time_on': '00:04', 'time_off': '07:14', 'window': 'binary_sensor.skylight', 'setpoint': 61}, {'title': 'Day (Weekday)', 'days': 'MTWTF..', 'operation': 'heat', 'time_on': '07:14', 'time_off': '16:59', 'window': 'binary_sensor.skylight', 'setpoint': 68}, {'title': 'Day (Weekend)', 'days': '.....SS', 'operation': 'heat', 'time_on': '08:59', 'time_off': '16:59', 'window': 'binary_sensor.skylight', 'setpoint': 62}, {'title': 'Evening', 'operation': 'heat', 'time_on': '16:59', 'time_off': '00:04', 'window': 'binary_sensor.skylight', 'setpoint': 63}], ('Warm Shoulder', 'climate.first_floor'): [{'title': 'Morning (weekday)', 'days': 'MTWTF..', 'time_on': '05:44', 'time_off': '07:59', 'operation': 'heat', 'setpoint': 68}, {'title': 'Morning (weekend)', 'days': '.....SS', 'time_on': '07:29', 'time_off': '08:59', 'operation': 'heat', 'setpoint': 68}, {'title': 'Pre-Sleeping', 'time_on': '21:44', 'time_off': '21:59', 'operation': 'heat', 'setpoint': 62}, {'title': 'Sleeping', 'time_on': '21:59', 'time_off': '08:59', 'operation': 'heat', 'setpoint': 62}, {'title': 'Day (Away)', 'time_on': '08:59', 'time_off': '16:29', 'if_away': True, 'operation': 'heat', 'setpoint': 62}, {'title': 'Day (Home)', 'time_on': '08:59', 'time_off': '17:59', 'operation': 'heat', 'setpoint': 68}, {'title': 'Evening (Away)', 'time_on': '17:59', 'time_off': '21:44', 'operation': 'heat', 'if_away': True, 'setpoint': 62}, {'title': 'Evening (Home)', 'time_on': '15:59', 'time_off': '21:44', 'operation': 'heat', 'setpoint': 69}], ('Warm Shoulder', 'climate.master_br'): [{'title': 'Morning (weekday)', 'days': 'MTWTF..', 'time_on': '05:44', 'time_off': '07:59', 'operation': 'heat', 'setpoint': 67}, {'title': 'Morning (weekend)', 'days': '.....SS', 'time_on': '07:29', 'time_off': '08:59', 'operation': 'heat', 'setpoint': 68}, {'title': 'Pre-Sleeping', 'time_on': '21:44', 'time_off': '21:59', 'operation': 'heat', 'setpoint': 64}, {'title': 'Sleeping', 'time_on': '21:59', 'time_off': '08:59', 'operation': 'heat', 'setpoint': 64}, {'title': 'Day (Away)', 'time_on': '08:59', 'time_off': '16:29', 'if_away': True, 'operation': 'heat', 'setpoint': 62}, {'title': 'Day (Home)', 'time_on': '08:59', 'time_off': '17:59', 'operation': 'heat', 'setpoint': 68}, {'title': 'Evening (Away)', 'time_on': '17:59', 'time_off': '21:44', 'operation': 'heat', 'if_away': True, 'setpoint': 62}, {'title': 'Evening (Home)', 'time_on': '15:59', 'time_off': '21:44', 'operation': 'heat', 'setpoint': 68}], ('Warm Shoulder', 'climate.loft'): [{'title': 'Night', 'operation': 'heat', 'time_on': '00:04', 'time_off': '07:29', 'window': 'binary_sensor.skylight', 'setpoint': 61}, {'title': 'Day (Weekday)', 'days': 'MTWTF..', 'operation': 'heat', 'time_on': '07:29', 'time_off': '17:59', 'window': 'binary_sensor.skylight', 'setpoint': 68}, {'title': 'Day (Weekend)', 'days': '.....SS', 'operation': 'heat', 'time_on': '08:59', 'time_off': '17:59', 'window': 'binary_sensor.skylight', 'setpoint': 62}, {'title': 'Evening', 'operation': 'heat', 'time_on': '17:59', 'time_off': '00:04', 'window': 'binary_sensor.skylight', 'setpoint': 63}], ('Normal Summer', 'climate.master_br'): [{'title': 'Dehumidify', 'time_on': '19:59', 'time_off': '20:59', 'operation': 'dry', 'humidity_sensor': 'sensor.dewpoint_mbr', 'if_humid': 63, 'window': 'binary_sensor.bedroom_window'}, {'title': 'Sleeping-early', 'time_on': '20:59', 'time_off': '02:59', 'operation': 'cool', 'window': 'binary_sensor.bedroom_window', 'setpoint': 73}, {'title': 'Sleeping-late', 'time_on': '02:59', 'time_off': '07:59', 'operation': 'cool', 'window': 'binary_sensor.bedroom_window', 'setpoint': 74}], ('Hot Summer', 'climate.master_br'): [{'title': 'Dehumidify', 'time_on': '19:59', 'time_off': '20:59', 'operation': 'dry', 'humidity_sensor': 'sensor.dewpoint_mbr', 'if_humid': 63, 'window': 'binary_sensor.bedroom_window'}, {'title': 'Sleeping-early', 'time_on': '20:59', 'time_off': '02:59', 'operation': 'cool', 'window': 'binary_sensor.bedroom_window', 'setpoint': 73}, {'title': 'Sleeping-late', 'time_on': '02:59', 'time_off': '07:59', 'operation': 'cool', 'window': 'binary_sensor.bedroom_window', 'setpoint': 74}, {'title': 'Day (Away)', 'time_on': '08:29', 'time_off': '19:44', 'operation': 'cool', 'window': 'binary_sensor.bedroom_window', 'if_away': True, 'setpoint': 78}, {'title': 'Day (Home)', 'time_on': '08:29', 'time_off': '19:44', 'operation': 'cool', 'window': 'binary_sensor.bedroom_window', 'setpoint': 76}], ('Hot Summer', 'climate.loft'): [{'title': 'Night', 'operation': 'cool', 'time_on': '00:04', 'time_off': '08:59', 'window': 'binary_sensor.skylight', 'setpoint': 83}, {'title': 'Day (away)', 'operation': 'cool', 'time_on': '08:59', 'time_off': '17:59', 'if_away': True, 'window': 'binary_sensor.skylight', 'setpoint': 85}, {'title': 'Day', 'operation': 'cool', 'time_on': '08:59', 'time_off': '17:59', 'window': 'binary_sensor.skylight', 'setpoint': 80}, {'title': 'Evening', 'operation': 'cool', 'time_on': '17:59', 'time_off': '00:04', 'window': 'binary_sensor.skylight', 'setpoint': 81}], ('Hot Summer', 'climate.first_floor'): [{'title': 'Sleeping', 'time_on': '21:59', 'time_off': '05:59', 'window': 'binary_sensor.first_floor_windows', 'operation': 'cool', 'setpoint': 78}, {'title': 'Day (Away)', 'time_on': '07:59', 'time_off': '15:59', 'operation': 'cool', 'window': 'binary_sensor.first_floor_windows', 'if_away': True, 'setpoint': 78}, {'title': 'Day (Home)', 'time_on': '05:59', 'time_off': '15:59', 'window': 'binary_sensor.first_floor_windows', 'operation': 'cool', 'setpoint': 75}, {'title': 'Evening (Away)', 'time_on': '17:59', 'time_off': '21:44', 'operation': 'cool', 'window': 'binary_sensor.first_floor_windows', 'if_away': True, 'setpoint': 78}, {'title': 'Evening (Home)', 'time_on': '15:59', 'time_off': '21:44', 'window': 'binary_sensor.first_floor_windows', 'operation': 'cool', 'setpoint': 75}]} def is_time_between(begin_time, end_time, check_time): if begin_time < end_time: return begin_time <= check_time <= end_time return check_time >= begin_time or check_time <= end_time def time_offset(orig_time, offset): hour = orig_time.hour minute = orig_time.minute minute = minute + offset if minute < 0: hour = hour - 1 minute = minute + 60 if minute > 60: hour = hour + 1 minute = minute - 60 if hour < 0: hour = hour + 24 if hour > 24: hour = hour - 24 return datetime.time(hour=hour, minute=minute) def day_of_start(start_time, end_time, check_time): today = datetime.datetime.now().weekday() if not start_time or not end_time or start_time <= end_time: return today if start_time <= check_time: return today return 6 if today == 0 else today - 1 saved_state = hass.states.get(data.get('state_entity')).state climate_unit = data.get('climate_unit', 'climate.master_br') current_mode = hass.states.get(data.get('global_mode')).state from_timer = data.get('from_timer', False) at_home_sensor = data.get('at_home_sensor') is_home = False is_away = False if at_home_sensor: is_home = hass.states.get(at_home_sensor).state == 'on' is_away = not is_home now = datetime.datetime.now().time() key = (current_mode, climate_unit) schedules = SEASONS.get(key) matched = False setpoint = None turn_on = False turn_off = False desired_operation = None title = None next_state = None if not schedules: logger.info('No schedules for {}'.format(key)) else: for schedule in schedules: time_on_str = schedule.get('time_on') time_off_str = schedule.get('time_off') time_on = None time_off = None if time_on_str: time_on = datetime.datetime.strptime(time_on_str, '%H:%M').time() if time_off_str: time_off = datetime.datetime.strptime(time_off_str, '%H:%M').time() start_day = day_of_start(time_on, time_off, now) day_match = True days = schedule.get('days') if days and len(days) == 7: day_match = days[start_day] != '-' and days[start_day] != '.' in_interval = day_match and (not time_on or not time_off or is_time_between(time_on, time_off, now)) home_away_match = True if schedule.get('if_home'): home_away_match = is_home if schedule.get('if_away'): home_away_match = not is_home dry_exclude = False hs = schedule.get('humidity_sensor') if hs and schedule.get('if_humid'): dry_exclude = float(hass.states.get(hs).state) < float(schedule['if_humid']) if in_interval and home_away_match and (not dry_exclude): if not time_on: time_on = datetime.datetime.strptime('00:00', '%H:%M').time() window_open = False if schedule.get('window'): window_open = hass.states.get(schedule['window']).state == 'on' else: window_open = False decided = False matched = True next_state = '%s-%s' % (str(schedule.get('operation')), str(schedule.get('setpoint'))) same_next_state = next_state == saved_state if window_open: turn_off = True title = schedule.get('title') + ' (Window open)' decided = True if not decided and from_timer and (not same_next_state): desired_operation = schedule.get('operation') if desired_operation == 'off': turn_off = True else: turn_on = True setpoint = schedule.get('setpoint') title = schedule.get('title') decided = True if not decided and (not from_timer): desired_operation = schedule.get('operation') if desired_operation == 'off': turn_off = True else: turn_on = True setpoint = schedule.get('setpoint') title = schedule.get('title') decided = True break if not matched and current_mode != 'Manual': next_state = 'off-None' same_next_state = next_state == saved_state if not from_timer or not same_next_state: turn_off = True title = 'Default (Off)' if turn_off: desired_operation = 'off' if desired_operation: logger.info('Setting {} to mode {} target {} from schedule {}'.format(climate_unit, desired_operation, setpoint, title)) service_data = {'entity_id': climate_unit, 'hvac_mode': desired_operation} hass.services.call('climate', 'set_hvac_mode', service_data, False) if setpoint: time.sleep(2.0) if '.' in str(setpoint): setpoint_num = float(setpoint) else: setpoint_num = int(setpoint) service_data = {'entity_id': climate_unit, 'temperature': setpoint_num, 'hvac_mode': desired_operation} hass.services.call('climate', 'set_temperature', service_data, False) if next_state: hass.states.set(data.get('state_entity'), next_state)
# -------------- # Code starts here class_1=['Geoffrey Hinton','Andrew Ng','Sebastian Raschka','Yoshua Bengio'] class_2=['Hilary Mason','Carla Gentry','Corinna Cortes'] new_class= class_1 + class_2 print(new_class) new_class.append('Peter Warden') print(new_class) new_class.remove('Carla Gentry') print(new_class) # Code ends here # -------------- # Code starts here courses= {'Math':65,'English':70,'History':80,'French':70,'Science':60} total= 65+70+80+70+60 print(total) percentage= ((total)/500)*100 print(percentage) # Code ends here # -------------- # Code starts here mathematics={'Geoffrey Hinton':78,'Andrew Ng':95,'Sebastian Raschka':65,'Yoshua Benjio':50, 'Hilary Mason':70,'Corinna Cortes':66,'Peter Warden':75} topper= max(mathematics,key=mathematics.get) print(topper) # Code ends here # -------------- # Given string topper = 'andrew ng' # Code starts here first_name=(topper.split( )[0]) print(first_name) last_name=(topper.split( )[1]) print(last_name) #first_name=print(topper[0:6]) #last_name=print(topper[7:9]) full_name ='ng' +' '+ 'andrew' certificate_name=full_name.upper() print(certificate_name) #print(full_name) # Code ends here
class_1 = ['Geoffrey Hinton', 'Andrew Ng', 'Sebastian Raschka', 'Yoshua Bengio'] class_2 = ['Hilary Mason', 'Carla Gentry', 'Corinna Cortes'] new_class = class_1 + class_2 print(new_class) new_class.append('Peter Warden') print(new_class) new_class.remove('Carla Gentry') print(new_class) courses = {'Math': 65, 'English': 70, 'History': 80, 'French': 70, 'Science': 60} total = 65 + 70 + 80 + 70 + 60 print(total) percentage = total / 500 * 100 print(percentage) mathematics = {'Geoffrey Hinton': 78, 'Andrew Ng': 95, 'Sebastian Raschka': 65, 'Yoshua Benjio': 50, 'Hilary Mason': 70, 'Corinna Cortes': 66, 'Peter Warden': 75} topper = max(mathematics, key=mathematics.get) print(topper) topper = 'andrew ng' first_name = topper.split()[0] print(first_name) last_name = topper.split()[1] print(last_name) full_name = 'ng' + ' ' + 'andrew' certificate_name = full_name.upper() print(certificate_name)
def cria(linhas, colunas): return {'linhas': linhas, 'colunas': colunas, 'dados': {}} #[[0,3],[1,2]] def criaLst(matriz_lst): linhas = len(matriz_lst) #2 colunas = len(matriz_lst[0]) #2 dados = {} #{(0,1): 3, (1,0):1, (1,1):2} for i in range(linhas): for j in range(colunas): if matriz_lst[i][j] != 0: #Cast to int before dados[i,j] = matriz_lst[i][j] return {'linhas': linhas, 'colunas': colunas, 'dados': dados} def carrega(nome_arquivo): matriz_file = open(nome_arquivo, 'rt', encoding='utf8') linha_matriz = matriz_file.readline() matriz_lst = [] while linha_matriz != "": temp = '' linha_mat = [] for i in range(len(linha_matriz)): if linha_matriz[i] != ' ': temp += linha_matriz[i] elif len(temp) > 0: striped_temp = temp.strip() striped_temp = float(striped_temp) linha_mat.append(striped_temp) temp = '' if len(temp) > 0: striped_temp = temp.strip() striped_temp = float(striped_temp) linha_mat.append(striped_temp) matriz_lst.append(linha_mat) linha_matriz = matriz_file.readline() matriz_file.close() return criaLst(matriz_lst) def salva(tadMat, nome_arquivo): matriz_file = open(nome_arquivo, 'wt', encoding='utf8') linhas = tadMat['linhas'] colunas = tadMat['colunas'] linha_lst = [] for l in range(linhas): for c in range(colunas): linha_lst.append("{:.1f}".format(getElem(tadMat,l,c))) matriz_file.write(" ".join(linha_lst)+"\n") linha_lst.clear() matriz_file.close() return tadMat def destroi(): return None def getElem(tadMat, linha, coluna): chave = (linha,coluna) if linha < tadMat['linhas'] and coluna < tadMat['colunas']: if chave in tadMat['dados'].keys(): return tadMat['dados'][chave] else: return 0 else: return None def setElem(tadMat, linha, coluna, valor): chave = (linha,coluna) if linha < tadMat['linhas'] and coluna < tadMat['colunas']: if chave in tadMat['dados'].keys(): existente = tadMat['dados'][chave] else: existente = 0 if valor == 0 and existente == 0: return elif valor == 0 and existente != 0: del tadMat['dados'][linha, coluna] elif valor != 0 and existente == 0: tadMat['dados'][linha, coluna] = valor elif valor != 0 and existente != 0: tadMat['dados'][linha, coluna] = valor else: return None def subtracao(tadMatA, tadMatB): #User o getElem e o setElem vai facilitar linhasA = tadMatA['linhas'] colunasA = tadMatA['colunas'] if (linhasA == tadMatB['linhas']) and (colunasA == tadMatB['colunas']): tadMatC = cria(linhasA, colunasA) for l in range(linhasA): for c in range(colunasA): setElem(tadMatC,l,c,getElem(tadMatA,l,c) - getElem(tadMatB,l,c)) return tadMatC else: return None def soma(tadMatA, tadMatB): #User o getElem e o setElem vai facilitar linhasA = tadMatA['linhas'] colunasA = tadMatA['colunas'] if (linhasA == tadMatB['linhas']) and (colunasA == tadMatB['colunas']): tadMatC = cria(linhasA, colunasA) for l in range(linhasA): for c in range(colunasA): setElem(tadMatC,l,c,getElem(tadMatA,l,c) + getElem(tadMatB,l,c)) return tadMatC else: return None def vezesK(tadMat, k): linhas = tadMat['linhas'] colunas = tadMat['colunas'] for l in range(linhas): for c in range(colunas): setElem(tadMat,l,c,getElem(tadMat,l,c) * k) return tadMat def multi(tadMatA, tadMatB): colunasA = tadMatA['colunas'] linhasB = tadMatB['linhas'] if colunasA == linhasB: linhasA = tadMatA['linhas'] colunasB = tadMatB['colunas'] tadMatC_lst = [] for l in range(linhasA): tadMatC_lst.append([]) for c in range(colunasB): tadMatC_lst[l].append(0) for k in range(colunasA): tadMatC_lst[l][c] += getElem(tadMatA, l, k) * getElem(tadMatB, k, c) return criaLst(tadMatC_lst) else: return None def clona(tadMat): linhas = tadMat['linhas'] colunas = tadMat['colunas'] dados = tadMat['dados'] return {'linhas': linhas, 'colunas': colunas, 'dados': dados } def quantLinhas(tadMat): return tadMat['linhas'] def quantColunas(tadMat): return tadMat['colunas'] def diagP(tadMat): diagP_lst = [] linhas = tadMat['linhas'] colunas = tadMat['colunas'] if linhas == colunas: for l in range(linhas): for c in range(colunas): if l == c: diagP_lst.append(getElem(tadMat,l,c)) return diagP_lst else: return None def diagS(tadMat): diagS_lst = [] linhas = tadMat['linhas'] colunas = tadMat['colunas'] if linhas == colunas: for l in range(linhas): for c in range(colunas): if (colunas - 1) == (l + c): diagS_lst.append(getElem(tadMat,l,c)) return diagS_lst else: return None def transposta(tadMat): linhas = tadMat['linhas'] colunas = tadMat['colunas'] dados = tadMat['dados'] dados_t = {} for key in dados: dados_t[key[1],key[0]] = dados[key] tadMat['linhas'] = colunas tadMat['colunas'] = linhas tadMat['dados'] = dados_t
def cria(linhas, colunas): return {'linhas': linhas, 'colunas': colunas, 'dados': {}} def cria_lst(matriz_lst): linhas = len(matriz_lst) colunas = len(matriz_lst[0]) dados = {} for i in range(linhas): for j in range(colunas): if matriz_lst[i][j] != 0: dados[i, j] = matriz_lst[i][j] return {'linhas': linhas, 'colunas': colunas, 'dados': dados} def carrega(nome_arquivo): matriz_file = open(nome_arquivo, 'rt', encoding='utf8') linha_matriz = matriz_file.readline() matriz_lst = [] while linha_matriz != '': temp = '' linha_mat = [] for i in range(len(linha_matriz)): if linha_matriz[i] != ' ': temp += linha_matriz[i] elif len(temp) > 0: striped_temp = temp.strip() striped_temp = float(striped_temp) linha_mat.append(striped_temp) temp = '' if len(temp) > 0: striped_temp = temp.strip() striped_temp = float(striped_temp) linha_mat.append(striped_temp) matriz_lst.append(linha_mat) linha_matriz = matriz_file.readline() matriz_file.close() return cria_lst(matriz_lst) def salva(tadMat, nome_arquivo): matriz_file = open(nome_arquivo, 'wt', encoding='utf8') linhas = tadMat['linhas'] colunas = tadMat['colunas'] linha_lst = [] for l in range(linhas): for c in range(colunas): linha_lst.append('{:.1f}'.format(get_elem(tadMat, l, c))) matriz_file.write(' '.join(linha_lst) + '\n') linha_lst.clear() matriz_file.close() return tadMat def destroi(): return None def get_elem(tadMat, linha, coluna): chave = (linha, coluna) if linha < tadMat['linhas'] and coluna < tadMat['colunas']: if chave in tadMat['dados'].keys(): return tadMat['dados'][chave] else: return 0 else: return None def set_elem(tadMat, linha, coluna, valor): chave = (linha, coluna) if linha < tadMat['linhas'] and coluna < tadMat['colunas']: if chave in tadMat['dados'].keys(): existente = tadMat['dados'][chave] else: existente = 0 if valor == 0 and existente == 0: return elif valor == 0 and existente != 0: del tadMat['dados'][linha, coluna] elif valor != 0 and existente == 0: tadMat['dados'][linha, coluna] = valor elif valor != 0 and existente != 0: tadMat['dados'][linha, coluna] = valor else: return None def subtracao(tadMatA, tadMatB): linhas_a = tadMatA['linhas'] colunas_a = tadMatA['colunas'] if linhasA == tadMatB['linhas'] and colunasA == tadMatB['colunas']: tad_mat_c = cria(linhasA, colunasA) for l in range(linhasA): for c in range(colunasA): set_elem(tadMatC, l, c, get_elem(tadMatA, l, c) - get_elem(tadMatB, l, c)) return tadMatC else: return None def soma(tadMatA, tadMatB): linhas_a = tadMatA['linhas'] colunas_a = tadMatA['colunas'] if linhasA == tadMatB['linhas'] and colunasA == tadMatB['colunas']: tad_mat_c = cria(linhasA, colunasA) for l in range(linhasA): for c in range(colunasA): set_elem(tadMatC, l, c, get_elem(tadMatA, l, c) + get_elem(tadMatB, l, c)) return tadMatC else: return None def vezes_k(tadMat, k): linhas = tadMat['linhas'] colunas = tadMat['colunas'] for l in range(linhas): for c in range(colunas): set_elem(tadMat, l, c, get_elem(tadMat, l, c) * k) return tadMat def multi(tadMatA, tadMatB): colunas_a = tadMatA['colunas'] linhas_b = tadMatB['linhas'] if colunasA == linhasB: linhas_a = tadMatA['linhas'] colunas_b = tadMatB['colunas'] tad_mat_c_lst = [] for l in range(linhasA): tadMatC_lst.append([]) for c in range(colunasB): tadMatC_lst[l].append(0) for k in range(colunasA): tadMatC_lst[l][c] += get_elem(tadMatA, l, k) * get_elem(tadMatB, k, c) return cria_lst(tadMatC_lst) else: return None def clona(tadMat): linhas = tadMat['linhas'] colunas = tadMat['colunas'] dados = tadMat['dados'] return {'linhas': linhas, 'colunas': colunas, 'dados': dados} def quant_linhas(tadMat): return tadMat['linhas'] def quant_colunas(tadMat): return tadMat['colunas'] def diag_p(tadMat): diag_p_lst = [] linhas = tadMat['linhas'] colunas = tadMat['colunas'] if linhas == colunas: for l in range(linhas): for c in range(colunas): if l == c: diagP_lst.append(get_elem(tadMat, l, c)) return diagP_lst else: return None def diag_s(tadMat): diag_s_lst = [] linhas = tadMat['linhas'] colunas = tadMat['colunas'] if linhas == colunas: for l in range(linhas): for c in range(colunas): if colunas - 1 == l + c: diagS_lst.append(get_elem(tadMat, l, c)) return diagS_lst else: return None def transposta(tadMat): linhas = tadMat['linhas'] colunas = tadMat['colunas'] dados = tadMat['dados'] dados_t = {} for key in dados: dados_t[key[1], key[0]] = dados[key] tadMat['linhas'] = colunas tadMat['colunas'] = linhas tadMat['dados'] = dados_t
# -*- coding: utf-8 -*- def main(): n, l = list(map(int, input().split())) s = input() tab_count = 1 crash_count = 0 for si in s: if si == '+': tab_count += 1 else: tab_count -= 1 if tab_count > l: crash_count += 1 tab_count = 1 print(crash_count) if __name__ == '__main__': main()
def main(): (n, l) = list(map(int, input().split())) s = input() tab_count = 1 crash_count = 0 for si in s: if si == '+': tab_count += 1 else: tab_count -= 1 if tab_count > l: crash_count += 1 tab_count = 1 print(crash_count) if __name__ == '__main__': main()
#Autor Manuela Garcia Monsalve # 28 septiembre 2018 #Esta es la super clase Vehiculo donde se encuentran los atributos de marca, modelo y color que seran #heredados para las subclases class Vehiculo(): def __init__(self,marca,color, modelo): #Se generan los atributos para poder ser heredados self.marca = marca self.color = color self.modelo = modelo def Prender(self): #Metodo prender vehiculo pass def Arrancar(self):#Metodo arrancar vehiculo pass def Apagar(self):#Metodo apagar vehiculo pass
class Vehiculo: def __init__(self, marca, color, modelo): self.marca = marca self.color = color self.modelo = modelo def prender(self): pass def arrancar(self): pass def apagar(self): pass
def cookie(x): if isinstance(x, str): cookie_eater = "Zach" elif isinstance(x, int) or isinstance(x, float): cookie_eater = "Monica" else: cookie_eater = "the dog" if x == True or x == False: cookie_eater = "the dog" return "Who ate the last cookie? It was %s!" % cookie_eater print(cookie("Ryan")) print(cookie(2.3)) print(cookie(True)) print(isinstance(True, float)) ## More common use: x = 200 print(type(x) == int)
def cookie(x): if isinstance(x, str): cookie_eater = 'Zach' elif isinstance(x, int) or isinstance(x, float): cookie_eater = 'Monica' else: cookie_eater = 'the dog' if x == True or x == False: cookie_eater = 'the dog' return 'Who ate the last cookie? It was %s!' % cookie_eater print(cookie('Ryan')) print(cookie(2.3)) print(cookie(True)) print(isinstance(True, float)) x = 200 print(type(x) == int)
result = '' for line in DATA: result += line + '\n'
result = '' for line in DATA: result += line + '\n'
class Solution: def maximalRectangle(self, matrix: List[List[str]]) -> int: dp = [[0] * len(matrix[0]) for i in range(len(matrix))] for row_i, row in enumerate(matrix): for col_i, col in enumerate(row): if col == "0": dp[row_i][col_i] = 0 else: dp[row_i][col_i] = self.find(col_i, row) mx = 0 print(dp) for i in range(len(dp)): for j in range(len(dp[i])): mx = max(mx, self.search(dp, i, j)) return mx def search(self, dp, start_row, start_col): start, up, down = dp[start_row][start_col], 0, 0 if start_row > 0: for i in range(start_row - 1, -1, -1): if start <= dp[i][start_col]: up += 1 else: break if start_row < len(dp) - 1: for i in range(start_row + 1, len(dp)): if start <= dp[i][start_col]: down += 1 else: break return start * (up + down + 1) def find(self, index, row): count = 0 for i in range(index, len(row)): if row[i] == "0": break count += 1 return count
class Solution: def maximal_rectangle(self, matrix: List[List[str]]) -> int: dp = [[0] * len(matrix[0]) for i in range(len(matrix))] for (row_i, row) in enumerate(matrix): for (col_i, col) in enumerate(row): if col == '0': dp[row_i][col_i] = 0 else: dp[row_i][col_i] = self.find(col_i, row) mx = 0 print(dp) for i in range(len(dp)): for j in range(len(dp[i])): mx = max(mx, self.search(dp, i, j)) return mx def search(self, dp, start_row, start_col): (start, up, down) = (dp[start_row][start_col], 0, 0) if start_row > 0: for i in range(start_row - 1, -1, -1): if start <= dp[i][start_col]: up += 1 else: break if start_row < len(dp) - 1: for i in range(start_row + 1, len(dp)): if start <= dp[i][start_col]: down += 1 else: break return start * (up + down + 1) def find(self, index, row): count = 0 for i in range(index, len(row)): if row[i] == '0': break count += 1 return count
# variables 4 a = "abc" b = 1 c = 1.5 d = True e = 3 + 5j print("a:", type(a), "b", type(b), "c:", type(c), "d:", type(d), "e:", type(e))
a = 'abc' b = 1 c = 1.5 d = True e = 3 + 5j print('a:', type(a), 'b', type(b), 'c:', type(c), 'd:', type(d), 'e:', type(e))
# Copyright (c) 2019-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # def f_gold(x1, y1, x2, y2, r1, r2): distSq = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2) radSumSq = (r1 + r2) * (r1 + r2) if (distSq == radSumSq): return 1 elif (distSq > radSumSq): return - 1 else: return 0 #TOFILL if __name__ == '__main__': param = [ (11, 36, 62, 64, 50, 4,), (87, 1, 62, 64, 54, 41,), (51, 1, 47, 90, 14, 71,), (89, 67, 9, 52, 94, 21,), (64, 10, 79, 45, 67, 78,), (57, 86, 99, 43, 83, 63,), (65, 90, 42, 82, 77, 32,), (32, 23, 28, 26, 60, 45,), (73, 61, 63, 77, 92, 76,), (3, 99, 6, 19, 21, 28,) ] n_success = 0 for i, parameters_set in enumerate(param): if f_filled(*parameters_set) == f_gold(*parameters_set): n_success += 1 print("#Results: %i, %i" % (n_success, len(param)))
def f_gold(x1, y1, x2, y2, r1, r2): dist_sq = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2) rad_sum_sq = (r1 + r2) * (r1 + r2) if distSq == radSumSq: return 1 elif distSq > radSumSq: return -1 else: return 0 if __name__ == '__main__': param = [(11, 36, 62, 64, 50, 4), (87, 1, 62, 64, 54, 41), (51, 1, 47, 90, 14, 71), (89, 67, 9, 52, 94, 21), (64, 10, 79, 45, 67, 78), (57, 86, 99, 43, 83, 63), (65, 90, 42, 82, 77, 32), (32, 23, 28, 26, 60, 45), (73, 61, 63, 77, 92, 76), (3, 99, 6, 19, 21, 28)] n_success = 0 for (i, parameters_set) in enumerate(param): if f_filled(*parameters_set) == f_gold(*parameters_set): n_success += 1 print('#Results: %i, %i' % (n_success, len(param)))
#!/usr/bin/env python # Task 1 instructions = list() with open("./dec_2/dec2_input.txt") as f: instructions = [x for x in f.read().split('\n')] start_position = [0, 0] for direction in instructions: info = direction.split(' ') vector, length = info[0], int(info[1]) if vector == "forward": start_position[0] += length elif vector == "up": start_position[1] -= length elif vector == "down": start_position[1] += length print(start_position[0] * start_position[1]) # Task 2 start_position = [0, 0, 0] for direction in instructions: info = direction.split(' ') vector, length = info[0], int(info[1]) if vector == "forward": start_position[0] += length start_position[1] += length * start_position[2] elif vector == "up": start_position[2] -= length elif vector == "down": start_position[2] += length print(info, start_position) print(start_position[0] * start_position[1])
instructions = list() with open('./dec_2/dec2_input.txt') as f: instructions = [x for x in f.read().split('\n')] start_position = [0, 0] for direction in instructions: info = direction.split(' ') (vector, length) = (info[0], int(info[1])) if vector == 'forward': start_position[0] += length elif vector == 'up': start_position[1] -= length elif vector == 'down': start_position[1] += length print(start_position[0] * start_position[1]) start_position = [0, 0, 0] for direction in instructions: info = direction.split(' ') (vector, length) = (info[0], int(info[1])) if vector == 'forward': start_position[0] += length start_position[1] += length * start_position[2] elif vector == 'up': start_position[2] -= length elif vector == 'down': start_position[2] += length print(info, start_position) print(start_position[0] * start_position[1])
a = input() s = [int(x) for x in input().split()] buff = 0 load = False for num in s: if num - buff < 0: load = True if num - buff >= 30: print(buff+30) break else: if load: buff += 5 load = False else: buff = num + 5 else: print(buff+30)
a = input() s = [int(x) for x in input().split()] buff = 0 load = False for num in s: if num - buff < 0: load = True if num - buff >= 30: print(buff + 30) break elif load: buff += 5 load = False else: buff = num + 5 else: print(buff + 30)
class OmnipyConfiguration(object): def __init__(self): self.mqtt_host = "" self.mqtt_port = 1883 self.mqtt_clientid = "" self.mqtt_command_topic = "" self.mqtt_response_topic = "" self.mqtt_rate_topic = ""
class Omnipyconfiguration(object): def __init__(self): self.mqtt_host = '' self.mqtt_port = 1883 self.mqtt_clientid = '' self.mqtt_command_topic = '' self.mqtt_response_topic = '' self.mqtt_rate_topic = ''
def solution(N): num = bin(N)[2:].split('1') if len(num[1:-1]) == 0: return 0 return len(max(num[1:-1], key=lambda x: len(x)))
def solution(N): num = bin(N)[2:].split('1') if len(num[1:-1]) == 0: return 0 return len(max(num[1:-1], key=lambda x: len(x)))
a = int(input()) b = int ( input ( ) ) a = int(input())
a = int(input()) b = int(input()) a = int(input())
word = 'Python' word[0] = 'M'
word = 'Python' word[0] = 'M'
#Operator Name Example # > Greater than x > y x = 5 y = 3 print(x > y) # true
x = 5 y = 3 print(x > y)
# Copyright (c) 2019-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. # def f_gold ( x , y , z ) : c = 0 while ( x and y and z ) : x = x - 1 y = y - 1 z = z - 1 c = c + 1 return c #TOFILL if __name__ == '__main__': param = [ (23,98,25,), (87,55,94,), (35,90,29,), (25,9,41,), (93,22,39,), (52,42,96,), (95,88,26,), (91,64,51,), (75,1,6,), (96,44,76,) ] n_success = 0 for i, parameters_set in enumerate(param): if f_filled(*parameters_set) == f_gold(*parameters_set): n_success+=1 print("#Results: %i, %i" % (n_success, len(param)))
def f_gold(x, y, z): c = 0 while x and y and z: x = x - 1 y = y - 1 z = z - 1 c = c + 1 return c if __name__ == '__main__': param = [(23, 98, 25), (87, 55, 94), (35, 90, 29), (25, 9, 41), (93, 22, 39), (52, 42, 96), (95, 88, 26), (91, 64, 51), (75, 1, 6), (96, 44, 76)] n_success = 0 for (i, parameters_set) in enumerate(param): if f_filled(*parameters_set) == f_gold(*parameters_set): n_success += 1 print('#Results: %i, %i' % (n_success, len(param)))
# Voting with delegation. # Information about voters voters: public({ # weight is accumulated by delegation weight: num, # if true, that person already voted voted: bool, # person delegated to delegate: address, # index of the voted proposal vote: num }[address]) # This is a type for a list of proposals. proposals: public({ # short name (up to 32 bytes) name: bytes32, # number of accumulated votes vote_count: num }[num]) voter_count: public(num) chairperson: public(address) # Setup global variables def __init__(_proposalNames: bytes32[5]): self.chairperson = msg.sender self.voter_count = 0 for i in range(5): self.proposals[i] = { name: _proposalNames[i], vote_count: 0 } # Give `voter` the right to vote on this ballot. # May only be called by `chairperson`. def give_right_to_vote(voter: address): # Throws if sender is not chairpers assert msg.sender == self.chairperson # Throws if voter has already voted assert not self.voters[voter].voted # Throws if voters voting weight isn't 0 assert self.voters[voter].weight == 0 self.voters[voter].weight = 1 self.voter_count += 1 # Delegate your vote to the voter `to`. def delegate(_to: address): to = _to # Throws if sender has already voted assert not self.voters[msg.sender].voted # Throws if sender tries to delegate their vote to themselves assert not msg.sender == to # loop can delegate votes up to the current voter count for i in range(self.voter_count, self.voter_count+1): if self.voters[to].delegate: # Because there are not while loops, use recursion to forward the delegation # self.delegate(self.voters[to].delegate) assert self.voters[to].delegate != msg.sender to = self.voters[to].delegate self.voters[msg.sender].voted = True self.voters[msg.sender].delegate = to if self.voters[to].voted: # If the delegate already voted, # directly add to the number of votes self.proposals[self.voters[to].vote].vote_count += self.voters[msg.sender].weight else: # If the delegate did not vote yet, # add to her weight. self.voters[to].weight += self.voters[msg.sender].weight # Give your vote (including votes delegated to you) # to proposal `proposals[proposal].name`. def vote(proposal: num): assert not self.voters[msg.sender].voted self.voters[msg.sender].voted = True self.voters[msg.sender].vote = proposal # If `proposal` is out of the range of the array, # this will throw automatically and revert all # changes. self.proposals[proposal].vote_count += self.voters[msg.sender].weight # Computes the winning proposal taking all # previous votes into account. @constant def winning_proposal() -> num: winning_vote_count = 0 for i in range(5): if self.proposals[i].vote_count > winning_vote_count: winning_vote_count = self.proposals[i].vote_count winning_proposal = i return winning_proposal # Calls winning_proposal() function to get the index # of the winner contained in the proposals array and then # returns the name of the winner @constant def winner_name() -> bytes32: return self.proposals[self.winning_proposal()].name
voters: public({weight: num, voted: bool, delegate: address, vote: num}[address]) proposals: public({name: bytes32, vote_count: num}[num]) voter_count: public(num) chairperson: public(address) def __init__(_proposalNames: bytes32[5]): self.chairperson = msg.sender self.voter_count = 0 for i in range(5): self.proposals[i] = {name: _proposalNames[i], vote_count: 0} def give_right_to_vote(voter: address): assert msg.sender == self.chairperson assert not self.voters[voter].voted assert self.voters[voter].weight == 0 self.voters[voter].weight = 1 self.voter_count += 1 def delegate(_to: address): to = _to assert not self.voters[msg.sender].voted assert not msg.sender == to for i in range(self.voter_count, self.voter_count + 1): if self.voters[to].delegate: assert self.voters[to].delegate != msg.sender to = self.voters[to].delegate self.voters[msg.sender].voted = True self.voters[msg.sender].delegate = to if self.voters[to].voted: self.proposals[self.voters[to].vote].vote_count += self.voters[msg.sender].weight else: self.voters[to].weight += self.voters[msg.sender].weight def vote(proposal: num): assert not self.voters[msg.sender].voted self.voters[msg.sender].voted = True self.voters[msg.sender].vote = proposal self.proposals[proposal].vote_count += self.voters[msg.sender].weight @constant def winning_proposal() -> num: winning_vote_count = 0 for i in range(5): if self.proposals[i].vote_count > winning_vote_count: winning_vote_count = self.proposals[i].vote_count winning_proposal = i return winning_proposal @constant def winner_name() -> bytes32: return self.proposals[self.winning_proposal()].name
load( "@com_googlesource_gerrit_bazlets//tools:junit.bzl", "junit_tests", ) def tests(tests): for src in tests: name = src[len("tst/"):len(src) - len(".java")].replace("/", "_") labels = [] timeout = "moderate" if name.startswith("org_eclipse_jgit_"): package = name[len("org.eclipse.jgit_"):] if package.startswith("internal_storage_"): package = package[len("internal.storage_"):] index = package.find("_") if index > 0: labels.append(package[:index]) else: labels.append(index) if "lib" not in labels: labels.append("lib") # TODO(http://eclip.se/534285): Make this test pass reliably # and remove the flaky attribute. flaky = src.endswith("CrissCrossMergeTest.java") additional_deps = [] if src.endswith("RootLocaleTest.java"): additional_deps = [ "//org.eclipse.jgit.pgm:pgm", "//org.eclipse.jgit.ui:ui", ] if src.endswith("WalkEncryptionTest.java"): additional_deps = [ "//org.eclipse.jgit:insecure_cipher_factory", ] if src.endswith("OpenSshConfigTest.java"): additional_deps = [ "//lib:jsch", ] if src.endswith("JschConfigSessionFactoryTest.java"): additional_deps = [ "//lib:jsch", ] if src.endswith("ArchiveCommandTest.java"): additional_deps = [ "//lib:commons-compress", "//lib:xz", "//org.eclipse.jgit.archive:jgit-archive", ] heap_size = "-Xmx256m" if src.endswith("HugeCommitMessageTest.java"): heap_size = "-Xmx512m" if src.endswith("EolRepositoryTest.java") or src.endswith("GcCommitSelectionTest.java"): timeout = "long" junit_tests( name = name, tags = labels, srcs = [src], deps = additional_deps + [ ":helpers", ":tst_rsrc", "//lib:javaewah", "//lib:junit", "//lib:slf4j-api", "//org.eclipse.jgit:jgit", "//org.eclipse.jgit.junit:junit", "//org.eclipse.jgit.lfs:jgit-lfs", ], flaky = flaky, jvm_flags = [heap_size, "-Dfile.encoding=UTF-8"], timeout = timeout, )
load('@com_googlesource_gerrit_bazlets//tools:junit.bzl', 'junit_tests') def tests(tests): for src in tests: name = src[len('tst/'):len(src) - len('.java')].replace('/', '_') labels = [] timeout = 'moderate' if name.startswith('org_eclipse_jgit_'): package = name[len('org.eclipse.jgit_'):] if package.startswith('internal_storage_'): package = package[len('internal.storage_'):] index = package.find('_') if index > 0: labels.append(package[:index]) else: labels.append(index) if 'lib' not in labels: labels.append('lib') flaky = src.endswith('CrissCrossMergeTest.java') additional_deps = [] if src.endswith('RootLocaleTest.java'): additional_deps = ['//org.eclipse.jgit.pgm:pgm', '//org.eclipse.jgit.ui:ui'] if src.endswith('WalkEncryptionTest.java'): additional_deps = ['//org.eclipse.jgit:insecure_cipher_factory'] if src.endswith('OpenSshConfigTest.java'): additional_deps = ['//lib:jsch'] if src.endswith('JschConfigSessionFactoryTest.java'): additional_deps = ['//lib:jsch'] if src.endswith('ArchiveCommandTest.java'): additional_deps = ['//lib:commons-compress', '//lib:xz', '//org.eclipse.jgit.archive:jgit-archive'] heap_size = '-Xmx256m' if src.endswith('HugeCommitMessageTest.java'): heap_size = '-Xmx512m' if src.endswith('EolRepositoryTest.java') or src.endswith('GcCommitSelectionTest.java'): timeout = 'long' junit_tests(name=name, tags=labels, srcs=[src], deps=additional_deps + [':helpers', ':tst_rsrc', '//lib:javaewah', '//lib:junit', '//lib:slf4j-api', '//org.eclipse.jgit:jgit', '//org.eclipse.jgit.junit:junit', '//org.eclipse.jgit.lfs:jgit-lfs'], flaky=flaky, jvm_flags=[heap_size, '-Dfile.encoding=UTF-8'], timeout=timeout)
#Exam def solution(N): if (N > 0) and (N < 1000): #Assume that N is an integer within 1 to 1000 list_of_coded_numbers = [] #List will contain the coded numbers in descending order while N > 0: if (N % 2 == 0) and (N % 3 == 0) and (N % 5 == 0): list_of_coded_numbers.append("CodilityTestCoders") elif (N % 3 == 0) and (N % 5 == 0): list_of_coded_numbers.append("TestCoders") elif (N % 2 == 0) and (N % 5 == 0): list_of_coded_numbers.append("CodilityCoders") elif (N % 2 == 0) and (N % 3 == 0): list_of_coded_numbers.append("CodilityTest") elif (N % 5 == 0): list_of_coded_numbers.append("Coders") elif (N % 3 == 0): list_of_coded_numbers.append("Test") elif (N % 2 == 0): list_of_coded_numbers.append("Codility") else: list_of_coded_numbers.append(N) N -= 1 list_of_coded_numbers.reverse() #Arrange the coded numbers in ascending order for coded_number in list_of_coded_numbers:# Print the coded numbers in each line print(coded_number) if __name__ == '__main__': solution(110)
def solution(N): if N > 0 and N < 1000: list_of_coded_numbers = [] while N > 0: if N % 2 == 0 and N % 3 == 0 and (N % 5 == 0): list_of_coded_numbers.append('CodilityTestCoders') elif N % 3 == 0 and N % 5 == 0: list_of_coded_numbers.append('TestCoders') elif N % 2 == 0 and N % 5 == 0: list_of_coded_numbers.append('CodilityCoders') elif N % 2 == 0 and N % 3 == 0: list_of_coded_numbers.append('CodilityTest') elif N % 5 == 0: list_of_coded_numbers.append('Coders') elif N % 3 == 0: list_of_coded_numbers.append('Test') elif N % 2 == 0: list_of_coded_numbers.append('Codility') else: list_of_coded_numbers.append(N) n -= 1 list_of_coded_numbers.reverse() for coded_number in list_of_coded_numbers: print(coded_number) if __name__ == '__main__': solution(110)
# # This file is part of stac2odc # Copyright (C) 2020 INPE. # # stac2odc is free software; you can redistribute it and/or modify it # under the terms of the MIT License; see LICENSE file for more details. # __version__ = '0.0.1'
__version__ = '0.0.1'
str = 'X-DSPAM-Confidence:0.8475' print(str) colon = str.find(":") fnum = float(str[colon+1:]) print("Number from string equals:", fnum)
str = 'X-DSPAM-Confidence:0.8475' print(str) colon = str.find(':') fnum = float(str[colon + 1:]) print('Number from string equals:', fnum)
# Python > Strings > String Validators # Identify the presence of alphanumeric characters, alphabetical characters, digits, lowercase and uppercase characters in a string. # # https://www.hackerrank.com/challenges/string-validators/problem # if __name__ == '__main__': s = input() # any alphanumeric characters print(any(c.isalnum() for c in s)) # any alphabetical characters print(any(c.isalpha() for c in s)) # any digits print(any(c.isdigit() for c in s)) # any lowercase characters print(any(c.islower() for c in s)) # any uppercase characters print(any(c.isupper() for c in s))
if __name__ == '__main__': s = input() print(any((c.isalnum() for c in s))) print(any((c.isalpha() for c in s))) print(any((c.isdigit() for c in s))) print(any((c.islower() for c in s))) print(any((c.isupper() for c in s)))
DOMAIN = "airthings" KEY_API = "api" PLATFORMS = ("sensor",) ERROR_LOGIN_FAILED = "login_failed"
domain = 'airthings' key_api = 'api' platforms = ('sensor',) error_login_failed = 'login_failed'
def updatePars(): if not parent().par.Lockbuffermenu: return op('output_table_path').cook(force=True) dat = op('output_table') if dat.numRows < 2: return p = parent().par.Outputbuffer p.menuNames = dat.col('name')[1:] p.menuLabels = dat.col('label')[1:] def onTableChange(dat): updatePars() def onValueChange(*_): updatePars()
def update_pars(): if not parent().par.Lockbuffermenu: return op('output_table_path').cook(force=True) dat = op('output_table') if dat.numRows < 2: return p = parent().par.Outputbuffer p.menuNames = dat.col('name')[1:] p.menuLabels = dat.col('label')[1:] def on_table_change(dat): update_pars() def on_value_change(*_): update_pars()
def error_Check(inputX, inputY, nSamples, initVector, minCost, alpha, training_epochs, silent, overlap, objFunc, keepPercent, batchSize, batching): acceptedObjFuncs = ["", "QUAD"] if inputX.shape[0] != inputY.shape[0]: print("Must have the same number of labels and training samples") return -1 if type(nSamples) != int: print("nSamples must be an integer") return -1 if len(initVector) <= 1: print("init vector is too short, must be at least 2 layers") return -1 if type(minCost) not in [int, float]: print("minCost must be float or integer") return -1 if type(alpha) not in [int, float]: print("alpha must be float or integer") return -1 if type(training_epochs) != int: print("training_epochs must be an integer") return -1 if type(silent) != bool: print("silent must be either True or False") return -1 if type(overlap) != bool: print("silent must be either True or False") return -1 if type(keepPercent) not in [float, int]: print("keepPercent must be an int or float") return -1 if keepPercent > 1 or keepPercent < 0: print("keepPercent must be between 0 and 1") return -1 if objFunc not in acceptedObjFuncs: print("objFunc can only take on values: ", end='') for func in acceptedObjFuncs[:-1]: if func == '': print("Empty string", end=', ') else: print(func, end=", ") print(acceptedObjFuncs[-1] + '.') return -1 if type(batchSize) != int: print("batchSize must be int") return -1 if batching not in [True, False]: print("batching must be boolean") return -1 #passed all tests return 0
def error__check(inputX, inputY, nSamples, initVector, minCost, alpha, training_epochs, silent, overlap, objFunc, keepPercent, batchSize, batching): accepted_obj_funcs = ['', 'QUAD'] if inputX.shape[0] != inputY.shape[0]: print('Must have the same number of labels and training samples') return -1 if type(nSamples) != int: print('nSamples must be an integer') return -1 if len(initVector) <= 1: print('init vector is too short, must be at least 2 layers') return -1 if type(minCost) not in [int, float]: print('minCost must be float or integer') return -1 if type(alpha) not in [int, float]: print('alpha must be float or integer') return -1 if type(training_epochs) != int: print('training_epochs must be an integer') return -1 if type(silent) != bool: print('silent must be either True or False') return -1 if type(overlap) != bool: print('silent must be either True or False') return -1 if type(keepPercent) not in [float, int]: print('keepPercent must be an int or float') return -1 if keepPercent > 1 or keepPercent < 0: print('keepPercent must be between 0 and 1') return -1 if objFunc not in acceptedObjFuncs: print('objFunc can only take on values: ', end='') for func in acceptedObjFuncs[:-1]: if func == '': print('Empty string', end=', ') else: print(func, end=', ') print(acceptedObjFuncs[-1] + '.') return -1 if type(batchSize) != int: print('batchSize must be int') return -1 if batching not in [True, False]: print('batching must be boolean') return -1 return 0
''' Kattis - oddgnome theres probably a smarter way, but i really can't be bothered Time: O(n^2 log n), Space: O(n) ''' num_tc = int(input()) for _ in range(num_tc): arr = list(map(int, input().split())) n = arr.pop(0) for i in range(1, n): new_arr = arr[:i] + arr[i+1:] if new_arr == sorted(new_arr): print(i+1) break
""" Kattis - oddgnome theres probably a smarter way, but i really can't be bothered Time: O(n^2 log n), Space: O(n) """ num_tc = int(input()) for _ in range(num_tc): arr = list(map(int, input().split())) n = arr.pop(0) for i in range(1, n): new_arr = arr[:i] + arr[i + 1:] if new_arr == sorted(new_arr): print(i + 1) break
def force_bytes(value): if isinstance(value, bytes): return value return str(value).encode('utf-8')
def force_bytes(value): if isinstance(value, bytes): return value return str(value).encode('utf-8')
coords = [] for ry in range(-2, 3): for rx in range(2, -3, -1): x = rx / 4 y = ry / 4 coords.append((x,y)) for p in range(16): y, x = divmod(p, 4) top_right = coords[(y+1)*5 + x] top_left = coords[(y+1)*5 + x + 1] bottom_left = coords[y*5 + x + 1] bottom_right = coords[y*5 + x] line = '{{{{ {} }}}},'.format(', '.join('{: .2f}f' for _ in range(12))) line = line.format( top_right[0], top_right[1], top_left[0], top_left[1], bottom_left[0], bottom_left[1], top_right[0], top_right[1], bottom_left[0], bottom_left[1], bottom_right[0], bottom_right[1], ) print(line)
coords = [] for ry in range(-2, 3): for rx in range(2, -3, -1): x = rx / 4 y = ry / 4 coords.append((x, y)) for p in range(16): (y, x) = divmod(p, 4) top_right = coords[(y + 1) * 5 + x] top_left = coords[(y + 1) * 5 + x + 1] bottom_left = coords[y * 5 + x + 1] bottom_right = coords[y * 5 + x] line = '{{{{ {} }}}},'.format(', '.join(('{: .2f}f' for _ in range(12)))) line = line.format(top_right[0], top_right[1], top_left[0], top_left[1], bottom_left[0], bottom_left[1], top_right[0], top_right[1], bottom_left[0], bottom_left[1], bottom_right[0], bottom_right[1]) print(line)
# -*- coding: utf-8 -*- __author__ = 'Bruno Paes' __email__ = 'brunopaes05@gmail.com' __github__ = 'https://www.github.com/Brunopaes' __status__ = 'Finalised' class Viginere(object): @staticmethod def encrypt(plaintext, key): key_length = len(key) key_as_int = [ord(i) for i in key] plaintext_int = [ord(i) for i in plaintext] ciphertext = '' for i in range(len(plaintext_int)): value = (plaintext_int[i] + key_as_int[i % key_length]) % 26 ciphertext += chr(value + 65) return ciphertext @staticmethod def decrypt(ciphertext, key): key_length = len(key) key_as_int = [ord(i) for i in key] ciphertext_int = [ord(i) for i in ciphertext] plaintext = '' for i in range(len(ciphertext_int)): value = (ciphertext_int[i] - key_as_int[i % key_length]) % 26 plaintext += chr(value + 65) return plaintext if __name__ == '__main__': c = Viginere() print(c.decrypt('efsdsetpe', 'espm'))
__author__ = 'Bruno Paes' __email__ = 'brunopaes05@gmail.com' __github__ = 'https://www.github.com/Brunopaes' __status__ = 'Finalised' class Viginere(object): @staticmethod def encrypt(plaintext, key): key_length = len(key) key_as_int = [ord(i) for i in key] plaintext_int = [ord(i) for i in plaintext] ciphertext = '' for i in range(len(plaintext_int)): value = (plaintext_int[i] + key_as_int[i % key_length]) % 26 ciphertext += chr(value + 65) return ciphertext @staticmethod def decrypt(ciphertext, key): key_length = len(key) key_as_int = [ord(i) for i in key] ciphertext_int = [ord(i) for i in ciphertext] plaintext = '' for i in range(len(ciphertext_int)): value = (ciphertext_int[i] - key_as_int[i % key_length]) % 26 plaintext += chr(value + 65) return plaintext if __name__ == '__main__': c = viginere() print(c.decrypt('efsdsetpe', 'espm'))
predictor_url = 'http://dlib.net/files/shape_predictor_68_face_landmarks.dat.bz2' predictor_file = '../weights/shape_predictor_68_face_landmarks.dat' p2v_model_gdrive_id = '1op5_zyH4CWm_JFDdCUPZM4X-A045ETex' sample_image = '../examples/sample.jpg'
predictor_url = 'http://dlib.net/files/shape_predictor_68_face_landmarks.dat.bz2' predictor_file = '../weights/shape_predictor_68_face_landmarks.dat' p2v_model_gdrive_id = '1op5_zyH4CWm_JFDdCUPZM4X-A045ETex' sample_image = '../examples/sample.jpg'
def main(request, response): name = request.GET.first(b"name") value = request.GET.first(b"value") source_origin = request.headers.get(b"origin", None) response_headers = [(b"Set-Cookie", name + b"=" + value), (b"Access-Control-Allow-Origin", source_origin), (b"Access-Control-Allow-Credentials", b"true")] return (200, response_headers, u"")
def main(request, response): name = request.GET.first(b'name') value = request.GET.first(b'value') source_origin = request.headers.get(b'origin', None) response_headers = [(b'Set-Cookie', name + b'=' + value), (b'Access-Control-Allow-Origin', source_origin), (b'Access-Control-Allow-Credentials', b'true')] return (200, response_headers, u'')
# Leetcode 435. Non-overlapping Intervals # # Link: https://leetcode.com/problems/non-overlapping-intervals/ # Difficulty: Medium # Solution using sorting. # Complexity: # O(NlogN) time | where N represent the number of intervals # O(1) space class Solution: def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int: intervals.sort(key = lambda pair : pair[0]) result = 0 prevEnd = intervals[0][1] for start, end in intervals[1:]: if start >= prevEnd: # Not overlapping if prevEnd < start prevEnd = end else: # Overlapping if prevEnd > start # Remove the longest one result += 1 prevEnd = min(prevEnd, end) return result
class Solution: def erase_overlap_intervals(self, intervals: List[List[int]]) -> int: intervals.sort(key=lambda pair: pair[0]) result = 0 prev_end = intervals[0][1] for (start, end) in intervals[1:]: if start >= prevEnd: prev_end = end else: result += 1 prev_end = min(prevEnd, end) return result
BOARD_TILE_SIZE = 56 # the size of each board tile BOARD_PLAYER_SIZE = 20 # the size of each player icon BOARD_MARGIN = (10, 0) # margins, in pixels (for player icons) PLAYER_ICON_IMAGE_SIZE = 32 # the size of the image to download, should a power of 2 and higher than BOARD_PLAYER_SIZE MAX_PLAYERS = 4 # depends on the board size/quality, 4 is for the default board # board definition (from, to) BOARD = { # ladders 2: 38, 7: 14, 8: 31, 15: 26, 21: 42, 28: 84, 36: 44, 51: 67, 71: 91, 78: 98, 87: 94, # snakes 99: 80, 95: 75, 92: 88, 89: 68, 74: 53, 64: 60, 62: 19, 49: 11, 46: 25, 16: 6 }
board_tile_size = 56 board_player_size = 20 board_margin = (10, 0) player_icon_image_size = 32 max_players = 4 board = {2: 38, 7: 14, 8: 31, 15: 26, 21: 42, 28: 84, 36: 44, 51: 67, 71: 91, 78: 98, 87: 94, 99: 80, 95: 75, 92: 88, 89: 68, 74: 53, 64: 60, 62: 19, 49: 11, 46: 25, 16: 6}
def truncate(string, length): "Ensure a string is no longer than a given length." if len(string) <= length: return string else: return string[:length]
def truncate(string, length): """Ensure a string is no longer than a given length.""" if len(string) <= length: return string else: return string[:length]
def insertionSort(arr, size): for i in range(1, size): key = arr[i] j = i - 1 while j >= 0 and arr[j] > key: arr[j + 1] = arr[j] j -= 1 arr[j + 1] = key return arr def shakerSort(arr, size): left = 0 right = size - 1 lastSwap = 0 while left < right: for i in range(left, right): if arr[i] > arr[i + 1]: arr[i], arr[i + 1] = arr[i + 1], arr[i] lastSwap = i right = lastSwap for i in range(right, left, -1): if arr[i - 1] > arr[i]: arr[i], arr[i - 1] = arr[i - 1], arr[i] lastSwap = i left = lastSwap return arr def selectionSort(arr, size): for i in range(size - 1): minIndex = i for j in range(i + 1, size): if arr[minIndex] > arr[j]: minIndex = j arr[minIndex], arr[i] = arr[i], arr[minIndex] return arr if __name__ == '__main__': a = [1, 2, 3, 4, 5] b = [5, 4, 3, 2, 1] c = [4, 2 ,3, 5, 1] print(insertionSort(a, 5)) print(shakerSort(a, 5)) print(selectionSort(a, 5)) print(insertionSort(b, 5)) print(shakerSort(b, 5)) print(selectionSort(b, 5)) print(insertionSort(c, 5)) print(shakerSort(c, 5)) print(selectionSort(c, 5)) print(insertionSort([1], 1)) print(shakerSort([1], 1)) print(selectionSort([1], 1)) print(insertionSort([], 0)) print(shakerSort([], 0)) print(selectionSort([], 0)) print(insertionSort(["ab", "make", "draw"], 3)) print(insertionSort([2, 1, 3, 4, 5], 5))
def insertion_sort(arr, size): for i in range(1, size): key = arr[i] j = i - 1 while j >= 0 and arr[j] > key: arr[j + 1] = arr[j] j -= 1 arr[j + 1] = key return arr def shaker_sort(arr, size): left = 0 right = size - 1 last_swap = 0 while left < right: for i in range(left, right): if arr[i] > arr[i + 1]: (arr[i], arr[i + 1]) = (arr[i + 1], arr[i]) last_swap = i right = lastSwap for i in range(right, left, -1): if arr[i - 1] > arr[i]: (arr[i], arr[i - 1]) = (arr[i - 1], arr[i]) last_swap = i left = lastSwap return arr def selection_sort(arr, size): for i in range(size - 1): min_index = i for j in range(i + 1, size): if arr[minIndex] > arr[j]: min_index = j (arr[minIndex], arr[i]) = (arr[i], arr[minIndex]) return arr if __name__ == '__main__': a = [1, 2, 3, 4, 5] b = [5, 4, 3, 2, 1] c = [4, 2, 3, 5, 1] print(insertion_sort(a, 5)) print(shaker_sort(a, 5)) print(selection_sort(a, 5)) print(insertion_sort(b, 5)) print(shaker_sort(b, 5)) print(selection_sort(b, 5)) print(insertion_sort(c, 5)) print(shaker_sort(c, 5)) print(selection_sort(c, 5)) print(insertion_sort([1], 1)) print(shaker_sort([1], 1)) print(selection_sort([1], 1)) print(insertion_sort([], 0)) print(shaker_sort([], 0)) print(selection_sort([], 0)) print(insertion_sort(['ab', 'make', 'draw'], 3)) print(insertion_sort([2, 1, 3, 4, 5], 5))
def mergeOverlappingIntervals(intervals): sortedIntervals = sorted(intervals, key=lambda x: x[0]) overlappingIntervals = [] left = sortedIntervals[0][0] right = sortedIntervals[0][1] for i in range(1, len(sortedIntervals)): if right >= sortedIntervals[i][0]: right = max(right, sortedIntervals[i][1]) else: overlappingIntervals.append([left, right]) left, right = sortedIntervals[i][0], sortedIntervals[i][1] overlappingIntervals.append([left, right]) return overlappingIntervals
def merge_overlapping_intervals(intervals): sorted_intervals = sorted(intervals, key=lambda x: x[0]) overlapping_intervals = [] left = sortedIntervals[0][0] right = sortedIntervals[0][1] for i in range(1, len(sortedIntervals)): if right >= sortedIntervals[i][0]: right = max(right, sortedIntervals[i][1]) else: overlappingIntervals.append([left, right]) (left, right) = (sortedIntervals[i][0], sortedIntervals[i][1]) overlappingIntervals.append([left, right]) return overlappingIntervals
class GameLogic: def __int__(self): self def add_lander(self, lander): self.lander = lander def update(self, delta_time): self.lander.update_lander(delta_time)
class Gamelogic: def __int__(self): self def add_lander(self, lander): self.lander = lander def update(self, delta_time): self.lander.update_lander(delta_time)
data = [] with open("data.txt") as file: data = [int(x) for x in file.read().split(",")] def part_one(data, noun, verb): opcode = 0 data_c = data[:] data_c[1] = noun data_c[2] = verb while True: if data_c[opcode] == 1: data_c[data_c[opcode + 3]] = data_c[data_c[opcode + 1]] + data_c[data_c[opcode + 2]] elif data_c[opcode] == 2: data_c[data_c[opcode + 3]] = data_c[data_c[opcode + 1]] * data_c[data_c[opcode + 2]] elif data_c[opcode] == 99: break else: print("It failed!") opcode += 4 return data_c[0] def part_two(data): for noun in range(100): for verb in range(100): if part_one(data, noun, verb) == 19690720: return 100 * noun + verb print(part_two(data))
data = [] with open('data.txt') as file: data = [int(x) for x in file.read().split(',')] def part_one(data, noun, verb): opcode = 0 data_c = data[:] data_c[1] = noun data_c[2] = verb while True: if data_c[opcode] == 1: data_c[data_c[opcode + 3]] = data_c[data_c[opcode + 1]] + data_c[data_c[opcode + 2]] elif data_c[opcode] == 2: data_c[data_c[opcode + 3]] = data_c[data_c[opcode + 1]] * data_c[data_c[opcode + 2]] elif data_c[opcode] == 99: break else: print('It failed!') opcode += 4 return data_c[0] def part_two(data): for noun in range(100): for verb in range(100): if part_one(data, noun, verb) == 19690720: return 100 * noun + verb print(part_two(data))
var = 'foo' def ex2(): var = 'bar' print ('inside the function var is ', var) ex2() def ex3(): global var var = 'bar' print ('inside the function var is ', var) ex3() print ('outside the function var is ', var)
var = 'foo' def ex2(): var = 'bar' print('inside the function var is ', var) ex2() def ex3(): global var var = 'bar' print('inside the function var is ', var) ex3() print('outside the function var is ', var)
code = bytearray([ 0xa9, 0xff, 0x8d, 0x02, 0x60, 0xa9, 0x55, # lda #$55 0x8d, 0x00, 0x60, #sta $6000 0xa9, 0x00, # lda #00 0x8d, 0x00, 0x60, #sta $6000 0x4c, 0x05, 0x80 #jmp 8005 (#lda $55) ]) rom = code + bytearray([0xea] * (32768 - len(code)) ) rom[0x7ffc] = 0x00 rom[0x7ffd] = 0x80 with open("rom.bin", "wb") as out_file: out_file.write(rom);
code = bytearray([169, 255, 141, 2, 96, 169, 85, 141, 0, 96, 169, 0, 141, 0, 96, 76, 5, 128]) rom = code + bytearray([234] * (32768 - len(code))) rom[32764] = 0 rom[32765] = 128 with open('rom.bin', 'wb') as out_file: out_file.write(rom)
_sampler = None def get_sampler(): return _sampler def set_sampler(sampler): global _sampler _sampler = sampler
_sampler = None def get_sampler(): return _sampler def set_sampler(sampler): global _sampler _sampler = sampler
class Node: def __init__(self,id,parent,val): self.id=id self.parent=parent self.ch1,self.ch2=0,0 self.val=val self.leaf=True n=int(input()) orix=[*map(int,input().split())] x=sorted(orix) node=dict() node[1]=Node(1,0,-1) cnt=1 li=[] for i in x: li2=[] root=node[1] for j in range(i): if root.ch1==0: cnt+=1 node[cnt]=Node(cnt,root.id,0) root.ch1=cnt root.leaf=False root=node[cnt] li2.append("0") elif root.ch2==0: cnt+=1 node[cnt]=Node(cnt,root.id,1) root.ch2=cnt if j==i-1: while root.id!=1: if node[root.ch1].leaf and node[root.ch2].leaf: root.leaf=True root=node[root.parent] else: break else: root=node[cnt] li2.append("1") elif not node[root.ch1].leaf: root=node[root.ch1] li2.append("0") elif not node[root.ch2].leaf: root=node[root.ch2] li2.append("1") else: print(-1) exit(0) li.append("".join(li2)) print(1) for i in li: for j in range(n): if orix[j]==len(i): break orix[j]=i for i in orix: print(i)
class Node: def __init__(self, id, parent, val): self.id = id self.parent = parent (self.ch1, self.ch2) = (0, 0) self.val = val self.leaf = True n = int(input()) orix = [*map(int, input().split())] x = sorted(orix) node = dict() node[1] = node(1, 0, -1) cnt = 1 li = [] for i in x: li2 = [] root = node[1] for j in range(i): if root.ch1 == 0: cnt += 1 node[cnt] = node(cnt, root.id, 0) root.ch1 = cnt root.leaf = False root = node[cnt] li2.append('0') elif root.ch2 == 0: cnt += 1 node[cnt] = node(cnt, root.id, 1) root.ch2 = cnt if j == i - 1: while root.id != 1: if node[root.ch1].leaf and node[root.ch2].leaf: root.leaf = True root = node[root.parent] else: break else: root = node[cnt] li2.append('1') elif not node[root.ch1].leaf: root = node[root.ch1] li2.append('0') elif not node[root.ch2].leaf: root = node[root.ch2] li2.append('1') else: print(-1) exit(0) li.append(''.join(li2)) print(1) for i in li: for j in range(n): if orix[j] == len(i): break orix[j] = i for i in orix: print(i)
#!/usr/bin/env python # coding=utf-8 ''' @Author: John @Email: johnjim0816@gmail.com @Date: 2019-11-15 13:46:12 @LastEditor: John @LastEditTime: 2020-07-29 22:43:12 @Discription: @Environment: ''' class Solution: def singleNumber(self, nums: List[int]) -> int: seen_once = seen_twice = 0 for num in nums: seen_once = ~seen_twice & (seen_once ^ num) seen_twice = ~seen_once & (seen_twice ^ num) return seen_once
""" @Author: John @Email: johnjim0816@gmail.com @Date: 2019-11-15 13:46:12 @LastEditor: John @LastEditTime: 2020-07-29 22:43:12 @Discription: @Environment: """ class Solution: def single_number(self, nums: List[int]) -> int: seen_once = seen_twice = 0 for num in nums: seen_once = ~seen_twice & (seen_once ^ num) seen_twice = ~seen_once & (seen_twice ^ num) return seen_once
res = 0 i = 0 nb = int(input()) if nb == -1: while i != 'F': i = input() if i != 'F': res += int(i) else: for x in range(nb): i = int(input()) res += i print(res)
res = 0 i = 0 nb = int(input()) if nb == -1: while i != 'F': i = input() if i != 'F': res += int(i) else: for x in range(nb): i = int(input()) res += i print(res)
# # Example file for working with conditional statements # def main(): x, y = 10, 100 # conditional flow uses if, elif, else if x < y: print("x is smaller than y") elif x == y: print("x has same value as y") else: print("x is larger than y") # conditional statements let you use "a if C else b" result = "x is less than y" if x < y else "x is same as or larger than y" print(result) if __name__ == "__main__": main()
def main(): (x, y) = (10, 100) if x < y: print('x is smaller than y') elif x == y: print('x has same value as y') else: print('x is larger than y') result = 'x is less than y' if x < y else 'x is same as or larger than y' print(result) if __name__ == '__main__': main()
class AreaLight: def __init__(self, shape_id, intensity, two_sided = False): assert(intensity.device.type == 'cpu') self.shape_id = shape_id self.intensity = intensity self.two_sided = two_sided def state_dict(self): return { 'shape_id': self.shape_id, 'intensity': self.intensity, 'two_sided': self.two_sided } @classmethod def load_state_dict(cls, state_dict): return cls( state_dict['shape_id'], state_dict['intensity'], state_dict['two_sided'])
class Arealight: def __init__(self, shape_id, intensity, two_sided=False): assert intensity.device.type == 'cpu' self.shape_id = shape_id self.intensity = intensity self.two_sided = two_sided def state_dict(self): return {'shape_id': self.shape_id, 'intensity': self.intensity, 'two_sided': self.two_sided} @classmethod def load_state_dict(cls, state_dict): return cls(state_dict['shape_id'], state_dict['intensity'], state_dict['two_sided'])
# # PySNMP MIB module CISCO-VOICE-CAS-MODULE-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-VOICE-CAS-MODULE-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 18:02:23 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") ConstraintsIntersection, ValueSizeConstraint, SingleValueConstraint, ValueRangeConstraint, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ValueSizeConstraint", "SingleValueConstraint", "ValueRangeConstraint", "ConstraintsUnion") ciscoMgmt, = mibBuilder.importSymbols("CISCO-SMI", "ciscoMgmt") EntPhysicalIndexOrZero, = mibBuilder.importSymbols("CISCO-TC", "EntPhysicalIndexOrZero") SnmpAdminString, = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString") ModuleCompliance, NotificationGroup, ObjectGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup", "ObjectGroup") IpAddress, Counter32, TimeTicks, Gauge32, Unsigned32, MibIdentifier, Bits, iso, ObjectIdentity, Counter64, ModuleIdentity, NotificationType, MibScalar, MibTable, MibTableRow, MibTableColumn, Integer32 = mibBuilder.importSymbols("SNMPv2-SMI", "IpAddress", "Counter32", "TimeTicks", "Gauge32", "Unsigned32", "MibIdentifier", "Bits", "iso", "ObjectIdentity", "Counter64", "ModuleIdentity", "NotificationType", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Integer32") TextualConvention, DisplayString, RowStatus = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString", "RowStatus") ciscoVoiceCasModuleMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 9, 9, 389)) ciscoVoiceCasModuleMIB.setRevisions(('2004-03-15 00:00',)) if mibBuilder.loadTexts: ciscoVoiceCasModuleMIB.setLastUpdated('200403150000Z') if mibBuilder.loadTexts: ciscoVoiceCasModuleMIB.setOrganization('Cisco Systems, Inc.') ciscoVoiceCasModuleNotifs = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 389, 0)) ciscoVoiceCasModuleObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 389, 1)) cvcmCasConfig = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 389, 1, 1)) class CvcmCasPatternBitPosition(TextualConvention, Bits): status = 'current' namedValues = NamedValues(("dBit", 0), ("cBit", 1), ("bBit", 2), ("aBit", 3)) class CvcmCasBitAction(TextualConvention, Integer32): status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)) namedValues = NamedValues(("casBitNoAction", 1), ("casBitSetToZero", 2), ("casBitSetToOne", 3), ("casBitInvertBit", 4), ("casBitInvertABit", 5), ("casBitInvertBBit", 6), ("casBitInvertCBit", 7), ("casBitInvertDBit", 8), ("casBitABit", 9), ("casBitBBit", 10), ("casBitCBit", 11), ("casBitDBit", 12)) cvcmABCDBitTemplateConfigTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 389, 1, 1, 1), ) if mibBuilder.loadTexts: cvcmABCDBitTemplateConfigTable.setStatus('current') cvcmABCDBitTemplateConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 389, 1, 1, 1, 1), ).setIndexNames((0, "CISCO-VOICE-CAS-MODULE-MIB", "cvcmModuleIndex"), (0, "CISCO-VOICE-CAS-MODULE-MIB", "cvcmCasTemplateIndex"), (0, "CISCO-VOICE-CAS-MODULE-MIB", "cvcmABCDPatternIndex")) if mibBuilder.loadTexts: cvcmABCDBitTemplateConfigEntry.setStatus('current') cvcmModuleIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 389, 1, 1, 1, 1, 1), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))) if mibBuilder.loadTexts: cvcmModuleIndex.setStatus('current') cvcmCasTemplateIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 389, 1, 1, 1, 1, 2), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1, 2147483647))) if mibBuilder.loadTexts: cvcmCasTemplateIndex.setStatus('current') cvcmABCDPatternIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 389, 1, 1, 1, 1, 3), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1, 16))) if mibBuilder.loadTexts: cvcmABCDPatternIndex.setStatus('current') cvcmModulePhysicalIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 389, 1, 1, 1, 1, 4), EntPhysicalIndexOrZero()).setMaxAccess("readonly") if mibBuilder.loadTexts: cvcmModulePhysicalIndex.setStatus('current') cvcmCasTemplateName = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 389, 1, 1, 1, 1, 5), SnmpAdminString()).setMaxAccess("readcreate") if mibBuilder.loadTexts: cvcmCasTemplateName.setStatus('current') cvcmABCDIncomingPattern = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 389, 1, 1, 1, 1, 6), CvcmCasPatternBitPosition()).setMaxAccess("readcreate") if mibBuilder.loadTexts: cvcmABCDIncomingPattern.setStatus('current') cvcmABCDOutgoingPattern = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 389, 1, 1, 1, 1, 7), CvcmCasPatternBitPosition()).setMaxAccess("readonly") if mibBuilder.loadTexts: cvcmABCDOutgoingPattern.setStatus('current') cvcmCasABitAction = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 389, 1, 1, 1, 1, 8), CvcmCasBitAction().clone('casBitABit')).setMaxAccess("readcreate") if mibBuilder.loadTexts: cvcmCasABitAction.setStatus('current') cvcmCasBBitAction = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 389, 1, 1, 1, 1, 9), CvcmCasBitAction().clone('casBitBBit')).setMaxAccess("readcreate") if mibBuilder.loadTexts: cvcmCasBBitAction.setStatus('current') cvcmCasCBitAction = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 389, 1, 1, 1, 1, 10), CvcmCasBitAction().clone('casBitCBit')).setMaxAccess("readcreate") if mibBuilder.loadTexts: cvcmCasCBitAction.setStatus('current') cvcmCasDBitAction = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 389, 1, 1, 1, 1, 11), CvcmCasBitAction().clone('casBitDBit')).setMaxAccess("readcreate") if mibBuilder.loadTexts: cvcmCasDBitAction.setStatus('current') cvcmCasBitRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 389, 1, 1, 1, 1, 12), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: cvcmCasBitRowStatus.setStatus('current') cvcmMIBConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 389, 2)) cvcmMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 389, 2, 1)) cvcmMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 389, 2, 2)) ciscoVoiceCasModuleMIBCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 389, 2, 2, 1)).setObjects(("CISCO-VOICE-CAS-MODULE-MIB", "cvcmCasBitGroup")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoVoiceCasModuleMIBCompliance = ciscoVoiceCasModuleMIBCompliance.setStatus('current') cvcmCasBitGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 389, 2, 1, 1)).setObjects(("CISCO-VOICE-CAS-MODULE-MIB", "cvcmModulePhysicalIndex"), ("CISCO-VOICE-CAS-MODULE-MIB", "cvcmCasTemplateName"), ("CISCO-VOICE-CAS-MODULE-MIB", "cvcmABCDIncomingPattern"), ("CISCO-VOICE-CAS-MODULE-MIB", "cvcmABCDOutgoingPattern"), ("CISCO-VOICE-CAS-MODULE-MIB", "cvcmCasABitAction"), ("CISCO-VOICE-CAS-MODULE-MIB", "cvcmCasBBitAction"), ("CISCO-VOICE-CAS-MODULE-MIB", "cvcmCasCBitAction"), ("CISCO-VOICE-CAS-MODULE-MIB", "cvcmCasDBitAction"), ("CISCO-VOICE-CAS-MODULE-MIB", "cvcmCasBitRowStatus")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): cvcmCasBitGroup = cvcmCasBitGroup.setStatus('current') mibBuilder.exportSymbols("CISCO-VOICE-CAS-MODULE-MIB", cvcmModulePhysicalIndex=cvcmModulePhysicalIndex, ciscoVoiceCasModuleMIB=ciscoVoiceCasModuleMIB, cvcmModuleIndex=cvcmModuleIndex, CvcmCasBitAction=CvcmCasBitAction, cvcmMIBCompliances=cvcmMIBCompliances, PYSNMP_MODULE_ID=ciscoVoiceCasModuleMIB, cvcmABCDOutgoingPattern=cvcmABCDOutgoingPattern, cvcmCasTemplateName=cvcmCasTemplateName, cvcmABCDIncomingPattern=cvcmABCDIncomingPattern, cvcmCasABitAction=cvcmCasABitAction, cvcmCasCBitAction=cvcmCasCBitAction, cvcmCasTemplateIndex=cvcmCasTemplateIndex, cvcmABCDPatternIndex=cvcmABCDPatternIndex, ciscoVoiceCasModuleMIBCompliance=ciscoVoiceCasModuleMIBCompliance, cvcmABCDBitTemplateConfigEntry=cvcmABCDBitTemplateConfigEntry, cvcmCasBitGroup=cvcmCasBitGroup, ciscoVoiceCasModuleNotifs=ciscoVoiceCasModuleNotifs, cvcmCasConfig=cvcmCasConfig, cvcmMIBConformance=cvcmMIBConformance, cvcmCasBitRowStatus=cvcmCasBitRowStatus, ciscoVoiceCasModuleObjects=ciscoVoiceCasModuleObjects, CvcmCasPatternBitPosition=CvcmCasPatternBitPosition, cvcmCasBBitAction=cvcmCasBBitAction, cvcmABCDBitTemplateConfigTable=cvcmABCDBitTemplateConfigTable, cvcmMIBGroups=cvcmMIBGroups, cvcmCasDBitAction=cvcmCasDBitAction)
(octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_intersection, value_size_constraint, single_value_constraint, value_range_constraint, constraints_union) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsIntersection', 'ValueSizeConstraint', 'SingleValueConstraint', 'ValueRangeConstraint', 'ConstraintsUnion') (cisco_mgmt,) = mibBuilder.importSymbols('CISCO-SMI', 'ciscoMgmt') (ent_physical_index_or_zero,) = mibBuilder.importSymbols('CISCO-TC', 'EntPhysicalIndexOrZero') (snmp_admin_string,) = mibBuilder.importSymbols('SNMP-FRAMEWORK-MIB', 'SnmpAdminString') (module_compliance, notification_group, object_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup', 'ObjectGroup') (ip_address, counter32, time_ticks, gauge32, unsigned32, mib_identifier, bits, iso, object_identity, counter64, module_identity, notification_type, mib_scalar, mib_table, mib_table_row, mib_table_column, integer32) = mibBuilder.importSymbols('SNMPv2-SMI', 'IpAddress', 'Counter32', 'TimeTicks', 'Gauge32', 'Unsigned32', 'MibIdentifier', 'Bits', 'iso', 'ObjectIdentity', 'Counter64', 'ModuleIdentity', 'NotificationType', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'Integer32') (textual_convention, display_string, row_status) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'DisplayString', 'RowStatus') cisco_voice_cas_module_mib = module_identity((1, 3, 6, 1, 4, 1, 9, 9, 389)) ciscoVoiceCasModuleMIB.setRevisions(('2004-03-15 00:00',)) if mibBuilder.loadTexts: ciscoVoiceCasModuleMIB.setLastUpdated('200403150000Z') if mibBuilder.loadTexts: ciscoVoiceCasModuleMIB.setOrganization('Cisco Systems, Inc.') cisco_voice_cas_module_notifs = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 389, 0)) cisco_voice_cas_module_objects = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 389, 1)) cvcm_cas_config = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 389, 1, 1)) class Cvcmcaspatternbitposition(TextualConvention, Bits): status = 'current' named_values = named_values(('dBit', 0), ('cBit', 1), ('bBit', 2), ('aBit', 3)) class Cvcmcasbitaction(TextualConvention, Integer32): status = 'current' subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)) named_values = named_values(('casBitNoAction', 1), ('casBitSetToZero', 2), ('casBitSetToOne', 3), ('casBitInvertBit', 4), ('casBitInvertABit', 5), ('casBitInvertBBit', 6), ('casBitInvertCBit', 7), ('casBitInvertDBit', 8), ('casBitABit', 9), ('casBitBBit', 10), ('casBitCBit', 11), ('casBitDBit', 12)) cvcm_abcd_bit_template_config_table = mib_table((1, 3, 6, 1, 4, 1, 9, 9, 389, 1, 1, 1)) if mibBuilder.loadTexts: cvcmABCDBitTemplateConfigTable.setStatus('current') cvcm_abcd_bit_template_config_entry = mib_table_row((1, 3, 6, 1, 4, 1, 9, 9, 389, 1, 1, 1, 1)).setIndexNames((0, 'CISCO-VOICE-CAS-MODULE-MIB', 'cvcmModuleIndex'), (0, 'CISCO-VOICE-CAS-MODULE-MIB', 'cvcmCasTemplateIndex'), (0, 'CISCO-VOICE-CAS-MODULE-MIB', 'cvcmABCDPatternIndex')) if mibBuilder.loadTexts: cvcmABCDBitTemplateConfigEntry.setStatus('current') cvcm_module_index = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 389, 1, 1, 1, 1, 1), unsigned32().subtype(subtypeSpec=value_range_constraint(1, 2147483647))) if mibBuilder.loadTexts: cvcmModuleIndex.setStatus('current') cvcm_cas_template_index = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 389, 1, 1, 1, 1, 2), unsigned32().subtype(subtypeSpec=value_range_constraint(1, 2147483647))) if mibBuilder.loadTexts: cvcmCasTemplateIndex.setStatus('current') cvcm_abcd_pattern_index = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 389, 1, 1, 1, 1, 3), unsigned32().subtype(subtypeSpec=value_range_constraint(1, 16))) if mibBuilder.loadTexts: cvcmABCDPatternIndex.setStatus('current') cvcm_module_physical_index = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 389, 1, 1, 1, 1, 4), ent_physical_index_or_zero()).setMaxAccess('readonly') if mibBuilder.loadTexts: cvcmModulePhysicalIndex.setStatus('current') cvcm_cas_template_name = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 389, 1, 1, 1, 1, 5), snmp_admin_string()).setMaxAccess('readcreate') if mibBuilder.loadTexts: cvcmCasTemplateName.setStatus('current') cvcm_abcd_incoming_pattern = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 389, 1, 1, 1, 1, 6), cvcm_cas_pattern_bit_position()).setMaxAccess('readcreate') if mibBuilder.loadTexts: cvcmABCDIncomingPattern.setStatus('current') cvcm_abcd_outgoing_pattern = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 389, 1, 1, 1, 1, 7), cvcm_cas_pattern_bit_position()).setMaxAccess('readonly') if mibBuilder.loadTexts: cvcmABCDOutgoingPattern.setStatus('current') cvcm_cas_a_bit_action = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 389, 1, 1, 1, 1, 8), cvcm_cas_bit_action().clone('casBitABit')).setMaxAccess('readcreate') if mibBuilder.loadTexts: cvcmCasABitAction.setStatus('current') cvcm_cas_b_bit_action = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 389, 1, 1, 1, 1, 9), cvcm_cas_bit_action().clone('casBitBBit')).setMaxAccess('readcreate') if mibBuilder.loadTexts: cvcmCasBBitAction.setStatus('current') cvcm_cas_c_bit_action = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 389, 1, 1, 1, 1, 10), cvcm_cas_bit_action().clone('casBitCBit')).setMaxAccess('readcreate') if mibBuilder.loadTexts: cvcmCasCBitAction.setStatus('current') cvcm_cas_d_bit_action = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 389, 1, 1, 1, 1, 11), cvcm_cas_bit_action().clone('casBitDBit')).setMaxAccess('readcreate') if mibBuilder.loadTexts: cvcmCasDBitAction.setStatus('current') cvcm_cas_bit_row_status = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 389, 1, 1, 1, 1, 12), row_status()).setMaxAccess('readcreate') if mibBuilder.loadTexts: cvcmCasBitRowStatus.setStatus('current') cvcm_mib_conformance = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 389, 2)) cvcm_mib_groups = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 389, 2, 1)) cvcm_mib_compliances = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 389, 2, 2)) cisco_voice_cas_module_mib_compliance = module_compliance((1, 3, 6, 1, 4, 1, 9, 9, 389, 2, 2, 1)).setObjects(('CISCO-VOICE-CAS-MODULE-MIB', 'cvcmCasBitGroup')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): cisco_voice_cas_module_mib_compliance = ciscoVoiceCasModuleMIBCompliance.setStatus('current') cvcm_cas_bit_group = object_group((1, 3, 6, 1, 4, 1, 9, 9, 389, 2, 1, 1)).setObjects(('CISCO-VOICE-CAS-MODULE-MIB', 'cvcmModulePhysicalIndex'), ('CISCO-VOICE-CAS-MODULE-MIB', 'cvcmCasTemplateName'), ('CISCO-VOICE-CAS-MODULE-MIB', 'cvcmABCDIncomingPattern'), ('CISCO-VOICE-CAS-MODULE-MIB', 'cvcmABCDOutgoingPattern'), ('CISCO-VOICE-CAS-MODULE-MIB', 'cvcmCasABitAction'), ('CISCO-VOICE-CAS-MODULE-MIB', 'cvcmCasBBitAction'), ('CISCO-VOICE-CAS-MODULE-MIB', 'cvcmCasCBitAction'), ('CISCO-VOICE-CAS-MODULE-MIB', 'cvcmCasDBitAction'), ('CISCO-VOICE-CAS-MODULE-MIB', 'cvcmCasBitRowStatus')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): cvcm_cas_bit_group = cvcmCasBitGroup.setStatus('current') mibBuilder.exportSymbols('CISCO-VOICE-CAS-MODULE-MIB', cvcmModulePhysicalIndex=cvcmModulePhysicalIndex, ciscoVoiceCasModuleMIB=ciscoVoiceCasModuleMIB, cvcmModuleIndex=cvcmModuleIndex, CvcmCasBitAction=CvcmCasBitAction, cvcmMIBCompliances=cvcmMIBCompliances, PYSNMP_MODULE_ID=ciscoVoiceCasModuleMIB, cvcmABCDOutgoingPattern=cvcmABCDOutgoingPattern, cvcmCasTemplateName=cvcmCasTemplateName, cvcmABCDIncomingPattern=cvcmABCDIncomingPattern, cvcmCasABitAction=cvcmCasABitAction, cvcmCasCBitAction=cvcmCasCBitAction, cvcmCasTemplateIndex=cvcmCasTemplateIndex, cvcmABCDPatternIndex=cvcmABCDPatternIndex, ciscoVoiceCasModuleMIBCompliance=ciscoVoiceCasModuleMIBCompliance, cvcmABCDBitTemplateConfigEntry=cvcmABCDBitTemplateConfigEntry, cvcmCasBitGroup=cvcmCasBitGroup, ciscoVoiceCasModuleNotifs=ciscoVoiceCasModuleNotifs, cvcmCasConfig=cvcmCasConfig, cvcmMIBConformance=cvcmMIBConformance, cvcmCasBitRowStatus=cvcmCasBitRowStatus, ciscoVoiceCasModuleObjects=ciscoVoiceCasModuleObjects, CvcmCasPatternBitPosition=CvcmCasPatternBitPosition, cvcmCasBBitAction=cvcmCasBBitAction, cvcmABCDBitTemplateConfigTable=cvcmABCDBitTemplateConfigTable, cvcmMIBGroups=cvcmMIBGroups, cvcmCasDBitAction=cvcmCasDBitAction)
# # PySNMP MIB module CISCOSB-rlInterfaces (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCOSB-rlInterfaces # Produced by pysmi-0.3.4 at Wed May 1 12:24:20 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") ConstraintsIntersection, SingleValueConstraint, ValueSizeConstraint, ConstraintsUnion, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "SingleValueConstraint", "ValueSizeConstraint", "ConstraintsUnion", "ValueRangeConstraint") rlIfInterfaces, switch001 = mibBuilder.importSymbols("CISCOSB-MIB", "rlIfInterfaces", "switch001") InterfaceIndexOrZero, ifIndex, InterfaceIndex = mibBuilder.importSymbols("IF-MIB", "InterfaceIndexOrZero", "ifIndex", "InterfaceIndex") PortList, = mibBuilder.importSymbols("Q-BRIDGE-MIB", "PortList") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") Counter32, Gauge32, Unsigned32, MibScalar, MibTable, MibTableRow, MibTableColumn, Counter64, Bits, iso, ObjectIdentity, TimeTicks, IpAddress, ModuleIdentity, MibIdentifier, NotificationType, Integer32 = mibBuilder.importSymbols("SNMPv2-SMI", "Counter32", "Gauge32", "Unsigned32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Counter64", "Bits", "iso", "ObjectIdentity", "TimeTicks", "IpAddress", "ModuleIdentity", "MibIdentifier", "NotificationType", "Integer32") RowStatus, DisplayString, TruthValue, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "RowStatus", "DisplayString", "TruthValue", "TextualConvention") swInterfaces = ModuleIdentity((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43)) swInterfaces.setRevisions(('2013-04-01 00:00',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: swInterfaces.setRevisionsDescriptions(('Added MODULE-IDENTITY',)) if mibBuilder.loadTexts: swInterfaces.setLastUpdated('201304010000Z') if mibBuilder.loadTexts: swInterfaces.setOrganization('Cisco Small Business') if mibBuilder.loadTexts: swInterfaces.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: swInterfaces.setDescription('The private MIB module definition for Switch Interfaces.') class AutoNegCapabilitiesBits(TextualConvention, Bits): description = 'Auto negotiation capabilities bits.' status = 'current' namedValues = NamedValues(("default", 0), ("unknown", 1), ("tenHalf", 2), ("tenFull", 3), ("fastHalf", 4), ("fastFull", 5), ("gigaHalf", 6), ("gigaFull", 7), ("tenGigaFull", 8)) swIfTable = MibTable((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1), ) if mibBuilder.loadTexts: swIfTable.setStatus('current') if mibBuilder.loadTexts: swIfTable.setDescription('Switch media specific information and configuration of the device interfaces.') swIfEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1), ).setIndexNames((0, "CISCOSB-rlInterfaces", "swIfIndex")) if mibBuilder.loadTexts: swIfEntry.setStatus('current') if mibBuilder.loadTexts: swIfEntry.setDescription('Defines the contents of each line in the swIfTable table.') swIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: swIfIndex.setStatus('current') if mibBuilder.loadTexts: swIfIndex.setDescription('Index to the swIfTable. The interface defined by a particular value of this index is the same interface as identified by the same value of ifIndex (MIB II).') swIfPhysAddressType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("default", 1), ("reserve", 2))).clone('default')).setMaxAccess("readwrite") if mibBuilder.loadTexts: swIfPhysAddressType.setStatus('obsolete') if mibBuilder.loadTexts: swIfPhysAddressType.setDescription(' This variable indicates whether the physical address assigned to this interface should be the default one or be chosen from the set of reserved physical addresses of the device.') swIfDuplexAdminMode = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("none", 1), ("half", 2), ("full", 3))).clone('none')).setMaxAccess("readwrite") if mibBuilder.loadTexts: swIfDuplexAdminMode.setStatus('current') if mibBuilder.loadTexts: swIfDuplexAdminMode.setDescription("This variable specifies whether this interface should operate in half duplex or full duplex mode. This specification will take effect only if swIfSpeedDuplexAutoNegotiation is disabled. A value of 'none' is returned if a value of the variable hasn't been set.") swIfDuplexOperMode = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("half", 1), ("full", 2), ("hybrid", 3), ("unknown", 4)))).setMaxAccess("readonly") if mibBuilder.loadTexts: swIfDuplexOperMode.setStatus('current') if mibBuilder.loadTexts: swIfDuplexOperMode.setDescription(' This variable indicates whether this interface operates in half duplex or full duplex mode. This variable can have the values hybrid or unknown only for a trunk. unknown - only if trunk operative status is not present.') swIfBackPressureMode = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: swIfBackPressureMode.setStatus('current') if mibBuilder.loadTexts: swIfBackPressureMode.setDescription('This variable indicates whether this interface activates back pressure when congested.') swIfTaggedMode = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('disable')).setMaxAccess("readwrite") if mibBuilder.loadTexts: swIfTaggedMode.setStatus('current') if mibBuilder.loadTexts: swIfTaggedMode.setDescription('If enable, this interface operates in tagged mode, i.e all frames sent out through this interface will have the 802.1Q header. If disabled the frames will not be tagged.') swIfTransceiverType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("regular", 1), ("fiberOptics", 2), ("comboRegular", 3), ("comboFiberOptics", 4)))).setMaxAccess("readonly") if mibBuilder.loadTexts: swIfTransceiverType.setStatus('current') if mibBuilder.loadTexts: swIfTransceiverType.setDescription(' This variable indicates the transceiver type of this interface.') swIfLockAdminStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("locked", 1), ("unlocked", 2))).clone('unlocked')).setMaxAccess("readwrite") if mibBuilder.loadTexts: swIfLockAdminStatus.setStatus('current') if mibBuilder.loadTexts: swIfLockAdminStatus.setDescription('This variable indicates whether this interface should operate in locked or unlocked mode. In unlocked mode the device learns all MAC addresses from this port and forwards all frames arrived at this port. In locked mode no new MAC addresses are learned and only frames with known source MAC addresses are forwarded.') swIfLockOperStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("locked", 1), ("unlocked", 2)))).setMaxAccess("readonly") if mibBuilder.loadTexts: swIfLockOperStatus.setStatus('current') if mibBuilder.loadTexts: swIfLockOperStatus.setDescription('This variable defines whether this interface operates in locked or unlocked mode. It is locked in each of the following two cases: 1) if swLockAdminStatus is set to locked 2) no IP/IPX interface is defined over this interface and no VLAN contains this interface. In unlocked mode the device learns all MAC addresses from this port and forwards all frames arrived at this port. In locked mode no new MAC addresses are learned and only frames with known source MAC addresses are forwarded.') swIfType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("eth10M", 1), ("eth100M", 2), ("eth1000M", 3), ("eth10G", 4), ("unknown", 5)))).setMaxAccess("readonly") if mibBuilder.loadTexts: swIfType.setStatus('current') if mibBuilder.loadTexts: swIfType.setDescription(' This variable specifies the type of interface.') swIfDefaultTag = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 11), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 4095))).setMaxAccess("readonly") if mibBuilder.loadTexts: swIfDefaultTag.setStatus('current') if mibBuilder.loadTexts: swIfDefaultTag.setDescription('This variable specifies the default VLAN tag which will be attached to outgoing frames if swIfTaggedMode for this interface is enabled.') swIfDefaultPriority = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 12), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 7))).setMaxAccess("readwrite") if mibBuilder.loadTexts: swIfDefaultPriority.setStatus('current') if mibBuilder.loadTexts: swIfDefaultPriority.setDescription(' This variable specifies the default port priority.') swIfStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 13), RowStatus()).setMaxAccess("readwrite") if mibBuilder.loadTexts: swIfStatus.setStatus('current') if mibBuilder.loadTexts: swIfStatus.setDescription('The status of a table entry. It is used to delete an entry from this table.') swIfFlowControlMode = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 14), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("on", 1), ("off", 2), ("autoNegotiation", 3), ("enabledRx", 4), ("enabledTx", 5)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: swIfFlowControlMode.setStatus('current') if mibBuilder.loadTexts: swIfFlowControlMode.setDescription("on - Flow control will be enabled on this interface according to the IEEE 802.3x standard. off - Flow control is disabled. autoNegotiation - Flow control will be enabled or disabled on this interface. If enabled, it will operate as specified by the IEEE 802.3x standard. enabledRx - Flow control will be enabled on this interface for recieved frames. enabledTx - Flow control will be enabled on this interface for transmitted frames. An attempt to set this object to 'enabledRx(4)' or 'enabledTx(5)' will fail on interfaces that do not support operation at greater than 100 Mb/s. In any case, flow control can work only if swIfDuplexOperMode is full.") swIfSpeedAdminMode = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 15), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: swIfSpeedAdminMode.setStatus('current') if mibBuilder.loadTexts: swIfSpeedAdminMode.setDescription("This variable specifies the required speed of this interface in bits per second. This specification will take effect only if swIfSpeedDuplexAutoNegotiation is disabled. A value of 10 is returned for 10G. A value of 0 is returned if the value of the variable hasn't been set.") swIfSpeedDuplexAutoNegotiation = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 16), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: swIfSpeedDuplexAutoNegotiation.setStatus('current') if mibBuilder.loadTexts: swIfSpeedDuplexAutoNegotiation.setDescription('If enabled the speed and duplex mode will be set by the device through the autonegotiation process. Otherwise these characteristics will be set according to the values of swIfSpeedAdminMode and swIfSpeedDuplexAutoNegotiation.') swIfOperFlowControlMode = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 17), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("on", 1), ("off", 2), ("enabledRx", 3), ("enabledTx", 4)))).setMaxAccess("readonly") if mibBuilder.loadTexts: swIfOperFlowControlMode.setStatus('current') if mibBuilder.loadTexts: swIfOperFlowControlMode.setDescription('on - Flow control is enabled on this interface according to the IEEE 802.3x standard. off - Flow control is disabled. enabledRx - Flow control is enabled on this interface for recieved frames. enabledTx - Flow control is enabled on this interface for transmitted frames.') swIfOperSpeedDuplexAutoNegotiation = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 18), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2), ("hybrid", 3), ("unknown", 4)))).setMaxAccess("readonly") if mibBuilder.loadTexts: swIfOperSpeedDuplexAutoNegotiation.setStatus('current') if mibBuilder.loadTexts: swIfOperSpeedDuplexAutoNegotiation.setDescription('If enabled the speed and duplex are determined by the device through the autonegotiation process. If disabled these characteristics are determined according to the values of swIfSpeedAdminMode and swIfDuplexAdminMode. hybrid - only for a trunk. unknown - only for ports that there operative status is not present.') swIfOperBackPressureMode = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 19), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2), ("hybrid", 3), ("unknown", 4)))).setMaxAccess("readonly") if mibBuilder.loadTexts: swIfOperBackPressureMode.setStatus('current') if mibBuilder.loadTexts: swIfOperBackPressureMode.setDescription('This variable indicates the operative back pressure mode of this interface.') swIfAdminLockAction = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 20), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("discard", 1), ("forwardNormal", 2), ("discardDisable", 3)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: swIfAdminLockAction.setStatus('current') if mibBuilder.loadTexts: swIfAdminLockAction.setDescription('This variable indicates which action this interface should be taken in locked mode and therefore relevant only in locked mode. Possible actions: discard(1) - every packet is dropped. forwardNormal(2) - every packet is forwarded according to the DST address. discardDisable(3) - drops the first packet and suspends the port.') swIfOperLockAction = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 21), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("discard", 1), ("forwardNormal", 2), ("discardDisable", 3)))).setMaxAccess("readonly") if mibBuilder.loadTexts: swIfOperLockAction.setStatus('current') if mibBuilder.loadTexts: swIfOperLockAction.setDescription('This variable indicates which action this interface actually takes in locked mode and therefore relevant only in locked mode. Possible actions: discard(1) - every packet is dropped. forwardNormal(2) - every packet is forwarded according to the DST address. discardDisable(3) - drops the first packet and suspends the port.') swIfAdminLockTrapEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 22), TruthValue()).setMaxAccess("readwrite") if mibBuilder.loadTexts: swIfAdminLockTrapEnable.setStatus('current') if mibBuilder.loadTexts: swIfAdminLockTrapEnable.setDescription('This variable indicates whether to create a SNMP trap in the locked mode.') swIfOperLockTrapEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 23), TruthValue()).setMaxAccess("readonly") if mibBuilder.loadTexts: swIfOperLockTrapEnable.setStatus('current') if mibBuilder.loadTexts: swIfOperLockTrapEnable.setDescription('This variable indicates whether a SNMP trap can be created in the locked mode.') swIfOperSuspendedStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 24), TruthValue()).setMaxAccess("readonly") if mibBuilder.loadTexts: swIfOperSuspendedStatus.setStatus('current') if mibBuilder.loadTexts: swIfOperSuspendedStatus.setDescription('This variable indicates whether the port is suspended or not due to some feature. After reboot this value is false') swIfLockOperTrapCount = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 25), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 2147483647))).setMaxAccess("readonly") if mibBuilder.loadTexts: swIfLockOperTrapCount.setStatus('current') if mibBuilder.loadTexts: swIfLockOperTrapCount.setDescription("This variable indicates the trap counter status per ifIndex (i.e. number of received packets since the last trap sent due to a packet which was received on this ifIndex). It's relevant only in locked mode while trap is enabled.") swIfLockAdminTrapFrequency = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 26), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 1000000))).setMaxAccess("readwrite") if mibBuilder.loadTexts: swIfLockAdminTrapFrequency.setStatus('current') if mibBuilder.loadTexts: swIfLockAdminTrapFrequency.setDescription("This variable indicates the minimal frequency (in seconds) of sending a trap per ifIndex. It's relevant only in locked mode and in trap enabled.") swIfReActivate = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 27), TruthValue().clone('false')).setMaxAccess("readwrite") if mibBuilder.loadTexts: swIfReActivate.setStatus('current') if mibBuilder.loadTexts: swIfReActivate.setDescription('This variable reactivates (enables) an ifIndex (which was suspended)') swIfAdminMdix = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 28), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("cross", 1), ("normal", 2), ("auto", 3)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: swIfAdminMdix.setStatus('current') if mibBuilder.loadTexts: swIfAdminMdix.setDescription('The configuration is on a physical port, not include trunks. cross - The interface should force crossover. normal - The interface should not force crossover. auto - Auto mdix is enabled on the interface.') swIfOperMdix = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 29), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("cross", 1), ("normal", 2), ("unknown", 3)))).setMaxAccess("readonly") if mibBuilder.loadTexts: swIfOperMdix.setStatus('current') if mibBuilder.loadTexts: swIfOperMdix.setDescription('cross - The interface is in crossover mode. normal - The interface is not in crossover mode. unknown - Only for port that its operative status is not present or down.') swIfHostMode = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 30), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("single", 1), ("multiple", 2), ("multiple-auth", 3))).clone('single')).setMaxAccess("readwrite") if mibBuilder.loadTexts: swIfHostMode.setStatus('current') if mibBuilder.loadTexts: swIfHostMode.setDescription("This variable indicates the 802.1X host mode of a port. Relevant when the port's 802.1X control is auto. In addtion multiple-auth was added.") swIfSingleHostViolationAdminAction = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 31), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("discard", 1), ("forwardNormal", 2), ("discardDisable", 3))).clone('discard')).setMaxAccess("readwrite") if mibBuilder.loadTexts: swIfSingleHostViolationAdminAction.setStatus('current') if mibBuilder.loadTexts: swIfSingleHostViolationAdminAction.setDescription('This variable indicates which action this interface should take in single authorized. Possible actions: discard - every packet is dropped. forwardNormal - every packet is forwarded according to the DST address. discardDisable - drops the first packet and suspends the port.') swIfSingleHostViolationOperAction = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 32), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("discard", 1), ("forwardNormal", 2), ("discardDisable", 3))).clone('discard')).setMaxAccess("readonly") if mibBuilder.loadTexts: swIfSingleHostViolationOperAction.setStatus('current') if mibBuilder.loadTexts: swIfSingleHostViolationOperAction.setDescription('This variable indicates which action this interface actually takes in single authorized. Possible actions: discard(1) - every packet is dropped. forwardNormal(2) - every packet is forwarded according to the DST address. discardDisable(3) - drops the first packet and suspends the port.') swIfSingleHostViolationAdminTrapEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 33), TruthValue().clone('false')).setMaxAccess("readwrite") if mibBuilder.loadTexts: swIfSingleHostViolationAdminTrapEnable.setStatus('current') if mibBuilder.loadTexts: swIfSingleHostViolationAdminTrapEnable.setDescription('This variable indicates whether to create a SNMP trap in single authorized.') swIfSingleHostViolationOperTrapEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 34), TruthValue()).setMaxAccess("readonly") if mibBuilder.loadTexts: swIfSingleHostViolationOperTrapEnable.setStatus('current') if mibBuilder.loadTexts: swIfSingleHostViolationOperTrapEnable.setDescription('This variable indicates whether a SNMP trap can be created in the single authorized.') swIfSingleHostViolationOperTrapCount = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 35), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 2147483647))).setMaxAccess("readonly") if mibBuilder.loadTexts: swIfSingleHostViolationOperTrapCount.setStatus('current') if mibBuilder.loadTexts: swIfSingleHostViolationOperTrapCount.setDescription("This variable indicates the trap counter status per ifIndex (i.e. number of received packets since the last trap sent due to a packet which was received on this ifIndex). It's relevant only in single authorized while trap is enabled.") swIfSingleHostViolationAdminTrapFrequency = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 36), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 1000000))).setMaxAccess("readwrite") if mibBuilder.loadTexts: swIfSingleHostViolationAdminTrapFrequency.setStatus('current') if mibBuilder.loadTexts: swIfSingleHostViolationAdminTrapFrequency.setDescription("This variable indicates the minimal frequency (in seconds) of sending a trap per ifIndex. It's relevant only in single authorized and in trap enabled. A value of 0 means that trap is disabled.") swIfLockLimitationMode = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 37), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("disabled", 1), ("dynamic", 2), ("secure-permanent", 3), ("secure-delete-on-reset", 4)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: swIfLockLimitationMode.setStatus('current') if mibBuilder.loadTexts: swIfLockLimitationMode.setDescription("This variable indicates what is the learning limitation on the locked interface. Possible values: disabled - learning is stopped. The dynamic addresses associated with the port are not aged out or relearned on other port as long as the port is locked. dynamic - dynamic addresses can be learned up to the maximum dynamic addresses allowed on the port. Relearning and aging of the dynamic addresses are enabled. The learned addresses aren't kept after reset. secure-permanent - secure addresses can be learned up to the maximum addresses allowed on the port. Relearning and aging of addresses are disabled. The learned addresses are kept after reset. secure-delete-on-reset - secure addresses can be learned up to the maximum addresses allowed on the port. Relearning and aging of addresses are disabled. The learned addresses are not kept after reset.") swIfLockMaxMacAddresses = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 38), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 2147483647)).clone(1)).setMaxAccess("readwrite") if mibBuilder.loadTexts: swIfLockMaxMacAddresses.setStatus('current') if mibBuilder.loadTexts: swIfLockMaxMacAddresses.setDescription("This variable defines the maximum number of dynamic addresses that can be asscoiated with the locked interface. It isn't relevant in disabled limitation mode.") swIfLockMacAddressesCount = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 39), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 2147483647))).setMaxAccess("readonly") if mibBuilder.loadTexts: swIfLockMacAddressesCount.setStatus('current') if mibBuilder.loadTexts: swIfLockMacAddressesCount.setDescription("This variable indicates the actual number of dynamic addresses that can be asscoiated with the locked interface. It isn't relevant in disabled limitation mode.") swIfAdminSpeedDuplexAutoNegotiationLocalCapabilities = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 40), AutoNegCapabilitiesBits().clone(namedValues=NamedValues(("default", 0)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: swIfAdminSpeedDuplexAutoNegotiationLocalCapabilities.setStatus('current') if mibBuilder.loadTexts: swIfAdminSpeedDuplexAutoNegotiationLocalCapabilities.setDescription("Administrative auto negotiation capabilities of the interface that can be advertised when swIfSpeedDuplexAutoNegotiation is enabled. default bit means advertise all the port's capabilities according to its type.") swIfOperSpeedDuplexAutoNegotiationLocalCapabilities = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 41), AutoNegCapabilitiesBits()).setMaxAccess("readonly") if mibBuilder.loadTexts: swIfOperSpeedDuplexAutoNegotiationLocalCapabilities.setStatus('current') if mibBuilder.loadTexts: swIfOperSpeedDuplexAutoNegotiationLocalCapabilities.setDescription('Operative auto negotiation capabilities of the remote link. unknown bit means that port operative status is not up.') swIfSpeedDuplexNegotiationRemoteCapabilities = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 42), AutoNegCapabilitiesBits()).setMaxAccess("readonly") if mibBuilder.loadTexts: swIfSpeedDuplexNegotiationRemoteCapabilities.setStatus('current') if mibBuilder.loadTexts: swIfSpeedDuplexNegotiationRemoteCapabilities.setDescription('Operative auto negotiation capabilities of the remote link. unknown bit means that port operative status is not up, or auto negotiation process not complete, or remote link is not auto negotiation able.') swIfAdminComboMode = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 43), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("force-fiber", 1), ("force-copper", 2), ("prefer-fiber", 3), ("prefer-copper", 4))).clone('prefer-fiber')).setMaxAccess("readwrite") if mibBuilder.loadTexts: swIfAdminComboMode.setStatus('current') if mibBuilder.loadTexts: swIfAdminComboMode.setDescription('This variable specifies the administrative mode of a combo Ethernet interface.') swIfOperComboMode = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 44), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("fiber", 1), ("copper", 2), ("unknown", 3)))).setMaxAccess("readonly") if mibBuilder.loadTexts: swIfOperComboMode.setStatus('current') if mibBuilder.loadTexts: swIfOperComboMode.setDescription('This variable specifies the operative mode of a combo Ethernet interface.') swIfAutoNegotiationMasterSlavePreference = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 45), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("preferMaster", 1), ("preferSlave", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: swIfAutoNegotiationMasterSlavePreference.setStatus('current') if mibBuilder.loadTexts: swIfAutoNegotiationMasterSlavePreference.setDescription('This variable specifies the administrative mode of the Maste-Slave preference in auto negotiation.') swIfMibVersion = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: swIfMibVersion.setStatus('current') if mibBuilder.loadTexts: swIfMibVersion.setDescription("The swIfTable Mib's version, the current version is 3.") swIfPortLockSupport = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("supported", 1), ("notSupported", 2)))).setMaxAccess("readonly") if mibBuilder.loadTexts: swIfPortLockSupport.setStatus('current') if mibBuilder.loadTexts: swIfPortLockSupport.setDescription('indicates if the locked port package is supported.') swIfPortLockActionSupport = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 4), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 1)).setFixedLength(1)).setMaxAccess("readonly") if mibBuilder.loadTexts: swIfPortLockActionSupport.setStatus('current') if mibBuilder.loadTexts: swIfPortLockActionSupport.setDescription('indicates which port lock actions are supported: (bit 0 is the most significant bit) bit 0 - discard bit 1 - forwardNormal bit 2 - discardDisable') swIfPortLockTrapSupport = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 5), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 1)).setFixedLength(1)).setMaxAccess("readonly") if mibBuilder.loadTexts: swIfPortLockTrapSupport.setStatus('current') if mibBuilder.loadTexts: swIfPortLockTrapSupport.setDescription('indicates with which port lock actions the trap option is supported (e.g. discard indicates that trap is supported only when the portlock action is discard): (bit 0 is the most significant bit) bit 0 - discard bit 1 - forwardNormal bit 2 - discardDisable') swIfPortLockIfRangeTable = MibTable((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 6), ) if mibBuilder.loadTexts: swIfPortLockIfRangeTable.setStatus('current') if mibBuilder.loadTexts: swIfPortLockIfRangeTable.setDescription('Port lock interfaces range configuration') swIfPortLockIfRangeEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 6, 1), ).setIndexNames((0, "CISCOSB-rlInterfaces", "swIfPortLockIfRangeIndex")) if mibBuilder.loadTexts: swIfPortLockIfRangeEntry.setStatus('current') if mibBuilder.loadTexts: swIfPortLockIfRangeEntry.setDescription('Defines the contents of each line in the swIfPortLockIfRangeTable table.') swIfPortLockIfRangeIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 6, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: swIfPortLockIfRangeIndex.setStatus('current') if mibBuilder.loadTexts: swIfPortLockIfRangeIndex.setDescription('Index to the swIfPortLockIfRangeTable.') swIfPortLockIfRange = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 6, 1, 2), PortList()).setMaxAccess("readwrite") if mibBuilder.loadTexts: swIfPortLockIfRange.setStatus('current') if mibBuilder.loadTexts: swIfPortLockIfRange.setDescription('The set of interfaces to which the port lock parameters should be configured') swIfPortLockIfRangeLockStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 6, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("locked", 1), ("unlocked", 2))).clone('unlocked')).setMaxAccess("readwrite") if mibBuilder.loadTexts: swIfPortLockIfRangeLockStatus.setStatus('current') if mibBuilder.loadTexts: swIfPortLockIfRangeLockStatus.setDescription('This variable indicates whether the interfaces range should operate in locked or unlocked mode. In unlocked mode the device learns all MAC addresses from these interfaces and forwards all frames arrived at these interfaces. In locked mode no new MAC addresses are learned and only frames with known source MAC addresses are forwarded.') swIfPortLockIfRangeAction = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 6, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("discard", 1), ("forwardNormal", 2), ("discardDisable", 3)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: swIfPortLockIfRangeAction.setStatus('current') if mibBuilder.loadTexts: swIfPortLockIfRangeAction.setDescription('This variable indicates which action for these interfaces should be take in locked mode and therefore relevant only in locked mode. Possible actions: discard(1) - every packet is dropped. forwardNormal(2) - every packet is forwarded according to the DST address. discardDisable(3) - drops the first packet and suspends the port.') swIfPortLockIfRangeTrapEn = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 6, 1, 5), TruthValue()).setMaxAccess("readwrite") if mibBuilder.loadTexts: swIfPortLockIfRangeTrapEn.setStatus('current') if mibBuilder.loadTexts: swIfPortLockIfRangeTrapEn.setDescription('This variable indicates whether to create a SNMP trap in the locked mode.') swIfPortLockIfRangeTrapFreq = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 6, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 1000000))).setMaxAccess("readwrite") if mibBuilder.loadTexts: swIfPortLockIfRangeTrapFreq.setStatus('current') if mibBuilder.loadTexts: swIfPortLockIfRangeTrapFreq.setDescription("This variable indicates the minimal frequency (in seconds) of sending a trap for these interfaces. It's relevant only in locked mode and in trap enabled.") swIfExtTable = MibTable((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 7), ) if mibBuilder.loadTexts: swIfExtTable.setStatus('current') if mibBuilder.loadTexts: swIfExtTable.setDescription('Display information and configuration of the device interfaces.') swIfExtEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 7, 1), ).setIndexNames((0, "IF-MIB", "ifIndex")) if mibBuilder.loadTexts: swIfExtEntry.setStatus('current') if mibBuilder.loadTexts: swIfExtEntry.setDescription('Defines the contents of each row in the swIfExtTable.') swIfExtSFPSpeed = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 7, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("default", 1), ("eth100M", 2), ("eth1G", 3))).clone('default')).setMaxAccess("readwrite") if mibBuilder.loadTexts: swIfExtSFPSpeed.setStatus('current') if mibBuilder.loadTexts: swIfExtSFPSpeed.setDescription('Configure speed of an SFP Ethernet interface.') rlIfMibVersion = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: rlIfMibVersion.setStatus('current') if mibBuilder.loadTexts: rlIfMibVersion.setDescription("MIB's version, the current version is 1.") rlIfNumOfPhPorts = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: rlIfNumOfPhPorts.setStatus('current') if mibBuilder.loadTexts: rlIfNumOfPhPorts.setDescription('Total number of physical ports on this device (including all stack units)') rlIfMapOfOnPhPorts = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 3), OctetString()).setMaxAccess("readonly") if mibBuilder.loadTexts: rlIfMapOfOnPhPorts.setStatus('current') if mibBuilder.loadTexts: rlIfMapOfOnPhPorts.setDescription("Each bit in this octet string indicates that the correspondig port's ifOperStatus is ON if set. The mapping of port number to bits in this octet string is as follows: The port with the L2 interface number 1 is mapped to the least significant bit of the 1st octet, the port with L2 ifNumber 2 to the next significant bit in the 1st octet, port 8 to the most-significant bit of the in the 1st octet, port 9 to the least significant bit of the 2nd octet, etc. and in general, port n to bit corresponding to 2**((n mod 8) -1) in byte n/8 + 1") rlIfClearPortMibCounters = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 4), PortList()).setMaxAccess("readwrite") if mibBuilder.loadTexts: rlIfClearPortMibCounters.setStatus('current') if mibBuilder.loadTexts: rlIfClearPortMibCounters.setDescription('Each bit that is set in this portList represent a port that its mib counters should be reset.') rlIfNumOfUserDefinedPorts = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 5), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: rlIfNumOfUserDefinedPorts.setStatus('current') if mibBuilder.loadTexts: rlIfNumOfUserDefinedPorts.setDescription('The number of user defined ports on this device.') rlIfFirstOutOfBandIfIndex = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 6), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: rlIfFirstOutOfBandIfIndex.setStatus('current') if mibBuilder.loadTexts: rlIfFirstOutOfBandIfIndex.setDescription('First ifIndex of out-of-band port. This scalar exists only the device has out of band ports.') rlIfNumOfLoopbackPorts = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 7), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: rlIfNumOfLoopbackPorts.setStatus('current') if mibBuilder.loadTexts: rlIfNumOfLoopbackPorts.setDescription('The number of loopback ports on this device.') rlIfFirstLoopbackIfIndex = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 8), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: rlIfFirstLoopbackIfIndex.setStatus('current') if mibBuilder.loadTexts: rlIfFirstLoopbackIfIndex.setDescription('First ifIndex of loopback port. This scalar will exists only if rlIfNumOfLoopbackPorts is different from 0.') rlIfExistingPortList = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 9), PortList()).setMaxAccess("readonly") if mibBuilder.loadTexts: rlIfExistingPortList.setStatus('current') if mibBuilder.loadTexts: rlIfExistingPortList.setDescription("Indicates which ports/trunks exist in the system. It doesn't indicate which are present.") rlIfBaseMACAddressPerIfIndex = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 10), TruthValue()).setMaxAccess("readwrite") if mibBuilder.loadTexts: rlIfBaseMACAddressPerIfIndex.setStatus('current') if mibBuilder.loadTexts: rlIfBaseMACAddressPerIfIndex.setDescription('Indicates if the system will assign a unique MAC per Ethernet port or not.') rlFlowControlCascadeMode = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: rlFlowControlCascadeMode.setStatus('current') if mibBuilder.loadTexts: rlFlowControlCascadeMode.setDescription('enable disable flow control on cascade ports') rlFlowControlCascadeType = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 12), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("internalonly", 1), ("internalexternal", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: rlFlowControlCascadeType.setStatus('current') if mibBuilder.loadTexts: rlFlowControlCascadeType.setDescription('define which type of ports will be affected by flow control on cascade ports') rlFlowControlRxPerSystem = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 13), TruthValue()).setMaxAccess("readwrite") if mibBuilder.loadTexts: rlFlowControlRxPerSystem.setStatus('current') if mibBuilder.loadTexts: rlFlowControlRxPerSystem.setDescription('define if flow control RX is supported per system.') rlCascadePortProtectionAction = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 14), TruthValue()).setMaxAccess("readwrite") if mibBuilder.loadTexts: rlCascadePortProtectionAction.setStatus('current') if mibBuilder.loadTexts: rlCascadePortProtectionAction.setDescription('As a result of this set all of the local cascade ports will stop being consider unstable and will be force up.') rlManagementIfIndex = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 15), InterfaceIndex()).setMaxAccess("readwrite") if mibBuilder.loadTexts: rlManagementIfIndex.setStatus('current') if mibBuilder.loadTexts: rlManagementIfIndex.setDescription('Specify L2 bound management interface index in a single IP address system when configurable management interface is supported.') rlIfClearStackPortsCounters = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 16), TruthValue()).setMaxAccess("readwrite") if mibBuilder.loadTexts: rlIfClearStackPortsCounters.setStatus('current') if mibBuilder.loadTexts: rlIfClearStackPortsCounters.setDescription('As a result of this set all counters of all external cascade ports will be cleared.') rlIfClearPortMacAddresses = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 17), InterfaceIndexOrZero()).setMaxAccess("readwrite") if mibBuilder.loadTexts: rlIfClearPortMacAddresses.setStatus('current') if mibBuilder.loadTexts: rlIfClearPortMacAddresses.setDescription('if port is non secure, its all dynamic MAC addresses are cleared. if port is secure, its all secure MAC addresses which have learned or configured are cleared.') rlIfCutThroughPacketLength = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 18), Integer32().subtype(subtypeSpec=ValueRangeConstraint(257, 16383)).clone(1522)).setMaxAccess("readwrite") if mibBuilder.loadTexts: rlIfCutThroughPacketLength.setStatus('current') if mibBuilder.loadTexts: rlIfCutThroughPacketLength.setDescription('The default packet length that is assigned to a packet in the Cut-Through mode.') rlIfCutPriorityZero = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 19), TruthValue().clone('false')).setMaxAccess("readwrite") if mibBuilder.loadTexts: rlIfCutPriorityZero.setStatus('current') if mibBuilder.loadTexts: rlIfCutPriorityZero.setDescription('Enable or disable cut-Through for priority 0.') rlIfCutPriorityOne = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 20), TruthValue().clone('false')).setMaxAccess("readwrite") if mibBuilder.loadTexts: rlIfCutPriorityOne.setStatus('current') if mibBuilder.loadTexts: rlIfCutPriorityOne.setDescription('Enable or disable cut-Through for priority 1.') rlIfCutPriorityTwo = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 21), TruthValue().clone('false')).setMaxAccess("readwrite") if mibBuilder.loadTexts: rlIfCutPriorityTwo.setStatus('current') if mibBuilder.loadTexts: rlIfCutPriorityTwo.setDescription('Enable or disable cut-Through for priority 2.') rlIfCutPriorityThree = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 22), TruthValue().clone('false')).setMaxAccess("readwrite") if mibBuilder.loadTexts: rlIfCutPriorityThree.setStatus('current') if mibBuilder.loadTexts: rlIfCutPriorityThree.setDescription('Enable or disable cut-Through for priority 3.') rlIfCutPriorityFour = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 23), TruthValue().clone('false')).setMaxAccess("readwrite") if mibBuilder.loadTexts: rlIfCutPriorityFour.setStatus('current') if mibBuilder.loadTexts: rlIfCutPriorityFour.setDescription('Enable or disable cut-Through for priority 4.') rlIfCutPriorityFive = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 24), TruthValue().clone('false')).setMaxAccess("readwrite") if mibBuilder.loadTexts: rlIfCutPriorityFive.setStatus('current') if mibBuilder.loadTexts: rlIfCutPriorityFive.setDescription('Enable or disable cut-Through for priority 5.') rlIfCutPrioritySix = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 25), TruthValue().clone('false')).setMaxAccess("readwrite") if mibBuilder.loadTexts: rlIfCutPrioritySix.setStatus('current') if mibBuilder.loadTexts: rlIfCutPrioritySix.setDescription('Enable or disable cut-Through for priority 6.') rlIfCutPrioritySeven = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 26), TruthValue().clone('false')).setMaxAccess("readwrite") if mibBuilder.loadTexts: rlIfCutPrioritySeven.setStatus('current') if mibBuilder.loadTexts: rlIfCutPrioritySeven.setDescription('Enable or disable cut-Through for priority 7.') rlIfCutThroughTable = MibTable((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 27), ) if mibBuilder.loadTexts: rlIfCutThroughTable.setStatus('current') if mibBuilder.loadTexts: rlIfCutThroughTable.setDescription('Information and configuration of cut-through feature.') rlIfCutThroughEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 27, 1), ).setIndexNames((0, "CISCOSB-rlInterfaces", "swIfIndex")) if mibBuilder.loadTexts: rlIfCutThroughEntry.setStatus('current') if mibBuilder.loadTexts: rlIfCutThroughEntry.setDescription('Defines the contents of each line in the swIfTable table.') rlIfCutThroughPriorityEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 27, 1, 1), TruthValue().clone('false')).setMaxAccess("readwrite") if mibBuilder.loadTexts: rlIfCutThroughPriorityEnable.setStatus('current') if mibBuilder.loadTexts: rlIfCutThroughPriorityEnable.setDescription('Enable or disable cut-through for a priority for an interface.') rlIfCutThroughUntaggedEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 27, 1, 2), TruthValue().clone('false')).setMaxAccess("readwrite") if mibBuilder.loadTexts: rlIfCutThroughUntaggedEnable.setStatus('current') if mibBuilder.loadTexts: rlIfCutThroughUntaggedEnable.setDescription('Enable or disable cut-through for untagged packets for an interface.') rlIfCutThroughOperMode = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 27, 1, 3), TruthValue()).setMaxAccess("readonly") if mibBuilder.loadTexts: rlIfCutThroughOperMode.setStatus('current') if mibBuilder.loadTexts: rlIfCutThroughOperMode.setDescription('Operational mode of spesific cut-through interface.') rlCutThroughPacketLength = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 28), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: rlCutThroughPacketLength.setStatus('current') if mibBuilder.loadTexts: rlCutThroughPacketLength.setDescription('The default packet length that is assigned to a packet in the Cut-Through mode.') rlCutThroughPacketLengthAfterReset = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 29), Integer32().subtype(subtypeSpec=ValueRangeConstraint(257, 16383)).clone(1522)).setMaxAccess("readwrite") if mibBuilder.loadTexts: rlCutThroughPacketLengthAfterReset.setStatus('current') if mibBuilder.loadTexts: rlCutThroughPacketLengthAfterReset.setDescription('The default packet length that is assigned to a packet in the Cut-Through mode after reset.') rlCutThroughEnable = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 30), TruthValue()).setMaxAccess("readonly") if mibBuilder.loadTexts: rlCutThroughEnable.setStatus('current') if mibBuilder.loadTexts: rlCutThroughEnable.setDescription('Cut-Through global enable mode.') rlCutThroughEnableAfterReset = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 31), TruthValue().clone('false')).setMaxAccess("readwrite") if mibBuilder.loadTexts: rlCutThroughEnableAfterReset.setStatus('current') if mibBuilder.loadTexts: rlCutThroughEnableAfterReset.setDescription('Cut-Through global enable mode after reset.') rlFlowControlMode = MibScalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 32), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("send-receive", 1), ("receive-only", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: rlFlowControlMode.setStatus('current') if mibBuilder.loadTexts: rlFlowControlMode.setDescription('Define which mode will be enabled on flow control enabled ports. The interfaces with enabled flow control will receive pause frames, but will not send flow control pause frames Send-receive: The interfaces with enabled flow control will receive and send pause frames. Receive-only: The interfaces with enabled flow control will receive pause frames, but will not send flow control pause frames.') mibBuilder.exportSymbols("CISCOSB-rlInterfaces", rlFlowControlCascadeType=rlFlowControlCascadeType, rlIfNumOfPhPorts=rlIfNumOfPhPorts, rlIfFirstLoopbackIfIndex=rlIfFirstLoopbackIfIndex, rlIfNumOfLoopbackPorts=rlIfNumOfLoopbackPorts, swIfAdminSpeedDuplexAutoNegotiationLocalCapabilities=swIfAdminSpeedDuplexAutoNegotiationLocalCapabilities, PYSNMP_MODULE_ID=swInterfaces, swIfMibVersion=swIfMibVersion, rlIfClearPortMacAddresses=rlIfClearPortMacAddresses, swIfStatus=swIfStatus, swIfOperSpeedDuplexAutoNegotiation=swIfOperSpeedDuplexAutoNegotiation, swIfSingleHostViolationOperTrapCount=swIfSingleHostViolationOperTrapCount, rlIfClearPortMibCounters=rlIfClearPortMibCounters, swIfOperFlowControlMode=swIfOperFlowControlMode, swIfAdminMdix=swIfAdminMdix, swIfDuplexAdminMode=swIfDuplexAdminMode, swIfPortLockTrapSupport=swIfPortLockTrapSupport, swIfPortLockIfRangeIndex=swIfPortLockIfRangeIndex, rlIfClearStackPortsCounters=rlIfClearStackPortsCounters, swIfTransceiverType=swIfTransceiverType, swInterfaces=swInterfaces, swIfPortLockSupport=swIfPortLockSupport, swIfDefaultTag=swIfDefaultTag, swIfSingleHostViolationAdminTrapEnable=swIfSingleHostViolationAdminTrapEnable, swIfTable=swIfTable, rlIfCutPriorityThree=rlIfCutPriorityThree, swIfOperLockTrapEnable=swIfOperLockTrapEnable, rlCascadePortProtectionAction=rlCascadePortProtectionAction, rlFlowControlRxPerSystem=rlFlowControlRxPerSystem, swIfType=swIfType, rlIfCutThroughPriorityEnable=rlIfCutThroughPriorityEnable, rlIfCutPriorityTwo=rlIfCutPriorityTwo, swIfHostMode=swIfHostMode, rlIfCutPriorityFour=rlIfCutPriorityFour, rlCutThroughPacketLengthAfterReset=rlCutThroughPacketLengthAfterReset, rlIfMibVersion=rlIfMibVersion, swIfDuplexOperMode=swIfDuplexOperMode, rlIfCutPrioritySix=rlIfCutPrioritySix, AutoNegCapabilitiesBits=AutoNegCapabilitiesBits, rlIfNumOfUserDefinedPorts=rlIfNumOfUserDefinedPorts, rlIfCutPriorityOne=rlIfCutPriorityOne, swIfPortLockActionSupport=swIfPortLockActionSupport, swIfSpeedAdminMode=swIfSpeedAdminMode, rlIfMapOfOnPhPorts=rlIfMapOfOnPhPorts, swIfSingleHostViolationOperTrapEnable=swIfSingleHostViolationOperTrapEnable, swIfOperLockAction=swIfOperLockAction, rlIfCutPrioritySeven=rlIfCutPrioritySeven, rlFlowControlMode=rlFlowControlMode, rlIfExistingPortList=rlIfExistingPortList, rlManagementIfIndex=rlManagementIfIndex, rlIfCutThroughTable=rlIfCutThroughTable, swIfLockOperStatus=swIfLockOperStatus, swIfAdminLockAction=swIfAdminLockAction, swIfOperComboMode=swIfOperComboMode, swIfBackPressureMode=swIfBackPressureMode, rlCutThroughPacketLength=rlCutThroughPacketLength, swIfDefaultPriority=swIfDefaultPriority, swIfOperBackPressureMode=swIfOperBackPressureMode, rlIfCutThroughPacketLength=rlIfCutThroughPacketLength, swIfOperMdix=swIfOperMdix, rlIfFirstOutOfBandIfIndex=rlIfFirstOutOfBandIfIndex, rlIfCutThroughOperMode=rlIfCutThroughOperMode, swIfOperSpeedDuplexAutoNegotiationLocalCapabilities=swIfOperSpeedDuplexAutoNegotiationLocalCapabilities, rlCutThroughEnable=rlCutThroughEnable, swIfOperSuspendedStatus=swIfOperSuspendedStatus, rlCutThroughEnableAfterReset=rlCutThroughEnableAfterReset, swIfSingleHostViolationAdminTrapFrequency=swIfSingleHostViolationAdminTrapFrequency, swIfAdminLockTrapEnable=swIfAdminLockTrapEnable, swIfPhysAddressType=swIfPhysAddressType, swIfSingleHostViolationOperAction=swIfSingleHostViolationOperAction, swIfExtTable=swIfExtTable, swIfPortLockIfRangeTrapEn=swIfPortLockIfRangeTrapEn, swIfPortLockIfRange=swIfPortLockIfRange, swIfPortLockIfRangeLockStatus=swIfPortLockIfRangeLockStatus, swIfLockAdminStatus=swIfLockAdminStatus, swIfReActivate=swIfReActivate, swIfPortLockIfRangeEntry=swIfPortLockIfRangeEntry, swIfLockMacAddressesCount=swIfLockMacAddressesCount, swIfLockAdminTrapFrequency=swIfLockAdminTrapFrequency, rlIfCutThroughUntaggedEnable=rlIfCutThroughUntaggedEnable, rlIfCutPriorityFive=rlIfCutPriorityFive, swIfAdminComboMode=swIfAdminComboMode, swIfIndex=swIfIndex, swIfPortLockIfRangeAction=swIfPortLockIfRangeAction, swIfFlowControlMode=swIfFlowControlMode, rlIfBaseMACAddressPerIfIndex=rlIfBaseMACAddressPerIfIndex, swIfPortLockIfRangeTrapFreq=swIfPortLockIfRangeTrapFreq, swIfEntry=swIfEntry, swIfSingleHostViolationAdminAction=swIfSingleHostViolationAdminAction, swIfExtSFPSpeed=swIfExtSFPSpeed, swIfPortLockIfRangeTable=swIfPortLockIfRangeTable, rlFlowControlCascadeMode=rlFlowControlCascadeMode, rlIfCutThroughEntry=rlIfCutThroughEntry, swIfTaggedMode=swIfTaggedMode, swIfAutoNegotiationMasterSlavePreference=swIfAutoNegotiationMasterSlavePreference, swIfSpeedDuplexAutoNegotiation=swIfSpeedDuplexAutoNegotiation, swIfLockOperTrapCount=swIfLockOperTrapCount, swIfSpeedDuplexNegotiationRemoteCapabilities=swIfSpeedDuplexNegotiationRemoteCapabilities, swIfExtEntry=swIfExtEntry, swIfLockLimitationMode=swIfLockLimitationMode, swIfLockMaxMacAddresses=swIfLockMaxMacAddresses, rlIfCutPriorityZero=rlIfCutPriorityZero)
(octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_intersection, single_value_constraint, value_size_constraint, constraints_union, value_range_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsIntersection', 'SingleValueConstraint', 'ValueSizeConstraint', 'ConstraintsUnion', 'ValueRangeConstraint') (rl_if_interfaces, switch001) = mibBuilder.importSymbols('CISCOSB-MIB', 'rlIfInterfaces', 'switch001') (interface_index_or_zero, if_index, interface_index) = mibBuilder.importSymbols('IF-MIB', 'InterfaceIndexOrZero', 'ifIndex', 'InterfaceIndex') (port_list,) = mibBuilder.importSymbols('Q-BRIDGE-MIB', 'PortList') (notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance') (counter32, gauge32, unsigned32, mib_scalar, mib_table, mib_table_row, mib_table_column, counter64, bits, iso, object_identity, time_ticks, ip_address, module_identity, mib_identifier, notification_type, integer32) = mibBuilder.importSymbols('SNMPv2-SMI', 'Counter32', 'Gauge32', 'Unsigned32', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'Counter64', 'Bits', 'iso', 'ObjectIdentity', 'TimeTicks', 'IpAddress', 'ModuleIdentity', 'MibIdentifier', 'NotificationType', 'Integer32') (row_status, display_string, truth_value, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'RowStatus', 'DisplayString', 'TruthValue', 'TextualConvention') sw_interfaces = module_identity((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43)) swInterfaces.setRevisions(('2013-04-01 00:00',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: swInterfaces.setRevisionsDescriptions(('Added MODULE-IDENTITY',)) if mibBuilder.loadTexts: swInterfaces.setLastUpdated('201304010000Z') if mibBuilder.loadTexts: swInterfaces.setOrganization('Cisco Small Business') if mibBuilder.loadTexts: swInterfaces.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: swInterfaces.setDescription('The private MIB module definition for Switch Interfaces.') class Autonegcapabilitiesbits(TextualConvention, Bits): description = 'Auto negotiation capabilities bits.' status = 'current' named_values = named_values(('default', 0), ('unknown', 1), ('tenHalf', 2), ('tenFull', 3), ('fastHalf', 4), ('fastFull', 5), ('gigaHalf', 6), ('gigaFull', 7), ('tenGigaFull', 8)) sw_if_table = mib_table((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1)) if mibBuilder.loadTexts: swIfTable.setStatus('current') if mibBuilder.loadTexts: swIfTable.setDescription('Switch media specific information and configuration of the device interfaces.') sw_if_entry = mib_table_row((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1)).setIndexNames((0, 'CISCOSB-rlInterfaces', 'swIfIndex')) if mibBuilder.loadTexts: swIfEntry.setStatus('current') if mibBuilder.loadTexts: swIfEntry.setDescription('Defines the contents of each line in the swIfTable table.') sw_if_index = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 1), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: swIfIndex.setStatus('current') if mibBuilder.loadTexts: swIfIndex.setDescription('Index to the swIfTable. The interface defined by a particular value of this index is the same interface as identified by the same value of ifIndex (MIB II).') sw_if_phys_address_type = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('default', 1), ('reserve', 2))).clone('default')).setMaxAccess('readwrite') if mibBuilder.loadTexts: swIfPhysAddressType.setStatus('obsolete') if mibBuilder.loadTexts: swIfPhysAddressType.setDescription(' This variable indicates whether the physical address assigned to this interface should be the default one or be chosen from the set of reserved physical addresses of the device.') sw_if_duplex_admin_mode = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 3), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('none', 1), ('half', 2), ('full', 3))).clone('none')).setMaxAccess('readwrite') if mibBuilder.loadTexts: swIfDuplexAdminMode.setStatus('current') if mibBuilder.loadTexts: swIfDuplexAdminMode.setDescription("This variable specifies whether this interface should operate in half duplex or full duplex mode. This specification will take effect only if swIfSpeedDuplexAutoNegotiation is disabled. A value of 'none' is returned if a value of the variable hasn't been set.") sw_if_duplex_oper_mode = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 4), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4))).clone(namedValues=named_values(('half', 1), ('full', 2), ('hybrid', 3), ('unknown', 4)))).setMaxAccess('readonly') if mibBuilder.loadTexts: swIfDuplexOperMode.setStatus('current') if mibBuilder.loadTexts: swIfDuplexOperMode.setDescription(' This variable indicates whether this interface operates in half duplex or full duplex mode. This variable can have the values hybrid or unknown only for a trunk. unknown - only if trunk operative status is not present.') sw_if_back_pressure_mode = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 5), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('enable', 1), ('disable', 2)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: swIfBackPressureMode.setStatus('current') if mibBuilder.loadTexts: swIfBackPressureMode.setDescription('This variable indicates whether this interface activates back pressure when congested.') sw_if_tagged_mode = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 6), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('enable', 1), ('disable', 2))).clone('disable')).setMaxAccess('readwrite') if mibBuilder.loadTexts: swIfTaggedMode.setStatus('current') if mibBuilder.loadTexts: swIfTaggedMode.setDescription('If enable, this interface operates in tagged mode, i.e all frames sent out through this interface will have the 802.1Q header. If disabled the frames will not be tagged.') sw_if_transceiver_type = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 7), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4))).clone(namedValues=named_values(('regular', 1), ('fiberOptics', 2), ('comboRegular', 3), ('comboFiberOptics', 4)))).setMaxAccess('readonly') if mibBuilder.loadTexts: swIfTransceiverType.setStatus('current') if mibBuilder.loadTexts: swIfTransceiverType.setDescription(' This variable indicates the transceiver type of this interface.') sw_if_lock_admin_status = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 8), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('locked', 1), ('unlocked', 2))).clone('unlocked')).setMaxAccess('readwrite') if mibBuilder.loadTexts: swIfLockAdminStatus.setStatus('current') if mibBuilder.loadTexts: swIfLockAdminStatus.setDescription('This variable indicates whether this interface should operate in locked or unlocked mode. In unlocked mode the device learns all MAC addresses from this port and forwards all frames arrived at this port. In locked mode no new MAC addresses are learned and only frames with known source MAC addresses are forwarded.') sw_if_lock_oper_status = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 9), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('locked', 1), ('unlocked', 2)))).setMaxAccess('readonly') if mibBuilder.loadTexts: swIfLockOperStatus.setStatus('current') if mibBuilder.loadTexts: swIfLockOperStatus.setDescription('This variable defines whether this interface operates in locked or unlocked mode. It is locked in each of the following two cases: 1) if swLockAdminStatus is set to locked 2) no IP/IPX interface is defined over this interface and no VLAN contains this interface. In unlocked mode the device learns all MAC addresses from this port and forwards all frames arrived at this port. In locked mode no new MAC addresses are learned and only frames with known source MAC addresses are forwarded.') sw_if_type = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 10), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4, 5))).clone(namedValues=named_values(('eth10M', 1), ('eth100M', 2), ('eth1000M', 3), ('eth10G', 4), ('unknown', 5)))).setMaxAccess('readonly') if mibBuilder.loadTexts: swIfType.setStatus('current') if mibBuilder.loadTexts: swIfType.setDescription(' This variable specifies the type of interface.') sw_if_default_tag = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 11), integer32().subtype(subtypeSpec=value_range_constraint(0, 4095))).setMaxAccess('readonly') if mibBuilder.loadTexts: swIfDefaultTag.setStatus('current') if mibBuilder.loadTexts: swIfDefaultTag.setDescription('This variable specifies the default VLAN tag which will be attached to outgoing frames if swIfTaggedMode for this interface is enabled.') sw_if_default_priority = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 12), integer32().subtype(subtypeSpec=value_range_constraint(0, 7))).setMaxAccess('readwrite') if mibBuilder.loadTexts: swIfDefaultPriority.setStatus('current') if mibBuilder.loadTexts: swIfDefaultPriority.setDescription(' This variable specifies the default port priority.') sw_if_status = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 13), row_status()).setMaxAccess('readwrite') if mibBuilder.loadTexts: swIfStatus.setStatus('current') if mibBuilder.loadTexts: swIfStatus.setDescription('The status of a table entry. It is used to delete an entry from this table.') sw_if_flow_control_mode = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 14), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4, 5))).clone(namedValues=named_values(('on', 1), ('off', 2), ('autoNegotiation', 3), ('enabledRx', 4), ('enabledTx', 5)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: swIfFlowControlMode.setStatus('current') if mibBuilder.loadTexts: swIfFlowControlMode.setDescription("on - Flow control will be enabled on this interface according to the IEEE 802.3x standard. off - Flow control is disabled. autoNegotiation - Flow control will be enabled or disabled on this interface. If enabled, it will operate as specified by the IEEE 802.3x standard. enabledRx - Flow control will be enabled on this interface for recieved frames. enabledTx - Flow control will be enabled on this interface for transmitted frames. An attempt to set this object to 'enabledRx(4)' or 'enabledTx(5)' will fail on interfaces that do not support operation at greater than 100 Mb/s. In any case, flow control can work only if swIfDuplexOperMode is full.") sw_if_speed_admin_mode = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 15), integer32()).setMaxAccess('readwrite') if mibBuilder.loadTexts: swIfSpeedAdminMode.setStatus('current') if mibBuilder.loadTexts: swIfSpeedAdminMode.setDescription("This variable specifies the required speed of this interface in bits per second. This specification will take effect only if swIfSpeedDuplexAutoNegotiation is disabled. A value of 10 is returned for 10G. A value of 0 is returned if the value of the variable hasn't been set.") sw_if_speed_duplex_auto_negotiation = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 16), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('enabled', 1), ('disabled', 2)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: swIfSpeedDuplexAutoNegotiation.setStatus('current') if mibBuilder.loadTexts: swIfSpeedDuplexAutoNegotiation.setDescription('If enabled the speed and duplex mode will be set by the device through the autonegotiation process. Otherwise these characteristics will be set according to the values of swIfSpeedAdminMode and swIfSpeedDuplexAutoNegotiation.') sw_if_oper_flow_control_mode = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 17), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4))).clone(namedValues=named_values(('on', 1), ('off', 2), ('enabledRx', 3), ('enabledTx', 4)))).setMaxAccess('readonly') if mibBuilder.loadTexts: swIfOperFlowControlMode.setStatus('current') if mibBuilder.loadTexts: swIfOperFlowControlMode.setDescription('on - Flow control is enabled on this interface according to the IEEE 802.3x standard. off - Flow control is disabled. enabledRx - Flow control is enabled on this interface for recieved frames. enabledTx - Flow control is enabled on this interface for transmitted frames.') sw_if_oper_speed_duplex_auto_negotiation = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 18), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4))).clone(namedValues=named_values(('enabled', 1), ('disabled', 2), ('hybrid', 3), ('unknown', 4)))).setMaxAccess('readonly') if mibBuilder.loadTexts: swIfOperSpeedDuplexAutoNegotiation.setStatus('current') if mibBuilder.loadTexts: swIfOperSpeedDuplexAutoNegotiation.setDescription('If enabled the speed and duplex are determined by the device through the autonegotiation process. If disabled these characteristics are determined according to the values of swIfSpeedAdminMode and swIfDuplexAdminMode. hybrid - only for a trunk. unknown - only for ports that there operative status is not present.') sw_if_oper_back_pressure_mode = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 19), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4))).clone(namedValues=named_values(('enable', 1), ('disable', 2), ('hybrid', 3), ('unknown', 4)))).setMaxAccess('readonly') if mibBuilder.loadTexts: swIfOperBackPressureMode.setStatus('current') if mibBuilder.loadTexts: swIfOperBackPressureMode.setDescription('This variable indicates the operative back pressure mode of this interface.') sw_if_admin_lock_action = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 20), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('discard', 1), ('forwardNormal', 2), ('discardDisable', 3)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: swIfAdminLockAction.setStatus('current') if mibBuilder.loadTexts: swIfAdminLockAction.setDescription('This variable indicates which action this interface should be taken in locked mode and therefore relevant only in locked mode. Possible actions: discard(1) - every packet is dropped. forwardNormal(2) - every packet is forwarded according to the DST address. discardDisable(3) - drops the first packet and suspends the port.') sw_if_oper_lock_action = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 21), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('discard', 1), ('forwardNormal', 2), ('discardDisable', 3)))).setMaxAccess('readonly') if mibBuilder.loadTexts: swIfOperLockAction.setStatus('current') if mibBuilder.loadTexts: swIfOperLockAction.setDescription('This variable indicates which action this interface actually takes in locked mode and therefore relevant only in locked mode. Possible actions: discard(1) - every packet is dropped. forwardNormal(2) - every packet is forwarded according to the DST address. discardDisable(3) - drops the first packet and suspends the port.') sw_if_admin_lock_trap_enable = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 22), truth_value()).setMaxAccess('readwrite') if mibBuilder.loadTexts: swIfAdminLockTrapEnable.setStatus('current') if mibBuilder.loadTexts: swIfAdminLockTrapEnable.setDescription('This variable indicates whether to create a SNMP trap in the locked mode.') sw_if_oper_lock_trap_enable = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 23), truth_value()).setMaxAccess('readonly') if mibBuilder.loadTexts: swIfOperLockTrapEnable.setStatus('current') if mibBuilder.loadTexts: swIfOperLockTrapEnable.setDescription('This variable indicates whether a SNMP trap can be created in the locked mode.') sw_if_oper_suspended_status = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 24), truth_value()).setMaxAccess('readonly') if mibBuilder.loadTexts: swIfOperSuspendedStatus.setStatus('current') if mibBuilder.loadTexts: swIfOperSuspendedStatus.setDescription('This variable indicates whether the port is suspended or not due to some feature. After reboot this value is false') sw_if_lock_oper_trap_count = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 25), integer32().subtype(subtypeSpec=value_range_constraint(0, 2147483647))).setMaxAccess('readonly') if mibBuilder.loadTexts: swIfLockOperTrapCount.setStatus('current') if mibBuilder.loadTexts: swIfLockOperTrapCount.setDescription("This variable indicates the trap counter status per ifIndex (i.e. number of received packets since the last trap sent due to a packet which was received on this ifIndex). It's relevant only in locked mode while trap is enabled.") sw_if_lock_admin_trap_frequency = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 26), integer32().subtype(subtypeSpec=value_range_constraint(1, 1000000))).setMaxAccess('readwrite') if mibBuilder.loadTexts: swIfLockAdminTrapFrequency.setStatus('current') if mibBuilder.loadTexts: swIfLockAdminTrapFrequency.setDescription("This variable indicates the minimal frequency (in seconds) of sending a trap per ifIndex. It's relevant only in locked mode and in trap enabled.") sw_if_re_activate = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 27), truth_value().clone('false')).setMaxAccess('readwrite') if mibBuilder.loadTexts: swIfReActivate.setStatus('current') if mibBuilder.loadTexts: swIfReActivate.setDescription('This variable reactivates (enables) an ifIndex (which was suspended)') sw_if_admin_mdix = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 28), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('cross', 1), ('normal', 2), ('auto', 3)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: swIfAdminMdix.setStatus('current') if mibBuilder.loadTexts: swIfAdminMdix.setDescription('The configuration is on a physical port, not include trunks. cross - The interface should force crossover. normal - The interface should not force crossover. auto - Auto mdix is enabled on the interface.') sw_if_oper_mdix = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 29), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('cross', 1), ('normal', 2), ('unknown', 3)))).setMaxAccess('readonly') if mibBuilder.loadTexts: swIfOperMdix.setStatus('current') if mibBuilder.loadTexts: swIfOperMdix.setDescription('cross - The interface is in crossover mode. normal - The interface is not in crossover mode. unknown - Only for port that its operative status is not present or down.') sw_if_host_mode = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 30), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('single', 1), ('multiple', 2), ('multiple-auth', 3))).clone('single')).setMaxAccess('readwrite') if mibBuilder.loadTexts: swIfHostMode.setStatus('current') if mibBuilder.loadTexts: swIfHostMode.setDescription("This variable indicates the 802.1X host mode of a port. Relevant when the port's 802.1X control is auto. In addtion multiple-auth was added.") sw_if_single_host_violation_admin_action = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 31), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('discard', 1), ('forwardNormal', 2), ('discardDisable', 3))).clone('discard')).setMaxAccess('readwrite') if mibBuilder.loadTexts: swIfSingleHostViolationAdminAction.setStatus('current') if mibBuilder.loadTexts: swIfSingleHostViolationAdminAction.setDescription('This variable indicates which action this interface should take in single authorized. Possible actions: discard - every packet is dropped. forwardNormal - every packet is forwarded according to the DST address. discardDisable - drops the first packet and suspends the port.') sw_if_single_host_violation_oper_action = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 32), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('discard', 1), ('forwardNormal', 2), ('discardDisable', 3))).clone('discard')).setMaxAccess('readonly') if mibBuilder.loadTexts: swIfSingleHostViolationOperAction.setStatus('current') if mibBuilder.loadTexts: swIfSingleHostViolationOperAction.setDescription('This variable indicates which action this interface actually takes in single authorized. Possible actions: discard(1) - every packet is dropped. forwardNormal(2) - every packet is forwarded according to the DST address. discardDisable(3) - drops the first packet and suspends the port.') sw_if_single_host_violation_admin_trap_enable = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 33), truth_value().clone('false')).setMaxAccess('readwrite') if mibBuilder.loadTexts: swIfSingleHostViolationAdminTrapEnable.setStatus('current') if mibBuilder.loadTexts: swIfSingleHostViolationAdminTrapEnable.setDescription('This variable indicates whether to create a SNMP trap in single authorized.') sw_if_single_host_violation_oper_trap_enable = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 34), truth_value()).setMaxAccess('readonly') if mibBuilder.loadTexts: swIfSingleHostViolationOperTrapEnable.setStatus('current') if mibBuilder.loadTexts: swIfSingleHostViolationOperTrapEnable.setDescription('This variable indicates whether a SNMP trap can be created in the single authorized.') sw_if_single_host_violation_oper_trap_count = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 35), integer32().subtype(subtypeSpec=value_range_constraint(0, 2147483647))).setMaxAccess('readonly') if mibBuilder.loadTexts: swIfSingleHostViolationOperTrapCount.setStatus('current') if mibBuilder.loadTexts: swIfSingleHostViolationOperTrapCount.setDescription("This variable indicates the trap counter status per ifIndex (i.e. number of received packets since the last trap sent due to a packet which was received on this ifIndex). It's relevant only in single authorized while trap is enabled.") sw_if_single_host_violation_admin_trap_frequency = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 36), integer32().subtype(subtypeSpec=value_range_constraint(0, 1000000))).setMaxAccess('readwrite') if mibBuilder.loadTexts: swIfSingleHostViolationAdminTrapFrequency.setStatus('current') if mibBuilder.loadTexts: swIfSingleHostViolationAdminTrapFrequency.setDescription("This variable indicates the minimal frequency (in seconds) of sending a trap per ifIndex. It's relevant only in single authorized and in trap enabled. A value of 0 means that trap is disabled.") sw_if_lock_limitation_mode = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 37), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4))).clone(namedValues=named_values(('disabled', 1), ('dynamic', 2), ('secure-permanent', 3), ('secure-delete-on-reset', 4)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: swIfLockLimitationMode.setStatus('current') if mibBuilder.loadTexts: swIfLockLimitationMode.setDescription("This variable indicates what is the learning limitation on the locked interface. Possible values: disabled - learning is stopped. The dynamic addresses associated with the port are not aged out or relearned on other port as long as the port is locked. dynamic - dynamic addresses can be learned up to the maximum dynamic addresses allowed on the port. Relearning and aging of the dynamic addresses are enabled. The learned addresses aren't kept after reset. secure-permanent - secure addresses can be learned up to the maximum addresses allowed on the port. Relearning and aging of addresses are disabled. The learned addresses are kept after reset. secure-delete-on-reset - secure addresses can be learned up to the maximum addresses allowed on the port. Relearning and aging of addresses are disabled. The learned addresses are not kept after reset.") sw_if_lock_max_mac_addresses = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 38), integer32().subtype(subtypeSpec=value_range_constraint(0, 2147483647)).clone(1)).setMaxAccess('readwrite') if mibBuilder.loadTexts: swIfLockMaxMacAddresses.setStatus('current') if mibBuilder.loadTexts: swIfLockMaxMacAddresses.setDescription("This variable defines the maximum number of dynamic addresses that can be asscoiated with the locked interface. It isn't relevant in disabled limitation mode.") sw_if_lock_mac_addresses_count = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 39), integer32().subtype(subtypeSpec=value_range_constraint(0, 2147483647))).setMaxAccess('readonly') if mibBuilder.loadTexts: swIfLockMacAddressesCount.setStatus('current') if mibBuilder.loadTexts: swIfLockMacAddressesCount.setDescription("This variable indicates the actual number of dynamic addresses that can be asscoiated with the locked interface. It isn't relevant in disabled limitation mode.") sw_if_admin_speed_duplex_auto_negotiation_local_capabilities = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 40), auto_neg_capabilities_bits().clone(namedValues=named_values(('default', 0)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: swIfAdminSpeedDuplexAutoNegotiationLocalCapabilities.setStatus('current') if mibBuilder.loadTexts: swIfAdminSpeedDuplexAutoNegotiationLocalCapabilities.setDescription("Administrative auto negotiation capabilities of the interface that can be advertised when swIfSpeedDuplexAutoNegotiation is enabled. default bit means advertise all the port's capabilities according to its type.") sw_if_oper_speed_duplex_auto_negotiation_local_capabilities = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 41), auto_neg_capabilities_bits()).setMaxAccess('readonly') if mibBuilder.loadTexts: swIfOperSpeedDuplexAutoNegotiationLocalCapabilities.setStatus('current') if mibBuilder.loadTexts: swIfOperSpeedDuplexAutoNegotiationLocalCapabilities.setDescription('Operative auto negotiation capabilities of the remote link. unknown bit means that port operative status is not up.') sw_if_speed_duplex_negotiation_remote_capabilities = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 42), auto_neg_capabilities_bits()).setMaxAccess('readonly') if mibBuilder.loadTexts: swIfSpeedDuplexNegotiationRemoteCapabilities.setStatus('current') if mibBuilder.loadTexts: swIfSpeedDuplexNegotiationRemoteCapabilities.setDescription('Operative auto negotiation capabilities of the remote link. unknown bit means that port operative status is not up, or auto negotiation process not complete, or remote link is not auto negotiation able.') sw_if_admin_combo_mode = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 43), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4))).clone(namedValues=named_values(('force-fiber', 1), ('force-copper', 2), ('prefer-fiber', 3), ('prefer-copper', 4))).clone('prefer-fiber')).setMaxAccess('readwrite') if mibBuilder.loadTexts: swIfAdminComboMode.setStatus('current') if mibBuilder.loadTexts: swIfAdminComboMode.setDescription('This variable specifies the administrative mode of a combo Ethernet interface.') sw_if_oper_combo_mode = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 44), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('fiber', 1), ('copper', 2), ('unknown', 3)))).setMaxAccess('readonly') if mibBuilder.loadTexts: swIfOperComboMode.setStatus('current') if mibBuilder.loadTexts: swIfOperComboMode.setDescription('This variable specifies the operative mode of a combo Ethernet interface.') sw_if_auto_negotiation_master_slave_preference = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 1, 1, 45), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('preferMaster', 1), ('preferSlave', 2)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: swIfAutoNegotiationMasterSlavePreference.setStatus('current') if mibBuilder.loadTexts: swIfAutoNegotiationMasterSlavePreference.setDescription('This variable specifies the administrative mode of the Maste-Slave preference in auto negotiation.') sw_if_mib_version = mib_scalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 2), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: swIfMibVersion.setStatus('current') if mibBuilder.loadTexts: swIfMibVersion.setDescription("The swIfTable Mib's version, the current version is 3.") sw_if_port_lock_support = mib_scalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 3), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('supported', 1), ('notSupported', 2)))).setMaxAccess('readonly') if mibBuilder.loadTexts: swIfPortLockSupport.setStatus('current') if mibBuilder.loadTexts: swIfPortLockSupport.setDescription('indicates if the locked port package is supported.') sw_if_port_lock_action_support = mib_scalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 4), octet_string().subtype(subtypeSpec=value_size_constraint(1, 1)).setFixedLength(1)).setMaxAccess('readonly') if mibBuilder.loadTexts: swIfPortLockActionSupport.setStatus('current') if mibBuilder.loadTexts: swIfPortLockActionSupport.setDescription('indicates which port lock actions are supported: (bit 0 is the most significant bit) bit 0 - discard bit 1 - forwardNormal bit 2 - discardDisable') sw_if_port_lock_trap_support = mib_scalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 5), octet_string().subtype(subtypeSpec=value_size_constraint(1, 1)).setFixedLength(1)).setMaxAccess('readonly') if mibBuilder.loadTexts: swIfPortLockTrapSupport.setStatus('current') if mibBuilder.loadTexts: swIfPortLockTrapSupport.setDescription('indicates with which port lock actions the trap option is supported (e.g. discard indicates that trap is supported only when the portlock action is discard): (bit 0 is the most significant bit) bit 0 - discard bit 1 - forwardNormal bit 2 - discardDisable') sw_if_port_lock_if_range_table = mib_table((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 6)) if mibBuilder.loadTexts: swIfPortLockIfRangeTable.setStatus('current') if mibBuilder.loadTexts: swIfPortLockIfRangeTable.setDescription('Port lock interfaces range configuration') sw_if_port_lock_if_range_entry = mib_table_row((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 6, 1)).setIndexNames((0, 'CISCOSB-rlInterfaces', 'swIfPortLockIfRangeIndex')) if mibBuilder.loadTexts: swIfPortLockIfRangeEntry.setStatus('current') if mibBuilder.loadTexts: swIfPortLockIfRangeEntry.setDescription('Defines the contents of each line in the swIfPortLockIfRangeTable table.') sw_if_port_lock_if_range_index = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 6, 1, 1), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: swIfPortLockIfRangeIndex.setStatus('current') if mibBuilder.loadTexts: swIfPortLockIfRangeIndex.setDescription('Index to the swIfPortLockIfRangeTable.') sw_if_port_lock_if_range = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 6, 1, 2), port_list()).setMaxAccess('readwrite') if mibBuilder.loadTexts: swIfPortLockIfRange.setStatus('current') if mibBuilder.loadTexts: swIfPortLockIfRange.setDescription('The set of interfaces to which the port lock parameters should be configured') sw_if_port_lock_if_range_lock_status = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 6, 1, 3), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('locked', 1), ('unlocked', 2))).clone('unlocked')).setMaxAccess('readwrite') if mibBuilder.loadTexts: swIfPortLockIfRangeLockStatus.setStatus('current') if mibBuilder.loadTexts: swIfPortLockIfRangeLockStatus.setDescription('This variable indicates whether the interfaces range should operate in locked or unlocked mode. In unlocked mode the device learns all MAC addresses from these interfaces and forwards all frames arrived at these interfaces. In locked mode no new MAC addresses are learned and only frames with known source MAC addresses are forwarded.') sw_if_port_lock_if_range_action = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 6, 1, 4), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('discard', 1), ('forwardNormal', 2), ('discardDisable', 3)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: swIfPortLockIfRangeAction.setStatus('current') if mibBuilder.loadTexts: swIfPortLockIfRangeAction.setDescription('This variable indicates which action for these interfaces should be take in locked mode and therefore relevant only in locked mode. Possible actions: discard(1) - every packet is dropped. forwardNormal(2) - every packet is forwarded according to the DST address. discardDisable(3) - drops the first packet and suspends the port.') sw_if_port_lock_if_range_trap_en = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 6, 1, 5), truth_value()).setMaxAccess('readwrite') if mibBuilder.loadTexts: swIfPortLockIfRangeTrapEn.setStatus('current') if mibBuilder.loadTexts: swIfPortLockIfRangeTrapEn.setDescription('This variable indicates whether to create a SNMP trap in the locked mode.') sw_if_port_lock_if_range_trap_freq = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 6, 1, 6), integer32().subtype(subtypeSpec=value_range_constraint(1, 1000000))).setMaxAccess('readwrite') if mibBuilder.loadTexts: swIfPortLockIfRangeTrapFreq.setStatus('current') if mibBuilder.loadTexts: swIfPortLockIfRangeTrapFreq.setDescription("This variable indicates the minimal frequency (in seconds) of sending a trap for these interfaces. It's relevant only in locked mode and in trap enabled.") sw_if_ext_table = mib_table((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 7)) if mibBuilder.loadTexts: swIfExtTable.setStatus('current') if mibBuilder.loadTexts: swIfExtTable.setDescription('Display information and configuration of the device interfaces.') sw_if_ext_entry = mib_table_row((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 7, 1)).setIndexNames((0, 'IF-MIB', 'ifIndex')) if mibBuilder.loadTexts: swIfExtEntry.setStatus('current') if mibBuilder.loadTexts: swIfExtEntry.setDescription('Defines the contents of each row in the swIfExtTable.') sw_if_ext_sfp_speed = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 43, 7, 1, 1), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('default', 1), ('eth100M', 2), ('eth1G', 3))).clone('default')).setMaxAccess('readwrite') if mibBuilder.loadTexts: swIfExtSFPSpeed.setStatus('current') if mibBuilder.loadTexts: swIfExtSFPSpeed.setDescription('Configure speed of an SFP Ethernet interface.') rl_if_mib_version = mib_scalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 1), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: rlIfMibVersion.setStatus('current') if mibBuilder.loadTexts: rlIfMibVersion.setDescription("MIB's version, the current version is 1.") rl_if_num_of_ph_ports = mib_scalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 2), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: rlIfNumOfPhPorts.setStatus('current') if mibBuilder.loadTexts: rlIfNumOfPhPorts.setDescription('Total number of physical ports on this device (including all stack units)') rl_if_map_of_on_ph_ports = mib_scalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 3), octet_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: rlIfMapOfOnPhPorts.setStatus('current') if mibBuilder.loadTexts: rlIfMapOfOnPhPorts.setDescription("Each bit in this octet string indicates that the correspondig port's ifOperStatus is ON if set. The mapping of port number to bits in this octet string is as follows: The port with the L2 interface number 1 is mapped to the least significant bit of the 1st octet, the port with L2 ifNumber 2 to the next significant bit in the 1st octet, port 8 to the most-significant bit of the in the 1st octet, port 9 to the least significant bit of the 2nd octet, etc. and in general, port n to bit corresponding to 2**((n mod 8) -1) in byte n/8 + 1") rl_if_clear_port_mib_counters = mib_scalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 4), port_list()).setMaxAccess('readwrite') if mibBuilder.loadTexts: rlIfClearPortMibCounters.setStatus('current') if mibBuilder.loadTexts: rlIfClearPortMibCounters.setDescription('Each bit that is set in this portList represent a port that its mib counters should be reset.') rl_if_num_of_user_defined_ports = mib_scalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 5), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: rlIfNumOfUserDefinedPorts.setStatus('current') if mibBuilder.loadTexts: rlIfNumOfUserDefinedPorts.setDescription('The number of user defined ports on this device.') rl_if_first_out_of_band_if_index = mib_scalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 6), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: rlIfFirstOutOfBandIfIndex.setStatus('current') if mibBuilder.loadTexts: rlIfFirstOutOfBandIfIndex.setDescription('First ifIndex of out-of-band port. This scalar exists only the device has out of band ports.') rl_if_num_of_loopback_ports = mib_scalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 7), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: rlIfNumOfLoopbackPorts.setStatus('current') if mibBuilder.loadTexts: rlIfNumOfLoopbackPorts.setDescription('The number of loopback ports on this device.') rl_if_first_loopback_if_index = mib_scalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 8), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: rlIfFirstLoopbackIfIndex.setStatus('current') if mibBuilder.loadTexts: rlIfFirstLoopbackIfIndex.setDescription('First ifIndex of loopback port. This scalar will exists only if rlIfNumOfLoopbackPorts is different from 0.') rl_if_existing_port_list = mib_scalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 9), port_list()).setMaxAccess('readonly') if mibBuilder.loadTexts: rlIfExistingPortList.setStatus('current') if mibBuilder.loadTexts: rlIfExistingPortList.setDescription("Indicates which ports/trunks exist in the system. It doesn't indicate which are present.") rl_if_base_mac_address_per_if_index = mib_scalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 10), truth_value()).setMaxAccess('readwrite') if mibBuilder.loadTexts: rlIfBaseMACAddressPerIfIndex.setStatus('current') if mibBuilder.loadTexts: rlIfBaseMACAddressPerIfIndex.setDescription('Indicates if the system will assign a unique MAC per Ethernet port or not.') rl_flow_control_cascade_mode = mib_scalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 11), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('enabled', 1), ('disabled', 2)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: rlFlowControlCascadeMode.setStatus('current') if mibBuilder.loadTexts: rlFlowControlCascadeMode.setDescription('enable disable flow control on cascade ports') rl_flow_control_cascade_type = mib_scalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 12), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('internalonly', 1), ('internalexternal', 2)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: rlFlowControlCascadeType.setStatus('current') if mibBuilder.loadTexts: rlFlowControlCascadeType.setDescription('define which type of ports will be affected by flow control on cascade ports') rl_flow_control_rx_per_system = mib_scalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 13), truth_value()).setMaxAccess('readwrite') if mibBuilder.loadTexts: rlFlowControlRxPerSystem.setStatus('current') if mibBuilder.loadTexts: rlFlowControlRxPerSystem.setDescription('define if flow control RX is supported per system.') rl_cascade_port_protection_action = mib_scalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 14), truth_value()).setMaxAccess('readwrite') if mibBuilder.loadTexts: rlCascadePortProtectionAction.setStatus('current') if mibBuilder.loadTexts: rlCascadePortProtectionAction.setDescription('As a result of this set all of the local cascade ports will stop being consider unstable and will be force up.') rl_management_if_index = mib_scalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 15), interface_index()).setMaxAccess('readwrite') if mibBuilder.loadTexts: rlManagementIfIndex.setStatus('current') if mibBuilder.loadTexts: rlManagementIfIndex.setDescription('Specify L2 bound management interface index in a single IP address system when configurable management interface is supported.') rl_if_clear_stack_ports_counters = mib_scalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 16), truth_value()).setMaxAccess('readwrite') if mibBuilder.loadTexts: rlIfClearStackPortsCounters.setStatus('current') if mibBuilder.loadTexts: rlIfClearStackPortsCounters.setDescription('As a result of this set all counters of all external cascade ports will be cleared.') rl_if_clear_port_mac_addresses = mib_scalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 17), interface_index_or_zero()).setMaxAccess('readwrite') if mibBuilder.loadTexts: rlIfClearPortMacAddresses.setStatus('current') if mibBuilder.loadTexts: rlIfClearPortMacAddresses.setDescription('if port is non secure, its all dynamic MAC addresses are cleared. if port is secure, its all secure MAC addresses which have learned or configured are cleared.') rl_if_cut_through_packet_length = mib_scalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 18), integer32().subtype(subtypeSpec=value_range_constraint(257, 16383)).clone(1522)).setMaxAccess('readwrite') if mibBuilder.loadTexts: rlIfCutThroughPacketLength.setStatus('current') if mibBuilder.loadTexts: rlIfCutThroughPacketLength.setDescription('The default packet length that is assigned to a packet in the Cut-Through mode.') rl_if_cut_priority_zero = mib_scalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 19), truth_value().clone('false')).setMaxAccess('readwrite') if mibBuilder.loadTexts: rlIfCutPriorityZero.setStatus('current') if mibBuilder.loadTexts: rlIfCutPriorityZero.setDescription('Enable or disable cut-Through for priority 0.') rl_if_cut_priority_one = mib_scalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 20), truth_value().clone('false')).setMaxAccess('readwrite') if mibBuilder.loadTexts: rlIfCutPriorityOne.setStatus('current') if mibBuilder.loadTexts: rlIfCutPriorityOne.setDescription('Enable or disable cut-Through for priority 1.') rl_if_cut_priority_two = mib_scalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 21), truth_value().clone('false')).setMaxAccess('readwrite') if mibBuilder.loadTexts: rlIfCutPriorityTwo.setStatus('current') if mibBuilder.loadTexts: rlIfCutPriorityTwo.setDescription('Enable or disable cut-Through for priority 2.') rl_if_cut_priority_three = mib_scalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 22), truth_value().clone('false')).setMaxAccess('readwrite') if mibBuilder.loadTexts: rlIfCutPriorityThree.setStatus('current') if mibBuilder.loadTexts: rlIfCutPriorityThree.setDescription('Enable or disable cut-Through for priority 3.') rl_if_cut_priority_four = mib_scalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 23), truth_value().clone('false')).setMaxAccess('readwrite') if mibBuilder.loadTexts: rlIfCutPriorityFour.setStatus('current') if mibBuilder.loadTexts: rlIfCutPriorityFour.setDescription('Enable or disable cut-Through for priority 4.') rl_if_cut_priority_five = mib_scalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 24), truth_value().clone('false')).setMaxAccess('readwrite') if mibBuilder.loadTexts: rlIfCutPriorityFive.setStatus('current') if mibBuilder.loadTexts: rlIfCutPriorityFive.setDescription('Enable or disable cut-Through for priority 5.') rl_if_cut_priority_six = mib_scalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 25), truth_value().clone('false')).setMaxAccess('readwrite') if mibBuilder.loadTexts: rlIfCutPrioritySix.setStatus('current') if mibBuilder.loadTexts: rlIfCutPrioritySix.setDescription('Enable or disable cut-Through for priority 6.') rl_if_cut_priority_seven = mib_scalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 26), truth_value().clone('false')).setMaxAccess('readwrite') if mibBuilder.loadTexts: rlIfCutPrioritySeven.setStatus('current') if mibBuilder.loadTexts: rlIfCutPrioritySeven.setDescription('Enable or disable cut-Through for priority 7.') rl_if_cut_through_table = mib_table((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 27)) if mibBuilder.loadTexts: rlIfCutThroughTable.setStatus('current') if mibBuilder.loadTexts: rlIfCutThroughTable.setDescription('Information and configuration of cut-through feature.') rl_if_cut_through_entry = mib_table_row((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 27, 1)).setIndexNames((0, 'CISCOSB-rlInterfaces', 'swIfIndex')) if mibBuilder.loadTexts: rlIfCutThroughEntry.setStatus('current') if mibBuilder.loadTexts: rlIfCutThroughEntry.setDescription('Defines the contents of each line in the swIfTable table.') rl_if_cut_through_priority_enable = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 27, 1, 1), truth_value().clone('false')).setMaxAccess('readwrite') if mibBuilder.loadTexts: rlIfCutThroughPriorityEnable.setStatus('current') if mibBuilder.loadTexts: rlIfCutThroughPriorityEnable.setDescription('Enable or disable cut-through for a priority for an interface.') rl_if_cut_through_untagged_enable = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 27, 1, 2), truth_value().clone('false')).setMaxAccess('readwrite') if mibBuilder.loadTexts: rlIfCutThroughUntaggedEnable.setStatus('current') if mibBuilder.loadTexts: rlIfCutThroughUntaggedEnable.setDescription('Enable or disable cut-through for untagged packets for an interface.') rl_if_cut_through_oper_mode = mib_table_column((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 27, 1, 3), truth_value()).setMaxAccess('readonly') if mibBuilder.loadTexts: rlIfCutThroughOperMode.setStatus('current') if mibBuilder.loadTexts: rlIfCutThroughOperMode.setDescription('Operational mode of spesific cut-through interface.') rl_cut_through_packet_length = mib_scalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 28), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: rlCutThroughPacketLength.setStatus('current') if mibBuilder.loadTexts: rlCutThroughPacketLength.setDescription('The default packet length that is assigned to a packet in the Cut-Through mode.') rl_cut_through_packet_length_after_reset = mib_scalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 29), integer32().subtype(subtypeSpec=value_range_constraint(257, 16383)).clone(1522)).setMaxAccess('readwrite') if mibBuilder.loadTexts: rlCutThroughPacketLengthAfterReset.setStatus('current') if mibBuilder.loadTexts: rlCutThroughPacketLengthAfterReset.setDescription('The default packet length that is assigned to a packet in the Cut-Through mode after reset.') rl_cut_through_enable = mib_scalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 30), truth_value()).setMaxAccess('readonly') if mibBuilder.loadTexts: rlCutThroughEnable.setStatus('current') if mibBuilder.loadTexts: rlCutThroughEnable.setDescription('Cut-Through global enable mode.') rl_cut_through_enable_after_reset = mib_scalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 31), truth_value().clone('false')).setMaxAccess('readwrite') if mibBuilder.loadTexts: rlCutThroughEnableAfterReset.setStatus('current') if mibBuilder.loadTexts: rlCutThroughEnableAfterReset.setDescription('Cut-Through global enable mode after reset.') rl_flow_control_mode = mib_scalar((1, 3, 6, 1, 4, 1, 9, 6, 1, 101, 54, 32), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('send-receive', 1), ('receive-only', 2)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: rlFlowControlMode.setStatus('current') if mibBuilder.loadTexts: rlFlowControlMode.setDescription('Define which mode will be enabled on flow control enabled ports. The interfaces with enabled flow control will receive pause frames, but will not send flow control pause frames Send-receive: The interfaces with enabled flow control will receive and send pause frames. Receive-only: The interfaces with enabled flow control will receive pause frames, but will not send flow control pause frames.') mibBuilder.exportSymbols('CISCOSB-rlInterfaces', rlFlowControlCascadeType=rlFlowControlCascadeType, rlIfNumOfPhPorts=rlIfNumOfPhPorts, rlIfFirstLoopbackIfIndex=rlIfFirstLoopbackIfIndex, rlIfNumOfLoopbackPorts=rlIfNumOfLoopbackPorts, swIfAdminSpeedDuplexAutoNegotiationLocalCapabilities=swIfAdminSpeedDuplexAutoNegotiationLocalCapabilities, PYSNMP_MODULE_ID=swInterfaces, swIfMibVersion=swIfMibVersion, rlIfClearPortMacAddresses=rlIfClearPortMacAddresses, swIfStatus=swIfStatus, swIfOperSpeedDuplexAutoNegotiation=swIfOperSpeedDuplexAutoNegotiation, swIfSingleHostViolationOperTrapCount=swIfSingleHostViolationOperTrapCount, rlIfClearPortMibCounters=rlIfClearPortMibCounters, swIfOperFlowControlMode=swIfOperFlowControlMode, swIfAdminMdix=swIfAdminMdix, swIfDuplexAdminMode=swIfDuplexAdminMode, swIfPortLockTrapSupport=swIfPortLockTrapSupport, swIfPortLockIfRangeIndex=swIfPortLockIfRangeIndex, rlIfClearStackPortsCounters=rlIfClearStackPortsCounters, swIfTransceiverType=swIfTransceiverType, swInterfaces=swInterfaces, swIfPortLockSupport=swIfPortLockSupport, swIfDefaultTag=swIfDefaultTag, swIfSingleHostViolationAdminTrapEnable=swIfSingleHostViolationAdminTrapEnable, swIfTable=swIfTable, rlIfCutPriorityThree=rlIfCutPriorityThree, swIfOperLockTrapEnable=swIfOperLockTrapEnable, rlCascadePortProtectionAction=rlCascadePortProtectionAction, rlFlowControlRxPerSystem=rlFlowControlRxPerSystem, swIfType=swIfType, rlIfCutThroughPriorityEnable=rlIfCutThroughPriorityEnable, rlIfCutPriorityTwo=rlIfCutPriorityTwo, swIfHostMode=swIfHostMode, rlIfCutPriorityFour=rlIfCutPriorityFour, rlCutThroughPacketLengthAfterReset=rlCutThroughPacketLengthAfterReset, rlIfMibVersion=rlIfMibVersion, swIfDuplexOperMode=swIfDuplexOperMode, rlIfCutPrioritySix=rlIfCutPrioritySix, AutoNegCapabilitiesBits=AutoNegCapabilitiesBits, rlIfNumOfUserDefinedPorts=rlIfNumOfUserDefinedPorts, rlIfCutPriorityOne=rlIfCutPriorityOne, swIfPortLockActionSupport=swIfPortLockActionSupport, swIfSpeedAdminMode=swIfSpeedAdminMode, rlIfMapOfOnPhPorts=rlIfMapOfOnPhPorts, swIfSingleHostViolationOperTrapEnable=swIfSingleHostViolationOperTrapEnable, swIfOperLockAction=swIfOperLockAction, rlIfCutPrioritySeven=rlIfCutPrioritySeven, rlFlowControlMode=rlFlowControlMode, rlIfExistingPortList=rlIfExistingPortList, rlManagementIfIndex=rlManagementIfIndex, rlIfCutThroughTable=rlIfCutThroughTable, swIfLockOperStatus=swIfLockOperStatus, swIfAdminLockAction=swIfAdminLockAction, swIfOperComboMode=swIfOperComboMode, swIfBackPressureMode=swIfBackPressureMode, rlCutThroughPacketLength=rlCutThroughPacketLength, swIfDefaultPriority=swIfDefaultPriority, swIfOperBackPressureMode=swIfOperBackPressureMode, rlIfCutThroughPacketLength=rlIfCutThroughPacketLength, swIfOperMdix=swIfOperMdix, rlIfFirstOutOfBandIfIndex=rlIfFirstOutOfBandIfIndex, rlIfCutThroughOperMode=rlIfCutThroughOperMode, swIfOperSpeedDuplexAutoNegotiationLocalCapabilities=swIfOperSpeedDuplexAutoNegotiationLocalCapabilities, rlCutThroughEnable=rlCutThroughEnable, swIfOperSuspendedStatus=swIfOperSuspendedStatus, rlCutThroughEnableAfterReset=rlCutThroughEnableAfterReset, swIfSingleHostViolationAdminTrapFrequency=swIfSingleHostViolationAdminTrapFrequency, swIfAdminLockTrapEnable=swIfAdminLockTrapEnable, swIfPhysAddressType=swIfPhysAddressType, swIfSingleHostViolationOperAction=swIfSingleHostViolationOperAction, swIfExtTable=swIfExtTable, swIfPortLockIfRangeTrapEn=swIfPortLockIfRangeTrapEn, swIfPortLockIfRange=swIfPortLockIfRange, swIfPortLockIfRangeLockStatus=swIfPortLockIfRangeLockStatus, swIfLockAdminStatus=swIfLockAdminStatus, swIfReActivate=swIfReActivate, swIfPortLockIfRangeEntry=swIfPortLockIfRangeEntry, swIfLockMacAddressesCount=swIfLockMacAddressesCount, swIfLockAdminTrapFrequency=swIfLockAdminTrapFrequency, rlIfCutThroughUntaggedEnable=rlIfCutThroughUntaggedEnable, rlIfCutPriorityFive=rlIfCutPriorityFive, swIfAdminComboMode=swIfAdminComboMode, swIfIndex=swIfIndex, swIfPortLockIfRangeAction=swIfPortLockIfRangeAction, swIfFlowControlMode=swIfFlowControlMode, rlIfBaseMACAddressPerIfIndex=rlIfBaseMACAddressPerIfIndex, swIfPortLockIfRangeTrapFreq=swIfPortLockIfRangeTrapFreq, swIfEntry=swIfEntry, swIfSingleHostViolationAdminAction=swIfSingleHostViolationAdminAction, swIfExtSFPSpeed=swIfExtSFPSpeed, swIfPortLockIfRangeTable=swIfPortLockIfRangeTable, rlFlowControlCascadeMode=rlFlowControlCascadeMode, rlIfCutThroughEntry=rlIfCutThroughEntry, swIfTaggedMode=swIfTaggedMode, swIfAutoNegotiationMasterSlavePreference=swIfAutoNegotiationMasterSlavePreference, swIfSpeedDuplexAutoNegotiation=swIfSpeedDuplexAutoNegotiation, swIfLockOperTrapCount=swIfLockOperTrapCount, swIfSpeedDuplexNegotiationRemoteCapabilities=swIfSpeedDuplexNegotiationRemoteCapabilities, swIfExtEntry=swIfExtEntry, swIfLockLimitationMode=swIfLockLimitationMode, swIfLockMaxMacAddresses=swIfLockMaxMacAddresses, rlIfCutPriorityZero=rlIfCutPriorityZero)
def solveQuestion(inputPath): fileP = open(inputPath, 'r') fileLines = fileP.readlines() fileP.close() newPosition = [] numRows = len(fileLines) numCols = len(fileLines[0].strip('\n')) for line in fileLines: currentLine = [] for grid in line.strip('\n'): currentLine.append(grid) newPosition.append(currentLine) lastPosition = [] counter = 0 while lastPosition != newPosition: lastPosition = list(newPosition) newPosition =[] counter += 1 for row in range(numRows): currentLine = [] for col in range(numCols): if lastPosition[row][col] == '.': currentLine.append('.') continue numNeighbors = getNeighbors(lastPosition, row, col, numRows, numCols) if numNeighbors == 0 and lastPosition[row][col] == 'L': currentLine.append('#') elif numNeighbors >= 4 and lastPosition[row][col] == '#': currentLine.append('L') else: currentLine.append(lastPosition[row][col]) newPosition.append(currentLine) totalOccupied = 0 for position in newPosition: totalOccupied += ''.join(position).count('#') return totalOccupied def getNeighbors(lastPosition, row, col, maxRow, maxCol): indexMove = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]] counter = 0 for index in indexMove: rowActual = row + index[0] colActual = col + index[1] if rowActual < 0 or colActual < 0: continue if rowActual == maxRow: continue if colActual == maxCol: continue if lastPosition[rowActual][colActual] == '#': counter += 1 return counter print(solveQuestion('InputD11Q1.txt'))
def solve_question(inputPath): file_p = open(inputPath, 'r') file_lines = fileP.readlines() fileP.close() new_position = [] num_rows = len(fileLines) num_cols = len(fileLines[0].strip('\n')) for line in fileLines: current_line = [] for grid in line.strip('\n'): currentLine.append(grid) newPosition.append(currentLine) last_position = [] counter = 0 while lastPosition != newPosition: last_position = list(newPosition) new_position = [] counter += 1 for row in range(numRows): current_line = [] for col in range(numCols): if lastPosition[row][col] == '.': currentLine.append('.') continue num_neighbors = get_neighbors(lastPosition, row, col, numRows, numCols) if numNeighbors == 0 and lastPosition[row][col] == 'L': currentLine.append('#') elif numNeighbors >= 4 and lastPosition[row][col] == '#': currentLine.append('L') else: currentLine.append(lastPosition[row][col]) newPosition.append(currentLine) total_occupied = 0 for position in newPosition: total_occupied += ''.join(position).count('#') return totalOccupied def get_neighbors(lastPosition, row, col, maxRow, maxCol): index_move = [[-1, -1], [-1, 0], [-1, 1], [0, -1], [0, 1], [1, -1], [1, 0], [1, 1]] counter = 0 for index in indexMove: row_actual = row + index[0] col_actual = col + index[1] if rowActual < 0 or colActual < 0: continue if rowActual == maxRow: continue if colActual == maxCol: continue if lastPosition[rowActual][colActual] == '#': counter += 1 return counter print(solve_question('InputD11Q1.txt'))
n = int(input()) if n%2 != 0: print('Weird') else: if n in range(2, 6): print('Not Weird') if n in range(6, 21): print('Weird') if n > 20: print('Not Weird')
n = int(input()) if n % 2 != 0: print('Weird') else: if n in range(2, 6): print('Not Weird') if n in range(6, 21): print('Weird') if n > 20: print('Not Weird')
def add_numbers(start, end): total=0 for i in range(start,end+1): total=total+i return total test1 = add_numbers(333, 777) print(test1)
def add_numbers(start, end): total = 0 for i in range(start, end + 1): total = total + i return total test1 = add_numbers(333, 777) print(test1)
MOD = 10 ** 9 + 7 n, k = map(int, input().split()) dp = [0] * (k + 1) ans = 0 for x in range(k, 0, -1): dp[x] = pow(k // x, n, MOD) for i in range(2 * x, k + 1, x): dp[x] -= dp[i] ans += dp[x] * x ans %= MOD print(ans)
mod = 10 ** 9 + 7 (n, k) = map(int, input().split()) dp = [0] * (k + 1) ans = 0 for x in range(k, 0, -1): dp[x] = pow(k // x, n, MOD) for i in range(2 * x, k + 1, x): dp[x] -= dp[i] ans += dp[x] * x ans %= MOD print(ans)
# Bidirectional BFS class Solution(object): def minKnightMoves(self, x, y): offsets = [(1, 2), (2, 1), (2, -1), (1, -2), (-1, -2), (-2, -1), (-2, 1), (-1, 2)] q1 = collections.deque([(0, 0)]) q2 = collections.deque([(x, y)]) steps1 = {(0, 0): 0} #steps needed starting from (0, 0) steps2 = {(x, y): 0} #steps needed starting from (x,y) while q1 and q2: i1, j1 = q1.popleft() if (i1, j1) in steps2: return steps1[(i1, j1)]+steps2[(i1, j1)] i2, j2 = q2.popleft() if (i2, j2) in steps1: return steps1[(i2, j2)]+steps2[(i2, j2)] for ox, oy in offsets: nextI1 = i1+ox nextJ1 = j1+oy if (nextI1, nextJ1) not in steps1: q1.append((nextI1, nextJ1)) steps1[(nextI1, nextJ1)] = steps1[(i1, j1)]+1 nextI2 = i2+ox nextJ2 = j2+oy if (nextI2, nextJ2) not in steps2: q2.append((nextI2, nextJ2)) steps2[(nextI2, nextJ2)] = steps2[(i2, j2)]+1 return float('inf')
class Solution(object): def min_knight_moves(self, x, y): offsets = [(1, 2), (2, 1), (2, -1), (1, -2), (-1, -2), (-2, -1), (-2, 1), (-1, 2)] q1 = collections.deque([(0, 0)]) q2 = collections.deque([(x, y)]) steps1 = {(0, 0): 0} steps2 = {(x, y): 0} while q1 and q2: (i1, j1) = q1.popleft() if (i1, j1) in steps2: return steps1[i1, j1] + steps2[i1, j1] (i2, j2) = q2.popleft() if (i2, j2) in steps1: return steps1[i2, j2] + steps2[i2, j2] for (ox, oy) in offsets: next_i1 = i1 + ox next_j1 = j1 + oy if (nextI1, nextJ1) not in steps1: q1.append((nextI1, nextJ1)) steps1[nextI1, nextJ1] = steps1[i1, j1] + 1 next_i2 = i2 + ox next_j2 = j2 + oy if (nextI2, nextJ2) not in steps2: q2.append((nextI2, nextJ2)) steps2[nextI2, nextJ2] = steps2[i2, j2] + 1 return float('inf')
class School: def __init__(self): self.list_students = list() self.list_data = list() def add_student(self, name, grade): self.list_students.append({"name": name, "grade": grade}) def roster(self): return self.sort_student_list_by_name_and_grade() def grade(self, grade_number): return self.expect_grade_number_and_return_list_ordered(grade_number) def sort_student_list_by_name_and_grade(self): sorted_list = sorted(self.list_students, key=lambda k: (k['grade'], k['name'])) return self.add_to_a_new_list_student_list(sorted_list) def add_to_a_new_list_student_list(self, list_name): for names_students in list_name: self.list_data.append(names_students["name"]) return self.list_data def expect_grade_number_and_return_list_ordered(self, grade_number): for names_students in self.list_students: if names_students["grade"] == grade_number: self.list_data.append(names_students["name"]) return sorted(self.list_data)
class School: def __init__(self): self.list_students = list() self.list_data = list() def add_student(self, name, grade): self.list_students.append({'name': name, 'grade': grade}) def roster(self): return self.sort_student_list_by_name_and_grade() def grade(self, grade_number): return self.expect_grade_number_and_return_list_ordered(grade_number) def sort_student_list_by_name_and_grade(self): sorted_list = sorted(self.list_students, key=lambda k: (k['grade'], k['name'])) return self.add_to_a_new_list_student_list(sorted_list) def add_to_a_new_list_student_list(self, list_name): for names_students in list_name: self.list_data.append(names_students['name']) return self.list_data def expect_grade_number_and_return_list_ordered(self, grade_number): for names_students in self.list_students: if names_students['grade'] == grade_number: self.list_data.append(names_students['name']) return sorted(self.list_data)
#!/usr/bin/python3 # * Copyright (c) 2020-2021, Happiest Minds Technologies Limited Intellectual Property. All rights reserved. # * # * SPDX-License-Identifier: LGPL-2.1-only PE1_binding_chk = 'ipv4 PE1ID/32 P1ID imp-null' P1_binding_chk1 = 'ipv4 P1ID/32 PE1ID imp-null' P1_binding_chk2 = 'ipv4 P1ID/32 PE2ID imp-null' PE2_binding_chk = 'ipv4 PE2ID/32 P1ID imp-null'
pe1_binding_chk = 'ipv4 PE1ID/32 P1ID imp-null' p1_binding_chk1 = 'ipv4 P1ID/32 PE1ID imp-null' p1_binding_chk2 = 'ipv4 P1ID/32 PE2ID imp-null' pe2_binding_chk = 'ipv4 PE2ID/32 P1ID imp-null'
# Url source: # https://stackoverflow.com/questions/6260089/strange-result-when-removing-item-from-a-list numbers = list(range(1, 50)) for i in numbers: if i < 20: numbers.remove(i) print(numbers)
numbers = list(range(1, 50)) for i in numbers: if i < 20: numbers.remove(i) print(numbers)
class Solution: def shortestPathLength(self, graph): def dp(node, mask): state = (node, mask) if state in cache: return cache[state] if mask & (mask - 1) == 0: # Base case - mask only has a single "1", which means # that only one node has been visited (the current node) return 0 cache[state] = float("inf") # Avoid infinite loop in recursion for neighbor in graph[node]: if mask & (1 << neighbor): already_visited = 1 + dp(neighbor, mask) not_visited = 1 + dp(neighbor, mask ^ (1 << node)) cache[state] = min(cache[state], already_visited, not_visited) return cache[state] n = len(graph) ending_mask = (1 << n) - 1 cache = {} return min(dp(node, ending_mask) for node in range(n))
class Solution: def shortest_path_length(self, graph): def dp(node, mask): state = (node, mask) if state in cache: return cache[state] if mask & mask - 1 == 0: return 0 cache[state] = float('inf') for neighbor in graph[node]: if mask & 1 << neighbor: already_visited = 1 + dp(neighbor, mask) not_visited = 1 + dp(neighbor, mask ^ 1 << node) cache[state] = min(cache[state], already_visited, not_visited) return cache[state] n = len(graph) ending_mask = (1 << n) - 1 cache = {} return min((dp(node, ending_mask) for node in range(n)))
def format_dict(data, sep_item=", ", sep_key_value="=", brackets=True): output = "" delim = "" for key, value in data.items(): output += f"{delim}{key}{sep_key_value}{value}" delim = f"{sep_item}" return f"{{{output}}}" if brackets else f"{output}" def powerdict(data): # https://stackoverflow.com/a/1482320 n = len(data) masks = [1 << i for i in range(n)] for i in range(1 << n): yield {key: data[key] for mask, key in zip(masks, data) if i & mask} def powerset(data): # https://stackoverflow.com/a/1482320 n = len(data) masks = [1 << i for i in range(n)] for i in range(1 << n): yield {element for mask, element in zip(masks, data) if i & mask} def powerlist(data): # https://stackoverflow.com/a/1482320 n = len(data) masks = [1 << i for i in range(n)] for i in range(1 << n): yield [element for mask, element in zip(masks, data) if i & mask] def issubdict(a, b): return all(key in b for key in a.keys()) and all(b[key] == value for key, value in a.items())
def format_dict(data, sep_item=', ', sep_key_value='=', brackets=True): output = '' delim = '' for (key, value) in data.items(): output += f'{delim}{key}{sep_key_value}{value}' delim = f'{sep_item}' return f'{{{output}}}' if brackets else f'{output}' def powerdict(data): n = len(data) masks = [1 << i for i in range(n)] for i in range(1 << n): yield {key: data[key] for (mask, key) in zip(masks, data) if i & mask} def powerset(data): n = len(data) masks = [1 << i for i in range(n)] for i in range(1 << n): yield {element for (mask, element) in zip(masks, data) if i & mask} def powerlist(data): n = len(data) masks = [1 << i for i in range(n)] for i in range(1 << n): yield [element for (mask, element) in zip(masks, data) if i & mask] def issubdict(a, b): return all((key in b for key in a.keys())) and all((b[key] == value for (key, value) in a.items()))
#!/usr/bin/env python3 # Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # These are the snippets shown during the demo videos in C2M2 # Each snippet is followed by the corresponding output when executed in the # Python interpreter. # >>> file = open("spider.txt") # >>> print(file.readline()) # The itsy bitsy spider climbed up the waterspout. # # >>> print(file.readline()) # Down came the rain # # >>> print(file.read()) # and washed the spider out. # Out came the sun # and dried up all the rain # and the itsy bitsy spider climbed up the spout again. # # >>> file.close() # # >>> with open("spider.txt") as file: # ... print(file.readline()) # ... # The itsy bitsy spider climbed up the waterspout. # # >>> with open("spider.txt") as file: # ... for line in file: # ... print(line.upper()) # ... # # THE ITSY BITSY SPIDER CLIMBED UP THE WATERSPOUT. # # DOWN CAME THE RAIN # # AND WASHED THE SPIDER OUT. # # OUT CAME THE SUN # # AND DRIED UP ALL THE RAIN # # AND THE ITSY BITSY SPIDER CLIMBED UP THE SPOUT AGAIN. # # # >>> with open("spider.txt") as file: # ... for line in file: # ... print(line.strip().upper()) # ... # THE ITSY BITSY SPIDER CLIMBED UP THE WATERSPOUT. # DOWN CAME THE RAIN # AND WASHED THE SPIDER OUT. # OUT CAME THE SUN # AND DRIED UP ALL THE RAIN # AND THE ITSY BITSY SPIDER CLIMBED UP THE SPOUT AGAIN. # # >>> file = open("spider.txt") # >>> lines = file.readlines() # >>> file.close() # >>> lines.sort() # >>> print(lines) # ['Down came the rain\n', 'Out came the sun\n', 'The itsy bitsy spider climbed up the waterspout.\n', 'and dried up all the rain\n', 'and the itsy bitsy spider climbed up the spout again.\n', 'and washed the spider out.\n'] # # >>> with open("novel.txt", "w") as file: # ... file.write("It was a dark and stormy night") # ... # 30 # # >>> import os # >>> os.remove("novel.txt") # >>> # # >>> os.remove("novel.txt") # Traceback (most recent call last): # File "<stdin>", line 1, in <module> # FileNotFoundError: [Errno 2] No such file or directory: 'novel.txt' # # >>> os.rename("first_draft.txt", "finished_masterpiece.txt") # >>> # # # >>> os.path.exists("finished_masterpiece.txt") # True # >>> os.path.exists("userlist.txt") # False # # >>> os.path.getsize("spider.txt") # 192 # # >>> os.path.getmtime("spider.txt") # 1556990746.582071 # # >>> import datetime # >>> timestamp = os.path.getmtime("spider.txt") # >>> datetime.datetime.fromtimestamp(timestamp) # datetime.datetime(2019, 5, 4, 19, 25, 46, 582071) # # >>> os.path.abspath("spider.txt") # '/home/user/spider.txt' # # >>> print(os.getcwd()) # /home/user # # # >>> os.mkdir("new_dir") # >>> os.chdir("new_dir") # # >>> os.getcwd() # '/home/user/new_dir' # # >>> os.mkdir("newer_dir") # >>> os.rmdir("newer_dir") # # >>> import os # >>> os.listdir("website") # ['index.html', 'images', 'favicon.ico'] # dir = "website" for name in os.listdir(dir): fullname = os.path.join(dir, name) if os.path.isdir(fullname): print("{} is a directory".format(fullname)) else: print("{} is a file".format(fullname)) # >>> dir = "website" # >>> for name in os.listdir(dir): # ... fullname = os.path.join(dir, name) # ... if os.path.isdir(fullname): # ... print("{} is a directory".format(fullname)) # ... else: # ... print("{} is a file".format(fullname)) # ... # website/index.html is a file # website/images is a directory # website/favicon.ico is a file # # # CSV files # # --------- # # >>> import csv # >>> f = open("csv_file.txt") # >>> csv_f = csv.reader(f) # >>> for row in csv_f: # ... name, phone, role = row # ... print("Name: {}, Phone: {}, Role: {}".format(name, phone, role)) # ... # Name: Sabrina Green, Phone: 802-867-5309, Role: System Administrator # Name: Eli Jones, Phone: 684-3481127, Role: IT specialist # Name: Melody Daniels, Phone: 846-687-7436, Role: Programmer # Name: Charlie Rivera, Phone: 698-746-3357, Role: Web Developer # # >>> f.close() # # >>> hosts = [["workstation.local", "192.168.25.46"],["webserver.cloud", "10.2.5.6"]] # >>> with open('hosts.csv', 'w') as hosts_csv: # ... writer = csv.writer(hosts_csv) # ... writer.writerows(hosts) # ... # with open('software.csv') as software: reader = csv.DictReader(software) for row in reader: print(("{} has {} users").format(row["name"], row["users"])) # >>> with open('software.csv') as software: # ... reader = csv.DictReader(software) # ... for row in reader: # ... print(("{} has {} users").format(row["name"], row["users"])) # ... # MailTree has 324 users # CalDoor has 22 users # Chatty Chicken has 4 users # # # users = [ {"name": "Sol Mansi", "username": "solm", "department": "IT infrastructure"}, # {"name": "Lio Nelson", "username": "lion", "department": "User Experience Research"}, # {"name": "Charlie Grey", "username": "greyc", "department": "Development"}] # keys = ["name", "username", "department"] # with open('by_department.csv', 'w') as by_department: # writer = csv.DictWriter(by_department, fieldnames=keys) # writer.writeheader() # writer.writerows(users)
dir = 'website' for name in os.listdir(dir): fullname = os.path.join(dir, name) if os.path.isdir(fullname): print('{} is a directory'.format(fullname)) else: print('{} is a file'.format(fullname)) with open('software.csv') as software: reader = csv.DictReader(software) for row in reader: print('{} has {} users'.format(row['name'], row['users']))
class Solution: def shortestPathBinaryMatrix(self, grid: List[List[int]]) -> int: if grid[0][0] == 1: return -1 def neighbor8(i, j): n = len(grid) for di in (-1, 0, 1): for dj in (-1, 0, 1): if di == dj == 0: continue newi, newj = i + di, j + dj if 0 <= newi < n and 0 <= newj < n and grid[newi][newj] == 0: yield (newi, newj) n = len(grid) ds = [[math.inf] * n for _ in range(n)] queue = collections.deque([(0, 0)]) ds[0][0] = 1 while queue: i, j = queue.popleft() if i == j == n - 1: return ds[n - 1][n - 1] for newi, newj in neighbor8(i, j): if ds[i][j] + 1 < ds[newi][newj]: ds[newi][newj] = ds[i][j] + 1 queue.append((newi, newj)) return -1
class Solution: def shortest_path_binary_matrix(self, grid: List[List[int]]) -> int: if grid[0][0] == 1: return -1 def neighbor8(i, j): n = len(grid) for di in (-1, 0, 1): for dj in (-1, 0, 1): if di == dj == 0: continue (newi, newj) = (i + di, j + dj) if 0 <= newi < n and 0 <= newj < n and (grid[newi][newj] == 0): yield (newi, newj) n = len(grid) ds = [[math.inf] * n for _ in range(n)] queue = collections.deque([(0, 0)]) ds[0][0] = 1 while queue: (i, j) = queue.popleft() if i == j == n - 1: return ds[n - 1][n - 1] for (newi, newj) in neighbor8(i, j): if ds[i][j] + 1 < ds[newi][newj]: ds[newi][newj] = ds[i][j] + 1 queue.append((newi, newj)) return -1
first = "Aditya" last = "Mhambrey" full = first+" "+last print(full) full = f"{first} {last} {2+2} {len(first)}" print(full) course = " Python Programming" print(course.upper()) print(course.lower()) print(course.title()) # First Letter of every Word is capital print(course.strip()) # Getting rid of white space print(course.rstrip()) # Getting rid of white space from right similar for Left print(course.find("Pro")) # Same as JS, -1 for wrong case print(course.replace("P", "-")) print("Programming" in course) print("Programming" not in course)
first = 'Aditya' last = 'Mhambrey' full = first + ' ' + last print(full) full = f'{first} {last} {2 + 2} {len(first)}' print(full) course = ' Python Programming' print(course.upper()) print(course.lower()) print(course.title()) print(course.strip()) print(course.rstrip()) print(course.find('Pro')) print(course.replace('P', '-')) print('Programming' in course) print('Programming' not in course)
class Node: def __init__(self, value, next=None): self.value = value self.next = next def has_cycle(head): slow, fast = head, head while fast is not None and fast.next is not None: fast = fast.next.next slow = slow.next if slow == fast: return True # found the cycle return False
class Node: def __init__(self, value, next=None): self.value = value self.next = next def has_cycle(head): (slow, fast) = (head, head) while fast is not None and fast.next is not None: fast = fast.next.next slow = slow.next if slow == fast: return True return False
#Sort an array of 0s, 1s and 2s #It is a problem from geeksforgeeks and can be solved using python code #Given an array A of size N containing 0s, 1s, and 2s; you need to sort the array in ascending order. # Here t is the number of test cases, # i is an iterative variable, # n is the number of elements in list, # x is the list in which elements are to be entered # and sort() is a python in-built function which will sort the list of elements in ascending order t = int(input()) for i in range(t): n = int(input()) x = list(map(int, input().split())) x.sort() for i in x: print(i, end=" ") print() #This code is contributed by Akhil
t = int(input()) for i in range(t): n = int(input()) x = list(map(int, input().split())) x.sort() for i in x: print(i, end=' ') print()
# list(map(int, input().split())) # int(input()) def main(): X = int(input()) if X >= 30: print('Yes') else: print('No') if __name__ == '__main__': main()
def main(): x = int(input()) if X >= 30: print('Yes') else: print('No') if __name__ == '__main__': main()
class ManageCards: cards = {} cards["154-98-11-133-118"] = "1" cards["64-91-169-137-59"] = "2" cards["46-245-168-137-250"] = "3" cards["198-241-168-137-22"] = "4" cards["127-72-227-41-253"] = "5" cards["78-4-170-137-105"] = "6" cards["119-174-226-41-18"] = "7" cards["98-155-250-41-42"] = "8" cards["1-112-169-137-81"] = "9" cards["26-171-169-137-145"] = "10" cards["167-132-229-41-239"] = "11" cards["150-234-168-137-93"] = "12" def getCardFromUID(self, uid): try: return self.cards[uid] except KeyError: return None
class Managecards: cards = {} cards['154-98-11-133-118'] = '1' cards['64-91-169-137-59'] = '2' cards['46-245-168-137-250'] = '3' cards['198-241-168-137-22'] = '4' cards['127-72-227-41-253'] = '5' cards['78-4-170-137-105'] = '6' cards['119-174-226-41-18'] = '7' cards['98-155-250-41-42'] = '8' cards['1-112-169-137-81'] = '9' cards['26-171-169-137-145'] = '10' cards['167-132-229-41-239'] = '11' cards['150-234-168-137-93'] = '12' def get_card_from_uid(self, uid): try: return self.cards[uid] except KeyError: return None
'''An e-commerce website wishes to find the lucky customer who will be eligible for full value cash back. For this purpose,a number N is fed to the system. It will return another number that is calculated by an algorithm. In the algorithm, a sequence is generated, in which each number n the sum of the preceding numbers. initially the sequence will have two 1's in it. The System will return the Nth number from the generated sequence which is treated as the order ID. The lucky customer will be one who has placed that order. Write an alorithm to help the website find the lucky customer. Input Format an integer value from the user Constraints no constraints Output Format print order ID as an integer Sample Input 0 8 Sample Output 0 21 Sample Input 1 5 Sample Output 1 5''' #solution def lucky(num): n1 = 1 n2 = 1 summ = 0 for i in range(2,num): summ = n1+n2 n1 = n2 n2 = summ return summ print(lucky(int(input())))
"""An e-commerce website wishes to find the lucky customer who will be eligible for full value cash back. For this purpose,a number N is fed to the system. It will return another number that is calculated by an algorithm. In the algorithm, a sequence is generated, in which each number n the sum of the preceding numbers. initially the sequence will have two 1's in it. The System will return the Nth number from the generated sequence which is treated as the order ID. The lucky customer will be one who has placed that order. Write an alorithm to help the website find the lucky customer. Input Format an integer value from the user Constraints no constraints Output Format print order ID as an integer Sample Input 0 8 Sample Output 0 21 Sample Input 1 5 Sample Output 1 5""" def lucky(num): n1 = 1 n2 = 1 summ = 0 for i in range(2, num): summ = n1 + n2 n1 = n2 n2 = summ return summ print(lucky(int(input())))
class CommonsShared: # period, step, and episode counter periods_counter = 1 steps_counter = 1 episode_number = 0 # number of periods considered for calculating short and long term sustainabilities n_steps_short_term = 1 n_steps_long_term = 4 # number of agents n_agents = 5 # max periods per episode max_episode_periods = 10 # rounds played by each agent in a period agents_loop_steps = 20 # resources growing rate and environment carrying capacity growing_rate = 0.3 # Ghorbani uses 0.25 - 0.35 carrying_capacity = 50000 # Ghorbani uses 10000 - 20000 # probability of being caught wrong-doing punishment_probability = 1 # max replenishment (dependent on growth function) max_replenishment = carrying_capacity * growing_rate * 0.5 ** 2 # max consumption, penalty, and increases in consumption and penalty max_penalty_multiplier = 3 max_penalty_multiplier_increase = 0.5 max_limit_exploit = max_replenishment * 2 / n_agents # two times max replenishment max_limit_exploit_increase = 1000 #consumption and replenishment buffers consumed_buffer = [] consumed = [] replenished_buffer = [] replenished = []
class Commonsshared: periods_counter = 1 steps_counter = 1 episode_number = 0 n_steps_short_term = 1 n_steps_long_term = 4 n_agents = 5 max_episode_periods = 10 agents_loop_steps = 20 growing_rate = 0.3 carrying_capacity = 50000 punishment_probability = 1 max_replenishment = carrying_capacity * growing_rate * 0.5 ** 2 max_penalty_multiplier = 3 max_penalty_multiplier_increase = 0.5 max_limit_exploit = max_replenishment * 2 / n_agents max_limit_exploit_increase = 1000 consumed_buffer = [] consumed = [] replenished_buffer = [] replenished = []
def test_ci_placeholder(): # This empty test is used within the CI to # setup the tox venv without running the test suite # if we simply skip all test with pytest -k=wrong_pattern # pytest command would return with exit_code=5 (i.e "no tests run") # making travis fail # this empty test is the recommended way to handle this # as described in https://github.com/pytest-dev/pytest/issues/2393 pass
def test_ci_placeholder(): pass
if __name__ == '__main__': x = 1 y = [2] x, = y print(x)
if __name__ == '__main__': x = 1 y = [2] (x,) = y print(x)
class Decoder: def __init__(self, alphabet, symbol): self._alphabet = alphabet self._symbol = symbol self._reconstructed_extended_dict = { int(symbol): letter for letter, symbol in self._alphabet.copy().items() } def decode(self, encoded_input): output = "" last_decoded_symbol = "" for current_decoded_symbol in self._decoded_symbols(encoded_input): if current_decoded_symbol is None: value_to_add = last_decoded_symbol + last_decoded_symbol[0] current_decoded_symbol = value_to_add else: value_to_add = last_decoded_symbol + current_decoded_symbol[0] output += current_decoded_symbol last_decoded_symbol = current_decoded_symbol self._update_dict(value_to_add) return output def _decoded_symbols(self, encoded_input): i = 0 while i < len(encoded_input): symbol_length = self._symbol.next_bit_length current_symbol = encoded_input[i : i + symbol_length] current_int_symbol = int(current_symbol) current_decoded_symbol = self._reconstructed_extended_dict.get( current_int_symbol ) i += symbol_length yield current_decoded_symbol def _update_dict(self, value_to_add): if value_to_add not in self._reconstructed_extended_dict.values(): self._reconstructed_extended_dict[int(next(self._symbol))] = value_to_add
class Decoder: def __init__(self, alphabet, symbol): self._alphabet = alphabet self._symbol = symbol self._reconstructed_extended_dict = {int(symbol): letter for (letter, symbol) in self._alphabet.copy().items()} def decode(self, encoded_input): output = '' last_decoded_symbol = '' for current_decoded_symbol in self._decoded_symbols(encoded_input): if current_decoded_symbol is None: value_to_add = last_decoded_symbol + last_decoded_symbol[0] current_decoded_symbol = value_to_add else: value_to_add = last_decoded_symbol + current_decoded_symbol[0] output += current_decoded_symbol last_decoded_symbol = current_decoded_symbol self._update_dict(value_to_add) return output def _decoded_symbols(self, encoded_input): i = 0 while i < len(encoded_input): symbol_length = self._symbol.next_bit_length current_symbol = encoded_input[i:i + symbol_length] current_int_symbol = int(current_symbol) current_decoded_symbol = self._reconstructed_extended_dict.get(current_int_symbol) i += symbol_length yield current_decoded_symbol def _update_dict(self, value_to_add): if value_to_add not in self._reconstructed_extended_dict.values(): self._reconstructed_extended_dict[int(next(self._symbol))] = value_to_add
listanum = [[],[]] #Primeiro colchete numeros pares e segundo colchete numeros impares valor = 0 for cont in range(1,8): valor = int(input("Digite um valor: ")) if valor % 2 ==0: listanum[0].append(valor) else: listanum[1].append(valor) listanum[0].sort() listanum[1].sort() print(f"Os numeros pares digitados foram {listanum[0]}") print(f"Os numeros impares digitados foram {listanum[1]}")
listanum = [[], []] valor = 0 for cont in range(1, 8): valor = int(input('Digite um valor: ')) if valor % 2 == 0: listanum[0].append(valor) else: listanum[1].append(valor) listanum[0].sort() listanum[1].sort() print(f'Os numeros pares digitados foram {listanum[0]}') print(f'Os numeros impares digitados foram {listanum[1]}')
path = "../data/stockfish_norm.csv" scores = open( path) last_scores = open( "last_scores.fea", "w") for row in scores: last_scores.write( row.rsplit(" ", 1)[1]) scores.close() last_scores.close()
path = '../data/stockfish_norm.csv' scores = open(path) last_scores = open('last_scores.fea', 'w') for row in scores: last_scores.write(row.rsplit(' ', 1)[1]) scores.close() last_scores.close()
def mutation(word_list): if all(i in word_list[0].lower() for i in word_list[1].lower()): return True return False print(mutation(["hello", "Hello"])) print(mutation(["hello", "hey"])) print(mutation(["Alien", "line"]))
def mutation(word_list): if all((i in word_list[0].lower() for i in word_list[1].lower())): return True return False print(mutation(['hello', 'Hello'])) print(mutation(['hello', 'hey'])) print(mutation(['Alien', 'line']))
def index(req): req.content_type = "text/html" req.add_common_vars() env_vars = req.subprocess_env.copy() req.write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">') req.write('<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">') req.write('<head><title>mod_python.publisher</title></head>') req.write('<body>') req.write('<h1>Environment Variables</h1>') req.write('<table border="1">') for key in env_vars: req.write('<tr><td>%s</td><td>%s</td></tr>' % (key, env_vars[key])) req.write('</table>') req.write('</body>') req.write('</html>')
def index(req): req.content_type = 'text/html' req.add_common_vars() env_vars = req.subprocess_env.copy() req.write('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">') req.write('<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">') req.write('<head><title>mod_python.publisher</title></head>') req.write('<body>') req.write('<h1>Environment Variables</h1>') req.write('<table border="1">') for key in env_vars: req.write('<tr><td>%s</td><td>%s</td></tr>' % (key, env_vars[key])) req.write('</table>') req.write('</body>') req.write('</html>')
class Vehicle: name = "" kind = "car" color = "" value = 00.00 def description (self): desc ="%s is a %s %s worth $%.2f." % (self.name,self.color,self.kind,self.value) return desc car1 = Vehicle() car1.name = "Fuso" car1.color = "grey" car1.kind = "lorry" car1.value = 1000 car2 = Vehicle() car2.name = "ferrari" car2.color = "Red" car2.kind = "convertible" car2.value = 5000 print (car1.description()) print (car2.description())
class Vehicle: name = '' kind = 'car' color = '' value = 0.0 def description(self): desc = '%s is a %s %s worth $%.2f.' % (self.name, self.color, self.kind, self.value) return desc car1 = vehicle() car1.name = 'Fuso' car1.color = 'grey' car1.kind = 'lorry' car1.value = 1000 car2 = vehicle() car2.name = 'ferrari' car2.color = 'Red' car2.kind = 'convertible' car2.value = 5000 print(car1.description()) print(car2.description())
class ContactHelper: def __init__(self, app): self.app = app def create(self, contact): wd = self.app.wd # init contact creation wd.find_element_by_link_text("add new").click() # foll contact form wd.find_element_by_name("firstname").click() wd.find_element_by_name("firstname").clear() wd.find_element_by_name("firstname").send_keys(contact.firstname) wd.find_element_by_name("lastname").click() wd.find_element_by_name("lastname").clear() wd.find_element_by_name("lastname").send_keys(contact.lastname) wd.find_element_by_name("address").click() wd.find_element_by_name("address").clear() wd.find_element_by_name("address").send_keys(contact.address) wd.find_element_by_name("mobile").click() wd.find_element_by_name("mobile").clear() wd.find_element_by_name("mobile").send_keys(contact.mobile) wd.find_element_by_xpath("//div[@id='content']/form/input[21]").click() self.return_to_contacts_page() def return_to_contacts_page(self): wd = self.app.wd wd.find_element_by_link_text("home").click()
class Contacthelper: def __init__(self, app): self.app = app def create(self, contact): wd = self.app.wd wd.find_element_by_link_text('add new').click() wd.find_element_by_name('firstname').click() wd.find_element_by_name('firstname').clear() wd.find_element_by_name('firstname').send_keys(contact.firstname) wd.find_element_by_name('lastname').click() wd.find_element_by_name('lastname').clear() wd.find_element_by_name('lastname').send_keys(contact.lastname) wd.find_element_by_name('address').click() wd.find_element_by_name('address').clear() wd.find_element_by_name('address').send_keys(contact.address) wd.find_element_by_name('mobile').click() wd.find_element_by_name('mobile').clear() wd.find_element_by_name('mobile').send_keys(contact.mobile) wd.find_element_by_xpath("//div[@id='content']/form/input[21]").click() self.return_to_contacts_page() def return_to_contacts_page(self): wd = self.app.wd wd.find_element_by_link_text('home').click()
# # Copyright (c) 2017 Amit Green. All rights reserved. # @gem('Gem.Codec') def gem(): require_gem('Gem.Import') PythonCodec = import_module('codecs') python_encode_ascii = PythonCodec.getencoder('ascii') @export def encode_ascii(s): return python_encode_ascii(s)[0]
@gem('Gem.Codec') def gem(): require_gem('Gem.Import') python_codec = import_module('codecs') python_encode_ascii = PythonCodec.getencoder('ascii') @export def encode_ascii(s): return python_encode_ascii(s)[0]