content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
motorcycles = ['honda', 'yamaha','suzuki'] print(motorcycles) #motorcycles[0] = 'ducati' motorcycles.append('ducati') print(motorcycles) motorcycles = [] motorcycles.append('honda') motorcycles.append('yamaha') motorcycles.append('suzuki') motorcycles.insert(0, 'ducati') print(motorcycles) del motorcycles[1] print(motorcycles)
motorcycles = ['honda', 'yamaha', 'suzuki'] print(motorcycles) motorcycles.append('ducati') print(motorcycles) motorcycles = [] motorcycles.append('honda') motorcycles.append('yamaha') motorcycles.append('suzuki') motorcycles.insert(0, 'ducati') print(motorcycles) del motorcycles[1] print(motorcycles)
# Requirements # Python 3.6+ # Torch 1.8+ class BertClassifier(nn.Module): def __init__(self, n): super(BertClassifier, self).__init__() self.bert = BertModel.from_pretrained('bert-base-cased') self.drop = nn.Dropout(p=0.3) self.out = nn.Linear(self.bert.config.hidden_size, n) def forward(self, input_ids, attention_mask): _, pooled_output = self.bert( input_ids=input_ids, attention_mask=attention_mask, return_dict=False) output = self.drop(pooled_output) return self.out(output)
class Bertclassifier(nn.Module): def __init__(self, n): super(BertClassifier, self).__init__() self.bert = BertModel.from_pretrained('bert-base-cased') self.drop = nn.Dropout(p=0.3) self.out = nn.Linear(self.bert.config.hidden_size, n) def forward(self, input_ids, attention_mask): (_, pooled_output) = self.bert(input_ids=input_ids, attention_mask=attention_mask, return_dict=False) output = self.drop(pooled_output) return self.out(output)
# type: ignore def test_func(): assert True
def test_func(): assert True
class PropertyNotHoldsException(Exception): def __init__(self, property_text, last_proved_stacktrace): self.last_proved_stacktrace = last_proved_stacktrace message = "A property found not to hold:\n\t" message += property_text super().__init__(message) class ModelNotFoundException(Exception): pass
class Propertynotholdsexception(Exception): def __init__(self, property_text, last_proved_stacktrace): self.last_proved_stacktrace = last_proved_stacktrace message = 'A property found not to hold:\n\t' message += property_text super().__init__(message) class Modelnotfoundexception(Exception): pass
def range(minimo,maximo,step): lista=[] while minimo<maximo: lista+=[minimo] #lista.append(minimo) minimo+=step return lista print(range(2,10,2)) print(range(100,1000,100))
def range(minimo, maximo, step): lista = [] while minimo < maximo: lista += [minimo] minimo += step return lista print(range(2, 10, 2)) print(range(100, 1000, 100))
class Type(): NONE = 0x0 NOCOLOR = 0x1 JAIL = 0x2 BHYVE = 0x4 EXIT = 0x8 CONNECTION_CLOSED = 0x10
class Type: none = 0 nocolor = 1 jail = 2 bhyve = 4 exit = 8 connection_closed = 16
print("==== PROGRAM HITUNG TOTAL HARGA PESANAN ====".center(50)) print("="*38) print("*Menu*".center(37)) print("="*38) print("1. Susu".rjust(8), "Rp.7.000".rjust(27)) print("2. Teh".rjust(7), "Rp.5.000".rjust(28)) print("3. Kopi".rjust(8), " Rp.5.000".rjust(27)) print("="*38, "\n") banyak_jenis = int(input("banyak jenis: ")) kode_potong = [] banyak_potong = [] jenis_potong = [] harga = [] total = [] i = 0 while i < banyak_jenis: print("jenis ke", i+1) kode_potong.append(input("kode Pesanan [S/T/K]: ")) banyak_potong.append(int(input("banyak Pesanan: \n"))) if kode_potong[i] == "S" or kode_potong[i] == "s": jenis_potong.append("Susu") harga.append("7000") total.append(banyak_potong[i]*int("7000")) elif kode_potong[i] == "T" or kode_potong[i] == "t": jenis_potong.append("Teh") harga.append("5000") total.append(banyak_potong[i]*int("5000")) elif kode_potong[i] == "K" or kode_potong[i] == "k": jenis_potong.append("Kopi") harga.append("5000") total.append(banyak_potong[i] * int("5000")) else: jenis_potong.append("Kode salah") harga.append("0") total.append(banyak_potong[i]*int("0")) i = i+1 print("="*61) print("*CAFE BALE-BALE*".center(61)) print("="*61) print("No".rjust(4), "Jenis".rjust(10), "Harga".rjust(15), "Banyak".rjust(15), "Jumlah".rjust(10)) print("".rjust(4), "Potong".rjust(11), "satuan".rjust(15), "Beli".rjust(13), "Harga".rjust(11)) print("-"*61) jumlah_bayar = 0 a = 0 while a < banyak_jenis: jumlah_bayar = jumlah_bayar + total[0] print(" %i %s %s %i Rp.%i\n" % (a+1, jenis_potong[a], harga[a], banyak_potong[a], total[a])) a = a + 1 print("Total jumlah Rp.".rjust(52), jumlah_bayar) print("-"*61) jumlah = jumlah_bayar if jumlah >= 35000: diskon = jumlah_bayar / 10 total_bayar = jumlah_bayar - diskon print("Diskon 10% Rp.".rjust(50), diskon) print("kamu hanya perlu membayar Rp.".rjust(49), total_bayar) elif jumlah >= 35000 or jumlah_bayar >= 15000: diskon = jumlah_bayar / 5 total_bayar = jumlah_bayar - diskon print("Diskon 5% Rp.".rjust(50), diskon) print("kamu hanya perlu membayar Rp.".rjust(49), total_bayar) elif jumlah < 15000: diskon = 0 total = jumlah_bayar print("Diskon Rp.0".rjust(47)) print("Total bayar Rp.".rjust(51), total) print("="*61)
print('==== PROGRAM HITUNG TOTAL HARGA PESANAN ===='.center(50)) print('=' * 38) print('*Menu*'.center(37)) print('=' * 38) print('1. Susu'.rjust(8), 'Rp.7.000'.rjust(27)) print('2. Teh'.rjust(7), 'Rp.5.000'.rjust(28)) print('3. Kopi'.rjust(8), ' Rp.5.000'.rjust(27)) print('=' * 38, '\n') banyak_jenis = int(input('banyak jenis: ')) kode_potong = [] banyak_potong = [] jenis_potong = [] harga = [] total = [] i = 0 while i < banyak_jenis: print('jenis ke', i + 1) kode_potong.append(input('kode Pesanan [S/T/K]: ')) banyak_potong.append(int(input('banyak Pesanan: \n'))) if kode_potong[i] == 'S' or kode_potong[i] == 's': jenis_potong.append('Susu') harga.append('7000') total.append(banyak_potong[i] * int('7000')) elif kode_potong[i] == 'T' or kode_potong[i] == 't': jenis_potong.append('Teh') harga.append('5000') total.append(banyak_potong[i] * int('5000')) elif kode_potong[i] == 'K' or kode_potong[i] == 'k': jenis_potong.append('Kopi') harga.append('5000') total.append(banyak_potong[i] * int('5000')) else: jenis_potong.append('Kode salah') harga.append('0') total.append(banyak_potong[i] * int('0')) i = i + 1 print('=' * 61) print('*CAFE BALE-BALE*'.center(61)) print('=' * 61) print('No'.rjust(4), 'Jenis'.rjust(10), 'Harga'.rjust(15), 'Banyak'.rjust(15), 'Jumlah'.rjust(10)) print(''.rjust(4), 'Potong'.rjust(11), 'satuan'.rjust(15), 'Beli'.rjust(13), 'Harga'.rjust(11)) print('-' * 61) jumlah_bayar = 0 a = 0 while a < banyak_jenis: jumlah_bayar = jumlah_bayar + total[0] print(' %i %s %s %i Rp.%i\n' % (a + 1, jenis_potong[a], harga[a], banyak_potong[a], total[a])) a = a + 1 print('Total jumlah Rp.'.rjust(52), jumlah_bayar) print('-' * 61) jumlah = jumlah_bayar if jumlah >= 35000: diskon = jumlah_bayar / 10 total_bayar = jumlah_bayar - diskon print('Diskon 10% Rp.'.rjust(50), diskon) print('kamu hanya perlu membayar Rp.'.rjust(49), total_bayar) elif jumlah >= 35000 or jumlah_bayar >= 15000: diskon = jumlah_bayar / 5 total_bayar = jumlah_bayar - diskon print('Diskon 5% Rp.'.rjust(50), diskon) print('kamu hanya perlu membayar Rp.'.rjust(49), total_bayar) elif jumlah < 15000: diskon = 0 total = jumlah_bayar print('Diskon Rp.0'.rjust(47)) print('Total bayar Rp.'.rjust(51), total) print('=' * 61)
first_num = int(input()) second_num = int(input()) third_num = int(input()) for i in range (1, first_num + 1): for j in range (1, second_num + 1): for k in range (1, third_num + 1): if i % 2 == 0 and j > 1 and k % 2 == 0: for prime in range(2, j): if (j % prime) == 0: break else: print(f'{i} {j} {k}')
first_num = int(input()) second_num = int(input()) third_num = int(input()) for i in range(1, first_num + 1): for j in range(1, second_num + 1): for k in range(1, third_num + 1): if i % 2 == 0 and j > 1 and (k % 2 == 0): for prime in range(2, j): if j % prime == 0: break else: print(f'{i} {j} {k}')
a = int(input("Enter number a: ")) b = int(input("Enter number b: ")) i = a % b j = b % a print(i * j + 1)
a = int(input('Enter number a: ')) b = int(input('Enter number b: ')) i = a % b j = b % a print(i * j + 1)
class UserMessageError(Exception): def __init__(self, response_code, user_msg=None, server_msg=None): self.user_msg = user_msg or "" self.server_msg = server_msg or self.user_msg self.response_code = response_code super().__init__() class ClientError(UserMessageError): def __init__(self, response_code=400, user_msg=None, **kwargs): if not user_msg: user_msg = "Invalid request" super().__init__(response_code, user_msg=user_msg, **kwargs) class ServerError(UserMessageError): def __init__(self, response_code=500, user_msg=None, server_msg=None): user_msg = f"An error occurred while processing the request{f': {user_msg}' if user_msg else ''}" server_msg = f"Server-side error while processing request: {server_msg or user_msg}" super().__init__(response_code, user_msg=user_msg, server_msg=server_msg) class NotFoundError(UserMessageError): def __init__(self, user_msg=None, **kwargs): if not user_msg: user_msg = "Requested resource not found" super().__init__(404, user_msg=user_msg, **kwargs) class NotAuthorized(ClientError): def __init__(self, user_msg=None, **kwargs): if not user_msg: user_msg = "You are not authorized to access the requested resource." super().__init__(response_code=401, user_msg=user_msg, **kwargs) class InvalidEnum(ValueError): pass
class Usermessageerror(Exception): def __init__(self, response_code, user_msg=None, server_msg=None): self.user_msg = user_msg or '' self.server_msg = server_msg or self.user_msg self.response_code = response_code super().__init__() class Clienterror(UserMessageError): def __init__(self, response_code=400, user_msg=None, **kwargs): if not user_msg: user_msg = 'Invalid request' super().__init__(response_code, user_msg=user_msg, **kwargs) class Servererror(UserMessageError): def __init__(self, response_code=500, user_msg=None, server_msg=None): user_msg = f"An error occurred while processing the request{(f': {user_msg}' if user_msg else '')}" server_msg = f'Server-side error while processing request: {server_msg or user_msg}' super().__init__(response_code, user_msg=user_msg, server_msg=server_msg) class Notfounderror(UserMessageError): def __init__(self, user_msg=None, **kwargs): if not user_msg: user_msg = 'Requested resource not found' super().__init__(404, user_msg=user_msg, **kwargs) class Notauthorized(ClientError): def __init__(self, user_msg=None, **kwargs): if not user_msg: user_msg = 'You are not authorized to access the requested resource.' super().__init__(response_code=401, user_msg=user_msg, **kwargs) class Invalidenum(ValueError): pass
# https://projecteuler.net/problem=5 def gcd(a, b): if b == 0: return a return gcd(b, a%b) print(gcd(1,6)) result = 1 for i in range(2, 21): g = gcd(result, i) result = result * (i/g) print(i, g, result) print(result)
def gcd(a, b): if b == 0: return a return gcd(b, a % b) print(gcd(1, 6)) result = 1 for i in range(2, 21): g = gcd(result, i) result = result * (i / g) print(i, g, result) print(result)
#Calculadora basica que haga suma,resta,multiplicacion y division def main() : n = input('Ingresa los numeroes entre espacios: \n') print("\t") print("Estos son los numeros ingresados: ") respuesta = input("\n Desea continuar? Y/N: ") if respuesta == "Y": print("Funciono") print(n)
def main(): n = input('Ingresa los numeroes entre espacios: \n') print('\t') print('Estos son los numeros ingresados: ') respuesta = input('\n Desea continuar? Y/N: ') if respuesta == 'Y': print('Funciono') print(n)
def insertion_sort(lst): for passes in range(1, len(lst)): # n-1 passes current_val = lst[passes] pos = passes while pos > 0 and lst[pos-1] > current_val: lst[pos] = lst[pos-1] pos = pos-1 lst[pos] = current_val return lst arr = [2, 4, 42, 6, 22, 7] print(insertion_sort(arr))
def insertion_sort(lst): for passes in range(1, len(lst)): current_val = lst[passes] pos = passes while pos > 0 and lst[pos - 1] > current_val: lst[pos] = lst[pos - 1] pos = pos - 1 lst[pos] = current_val return lst arr = [2, 4, 42, 6, 22, 7] print(insertion_sort(arr))
class Util: def __init__(self, node): self._node = node def createmultisig(self, nrequired, keys, address_type="legacy"): # 01 return self._node._rpc.call("createmultisig", nrequired, keys, address_type) def deriveaddresses(self, descriptor, range=None): # 02 return self._node._rpc.call("deriveaddresses", descriptor, range) def estimatesmartfee(self, conf_target, estimate_mode="CONSERVATIVE"): # 03 return self._node._rpc.call("estimatesmartfee", conf_target, estimate_mode) def getdescriptorinfo(self, descriptor): # 04 return self._node._rpc.call("getdescriptorinfo", descriptor) def signmessagewithprivkey(self, privkey, message): # 05 return self._node._rpc.call("signmessagewithprivkey", privkey, message) def validateaddress(self, address): # 06 return self._node._rpc.call("validateaddress", address) def verifymessage(self, address, signature, message): # 07 return self._node._rpc.call("verifymessage", address, signature, message)
class Util: def __init__(self, node): self._node = node def createmultisig(self, nrequired, keys, address_type='legacy'): return self._node._rpc.call('createmultisig', nrequired, keys, address_type) def deriveaddresses(self, descriptor, range=None): return self._node._rpc.call('deriveaddresses', descriptor, range) def estimatesmartfee(self, conf_target, estimate_mode='CONSERVATIVE'): return self._node._rpc.call('estimatesmartfee', conf_target, estimate_mode) def getdescriptorinfo(self, descriptor): return self._node._rpc.call('getdescriptorinfo', descriptor) def signmessagewithprivkey(self, privkey, message): return self._node._rpc.call('signmessagewithprivkey', privkey, message) def validateaddress(self, address): return self._node._rpc.call('validateaddress', address) def verifymessage(self, address, signature, message): return self._node._rpc.call('verifymessage', address, signature, message)
# For singly Linked List # class MySinglyLinkedList: # def __init__(self): # self.head = None # self.size = 0 # # If the index is invalid, return -1 # def get(self, index: int) -> int: # if index >= self.size or index < 0: # return -1 # if self.head is None: # return -1 # curr = self.head # for i in range(index): # curr = curr.next # return curr.val # def addAtHead(self, val: int) -> None: # node = Node(val, self.head) # self.head = node # self.size += 1 # def addAtTail(self, val: int) -> None: # curr = self.head # if curr is None: # self.addAtHead(val) # else: # while curr.next is not None: # curr = curr.next # curr.next = Node(val) # self.size += 1 # def addAtIndex(self, index: int, val: int) -> None: # if index > self.size: # return -1 # if index == 0: # self.addAtHead(val) # else: # curr = self.head # prev = curr # for i in range(index): # prev = curr # curr = curr.next # prev.next = Node(val, curr) # self.size += 1 # # Delete the indexth node in the linked list, if the index is valid. # def deleteAtIndex(self, index: int) -> None: # if index >= self.size: # return -1 # curr = self.head # if index == 0: # self.head = self.head.next # else: # prev = curr # for i in range(index): # prev = curr # curr = curr.next # if curr.next is None: # prev.next = None # else: # prev.next = curr.next # self.size -= 1 ''' ["MyLinkedList","addAtIndex","addAtIndex","addAtIndex","get"] [[],[0,10],[0,20],[1,30],[0]] ["MyLinkedList","addAtHead","addAtTail","addAtIndex","get","deleteAtIndex","deleteAtIndex","deleteAtIndex","get"] [[],[1],[3],[1,2],[1],[1],[0],[0],[1]] ["MyLinkedList","addAtHead","get","addAtTail","get","addAtIndex","addAtIndex","get","deleteAtIndex","get"] [[],[1],[0],[3],[1],[1,2],[4,4],[1],[1],[1]] ["MyLinkedList","addAtHead","deleteAtIndex"] [[],[1],[0]] ["MyLinkedList","addAtHead","addAtTail","addAtIndex","get","deleteAtIndex","get"] [[],[1],[3],[1,2],[1],[0],[0]] ''' # Your MyLinkedList object will be instantiated and called as such: # obj = MyLinkedList() # param_1 = obj.get(index) # obj.addAtHead(val) # obj.addAtTail(val) # obj.addAtIndex(index,val) # obj.deleteAtIndex(index) class Node: def __init__(self, val = 0, anext = None, prev = None): self.val = val self.next = anext self.prev = prev class MyLinkedList: def __init__(self): self.head = None self.size = 0 def get(self, index): if self.size and 0 <= index < self.size: curr = self.head while index > 0: curr = curr.next index -= 1 return curr.val else: return -1 def addAtHead(self, val): node = Node(val, self.head, None) self.head = node self.size += 1 def addAtTail(self, val): if not self.size: self.addAtHead(val) return curr = self.head while curr.next: curr = curr.next node = Node(val, None, curr) curr.next = node self.size += 1 def deleteAtIndex(self, index): if index == 0: self.head = self.head.next self.size -= 1 return if index < self.size and index > 0: curr = self.head while index > 0: prev = curr curr = curr.next index -= 1 anext = None if curr is not None: anext = curr.next prev.next = anext self.size -= 1 def addAtIndex(self, index, val): if index > self.size or index < 0: return self.head if not self.size or index == 0: self.addAtHead(val) return if index == self.size: self.addAtTail(val) return curr = self.head while index > 0: prev = curr curr = curr.next index -= 1 anext = curr node = Node(val, anext, prev) anext.prev = node if prev: prev.next = node self.size += 1
""" ["MyLinkedList","addAtIndex","addAtIndex","addAtIndex","get"] [[],[0,10],[0,20],[1,30],[0]] ["MyLinkedList","addAtHead","addAtTail","addAtIndex","get","deleteAtIndex","deleteAtIndex","deleteAtIndex","get"] [[],[1],[3],[1,2],[1],[1],[0],[0],[1]] ["MyLinkedList","addAtHead","get","addAtTail","get","addAtIndex","addAtIndex","get","deleteAtIndex","get"] [[],[1],[0],[3],[1],[1,2],[4,4],[1],[1],[1]] ["MyLinkedList","addAtHead","deleteAtIndex"] [[],[1],[0]] ["MyLinkedList","addAtHead","addAtTail","addAtIndex","get","deleteAtIndex","get"] [[],[1],[3],[1,2],[1],[0],[0]] """ class Node: def __init__(self, val=0, anext=None, prev=None): self.val = val self.next = anext self.prev = prev class Mylinkedlist: def __init__(self): self.head = None self.size = 0 def get(self, index): if self.size and 0 <= index < self.size: curr = self.head while index > 0: curr = curr.next index -= 1 return curr.val else: return -1 def add_at_head(self, val): node = node(val, self.head, None) self.head = node self.size += 1 def add_at_tail(self, val): if not self.size: self.addAtHead(val) return curr = self.head while curr.next: curr = curr.next node = node(val, None, curr) curr.next = node self.size += 1 def delete_at_index(self, index): if index == 0: self.head = self.head.next self.size -= 1 return if index < self.size and index > 0: curr = self.head while index > 0: prev = curr curr = curr.next index -= 1 anext = None if curr is not None: anext = curr.next prev.next = anext self.size -= 1 def add_at_index(self, index, val): if index > self.size or index < 0: return self.head if not self.size or index == 0: self.addAtHead(val) return if index == self.size: self.addAtTail(val) return curr = self.head while index > 0: prev = curr curr = curr.next index -= 1 anext = curr node = node(val, anext, prev) anext.prev = node if prev: prev.next = node self.size += 1
widget = WidgetDefault() widget.width = 101 widget.height = 101 widget.border = "None" widget.background = "None" commonDefaults["BarGraphWidget"] = widget def generateBarGraphWidget(file, screen, bar, parentName): name = bar.getName() file.write(" %s = leBarGraphWidget_New();" % (name)) generateBaseWidget(file, screen, bar) writeSetBoolean(file, name, "Stacked", bar.getStacked(), False) writeSetBoolean(file, name, "FillGraphArea", bar.getFillGraphArea(), True) writeSetInt(file, name, "TickLength", bar.getTickLength(), 5) if bar.getMinValue() != 0: file.write(" %s->fn->setMinValue(%s, BAR_GRAPH_AXIS_0, %d);" % (name, name, bar.getMinValue())) if bar.getMaxValue() != 100: file.write(" %s->fn->setMaxValue(%s, BAR_GRAPH_AXIS_0, %d);" % (name, name, bar.getMaxValue())) if bar.getTickInterval() != 10: file.write(" %s->fn->setValueAxisTicksInterval(%s, BAR_GRAPH_AXIS_0, %d);" % (name, name, bar.getTickInterval())) if bar.getSubtickInterval() != 5: file.write(" %s->fn->setValueAxisSubticksInterval(%s, BAR_GRAPH_AXIS_0, %d);" % (name, name, bar.getSubtickInterval())) if bar.getValueAxisTicksVisible() == False: file.write(" %s->fn->setValueAxisTicksVisible(%s, BAR_GRAPH_AXIS_0, LE_FALSE);" % (name, name)) if bar.getValueGridlinesVisible() == False: file.write(" %s->fn->setGridLinesVisible(%s, BAR_GRAPH_AXIS_0, LE_FALSE);" % (name, name)) position = bar.getValueAxisTicksPosition().toString() if position != "Center": if position == "Inside": position = "BAR_GRAPH_TICK_IN" elif position == "Outside": position = "BAR_GRAPH_TICK_OUT" else: position = "BAR_GRAPH_TICK_CENTER" file.write(" %s->fn->setValueAxisTicksPosition(%s, BAR_GRAPH_AXIS_0, %s);" % (name, name, position)) if bar.getValueAxisLabelsVisible() == False: file.write(" %s->fn->setValueAxisLabelsVisible(%s, BAR_GRAPH_AXIS_0, LE_FALSE);" % (name, name)) if bar.getValueAxisSubticksVisible() == False: file.write(" %s->fn->setValueAxisSubticksVisible(%s, BAR_GRAPH_AXIS_0, LE_FALSE);" % (name, name)) position = bar.getValueAxisSubticksPosition().toString() if position != "Center": if position == "Inside": position = "BAR_GRAPH_TICK_IN" elif position == "Outside": position = "BAR_GRAPH_TICK_OUT" else: position = "BAR_GRAPH_TICK_CENTER" file.write(" %s->fn->setValueAxisSubticksPosition(%s, BAR_GRAPH_AXIS_0, %s);" % (name, name, position)) writeSetFontAssetName(file, name, "TicksLabelFont", bar.getLabelFontName()) writeSetBoolean(file, name, "CategoryAxisTicksVisible", bar.getCategoryAxisTicksVisible(), True) writeSetBoolean(file, name, "CategoryAxisLabelsVisible", bar.getCategoryAxisLabelsVisible(), True) position = bar.getCategoryAxisTicksPosition().toString() if position != "Center": if position == "Inside": position = "BAR_GRAPH_TICK_IN" elif position == "Outside": position = "BAR_GRAPH_TICK_OUT" else: position = "BAR_GRAPH_TICK_CENTER" file.write(" %s->fn->setCategoryAxisTicksPosition(%s, %s);" % (name, name, position)) categoryList = bar.getCategories() for i in range(0, len(categoryList)): file.write(" %s->fn->addCategory(%s, NULL);" % (name, name)) stringName = craftStringAssetName(categoryList[i].string) if stringName != "NULL": file.write(" %s->fn->setCategoryString(%s, %d, (leString*)%s);" % (name, name, i, stringName)) seriesList = bar.getDataSeries() if len(seriesList) > 0: for idx, series in enumerate(seriesList): file.write(" %s->fn->addSeries(%s, NULL);" % (name, name)) if testStringValidity(series.scheme): file.write(" %s->fn->setSeriesScheme(%s, %d, &%s);" % (name, name, idx, series.scheme)) for dataVal in series.data: file.write(" %s->fn->addDataToSeries(%s, %d, %d, NULL);" % (name, name, idx, dataVal)) file.write(" %s->fn->addChild(%s, (leWidget*)%s);" % (parentName, parentName, name)) file.writeNewLine() def generateBarGraphAction(text, variables, owner, event, action): name = action.targetName #print(action.argumentData) if action.actionID == "SetTickLength": val = getActionArgumentValue(action, "Length") writeActionFunc(text, action, "setTickLength", [val]) elif action.actionID == "SetFillGraphArea": val = getActionArgumentValue(action, "Fill") writeActionFunc(text, action, "setFillGraphArea", [val]) elif action.actionID == "SetStacked": val = getActionArgumentValue(action, "Stacked") writeActionFunc(text, action, "setStacked", [val]) elif action.actionID == "SetMax": val = getActionArgumentValue(action, "Value") writeActionFunc(text, action, "setMaxValue", ["BAR_GRAPH_AXIS_0", val]) elif action.actionID == "SetMin": val = getActionArgumentValue(action, "Value") writeActionFunc(text, action, "setMinValue", ["BAR_GRAPH_AXIS_0", val]) elif action.actionID == "SetTickInterval": val = getActionArgumentValue(action, "Interval") writeActionFunc(text, action, "setValueAxisTicksInterval", ["BAR_GRAPH_AXIS_0", val]) elif action.actionID == "SetSubtickInterval": val = getActionArgumentValue(action, "Interval") writeActionFunc(text, action, "setValueAxisSubticksInterval", ["BAR_GRAPH_AXIS_0", val]) elif action.actionID == "ShowValueAxisLabels": val = getActionArgumentValue(action, "Show") writeActionFunc(text, action, "setValueAxisLabelsVisible", ["BAR_GRAPH_AXIS_0", val]) elif action.actionID == "ShowValueAxisTicks": val = getActionArgumentValue(action, "Show") writeActionFunc(text, action, "setValueAxisTicksVisible", ["BAR_GRAPH_AXIS_0", val]) elif action.actionID == "ShowValueAxisSubticks": val = getActionArgumentValue(action, "Show") writeActionFunc(text, action, "setValueAxisSubticksVisible", ["BAR_GRAPH_AXIS_0", val]) elif action.actionID == "ShowValueAxisGrid": val = getActionArgumentValue(action, "Show") writeActionFunc(text, action, "setGridLinesVisible", ["BAR_GRAPH_AXIS_0", val]) elif action.actionID == "SetValueAxisTickPosition": val = getActionArgumentValue(action, "Position") if val == "Center": val = "BAR_GRAPH_TICK_CENTER" elif val == "Inside": val = "BAR_GRAPH_TICK_IN" elif val == "Outside": val = "BAR_GRAPH_TICK_OUT" writeActionFunc(text, action, "setValueAxisTicksPosition", ["BAR_GRAPH_AXIS_0", val]) elif action.actionID == "SetValueAxisSubtickPosition": val = getActionArgumentValue(action, "Position") if val == "Center": val = "BAR_GRAPH_TICK_CENTER" elif val == "Inside": val = "BAR_GRAPH_TICK_IN" elif val == "Outside": val = "BAR_GRAPH_TICK_OUT" writeActionFunc(text, action, "setValueAxisSubticksPosition", ["BAR_GRAPH_AXIS_0", val]) elif action.actionID == "ShowCategoryAxisLabels": val = getActionArgumentValue(action, "Show") writeActionFunc(text, action, "setCategoryAxisLabelsVisible", [val]) elif action.actionID == "ShowCategoryAxisTicks": val = getActionArgumentValue(action, "Show") writeActionFunc(text, action, "setCategoryAxisTicksVisible", [val]) elif action.actionID == "SetCategoryAxisTickPosition": val = getActionArgumentValue(action, "Position") if val == "Center": val = "BAR_GRAPH_TICK_CENTER" elif val == "Inside": val = "BAR_GRAPH_TICK_IN" elif val == "Outside": val = "BAR_GRAPH_TICK_OUT" writeActionFunc(text, action, "setCategoryAxisTicksPosition", [val]) elif action.actionID == "SetLabelFont": val = getActionArgumentValue(action, "FontAsset") writeActionFunc(text, action, "setTicksLabelFont", [val]) elif action.actionID == "AddCategory": val = getActionArgumentValue(action, "StringAsset") variables["categoryIdx"] = "uint32_t" writeActionFunc(text, action, "addCategory", ["&categoryIdx"]) writeActionFunc(text, action, "setCategoryString", ["categoryIdx", val]) elif action.actionID == "AddSeries": val = getActionArgumentValue(action, "Scheme") variables["seriesIdx"] = "uint32_t" writeActionFunc(text, action, "addSeries", ["&seriesIdx"]) writeActionFunc(text, action, "setSeriesScheme", ["seriesIdx", val]) elif action.actionID == "AddData": seriesIdx = getActionArgumentValue(action, "SeriesIndex") val = getActionArgumentValue(action, "Value") writeActionFunc(text, action, "addDataToSeries", [seriesIdx, val, "NULL"]) elif action.actionID == "SetData": catIdx = getActionArgumentValue(action, "CategoryIndex") seriesIdx = getActionArgumentValue(action, "SeriesIndex") val = getActionArgumentValue(action, "Value") variables["categoryIdx"] = "uint32_t" variables["seriesIdx"] = "uint32_t" writeActionFunc(text, action, "setDataInSeries", [seriesIdx, catIdx, val]) elif action.actionID == "DeleteData": writeActionFunc(text, action, "clearData", []) else: generateWidgetAction(text, variables, owner, event, action)
widget = widget_default() widget.width = 101 widget.height = 101 widget.border = 'None' widget.background = 'None' commonDefaults['BarGraphWidget'] = widget def generate_bar_graph_widget(file, screen, bar, parentName): name = bar.getName() file.write(' %s = leBarGraphWidget_New();' % name) generate_base_widget(file, screen, bar) write_set_boolean(file, name, 'Stacked', bar.getStacked(), False) write_set_boolean(file, name, 'FillGraphArea', bar.getFillGraphArea(), True) write_set_int(file, name, 'TickLength', bar.getTickLength(), 5) if bar.getMinValue() != 0: file.write(' %s->fn->setMinValue(%s, BAR_GRAPH_AXIS_0, %d);' % (name, name, bar.getMinValue())) if bar.getMaxValue() != 100: file.write(' %s->fn->setMaxValue(%s, BAR_GRAPH_AXIS_0, %d);' % (name, name, bar.getMaxValue())) if bar.getTickInterval() != 10: file.write(' %s->fn->setValueAxisTicksInterval(%s, BAR_GRAPH_AXIS_0, %d);' % (name, name, bar.getTickInterval())) if bar.getSubtickInterval() != 5: file.write(' %s->fn->setValueAxisSubticksInterval(%s, BAR_GRAPH_AXIS_0, %d);' % (name, name, bar.getSubtickInterval())) if bar.getValueAxisTicksVisible() == False: file.write(' %s->fn->setValueAxisTicksVisible(%s, BAR_GRAPH_AXIS_0, LE_FALSE);' % (name, name)) if bar.getValueGridlinesVisible() == False: file.write(' %s->fn->setGridLinesVisible(%s, BAR_GRAPH_AXIS_0, LE_FALSE);' % (name, name)) position = bar.getValueAxisTicksPosition().toString() if position != 'Center': if position == 'Inside': position = 'BAR_GRAPH_TICK_IN' elif position == 'Outside': position = 'BAR_GRAPH_TICK_OUT' else: position = 'BAR_GRAPH_TICK_CENTER' file.write(' %s->fn->setValueAxisTicksPosition(%s, BAR_GRAPH_AXIS_0, %s);' % (name, name, position)) if bar.getValueAxisLabelsVisible() == False: file.write(' %s->fn->setValueAxisLabelsVisible(%s, BAR_GRAPH_AXIS_0, LE_FALSE);' % (name, name)) if bar.getValueAxisSubticksVisible() == False: file.write(' %s->fn->setValueAxisSubticksVisible(%s, BAR_GRAPH_AXIS_0, LE_FALSE);' % (name, name)) position = bar.getValueAxisSubticksPosition().toString() if position != 'Center': if position == 'Inside': position = 'BAR_GRAPH_TICK_IN' elif position == 'Outside': position = 'BAR_GRAPH_TICK_OUT' else: position = 'BAR_GRAPH_TICK_CENTER' file.write(' %s->fn->setValueAxisSubticksPosition(%s, BAR_GRAPH_AXIS_0, %s);' % (name, name, position)) write_set_font_asset_name(file, name, 'TicksLabelFont', bar.getLabelFontName()) write_set_boolean(file, name, 'CategoryAxisTicksVisible', bar.getCategoryAxisTicksVisible(), True) write_set_boolean(file, name, 'CategoryAxisLabelsVisible', bar.getCategoryAxisLabelsVisible(), True) position = bar.getCategoryAxisTicksPosition().toString() if position != 'Center': if position == 'Inside': position = 'BAR_GRAPH_TICK_IN' elif position == 'Outside': position = 'BAR_GRAPH_TICK_OUT' else: position = 'BAR_GRAPH_TICK_CENTER' file.write(' %s->fn->setCategoryAxisTicksPosition(%s, %s);' % (name, name, position)) category_list = bar.getCategories() for i in range(0, len(categoryList)): file.write(' %s->fn->addCategory(%s, NULL);' % (name, name)) string_name = craft_string_asset_name(categoryList[i].string) if stringName != 'NULL': file.write(' %s->fn->setCategoryString(%s, %d, (leString*)%s);' % (name, name, i, stringName)) series_list = bar.getDataSeries() if len(seriesList) > 0: for (idx, series) in enumerate(seriesList): file.write(' %s->fn->addSeries(%s, NULL);' % (name, name)) if test_string_validity(series.scheme): file.write(' %s->fn->setSeriesScheme(%s, %d, &%s);' % (name, name, idx, series.scheme)) for data_val in series.data: file.write(' %s->fn->addDataToSeries(%s, %d, %d, NULL);' % (name, name, idx, dataVal)) file.write(' %s->fn->addChild(%s, (leWidget*)%s);' % (parentName, parentName, name)) file.writeNewLine() def generate_bar_graph_action(text, variables, owner, event, action): name = action.targetName if action.actionID == 'SetTickLength': val = get_action_argument_value(action, 'Length') write_action_func(text, action, 'setTickLength', [val]) elif action.actionID == 'SetFillGraphArea': val = get_action_argument_value(action, 'Fill') write_action_func(text, action, 'setFillGraphArea', [val]) elif action.actionID == 'SetStacked': val = get_action_argument_value(action, 'Stacked') write_action_func(text, action, 'setStacked', [val]) elif action.actionID == 'SetMax': val = get_action_argument_value(action, 'Value') write_action_func(text, action, 'setMaxValue', ['BAR_GRAPH_AXIS_0', val]) elif action.actionID == 'SetMin': val = get_action_argument_value(action, 'Value') write_action_func(text, action, 'setMinValue', ['BAR_GRAPH_AXIS_0', val]) elif action.actionID == 'SetTickInterval': val = get_action_argument_value(action, 'Interval') write_action_func(text, action, 'setValueAxisTicksInterval', ['BAR_GRAPH_AXIS_0', val]) elif action.actionID == 'SetSubtickInterval': val = get_action_argument_value(action, 'Interval') write_action_func(text, action, 'setValueAxisSubticksInterval', ['BAR_GRAPH_AXIS_0', val]) elif action.actionID == 'ShowValueAxisLabels': val = get_action_argument_value(action, 'Show') write_action_func(text, action, 'setValueAxisLabelsVisible', ['BAR_GRAPH_AXIS_0', val]) elif action.actionID == 'ShowValueAxisTicks': val = get_action_argument_value(action, 'Show') write_action_func(text, action, 'setValueAxisTicksVisible', ['BAR_GRAPH_AXIS_0', val]) elif action.actionID == 'ShowValueAxisSubticks': val = get_action_argument_value(action, 'Show') write_action_func(text, action, 'setValueAxisSubticksVisible', ['BAR_GRAPH_AXIS_0', val]) elif action.actionID == 'ShowValueAxisGrid': val = get_action_argument_value(action, 'Show') write_action_func(text, action, 'setGridLinesVisible', ['BAR_GRAPH_AXIS_0', val]) elif action.actionID == 'SetValueAxisTickPosition': val = get_action_argument_value(action, 'Position') if val == 'Center': val = 'BAR_GRAPH_TICK_CENTER' elif val == 'Inside': val = 'BAR_GRAPH_TICK_IN' elif val == 'Outside': val = 'BAR_GRAPH_TICK_OUT' write_action_func(text, action, 'setValueAxisTicksPosition', ['BAR_GRAPH_AXIS_0', val]) elif action.actionID == 'SetValueAxisSubtickPosition': val = get_action_argument_value(action, 'Position') if val == 'Center': val = 'BAR_GRAPH_TICK_CENTER' elif val == 'Inside': val = 'BAR_GRAPH_TICK_IN' elif val == 'Outside': val = 'BAR_GRAPH_TICK_OUT' write_action_func(text, action, 'setValueAxisSubticksPosition', ['BAR_GRAPH_AXIS_0', val]) elif action.actionID == 'ShowCategoryAxisLabels': val = get_action_argument_value(action, 'Show') write_action_func(text, action, 'setCategoryAxisLabelsVisible', [val]) elif action.actionID == 'ShowCategoryAxisTicks': val = get_action_argument_value(action, 'Show') write_action_func(text, action, 'setCategoryAxisTicksVisible', [val]) elif action.actionID == 'SetCategoryAxisTickPosition': val = get_action_argument_value(action, 'Position') if val == 'Center': val = 'BAR_GRAPH_TICK_CENTER' elif val == 'Inside': val = 'BAR_GRAPH_TICK_IN' elif val == 'Outside': val = 'BAR_GRAPH_TICK_OUT' write_action_func(text, action, 'setCategoryAxisTicksPosition', [val]) elif action.actionID == 'SetLabelFont': val = get_action_argument_value(action, 'FontAsset') write_action_func(text, action, 'setTicksLabelFont', [val]) elif action.actionID == 'AddCategory': val = get_action_argument_value(action, 'StringAsset') variables['categoryIdx'] = 'uint32_t' write_action_func(text, action, 'addCategory', ['&categoryIdx']) write_action_func(text, action, 'setCategoryString', ['categoryIdx', val]) elif action.actionID == 'AddSeries': val = get_action_argument_value(action, 'Scheme') variables['seriesIdx'] = 'uint32_t' write_action_func(text, action, 'addSeries', ['&seriesIdx']) write_action_func(text, action, 'setSeriesScheme', ['seriesIdx', val]) elif action.actionID == 'AddData': series_idx = get_action_argument_value(action, 'SeriesIndex') val = get_action_argument_value(action, 'Value') write_action_func(text, action, 'addDataToSeries', [seriesIdx, val, 'NULL']) elif action.actionID == 'SetData': cat_idx = get_action_argument_value(action, 'CategoryIndex') series_idx = get_action_argument_value(action, 'SeriesIndex') val = get_action_argument_value(action, 'Value') variables['categoryIdx'] = 'uint32_t' variables['seriesIdx'] = 'uint32_t' write_action_func(text, action, 'setDataInSeries', [seriesIdx, catIdx, val]) elif action.actionID == 'DeleteData': write_action_func(text, action, 'clearData', []) else: generate_widget_action(text, variables, owner, event, action)
#!/usr/bin/python35 fp = open('hello.txt') print(fp.__next__()) print(next(fp)) fp.close()
fp = open('hello.txt') print(fp.__next__()) print(next(fp)) fp.close()
GLOBAL_TRANSITIONS = "global_transitions" TRANSITIONS = "transitions" RESPONSE = "response" PROCESSING = "processing" GRAPH = "graph" MISC = "misc"
global_transitions = 'global_transitions' transitions = 'transitions' response = 'response' processing = 'processing' graph = 'graph' misc = 'misc'
################################################################################# # # # Copyright 2018/08/16 Zachary Priddy ([email protected]) https://zpriddy.com # # # # 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. # # # ################################################################################# class WTFRequest(object): def __init__(self, request_name, pid=None, **kwargs): self._request_name = request_name self._pid = pid self._kwargs = kwargs self.set_kwargs() def set_kwargs(self): for name, value in self._kwargs.iteritems(): setattr(self, name, value) @property def request_name(self): return self._request_name @property def pid(self): return self._pid @property def kwargs(self): return self._kwargs class WTFAction(WTFRequest): def __init__(self, action_name, pid=None, **kwargs): super(WTFAction, self).__init__(action_name, pid, **kwargs)
class Wtfrequest(object): def __init__(self, request_name, pid=None, **kwargs): self._request_name = request_name self._pid = pid self._kwargs = kwargs self.set_kwargs() def set_kwargs(self): for (name, value) in self._kwargs.iteritems(): setattr(self, name, value) @property def request_name(self): return self._request_name @property def pid(self): return self._pid @property def kwargs(self): return self._kwargs class Wtfaction(WTFRequest): def __init__(self, action_name, pid=None, **kwargs): super(WTFAction, self).__init__(action_name, pid, **kwargs)
def merge_the_tools(string, k): lens = len(string) for i in range(0, lens, k): lists = [j for j in string[i:i+k]] print(''.join(sorted(set(lists), key=lists.index))) s = input() n = int(input()) merge_the_tools(s, n)
def merge_the_tools(string, k): lens = len(string) for i in range(0, lens, k): lists = [j for j in string[i:i + k]] print(''.join(sorted(set(lists), key=lists.index))) s = input() n = int(input()) merge_the_tools(s, n)
# Stepper mode select STEPPER_m0 = 17 STEPPER_m1 = 27 STEPPER_m2 = 22 # First wheel GPIO Pin WHEEL1_step = 21 WHEEL1_dir = 20 # Second wheel GPIO Pin WHEEL2_step = 11 WHEEL2_dir = 10 # Third wheel GPIO Pin WHEEL3_step = 7 WHEEL3_dir = 8 # Fourth wheel GPIO Pin WHEEL4_step = 24 WHEEL4_dir = 23 CW = 1 # Clockwise rotation CCW = 0 # Counter-clockwise rotation STEPS_PER_REVOLUTION = 800 # Steps per Revolution (360/1.8) * 4. Multiply by 4 because quarter step. STEPPER_DELAY = 0.0005
stepper_m0 = 17 stepper_m1 = 27 stepper_m2 = 22 wheel1_step = 21 wheel1_dir = 20 wheel2_step = 11 wheel2_dir = 10 wheel3_step = 7 wheel3_dir = 8 wheel4_step = 24 wheel4_dir = 23 cw = 1 ccw = 0 steps_per_revolution = 800 stepper_delay = 0.0005
def compute(a, b): return a + b def Test1(): a = -1 b = 1 assert compute(a, b) == -1 def testabc(): a = 0 b = -1 assert compute(a, b) == 0 def Test3(): a = 1 b = 10 assert compute(a, b) == 10 def Test4(): a = -1 b = -1 assert compute(a, b) == 1
def compute(a, b): return a + b def test1(): a = -1 b = 1 assert compute(a, b) == -1 def testabc(): a = 0 b = -1 assert compute(a, b) == 0 def test3(): a = 1 b = 10 assert compute(a, b) == 10 def test4(): a = -1 b = -1 assert compute(a, b) == 1
URL_PROJECT_VIEW="http://tasks.hotosm.org/project/{project}" URL_PROJECT_EDIT="http://tasks.hotosm.org/project/{project}/edit" URL_PROJECT_TASKS="http://tasks.hotosm.org/project/{project}/tasks.json" URL_CHANGESET_VIEW="http://www.openstreetmap.org/changeset/{changeset}" URL_CHANGESET_API ="https://api.openstreetmap.org/api/0.6/changeset/{changeset}" URL_USER_VIEW="https://www.openstreetmap.org/user/{user}" TASK_STATE_READY = 0 TASK_STATE_INVALIDATED = 1 TASK_STATE_DONE = 2 TASK_STATE_VALIDATED = 3 TASK_STATE_REMOVED = -1
url_project_view = 'http://tasks.hotosm.org/project/{project}' url_project_edit = 'http://tasks.hotosm.org/project/{project}/edit' url_project_tasks = 'http://tasks.hotosm.org/project/{project}/tasks.json' url_changeset_view = 'http://www.openstreetmap.org/changeset/{changeset}' url_changeset_api = 'https://api.openstreetmap.org/api/0.6/changeset/{changeset}' url_user_view = 'https://www.openstreetmap.org/user/{user}' task_state_ready = 0 task_state_invalidated = 1 task_state_done = 2 task_state_validated = 3 task_state_removed = -1
def contains_cycle(first_node): nodes_visited = set() if not first_node or not first_node.next: return False current_node = first_node.next while current_node.next: if current_node.value in nodes_visited: return True else: nodes_visited.add(current_node.value) current_node = current_node.next return False
def contains_cycle(first_node): nodes_visited = set() if not first_node or not first_node.next: return False current_node = first_node.next while current_node.next: if current_node.value in nodes_visited: return True else: nodes_visited.add(current_node.value) current_node = current_node.next return False
pessoas = {'nome': 'Gustavo', 'sexo ': 'M', 'idade' : 22} print(pessoas) print(pessoas['idade'])## 22 print(f' O {pessoas["nome"]} tem {pessoas["idade"]} anos.')## O Gustavo tem 22 anos. print(pessoas.keys())## dict_keys(['nome', 'sexo ', 'idade']) print(pessoas.values())##dict_values(['Gustavo', 'M', 22]) print(pessoas.items())##dict_items([('nome', 'Gustavo'), ('sexo ', 'M'), ('idade', 22)]) for k in pessoas.keys(): print(k)## nome sexo idade for k, v in pessoas.items(): print(f'{k} = {v}') ## nome = Gustavo // sexo = M // idade=22 pessoas['peso ']= 98.5 ## apaga sexo] for k, v in pessoas.items(): print(f'{k} = {v}') ## nome = Gustavo // sexo = M // idade=22// peso = 98.5
pessoas = {'nome': 'Gustavo', 'sexo ': 'M', 'idade': 22} print(pessoas) print(pessoas['idade']) print(f" O {pessoas['nome']} tem {pessoas['idade']} anos.") print(pessoas.keys()) print(pessoas.values()) print(pessoas.items()) for k in pessoas.keys(): print(k) for (k, v) in pessoas.items(): print(f'{k} = {v}') pessoas['peso '] = 98.5 for (k, v) in pessoas.items(): print(f'{k} = {v}')
CONF_Main = { "environment": "lux_gym:lux-v0", "setup": "rl", "model_name": "actor_critic_sep_residual_six_actions", "n_points": 40, # check tfrecords reading transformation merge_rl } CONF_Scrape = { "lux_version": "3.1.0", "scrape_type": "single", "parallel_calls": 8, "is_for_rl": True, "is_pg_rl": True, "team_name": None, # "Toad Brigade", "only_wins": False, "only_top_teams": False, } CONF_Collect = { "is_for_imitator": False, "is_for_rl": True, "is_pg_rl": True, "only_wins": False, } CONF_Evaluate = { "eval_compare_agent": "compare_agent_sub13", } CONF_Imitate = { "batch_size": 300, "self_imitation": False, "with_evaluation": True, } CONF_RL = { "rl_type": "continuous_ac_mc", # "lambda": 0.8, "debug": False, "default_lr": 1e-5, "batch_size": 300, # "iterations_number": 1000, # "save_interval": 100, "entropy_c": 1e-5, "entropy_c_decay": 0.3, }
conf__main = {'environment': 'lux_gym:lux-v0', 'setup': 'rl', 'model_name': 'actor_critic_sep_residual_six_actions', 'n_points': 40} conf__scrape = {'lux_version': '3.1.0', 'scrape_type': 'single', 'parallel_calls': 8, 'is_for_rl': True, 'is_pg_rl': True, 'team_name': None, 'only_wins': False, 'only_top_teams': False} conf__collect = {'is_for_imitator': False, 'is_for_rl': True, 'is_pg_rl': True, 'only_wins': False} conf__evaluate = {'eval_compare_agent': 'compare_agent_sub13'} conf__imitate = {'batch_size': 300, 'self_imitation': False, 'with_evaluation': True} conf_rl = {'rl_type': 'continuous_ac_mc', 'debug': False, 'default_lr': 1e-05, 'batch_size': 300, 'entropy_c': 1e-05, 'entropy_c_decay': 0.3}
# Transmission registers TXB0CTRL = 0x30 TXB1CTRL = 0x40 TXB2CTRL = 0x50 TXRTSCTRL = 0x0D TXB0SIDH = 0x31 TXB1SIDH = 0x41 TXB2SIDH = 0x51 TXB0SIDL = 0x32 TXB1SIDL = 0x42 TXB2SIDL = 0x52 TXB0EID8 = 0x33 TXB1EID8 = 0x43 TXB0EID8 = 0x53 TXB0EID0 = 0x34 TXB1EID0 = 0x44 TXB2EID0 = 0x54 TXB0DLC = 0x35 TXB1DLC = 0x45 TXB2DLC = 0x55 TXB0D = 0x36 TXB1D = 0x46 TXB2D = 0x56 # receive registers RXB0CTRL = 0x60 RXB1CTRL = 0x70 BFPCTRL = 0x0C RXB0SIDH = 0x61 RXB1SIDH = 0x71 RXB0SIDL = 0x62 RXB1SIDL = 0x72 RXB0EID8 = 0x63 RXB1EID8 = 0x73 RXB0EID0 = 0x64 RXB1EID0 = 0x74 RXB0DLC = 0x65 RXB1DLC = 0x75 RXB0D0 = 0x66 RXB0D1 = 0x67 RXB0D2 = 0x68 RXB0D3 = 0x69 RXB0D4 = 0x6A RXB0D5 = 0x6B RXB0D6 = 0x6C RXB0D7 = 0x6D RXB1D = 0x76 # Filter Registers RXF0SIDH = 0x00 RXF1SIDH = 0x04 RXF2SIDH = 0x08 RXF3SIDH = 0x10 RXF4SIDH = 0x14 RXF5SIDH = 0x18 RXF0SIDL = 0x01 RXF1SIDL = 0x05 RXF2SIDL = 0x09 RXF3SIDL = 0x11 RXF4SIDL = 0x15 RXF5SIDL = 0x19 RXF0EID8 = 0x02 RXF1EID8 = 0x06 RXF2EID8 = 0x0A RXF3EID8 = 0x12 RXF4EID8 = 0x16 RXF5EID8 = 0x1A RXF0EID0 = 0x03 RXF1EID0 = 0x07 RXF2EID0 = 0x0B RXF3EID0 = 0x13 RXF4EID0 = 0x17 RXF5EID0 = 0x1B #Mask Registers RXM0SIDH = 0x20 RXM1SIDH = 0x24 RXM0SIDL = 0x21 RXM1SIDL = 0x25 RXM0EID8 = 0x22 RXM1EID8 = 0x26 RXM0EID0 = 0x23 RXM1EID0 = 0x27 # Configuration Registers CNF1 = 0x2A CNF2 = 0x29 CNF3 = 0x28 TEC = 0x1C REC = 0x1D EFLG = 0x2D CANINTE = 0x2B CANINTF = 0x2C CANCTRL = 0x0F CANSTAT = 0x0E
txb0_ctrl = 48 txb1_ctrl = 64 txb2_ctrl = 80 txrtsctrl = 13 txb0_sidh = 49 txb1_sidh = 65 txb2_sidh = 81 txb0_sidl = 50 txb1_sidl = 66 txb2_sidl = 82 txb0_eid8 = 51 txb1_eid8 = 67 txb0_eid8 = 83 txb0_eid0 = 52 txb1_eid0 = 68 txb2_eid0 = 84 txb0_dlc = 53 txb1_dlc = 69 txb2_dlc = 85 txb0_d = 54 txb1_d = 70 txb2_d = 86 rxb0_ctrl = 96 rxb1_ctrl = 112 bfpctrl = 12 rxb0_sidh = 97 rxb1_sidh = 113 rxb0_sidl = 98 rxb1_sidl = 114 rxb0_eid8 = 99 rxb1_eid8 = 115 rxb0_eid0 = 100 rxb1_eid0 = 116 rxb0_dlc = 101 rxb1_dlc = 117 rxb0_d0 = 102 rxb0_d1 = 103 rxb0_d2 = 104 rxb0_d3 = 105 rxb0_d4 = 106 rxb0_d5 = 107 rxb0_d6 = 108 rxb0_d7 = 109 rxb1_d = 118 rxf0_sidh = 0 rxf1_sidh = 4 rxf2_sidh = 8 rxf3_sidh = 16 rxf4_sidh = 20 rxf5_sidh = 24 rxf0_sidl = 1 rxf1_sidl = 5 rxf2_sidl = 9 rxf3_sidl = 17 rxf4_sidl = 21 rxf5_sidl = 25 rxf0_eid8 = 2 rxf1_eid8 = 6 rxf2_eid8 = 10 rxf3_eid8 = 18 rxf4_eid8 = 22 rxf5_eid8 = 26 rxf0_eid0 = 3 rxf1_eid0 = 7 rxf2_eid0 = 11 rxf3_eid0 = 19 rxf4_eid0 = 23 rxf5_eid0 = 27 rxm0_sidh = 32 rxm1_sidh = 36 rxm0_sidl = 33 rxm1_sidl = 37 rxm0_eid8 = 34 rxm1_eid8 = 38 rxm0_eid0 = 35 rxm1_eid0 = 39 cnf1 = 42 cnf2 = 41 cnf3 = 40 tec = 28 rec = 29 eflg = 45 caninte = 43 canintf = 44 canctrl = 15 canstat = 14
# Heroku PostgreSQL credentials, rename this file to config.py HOST = "placeholder" DB = "placeholder" USER = "placeholder" PASSWORD = "placeholder" PORT = "5432"
host = 'placeholder' db = 'placeholder' user = 'placeholder' password = 'placeholder' port = '5432'
# Every neuron has a unique connection to the previous neuron. inputs = [3.1 , 2.5 , 5.4] # Every input is going to have a unique weight weights = [4.5 , 7.6 , 2.4] # Every neuron is going to have a unique bias bias = 3 # Now let's check the output from the neuron output = inputs[0] * weights[0] + inputs[1] * weights[1] + inputs[2] * weights[2] + bias # Now let's print the output print(output)
inputs = [3.1, 2.5, 5.4] weights = [4.5, 7.6, 2.4] bias = 3 output = inputs[0] * weights[0] + inputs[1] * weights[1] + inputs[2] * weights[2] + bias print(output)
def generate_odd_nums(start, end): for num in range(start, end+1): if num % 2 !=0: print(num, end=" ") generate_odd_nums(start = 0, end = 15)
def generate_odd_nums(start, end): for num in range(start, end + 1): if num % 2 != 0: print(num, end=' ') generate_odd_nums(start=0, end=15)
__author__ = 'KKishore' PAD_WORD = '#=KISHORE=#' HEADERS = ['class', 'sms'] FEATURE_COL = 'sms' LABEL_COL = 'class' WEIGHT_COLUNM_NAME = 'weight' TARGET_LABELS = ['spam', 'ham'] TARGET_SIZE = len(TARGET_LABELS) HEADER_DEFAULTS = [['NA'], ['NA']] MAX_DOCUMENT_LENGTH = 100
__author__ = 'KKishore' pad_word = '#=KISHORE=#' headers = ['class', 'sms'] feature_col = 'sms' label_col = 'class' weight_colunm_name = 'weight' target_labels = ['spam', 'ham'] target_size = len(TARGET_LABELS) header_defaults = [['NA'], ['NA']] max_document_length = 100
class PracticeCenter: def __init__(self, practice_center_id, name, email=None, web_site=None, phone_number=None, climates=None, recommendations=None, average_note=None): self.id = practice_center_id self.name = name self.email = email self.web_site = web_site self.phone_number = phone_number self.climates = [] if climates is None else climates self.recommendations = [] if recommendations is None else recommendations self.average_note = 0 if average_note is None else average_note def __eq__(self, other): if isinstance(other, PracticeCenter): return self.id == other.id return False
class Practicecenter: def __init__(self, practice_center_id, name, email=None, web_site=None, phone_number=None, climates=None, recommendations=None, average_note=None): self.id = practice_center_id self.name = name self.email = email self.web_site = web_site self.phone_number = phone_number self.climates = [] if climates is None else climates self.recommendations = [] if recommendations is None else recommendations self.average_note = 0 if average_note is None else average_note def __eq__(self, other): if isinstance(other, PracticeCenter): return self.id == other.id return False
class Rectangle: def __init__(self, width, height): self.width = width self.height = height def __str__(self): return "Rectangle(width=" + str(self.width) + ", height="+ str(self.height) + ")" def set_width(self, width): self.width = width def set_height(self, height): self.height = height def get_area(self): return self.width * self.height def get_perimeter(self): return 2 * (self.width + self.height) def get_diagonal(self): return (self.width ** 2 + self.height ** 2) ** 0.5 def get_picture(self): if(self.width > 50 or self.height > 50): return "Too big for picture." string = "" for i in range(self.height): for j in range(self.width): string += '*' string += '\n' return string def get_amount_inside(self, another_shape): return self.get_area() // another_shape.get_area() class Square(Rectangle): def __init__(self, length): self.length = length def __str__(self): return "Square(side=" + str(self.length) + ")" def set_side(self, length): self.length = length def set_width(self, length): self.length = length def set_height(self, length): self.length = length def get_area(self): return self.length ** 2 def get_perimeter(self): return 4 * self.length def get_diagonal(self): return (2 * self.length ** 2) ** 0.5 def get_picture(self): if(self.length > 50): return "Too big for picture." string = "" for i in range(self.length): for j in range(self.length): string += '*' string += '\n' return string
class Rectangle: def __init__(self, width, height): self.width = width self.height = height def __str__(self): return 'Rectangle(width=' + str(self.width) + ', height=' + str(self.height) + ')' def set_width(self, width): self.width = width def set_height(self, height): self.height = height def get_area(self): return self.width * self.height def get_perimeter(self): return 2 * (self.width + self.height) def get_diagonal(self): return (self.width ** 2 + self.height ** 2) ** 0.5 def get_picture(self): if self.width > 50 or self.height > 50: return 'Too big for picture.' string = '' for i in range(self.height): for j in range(self.width): string += '*' string += '\n' return string def get_amount_inside(self, another_shape): return self.get_area() // another_shape.get_area() class Square(Rectangle): def __init__(self, length): self.length = length def __str__(self): return 'Square(side=' + str(self.length) + ')' def set_side(self, length): self.length = length def set_width(self, length): self.length = length def set_height(self, length): self.length = length def get_area(self): return self.length ** 2 def get_perimeter(self): return 4 * self.length def get_diagonal(self): return (2 * self.length ** 2) ** 0.5 def get_picture(self): if self.length > 50: return 'Too big for picture.' string = '' for i in range(self.length): for j in range(self.length): string += '*' string += '\n' return string
class Test: def foo(a): if a == 'foo': return 'foo' return 'bar'
class Test: def foo(a): if a == 'foo': return 'foo' return 'bar'
#------------------------------------------------------------------- # Copyright (c) 2021, Scott D. Peckham # # Oct. 2021. Added to bypass old tf_utils.py for version, etc. # #------------------------------------------------------------------- # Notes: Update these whenever a new version is released #------------------------------------------------------------------- # # name() # version_number() # build_date() # version_string() # #------------------------------------------------------------------- def name(): return 'Stochastic Conflict Model' # name() #------------------------------------------------------------------- def version_number(): return 0.8 # version_number() #------------------------------------------------------------------- def build_date(): return '2021-10-13' # build_date() #------------------------------------------------------------------- def version_string(): num_str = str( version_number() ) date_str = ' (' + build_date() + ')' ver_string = name() + ' Version ' + num_str + date_str return ver_string # version_string() #-------------------------------------------------------------------
def name(): return 'Stochastic Conflict Model' def version_number(): return 0.8 def build_date(): return '2021-10-13' def version_string(): num_str = str(version_number()) date_str = ' (' + build_date() + ')' ver_string = name() + ' Version ' + num_str + date_str return ver_string
first_name = "ada" last_name = "lovelace" full_name = f"{first_name} {last_name}" #or full_name = "{} {}".format(first_name,last_name) #print(full_name) message = f"Hello, {full_name.title()}!" print(message)
first_name = 'ada' last_name = 'lovelace' full_name = f'{first_name} {last_name}' full_name = '{} {}'.format(first_name, last_name) message = f'Hello, {full_name.title()}!' print(message)
''' the permission will be set in the database and only the managers will have permission to cancel an order already completed ''' class User(): def __init__(self, userid, username, permission): self.userid=userid self.username=username self.permission=permission def getUserNumber(self): return self.userid def getUserName(self): return self.username def getUserPermission(self): return self.permission def __str__(self): return self.username
""" the permission will be set in the database and only the managers will have permission to cancel an order already completed """ class User: def __init__(self, userid, username, permission): self.userid = userid self.username = username self.permission = permission def get_user_number(self): return self.userid def get_user_name(self): return self.username def get_user_permission(self): return self.permission def __str__(self): return self.username
class Solution: def recurse(self, A, stack) : if A == "" : self.ans.append(stack) temp_str = "" n = len(A) for i, ch in enumerate(A) : temp_str += ch if self.isPalindrome(temp_str) : self.recurse(A[i+1:], stack+[temp_str]) def isPalindrome(self, string) : if string == string[::-1] : return True return False # @param A : string # @return a list of list of strings def partition(self, A): n = len(A) if n <= 1 : return [A] self.ans = [] self.recurse(A, []) self.ans.sort() return self.ans
class Solution: def recurse(self, A, stack): if A == '': self.ans.append(stack) temp_str = '' n = len(A) for (i, ch) in enumerate(A): temp_str += ch if self.isPalindrome(temp_str): self.recurse(A[i + 1:], stack + [temp_str]) def is_palindrome(self, string): if string == string[::-1]: return True return False def partition(self, A): n = len(A) if n <= 1: return [A] self.ans = [] self.recurse(A, []) self.ans.sort() return self.ans
# name: TColors # Version: 1 # Created by: Grigory Sazanov # GitHub: https://github.com/SazanovGrigory class TerminalColors: # Description: Class that can be used to color terminal output # Example: print('GitHub: '+f"{BColors.TerminalColors.UNDERLINE}https://github.com/SazanovGrigory{BColors.TerminalColors.ENDC}") HEADER ='\033[95m' OKBLUE ='\033[94m' OKCYAN ='\033[96m' OKGREEN ='\033[92m' WARNING ='\033[93m' FAIL ='\033[91m' ENDC ='\033[0m' BOLD ='\033[1m' UNDERLINE ='\033[4m' def main(): print('Name: '+f"{TerminalColors.HEADER}TColors{TerminalColors.ENDC}") print('Version: '+f"{TerminalColors.WARNING}1{TerminalColors.ENDC}") print('Created by: '+f"{TerminalColors.BOLD}Grigory Sazanov{TerminalColors.ENDC}") print('GitHub: '+f"{TerminalColors.UNDERLINE}https://github.com/SazanovGrigory{TerminalColors.ENDC}") print(f"{TerminalColors.OKGREEN}Description: This is just a class that can be used to color terminal output{TerminalColors.ENDC}") print("Example: print(\"GitHub: \"+f\"{TColors.TerminalColors.UNDERLINE}Some text here{TColors.TerminalColors.ENDC}\")") print('Colors:') print(' '+f"{TerminalColors.HEADER}HEADER{TerminalColors.ENDC}") print(' '+f"{TerminalColors.OKBLUE}OKBLUE{TerminalColors.ENDC}") print(' '+f"{TerminalColors.OKCYAN}OKCYAN{TerminalColors.ENDC}") print(' '+f"{TerminalColors.OKGREEN}OKGREEN{TerminalColors.ENDC}") print(' '+f"{TerminalColors.WARNING}WARNING{TerminalColors.ENDC}") print(' '+f"{TerminalColors.FAIL}FAIL{TerminalColors.ENDC}") print(' '+f"{TerminalColors.BOLD}BOLD{TerminalColors.ENDC}") print(' '+f"{TerminalColors.UNDERLINE}UNDERLINE{TerminalColors.ENDC}") if __name__ == '__main__': main()
class Terminalcolors: header = '\x1b[95m' okblue = '\x1b[94m' okcyan = '\x1b[96m' okgreen = '\x1b[92m' warning = '\x1b[93m' fail = '\x1b[91m' endc = '\x1b[0m' bold = '\x1b[1m' underline = '\x1b[4m' def main(): print('Name: ' + f'{TerminalColors.HEADER}TColors{TerminalColors.ENDC}') print('Version: ' + f'{TerminalColors.WARNING}1{TerminalColors.ENDC}') print('Created by: ' + f'{TerminalColors.BOLD}Grigory Sazanov{TerminalColors.ENDC}') print('GitHub: ' + f'{TerminalColors.UNDERLINE}https://github.com/SazanovGrigory{TerminalColors.ENDC}') print(f'{TerminalColors.OKGREEN}Description: This is just a class that can be used to color terminal output{TerminalColors.ENDC}') print('Example: print("GitHub: "+f"{TColors.TerminalColors.UNDERLINE}Some text here{TColors.TerminalColors.ENDC}")') print('Colors:') print(' ' + f'{TerminalColors.HEADER}HEADER{TerminalColors.ENDC}') print(' ' + f'{TerminalColors.OKBLUE}OKBLUE{TerminalColors.ENDC}') print(' ' + f'{TerminalColors.OKCYAN}OKCYAN{TerminalColors.ENDC}') print(' ' + f'{TerminalColors.OKGREEN}OKGREEN{TerminalColors.ENDC}') print(' ' + f'{TerminalColors.WARNING}WARNING{TerminalColors.ENDC}') print(' ' + f'{TerminalColors.FAIL}FAIL{TerminalColors.ENDC}') print(' ' + f'{TerminalColors.BOLD}BOLD{TerminalColors.ENDC}') print(' ' + f'{TerminalColors.UNDERLINE}UNDERLINE{TerminalColors.ENDC}') if __name__ == '__main__': main()
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def solve(self, t1: TreeNode, t2: TreeNode) -> TreeNode: if not t1 and not t2: return None node = TreeNode(0) if t1: node.val += t1.val if t2: node.val += t2.val l = self.solve(t1.left if t1 else None, t2.left if t2 else None) r = self.solve(t1.right if t1 else None, t2.right if t2 else None) node.left = l node.right = r return node def mergeTrees(self, t1: TreeNode, t2: TreeNode) -> TreeNode: return self.solve(t1, t2)
class Treenode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def solve(self, t1: TreeNode, t2: TreeNode) -> TreeNode: if not t1 and (not t2): return None node = tree_node(0) if t1: node.val += t1.val if t2: node.val += t2.val l = self.solve(t1.left if t1 else None, t2.left if t2 else None) r = self.solve(t1.right if t1 else None, t2.right if t2 else None) node.left = l node.right = r return node def merge_trees(self, t1: TreeNode, t2: TreeNode) -> TreeNode: return self.solve(t1, t2)
def foo(): global bar def bar(): pass
def foo(): global bar def bar(): pass
class ParadoxException(Exception): pass class ParadoxConnectError(ParadoxException): def __init__(self) -> None: super().__init__('Unable to connect to panel') class ParadoxCommandError(ParadoxException): pass class ParadoxTimeout(ParadoxException): pass
class Paradoxexception(Exception): pass class Paradoxconnecterror(ParadoxException): def __init__(self) -> None: super().__init__('Unable to connect to panel') class Paradoxcommanderror(ParadoxException): pass class Paradoxtimeout(ParadoxException): pass
class Solution: def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: def merge(l1, l2): if not l1: return l2 if not l2: return l1 if l1[0] < l2[0]: return [l1[0]] + merge(l1[1:], l2) else: return [l2[0]] + merge(l1, l2[1:]) nums = merge(nums1,nums2) l = len(nums) if l%2: return nums[(l-1)//2] else: return (nums[l//2] +nums[l//2 -1])/2
class Solution: def find_median_sorted_arrays(self, nums1: List[int], nums2: List[int]) -> float: def merge(l1, l2): if not l1: return l2 if not l2: return l1 if l1[0] < l2[0]: return [l1[0]] + merge(l1[1:], l2) else: return [l2[0]] + merge(l1, l2[1:]) nums = merge(nums1, nums2) l = len(nums) if l % 2: return nums[(l - 1) // 2] else: return (nums[l // 2] + nums[l // 2 - 1]) / 2
cities = [ 'Riga', 'Daugavpils', 'Liepaja', 'Jelgava', 'Jurmala', 'Ventspils', 'Rezekne', 'Jekabpils', 'Valmiera', 'Ogre', 'Tukums', 'Cesis', 'Salaspils', 'Bolderaja', 'Kuldiga', 'Olaine', 'Saldus', 'Talsi', 'Dobele', 'Kraslava', 'Bauska', 'Ludza', 'Sigulda', 'Livani', 'Daugavgriva', 'Gulbene', 'Madona', 'Limbazi', 'Aizkraukle', 'Preili', 'Balvi', 'Karosta', 'Krustpils', 'Valka', 'Smiltene', 'Aizpute', 'Lielvarde', 'Kekava', 'Grobina', 'Iecava', 'Vilani', 'Plavinas', 'Rujiena', 'Kandava', 'Broceni', 'Salacgriva', 'Ozolnieki', 'Ikskile', 'Saulkrasti', 'Auce', 'Pinki', 'Ilukste', 'Skriveri', 'Ulbroka', 'Dagda', 'Skrunda', 'Karsava', 'Priekule', 'Priekuli', 'Vecumnieki', 'Mazsalaca', 'Kegums', 'Aluksne', 'Ergli', 'Viesite', 'Varaklani', 'Incukalns', 'Baldone', 'Jaunjelgava', 'Lubana', 'Zilupe', 'Mersrags', 'Cesvaine', 'Roja', 'Strenci', 'Vilaka', 'Ape', 'Aloja', 'Ligatne', 'Akniste', 'Nereta', 'Pavilosta', 'Jaunpils', 'Alsunga', 'Smarde', 'Vecpiebalga', 'Rucava', 'Marupe', 'Adazi', 'Aglona', 'Baltinava', 'Bergi', 'Carnikava', 'Drabesi', 'Dundaga', 'Cibla', 'Jaunpiebalga', 'Koceni', 'Koknese', 'Liegi', 'Loja', 'Malpils', 'Matisi', 'Murmuiza', 'Naukseni', 'Nica', 'Pilsrundale', 'Ragana', 'Rauna', 'Riebini', 'Ropazi', 'Garkalne', 'Rugaji', 'Sala', 'Stalbe', 'Vainode', 'Vecvarkava', 'Zelmeni' ]
cities = ['Riga', 'Daugavpils', 'Liepaja', 'Jelgava', 'Jurmala', 'Ventspils', 'Rezekne', 'Jekabpils', 'Valmiera', 'Ogre', 'Tukums', 'Cesis', 'Salaspils', 'Bolderaja', 'Kuldiga', 'Olaine', 'Saldus', 'Talsi', 'Dobele', 'Kraslava', 'Bauska', 'Ludza', 'Sigulda', 'Livani', 'Daugavgriva', 'Gulbene', 'Madona', 'Limbazi', 'Aizkraukle', 'Preili', 'Balvi', 'Karosta', 'Krustpils', 'Valka', 'Smiltene', 'Aizpute', 'Lielvarde', 'Kekava', 'Grobina', 'Iecava', 'Vilani', 'Plavinas', 'Rujiena', 'Kandava', 'Broceni', 'Salacgriva', 'Ozolnieki', 'Ikskile', 'Saulkrasti', 'Auce', 'Pinki', 'Ilukste', 'Skriveri', 'Ulbroka', 'Dagda', 'Skrunda', 'Karsava', 'Priekule', 'Priekuli', 'Vecumnieki', 'Mazsalaca', 'Kegums', 'Aluksne', 'Ergli', 'Viesite', 'Varaklani', 'Incukalns', 'Baldone', 'Jaunjelgava', 'Lubana', 'Zilupe', 'Mersrags', 'Cesvaine', 'Roja', 'Strenci', 'Vilaka', 'Ape', 'Aloja', 'Ligatne', 'Akniste', 'Nereta', 'Pavilosta', 'Jaunpils', 'Alsunga', 'Smarde', 'Vecpiebalga', 'Rucava', 'Marupe', 'Adazi', 'Aglona', 'Baltinava', 'Bergi', 'Carnikava', 'Drabesi', 'Dundaga', 'Cibla', 'Jaunpiebalga', 'Koceni', 'Koknese', 'Liegi', 'Loja', 'Malpils', 'Matisi', 'Murmuiza', 'Naukseni', 'Nica', 'Pilsrundale', 'Ragana', 'Rauna', 'Riebini', 'Ropazi', 'Garkalne', 'Rugaji', 'Sala', 'Stalbe', 'Vainode', 'Vecvarkava', 'Zelmeni']
# 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 ( s ) : n = len ( s ) ; sub_count = ( n * ( n + 1 ) ) // 2 ; arr = [ 0 ] * sub_count ; index = 0 ; for i in range ( n ) : for j in range ( 1 , n - i + 1 ) : arr [ index ] = s [ i : i + j ] ; index += 1 ; arr.sort ( ) ; res = "" ; for i in range ( sub_count ) : res += arr [ i ] ; return res ; #TOFILL if __name__ == '__main__': param = [ ('sqGOi',), ('848580',), ('01001110011001',), ('ZhWXUKmeiI',), ('0917296541285',), ('01101001111100',), ('tjP kR',), ('999907',), ('011100',), ('qJPHNSJOUj',) ] 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(s): n = len(s) sub_count = n * (n + 1) // 2 arr = [0] * sub_count index = 0 for i in range(n): for j in range(1, n - i + 1): arr[index] = s[i:i + j] index += 1 arr.sort() res = '' for i in range(sub_count): res += arr[i] return res if __name__ == '__main__': param = [('sqGOi',), ('848580',), ('01001110011001',), ('ZhWXUKmeiI',), ('0917296541285',), ('01101001111100',), ('tjP kR',), ('999907',), ('011100',), ('qJPHNSJOUj',)] 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)))
morse_translated_to_english = { ".-": "A", "-...": "B", "-.-.": "C", "-..": "D", ".": "E", "..-.": "F", "--.": "G", "....": "H", "..": "I", ".---": "J", "-.-": "K", ".-..": "L", "--": "M", "-.": "N", "---": "O", ".--.": "P", "--.-": "Q", ".-.": "R", "...": "S", "-": "T", "..-": "U", "...-": "V", ".--": "W", "-..-": "X", "-.--": "Y", "--..": "Z", "...---...": "SOS", ".----": "1", "..---": "2", "...--": "3", "....-": "4", ".....": "5", "-....": "6", "--...": "7", "---..": "8", "----.": "9", "-----": "0", ".-.-.-": ".", "--..--": ",", "..--..": "?", ".----.": "'", "-.-.--": "!", "-..-.": "/", "-.--.": "(", "-.--.-": ")", ".-...": "&", "---...": ":", "-.-.-.": ";", "-...-": "=", ".-.-.": "+", "-....-": "-", "..--.-": "_", ".-..-.": '"', "...-..-": "$", ".--.-.": "@", } english_translated_to_morse = dict() for key, value in morse_translated_to_english.items(): english_translated_to_morse[value] = key def morse_code_to_english(incoming_morse_code): output = "" word = "" morse_code_list = incoming_morse_code.split(" ") i = 0 for code in morse_code_list: i += 1 if code != "" and len(morse_code_list) != i: word = word + morse_translated_to_english.get(code, code) elif len(morse_code_list) == i: word = word + morse_translated_to_english.get(code, code) output = output + " " + word else: output = f'{output} {word}' word = "" output = output.strip() output = output.replace(" ", " ") return output def english_to_morse_code(incoming_english): output = "" letter = "" english_list = list(incoming_english.upper()) i = 0 for letters in english_list: i += 1 if letters != "" and len(english_list) != i: letter = letter + " " + english_translated_to_morse.get(letters, letters) elif len(english_list) == i: letter = letter + " " + english_translated_to_morse.get(letters, letters) output = output + " " + letter else: output = f'{output} {letter}' output = output.strip() output = output.replace(" ", " ") return output
morse_translated_to_english = {'.-': 'A', '-...': 'B', '-.-.': 'C', '-..': 'D', '.': 'E', '..-.': 'F', '--.': 'G', '....': 'H', '..': 'I', '.---': 'J', '-.-': 'K', '.-..': 'L', '--': 'M', '-.': 'N', '---': 'O', '.--.': 'P', '--.-': 'Q', '.-.': 'R', '...': 'S', '-': 'T', '..-': 'U', '...-': 'V', '.--': 'W', '-..-': 'X', '-.--': 'Y', '--..': 'Z', '...---...': 'SOS', '.----': '1', '..---': '2', '...--': '3', '....-': '4', '.....': '5', '-....': '6', '--...': '7', '---..': '8', '----.': '9', '-----': '0', '.-.-.-': '.', '--..--': ',', '..--..': '?', '.----.': "'", '-.-.--': '!', '-..-.': '/', '-.--.': '(', '-.--.-': ')', '.-...': '&', '---...': ':', '-.-.-.': ';', '-...-': '=', '.-.-.': '+', '-....-': '-', '..--.-': '_', '.-..-.': '"', '...-..-': '$', '.--.-.': '@'} english_translated_to_morse = dict() for (key, value) in morse_translated_to_english.items(): english_translated_to_morse[value] = key def morse_code_to_english(incoming_morse_code): output = '' word = '' morse_code_list = incoming_morse_code.split(' ') i = 0 for code in morse_code_list: i += 1 if code != '' and len(morse_code_list) != i: word = word + morse_translated_to_english.get(code, code) elif len(morse_code_list) == i: word = word + morse_translated_to_english.get(code, code) output = output + ' ' + word else: output = f'{output} {word}' word = '' output = output.strip() output = output.replace(' ', ' ') return output def english_to_morse_code(incoming_english): output = '' letter = '' english_list = list(incoming_english.upper()) i = 0 for letters in english_list: i += 1 if letters != '' and len(english_list) != i: letter = letter + ' ' + english_translated_to_morse.get(letters, letters) elif len(english_list) == i: letter = letter + ' ' + english_translated_to_morse.get(letters, letters) output = output + ' ' + letter else: output = f'{output} {letter}' output = output.strip() output = output.replace(' ', ' ') return output
# # PySNMP MIB module Wellfleet-NAME-TABLE-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Wellfleet-NAME-TABLE-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:41:01 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") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") IpAddress, iso, Integer32, TimeTicks, Counter32, ObjectIdentity, MibIdentifier, Bits, MibScalar, MibTable, MibTableRow, MibTableColumn, NotificationType, ModuleIdentity, Unsigned32, Counter64, Gauge32 = mibBuilder.importSymbols("SNMPv2-SMI", "IpAddress", "iso", "Integer32", "TimeTicks", "Counter32", "ObjectIdentity", "MibIdentifier", "Bits", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "NotificationType", "ModuleIdentity", "Unsigned32", "Counter64", "Gauge32") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") wfName, = mibBuilder.importSymbols("Wellfleet-COMMON-MIB", "wfName") wfNameEntry = MibIdentifier((1, 3, 6, 1, 4, 1, 18, 3, 3, 2, 18, 1)) wfNameDelete = MibScalar((1, 3, 6, 1, 4, 1, 18, 3, 3, 2, 18, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("created", 1), ("deleted", 2))).clone('created')).setMaxAccess("readwrite") if mibBuilder.loadTexts: wfNameDelete.setStatus('mandatory') if mibBuilder.loadTexts: wfNameDelete.setDescription('Create or Delete the Object Base Record') wfNameName = MibScalar((1, 3, 6, 1, 4, 1, 18, 3, 3, 2, 18, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 64))).setMaxAccess("readwrite") if mibBuilder.loadTexts: wfNameName.setStatus('mandatory') if mibBuilder.loadTexts: wfNameName.setDescription('The BCC name of an object') mibBuilder.exportSymbols("Wellfleet-NAME-TABLE-MIB", wfNameEntry=wfNameEntry, wfNameName=wfNameName, wfNameDelete=wfNameDelete)
(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') (notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance') (ip_address, iso, integer32, time_ticks, counter32, object_identity, mib_identifier, bits, mib_scalar, mib_table, mib_table_row, mib_table_column, notification_type, module_identity, unsigned32, counter64, gauge32) = mibBuilder.importSymbols('SNMPv2-SMI', 'IpAddress', 'iso', 'Integer32', 'TimeTicks', 'Counter32', 'ObjectIdentity', 'MibIdentifier', 'Bits', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'NotificationType', 'ModuleIdentity', 'Unsigned32', 'Counter64', 'Gauge32') (textual_convention, display_string) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'DisplayString') (wf_name,) = mibBuilder.importSymbols('Wellfleet-COMMON-MIB', 'wfName') wf_name_entry = mib_identifier((1, 3, 6, 1, 4, 1, 18, 3, 3, 2, 18, 1)) wf_name_delete = mib_scalar((1, 3, 6, 1, 4, 1, 18, 3, 3, 2, 18, 1, 1), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('created', 1), ('deleted', 2))).clone('created')).setMaxAccess('readwrite') if mibBuilder.loadTexts: wfNameDelete.setStatus('mandatory') if mibBuilder.loadTexts: wfNameDelete.setDescription('Create or Delete the Object Base Record') wf_name_name = mib_scalar((1, 3, 6, 1, 4, 1, 18, 3, 3, 2, 18, 1, 2), display_string().subtype(subtypeSpec=value_size_constraint(0, 64))).setMaxAccess('readwrite') if mibBuilder.loadTexts: wfNameName.setStatus('mandatory') if mibBuilder.loadTexts: wfNameName.setDescription('The BCC name of an object') mibBuilder.exportSymbols('Wellfleet-NAME-TABLE-MIB', wfNameEntry=wfNameEntry, wfNameName=wfNameName, wfNameDelete=wfNameDelete)
#!/usr/bin/env python #### provide two configuration dictionaries: global_setting and feature_set #### ###This is basic configuration global_setting=dict( max_len = 256, # max length for the dataset ) feature_set=dict( ccmpred=dict( suffix = "ccmpred", length = 1, parser_name = "ccmpred_parser_2d", type = "2d", skip = False, ), # secondary structure ss2=dict( suffix = "ss2", length = 3, parser_name = "ss2_parser_1d", type = "1d", skip = False, ), # whether is on surface solv=dict( suffix = "solv", length = 1, parser_name = "solv_parser_1d", type = "1d", skip = False, ), # colstats colstats=dict( suffix = "colstats", length = 22, parser_name = "colstats_parser_1d", type = "1d", skip = False, ), #pairwise conatct features pairstats=dict( suffix = "pairstats", length = 3, parser_name = "pairstats_parser_2d", type = "2d", skip = False, ), # EVFold output evfold=dict( suffix = "evfold", length = 1, parser_name = "evfold_parser_2d", type = "2d", skip = False, ), # NEFF Count neff=dict( suffix = "hhmake", length = 1, parser_name = "neff_parser_1d", type = "1d", skip = False, ), # STD-DEV of CCMPRED output ccmpred_std=dict( suffix = "ccmpred", length = 1, parser_name = "ccmpred_std_parser_1d", type = "1d", skip = False, ), # STD_DEV of EVfold output evfold_std=dict( suffix = "evfold", length = 1, parser_name = "evfold_std_parser_1d", type = "1d", skip = False, ), )
global_setting = dict(max_len=256) feature_set = dict(ccmpred=dict(suffix='ccmpred', length=1, parser_name='ccmpred_parser_2d', type='2d', skip=False), ss2=dict(suffix='ss2', length=3, parser_name='ss2_parser_1d', type='1d', skip=False), solv=dict(suffix='solv', length=1, parser_name='solv_parser_1d', type='1d', skip=False), colstats=dict(suffix='colstats', length=22, parser_name='colstats_parser_1d', type='1d', skip=False), pairstats=dict(suffix='pairstats', length=3, parser_name='pairstats_parser_2d', type='2d', skip=False), evfold=dict(suffix='evfold', length=1, parser_name='evfold_parser_2d', type='2d', skip=False), neff=dict(suffix='hhmake', length=1, parser_name='neff_parser_1d', type='1d', skip=False), ccmpred_std=dict(suffix='ccmpred', length=1, parser_name='ccmpred_std_parser_1d', type='1d', skip=False), evfold_std=dict(suffix='evfold', length=1, parser_name='evfold_std_parser_1d', type='1d', skip=False))
class Solution: def threeSum(self, nums: List[int]) -> List[List[int]]: if not nums: return [] res = [] nums.sort() for i, num in enumerate(nums): if i > 0 and num == nums[i - 1]: continue left, right = i + 1, len(nums) - 1 while left < right: total = num + nums[left] + nums[right] if total > 0: right -= 1 elif total < 0: left += 1 else: res.append([num, nums[left], nums[right]]) left += 1 while nums[left] == nums[left - 1] and left < right: left += 1 return res obj = Solution() print(obj.threeSum([-1,0,1,2,-1,-4])) print(obj.threeSum([])) print(obj.threeSum([-2,1,1,7,1,-8])) print(obj.threeSum([0,0,0,0,0]))
class Solution: def three_sum(self, nums: List[int]) -> List[List[int]]: if not nums: return [] res = [] nums.sort() for (i, num) in enumerate(nums): if i > 0 and num == nums[i - 1]: continue (left, right) = (i + 1, len(nums) - 1) while left < right: total = num + nums[left] + nums[right] if total > 0: right -= 1 elif total < 0: left += 1 else: res.append([num, nums[left], nums[right]]) left += 1 while nums[left] == nums[left - 1] and left < right: left += 1 return res obj = solution() print(obj.threeSum([-1, 0, 1, 2, -1, -4])) print(obj.threeSum([])) print(obj.threeSum([-2, 1, 1, 7, 1, -8])) print(obj.threeSum([0, 0, 0, 0, 0]))
#!/usr/bin/python3 with open('03_input', 'r') as f: lines = f.readlines() bits_list = [list(n.strip()) for n in lines] bit_len = len(bits_list[0]) zeros = [0 for i in range(bit_len)] ones = [0 for i in range(bit_len)] for bits in bits_list: for i, b in enumerate(bits): if b == '0': zeros[i] += 1 elif b == '1': ones[i] += 1 most = '' least = '' for i in range(bit_len): if zeros[i] > ones[i]: most += '0' least += '1' else: most += '1' least += '0' int_most = int(most, 2) int_least = int(least, 2) val = int_most * int_least print(val)
with open('03_input', 'r') as f: lines = f.readlines() bits_list = [list(n.strip()) for n in lines] bit_len = len(bits_list[0]) zeros = [0 for i in range(bit_len)] ones = [0 for i in range(bit_len)] for bits in bits_list: for (i, b) in enumerate(bits): if b == '0': zeros[i] += 1 elif b == '1': ones[i] += 1 most = '' least = '' for i in range(bit_len): if zeros[i] > ones[i]: most += '0' least += '1' else: most += '1' least += '0' int_most = int(most, 2) int_least = int(least, 2) val = int_most * int_least print(val)
# WHICH NUMBER IS NOT LIKE THE OTHERS EDABIT SOLUTION: # creating a function to solve the problem. def unique(lst): # creating a for-loop to iterate for the elements in the list. for i in lst: # creating a nested if-statement to check for a distinct element. if lst.count(i) == 1: # returning the element if the condition is met. return i
def unique(lst): for i in lst: if lst.count(i) == 1: return i
# Complete the function below. # Function to check ipv4 # @Return boolean def validateIPV4(ipAddress): isIPv4 = True # ipv4 address is composed by octet for octet in ipAddress: try: # pretty straigthforward, convert to int # ensure per-octet value falls between [0,255] tmp = int(octet) if tmp<0 or tmp>255: isIPv4 = False break except: isIPv4 = False break return "IPv4" if isIPv4 else "Neither" # Function to check ipv6 # @Return boolean def validateIPV6(ipAddress): isIPv6 = True # ipv6 address is composed by hextet for hextet in ipAddress: try: # straigthforward, convert hexa to int # ensure per-hextet value falls between [0,65535] tmp = int(str(hextet),16) if (tmp<0) or tmp>65535: isIPv6 = False break except: isIPv6 = False break return "IPv6" if isIPv6 else "Neither" # Function to check IP address def checkIP(ip): # list to store final result result = [] for ipAddress in ip: # ipv4 is composed by 4 blocks of octet and separated by dot (.) if len(ipAddress.split(".")) == 4: ipCategory = validateIPV4(ipAddress.split(".")) # ipv6 is composed by 8 blocks of hextet and separated by colon (:) elif len(ipAddress.split(":")) == 8: ipCategory = validateIPV6(ipAddress.split(":")) else: ipCategory = "Neither" result.append(ipCategory) return result
def validate_ipv4(ipAddress): is_i_pv4 = True for octet in ipAddress: try: tmp = int(octet) if tmp < 0 or tmp > 255: is_i_pv4 = False break except: is_i_pv4 = False break return 'IPv4' if isIPv4 else 'Neither' def validate_ipv6(ipAddress): is_i_pv6 = True for hextet in ipAddress: try: tmp = int(str(hextet), 16) if tmp < 0 or tmp > 65535: is_i_pv6 = False break except: is_i_pv6 = False break return 'IPv6' if isIPv6 else 'Neither' def check_ip(ip): result = [] for ip_address in ip: if len(ipAddress.split('.')) == 4: ip_category = validate_ipv4(ipAddress.split('.')) elif len(ipAddress.split(':')) == 8: ip_category = validate_ipv6(ipAddress.split(':')) else: ip_category = 'Neither' result.append(ipCategory) return result
def kph(ms): return ms * 3.6 def mph(ms): return ms * 2.2369362920544 def knots(ms): return ms * 1.9438444924574 def minPkm(ms): # minutes per kilometre return ms * (100 / 6) def c(ms): # speed of light return ms / 299792458 def speedOfLight(ms): return c(ms) def mach(ms): return ms / 340 def speedOfSound(ms): return mach(ms)
def kph(ms): return ms * 3.6 def mph(ms): return ms * 2.2369362920544 def knots(ms): return ms * 1.9438444924574 def min_pkm(ms): return ms * (100 / 6) def c(ms): return ms / 299792458 def speed_of_light(ms): return c(ms) def mach(ms): return ms / 340 def speed_of_sound(ms): return mach(ms)
# -*- encoding: utf-8 -*- # # Copyright 2015-2016 Red Hat, Inc. # # 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. def test_create_user(runner, test_user): assert test_user["name"] == "foo" assert test_user["fullname"] == "Foo Bar" assert test_user["email"] == "[email protected]" def test_create_admin(runner): user = runner.invoke( [ "user-create", "--name", "foo", "--email", "[email protected]", "--password", "pass" ] )["user"] assert user["name"] == "foo" assert user["fullname"] == "foo" assert user["email"] == "[email protected]" def test_create_super_admin(runner): user = runner.invoke( [ "user-create", "--name", "foo", "--email", "[email protected]", "--password", "pass" ] )["user"] assert user["name"] == "foo" assert user["fullname"] == "foo" assert user["email"] == "[email protected]" def test_create_inactive(runner): user = runner.invoke( [ "user-create", "--name", "foo", "--password", "pass", "--email", "[email protected]", "--no-active", ] )["user"] assert user["state"] == "inactive" def test_list(runner): users_cnt = len(runner.invoke(["user-list"])["users"]) runner.invoke( [ "user-create", "--name", "bar", "--email", "[email protected]", "--password", "pass", ] ) new_users_cnt = len(runner.invoke(["user-list"])["users"]) assert new_users_cnt == users_cnt + 1 def test_update(runner, test_user): runner.invoke( [ "user-update", test_user["id"], "--etag", test_user["etag"], "--name", "bar", "--email", "[email protected]", "--fullname", "Barry White", ] ) user = runner.invoke(["user-show", test_user["id"]])["user"] assert user["name"] == "bar" assert user["fullname"] == "Barry White" assert user["email"] == "[email protected]" def test_update_active(runner, test_user, team_id): assert test_user["state"] == "active" result = runner.invoke( ["user-update", test_user["id"], "--etag", test_user["etag"], "--no-active"] ) assert result["user"]["id"] == test_user["id"] assert result["user"]["state"] == "inactive" result = runner.invoke( [ "user-update", test_user["id"], "--etag", result["user"]["etag"], "--name", "foobar", ] ) assert result["user"]["id"] == test_user["id"] assert result["user"]["state"] == "inactive" assert result["user"]["name"] == "foobar" result = runner.invoke( ["user-update", test_user["id"], "--etag", result["user"]["etag"], "--active"] ) assert result["user"]["state"] == "active" def test_delete(runner, test_user, team_id): result = runner.invoke_raw( ["user-delete", test_user["id"], "--etag", test_user["etag"]] ) assert result.status_code == 204 def test_show(runner, test_user, team_id): user = runner.invoke(["user-show", test_user["id"]])["user"] assert user["name"] == test_user["name"] def test_where_on_list(runner, test_user, team_id): runner.invoke( [ "user-create", "--name", "foo2", "--email", "[email protected]", "--password", "pass", ] ) runner.invoke( [ "user-create", "--name", "foo3", "--email", "[email protected]", "--password", "pass", ] ) users_cnt = len(runner.invoke(["user-list"])["users"]) assert runner.invoke(["user-list"])["_meta"]["count"] == users_cnt assert runner.invoke(["user-list", "--where", "name:foo"])["_meta"]["count"] == 1
def test_create_user(runner, test_user): assert test_user['name'] == 'foo' assert test_user['fullname'] == 'Foo Bar' assert test_user['email'] == '[email protected]' def test_create_admin(runner): user = runner.invoke(['user-create', '--name', 'foo', '--email', '[email protected]', '--password', 'pass'])['user'] assert user['name'] == 'foo' assert user['fullname'] == 'foo' assert user['email'] == '[email protected]' def test_create_super_admin(runner): user = runner.invoke(['user-create', '--name', 'foo', '--email', '[email protected]', '--password', 'pass'])['user'] assert user['name'] == 'foo' assert user['fullname'] == 'foo' assert user['email'] == '[email protected]' def test_create_inactive(runner): user = runner.invoke(['user-create', '--name', 'foo', '--password', 'pass', '--email', '[email protected]', '--no-active'])['user'] assert user['state'] == 'inactive' def test_list(runner): users_cnt = len(runner.invoke(['user-list'])['users']) runner.invoke(['user-create', '--name', 'bar', '--email', '[email protected]', '--password', 'pass']) new_users_cnt = len(runner.invoke(['user-list'])['users']) assert new_users_cnt == users_cnt + 1 def test_update(runner, test_user): runner.invoke(['user-update', test_user['id'], '--etag', test_user['etag'], '--name', 'bar', '--email', '[email protected]', '--fullname', 'Barry White']) user = runner.invoke(['user-show', test_user['id']])['user'] assert user['name'] == 'bar' assert user['fullname'] == 'Barry White' assert user['email'] == '[email protected]' def test_update_active(runner, test_user, team_id): assert test_user['state'] == 'active' result = runner.invoke(['user-update', test_user['id'], '--etag', test_user['etag'], '--no-active']) assert result['user']['id'] == test_user['id'] assert result['user']['state'] == 'inactive' result = runner.invoke(['user-update', test_user['id'], '--etag', result['user']['etag'], '--name', 'foobar']) assert result['user']['id'] == test_user['id'] assert result['user']['state'] == 'inactive' assert result['user']['name'] == 'foobar' result = runner.invoke(['user-update', test_user['id'], '--etag', result['user']['etag'], '--active']) assert result['user']['state'] == 'active' def test_delete(runner, test_user, team_id): result = runner.invoke_raw(['user-delete', test_user['id'], '--etag', test_user['etag']]) assert result.status_code == 204 def test_show(runner, test_user, team_id): user = runner.invoke(['user-show', test_user['id']])['user'] assert user['name'] == test_user['name'] def test_where_on_list(runner, test_user, team_id): runner.invoke(['user-create', '--name', 'foo2', '--email', '[email protected]', '--password', 'pass']) runner.invoke(['user-create', '--name', 'foo3', '--email', '[email protected]', '--password', 'pass']) users_cnt = len(runner.invoke(['user-list'])['users']) assert runner.invoke(['user-list'])['_meta']['count'] == users_cnt assert runner.invoke(['user-list', '--where', 'name:foo'])['_meta']['count'] == 1
# -*- coding: utf-8 -*- even = 0 for i in range(5): A = float(input()) if (A % 2) == 0: even +=1 print("%i valores pares"%even)
even = 0 for i in range(5): a = float(input()) if A % 2 == 0: even += 1 print('%i valores pares' % even)
class user(): def __init__(self,id,passwd): self.id = id self.passwd = passwd def get_id(self): pass
class User: def __init__(self, id, passwd): self.id = id self.passwd = passwd def get_id(self): pass
## using hashing .. def duplicates_hash(arr, n): s = dict() for i in range(n): if arr[i] in s: s[arr[i]] = s[arr[i]]+1 else: s[arr[i]] = 1 res = [] for i in s: if s[i] > 1: res.append(i) if len(res)>0: return res else: return -1 ## using given array as hashmap because in question it is given that range of array -->[1,length of array] def duplicates_arr(arr, n): res = [] for i in range(n): arr[arr[i]%n] = arr[arr[i]%n] + n for i in range(n): if (arr[i]//n>1): res.append(i) return res ## Driver code...!!!!1 if __name__ == "__main__": n = int(input()) arr1 = list(map(int,input().split())) print('using array',duplicates_arr(arr1.copy(),n)) ## pass copy of main input array.. print('using hashmap',duplicates_hash(arr1,n)) ''' sample input 5 2 3 1 2 3 '''
def duplicates_hash(arr, n): s = dict() for i in range(n): if arr[i] in s: s[arr[i]] = s[arr[i]] + 1 else: s[arr[i]] = 1 res = [] for i in s: if s[i] > 1: res.append(i) if len(res) > 0: return res else: return -1 def duplicates_arr(arr, n): res = [] for i in range(n): arr[arr[i] % n] = arr[arr[i] % n] + n for i in range(n): if arr[i] // n > 1: res.append(i) return res if __name__ == '__main__': n = int(input()) arr1 = list(map(int, input().split())) print('using array', duplicates_arr(arr1.copy(), n)) print('using hashmap', duplicates_hash(arr1, n)) '\nsample input\n5\n2 3 1 2 3\n'
lastA = 116 lastB = 299 judgeCounter = 0 for i in range(40000000): # Generation cycle aRes = (lastA * 16807) % 2147483647 bRes = (lastB * 48271) % 2147483647 # Judging time if (aRes % 65536 == bRes % 65536): print("Match found! With ", aRes, " and ", bRes, sep="") judgeCounter += 1 # Setup for next round lastA = aRes lastB = bRes print("Final judge score, part 1:", judgeCounter) ## Part 2 lastA = 116 lastB = 299 judgeCounter = 0 for i in range(5000000): # Generation cycle aRes = (lastA * 16807) % 2147483647 while (aRes % 4 != 0): aRes = (aRes * 16807) % 2147483647 bRes = (lastB * 48271) % 2147483647 while (bRes % 8 != 0): bRes = (bRes * 48271) % 2147483647 # Judging time if (aRes % 65536 == bRes % 65536): print(i, ": Match found!", sep="") judgeCounter += 1 # Setup for next round lastA = aRes lastB = bRes print("Final judge score, part 2:", judgeCounter)
last_a = 116 last_b = 299 judge_counter = 0 for i in range(40000000): a_res = lastA * 16807 % 2147483647 b_res = lastB * 48271 % 2147483647 if aRes % 65536 == bRes % 65536: print('Match found! With ', aRes, ' and ', bRes, sep='') judge_counter += 1 last_a = aRes last_b = bRes print('Final judge score, part 1:', judgeCounter) last_a = 116 last_b = 299 judge_counter = 0 for i in range(5000000): a_res = lastA * 16807 % 2147483647 while aRes % 4 != 0: a_res = aRes * 16807 % 2147483647 b_res = lastB * 48271 % 2147483647 while bRes % 8 != 0: b_res = bRes * 48271 % 2147483647 if aRes % 65536 == bRes % 65536: print(i, ': Match found!', sep='') judge_counter += 1 last_a = aRes last_b = bRes print('Final judge score, part 2:', judgeCounter)
# # PySNMP MIB module ZYXEL-DIFFSERV-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZYXEL-DIFFSERV-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:49:30 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) # ObjectIdentifier, Integer, OctetString = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "Integer", "OctetString") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsUnion, ValueRangeConstraint, ValueSizeConstraint, SingleValueConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "ValueRangeConstraint", "ValueSizeConstraint", "SingleValueConstraint", "ConstraintsIntersection") dot1dBasePort, = mibBuilder.importSymbols("BRIDGE-MIB", "dot1dBasePort") EnabledStatus, = mibBuilder.importSymbols("P-BRIDGE-MIB", "EnabledStatus") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") TimeTicks, Counter64, MibIdentifier, Bits, ObjectIdentity, IpAddress, ModuleIdentity, MibScalar, MibTable, MibTableRow, MibTableColumn, iso, Unsigned32, Gauge32, Integer32, NotificationType, Counter32 = mibBuilder.importSymbols("SNMPv2-SMI", "TimeTicks", "Counter64", "MibIdentifier", "Bits", "ObjectIdentity", "IpAddress", "ModuleIdentity", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "iso", "Unsigned32", "Gauge32", "Integer32", "NotificationType", "Counter32") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") esMgmt, = mibBuilder.importSymbols("ZYXEL-ES-SMI", "esMgmt") zyxelDiffserv = ModuleIdentity((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 22)) if mibBuilder.loadTexts: zyxelDiffserv.setLastUpdated('201207010000Z') if mibBuilder.loadTexts: zyxelDiffserv.setOrganization('Enterprise Solution ZyXEL') if mibBuilder.loadTexts: zyxelDiffserv.setContactInfo('') if mibBuilder.loadTexts: zyxelDiffserv.setDescription('The subtree for Differentiated services (Diffserv)') zyxelDiffservSetup = MibIdentifier((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 22, 1)) zyDiffservState = MibScalar((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 22, 1, 1), EnabledStatus()).setMaxAccess("readwrite") if mibBuilder.loadTexts: zyDiffservState.setStatus('current') if mibBuilder.loadTexts: zyDiffservState.setDescription('Enable/Disable DiffServ on the switch. DiffServ is a class of service (CoS) model that marks packets so that they receive specific per-hop treatment at DiffServ-compliant network devices along the route based on the application types and traffic flow.') zyxelDiffservMapTable = MibTable((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 22, 1, 2), ) if mibBuilder.loadTexts: zyxelDiffservMapTable.setStatus('current') if mibBuilder.loadTexts: zyxelDiffservMapTable.setDescription('The table contains Diffserv map configuration. ') zyxelDiffservMapEntry = MibTableRow((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 22, 1, 2, 1), ).setIndexNames((0, "ZYXEL-DIFFSERV-MIB", "zyDiffservMapDscp")) if mibBuilder.loadTexts: zyxelDiffservMapEntry.setStatus('current') if mibBuilder.loadTexts: zyxelDiffservMapEntry.setDescription('An entry contains Diffserv map configuration.') zyDiffservMapDscp = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 22, 1, 2, 1, 1), Integer32()) if mibBuilder.loadTexts: zyDiffservMapDscp.setStatus('current') if mibBuilder.loadTexts: zyDiffservMapDscp.setDescription('The DSCP classification identification number.') zyDiffservMapPriority = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 22, 1, 2, 1, 2), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: zyDiffservMapPriority.setStatus('current') if mibBuilder.loadTexts: zyDiffservMapPriority.setDescription('Set the IEEE 802.1p priority mapping.') zyxelDiffservPortTable = MibTable((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 22, 1, 3), ) if mibBuilder.loadTexts: zyxelDiffservPortTable.setStatus('current') if mibBuilder.loadTexts: zyxelDiffservPortTable.setDescription('The table contains Diffserv port configuration.') zyxelDiffservPortEntry = MibTableRow((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 22, 1, 3, 1), ).setIndexNames((0, "BRIDGE-MIB", "dot1dBasePort")) if mibBuilder.loadTexts: zyxelDiffservPortEntry.setStatus('current') if mibBuilder.loadTexts: zyxelDiffservPortEntry.setDescription('An entry contains Diffserv port configuration.') zyDiffservPortState = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 22, 1, 3, 1, 1), EnabledStatus()).setMaxAccess("readwrite") if mibBuilder.loadTexts: zyDiffservPortState.setStatus('current') if mibBuilder.loadTexts: zyDiffservPortState.setDescription('Enable/Disable DiffServ on the port.') mibBuilder.exportSymbols("ZYXEL-DIFFSERV-MIB", zyDiffservState=zyDiffservState, zyxelDiffservMapTable=zyxelDiffservMapTable, zyxelDiffservPortTable=zyxelDiffservPortTable, zyxelDiffservSetup=zyxelDiffservSetup, zyDiffservPortState=zyDiffservPortState, zyxelDiffservPortEntry=zyxelDiffservPortEntry, PYSNMP_MODULE_ID=zyxelDiffserv, zyxelDiffserv=zyxelDiffserv, zyDiffservMapDscp=zyDiffservMapDscp, zyxelDiffservMapEntry=zyxelDiffservMapEntry, zyDiffservMapPriority=zyDiffservMapPriority)
(object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_union, value_range_constraint, value_size_constraint, single_value_constraint, constraints_intersection) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsUnion', 'ValueRangeConstraint', 'ValueSizeConstraint', 'SingleValueConstraint', 'ConstraintsIntersection') (dot1d_base_port,) = mibBuilder.importSymbols('BRIDGE-MIB', 'dot1dBasePort') (enabled_status,) = mibBuilder.importSymbols('P-BRIDGE-MIB', 'EnabledStatus') (notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance') (time_ticks, counter64, mib_identifier, bits, object_identity, ip_address, module_identity, mib_scalar, mib_table, mib_table_row, mib_table_column, iso, unsigned32, gauge32, integer32, notification_type, counter32) = mibBuilder.importSymbols('SNMPv2-SMI', 'TimeTicks', 'Counter64', 'MibIdentifier', 'Bits', 'ObjectIdentity', 'IpAddress', 'ModuleIdentity', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'iso', 'Unsigned32', 'Gauge32', 'Integer32', 'NotificationType', 'Counter32') (textual_convention, display_string) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'DisplayString') (es_mgmt,) = mibBuilder.importSymbols('ZYXEL-ES-SMI', 'esMgmt') zyxel_diffserv = module_identity((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 22)) if mibBuilder.loadTexts: zyxelDiffserv.setLastUpdated('201207010000Z') if mibBuilder.loadTexts: zyxelDiffserv.setOrganization('Enterprise Solution ZyXEL') if mibBuilder.loadTexts: zyxelDiffserv.setContactInfo('') if mibBuilder.loadTexts: zyxelDiffserv.setDescription('The subtree for Differentiated services (Diffserv)') zyxel_diffserv_setup = mib_identifier((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 22, 1)) zy_diffserv_state = mib_scalar((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 22, 1, 1), enabled_status()).setMaxAccess('readwrite') if mibBuilder.loadTexts: zyDiffservState.setStatus('current') if mibBuilder.loadTexts: zyDiffservState.setDescription('Enable/Disable DiffServ on the switch. DiffServ is a class of service (CoS) model that marks packets so that they receive specific per-hop treatment at DiffServ-compliant network devices along the route based on the application types and traffic flow.') zyxel_diffserv_map_table = mib_table((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 22, 1, 2)) if mibBuilder.loadTexts: zyxelDiffservMapTable.setStatus('current') if mibBuilder.loadTexts: zyxelDiffservMapTable.setDescription('The table contains Diffserv map configuration. ') zyxel_diffserv_map_entry = mib_table_row((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 22, 1, 2, 1)).setIndexNames((0, 'ZYXEL-DIFFSERV-MIB', 'zyDiffservMapDscp')) if mibBuilder.loadTexts: zyxelDiffservMapEntry.setStatus('current') if mibBuilder.loadTexts: zyxelDiffservMapEntry.setDescription('An entry contains Diffserv map configuration.') zy_diffserv_map_dscp = mib_table_column((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 22, 1, 2, 1, 1), integer32()) if mibBuilder.loadTexts: zyDiffservMapDscp.setStatus('current') if mibBuilder.loadTexts: zyDiffservMapDscp.setDescription('The DSCP classification identification number.') zy_diffserv_map_priority = mib_table_column((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 22, 1, 2, 1, 2), integer32()).setMaxAccess('readwrite') if mibBuilder.loadTexts: zyDiffservMapPriority.setStatus('current') if mibBuilder.loadTexts: zyDiffservMapPriority.setDescription('Set the IEEE 802.1p priority mapping.') zyxel_diffserv_port_table = mib_table((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 22, 1, 3)) if mibBuilder.loadTexts: zyxelDiffservPortTable.setStatus('current') if mibBuilder.loadTexts: zyxelDiffservPortTable.setDescription('The table contains Diffserv port configuration.') zyxel_diffserv_port_entry = mib_table_row((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 22, 1, 3, 1)).setIndexNames((0, 'BRIDGE-MIB', 'dot1dBasePort')) if mibBuilder.loadTexts: zyxelDiffservPortEntry.setStatus('current') if mibBuilder.loadTexts: zyxelDiffservPortEntry.setDescription('An entry contains Diffserv port configuration.') zy_diffserv_port_state = mib_table_column((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 22, 1, 3, 1, 1), enabled_status()).setMaxAccess('readwrite') if mibBuilder.loadTexts: zyDiffservPortState.setStatus('current') if mibBuilder.loadTexts: zyDiffservPortState.setDescription('Enable/Disable DiffServ on the port.') mibBuilder.exportSymbols('ZYXEL-DIFFSERV-MIB', zyDiffservState=zyDiffservState, zyxelDiffservMapTable=zyxelDiffservMapTable, zyxelDiffservPortTable=zyxelDiffservPortTable, zyxelDiffservSetup=zyxelDiffservSetup, zyDiffservPortState=zyDiffservPortState, zyxelDiffservPortEntry=zyxelDiffservPortEntry, PYSNMP_MODULE_ID=zyxelDiffserv, zyxelDiffserv=zyxelDiffserv, zyDiffservMapDscp=zyDiffservMapDscp, zyxelDiffservMapEntry=zyxelDiffservMapEntry, zyDiffservMapPriority=zyDiffservMapPriority)
PLUGIN_URL_NAME_PREFIX = 'djangocms_alias' CREATE_ALIAS_URL_NAME = '{}_create'.format(PLUGIN_URL_NAME_PREFIX) DELETE_ALIAS_URL_NAME = '{}_delete'.format(PLUGIN_URL_NAME_PREFIX) DETACH_ALIAS_PLUGIN_URL_NAME = '{}_detach_plugin'.format(PLUGIN_URL_NAME_PREFIX) # noqa: E501 LIST_ALIASES_URL_NAME = '{}_list'.format(PLUGIN_URL_NAME_PREFIX) CATEGORY_LIST_URL_NAME = '{}_category_list'.format(PLUGIN_URL_NAME_PREFIX) SET_ALIAS_POSITION_URL_NAME = '{}_set_alias_position'.format(PLUGIN_URL_NAME_PREFIX) # noqa: E501 SELECT2_ALIAS_URL_NAME = '{}_select2'.format(PLUGIN_URL_NAME_PREFIX) USAGE_ALIAS_URL_NAME = '{}_alias_usage'.format(PLUGIN_URL_NAME_PREFIX)
plugin_url_name_prefix = 'djangocms_alias' create_alias_url_name = '{}_create'.format(PLUGIN_URL_NAME_PREFIX) delete_alias_url_name = '{}_delete'.format(PLUGIN_URL_NAME_PREFIX) detach_alias_plugin_url_name = '{}_detach_plugin'.format(PLUGIN_URL_NAME_PREFIX) list_aliases_url_name = '{}_list'.format(PLUGIN_URL_NAME_PREFIX) category_list_url_name = '{}_category_list'.format(PLUGIN_URL_NAME_PREFIX) set_alias_position_url_name = '{}_set_alias_position'.format(PLUGIN_URL_NAME_PREFIX) select2_alias_url_name = '{}_select2'.format(PLUGIN_URL_NAME_PREFIX) usage_alias_url_name = '{}_alias_usage'.format(PLUGIN_URL_NAME_PREFIX)
class Party: def __init__(self): self.party_people = [] self.party_people_counter = 0 party = Party() people = input() while people != 'End': party.party_people.append(people) party.party_people_counter += 1 people = input() print(f'Going: {", ".join(party.party_people)}') print(f'Total: {party.party_people_counter}')
class Party: def __init__(self): self.party_people = [] self.party_people_counter = 0 party = party() people = input() while people != 'End': party.party_people.append(people) party.party_people_counter += 1 people = input() print(f"Going: {', '.join(party.party_people)}") print(f'Total: {party.party_people_counter}')
class Solution: def __init__(self): self.count = 0 def waysToStep(self, n: int) -> int: def dfs(n): if n == 1: self.count += 1 elif n == 2: self.count += 2 elif n == 3: self.count += 4 else: dfs(n - 1) dfs(n - 2) dfs(n - 3) dfs(n) return self.count def waysToStep(self, n: int) -> int: if n < 3: return n elif n == 3: return 4 dp0, dp1, dp2 = 1, 2, 4 for _ in range(4, n + 1): dp0, dp1, dp2 = dp1, dp2, (dp0 + dp1 + dp2) % 1000000007 return dp2
class Solution: def __init__(self): self.count = 0 def ways_to_step(self, n: int) -> int: def dfs(n): if n == 1: self.count += 1 elif n == 2: self.count += 2 elif n == 3: self.count += 4 else: dfs(n - 1) dfs(n - 2) dfs(n - 3) dfs(n) return self.count def ways_to_step(self, n: int) -> int: if n < 3: return n elif n == 3: return 4 (dp0, dp1, dp2) = (1, 2, 4) for _ in range(4, n + 1): (dp0, dp1, dp2) = (dp1, dp2, (dp0 + dp1 + dp2) % 1000000007) return dp2
# Determine whether a number is a perfect number, an Armstrong number or a palindrome. def perfect_number(n): sum1 = 0 for i in range(1, n): if(n % i == 0): sum1 = sum1 + i if (sum1 == n): return True else: return False def armstrong(n): sum = 0 temp = n while temp > 0: digit = temp % 10 sum += digit ** 3 temp //= 10 if n == sum: return True else: return False def palindrome(n): temp = n rev = 0 while(n > 0): dig = n % 10 rev = rev*10+dig n = n//10 if(temp == rev): return True else: return False k = True while k == True: n = int(input("Enter a number: ")) if perfect_number(n) == True: print(n, " is a Perfect number!") elif armstrong(n) == True: print(n, " is an Armstrong number!") elif palindrome(n) == True: print("The number is a palindrome!") else: print("The number is a Unknow!") option = input('Do you want to try again.(y/n): ').lower() if option == 'y': continue else: k = False
def perfect_number(n): sum1 = 0 for i in range(1, n): if n % i == 0: sum1 = sum1 + i if sum1 == n: return True else: return False def armstrong(n): sum = 0 temp = n while temp > 0: digit = temp % 10 sum += digit ** 3 temp //= 10 if n == sum: return True else: return False def palindrome(n): temp = n rev = 0 while n > 0: dig = n % 10 rev = rev * 10 + dig n = n // 10 if temp == rev: return True else: return False k = True while k == True: n = int(input('Enter a number: ')) if perfect_number(n) == True: print(n, ' is a Perfect number!') elif armstrong(n) == True: print(n, ' is an Armstrong number!') elif palindrome(n) == True: print('The number is a palindrome!') else: print('The number is a Unknow!') option = input('Do you want to try again.(y/n): ').lower() if option == 'y': continue else: k = False
# Created by MechAviv # [Kyrin] | [1090000] # Nautilus : Navigation Room sm.setSpeakerID(1090000) sm.sendSayOkay("Welcome aboard the Nautilus. The ship isn't headed anywhere for a while. How about going out to the deck?")
sm.setSpeakerID(1090000) sm.sendSayOkay("Welcome aboard the Nautilus. The ship isn't headed anywhere for a while. How about going out to the deck?")
def deduplicate_list(list_with_dups): return list(dict.fromkeys(list_with_dups)) def filter_list_by_set(original_list, filter_set): return [elem for elem in original_list if elem not in filter_set] def write_to_file(filename, text, message): # pragma: no cover with open(filename, 'w') as f: f.write(text) print(message)
def deduplicate_list(list_with_dups): return list(dict.fromkeys(list_with_dups)) def filter_list_by_set(original_list, filter_set): return [elem for elem in original_list if elem not in filter_set] def write_to_file(filename, text, message): with open(filename, 'w') as f: f.write(text) print(message)
# # PySNMP MIB module HM2-DNS-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HM2-DNS-MIB # Produced by pysmi-0.3.4 at Wed May 1 13:31: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") ConstraintsUnion, SingleValueConstraint, ConstraintsIntersection, ValueRangeConstraint, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "SingleValueConstraint", "ConstraintsIntersection", "ValueRangeConstraint", "ValueSizeConstraint") HmActionValue, HmEnabledStatus, hm2ConfigurationMibs = mibBuilder.importSymbols("HM2-TC-MIB", "HmActionValue", "HmEnabledStatus", "hm2ConfigurationMibs") InetAddressType, InetAddress = mibBuilder.importSymbols("INET-ADDRESS-MIB", "InetAddressType", "InetAddress") SnmpAdminString, = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") Gauge32, Unsigned32, ModuleIdentity, NotificationType, TimeTicks, Counter32, Integer32, Counter64, IpAddress, MibIdentifier, iso, ObjectIdentity, MibScalar, MibTable, MibTableRow, MibTableColumn, Bits = mibBuilder.importSymbols("SNMPv2-SMI", "Gauge32", "Unsigned32", "ModuleIdentity", "NotificationType", "TimeTicks", "Counter32", "Integer32", "Counter64", "IpAddress", "MibIdentifier", "iso", "ObjectIdentity", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Bits") DisplayString, TextualConvention, RowStatus = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention", "RowStatus") hm2DnsMib = ModuleIdentity((1, 3, 6, 1, 4, 1, 248, 11, 90)) hm2DnsMib.setRevisions(('2011-06-17 00:00',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: hm2DnsMib.setRevisionsDescriptions(('Initial version.',)) if mibBuilder.loadTexts: hm2DnsMib.setLastUpdated('201106170000Z') if mibBuilder.loadTexts: hm2DnsMib.setOrganization('Hirschmann Automation and Control GmbH') if mibBuilder.loadTexts: hm2DnsMib.setContactInfo('Postal: Stuttgarter Str. 45-51 72654 Neckartenzlingen Germany Phone: +49 7127 140 E-mail: [email protected]') if mibBuilder.loadTexts: hm2DnsMib.setDescription('Hirschmann DNS MIB for DNS client, DNS client cache and DNS caching server. Copyright (C) 2011. All Rights Reserved.') hm2DnsMibNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 248, 11, 90, 0)) hm2DnsMibObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 248, 11, 90, 1)) hm2DnsMibSNMPExtensionGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 248, 11, 90, 3)) hm2DnsClientGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1)) hm2DnsCacheGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 2)) hm2DnsCachingServerGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 3)) hm2DnsClientAdminState = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 1), HmEnabledStatus().clone('disable')).setMaxAccess("readwrite") if mibBuilder.loadTexts: hm2DnsClientAdminState.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientAdminState.setDescription('The operational status of DNS client. If disabled, no host name lookups will be done for names entered on the CLI and in the configuration of services e.g. NTP.') hm2DnsClientConfigSource = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("user", 1), ("mgmt-dhcp", 2), ("provider", 3))).clone('mgmt-dhcp')).setMaxAccess("readwrite") if mibBuilder.loadTexts: hm2DnsClientConfigSource.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientConfigSource.setDescription('DNS client server source. If the value is set to user(1), the variables from hm2DnsClientServerCfgTable will be used. If the value is set to mgmt-dhcp(2), the DNS servers received by DHCP on the management interface will be used. If the value is set to provider(3), the DNS configuration will be taken from DHCP, PPP or PPPoE on the primary WAN link.') hm2DnsClientServerCfgTable = MibTable((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 3), ) if mibBuilder.loadTexts: hm2DnsClientServerCfgTable.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientServerCfgTable.setDescription('The table that contains the DNS Servers entries configured by the user in the system.') hm2DnsClientServerCfgEntry = MibTableRow((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 3, 1), ).setIndexNames((0, "HM2-DNS-MIB", "hm2DnsClientServerIndex")) if mibBuilder.loadTexts: hm2DnsClientServerCfgEntry.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientServerCfgEntry.setDescription('An entry contains the IP address of a DNS server configured in the system.') hm2DnsClientServerIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 3, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4))) if mibBuilder.loadTexts: hm2DnsClientServerIndex.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientServerIndex.setDescription('The unique index used for each server added in the DNS servers table.') hm2DnsClientServerAddressType = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 3, 1, 2), InetAddressType().clone('ipv4')).setMaxAccess("readwrite") if mibBuilder.loadTexts: hm2DnsClientServerAddressType.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientServerAddressType.setDescription('Address type for DNS server. Currently, only ipv4 is supported.') hm2DnsClientServerAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 3, 1, 3), InetAddress().clone(hexValue="00000000")).setMaxAccess("readwrite") if mibBuilder.loadTexts: hm2DnsClientServerAddress.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientServerAddress.setDescription('The IP address of the DNS server.') hm2DnsClientServerRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 3, 1, 4), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: hm2DnsClientServerRowStatus.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientServerRowStatus.setDescription('Describes the status of a row in the table.') hm2DnsClientServerDiagTable = MibTable((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 4), ) if mibBuilder.loadTexts: hm2DnsClientServerDiagTable.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientServerDiagTable.setDescription('The table that contains the DNS Servers entries configured and used in the system.') hm2DnsClientServerDiagEntry = MibTableRow((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 4, 1), ).setIndexNames((0, "HM2-DNS-MIB", "hm2DnsClientServerDiagIndex")) if mibBuilder.loadTexts: hm2DnsClientServerDiagEntry.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientServerDiagEntry.setDescription('An entry contains the IP address of a DNS server used in the system.') hm2DnsClientServerDiagIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 4, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 4))) if mibBuilder.loadTexts: hm2DnsClientServerDiagIndex.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientServerDiagIndex.setDescription('The unique index used for each server added in the DNS servers table.') hm2DnsClientServerDiagAddressType = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 4, 1, 2), InetAddressType()).setMaxAccess("readonly") if mibBuilder.loadTexts: hm2DnsClientServerDiagAddressType.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientServerDiagAddressType.setDescription('Address type for DNS server used. Currently, only ipv4 is supported.') hm2DnsClientServerDiagAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 4, 1, 3), InetAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: hm2DnsClientServerDiagAddress.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientServerDiagAddress.setDescription('The IP address of the DNS server used by the system. The entry can be configured by the provider, e.g. through DHCP client or PPPoE client.') hm2DnsClientGlobalGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 5)) hm2DnsClientDefaultDomainName = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 5, 1), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readwrite") if mibBuilder.loadTexts: hm2DnsClientDefaultDomainName.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientDefaultDomainName.setDescription('The default domain name for unqualified hostnames.') hm2DnsClientRequestTimeout = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 5, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 3600)).clone(3)).setMaxAccess("readwrite") if mibBuilder.loadTexts: hm2DnsClientRequestTimeout.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientRequestTimeout.setDescription('The timeout before retransmitting a request to the server. The timeout value is configured and displayed in seconds.') hm2DnsClientRequestRetransmits = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 5, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 100)).clone(2)).setMaxAccess("readwrite") if mibBuilder.loadTexts: hm2DnsClientRequestRetransmits.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientRequestRetransmits.setDescription('The number of times the request is retransmitted. The request is retransmitted provided the maximum timeout value allows this many number of retransmits.') hm2DnsClientCacheAdminState = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 5, 4), HmEnabledStatus().clone('enable')).setMaxAccess("readwrite") if mibBuilder.loadTexts: hm2DnsClientCacheAdminState.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientCacheAdminState.setDescription('Enables/Disables DNS client cache functionality of the device.') hm2DnsClientStaticHostConfigTable = MibTable((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 6), ) if mibBuilder.loadTexts: hm2DnsClientStaticHostConfigTable.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientStaticHostConfigTable.setDescription('Static table of DNS hostname to IP address table') hm2DnsClientStaticHostConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 6, 1), ).setIndexNames((0, "HM2-DNS-MIB", "hm2DnsClientStaticIndex")) if mibBuilder.loadTexts: hm2DnsClientStaticHostConfigEntry.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientStaticHostConfigEntry.setDescription('An entry in the static DNS hostname IP address list. Rows may be created or deleted at any time by the DNS resolver and by SNMP SET requests.') hm2DnsClientStaticIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 6, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 64))) if mibBuilder.loadTexts: hm2DnsClientStaticIndex.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientStaticIndex.setDescription('The index of the entry.') hm2DnsClientStaticHostName = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 6, 1, 2), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readcreate") if mibBuilder.loadTexts: hm2DnsClientStaticHostName.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientStaticHostName.setDescription('The static hostname.') hm2DnsClientStaticHostAddressType = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 6, 1, 3), InetAddressType()).setMaxAccess("readcreate") if mibBuilder.loadTexts: hm2DnsClientStaticHostAddressType.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientStaticHostAddressType.setDescription('Address type for static hosts used. Currently, only ipv4 is supported.') hm2DnsClientStaticHostIPAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 6, 1, 4), InetAddress()).setMaxAccess("readcreate") if mibBuilder.loadTexts: hm2DnsClientStaticHostIPAddress.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientStaticHostIPAddress.setDescription('The IP address of the static host.') hm2DnsClientStaticHostStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 6, 1, 5), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: hm2DnsClientStaticHostStatus.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientStaticHostStatus.setDescription('Describes the status of a row in the table.') hm2DnsCachingServerGlobalGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 3, 1)) hm2DnsCachingServerAdminState = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 3, 1, 1), HmEnabledStatus().clone('enable')).setMaxAccess("readwrite") if mibBuilder.loadTexts: hm2DnsCachingServerAdminState.setStatus('current') if mibBuilder.loadTexts: hm2DnsCachingServerAdminState.setDescription('Enables/Disables DNS caching server functionality of the device.') hm2DnsCacheAdminState = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 2, 1), HmEnabledStatus().clone('enable')).setMaxAccess("readwrite") if mibBuilder.loadTexts: hm2DnsCacheAdminState.setStatus('deprecated') if mibBuilder.loadTexts: hm2DnsCacheAdminState.setDescription('Enables/Disables DNS cache functionality of the device. **NOTE: this object is deprecated and replaced by hm2DnsClientCacheAdminState/hm2DnsCachingServerAdminState**.') hm2DnsCacheFlushAction = MibScalar((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 2, 2), HmActionValue().clone('noop')).setMaxAccess("readwrite") if mibBuilder.loadTexts: hm2DnsCacheFlushAction.setStatus('deprecated') if mibBuilder.loadTexts: hm2DnsCacheFlushAction.setDescription('Setting this value to action will flush the DNS cache. After flushing the cache, it will be set to noop automatically. **NOTE: this object is deprecated and replaced by hm2DevMgmtActionFlushDnsClientCache/hm2DevMgmtActionFlushDnsCachingServerCache**.') hm2DnsCHHostNameAlreadyExistsSESError = ObjectIdentity((1, 3, 6, 1, 4, 1, 248, 11, 90, 3, 1)) if mibBuilder.loadTexts: hm2DnsCHHostNameAlreadyExistsSESError.setStatus('current') if mibBuilder.loadTexts: hm2DnsCHHostNameAlreadyExistsSESError.setDescription('The host name entered exists and is associated with an IP. The change attempt was canceled.') hm2DnsCHBadIpNotAcceptedSESError = ObjectIdentity((1, 3, 6, 1, 4, 1, 248, 11, 90, 3, 2)) if mibBuilder.loadTexts: hm2DnsCHBadIpNotAcceptedSESError.setStatus('current') if mibBuilder.loadTexts: hm2DnsCHBadIpNotAcceptedSESError.setDescription('The Ip Adress entered is not a valid one for a host. The change attempt was canceled.') hm2DnsCHBadRowCannotBeActivatedSESError = ObjectIdentity((1, 3, 6, 1, 4, 1, 248, 11, 90, 3, 3)) if mibBuilder.loadTexts: hm2DnsCHBadRowCannotBeActivatedSESError.setStatus('current') if mibBuilder.loadTexts: hm2DnsCHBadRowCannotBeActivatedSESError.setDescription('The instance cannot be activated due to compliance issues. Please modify the entry and try again.') mibBuilder.exportSymbols("HM2-DNS-MIB", hm2DnsCachingServerGlobalGroup=hm2DnsCachingServerGlobalGroup, hm2DnsClientServerIndex=hm2DnsClientServerIndex, hm2DnsClientServerAddress=hm2DnsClientServerAddress, hm2DnsClientServerCfgTable=hm2DnsClientServerCfgTable, PYSNMP_MODULE_ID=hm2DnsMib, hm2DnsClientServerDiagAddress=hm2DnsClientServerDiagAddress, hm2DnsClientStaticHostConfigTable=hm2DnsClientStaticHostConfigTable, hm2DnsClientGlobalGroup=hm2DnsClientGlobalGroup, hm2DnsCacheGroup=hm2DnsCacheGroup, hm2DnsClientServerDiagEntry=hm2DnsClientServerDiagEntry, hm2DnsMibSNMPExtensionGroup=hm2DnsMibSNMPExtensionGroup, hm2DnsClientGroup=hm2DnsClientGroup, hm2DnsMibObjects=hm2DnsMibObjects, hm2DnsClientDefaultDomainName=hm2DnsClientDefaultDomainName, hm2DnsClientStaticHostStatus=hm2DnsClientStaticHostStatus, hm2DnsCacheAdminState=hm2DnsCacheAdminState, hm2DnsClientRequestTimeout=hm2DnsClientRequestTimeout, hm2DnsClientServerDiagAddressType=hm2DnsClientServerDiagAddressType, hm2DnsCachingServerGroup=hm2DnsCachingServerGroup, hm2DnsClientServerDiagTable=hm2DnsClientServerDiagTable, hm2DnsCHBadIpNotAcceptedSESError=hm2DnsCHBadIpNotAcceptedSESError, hm2DnsClientAdminState=hm2DnsClientAdminState, hm2DnsClientStaticHostName=hm2DnsClientStaticHostName, hm2DnsClientRequestRetransmits=hm2DnsClientRequestRetransmits, hm2DnsMibNotifications=hm2DnsMibNotifications, hm2DnsClientConfigSource=hm2DnsClientConfigSource, hm2DnsClientServerRowStatus=hm2DnsClientServerRowStatus, hm2DnsClientServerDiagIndex=hm2DnsClientServerDiagIndex, hm2DnsClientCacheAdminState=hm2DnsClientCacheAdminState, hm2DnsCHHostNameAlreadyExistsSESError=hm2DnsCHHostNameAlreadyExistsSESError, hm2DnsCacheFlushAction=hm2DnsCacheFlushAction, hm2DnsClientStaticIndex=hm2DnsClientStaticIndex, hm2DnsClientStaticHostAddressType=hm2DnsClientStaticHostAddressType, hm2DnsCachingServerAdminState=hm2DnsCachingServerAdminState, hm2DnsCHBadRowCannotBeActivatedSESError=hm2DnsCHBadRowCannotBeActivatedSESError, hm2DnsClientServerAddressType=hm2DnsClientServerAddressType, hm2DnsMib=hm2DnsMib, hm2DnsClientStaticHostIPAddress=hm2DnsClientStaticHostIPAddress, hm2DnsClientServerCfgEntry=hm2DnsClientServerCfgEntry, hm2DnsClientStaticHostConfigEntry=hm2DnsClientStaticHostConfigEntry)
(octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_union, single_value_constraint, constraints_intersection, value_range_constraint, value_size_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsUnion', 'SingleValueConstraint', 'ConstraintsIntersection', 'ValueRangeConstraint', 'ValueSizeConstraint') (hm_action_value, hm_enabled_status, hm2_configuration_mibs) = mibBuilder.importSymbols('HM2-TC-MIB', 'HmActionValue', 'HmEnabledStatus', 'hm2ConfigurationMibs') (inet_address_type, inet_address) = mibBuilder.importSymbols('INET-ADDRESS-MIB', 'InetAddressType', 'InetAddress') (snmp_admin_string,) = mibBuilder.importSymbols('SNMP-FRAMEWORK-MIB', 'SnmpAdminString') (module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup') (gauge32, unsigned32, module_identity, notification_type, time_ticks, counter32, integer32, counter64, ip_address, mib_identifier, iso, object_identity, mib_scalar, mib_table, mib_table_row, mib_table_column, bits) = mibBuilder.importSymbols('SNMPv2-SMI', 'Gauge32', 'Unsigned32', 'ModuleIdentity', 'NotificationType', 'TimeTicks', 'Counter32', 'Integer32', 'Counter64', 'IpAddress', 'MibIdentifier', 'iso', 'ObjectIdentity', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'Bits') (display_string, textual_convention, row_status) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention', 'RowStatus') hm2_dns_mib = module_identity((1, 3, 6, 1, 4, 1, 248, 11, 90)) hm2DnsMib.setRevisions(('2011-06-17 00:00',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: hm2DnsMib.setRevisionsDescriptions(('Initial version.',)) if mibBuilder.loadTexts: hm2DnsMib.setLastUpdated('201106170000Z') if mibBuilder.loadTexts: hm2DnsMib.setOrganization('Hirschmann Automation and Control GmbH') if mibBuilder.loadTexts: hm2DnsMib.setContactInfo('Postal: Stuttgarter Str. 45-51 72654 Neckartenzlingen Germany Phone: +49 7127 140 E-mail: [email protected]') if mibBuilder.loadTexts: hm2DnsMib.setDescription('Hirschmann DNS MIB for DNS client, DNS client cache and DNS caching server. Copyright (C) 2011. All Rights Reserved.') hm2_dns_mib_notifications = mib_identifier((1, 3, 6, 1, 4, 1, 248, 11, 90, 0)) hm2_dns_mib_objects = mib_identifier((1, 3, 6, 1, 4, 1, 248, 11, 90, 1)) hm2_dns_mib_snmp_extension_group = mib_identifier((1, 3, 6, 1, 4, 1, 248, 11, 90, 3)) hm2_dns_client_group = mib_identifier((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1)) hm2_dns_cache_group = mib_identifier((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 2)) hm2_dns_caching_server_group = mib_identifier((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 3)) hm2_dns_client_admin_state = mib_scalar((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 1), hm_enabled_status().clone('disable')).setMaxAccess('readwrite') if mibBuilder.loadTexts: hm2DnsClientAdminState.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientAdminState.setDescription('The operational status of DNS client. If disabled, no host name lookups will be done for names entered on the CLI and in the configuration of services e.g. NTP.') hm2_dns_client_config_source = mib_scalar((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('user', 1), ('mgmt-dhcp', 2), ('provider', 3))).clone('mgmt-dhcp')).setMaxAccess('readwrite') if mibBuilder.loadTexts: hm2DnsClientConfigSource.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientConfigSource.setDescription('DNS client server source. If the value is set to user(1), the variables from hm2DnsClientServerCfgTable will be used. If the value is set to mgmt-dhcp(2), the DNS servers received by DHCP on the management interface will be used. If the value is set to provider(3), the DNS configuration will be taken from DHCP, PPP or PPPoE on the primary WAN link.') hm2_dns_client_server_cfg_table = mib_table((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 3)) if mibBuilder.loadTexts: hm2DnsClientServerCfgTable.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientServerCfgTable.setDescription('The table that contains the DNS Servers entries configured by the user in the system.') hm2_dns_client_server_cfg_entry = mib_table_row((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 3, 1)).setIndexNames((0, 'HM2-DNS-MIB', 'hm2DnsClientServerIndex')) if mibBuilder.loadTexts: hm2DnsClientServerCfgEntry.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientServerCfgEntry.setDescription('An entry contains the IP address of a DNS server configured in the system.') hm2_dns_client_server_index = mib_table_column((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 3, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(1, 4))) if mibBuilder.loadTexts: hm2DnsClientServerIndex.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientServerIndex.setDescription('The unique index used for each server added in the DNS servers table.') hm2_dns_client_server_address_type = mib_table_column((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 3, 1, 2), inet_address_type().clone('ipv4')).setMaxAccess('readwrite') if mibBuilder.loadTexts: hm2DnsClientServerAddressType.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientServerAddressType.setDescription('Address type for DNS server. Currently, only ipv4 is supported.') hm2_dns_client_server_address = mib_table_column((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 3, 1, 3), inet_address().clone(hexValue='00000000')).setMaxAccess('readwrite') if mibBuilder.loadTexts: hm2DnsClientServerAddress.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientServerAddress.setDescription('The IP address of the DNS server.') hm2_dns_client_server_row_status = mib_table_column((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 3, 1, 4), row_status()).setMaxAccess('readcreate') if mibBuilder.loadTexts: hm2DnsClientServerRowStatus.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientServerRowStatus.setDescription('Describes the status of a row in the table.') hm2_dns_client_server_diag_table = mib_table((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 4)) if mibBuilder.loadTexts: hm2DnsClientServerDiagTable.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientServerDiagTable.setDescription('The table that contains the DNS Servers entries configured and used in the system.') hm2_dns_client_server_diag_entry = mib_table_row((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 4, 1)).setIndexNames((0, 'HM2-DNS-MIB', 'hm2DnsClientServerDiagIndex')) if mibBuilder.loadTexts: hm2DnsClientServerDiagEntry.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientServerDiagEntry.setDescription('An entry contains the IP address of a DNS server used in the system.') hm2_dns_client_server_diag_index = mib_table_column((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 4, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(1, 4))) if mibBuilder.loadTexts: hm2DnsClientServerDiagIndex.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientServerDiagIndex.setDescription('The unique index used for each server added in the DNS servers table.') hm2_dns_client_server_diag_address_type = mib_table_column((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 4, 1, 2), inet_address_type()).setMaxAccess('readonly') if mibBuilder.loadTexts: hm2DnsClientServerDiagAddressType.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientServerDiagAddressType.setDescription('Address type for DNS server used. Currently, only ipv4 is supported.') hm2_dns_client_server_diag_address = mib_table_column((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 4, 1, 3), inet_address()).setMaxAccess('readonly') if mibBuilder.loadTexts: hm2DnsClientServerDiagAddress.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientServerDiagAddress.setDescription('The IP address of the DNS server used by the system. The entry can be configured by the provider, e.g. through DHCP client or PPPoE client.') hm2_dns_client_global_group = mib_identifier((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 5)) hm2_dns_client_default_domain_name = mib_scalar((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 5, 1), snmp_admin_string().subtype(subtypeSpec=value_size_constraint(0, 255))).setMaxAccess('readwrite') if mibBuilder.loadTexts: hm2DnsClientDefaultDomainName.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientDefaultDomainName.setDescription('The default domain name for unqualified hostnames.') hm2_dns_client_request_timeout = mib_scalar((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 5, 2), integer32().subtype(subtypeSpec=value_range_constraint(0, 3600)).clone(3)).setMaxAccess('readwrite') if mibBuilder.loadTexts: hm2DnsClientRequestTimeout.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientRequestTimeout.setDescription('The timeout before retransmitting a request to the server. The timeout value is configured and displayed in seconds.') hm2_dns_client_request_retransmits = mib_scalar((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 5, 3), integer32().subtype(subtypeSpec=value_range_constraint(0, 100)).clone(2)).setMaxAccess('readwrite') if mibBuilder.loadTexts: hm2DnsClientRequestRetransmits.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientRequestRetransmits.setDescription('The number of times the request is retransmitted. The request is retransmitted provided the maximum timeout value allows this many number of retransmits.') hm2_dns_client_cache_admin_state = mib_scalar((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 5, 4), hm_enabled_status().clone('enable')).setMaxAccess('readwrite') if mibBuilder.loadTexts: hm2DnsClientCacheAdminState.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientCacheAdminState.setDescription('Enables/Disables DNS client cache functionality of the device.') hm2_dns_client_static_host_config_table = mib_table((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 6)) if mibBuilder.loadTexts: hm2DnsClientStaticHostConfigTable.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientStaticHostConfigTable.setDescription('Static table of DNS hostname to IP address table') hm2_dns_client_static_host_config_entry = mib_table_row((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 6, 1)).setIndexNames((0, 'HM2-DNS-MIB', 'hm2DnsClientStaticIndex')) if mibBuilder.loadTexts: hm2DnsClientStaticHostConfigEntry.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientStaticHostConfigEntry.setDescription('An entry in the static DNS hostname IP address list. Rows may be created or deleted at any time by the DNS resolver and by SNMP SET requests.') hm2_dns_client_static_index = mib_table_column((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 6, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(1, 64))) if mibBuilder.loadTexts: hm2DnsClientStaticIndex.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientStaticIndex.setDescription('The index of the entry.') hm2_dns_client_static_host_name = mib_table_column((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 6, 1, 2), snmp_admin_string().subtype(subtypeSpec=value_size_constraint(0, 255))).setMaxAccess('readcreate') if mibBuilder.loadTexts: hm2DnsClientStaticHostName.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientStaticHostName.setDescription('The static hostname.') hm2_dns_client_static_host_address_type = mib_table_column((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 6, 1, 3), inet_address_type()).setMaxAccess('readcreate') if mibBuilder.loadTexts: hm2DnsClientStaticHostAddressType.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientStaticHostAddressType.setDescription('Address type for static hosts used. Currently, only ipv4 is supported.') hm2_dns_client_static_host_ip_address = mib_table_column((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 6, 1, 4), inet_address()).setMaxAccess('readcreate') if mibBuilder.loadTexts: hm2DnsClientStaticHostIPAddress.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientStaticHostIPAddress.setDescription('The IP address of the static host.') hm2_dns_client_static_host_status = mib_table_column((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 1, 6, 1, 5), row_status()).setMaxAccess('readcreate') if mibBuilder.loadTexts: hm2DnsClientStaticHostStatus.setStatus('current') if mibBuilder.loadTexts: hm2DnsClientStaticHostStatus.setDescription('Describes the status of a row in the table.') hm2_dns_caching_server_global_group = mib_identifier((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 3, 1)) hm2_dns_caching_server_admin_state = mib_scalar((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 3, 1, 1), hm_enabled_status().clone('enable')).setMaxAccess('readwrite') if mibBuilder.loadTexts: hm2DnsCachingServerAdminState.setStatus('current') if mibBuilder.loadTexts: hm2DnsCachingServerAdminState.setDescription('Enables/Disables DNS caching server functionality of the device.') hm2_dns_cache_admin_state = mib_scalar((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 2, 1), hm_enabled_status().clone('enable')).setMaxAccess('readwrite') if mibBuilder.loadTexts: hm2DnsCacheAdminState.setStatus('deprecated') if mibBuilder.loadTexts: hm2DnsCacheAdminState.setDescription('Enables/Disables DNS cache functionality of the device. **NOTE: this object is deprecated and replaced by hm2DnsClientCacheAdminState/hm2DnsCachingServerAdminState**.') hm2_dns_cache_flush_action = mib_scalar((1, 3, 6, 1, 4, 1, 248, 11, 90, 1, 2, 2), hm_action_value().clone('noop')).setMaxAccess('readwrite') if mibBuilder.loadTexts: hm2DnsCacheFlushAction.setStatus('deprecated') if mibBuilder.loadTexts: hm2DnsCacheFlushAction.setDescription('Setting this value to action will flush the DNS cache. After flushing the cache, it will be set to noop automatically. **NOTE: this object is deprecated and replaced by hm2DevMgmtActionFlushDnsClientCache/hm2DevMgmtActionFlushDnsCachingServerCache**.') hm2_dns_ch_host_name_already_exists_ses_error = object_identity((1, 3, 6, 1, 4, 1, 248, 11, 90, 3, 1)) if mibBuilder.loadTexts: hm2DnsCHHostNameAlreadyExistsSESError.setStatus('current') if mibBuilder.loadTexts: hm2DnsCHHostNameAlreadyExistsSESError.setDescription('The host name entered exists and is associated with an IP. The change attempt was canceled.') hm2_dns_ch_bad_ip_not_accepted_ses_error = object_identity((1, 3, 6, 1, 4, 1, 248, 11, 90, 3, 2)) if mibBuilder.loadTexts: hm2DnsCHBadIpNotAcceptedSESError.setStatus('current') if mibBuilder.loadTexts: hm2DnsCHBadIpNotAcceptedSESError.setDescription('The Ip Adress entered is not a valid one for a host. The change attempt was canceled.') hm2_dns_ch_bad_row_cannot_be_activated_ses_error = object_identity((1, 3, 6, 1, 4, 1, 248, 11, 90, 3, 3)) if mibBuilder.loadTexts: hm2DnsCHBadRowCannotBeActivatedSESError.setStatus('current') if mibBuilder.loadTexts: hm2DnsCHBadRowCannotBeActivatedSESError.setDescription('The instance cannot be activated due to compliance issues. Please modify the entry and try again.') mibBuilder.exportSymbols('HM2-DNS-MIB', hm2DnsCachingServerGlobalGroup=hm2DnsCachingServerGlobalGroup, hm2DnsClientServerIndex=hm2DnsClientServerIndex, hm2DnsClientServerAddress=hm2DnsClientServerAddress, hm2DnsClientServerCfgTable=hm2DnsClientServerCfgTable, PYSNMP_MODULE_ID=hm2DnsMib, hm2DnsClientServerDiagAddress=hm2DnsClientServerDiagAddress, hm2DnsClientStaticHostConfigTable=hm2DnsClientStaticHostConfigTable, hm2DnsClientGlobalGroup=hm2DnsClientGlobalGroup, hm2DnsCacheGroup=hm2DnsCacheGroup, hm2DnsClientServerDiagEntry=hm2DnsClientServerDiagEntry, hm2DnsMibSNMPExtensionGroup=hm2DnsMibSNMPExtensionGroup, hm2DnsClientGroup=hm2DnsClientGroup, hm2DnsMibObjects=hm2DnsMibObjects, hm2DnsClientDefaultDomainName=hm2DnsClientDefaultDomainName, hm2DnsClientStaticHostStatus=hm2DnsClientStaticHostStatus, hm2DnsCacheAdminState=hm2DnsCacheAdminState, hm2DnsClientRequestTimeout=hm2DnsClientRequestTimeout, hm2DnsClientServerDiagAddressType=hm2DnsClientServerDiagAddressType, hm2DnsCachingServerGroup=hm2DnsCachingServerGroup, hm2DnsClientServerDiagTable=hm2DnsClientServerDiagTable, hm2DnsCHBadIpNotAcceptedSESError=hm2DnsCHBadIpNotAcceptedSESError, hm2DnsClientAdminState=hm2DnsClientAdminState, hm2DnsClientStaticHostName=hm2DnsClientStaticHostName, hm2DnsClientRequestRetransmits=hm2DnsClientRequestRetransmits, hm2DnsMibNotifications=hm2DnsMibNotifications, hm2DnsClientConfigSource=hm2DnsClientConfigSource, hm2DnsClientServerRowStatus=hm2DnsClientServerRowStatus, hm2DnsClientServerDiagIndex=hm2DnsClientServerDiagIndex, hm2DnsClientCacheAdminState=hm2DnsClientCacheAdminState, hm2DnsCHHostNameAlreadyExistsSESError=hm2DnsCHHostNameAlreadyExistsSESError, hm2DnsCacheFlushAction=hm2DnsCacheFlushAction, hm2DnsClientStaticIndex=hm2DnsClientStaticIndex, hm2DnsClientStaticHostAddressType=hm2DnsClientStaticHostAddressType, hm2DnsCachingServerAdminState=hm2DnsCachingServerAdminState, hm2DnsCHBadRowCannotBeActivatedSESError=hm2DnsCHBadRowCannotBeActivatedSESError, hm2DnsClientServerAddressType=hm2DnsClientServerAddressType, hm2DnsMib=hm2DnsMib, hm2DnsClientStaticHostIPAddress=hm2DnsClientStaticHostIPAddress, hm2DnsClientServerCfgEntry=hm2DnsClientServerCfgEntry, hm2DnsClientStaticHostConfigEntry=hm2DnsClientStaticHostConfigEntry)
class Params: def __init__(self): self.embed_size = 75 self.epochs = 2000 self.learning_rate = 0.01 self.top_k = 20 self.ent_top_k = [1, 5, 10, 50] self.lambda_3 = 0.7 self.generate_sim = 10 self.csls = 5 self.heuristic = True self.is_save = True self.mu1 = 1.0 self.mu2 = 1.0 self.nums_threads = 10 self.nums_threads_batch = 1 self.margin_rel = 0.5 self.margin_neg_triple = 1.2 self.margin_ent = 0.5 self.nums_neg = 10 self.nums_neg_neighbor = 10 self.epsilon = 0.95 self.batch_size = 10000 self.is_disc = True self.nn = 5 def print(self): print("Parameters used in this running are as follows:") items = sorted(self.__dict__.items(), key=lambda d: d[0]) for item in items: print("%s: %s" % item) print() P = Params() P.print() if __name__ == '__main__': print("w" + str(1))
class Params: def __init__(self): self.embed_size = 75 self.epochs = 2000 self.learning_rate = 0.01 self.top_k = 20 self.ent_top_k = [1, 5, 10, 50] self.lambda_3 = 0.7 self.generate_sim = 10 self.csls = 5 self.heuristic = True self.is_save = True self.mu1 = 1.0 self.mu2 = 1.0 self.nums_threads = 10 self.nums_threads_batch = 1 self.margin_rel = 0.5 self.margin_neg_triple = 1.2 self.margin_ent = 0.5 self.nums_neg = 10 self.nums_neg_neighbor = 10 self.epsilon = 0.95 self.batch_size = 10000 self.is_disc = True self.nn = 5 def print(self): print('Parameters used in this running are as follows:') items = sorted(self.__dict__.items(), key=lambda d: d[0]) for item in items: print('%s: %s' % item) print() p = params() P.print() if __name__ == '__main__': print('w' + str(1))
class Solution: def longestPalindrome(self, s: str) -> int: m = {} for c in s: if c in m: m[c] += 1 else: m[c] = 1 ans = 0 longest_odd = 0 longest_char = None; for key in m: if m[key] % 2 == 1: if longest_odd < m[key]: longest_char = key else: ans += m[key] for key in m: if m[key] % 2 == 1: if key == longest_char: ans += m[key] else: ans += m[key] - 1 return ans
class Solution: def longest_palindrome(self, s: str) -> int: m = {} for c in s: if c in m: m[c] += 1 else: m[c] = 1 ans = 0 longest_odd = 0 longest_char = None for key in m: if m[key] % 2 == 1: if longest_odd < m[key]: longest_char = key else: ans += m[key] for key in m: if m[key] % 2 == 1: if key == longest_char: ans += m[key] else: ans += m[key] - 1 return ans
# https://www.hackerrank.com/challenges/icecream-parlor/problem t = int(input()) for _ in range(t): m = int(input()) n = int(input()) cost = list(map(int, input().split())) memo = {} for i, c in enumerate(cost): if (m - c) in memo: print('%s %s' % (memo[m - c], i + 1)) break memo[c] = i + 1
t = int(input()) for _ in range(t): m = int(input()) n = int(input()) cost = list(map(int, input().split())) memo = {} for (i, c) in enumerate(cost): if m - c in memo: print('%s %s' % (memo[m - c], i + 1)) break memo[c] = i + 1
# Enum for allegiances ALLEGIANCE_MAP = { 0: "Shadow", 1: "Neutral", 2: "Hunter" } # Enum for card types CARD_COLOR_MAP = { 0: "White", 1: "Black", 2: "Green" } # Enum for text colors TEXT_COLORS = { 'server': 'rgb(200,200,200)', 'number': 'rgb(153,204,255)', 'White': 'rgb(255,255,255)', 'Black': 'rgb(75,75,75)', 'Green': 'rgb(143,194,0)', 'shadow': 'rgb(128,0,0)', 'neutral': 'rgb(255,255,153)', 'hunter': 'rgb(51,51,255)', 'Weird Woods': 'rgb(102,153,153)', 'Church': 'rgb(255,255,255)', 'Cemetery': 'rgb(75,75,75)', 'Erstwhile Altar': 'rgb(204,68,0)', 'Hermit\'s Cabin': 'rgb(143,194,0)', 'Underworld Gate': 'rgb(150,0,150)' } # Number of gameplay tests to run N_GAMEPLAY_TESTS = 250
allegiance_map = {0: 'Shadow', 1: 'Neutral', 2: 'Hunter'} card_color_map = {0: 'White', 1: 'Black', 2: 'Green'} text_colors = {'server': 'rgb(200,200,200)', 'number': 'rgb(153,204,255)', 'White': 'rgb(255,255,255)', 'Black': 'rgb(75,75,75)', 'Green': 'rgb(143,194,0)', 'shadow': 'rgb(128,0,0)', 'neutral': 'rgb(255,255,153)', 'hunter': 'rgb(51,51,255)', 'Weird Woods': 'rgb(102,153,153)', 'Church': 'rgb(255,255,255)', 'Cemetery': 'rgb(75,75,75)', 'Erstwhile Altar': 'rgb(204,68,0)', "Hermit's Cabin": 'rgb(143,194,0)', 'Underworld Gate': 'rgb(150,0,150)'} n_gameplay_tests = 250
with open('binary_numbers.txt') as f: lines = f.readlines() length = len(lines) # Part One def most_common(strings): # Creates a list of amount of 1's at each index for all lines in the string. E.g. a = [1, 3, 2] will have 3 binary numbers with 1 at index 1. indices = [] bit_length = len(strings[0].strip()) for _ in range(bit_length): indices.append(0) for line in strings: line = line.strip() for index, char in enumerate(line): if char == "1": indices[index] += 1 return indices def binary_converter(list, list_length): output_str = "" for index in list: if index / list_length >= 0.5: output_str += "1" else: output_str += "0" return output_str # function to flip bits def flip_bits(binary_str): output_str = "" for char in binary_str: if char == "1": output_str += "0" else: output_str += "1" return output_str # function to convert binary to decimal def binary_to_decimal(binary_str): decimal = 0 for index, char in enumerate(binary_str): if char == "1": decimal += 2**(len(binary_str) - index - 1) return decimal gamma_binary = binary_converter(most_common(lines), length) epsilon_binary = flip_bits(binary_converter(most_common(lines), length)) gamma_decimal = binary_to_decimal(gamma_binary) epsilon_decimal = binary_to_decimal(epsilon_binary) print("Gamma binary: {} \nEpsilon binary: {}".format(gamma_binary, epsilon_binary)) print("Gamma decimal: {} \nEpsilon decimal: {}".format(gamma_decimal, epsilon_decimal)) print("Power consumption: {}".format(gamma_decimal * epsilon_decimal)) # Part Two def most_common_with_zeros(list, list_length): indices = [] for index in list: if index / list_length >= 0.5: indices.append(1) else: indices.append(0) return indices def least_common_with_zeros(list, list_length): indices = [] for index in list: if index / list_length <= 0.5: indices.append(1) else: indices.append(0) return indices def oxygen_generator_rating(most_common_list, list): line_length = len(list[0].strip()) trimmed = list for i in range(line_length): mc_index = most_common_at_index(trimmed, i) temp = trim_elements(mc_index, i, trimmed) trimmed = temp if len(trimmed) == 1: return trimmed[0] def co2_scrubber_rating(least_common_list, list): line_length = len(list[0].strip()) trimmed = list for i in range(line_length): lc_index = least_common_at_index(trimmed, i) temp = trim_elements(lc_index, i, trimmed) trimmed = temp if len(trimmed) == 1: return trimmed[0] def most_common_at_index(list, index_number): length = len(list) ind = 0 for element in list: if element[index_number] == "1": ind += 1 if ind / length >= 0.5: return 1 else: return 0 def least_common_at_index(list, index_number): length = len(list) ind = 0 for element in list: if element[index_number] == "1": ind += 1 if ind / length < 0.5: return 1 else: return 0 def trim_elements(binary_number, index, list): return_list = [] for element in list: if int(element[index]) == binary_number: return_list.append(element) return return_list def magic_binary(binary_str): # How did i never know about this? Turns binary to decimal return int(binary_str, 2) def flip_list(list): output_list = [] for item in list: if item == 1: output_list.append(0) else: output_list.append(1) return output_list mci = most_common_with_zeros(most_common(lines), length) ogr = oxygen_generator_rating(mci, lines) dec_ogr = magic_binary(ogr) lci = least_common_with_zeros(most_common(lines), length) # lci = flip_list(mci) cosr = co2_scrubber_rating(lci, lines) dec_cosr = magic_binary(cosr) print("Most common: {}".format(most_common(lines))) print("Most common with zeros: {}".format(mci)) print("Least common with zeros: {}".format(lci)) print("Oxygen Generator Rating: | binary: {} | decimal: {}".format(ogr, dec_ogr)) print("CO2 Scrubber Rate: | binary {} | decimal: {}".format(cosr, dec_cosr)) print("Life Support Rating: {}.".format(dec_ogr * dec_cosr)) #print(oxygen_generator_rating(most_common_with_zeros(lines), lines))
with open('binary_numbers.txt') as f: lines = f.readlines() length = len(lines) def most_common(strings): indices = [] bit_length = len(strings[0].strip()) for _ in range(bit_length): indices.append(0) for line in strings: line = line.strip() for (index, char) in enumerate(line): if char == '1': indices[index] += 1 return indices def binary_converter(list, list_length): output_str = '' for index in list: if index / list_length >= 0.5: output_str += '1' else: output_str += '0' return output_str def flip_bits(binary_str): output_str = '' for char in binary_str: if char == '1': output_str += '0' else: output_str += '1' return output_str def binary_to_decimal(binary_str): decimal = 0 for (index, char) in enumerate(binary_str): if char == '1': decimal += 2 ** (len(binary_str) - index - 1) return decimal gamma_binary = binary_converter(most_common(lines), length) epsilon_binary = flip_bits(binary_converter(most_common(lines), length)) gamma_decimal = binary_to_decimal(gamma_binary) epsilon_decimal = binary_to_decimal(epsilon_binary) print('Gamma binary: {} \nEpsilon binary: {}'.format(gamma_binary, epsilon_binary)) print('Gamma decimal: {} \nEpsilon decimal: {}'.format(gamma_decimal, epsilon_decimal)) print('Power consumption: {}'.format(gamma_decimal * epsilon_decimal)) def most_common_with_zeros(list, list_length): indices = [] for index in list: if index / list_length >= 0.5: indices.append(1) else: indices.append(0) return indices def least_common_with_zeros(list, list_length): indices = [] for index in list: if index / list_length <= 0.5: indices.append(1) else: indices.append(0) return indices def oxygen_generator_rating(most_common_list, list): line_length = len(list[0].strip()) trimmed = list for i in range(line_length): mc_index = most_common_at_index(trimmed, i) temp = trim_elements(mc_index, i, trimmed) trimmed = temp if len(trimmed) == 1: return trimmed[0] def co2_scrubber_rating(least_common_list, list): line_length = len(list[0].strip()) trimmed = list for i in range(line_length): lc_index = least_common_at_index(trimmed, i) temp = trim_elements(lc_index, i, trimmed) trimmed = temp if len(trimmed) == 1: return trimmed[0] def most_common_at_index(list, index_number): length = len(list) ind = 0 for element in list: if element[index_number] == '1': ind += 1 if ind / length >= 0.5: return 1 else: return 0 def least_common_at_index(list, index_number): length = len(list) ind = 0 for element in list: if element[index_number] == '1': ind += 1 if ind / length < 0.5: return 1 else: return 0 def trim_elements(binary_number, index, list): return_list = [] for element in list: if int(element[index]) == binary_number: return_list.append(element) return return_list def magic_binary(binary_str): return int(binary_str, 2) def flip_list(list): output_list = [] for item in list: if item == 1: output_list.append(0) else: output_list.append(1) return output_list mci = most_common_with_zeros(most_common(lines), length) ogr = oxygen_generator_rating(mci, lines) dec_ogr = magic_binary(ogr) lci = least_common_with_zeros(most_common(lines), length) cosr = co2_scrubber_rating(lci, lines) dec_cosr = magic_binary(cosr) print('Most common: {}'.format(most_common(lines))) print('Most common with zeros: {}'.format(mci)) print('Least common with zeros: {}'.format(lci)) print('Oxygen Generator Rating: | binary: {} | decimal: {}'.format(ogr, dec_ogr)) print('CO2 Scrubber Rate: | binary {} | decimal: {}'.format(cosr, dec_cosr)) print('Life Support Rating: {}.'.format(dec_ogr * dec_cosr))
class DarkKeeperError(Exception): pass class DarkKeeperCacheError(DarkKeeperError): pass class DarkKeeperCacheReadError(DarkKeeperCacheError): pass class DarkKeeperCacheWriteError(DarkKeeperCacheError): pass class DarkKeeperParseError(DarkKeeperError): pass class DarkKeeperParseContentError(DarkKeeperParseError): pass class DarkKeeperRequestError(DarkKeeperError): pass class DarkKeeperRequestResponseError(DarkKeeperRequestError): pass class DarkKeeperMongoError(DarkKeeperError): pass class DarkKeeperParseUriMongoError(DarkKeeperMongoError): pass
class Darkkeepererror(Exception): pass class Darkkeepercacheerror(DarkKeeperError): pass class Darkkeepercachereaderror(DarkKeeperCacheError): pass class Darkkeepercachewriteerror(DarkKeeperCacheError): pass class Darkkeeperparseerror(DarkKeeperError): pass class Darkkeeperparsecontenterror(DarkKeeperParseError): pass class Darkkeeperrequesterror(DarkKeeperError): pass class Darkkeeperrequestresponseerror(DarkKeeperRequestError): pass class Darkkeepermongoerror(DarkKeeperError): pass class Darkkeeperparseurimongoerror(DarkKeeperMongoError): pass
def initialize(n): for key in ['queen','row','col','rwtose','swtose']: board[key]={} for i in range(n): board['queen'][i]=-1 board['row'][i]=0 board['col'][i]=0 for i in range(-(n-1),n): board['rwtose'][i]=0 for i in range(2*n-1): board['swtose'][i]=0 def free(i,j): return( board['row'][i]==0 and board['col'][j]==0 and board['rwtose'][j-i]==0 and board['swtose'][j+i]==0 ) def addqueen(i,j): board['queen'][i]=j board['row'][i]=1 board['col'][j]=1 board['rwtose'][j-i]=1 board['swtose'][j+i]=1 def undoqueen(i,j): board['queen'][i]=-1 board['row'][i]=0 board['col'][j]=0 board['rwtose'][j-i]=0 board['swtose'][j+i]=0 def printboard(): for row in sorted(board['queen'].keys()): print((row,board['queen'][row]),end=" ") print(" ") def placequeen(i): n=len(board['queen'].keys()) for j in range(n): if free(i,j): addqueen(i,j) if i==n-1: printboard()#remove for single solution # return(True) else: extendsoln=placequeen(i+1) # if(extendsoln): # return True # else: undoqueen(i,j) # else: # return(False) board={} n=int(input("How many queen?")) initialize(n) placequeen(0) # if placequeen(0): # printboard()
def initialize(n): for key in ['queen', 'row', 'col', 'rwtose', 'swtose']: board[key] = {} for i in range(n): board['queen'][i] = -1 board['row'][i] = 0 board['col'][i] = 0 for i in range(-(n - 1), n): board['rwtose'][i] = 0 for i in range(2 * n - 1): board['swtose'][i] = 0 def free(i, j): return board['row'][i] == 0 and board['col'][j] == 0 and (board['rwtose'][j - i] == 0) and (board['swtose'][j + i] == 0) def addqueen(i, j): board['queen'][i] = j board['row'][i] = 1 board['col'][j] = 1 board['rwtose'][j - i] = 1 board['swtose'][j + i] = 1 def undoqueen(i, j): board['queen'][i] = -1 board['row'][i] = 0 board['col'][j] = 0 board['rwtose'][j - i] = 0 board['swtose'][j + i] = 0 def printboard(): for row in sorted(board['queen'].keys()): print((row, board['queen'][row]), end=' ') print(' ') def placequeen(i): n = len(board['queen'].keys()) for j in range(n): if free(i, j): addqueen(i, j) if i == n - 1: printboard() else: extendsoln = placequeen(i + 1) undoqueen(i, j) board = {} n = int(input('How many queen?')) initialize(n) placequeen(0)
def raizI(x,b): if b** 2>x: return b-1 return raizI (x,b+1) raizI(11,5)
def raiz_i(x, b): if b ** 2 > x: return b - 1 return raiz_i(x, b + 1) raiz_i(11, 5)
class Solution: def numberOfSteps (self, num: int) -> int: count = 0 while num!=0: print(num,count) if num==1: count+=1 return count if num%2==0: count+=1 else: count+=2 num = num>>1
class Solution: def number_of_steps(self, num: int) -> int: count = 0 while num != 0: print(num, count) if num == 1: count += 1 return count if num % 2 == 0: count += 1 else: count += 2 num = num >> 1
class ErrorSeverity(object): FATAL = 'fatal' ERROR = 'error' WARNING = 'warning' ALLOWED_VALUES = (FATAL, ERROR, WARNING) @classmethod def validate(cls, value): return value in cls.ALLOWED_VALUES
class Errorseverity(object): fatal = 'fatal' error = 'error' warning = 'warning' allowed_values = (FATAL, ERROR, WARNING) @classmethod def validate(cls, value): return value in cls.ALLOWED_VALUES
#!/usr/bin/env python3 def write_csv(filename, content): with open(filename, 'w') as csvfile: for line in content: for i, item in enumerate(line): csvfile.write(str(item)) if i != len(line) - 1: csvfile.write(',') csvfile.write('\n') def read_csv(filename): with open(filename, 'r') as content: return [[v for v in line.replace('\n', '').split(',')] for line in content]
def write_csv(filename, content): with open(filename, 'w') as csvfile: for line in content: for (i, item) in enumerate(line): csvfile.write(str(item)) if i != len(line) - 1: csvfile.write(',') csvfile.write('\n') def read_csv(filename): with open(filename, 'r') as content: return [[v for v in line.replace('\n', '').split(',')] for line in content]
'''Change the database in this file Change the database in this script locally Careful here '''
"""Change the database in this file Change the database in this script locally Careful here """
class LevelUpCooldownError(Exception): pass class MaxLevelError(Exception): pass
class Levelupcooldownerror(Exception): pass class Maxlevelerror(Exception): pass
# # Copyright 2013 Red Hat, Inc. # # 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. # RESULT_OK = 0 RESULT_ERROR = 1 PLUGIN_ERRORS = "plugin_errors" ERRORS = "errors" class Result(object): def __init__(self): self._result = {} self._result["result_code"] = RESULT_OK # no error so far.. self._result["result"] = [] def add(self, obj_list): self._result["result"].extend(obj_list) def pluginError(self, pluginName, errorMsg): self._result["result_code"] = RESULT_ERROR pluginErrors = self._result.get(PLUGIN_ERRORS, {}) # get the list of error messages for plugin or a new list # if it's the first error pluginErrorMessages = pluginErrors.get(pluginName, []) pluginErrorMessages.append(errorMsg) # put the plugin error list to the error dict # we could do that only for the first time, # but this way we can save one 'if key in dict' pluginErrors[pluginName] = pluginErrorMessages self._result[PLUGIN_ERRORS] = pluginErrors def error(self, errorMsg): self._result["result_code"] = RESULT_ERROR errors = self._result.get(ERRORS, []) errors.append(errorMsg) self._result[ERRORS] = errors def to_dict(self): return self._result class FilterResult(Result): def __init__(self): super(FilterResult, self).__init__() class WeightResult(Result): def __init__(self): super(WeightResult, self).__init__()
result_ok = 0 result_error = 1 plugin_errors = 'plugin_errors' errors = 'errors' class Result(object): def __init__(self): self._result = {} self._result['result_code'] = RESULT_OK self._result['result'] = [] def add(self, obj_list): self._result['result'].extend(obj_list) def plugin_error(self, pluginName, errorMsg): self._result['result_code'] = RESULT_ERROR plugin_errors = self._result.get(PLUGIN_ERRORS, {}) plugin_error_messages = pluginErrors.get(pluginName, []) pluginErrorMessages.append(errorMsg) pluginErrors[pluginName] = pluginErrorMessages self._result[PLUGIN_ERRORS] = pluginErrors def error(self, errorMsg): self._result['result_code'] = RESULT_ERROR errors = self._result.get(ERRORS, []) errors.append(errorMsg) self._result[ERRORS] = errors def to_dict(self): return self._result class Filterresult(Result): def __init__(self): super(FilterResult, self).__init__() class Weightresult(Result): def __init__(self): super(WeightResult, self).__init__()
mys1 = {1,2,3,4} mys2 = {3,4,5,6} mys1.difference_update(mys2) print(mys1) # DU1 mys3 = {'a','b','c','d'} mys4 = {'d','w','f','g'} mys5 = {'v','w','x','z'} mys3.difference_update(mys4) print(mys3) # DU2 mys4.difference_update(mys5) print(mys4) # DU3
mys1 = {1, 2, 3, 4} mys2 = {3, 4, 5, 6} mys1.difference_update(mys2) print(mys1) mys3 = {'a', 'b', 'c', 'd'} mys4 = {'d', 'w', 'f', 'g'} mys5 = {'v', 'w', 'x', 'z'} mys3.difference_update(mys4) print(mys3) mys4.difference_update(mys5) print(mys4)
NUMERICAL_TYPE = "num" NUMERICAL_PREFIX = "n_" CATEGORY_TYPE = "cat" CATEGORY_PREFIX = "c_" TIME_TYPE = "time" TIME_PREFIX = "t_" MULTI_CAT_TYPE = "multi-cat" MULTI_CAT_PREFIX = "m_" MULTI_CAT_DELIMITER = "," MAIN_TABLE_NAME = "main" MAIN_TABLE_TEST_NAME = "main_test" TABLE_PREFIX = "table_" LABEL = "label" HASH_MAX = 200 AGG_FEAT_MAX = 4 RANDOM_SEED = 2019 N_RANDOM_COL = 7 SAMPLE_SIZE = 100000 HYPEROPT_TEST_SIZE = 0.5 BEST_ITER_THRESHOLD = 100 IMBALANCE_RATE = 0.001 MEMORY_LIMIT = 10000 # 10GB N_EST = 500 N_STOP = 10 KFOLD = 5
numerical_type = 'num' numerical_prefix = 'n_' category_type = 'cat' category_prefix = 'c_' time_type = 'time' time_prefix = 't_' multi_cat_type = 'multi-cat' multi_cat_prefix = 'm_' multi_cat_delimiter = ',' main_table_name = 'main' main_table_test_name = 'main_test' table_prefix = 'table_' label = 'label' hash_max = 200 agg_feat_max = 4 random_seed = 2019 n_random_col = 7 sample_size = 100000 hyperopt_test_size = 0.5 best_iter_threshold = 100 imbalance_rate = 0.001 memory_limit = 10000 n_est = 500 n_stop = 10 kfold = 5
# Operations allowed : Insertion, Addition, Deletion def func(str1, str2, m, n): dp = [[0 for x in range(n+1)] for x in range(m+1)] for i in range(m+1): for j in range(n+1): if i == 0: dp[i][j] = j elif j == 0: dp[i][j] = i elif str1[i-1] == str2[j-1]: dp[i][j] = dp[i-1][j-1] else: dp[i][j] = 1 + min(dp[i][j-1], dp[i-1][j], dp[i-1][j-1]) return dp[m][n] if __name__ == '__main__': str1 = "hacktoberfest" str2 = "hackerearth" print(func(str1, str2, len(str1), len(str2)))
def func(str1, str2, m, n): dp = [[0 for x in range(n + 1)] for x in range(m + 1)] for i in range(m + 1): for j in range(n + 1): if i == 0: dp[i][j] = j elif j == 0: dp[i][j] = i elif str1[i - 1] == str2[j - 1]: dp[i][j] = dp[i - 1][j - 1] else: dp[i][j] = 1 + min(dp[i][j - 1], dp[i - 1][j], dp[i - 1][j - 1]) return dp[m][n] if __name__ == '__main__': str1 = 'hacktoberfest' str2 = 'hackerearth' print(func(str1, str2, len(str1), len(str2)))
# Tai Sakuma <[email protected]> ##__________________________________________________________________|| def create_file_start_length_list(file_nevents_list, max_events_per_run = -1, max_events_total = -1, max_files_per_run = 1): file_nevents_list = _apply_max_events_total(file_nevents_list, max_events_total) return _file_start_length_list(file_nevents_list, max_events_per_run, max_files_per_run) ##__________________________________________________________________|| def _apply_max_events_total(file_nevents_list, max_events_total = -1): if max_events_total < 0: return file_nevents_list ret = [ ] for file, nevents in file_nevents_list: if max_events_total == 0: break nevents = min(max_events_total, nevents) ret.append((file, nevents)) max_events_total -= nevents return ret ##__________________________________________________________________|| def _file_start_length_list(file_nevents_list, max_events_per_run, max_files_per_run): if not file_nevents_list: return [ ] total_nevents = sum([n for f, n, in file_nevents_list]) if total_nevents == 0: return [ ] if max_files_per_run == 0: return [ ] if max_events_per_run == 0: return [ ] if max_events_per_run < 0: max_events_per_run = total_nevents total_nfiles = len(set([f for f, n, in file_nevents_list])) if max_files_per_run < 0: max_files_per_run = total_nfiles files = [ ] nevents = [ ] start = [ ] length = [ ] i = 0 for file_, nev in file_nevents_list: if nev == 0: continue if i == len(files): # create a new run files.append([ ]) nevents.append(0) start.append(0) length.append(0) files[i].append(file_) nevents[i] += nev if max_events_per_run >= nevents[i]: length[i] = nevents[i] else: dlength = max_events_per_run - length[i] length[i] = max_events_per_run i += 1 files.append([file_]) nevents.append(nevents[i-1] - length[i-1]) start.append(dlength) while max_events_per_run < nevents[i]: length.append(max_events_per_run) i += 1 files.append([file_]) nevents.append(nevents[i-1] - length[i-1]) start.append(start[i-1] + length[i-1]) length.append(nevents[i]) if max_events_per_run == nevents[i]: i += 1 # to next run continue if max_files_per_run == len(files[i]): i += 1 # to next run # print files, nevents, start, length ret = list(zip(files, start, length)) return ret ##__________________________________________________________________|| def _start_length_pairs_for_split_lists(ntotal, max_per_list): # e.g., ntotal = 35, max_per_list = 10 if max_per_list < 0: return [(0, ntotal)] nlists = ntotal//max_per_list # https://stackoverflow.com/questions/1282945/python-integer-division-yields-float # nlists = 3 ret = [(i*max_per_list, max_per_list) for i in range(nlists)] # e.g., [(0, 10), (10, 10), (20, 10)] remainder = ntotal % max_per_list # e.g., 5 if remainder > 0: last = (nlists*max_per_list, remainder) # e.g, (30, 5) ret.append(last) # e.g., [(0, 10), (10, 10), (20, 10), (30, 5)] return ret ##__________________________________________________________________|| def _minimum_positive_value(vals): # returns -1 if all negative or empty vals = [v for v in vals if v >= 0] if not vals: return -1 return min(vals) ##__________________________________________________________________||
def create_file_start_length_list(file_nevents_list, max_events_per_run=-1, max_events_total=-1, max_files_per_run=1): file_nevents_list = _apply_max_events_total(file_nevents_list, max_events_total) return _file_start_length_list(file_nevents_list, max_events_per_run, max_files_per_run) def _apply_max_events_total(file_nevents_list, max_events_total=-1): if max_events_total < 0: return file_nevents_list ret = [] for (file, nevents) in file_nevents_list: if max_events_total == 0: break nevents = min(max_events_total, nevents) ret.append((file, nevents)) max_events_total -= nevents return ret def _file_start_length_list(file_nevents_list, max_events_per_run, max_files_per_run): if not file_nevents_list: return [] total_nevents = sum([n for (f, n) in file_nevents_list]) if total_nevents == 0: return [] if max_files_per_run == 0: return [] if max_events_per_run == 0: return [] if max_events_per_run < 0: max_events_per_run = total_nevents total_nfiles = len(set([f for (f, n) in file_nevents_list])) if max_files_per_run < 0: max_files_per_run = total_nfiles files = [] nevents = [] start = [] length = [] i = 0 for (file_, nev) in file_nevents_list: if nev == 0: continue if i == len(files): files.append([]) nevents.append(0) start.append(0) length.append(0) files[i].append(file_) nevents[i] += nev if max_events_per_run >= nevents[i]: length[i] = nevents[i] else: dlength = max_events_per_run - length[i] length[i] = max_events_per_run i += 1 files.append([file_]) nevents.append(nevents[i - 1] - length[i - 1]) start.append(dlength) while max_events_per_run < nevents[i]: length.append(max_events_per_run) i += 1 files.append([file_]) nevents.append(nevents[i - 1] - length[i - 1]) start.append(start[i - 1] + length[i - 1]) length.append(nevents[i]) if max_events_per_run == nevents[i]: i += 1 continue if max_files_per_run == len(files[i]): i += 1 ret = list(zip(files, start, length)) return ret def _start_length_pairs_for_split_lists(ntotal, max_per_list): if max_per_list < 0: return [(0, ntotal)] nlists = ntotal // max_per_list ret = [(i * max_per_list, max_per_list) for i in range(nlists)] remainder = ntotal % max_per_list if remainder > 0: last = (nlists * max_per_list, remainder) ret.append(last) return ret def _minimum_positive_value(vals): vals = [v for v in vals if v >= 0] if not vals: return -1 return min(vals)
def buildFireTraps(start, end, step, x, y): for i in range(start, end+1, step): if x: hero.buildXY("fire-trap", x, i) else: hero.buildXY("fire-trap", i, y) buildFireTraps(40, 112, 24, False, 114) buildFireTraps(110, 38, -18, 140, False) buildFireTraps(132, 32, -20, False, 22) buildFireTraps(28, 108, 16, 20, False) hero.moveXY(40, 94)
def build_fire_traps(start, end, step, x, y): for i in range(start, end + 1, step): if x: hero.buildXY('fire-trap', x, i) else: hero.buildXY('fire-trap', i, y) build_fire_traps(40, 112, 24, False, 114) build_fire_traps(110, 38, -18, 140, False) build_fire_traps(132, 32, -20, False, 22) build_fire_traps(28, 108, 16, 20, False) hero.moveXY(40, 94)
# TLV format: # TAG | LENGTH | VALUE # Header contains nested TLV triplets TRACE_TAG_HEADER = 1 TRACE_TAG_EVENTS = 2 TRACE_TAG_FILES = 3 TRACE_TAG_METADATA = 4 HEADER_TAG_VERSION = 1 HEADER_TAG_FILES = 2 HEADER_TAG_METADATA = 3
trace_tag_header = 1 trace_tag_events = 2 trace_tag_files = 3 trace_tag_metadata = 4 header_tag_version = 1 header_tag_files = 2 header_tag_metadata = 3
''' Classes to work with WebSphere Application Servers Author: Christoph Stoettner Mail: [email protected] Documentation: http://scripting101.stoeps.de Version: 5.0.1 Date: 09/19/2015 License: Apache 2.0 ''' class WasServers: def __init__(self): # Get a list of all servers in WAS cell (dmgr, nodeagents, AppServer, # webserver) self.AllServers = self.getAllServers() self.WebServers = self.getWebServers() self.AppServers = self.getAllServersWithoutWeb() # self.serverNum, self.jvm, self.cell, self.node, self.serverName = self.getAttrServers() self.serverNum, self.jvm, self.cell, self.node, self.serverName = self.getAttrServers() def getAllServers(self): # get a list of all servers self.servers = AdminTask.listServers().splitlines() return self.servers def getAppServers(self): # get a list of all application servers # includes webserver, but no dmgr and nodeagents self.servers = AdminTask.listServers( '[-serverType APPLICATION_SERVER]').splitlines() return self.servers def getWebServers(self): # get a list of all webservers self.webservers = AdminTask.listServers( '[-serverType WEB_SERVER]').splitlines() return self.webservers def getAllServersWithoutWeb(self): # inclusive dmgr and nodeagents self.AppServers = self.AllServers for webserver in self.WebServers: self.AppServers.remove(webserver) return self.AppServers def getAttrServers(self): # get jvm, node, cell from single application server srvNum = 0 jvm = [] cell = [] node = [] servername = [] for server in self.AppServers: srvNum += 1 javavm = AdminConfig.list('JavaVirtualMachine', server) jvm.append(javavm) srv = server.split('/') cell.append(srv[1]) node.append(srv[3]) servername.append(srv[5].split('|')[0]) self.jvm = jvm cell = cell node = node servername = servername # return ( serverNum, jvm, cell, node, serverName ) return (srvNum, self.jvm, cell, node, servername)
""" Classes to work with WebSphere Application Servers Author: Christoph Stoettner Mail: [email protected] Documentation: http://scripting101.stoeps.de Version: 5.0.1 Date: 09/19/2015 License: Apache 2.0 """ class Wasservers: def __init__(self): self.AllServers = self.getAllServers() self.WebServers = self.getWebServers() self.AppServers = self.getAllServersWithoutWeb() (self.serverNum, self.jvm, self.cell, self.node, self.serverName) = self.getAttrServers() def get_all_servers(self): self.servers = AdminTask.listServers().splitlines() return self.servers def get_app_servers(self): self.servers = AdminTask.listServers('[-serverType APPLICATION_SERVER]').splitlines() return self.servers def get_web_servers(self): self.webservers = AdminTask.listServers('[-serverType WEB_SERVER]').splitlines() return self.webservers def get_all_servers_without_web(self): self.AppServers = self.AllServers for webserver in self.WebServers: self.AppServers.remove(webserver) return self.AppServers def get_attr_servers(self): srv_num = 0 jvm = [] cell = [] node = [] servername = [] for server in self.AppServers: srv_num += 1 javavm = AdminConfig.list('JavaVirtualMachine', server) jvm.append(javavm) srv = server.split('/') cell.append(srv[1]) node.append(srv[3]) servername.append(srv[5].split('|')[0]) self.jvm = jvm cell = cell node = node servername = servername return (srvNum, self.jvm, cell, node, servername)
class Solution: def findReplaceString(self, S: str, indexes: List[int], sources: List[str], targets: List[str]) -> str: ans = [""] * len(S) for i in range(len(S)): ans[i] = S[i] for i in range(len(indexes)): start = indexes[i] src = sources[i] change = 1 for j in range(len(src)): if S[start + j] != src[j]: change = 0 break if change == 0: continue ans[start] = targets[i] for j in range(1,len(src)): ans[start + j] = "" return "".join(ans)
class Solution: def find_replace_string(self, S: str, indexes: List[int], sources: List[str], targets: List[str]) -> str: ans = [''] * len(S) for i in range(len(S)): ans[i] = S[i] for i in range(len(indexes)): start = indexes[i] src = sources[i] change = 1 for j in range(len(src)): if S[start + j] != src[j]: change = 0 break if change == 0: continue ans[start] = targets[i] for j in range(1, len(src)): ans[start + j] = '' return ''.join(ans)
############################################################################### # Singlecell plot arrays # ############################################################################### tag = "singlecell"
tag = 'singlecell'
class PipelineNotDeployed(Exception): def __init__(self, pipeline_id=None, message="Pipeline not deployed") -> None: self.pipeline_id = pipeline_id self.message = message super().__init__(self.message) def __str__(self): return f"{self.pipeline_id} -> {self.message}"
class Pipelinenotdeployed(Exception): def __init__(self, pipeline_id=None, message='Pipeline not deployed') -> None: self.pipeline_id = pipeline_id self.message = message super().__init__(self.message) def __str__(self): return f'{self.pipeline_id} -> {self.message}'
class Solution: def search(self, nums, target): if not nums: return -1 x, y = 0, len(nums) - 1 while x <= y: m = x + (y - x) // 2 if nums[m] > nums[0]: x = m + 1 elif nums[m] < nums[0]: y = m else: x = y if nums[x] > nums[y] else y + 1 break print(x, y) if target > nums[0]: lo, hi = 0, x - 1 elif target < nums[0]: lo, hi = x, len(nums) - 1 else: return 0 print(lo, hi) while lo <= hi: m = lo + (hi - lo) // 2 if nums[m] == target: return m elif nums[m] > target: hi = m - 1 else: lo = m + 1 return -1 if __name__ == '__main__': ret1 = Solution().search(nums=[4, 5, 6, 7, 0, 1, 2], target=2) ret2 = Solution().search(nums=[1], target=1) ret3 = Solution().search(nums=[1, 3], target=1) ret4 = Solution().search(nums=[1, 3], target=3) ret5 = Solution().search(nums=[3, 1], target=1) print(ret1, ret2, ret3, ret4, ret5) ret = Solution().search(nums=[1, 3, 5], target=5) print(ret)
class Solution: def search(self, nums, target): if not nums: return -1 (x, y) = (0, len(nums) - 1) while x <= y: m = x + (y - x) // 2 if nums[m] > nums[0]: x = m + 1 elif nums[m] < nums[0]: y = m else: x = y if nums[x] > nums[y] else y + 1 break print(x, y) if target > nums[0]: (lo, hi) = (0, x - 1) elif target < nums[0]: (lo, hi) = (x, len(nums) - 1) else: return 0 print(lo, hi) while lo <= hi: m = lo + (hi - lo) // 2 if nums[m] == target: return m elif nums[m] > target: hi = m - 1 else: lo = m + 1 return -1 if __name__ == '__main__': ret1 = solution().search(nums=[4, 5, 6, 7, 0, 1, 2], target=2) ret2 = solution().search(nums=[1], target=1) ret3 = solution().search(nums=[1, 3], target=1) ret4 = solution().search(nums=[1, 3], target=3) ret5 = solution().search(nums=[3, 1], target=1) print(ret1, ret2, ret3, ret4, ret5) ret = solution().search(nums=[1, 3, 5], target=5) print(ret)
class Chapter: id: float title: str text: str
class Chapter: id: float title: str text: str
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def getKthFromEnd(self, head: ListNode, k: int) -> ListNode: p1 = head for _ in range(k): if p1: p1 = p1.next else: return None p2 = head while p1: p1 = p1.next p2 = p2.next return p2
class Solution: def get_kth_from_end(self, head: ListNode, k: int) -> ListNode: p1 = head for _ in range(k): if p1: p1 = p1.next else: return None p2 = head while p1: p1 = p1.next p2 = p2.next return p2
with open('input.txt') as f: lines = f.readlines() ans = 0 for line in lines: input, output = line.split(" | ") for word in output.split(): length = len(word) if length == 2 or length == 4 or length == 3 or length == 7: ans += 1 print(ans)
with open('input.txt') as f: lines = f.readlines() ans = 0 for line in lines: (input, output) = line.split(' | ') for word in output.split(): length = len(word) if length == 2 or length == 4 or length == 3 or (length == 7): ans += 1 print(ans)
def fibonacci_iterative(num): a = 0 b = 1 total = 0 for _ in range(2, num + 1): total = a + b a = b b = total return total def fibonacci_recursive(num): if num < 2: return num return fibonacci_recursive(num-1) + fibonacci_recursive(num-2) print(fibonacci_iterative(10)) print(fibonacci_recursive(10))
def fibonacci_iterative(num): a = 0 b = 1 total = 0 for _ in range(2, num + 1): total = a + b a = b b = total return total def fibonacci_recursive(num): if num < 2: return num return fibonacci_recursive(num - 1) + fibonacci_recursive(num - 2) print(fibonacci_iterative(10)) print(fibonacci_recursive(10))
data = { 'red' : 1, 'green' : 2, 'blue' : 3 } def makedict(**kwargs): return kwargs data = makedict(red=1, green=2, blue=3) print(data) def dodict(*args, **kwds): d = {} for k, v in args: d[k] = v d.update(kwds) return d tada = dodict(yellow=2, green=4, *data.items()) print(tada)
data = {'red': 1, 'green': 2, 'blue': 3} def makedict(**kwargs): return kwargs data = makedict(red=1, green=2, blue=3) print(data) def dodict(*args, **kwds): d = {} for (k, v) in args: d[k] = v d.update(kwds) return d tada = dodict(*data.items(), yellow=2, green=4) print(tada)
# A Narcissistic Number is a number which is the sum of its own digits, each raised to the power of the number # of digits in a given base. In this Kata, we will restrict ourselves to decimal (base 10). # For example, take 153 (3 digits): # 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153 # and 1634 (4 digits): # 1^4 + 6^4 + 3^4 + 4^4 = 1 + 1296 + 81 + 256 = 1634 # The Challenge: # Your code must return true or false depending upon whether the given number is a Narcissistic number in base 10. # Error checking for text strings or other invalid inputs is not required, only valid integers will be passed into the function. #https://www.codewars.com/kata/narcissistic-numbers/train/python def is_narcissistic(num): if 0: return False n = num exponente = len(str(num)) sum = 0 while n > 0: sum += pow(int(n % 10), exponente) n = int(n/10) return sum == num print (is_narcissistic(12)) print (is_narcissistic(153)) print (is_narcissistic(1634))
def is_narcissistic(num): if 0: return False n = num exponente = len(str(num)) sum = 0 while n > 0: sum += pow(int(n % 10), exponente) n = int(n / 10) return sum == num print(is_narcissistic(12)) print(is_narcissistic(153)) print(is_narcissistic(1634))
#!/usr/bin/python # -*- coding: UTF-8 -*- class Hello(object): def hello(self, name='world'): print('Hello, %s.' % name)
class Hello(object): def hello(self, name='world'): print('Hello, %s.' % name)
# Note that we can only test things here all implementations must support valid_data = [ ("acceptInsecureCerts", [ False, None, ]), ("browserName", [ None, ]), ("browserVersion", [ None, ]), ("platformName", [ None, ]), ("pageLoadStrategy", [ None, "none", "eager", "normal", ]), ("proxy", [ None, ]), ("timeouts", [ None, {}, {"script": 0, "pageLoad": 2.0, "implicit": 2**53 - 1}, {"script": 50, "pageLoad": 25}, {"script": 500}, ]), ("unhandledPromptBehavior", [ "dismiss", "accept", None, ]), ("test:extension", [ None, False, "abc", 123, [], {"key": "value"}, ]), ] invalid_data = [ ("acceptInsecureCerts", [ 1, [], {}, "false", ]), ("browserName", [ 1, [], {}, False, ]), ("browserVersion", [ 1, [], {}, False, ]), ("platformName", [ 1, [], {}, False, ]), ("pageLoadStrategy", [ 1, [], {}, False, "invalid", "NONE", "Eager", "eagerblah", "interactive", " eager", "eager "]), ("proxy", [ 1, [], "{}", {"proxyType": "SYSTEM"}, {"proxyType": "systemSomething"}, {"proxy type": "pac"}, {"proxy-Type": "system"}, {"proxy_type": "system"}, {"proxytype": "system"}, {"PROXYTYPE": "system"}, {"proxyType": None}, {"proxyType": 1}, {"proxyType": []}, {"proxyType": {"value": "system"}}, {" proxyType": "system"}, {"proxyType ": "system"}, {"proxyType ": " system"}, {"proxyType": "system "}, ]), ("timeouts", [ 1, [], "{}", False, {"invalid": 10}, {"PAGELOAD": 10}, {"page load": 10}, {" pageLoad": 10}, {"pageLoad ": 10}, {"pageLoad": None}, {"pageLoad": False}, {"pageLoad": []}, {"pageLoad": "10"}, {"pageLoad": 2.5}, {"pageLoad": -1}, {"pageLoad": 2**53}, {"pageLoad": {"value": 10}}, {"pageLoad": 10, "invalid": 10}, ]), ("unhandledPromptBehavior", [ 1, [], {}, False, "DISMISS", "dismissABC", "Accept", " dismiss", "dismiss ", ]) ] invalid_extensions = [ "firefox", "firefox_binary", "firefoxOptions", "chromeOptions", "automaticInspection", "automaticProfiling", "platform", "version", "browser", "platformVersion", "javascriptEnabled", "nativeEvents", "seleniumProtocol", "profile", "trustAllSSLCertificates", "initialBrowserUrl", "requireWindowFocus", "logFile", "logLevel", "safari.options", "ensureCleanSession", ]
valid_data = [('acceptInsecureCerts', [False, None]), ('browserName', [None]), ('browserVersion', [None]), ('platformName', [None]), ('pageLoadStrategy', [None, 'none', 'eager', 'normal']), ('proxy', [None]), ('timeouts', [None, {}, {'script': 0, 'pageLoad': 2.0, 'implicit': 2 ** 53 - 1}, {'script': 50, 'pageLoad': 25}, {'script': 500}]), ('unhandledPromptBehavior', ['dismiss', 'accept', None]), ('test:extension', [None, False, 'abc', 123, [], {'key': 'value'}])] invalid_data = [('acceptInsecureCerts', [1, [], {}, 'false']), ('browserName', [1, [], {}, False]), ('browserVersion', [1, [], {}, False]), ('platformName', [1, [], {}, False]), ('pageLoadStrategy', [1, [], {}, False, 'invalid', 'NONE', 'Eager', 'eagerblah', 'interactive', ' eager', 'eager ']), ('proxy', [1, [], '{}', {'proxyType': 'SYSTEM'}, {'proxyType': 'systemSomething'}, {'proxy type': 'pac'}, {'proxy-Type': 'system'}, {'proxy_type': 'system'}, {'proxytype': 'system'}, {'PROXYTYPE': 'system'}, {'proxyType': None}, {'proxyType': 1}, {'proxyType': []}, {'proxyType': {'value': 'system'}}, {' proxyType': 'system'}, {'proxyType ': 'system'}, {'proxyType ': ' system'}, {'proxyType': 'system '}]), ('timeouts', [1, [], '{}', False, {'invalid': 10}, {'PAGELOAD': 10}, {'page load': 10}, {' pageLoad': 10}, {'pageLoad ': 10}, {'pageLoad': None}, {'pageLoad': False}, {'pageLoad': []}, {'pageLoad': '10'}, {'pageLoad': 2.5}, {'pageLoad': -1}, {'pageLoad': 2 ** 53}, {'pageLoad': {'value': 10}}, {'pageLoad': 10, 'invalid': 10}]), ('unhandledPromptBehavior', [1, [], {}, False, 'DISMISS', 'dismissABC', 'Accept', ' dismiss', 'dismiss '])] invalid_extensions = ['firefox', 'firefox_binary', 'firefoxOptions', 'chromeOptions', 'automaticInspection', 'automaticProfiling', 'platform', 'version', 'browser', 'platformVersion', 'javascriptEnabled', 'nativeEvents', 'seleniumProtocol', 'profile', 'trustAllSSLCertificates', 'initialBrowserUrl', 'requireWindowFocus', 'logFile', 'logLevel', 'safari.options', 'ensureCleanSession']
class CodesDict(object): def __init__(self, codes): self.__dict__.update(codes) _codes = { 'waiting': 1, 'analysis': 2, 'paid': 3, 'available': 4, 'dispute': 5, 'returned': 6, 'canceled': 7, } codes = CodesDict(_codes)
class Codesdict(object): def __init__(self, codes): self.__dict__.update(codes) _codes = {'waiting': 1, 'analysis': 2, 'paid': 3, 'available': 4, 'dispute': 5, 'returned': 6, 'canceled': 7} codes = codes_dict(_codes)