content
stringlengths
7
1.05M
class Solution: def simplifyPath(self, path: str) -> str: stk = [] for p in path.split('/'): if p == '..': if stk: stk.pop() elif p and p != '.': stk.append(p) return '/' + '/'.join(stk)
class Fraction(object): def __init__(self, num, den): self.__num = num self.__den = den self.reduce() def __str__(self): return "%d/%d" % (self.__num, self.__den) def __invert__(self): return Fraction(self.__den,self.__num) def __neg__(self): return Fraction(-(self.__num), self.__den) def __pow__(self, pow): return Fraction(self.__num **pow,self.__den**pow) def __float__(self): return float(self.__num/self.__den) def __int__(self): return int(self.__num/self.__den) def reduce(self): g = Fraction.gcd(self.__num, self.__den) self.__num /= g self.__den /= g @staticmethod def gcd(n, m): if m == 0: return n else: return Fraction.gcd(m, n % m)
"""Configuration file for common models/experiments""" MAIN_PARAMS = { 'sent140': { 'small': (10, 2, 2), 'medium': (16, 2, 2), 'large': (24, 2, 2) }, 'femnist': { 'small': (30, 10, 2), 'medium': (100, 10, 2), 'large': (400, 20, 2) }, 'uni-femnist': { 'small': (30, 10, 2), 'medium': (100, 10, 2), 'large': (400, 20, 2) }, 'shakespeare': { 'small': (6, 2, 2), 'medium': (8, 2, 2), 'large': (20, 1, 2) }, 'celeba': { 'small': (30, 10, 2), 'medium': (100, 10, 2), 'large': (400, 20, 2) }, 'synthetic': { 'small': (6, 2, 2), 'medium': (8, 2, 2), 'large': (20, 1, 2) }, 'reddit': { 'small': (6, 2, 2), 'medium': (8, 2, 2), 'large': (20, 1, 2) }, } """dict: Specifies execution parameters (tot_num_rounds, eval_every_num_rounds, clients_per_round)""" MODEL_PARAMS = { 'sent140.bag_dnn': (0.0003, 2), # lr, num_classes 'sent140.stacked_lstm': (0.0003, 25, 2, 100), # lr, seq_len, num_classes, num_hidden 'sent140.bag_log_reg': (0.0003, 2), # lr, num_classes 'femnist.cnn': (0.0003, 62), # lr, num_classes 'shakespeare.stacked_lstm': (0.0003, 80, 80, 256), # lr, seq_len, num_classes, num_hidden 'celeba.cnn': (0.1, 2), # lr, num_classes 'synthetic.log_reg': (0.0003, 5, 60), # lr, num_classes, input_dim 'reddit.stacked_lstm': (0.0003, 10, 256, 2), # lr, seq_len, num_hidden, num_layers } """dict: Model specific parameter specification""" ACCURACY_KEY = 'accuracy' BYTES_WRITTEN_KEY = 'bytes_written' BYTES_READ_KEY = 'bytes_read' LOCAL_COMPUTATIONS_KEY = 'local_computations' NUM_ROUND_KEY = 'round_number' NUM_SAMPLES_KEY = 'num_samples' CLIENT_ID_KEY = 'client_id'
# filter1.py to get even numbers from a list def is_dublicate(item): return not(item in mylist) mylist = ["Orange","Apple", "Banana", "Peach", "Banana"] new_list = list(filter(is_dublicate, mylist)) print(new_list)
class strongly_connected_component(): def __init__(self, graph=None, visited=None): self.graph = dict() self.visited = dict() self.stack=list() def add_vertex(self, v, graph, visited): if not graph.get(v): graph[v] = [] visited[v]=0 def add_edge(self, v1, v2, e, graph = None): if v1 not in graph: print("Vertex ", v1, " does not exist.") elif v2 not in graph: print("Vertex ", v2, " does not exist.") else: temp = [v2, e] graph[v1].append(temp) def reverse_graph(self, original_graph, reverse_graph, rev_graph_visited): for key in original_graph.keys(): self.add_vertex(key, reverse_graph, rev_graph_visited) for src, value in original_graph.items(): for dest in value: self.add_edge(dest[0], src, dest[1], reverse_graph) def dfs_visit(self, v,visited): visited[v]=1 for edges in self.graph[v]: if self.visited[edges[0]]!=1: self.dfs_visit(edges[0],self.visited) self.stack.append(v) def scc_dfs(self,v, reverse_graph, reverse_visited, res): reverse_visited[v] = 1 res.append(v) for edges in reverse_graph[v]: if reverse_visited[edges[0]]!=1: self.scc_dfs(edges[0], reverse_graph ,reverse_visited, res) def dfs_main(self): for key, value in self.graph.items(): if self.visited[key] != 1: self.dfs_visit(key,self.visited) def strongly_connected_components_driver(self): reverse_graph = dict() reverse_graph_visited = dict() res = [] final = [] self.dfs_main() self.reverse_graph(self.graph, reverse_graph, reverse_graph_visited) while self.stack: vertex = self.stack.pop() if reverse_graph_visited[vertex] != 1: self.scc_dfs(vertex, reverse_graph, reverse_graph_visited, res) final.append(res) res = [] return final def scc_main(self, fileName='directedGraph1.txt'): sc = strongly_connected_component() fileLines = [] with open(fileName,'r') as graph_file: fileLines = graph_file.read().splitlines() graph_info = fileLines[0].split(' ') number_of_vertices = graph_info[0] number_of_edges = graph_info[1] for i in range(1, len(fileLines)-1): edge_info = fileLines[i].split(' ') vertex_src = edge_info[0] vertex_dest = edge_info[1] edge_weight = edge_info[2] sc.add_vertex(vertex_src, sc.graph, sc.visited) sc.add_vertex(vertex_dest, sc.graph, sc.visited) sc.add_edge(vertex_src, vertex_dest, int(edge_weight),sc.graph) print("The strong connected components are:", sc.strongly_connected_components_driver()) if __name__ == "__main__": menu = { 1: 'Directed Graph 1', 2: 'Directed Graph 2',3: 'Directed Graph 3',4: 'Directed Graph 4', 5: 'Exit'} d = strongly_connected_component() fileName = '' while True: print('--------------------------------------------------') for key, value in menu.items(): print(key,'-',value) select_option = '' try: select_option = int(input('Please select the graph to be used to get the strongly connected component: ')) except: print('Please input a number') if select_option == 1: fileName = 'scc_1.txt' d.scc_main(fileName) elif select_option == 2: fileName = 'scc_2.txt' d.scc_main(fileName) elif select_option == 3: fileName = 'scc_3.txt' d.scc_main(fileName) elif select_option == 4: fileName = 'scc_4.txt' d.scc_main(fileName) elif select_option == 5: break else: print('Please enter input from the menu options')
AVAILABLE_LANGUAGES = { "english": "en", "indonesian": "id", "czech": "cs", "german": "de", "spanish": "es-419", "french": "fr", "italian": "it", "latvian": "lv", "lithuanian": "lt", "hungarian": "hu", "dutch": "nl", "norwegian": "no", "polish": "pl", "portuguese brasil": "pt-419", "portuguese portugal": "pt-150", "romanian": "ro", "slovak": "sk", "slovenian": "sl", "swedish": "sv", "vietnamese": "vi", "turkish": "tr", "greek": "el", "bulgarian": "bg", "russian": "ru", "serbian": "sr", "ukrainian": "uk", "hebrew": "he", "arabic": "ar", "marathi": "mr", "hindi": "hi", "bengali": "bn", "tamil": "ta", "telugu": "te", "malyalam": "ml", "thai": "th", "chinese simplified": "zh-Hans", "chinese traditional": "zh-Hant", "japanese": "ja", "korean": "ko" } AVAILABLE_COUNTRIES = { "Australia": "AU", "Botswana": "BW", "Canada ": "CA", "Ethiopia": "ET", "Ghana": "GH", "India ": "IN", "Indonesia": "ID", "Ireland": "IE", "Israel ": "IL", "Kenya": "KE", "Latvia": "LV", "Malaysia": "MY", "Namibia": "NA", "New Zealand": "NZ", "Nigeria": "NG", "Pakistan": "PK", "Philippines": "PH", "Singapore": "SG", "South Africa": "ZA", "Tanzania": "TZ", "Uganda": "UG", "United Kingdom": "GB", "United States": "US", "Zimbabwe": "ZW", "Czech Republic": "CZ", "Germany": "DE", "Austria": "AT", "Switzerland": "CH", "Argentina": "AR", "Chile": "CL", "Colombia": "CO", "Cuba": "CU", "Mexico": "MX", "Peru": "PE", "Venezuela": "VE", "Belgium ": "BE", "France": "FR", "Morocco": "MA", "Senegal": "SN", "Italy": "IT", "Lithuania": "LT", "Hungary": "HU", "Netherlands": "NL", "Norway": "NO", "Poland": "PL", "Brazil": "BR", "Portugal": "PT", "Romania": "RO", "Slovakia": "SK", "Slovenia": "SI", "Sweden": "SE", "Vietnam": "VN", "Turkey": "TR", "Greece": "GR", "Bulgaria": "BG", "Russia": "RU", "Ukraine ": "UA", "Serbia": "RS", "United Arab Emirates": "AE", "Saudi Arabia": "SA", "Lebanon": "LB", "Egypt": "EG", "Bangladesh": "BD", "Thailand": "TH", "China": "CN", "Taiwan": "TW", "Hong Kong": "HK", "Japan": "JP", "Republic of Korea": "KR" }
sala = [] def AdicionarSala(cod_sala,lotacao): aux = [cod_sala,lotacao] sala.append(aux) print (" === Sala adicionada === ") def StatusOcupada(cod_sala): for s in sala: if (s[0] == cod_sala): s[1] = "Ocupada" return s return None def StatusLivre(cod_sala): for s in sala: if (s[0] == cod_sala): s[1] = "Ocupada" return s return None def BuscarSala(cod_sala): for s in sala: if (s[0] == cod_sala): print (s) return s return None def ListarSala(): global sala print (sala) return sala def RemoverSala(cod_sala): for s in sala: if (s[0] == cod_sala): sala.remove(s) print (" ==== Sala removida === ") return True return False def RemoverTodasSalas(): global sala sala = [] return sala def IniciarSala(): AdicionarSala(1,"livre") AdicionarSala(2,"ocupada")
""" Características: - Inverted a posição dos elementos de uma lista - Enquanto reverse() só funciona com listas, reversed() funciona com todos os iteráveis """ # Exemplo numeros = [6, 1, 8, 2] res = reversed(numeros) # Lista print(list(reversed(numeros))) # Tupla print(tuple(reversed(numeros))) # Conjunto (Set) print(set(reversed(numeros))) # OBS: Em sets, não definimos a ordem dos elementos print() # Inverter uma palavra print(''.join(list(reversed('Geek University')))) # Maneira mais fácil print('Geek University'[::-1])
""" All wgpu structs. """ # THIS CODE IS AUTOGENERATED - DO NOT EDIT # %% Structs (45) RequestAdapterOptions = {"power_preference": "GPUPowerPreference"} DeviceDescriptor = { "label": "str", "extensions": "GPUExtensionName-list", "limits": "GPULimits", } Limits = { "max_bind_groups": "GPUSize32", "max_dynamic_uniform_buffers_per_pipeline_layout": "GPUSize32", "max_dynamic_storage_buffers_per_pipeline_layout": "GPUSize32", "max_sampled_textures_per_shader_stage": "GPUSize32", "max_samplers_per_shader_stage": "GPUSize32", "max_storage_buffers_per_shader_stage": "GPUSize32", "max_storage_textures_per_shader_stage": "GPUSize32", "max_uniform_buffers_per_shader_stage": "GPUSize32", "max_uniform_buffer_binding_size": "GPUSize32", } BufferDescriptor = { "label": "str", "size": "int", "usage": "GPUBufferUsageFlags", "mapped_at_creation": "bool", } TextureDescriptor = { "label": "str", "size": "GPUExtent3D", "mip_level_count": "GPUIntegerCoordinate", "sample_count": "GPUSize32", "dimension": "GPUTextureDimension", "format": "GPUTextureFormat", "usage": "GPUTextureUsageFlags", } TextureViewDescriptor = { "label": "str", "format": "GPUTextureFormat", "dimension": "GPUTextureViewDimension", "aspect": "GPUTextureAspect", "base_mip_level": "GPUIntegerCoordinate", "mip_level_count": "GPUIntegerCoordinate", "base_array_layer": "GPUIntegerCoordinate", "array_layer_count": "GPUIntegerCoordinate", } SamplerDescriptor = { "label": "str", "address_mode_u": "GPUAddressMode", "address_mode_v": "GPUAddressMode", "address_mode_w": "GPUAddressMode", "mag_filter": "GPUFilterMode", "min_filter": "GPUFilterMode", "mipmap_filter": "GPUFilterMode", "lod_min_clamp": "float", "lod_max_clamp": "float", "compare": "GPUCompareFunction", } BindGroupLayoutDescriptor = {"label": "str", "entries": "GPUBindGroupLayoutEntry-list"} BindGroupLayoutEntry = { "binding": "GPUIndex32", "visibility": "GPUShaderStageFlags", "type": "GPUBindingType", "has_dynamic_offset": "bool", "min_buffer_binding_size": "int", "view_dimension": "GPUTextureViewDimension", "texture_component_type": "GPUTextureComponentType", "multisampled": "bool", "storage_texture_format": "GPUTextureFormat", } BindGroupDescriptor = { "label": "str", "layout": "GPUBindGroupLayout", "entries": "GPUBindGroupEntry-list", } BindGroupEntry = {"binding": "GPUIndex32", "resource": "GPUBindingResource"} BufferBinding = {"buffer": "GPUBuffer", "offset": "int", "size": "int"} PipelineLayoutDescriptor = { "label": "str", "bind_group_layouts": "GPUBindGroupLayout-list", } ShaderModuleDescriptor = {"label": "str", "code": "str", "source_map": "dict"} ProgrammableStageDescriptor = {"module": "GPUShaderModule", "entry_point": "str"} ComputePipelineDescriptor = { "label": "str", "layout": "GPUPipelineLayout", "compute_stage": "GPUProgrammableStageDescriptor", } RenderPipelineDescriptor = { "label": "str", "layout": "GPUPipelineLayout", "vertex_stage": "GPUProgrammableStageDescriptor", "fragment_stage": "GPUProgrammableStageDescriptor", "primitive_topology": "GPUPrimitiveTopology", "rasterization_state": "GPURasterizationStateDescriptor", "color_states": "GPUColorStateDescriptor-list", "depth_stencil_state": "GPUDepthStencilStateDescriptor", "vertex_state": "GPUVertexStateDescriptor", "sample_count": "GPUSize32", "sample_mask": "GPUSampleMask", "alpha_to_coverage_enabled": "bool", } RasterizationStateDescriptor = { "front_face": "GPUFrontFace", "cull_mode": "GPUCullMode", "depth_bias": "GPUDepthBias", "depth_bias_slope_scale": "float", "depth_bias_clamp": "float", } ColorStateDescriptor = { "format": "GPUTextureFormat", "alpha_blend": "GPUBlendDescriptor", "color_blend": "GPUBlendDescriptor", "write_mask": "GPUColorWriteFlags", } BlendDescriptor = { "src_factor": "GPUBlendFactor", "dst_factor": "GPUBlendFactor", "operation": "GPUBlendOperation", } DepthStencilStateDescriptor = { "format": "GPUTextureFormat", "depth_write_enabled": "bool", "depth_compare": "GPUCompareFunction", "stencil_front": "GPUStencilStateFaceDescriptor", "stencil_back": "GPUStencilStateFaceDescriptor", "stencil_read_mask": "GPUStencilValue", "stencil_write_mask": "GPUStencilValue", } StencilStateFaceDescriptor = { "compare": "GPUCompareFunction", "fail_op": "GPUStencilOperation", "depth_fail_op": "GPUStencilOperation", "pass_op": "GPUStencilOperation", } VertexStateDescriptor = { "index_format": "GPUIndexFormat", "vertex_buffers": "GPUVertexBufferLayoutDescriptor?-list", } VertexBufferLayoutDescriptor = { "array_stride": "int", "step_mode": "GPUInputStepMode", "attributes": "GPUVertexAttributeDescriptor-list", } VertexAttributeDescriptor = { "format": "GPUVertexFormat", "offset": "int", "shader_location": "GPUIndex32", } CommandBufferDescriptor = {"label": "str"} CommandEncoderDescriptor = {"label": "str"} TextureDataLayout = { "offset": "int", "bytes_per_row": "GPUSize32", "rows_per_image": "GPUSize32", } BufferCopyView = { "offset": "int", "bytes_per_row": "GPUSize32", "rows_per_image": "GPUSize32", "buffer": "GPUBuffer", } TextureCopyView = { "texture": "GPUTexture", "mip_level": "GPUIntegerCoordinate", "origin": "GPUOrigin3D", } ImageBitmapCopyView = {"image_bitmap": "array", "origin": "GPUOrigin2D"} ComputePassDescriptor = {"label": "str"} RenderPassDescriptor = { "label": "str", "color_attachments": "GPURenderPassColorAttachmentDescriptor-list", "depth_stencil_attachment": "GPURenderPassDepthStencilAttachmentDescriptor", "occlusion_query_set": "GPUQuerySet", } RenderPassColorAttachmentDescriptor = { "attachment": "GPUTextureView", "resolve_target": "GPUTextureView", "load_value": "GPULoadOp-or-GPUColor", "store_op": "GPUStoreOp", } RenderPassDepthStencilAttachmentDescriptor = { "attachment": "GPUTextureView", "depth_load_value": "GPULoadOp-or-float", "depth_store_op": "GPUStoreOp", "depth_read_only": "bool", "stencil_load_value": "GPULoadOp-or-GPUStencilValue", "stencil_store_op": "GPUStoreOp", "stencil_read_only": "bool", } RenderBundleDescriptor = {"label": "str"} RenderBundleEncoderDescriptor = { "label": "str", "color_formats": "GPUTextureFormat-list", "depth_stencil_format": "GPUTextureFormat", "sample_count": "GPUSize32", } FenceDescriptor = {"label": "str", "initial_value": "GPUFenceValue"} QuerySetDescriptor = { "label": "str", "type": "GPUQueryType", "count": "GPUSize32", "pipeline_statistics": "GPUPipelineStatisticName-list", } SwapChainDescriptor = { "label": "str", "device": "GPUDevice", "format": "GPUTextureFormat", "usage": "GPUTextureUsageFlags", } UncapturedErrorEventInit = {"error": "GPUError"} Color = {"r": "float", "g": "float", "b": "float", "a": "float"} Origin2D = {"x": "GPUIntegerCoordinate", "y": "GPUIntegerCoordinate"} Origin3D = { "x": "GPUIntegerCoordinate", "y": "GPUIntegerCoordinate", "z": "GPUIntegerCoordinate", } Extent3D = { "width": "GPUIntegerCoordinate", "height": "GPUIntegerCoordinate", "depth": "GPUIntegerCoordinate", }
class InvalidStateTransition(Exception): pass class State(object): def __init__(self, initial=False, **kwargs): self.initial = initial def __eq__(self, other): if isinstance(other, basestring): return self.name == other elif isinstance(other, State): return self.name == other.name else: return False def __ne__(self, other): return not self == other class Event(object): def __init__(self, **kwargs): self.to_state = kwargs.get('to_state', None) self.from_states = tuple() from_state_args = kwargs.get('from_states', tuple()) if isinstance(from_state_args, (tuple, list)): self.from_states = tuple(from_state_args) else: self.from_states = (from_state_args,)
__author__ = 'Aleksander Chrabaszcz' __all__ = ['config', 'parser', 'pyslate'] __version__ = '1.1'
""" Class to handle landmarkpoints template pt {"y":392,"x":311,"point":0,"state":"visible"} """ class l_point(object): def __init__(self, **kwargs): self.__x__ = kwargs['x'] self.__y__ = kwargs['y'] ''' self.__indx__ = kwargs['point'] if kwargs['state'] in 'visible': self.__vis__ = True else: self.__vis__ = False ''' def get_pt(self): return self.__x__, self.__y__ def index(self): return self.__indx__ def state(self): pass
H, W = map(int, input().split()) for _ in range(H): C = input() print(C) print(C)
class ResponseStatus: """Possible values for attendee's response status * NEEDS_ACTION - The attendee has not responded to the invitation. * DECLINED - The attendee has declined the invitation. * TENTATIVE - The attendee has tentatively accepted the invitation. * ACCEPTED - The attendee has accepted the invitation. """ NEEDS_ACTION = "needsAction" DECLINED = "declined" TENTATIVE = "tentative" ACCEPTED = "accepted" class Attendee: def __init__(self, email, display_name=None, comment=None, optional=None, is_resource=None, additional_guests=None, response_status=None): """Represents attendee of the event. :param email: the attendee's email address, if available. :param display_name: the attendee's name, if available :param comment: the attendee's response comment :param optional: whether this is an optional attendee. The default is False. :param is_resource: whether the attendee is a resource. Can only be set when the attendee is added to the event for the first time. Subsequent modifications are ignored. The default is False. :param additional_guests: number of additional guests. The default is 0. :param response_status: the attendee's response status. See :py:class:`~gcsa.attendee.ResponseStatus` """ self.email = email self.display_name = display_name self.comment = comment self.optional = optional self.is_resource = is_resource self.additional_guests = additional_guests self.response_status = response_status def __eq__(self, other): return isinstance(other, Attendee) \ and self.email == other.email \ and self.display_name == other.display_name \ and self.comment == other.comment \ and self.optional == other.optional \ and self.is_resource == other.is_resource \ and self.additional_guests == other.additional_guests \ and self.response_status == other.response_status
public_key = 28 # Store the discovered factors in this list factors = [] # Begin testing at 2 test_number = 2 # Loop through all numbers from 2 up until the public_key number while test_number < public_key: # If the public key divides exactly into the test_number, it is a factor if public_key % test_number == 0: factors.append(test_number) # Move on to the next number test_number += 1 # Print the result print(factors)
# -*- coding: utf-8 -*- """ The custom exception module Copyright 2017-2018, Leo Moll and Dominik Schlösser Licensed under MIT License """ class DatabaseCorrupted(RuntimeError): """This exception is raised when the database throws errors during update""" class DatabaseLost(RuntimeError): """This exception is raised when the connection to the database is lost during update""" class ExitRequested(Exception): """This exception is thrown if the addon is shut down by Kodi or by another same addon"""
# Display default_screen_width = 940 default_screen_height = 600 screen_width = default_screen_width screen_height = default_screen_height is_native = False max_tps = 16 board_width = 13 board_height = 9 theme = "neon" # neon/paper/football # Sound sound_volume = 0.1 sound_muted = False
class Funcionario: def __init__(self, nome): self.nome = nome def registrar_horas(self, horas): print(f"Horas registradas: {horas}") def mostrar_tarefas(self): print("Mostrando tarefas") class Caelum(Funcionario): def mostrar_tarefas(self): print("Mostrando tarefas do Caelum") def busca_cursos_do_mes(self, mes=None): print(f"Mostrando cursos do mês {mes}" if mes else "Mostrando cursos do mês") class Alura(Funcionario): # def mostrar_tarefas(self): # print("Mostrando tarefas da Alura") def busca_perguntas_sem_resposta(self): print("Mostrando perguntas não respondidas do fórum") class Hipster: def __str__(self): return f"Hipster, {self.nome}" class Junior(Alura): pass class Pleno(Alura, Caelum): pass class Senior(Caelum, Alura, Hipster): pass luan = Senior("Luan") print(luan) # # MRO # # Pleno > Alura > Funcionario > Caelum > Funcionario # Mixins, classes pequenas que é utilizado apenas para herança
# -*- coding: utf-8 -*- """ Functions for navigating trees represented as embedded dictionaries. """ __author__ = "Julian Jara-Ettinger" __license__ = "MIT" def BuildKeyList(Dictionary): """ WARNING: This function is for internal use. Return a list of lists where each inner list is chain of valid keys which when input access the dictionary tree and retrieve a numerical sample. """ if isinstance(Dictionary, dict): Result = [] for Key in Dictionary.keys(): List = BuildKeyList(Dictionary[Key]) List = [[Key] + x for x in List] Result = Result + List return Result else: return [[]] def NormalizeDictionary(Dictionary, Constant): """ WARNING: This function is for internal use. Divide all leaf values by a constant. """ if isinstance(Dictionary, dict): for key in Dictionary.keys(): Dictionary[key] = NormalizeDictionary(Dictionary[key], Constant) return Dictionary else: return Dictionary * 1.0 / Constant def RetrieveValue(Dictionary, IndexPath): """ WARNING: This function is for internal use. Enter dictionary recursively using IndexPath and return leaf value. """ if IndexPath == []: return Dictionary else: return RetrieveValue(Dictionary[IndexPath[0]], IndexPath[1:]) def RecursiveDictionaryExtraction(Dictionary): """ WARNING: This function is for internal use. This function goes into a tree structures as embedded dictionaries and returns the sum of all the leaves """ if isinstance(Dictionary, dict): Values = [RecursiveDictionaryExtraction( Dictionary[x]) for x in Dictionary.keys()] return sum(Values) else: return Dictionary
MIN_SIZE = 13 # coding: utf-8 class Reporter(object): def __init__(self): self.cnt = 0 self.cliques = [] def inc_count(self): self.cnt += 1 def record(self, clique): self.cliques.append(clique) def print_report(self): print ('%d recursive calls' % self.cnt) for i, clique in enumerate(self.cliques): print ('%d: %s' % (i, clique)) print() def get_cliques(self): return self.cliques def bronker_bosch2(clique, candidates, excluded, reporter, NEIGHBORS): '''Bron–Kerbosch algorithm with pivot''' reporter.inc_count() if not candidates and not excluded: if len(clique) >= MIN_SIZE: reporter.record(clique) return pivot = pick_random(candidates) or pick_random(excluded) for v in list(candidates.difference(NEIGHBORS[pivot])): new_candidates = candidates.intersection(NEIGHBORS[v]) new_excluded = excluded.intersection(NEIGHBORS[v]) bronker_bosch2(clique + [v], new_candidates, new_excluded, reporter, NEIGHBORS) candidates.remove(v) excluded.add(v) def pick_random(s): if s: elem = s.pop() s.add(elem) return elem # NEIGHBORS = [ # [], # I want to start index from 1 instead of 0 # [2,3,7], # [1,3,4,6,7], # [1,2,8], # [2,6,5,8], # [4,6], # [2,4,5], # [1,2], # [3,4], # [8] # ] # NODES = set(range(1, len(NEIGHBORS))) # report = Reporter() # bronker_bosch2([], set(NODES), set(), report) # report.print_report()
fib = [1, 1] for i in range(2, 11): fib.append(fib[i - 1] + fib[i - 2]) def c2f(c): n = ord(c) b = '' for i in range(10, -1, -1): if n >= fib[i]: n -= fib[i] b += '1' else: b += '0' return b ALPHABET = [chr(i) for i in range(33,126)] print(ALPHABET) flag = ['10000100100','10010000010','10010001010','10000100100','10010010010','10001000000','10100000000','10000100010','00101010000','10010010000','00101001010','10000101000','10000010010','00101010000','10010000000','10000101000','10000010010','10001000000','00101000100','10000100010','10010000100','00010101010','00101000100','00101000100','00101001010','10000101000','10100000100','00000100100'] flagd = '' while(len(flagd) <= len(flag)): for i in flag: for c in ALPHABET: if c2f(c) == i: flagd += c print(c) break; break; print(flagd)
# -*- coding: utf-8 -*- __version__ = "20.4.1a" __author__ = "Taro Sato" __author_email__ = "[email protected]" __license__ = "MIT"
# represents the format of the string (see http://docs.python.org/library/datetime.html#strftime-strptime-behavior) # format symbol "z" doesn't wok sometimes, maybe you will need to change csv2youtrack.to_unix_date(time_string) DATE_FORMAT_STRING = "" FIELD_NAMES = { "Project" : "project", "Summary" : "summary", "Reporter" : "reporterName", "Created" : "created", "Updated" : "updated", "Description" : "description" } FIELD_TYPES = { "Fix versions" : "version[*]", "State" : "state[1]", "Assignee" : "user[1]", "Affected versions" : "version[*]", "Fixed in build" : "build[1]", "Priority" : "enum[1]", "Subsystem" : "ownedField[1]", "Browser" : "enum[1]", "OS" : "enum[1]", "Verified in build" : "build[1]", "Verified by" : "user[1]", "Affected builds" : "build[*]", "Fixed in builds" : "build[*]", "Reviewed by" : "user[1]", "Story points" : "integer", "Value" : "integer", "Marketing value" : "integer" } CONVERSION = {} CSV_DELIMITER = ","
# -*- coding: utf-8 -*- # @Author: jerry # @Date: 2017-09-09 21:15:54 # @Last Modified by: jerry # @Last Modified time: 2017-09-09 21:21:08 '''[你想封装类的实例上面的“私有”数据,但是Python语言并没有访问控制。] [解决方案] Python程序员不去依赖语言特性去封装数据,而是通过遵循一定的属性和方法命名规约来达到这个效果。 第一个约定是任何以单下划线_开头的名字都应该是内部实现。 ''' class A: def __init__(self): self._internal = 0 # An internal attribute self.public = 1 # A public attribute def public_method(self): ''' [A public method] ''' pass def _internal_method(self): pass
#variables vetor = [] #input for(i) in range(0, 10): num = int(input("Digite um número para o vetor {0}/10: ".format(i + 1))) vetor.append(num) vetor.reverse() #inverte a ordem for(i) in (vetor): print(i)
# taken from: http://pjreddie.com/projects/mnist-in-csv/ # convert reads the binary data and outputs a csv file def convert(image_file_path, label_file_path, csv_file_path, n): # open files images_file = open(image_file_path, "rb") labels_file = open(label_file_path, "rb") csv_file = open(csv_file_path, "w") # read some kind of header images_file.read(16) labels_file.read(8) # prepare array images = [] # read images and labels for _ in range(n): image = [] for _ in range(28*28): image.append(ord(images_file.read(1))) image.append(ord(labels_file.read(1))) images.append(image) # write csv rows for image in images: csv_file.write(",".join(str(pix) for pix in image)+"\n") # close files images_file.close() csv_file.close() labels_file.close() # convert train data set convert( "train-images-idx3-ubyte", "train-labels-idx1-ubyte", "train.csv", 60000 ) # convert test data set convert( "t10k-images-idx3-ubyte", "t10k-labels-idx1-ubyte", "test.csv", 10000 )
# SPDX-License-Identifier: MIT # Source: https://github.com/microsoft/MaskFlownet/tree/5cba12772e2201f0d1c1e27161d224e585334571 class Reader: def __init__(self, obj, full_attr=""): self._object = obj self._full_attr = full_attr def __getattr__(self, name): if self._object is None: ret = None else: ret = self._object.get(name, None) return Reader(ret, self._full_attr + '.' + name) def get(self, default=None): if self._object is None: print('Default FLAGS.{} to {}'.format(self._full_attr, default)) return default else: return self._object @property def value(self): return self._object
""" Relaxation methods ------------------ The multigrid cycle is formed by two complementary procedures: relaxation and coarse-grid correction. The role of relaxation is to rapidly damp oscillatory (high-frequency) errors out of the approximate solution. When the error is smooth, it can then be accurately represented on the coarser grid, where a solution, or approximate solution, can be computed. Iterative methods for linear systems that have an error smoothing property are valid relaxation methods. Since the purpose of a relaxation method is to smooth oscillatory errors, its effectiveness on non-oscillatory errors is not important. This point explains why simple iterative methods like Gauss-Seidel iteration are effective relaxation methods while being very slow to converge to the solution of Ax=b. PyAMG implements relaxation methods of the following varieties: 1. Jacobi iteration 2. Gauss-Seidel iteration 3. Successive Over-Relaxation 4. Polynomial smoothing (e.g. Chebyshev) 5. Jacobi and Gauss-Seidel on the normal equations (A.H A and A A.H) 6. Krylov methods: gmres, cg, cgnr, cgne 7. No pre- or postsmoother Refer to the docstrings of the individual methods for additional information. """ __docformat__ = "restructuredtext en" # TODO: explain separation of basic methods from interface methods. # TODO: explain why each class of methods exist # (parallel vs. serial, SPD vs. indefinite) postpone_import = 1
taboada = int(input('Qual taboada você quer ver? ')) contador = 0 continuar = '' while True: if taboada < 0: print('Não imprimimos taboada com números negativos!') break if contador != 10: contador += 1 print(f'{taboada} x {contador} = {taboada * contador}') if contador == 10: contador = 0 if continuar != 0: continuar = int(input('Digite "0" para sair ou outro número para imprimir a taboada: ')) taboada = 0 taboada = continuar if continuar == 0: break print('Fim') #print(f'{taboada} x {contador} = {taboada * contador}')
# Copyright 2016 The LUCI Authors. All rights reserved. # Use of this source code is governed under the Apache License, Version 2.0 # that can be found in the LICENSE file. class InitializationError(Exception): """Raised by RemoteClient.initialize on fatal errors.""" def __init__(self, last_error): super(InitializationError, self).__init__('Failed to grab auth headers') self.last_error = last_error class BotCodeError(Exception): """Raised by RemoteClient.get_bot_code.""" def __init__(self, new_zip, url, version): super(BotCodeError, self).__init__('Unable to download %s from %s; first tried version %s' % (new_zip, url, version)) class InternalError(Exception): """Raised on unrecoverable errors that abort task with 'internal error'.""" class PollError(Exception): """Raised on unrecoverable errors in RemoteClient.poll.""" class MintTokenError(Exception): """Raised on unrecoverable errors in RemoteClient.mint_*_token."""
numeros = ("zero","um","dois","três","quatro","cinco","seis","sete","oito","nove") busca = int(input("Digite um número: ")) print(numeros[busca])
"""Special Pythagorean triplet A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a^2 + b^2 = c^2 For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc. """ def is_pythagorean_triplet(a, b, c): """Determine whether the provided numbers are a Pythagorean triplet. Arguments: a, b, c (int): Three integers. Returns: Boolean: True is the provided numbers are a Pythagorean triplet, False otherwise. """ return (a < b < c) and (a**2 + b**2 == c**2) def pair_sums(total, least): """Find all pairs which add up to the provided sum. Arguments: total (int): Number to which returned pairs must sum. least (int): The smallest integer which may be part of a returned pair. Returns: set of tuples: Containing pairs of integers adding up to the given sum. """ pairs = set() for i in range(least, total - least): pair = [i, total - i] pair.sort() pairs |= set([tuple(pair)]) return pairs def find_triplet_product(total): """Find a Pythagorean triplet adding up to the provided sum. Arguments: total (int): An integer to which a triplet must sum. Returns: tuple of list and int: First Pythagorean triplet found and its product. None: If no Pythagorean triplet summing to the provided total exists. """ triplets = [] for i in range(1, total): pairs = pair_sums(total - i, i) for pair in pairs: triplet = [i] triplet += pair triplets.append(triplet) for triplet in triplets: a, b, c = triplet if is_pythagorean_triplet(a, b, c): return triplet, a * b * c
""" Python program to check whether given tree is binary search tree(BST) or not [BST details - https://en.wikipedia.org/wiki/Binary_search_tree] """ class Node: # Create node for binary tree def __init__(self, v): self.value = v self.left = None self.right = None def inorder_traversal(node, arr): if node is None: return None inorder_traversal(node.left, arr) arr.append(node.value) inorder_traversal(node.right, arr) def is_bst(node): """ return true if given tree is a valid bst else return false """ arr = list() inorder_traversal(node, arr) # check if inorder traversal of tree is sorted i.e. strictly increasing for i in range(1, len(arr)): if arr[i] <= arr[i - 1]: return False return True if __name__ == "__main__": """ Creating Tree 4 / \ 2 5 / \ 1 3 """ root = Node(4) root.left = Node(2) root.right = Node(5) root.left.left = Node(1) root.left.right = Node(3) print(is_bst(root)) # Output: True
# Write your solution for 1.4 here! def is_prime(x): # mod = x for i in range(x-1, 1, -1): if x % i == 0 : return False return True # else: # return True # is_prime(8) print(is_prime(5191))
#!/usr/bin/env python # Copyright 2020 The Kubernetes Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. def define_env(env): """Hook function""" @env.macro def kops_feature_table(**kwargs): """ Generate a markdown table which will be rendered when called, along with the supported passed keyword args. :param kwargs: kops_added_ff => Kops version in which this feature was added as a feature flag kops_added_default => Kops version in which this feature was introduced as stable k8s_min => Minimum k8s version which supports this feature :return: rendered markdown table """ # this dict object maps the kwarg to its description, which will be used in the final table supported_args = { 'kops_added_ff': 'Alpha (Feature Flag)', 'kops_added_default': 'Default', 'k8s_min': 'Minimum K8s Version' } # Create the initial strings to which we'll concatenate the relevant columns title = '|' separators = '|' values = '|' # Iterate over provided supported kwargs and match them with the provided values. for arg, header in supported_args.items(): if arg not in kwargs.keys(): continue if arg == 'kops_added_default' and 'kops_added_ff' not in kwargs.keys(): title += ' Introduced |' else: title += f' {header} |' separators += ' :-: |' if arg == 'k8s_min': values += f' K8s {kwargs[arg]} |' else: values += f' Kops {kwargs[arg]} |' # Create a list object containing all the table rows, # Then return a string object which contains every list item in a new line. table = [ title, separators, values ] return '\n'.join(table) def main(): pass if __name__ == "__main__": main()
class CurveLoopIterator(object,IEnumerator[Curve],IDisposable,IEnumerator): """ An iterator to a curve loop. """ def Dispose(self): """ Dispose(self: CurveLoopIterator) """ pass def MoveNext(self): """ MoveNext(self: CurveLoopIterator) -> bool Increments the iterator to the next item. Returns: True if there is a next available item in this iterator. False if the iterator has completed all available items. """ pass def next(self,*args): """ next(self: object) -> object """ pass def ReleaseUnmanagedResources(self,*args): """ ReleaseUnmanagedResources(self: CurveLoopIterator,disposing: bool) """ pass def Reset(self): """ Reset(self: CurveLoopIterator) Resets the iterator to the initial state. """ pass def __contains__(self,*args): """ __contains__[Curve](enumerator: IEnumerator[Curve],value: Curve) -> bool """ pass def __enter__(self,*args): """ __enter__(self: IDisposable) -> object """ pass def __exit__(self,*args): """ __exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: object) """ pass def __init__(self,*args): """ x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """ pass def __iter__(self,*args): """ __iter__(self: IEnumerator) -> object """ pass def __repr__(self,*args): """ __repr__(self: object) -> str """ pass Current=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets the item at the current position of the iterator. Get: Current(self: CurveLoopIterator) -> Curve """ IsValidObject=property(lambda self: object(),lambda self,v: None,lambda self: None) """Specifies whether the .NET object represents a valid Revit entity. Get: IsValidObject(self: CurveLoopIterator) -> bool """
#!/usr/bin/env python3 # https://codeforces.com/problemset/problem/913/A # 求m%(2**n), 问题是n,m都很大.. # 用bit运算?? mask?? # n很大,直接算肯定会溢出,所以要利用数学属性? # 如果n足够大, 答案就是m # 如果n不够大, 就可以用对m的位运算? # https://codeforces.com/blog/entry/56992 # 敢于尝试/落实最简单的方案 n = int(input()) #1e8 m = int(input()) #1e8 print(m if n>=27 else m%(2**n))
class InternalServerError(Exception): pass class SchemaValidationError(Exception): pass class EmailAlreadyExistsError(Exception): pass class UnauthorizedError(Exception): pass class NoAuthorizationError(Exception): pass class UpdatingUserError(Exception): pass class DeletingUserError(Exception): pass class UserNotExistsError(Exception): pass errors = { "InternalServerError": { "message": "Something went wrong", "status": 500 }, "SchemaValidationError": { "message": "Request is missing required fields", "status": 400 }, "EmailAlreadyExistsError": { "message": "User with given email address already exists", "status": 400 }, "UnauthorizedError": { "message": "Invalid username or password", "status": 401 }, "NoAuthorizationError": { "message": "Missing Authorization Header", "status": 401 }, "UpdatingUserError": { "message": "Updating user added by other is forbidden", "status": 403 }, "DeletingUserError": { "message": "Deleting user added by other is forbidden", "status": 403 }, "UserNotExistsError": { "message": "User with given id doesn't exists", "status": 400 } }
"""This rule gathers all .proto files used by all of its dependencies. The entire dependency tree is searched. The search crosses through cc_library rules and portable_proto_library rules to collect the transitive set of all .proto dependencies. This is provided to other rules in the form of a "proto" provider, using the transitive_sources field. This rule uses aspects. For general information on the concept, see: - go/bazel-aspects-ides-tools - go/bazel-aspects The basic rule is transitive_protos. Example: proto_library( name = "a_proto_library", srcs = ["a.proto], ) proto_library( name = "b_proto_library", srcs = ["b.proto], ) cc_library( name = "a_cc_library", deps = ["b_proto_library], ) transitive_protos( name = "all_my_protos", deps = [ "a_proto_library", "a_cc_library", ], ) all_my_protos will gather all proto files used in its dependency tree; in this case, ["a.proto", "b.proto"]. These are provided as the default outputs of this rule, so you can place the rule in any context that requires a list of files, and also as a "proto" provider, for use by any rules that would normally depend on proto_library. The dependency tree is explored using an aspect, transitive_protos_aspect. This aspect propagates across two attributes, "deps" and "hdrs". The latter is used for compatibility with portable_proto_library; see comments below and in that file for more details. At each visited node in the tree, the aspect collects protos: - direct_sources from the proto provider in the current node. This is filled in by proto_library nodes, and also by piggyback_header nodes (see portable_proto_build_defs.bzl). - protos from the transitive_protos provider in dependency nodes, found from both the "deps" and the "hdrs" aspect. Then it puts all the protos in the protos field of the transitive_protos provider which it generates. This is how each node sends its gathered protos up the tree. """ def _gather_transitive_protos_deps(deps, my_protos = [], my_descriptors = [], my_proto_libs = []): useful_deps = [dep for dep in deps if hasattr(dep, "transitive_protos")] protos = depset( my_protos, transitive = [dep.transitive_protos.protos for dep in useful_deps], ) proto_libs = depset( my_proto_libs, transitive = [dep.transitive_protos.proto_libs for dep in useful_deps], ) descriptors = depset( my_descriptors, transitive = [dep.transitive_protos.descriptors for dep in useful_deps], ) return struct( transitive_protos = struct( protos = protos, descriptors = descriptors, proto_libs = proto_libs, ), ) def _transitive_protos_aspect_impl(target, ctx): """Implementation of the transitive_protos_aspect aspect. Args: target: The current target. ctx: The current rule context. Returns: A transitive_protos provider. """ protos = target.proto.direct_sources if hasattr(target, "proto") else [] deps = ctx.rule.attr.deps[:] if hasattr(ctx.rule.attr, "deps") else [] descriptors = [target.proto.direct_descriptor_set] if hasattr(target, "proto") and hasattr(target.proto, "direct_descriptor_set") else [] proto_libs = [] if ctx.rule.kind == "proto_library": proto_libs = [f for f in target.files.to_list() if f.extension == "a"] # Searching through the hdrs attribute is necessary because of # portable_proto_library. In portable mode, that macro # generates a cc_library that does not depend on any proto_libraries, so # the .proto files do not appear in its dependency tree. # portable_proto_library cannot add arbitrary providers or attributes to # a cc_library rule, so instead it piggybacks the provider on a rule that # generates a header, which occurs in the hdrs attribute of the cc_library. if hasattr(ctx.rule.attr, "hdrs"): deps += ctx.rule.attr.hdrs result = _gather_transitive_protos_deps(deps, protos, descriptors, proto_libs) return result transitive_protos_aspect = aspect( implementation = _transitive_protos_aspect_impl, attr_aspects = ["deps", "hdrs"], attrs = {}, ) def _transitive_protos_impl(ctx): """Implementation of transitive_protos rule. Args: ctx: The rule context. Returns: A proto provider (with transitive_sources and transitive_descriptor_sets filled in), and marks all transitive sources as default output. """ gathered = _gather_transitive_protos_deps(ctx.attr.deps) protos = gathered.transitive_protos.protos descriptors = gathered.transitive_protos.descriptors return struct( proto = struct( transitive_sources = protos, transitive_descriptor_sets = descriptors, ), files = depset(protos), ) transitive_protos = rule( implementation = _transitive_protos_impl, attrs = { "deps": attr.label_list( aspects = [transitive_protos_aspect], ), }, ) def _transitive_proto_cc_libs_impl(ctx): """Implementation of transitive_proto_cc_libs rule. NOTE: this only works on Bazel, not exobazel. Args: ctx: The rule context. Returns: All transitive proto C++ .a files as default output. """ gathered = _gather_transitive_protos_deps(ctx.attr.deps) proto_libs = gathered.transitive_protos.proto_libs return struct( files = proto_libs, ) transitive_proto_cc_libs = rule( implementation = _transitive_proto_cc_libs_impl, attrs = { "deps": attr.label_list( aspects = [transitive_protos_aspect], ), }, ) def _transitive_proto_descriptor_sets_impl(ctx): """Implementation of transitive_proto_descriptor_sets rule. Args: ctx: The rule context. Returns: All transitive proto descriptor files as default output. """ gathered = _gather_transitive_protos_deps(ctx.attr.deps) descriptors = gathered.transitive_protos.descriptors return struct( files = descriptors, ) transitive_proto_descriptor_sets = rule( implementation = _transitive_proto_descriptor_sets_impl, attrs = { "deps": attr.label_list( aspects = [transitive_protos_aspect], ), }, )
# # PySNMP MIB module DELL-NETWORKING-COPY-CONFIG-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DELL-NETWORKING-COPY-CONFIG-MIB # Produced by pysmi-0.3.4 at Wed May 1 12:37:52 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsUnion, ValueRangeConstraint, SingleValueConstraint, ValueSizeConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "ValueRangeConstraint", "SingleValueConstraint", "ValueSizeConstraint", "ConstraintsIntersection") dellNetMgmt, = mibBuilder.importSymbols("DELL-NETWORKING-SMI", "dellNetMgmt") InetAddress, InetAddressType = mibBuilder.importSymbols("INET-ADDRESS-MIB", "InetAddress", "InetAddressType") ModuleCompliance, NotificationGroup, ObjectGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup", "ObjectGroup") NotificationType, Integer32, MibScalar, MibTable, MibTableRow, MibTableColumn, MibIdentifier, Bits, Counter32, ObjectIdentity, Counter64, ModuleIdentity, Gauge32, Unsigned32, IpAddress, iso, TimeTicks = mibBuilder.importSymbols("SNMPv2-SMI", "NotificationType", "Integer32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "MibIdentifier", "Bits", "Counter32", "ObjectIdentity", "Counter64", "ModuleIdentity", "Gauge32", "Unsigned32", "IpAddress", "iso", "TimeTicks") RowStatus, DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "RowStatus", "DisplayString", "TextualConvention") dellNetCopyConfigMib = ModuleIdentity((1, 3, 6, 1, 4, 1, 6027, 3, 5)) dellNetCopyConfigMib.setRevisions(('2009-05-14 13:00', '2007-06-19 12:00', '2003-03-01 12:00',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: dellNetCopyConfigMib.setRevisionsDescriptions(('Added New enum for usbflash filesystem in Exascale', 'Update description to copy from remote server to local', 'Initial Revision',)) if mibBuilder.loadTexts: dellNetCopyConfigMib.setLastUpdated('200905141300Z') if mibBuilder.loadTexts: dellNetCopyConfigMib.setOrganization('Dell Inc.') if mibBuilder.loadTexts: dellNetCopyConfigMib.setContactInfo('http://www.dell.com/support') if mibBuilder.loadTexts: dellNetCopyConfigMib.setDescription('Dell Networking OS Copy Config MIB provides copying of running-config to to startup-config and vice-versa, and Dell Networking OS files to local disk or other system via ftp or tftp. ') dellNetCopyConfigObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 6027, 3, 5, 1)) dellNetCopyConfig = MibIdentifier((1, 3, 6, 1, 4, 1, 6027, 3, 5, 1, 1)) dellNetCopyConfigTraps = MibIdentifier((1, 3, 6, 1, 4, 1, 6027, 3, 5, 1, 2)) class DellNetConfigFileLocation(Integer32): subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7)) namedValues = NamedValues(("flash", 1), ("slot0", 2), ("tftp", 3), ("ftp", 4), ("scp", 5), ("usbflash", 6), ("nfsmount", 7)) class DellNetConfigFileType(Integer32): subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3)) namedValues = NamedValues(("dellNetFile", 1), ("runningConfig", 2), ("startupConfig", 3)) class DellNetConfigCopyState(Integer32): subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3)) namedValues = NamedValues(("running", 1), ("successful", 2), ("failed", 3)) class DellNetConfigCopyFailCause(Integer32): subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7)) namedValues = NamedValues(("badFileName", 1), ("copyInProgress", 2), ("diskFull", 3), ("fileExist", 4), ("fileNotFound", 5), ("timeout", 6), ("unknown", 7)) dellNetCopyTable = MibTable((1, 3, 6, 1, 4, 1, 6027, 3, 5, 1, 1, 1), ) if mibBuilder.loadTexts: dellNetCopyTable.setStatus('current') if mibBuilder.loadTexts: dellNetCopyTable.setDescription('A table of config-copy requests.') dellNetCopyEntry = MibTableRow((1, 3, 6, 1, 4, 1, 6027, 3, 5, 1, 1, 1, 1), ).setIndexNames((0, "DELL-NETWORKING-COPY-CONFIG-MIB", "copyConfigIndex")) if mibBuilder.loadTexts: dellNetCopyEntry.setStatus('current') if mibBuilder.loadTexts: dellNetCopyEntry.setDescription('A config-copy request. To use this copy on NMS, user must first query the MIB. if the query returns the result of the previous copied and there is no pending copy operation, user can submit a SNMP SET with a random number as index with the appropraite information as specified by this MIB and the row status as CreateAndGo. The system will only keep the last 5 copy requests as the history. If there are ten entries in the copy request table, the subsequent copy request will replace the existing one in the copy table. 1) To copy running-config from local directory to startup-config. Set the following mib objects in the copy table copySrcFileType : runningConfig (2) copyDestFileType : startupConfig (3) 2) To copy startup-config from local directory to a remote site. Set the following mib objects in the copy table copySrcFileType : startupConfig (3) copyDestFileType : dellNetFile (1) copyDestFileLocation : ftp (4) copyDestFileName : /user/tester1/ftp/ copyServerAddress : 172.20.10.123 copyUserName : tester1 copyUserPassword : mypasswd 3) To copy a file from local directory to a remote site. Set the following mib objects in the copy table copySrcFileType : dellNetFile (1) copySrcFileLocation : slot0 (2) copySrcFileName : NVTRACE_LOG_DIR/LP4-nvtrace-0 copyDestFileType : dellNetFile (1) copyDestFileLocation : ftp (4) copyDestFileName : /usr/tester1/trace/backup/LP4-nvtrace-0 copyServerAddress : 172.20.10.123 copyUserName : tester1 copyUserPassword : mypasswd ') copyConfigIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 5, 1, 1, 1, 1, 1), Integer32()) if mibBuilder.loadTexts: copyConfigIndex.setStatus('current') if mibBuilder.loadTexts: copyConfigIndex.setDescription('To initiate a config copy request, user should assign a positive random value as an index. ') copySrcFileType = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 5, 1, 1, 1, 1, 2), DellNetConfigFileType()).setMaxAccess("readwrite") if mibBuilder.loadTexts: copySrcFileType.setStatus('current') if mibBuilder.loadTexts: copySrcFileType.setDescription('Specifies the type of file to copy from. if the copySrcFileType is runningConfig(2) or startupConfig(3), the default DellNetConfigFileLocation is flash(1). If the copySrcFileType has the value of dellNetFile(1), it is expected that the copySrcFileLocation and copySrcFileName must also be spcified. The three objects together will uniquely identify the source file. ') copySrcFileLocation = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 5, 1, 1, 1, 1, 3), DellNetConfigFileLocation()).setMaxAccess("readwrite") if mibBuilder.loadTexts: copySrcFileLocation.setStatus('current') if mibBuilder.loadTexts: copySrcFileLocation.setDescription('Specifies the location of source file. If the copySrcFileType has the value of dellNetFile(1), it is expected that the copySrcFileType and copySrcFileName must also be spcified. The three objects together will uniquely identify the source file. If the copySrcFileLocation has the value of ftp(4) or scp(5), it is expected the login information liked copyServerAddress, copyUserName, and copyUserPassword also be spcified. ') copySrcFileName = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 5, 1, 1, 1, 1, 4), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: copySrcFileName.setStatus('current') if mibBuilder.loadTexts: copySrcFileName.setDescription('The file name (including the path, if applicable) of the file. If copySourceFileType is set to runningConfig or startupConfig, copySrcFileName is not needed. ') copyDestFileType = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 5, 1, 1, 1, 1, 5), DellNetConfigFileType()).setMaxAccess("readwrite") if mibBuilder.loadTexts: copyDestFileType.setStatus('current') if mibBuilder.loadTexts: copyDestFileType.setDescription('Specifies the type of file to copy to. if the copyDestFileType is runningConfig(2) or startupConfig(3), the default dellNetDestFileLocation is flash(1). If the copyDestFileType has the value of dellNetFile(1), it is expected that the copyDestFileLocation and copyDestFileName must also be spcified. The three objects together will uniquely identify the destination file. ') copyDestFileLocation = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 5, 1, 1, 1, 1, 6), DellNetConfigFileLocation()).setMaxAccess("readwrite") if mibBuilder.loadTexts: copyDestFileLocation.setStatus('current') if mibBuilder.loadTexts: copyDestFileLocation.setDescription('Specifies the location of destination file. If the copyDestFileType has the value of dellNetFile(1), it is expected that the copyDestFileType and copyDestFileName must also be spcified. The three objects together will uniquely identify the destination file. If the copyDestFileLocation has the value of ftp(4) or scp(5), it is expected the login information liked copyServerAddress, copyUserName, and copyUserPassword also be spcified. ') copyDestFileName = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 5, 1, 1, 1, 1, 7), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: copyDestFileName.setStatus('current') if mibBuilder.loadTexts: copyDestFileName.setDescription('Specifies the location of destination file. If the copyDestFileType has the value of dellNetFile(1), it is expected that the dellNetCopyDestFileTyp and copyDestFileLocation must also be spcified. The three objects together will uniquely identify the source file. If the copyDestFileLocation has the value of ftp(4) or scp(5), it is expected the login information liked copyServerAddress, copyUserName, and copyUserPassword also be spcified. ') copyServerAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 5, 1, 1, 1, 1, 8), IpAddress()).setMaxAccess("readwrite") if mibBuilder.loadTexts: copyServerAddress.setStatus('deprecated') if mibBuilder.loadTexts: copyServerAddress.setDescription('The ip address of the tftp server from (or to) which to copy the configuration file. Values of 0.0.0.0 or FF.FF.FF.FF for copyServerAddress are not allowed. If the copyDestFileLocation has the value of ftp(4) or scp(5), it is expected the login information liked copyServerAddress, copyUserName, and copyUserPassword also be spcified. ') copyUserName = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 5, 1, 1, 1, 1, 9), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 15))).setMaxAccess("readwrite") if mibBuilder.loadTexts: copyUserName.setStatus('current') if mibBuilder.loadTexts: copyUserName.setDescription('Remote user name for copy via ftp, or scp. If the copyDestFileLocation has the value of ftp(4) or scp(5), it is expected the login information liked copyServerAddress, copyUserName, and copyUserPassword also be spcified. ') copyUserPassword = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 5, 1, 1, 1, 1, 10), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 15))).setMaxAccess("readwrite") if mibBuilder.loadTexts: copyUserPassword.setStatus('current') if mibBuilder.loadTexts: copyUserPassword.setDescription('Password used by ftp, scp for copying a file to an ftp/scp server. If the copyDestFileLocation has the value of ftp(4) or scp(5), it is expected the login information liked copyServerAddress, copyUserName, and copyUserPassword also be spcified. ') copyState = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 5, 1, 1, 1, 1, 11), DellNetConfigCopyState()).setMaxAccess("readonly") if mibBuilder.loadTexts: copyState.setStatus('current') if mibBuilder.loadTexts: copyState.setDescription(' The state of config-copy operation. ') copyTimeStarted = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 5, 1, 1, 1, 1, 12), TimeTicks()).setMaxAccess("readonly") if mibBuilder.loadTexts: copyTimeStarted.setStatus('current') if mibBuilder.loadTexts: copyTimeStarted.setDescription(' The timetick when the copy started. ') copyTimeCompleted = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 5, 1, 1, 1, 1, 13), TimeTicks()).setMaxAccess("readonly") if mibBuilder.loadTexts: copyTimeCompleted.setStatus('current') if mibBuilder.loadTexts: copyTimeCompleted.setDescription(' The timetick when the copy completed. ') copyFailCause = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 5, 1, 1, 1, 1, 14), DellNetConfigCopyFailCause()).setMaxAccess("readonly") if mibBuilder.loadTexts: copyFailCause.setStatus('current') if mibBuilder.loadTexts: copyFailCause.setDescription(' The reason a config-copy request failed. ') copyEntryRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 5, 1, 1, 1, 1, 15), RowStatus()).setMaxAccess("readwrite") if mibBuilder.loadTexts: copyEntryRowStatus.setStatus('current') if mibBuilder.loadTexts: copyEntryRowStatus.setDescription(' The state of the copy operation. Uses CreateAndGo when you are performing the copy. The state is set to active when the copy is completed. ') copyServerInetAddressType = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 5, 1, 1, 1, 1, 16), InetAddressType()).setMaxAccess("readwrite") if mibBuilder.loadTexts: copyServerInetAddressType.setStatus('current') if mibBuilder.loadTexts: copyServerInetAddressType.setDescription(' The address type of copyServerInetAddress. Only ipv4 (1), ipv6 (2) and dns (16) types are supported. ') copyServerInetAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 6027, 3, 5, 1, 1, 1, 1, 17), InetAddress()).setMaxAccess("readwrite") if mibBuilder.loadTexts: copyServerInetAddress.setStatus('current') if mibBuilder.loadTexts: copyServerInetAddress.setDescription(' The IP address of the address ftp/tftp/scp server from or to which to copy the configuration file. If the copyDestFileLocation has the value of ftp(4) or scp(5), it is expected the login information copyUserName and copyUserPassword also be spcified. ') copyAlarmMibNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 6027, 3, 5, 1, 2, 0)) copyAlarmVariable = MibIdentifier((1, 3, 6, 1, 4, 1, 6027, 3, 5, 1, 2, 1)) copyAlarmLevel = MibScalar((1, 3, 6, 1, 4, 1, 6027, 3, 5, 1, 2, 1, 1), Integer32()).setMaxAccess("accessiblefornotify") if mibBuilder.loadTexts: copyAlarmLevel.setStatus('current') if mibBuilder.loadTexts: copyAlarmLevel.setDescription('the message warning level') copyAlarmString = MibScalar((1, 3, 6, 1, 4, 1, 6027, 3, 5, 1, 2, 1, 2), OctetString()).setMaxAccess("accessiblefornotify") if mibBuilder.loadTexts: copyAlarmString.setStatus('current') if mibBuilder.loadTexts: copyAlarmString.setDescription('An generic string value in the TRAP object') copyAlarmIndex = MibScalar((1, 3, 6, 1, 4, 1, 6027, 3, 5, 1, 2, 1, 3), Integer32()).setMaxAccess("accessiblefornotify") if mibBuilder.loadTexts: copyAlarmIndex.setStatus('current') if mibBuilder.loadTexts: copyAlarmIndex.setDescription("the index of the current copy. Indicates the index of the current copy, i.e. copyConfigIndex of dellNetCopyTable. Set to '-1' if copy executed by CLI") copyConfigCompleted = NotificationType((1, 3, 6, 1, 4, 1, 6027, 3, 5, 1, 2, 0, 1)).setObjects(("DELL-NETWORKING-COPY-CONFIG-MIB", "copyAlarmLevel"), ("DELL-NETWORKING-COPY-CONFIG-MIB", "copyAlarmString"), ("DELL-NETWORKING-COPY-CONFIG-MIB", "copyAlarmIndex")) if mibBuilder.loadTexts: copyConfigCompleted.setStatus('current') if mibBuilder.loadTexts: copyConfigCompleted.setDescription('The agent generate this trap when a copy operational is completed.') configConflict = NotificationType((1, 3, 6, 1, 4, 1, 6027, 3, 5, 1, 2, 0, 2)).setObjects(("DELL-NETWORKING-COPY-CONFIG-MIB", "copyAlarmLevel"), ("DELL-NETWORKING-COPY-CONFIG-MIB", "copyAlarmString"), ("DELL-NETWORKING-COPY-CONFIG-MIB", "copyAlarmIndex")) if mibBuilder.loadTexts: configConflict.setStatus('current') if mibBuilder.loadTexts: configConflict.setDescription('The agent generate this trap when a configuration conflict found during audit.') configConflictClear = NotificationType((1, 3, 6, 1, 4, 1, 6027, 3, 5, 1, 2, 0, 3)).setObjects(("DELL-NETWORKING-COPY-CONFIG-MIB", "copyAlarmLevel"), ("DELL-NETWORKING-COPY-CONFIG-MIB", "copyAlarmString"), ("DELL-NETWORKING-COPY-CONFIG-MIB", "copyAlarmIndex")) if mibBuilder.loadTexts: configConflictClear.setStatus('current') if mibBuilder.loadTexts: configConflictClear.setDescription('The agent generate this trap when a configuration conflict resolved during audit.') batchConfigCommitProgress = NotificationType((1, 3, 6, 1, 4, 1, 6027, 3, 5, 1, 2, 0, 4)).setObjects(("DELL-NETWORKING-COPY-CONFIG-MIB", "copyAlarmLevel"), ("DELL-NETWORKING-COPY-CONFIG-MIB", "copyAlarmString"), ("DELL-NETWORKING-COPY-CONFIG-MIB", "copyAlarmIndex")) if mibBuilder.loadTexts: batchConfigCommitProgress.setStatus('current') if mibBuilder.loadTexts: batchConfigCommitProgress.setDescription('The agent generate this trap when a configuration commit is initiated.') batchConfigCommitCompleted = NotificationType((1, 3, 6, 1, 4, 1, 6027, 3, 5, 1, 2, 0, 5)).setObjects(("DELL-NETWORKING-COPY-CONFIG-MIB", "copyAlarmLevel"), ("DELL-NETWORKING-COPY-CONFIG-MIB", "copyAlarmString"), ("DELL-NETWORKING-COPY-CONFIG-MIB", "copyAlarmIndex")) if mibBuilder.loadTexts: batchConfigCommitCompleted.setStatus('current') if mibBuilder.loadTexts: batchConfigCommitCompleted.setDescription('The agent generate this trap when a configuration commit is completed.') mibBuilder.exportSymbols("DELL-NETWORKING-COPY-CONFIG-MIB", dellNetCopyConfigTraps=dellNetCopyConfigTraps, dellNetCopyConfig=dellNetCopyConfig, DellNetConfigFileType=DellNetConfigFileType, copyAlarmMibNotifications=copyAlarmMibNotifications, copyAlarmLevel=copyAlarmLevel, dellNetCopyConfigMib=dellNetCopyConfigMib, copyFailCause=copyFailCause, copyDestFileName=copyDestFileName, copyServerInetAddressType=copyServerInetAddressType, DellNetConfigFileLocation=DellNetConfigFileLocation, copyTimeStarted=copyTimeStarted, copySrcFileLocation=copySrcFileLocation, copyDestFileLocation=copyDestFileLocation, copyState=copyState, copySrcFileType=copySrcFileType, copyConfigCompleted=copyConfigCompleted, copyUserPassword=copyUserPassword, batchConfigCommitProgress=batchConfigCommitProgress, dellNetCopyConfigObjects=dellNetCopyConfigObjects, DellNetConfigCopyState=DellNetConfigCopyState, copyConfigIndex=copyConfigIndex, copyServerInetAddress=copyServerInetAddress, DellNetConfigCopyFailCause=DellNetConfigCopyFailCause, dellNetCopyEntry=dellNetCopyEntry, copyDestFileType=copyDestFileType, copyAlarmVariable=copyAlarmVariable, copyServerAddress=copyServerAddress, batchConfigCommitCompleted=batchConfigCommitCompleted, copyAlarmIndex=copyAlarmIndex, copySrcFileName=copySrcFileName, PYSNMP_MODULE_ID=dellNetCopyConfigMib, copyTimeCompleted=copyTimeCompleted, configConflict=configConflict, configConflictClear=configConflictClear, copyUserName=copyUserName, dellNetCopyTable=dellNetCopyTable, copyAlarmString=copyAlarmString, copyEntryRowStatus=copyEntryRowStatus)
text = input() first = "AB" second = "BA" flag = False while True: if text.find(first) != -1: text = text[text.find(first)+2:] elif text.find(second) != -1: text = text[text.find(second)+2:] else: break if len(text) == 0: flag = True break if flag == True: print("YES") else: print("NO")
routes = { '{"command": "devs"}' : {"STATUS":[{"STATUS":"S","When":1553528607,"Code":9,"Msg":"3 GPU(s)","Description":"sgminer 5.6.2-b"}],"DEVS":[{"ASC":0,"Name":"BKLU","ID":0,"Enabled":"Y","Status":"Alive","Temperature":43.00,"MHS av":14131.4720,"MHS 5s":14130.6009,"Accepted":11788,"Rejected":9,"Hardware Errors":0,"Utility":2.9159,"Last Share Pool":0,"Last Share Time":1553528606,"Total MH":3427718036.9040,"Diff1 Work":224456704.000000,"Difficulty Accepted":195866624.00000000,"Difficulty Rejected":147456.00000000,"Last Share Difficulty":16384.00000000,"No Device":False,"Last Valid Work":1553528606,"Device Hardware%":0.0000,"Device Rejected%":0.0657,"Device Elapsed":242559},{"ASC":1,"Name":"BKLU","ID":1,"Enabled":"Y","Status":"Alive","Temperature":42.00,"MHS av":14131.4689,"MHS 5s":14131.1408,"Accepted":11757,"Rejected":10,"Hardware Errors":0,"Utility":2.9082,"Last Share Pool":0,"Last Share Time":1553528603,"Total MH":3427717273.8192,"Diff1 Work":223334400.000000,"Difficulty Accepted":195428352.00000000,"Difficulty Rejected":163840.00000000,"Last Share Difficulty":16384.00000000,"No Device":False,"Last Valid Work":1553528603,"Device Hardware%":0.0000,"Device Rejected%":0.0734,"Device Elapsed":242559},{"ASC":2,"Name":"BKLU","ID":2,"Enabled":"Y","Status":"Alive","Temperature":39.00,"MHS av":14131.4688,"MHS 5s":14131.2909,"Accepted":11570,"Rejected":12,"Hardware Errors":0,"Utility":2.8620,"Last Share Pool":0,"Last Share Time":1553528605,"Total MH":3427717259.6881,"Diff1 Work":219270144.000000,"Difficulty Accepted":191811584.00000000,"Difficulty Rejected":196608.00000000,"Last Share Difficulty":16384.00000000,"No Device":False,"Last Valid Work":1553528605,"Device Hardware%":0.0000,"Device Rejected%":0.0897,"Device Elapsed":242559}],"id":1}, '{"command": "pools"}' : {"STATUS":[{"STATUS":"S","When":1553528611,"Code":7,"Msg":"6 Pool(s)","Description":"sgminer 5.6.2-b"}],"POOLS":[{"POOL":0,"Name":"lbry.usa.nicehash.com","URL":"stratum+tcp://lbry.usa.nicehash.com:3356","Profile":"","Algorithm":"lbry","Algorithm Type":"Lbry","Description":"","Status":"Alive","Priority":0,"Quota":1,"Long Poll":"N","Getworks":7014,"Accepted":35115,"Rejected":31,"Works":3931179,"Discarded":135670,"Stale":5043,"Get Failures":0,"Remote Failures":0,"User":"3J6HNskoH271PVPFvfAmBqUmarMFjwwfCX.1","Last Share Time":1553528606,"Diff1 Shares":667061248.000000,"Proxy Type":"","Proxy":"","Difficulty Accepted":583106560.00000000,"Difficulty Rejected":507904.00000000,"Difficulty Stale":83446784.00000000,"Last Share Difficulty":16384.00000000,"Has Stratum":True,"Stratum Active":True,"Stratum URL":"lbry.usa.nicehash.com","Has GBT":False,"Best Share":1286062923.914351,"Pool Rejected%":0.0761,"Pool Stale%":12.5096},{"POOL":1,"Name":"decred.usa.nicehash.com","URL":"stratum+tcp://decred.usa.nicehash.com:3354","Profile":"","Algorithm":"decred","Algorithm Type":"Decred","Description":"","Status":"Alive","Priority":1,"Quota":1,"Long Poll":"N","Getworks":0,"Accepted":0,"Rejected":0,"Works":0,"Discarded":0,"Stale":0,"Get Failures":0,"Remote Failures":0,"User":"3J6HNskoH271PVPFvfAmBqUmarMFjwwfCX.1","Last Share Time":0,"Diff1 Shares":0.000000,"Proxy Type":"","Proxy":"","Difficulty Accepted":0.00000000,"Difficulty Rejected":0.00000000,"Difficulty Stale":0.00000000,"Last Share Difficulty":0.00000000,"Has Stratum":True,"Stratum Active":False,"Stratum URL":"","Has GBT":False,"Best Share":0.000000,"Pool Rejected%":0.0000,"Pool Stale%":0.0000},{"POOL":2,"Name":"blake256r14.usa.nicehash.com","URL":"stratum+tcp://blake256r14.usa.nicehash.com:3350","Profile":"","Algorithm":"blake256r14","Algorithm Type":"Blake","Description":"","Status":"Dead","Priority":1,"Quota":1,"Long Poll":"N","Getworks":0,"Accepted":0,"Rejected":0,"Works":0,"Discarded":0,"Stale":0,"Get Failures":0,"Remote Failures":0,"User":"3J6HNskoH271PVPFvfAmBqUmarMFjwwfCX.1","Last Share Time":0,"Diff1 Shares":0.000000,"Proxy Type":"","Proxy":"","Difficulty Accepted":0.00000000,"Difficulty Rejected":0.00000000,"Difficulty Stale":0.00000000,"Last Share Difficulty":0.00000000,"Has Stratum":True,"Stratum Active":False,"Stratum URL":"","Has GBT":False,"Best Share":0.000000,"Pool Rejected%":0.0000,"Pool Stale%":0.0000},{"POOL":3,"Name":"blake256r8.usa.nicehash.com","URL":"stratum+tcp://blake256r8.usa.nicehash.com:3349","Profile":"","Algorithm":"blake256r8","Algorithm Type":"Blakecoin","Description":"","Status":"Alive","Priority":1,"Quota":1,"Long Poll":"N","Getworks":0,"Accepted":0,"Rejected":0,"Works":0,"Discarded":0,"Stale":0,"Get Failures":0,"Remote Failures":0,"User":"3J6HNskoH271PVPFvfAmBqUmarMFjwwfCX.1","Last Share Time":0,"Diff1 Shares":0.000000,"Proxy Type":"","Proxy":"","Difficulty Accepted":0.00000000,"Difficulty Rejected":0.00000000,"Difficulty Stale":0.00000000,"Last Share Difficulty":0.00000000,"Has Stratum":True,"Stratum Active":False,"Stratum URL":"","Has GBT":False,"Best Share":0.000000,"Pool Rejected%":0.0000,"Pool Stale%":0.0000},{"POOL":4,"Name":"pascal.usa.nicehash.com","URL":"stratum+tcp://pascal.usa.nicehash.com:3358","Profile":"","Algorithm":"pascal","Algorithm Type":"Pascal","Description":"","Status":"Alive","Priority":1,"Quota":1,"Long Poll":"N","Getworks":0,"Accepted":0,"Rejected":0,"Works":0,"Discarded":0,"Stale":0,"Get Failures":0,"Remote Failures":0,"User":"3J6HNskoH271PVPFvfAmBqUmarMFjwwfCX.1","Last Share Time":0,"Diff1 Shares":0.000000,"Proxy Type":"","Proxy":"","Difficulty Accepted":0.00000000,"Difficulty Rejected":0.00000000,"Difficulty Stale":0.00000000,"Last Share Difficulty":0.00000000,"Has Stratum":True,"Stratum Active":False,"Stratum URL":"","Has GBT":False,"Best Share":0.000000,"Pool Rejected%":0.0000,"Pool Stale%":0.0000},{"POOL":5,"Name":"sia.usa.nicehash.com","URL":"stratum+tcp://sia.usa.nicehash.com:3360","Profile":"","Algorithm":"sia","Algorithm Type":"Sia","Description":"","Status":"Alive","Priority":2,"Quota":1,"Long Poll":"N","Getworks":0,"Accepted":0,"Rejected":0,"Works":0,"Discarded":0,"Stale":0,"Get Failures":0,"Remote Failures":0,"User":"3J6HNskoH271PVPFvfAmBqUmarMFjwwfCX.1","Last Share Time":0,"Diff1 Shares":0.000000,"Proxy Type":"","Proxy":"","Difficulty Accepted":0.00000000,"Difficulty Rejected":0.00000000,"Difficulty Stale":0.00000000,"Last Share Difficulty":0.00000000,"Has Stratum":True,"Stratum Active":False,"Stratum URL":"","Has GBT":False,"Best Share":0.000000,"Pool Rejected%":0.0000,"Pool Stale%":0.0000}],"id":1}, '{"command": "summary"}' : {"STATUS":[{"STATUS":"S","When":1553528611,"Code":11,"Msg":"Summary","Description":"sgminer 5.6.2-b"}],"SUMMARY":[{"Elapsed":242564,"MHS av":42394.3021,"MHS 5s":42383.2910,"KHS av":42394302,"KHS 5s":42383291,"Found Blocks":3995,"Getworks":7014,"Accepted":35115,"Rejected":31,"Hardware Errors":0,"Utility":8.6859,"Discarded":135670,"Stale":5043,"Get Failures":0,"Local Work":4072753,"Remote Failures":0,"Network Blocks":1548,"Total MH":10283339200.9091,"Work Utility":165002.4113,"Difficulty Accepted":583106560.00000000,"Difficulty Rejected":507904.00000000,"Difficulty Stale":83446784.00000000,"Best Share":1286062923.914351,"Device Hardware%":0.0000,"Device Rejected%":0.0761,"Pool Rejected%":0.0761,"Pool Stale%":12.5096,"Last getwork":1553528611}],"id":1} }
TAG_ALBUM = "album" TAG_ALBUM_ARTIST = "album_artist" TAG_ARTIST = "artist" TAG_DURATION = "duration" TAG_GENRE = "genre" TAG_TITLE = "title" TAG_TRACK = "track" TAG_YEAR = "year" TAGS = frozenset([ TAG_ALBUM, TAG_ALBUM_ARTIST, TAG_ARTIST, TAG_DURATION, TAG_GENRE, TAG_TITLE, TAG_TRACK, TAG_YEAR, ])
class Solution: def sortItems(self, n: int, m: int, group: List[int], beforeItems: List[List[int]]) -> List[int]: cnt = 0 groups = collections.defaultdict(list) for i, g in enumerate(group): if g == -1: group[i] = cnt + m cnt += 1 groups[group[i]].append(i) degrees = [0] * (m + cnt) graphs = collections.defaultdict(set) follows = collections.defaultdict(list) for v, befores in enumerate(beforeItems): for u in befores: if group[u] != group[v]: degrees[group[v]] += 1 follows[group[u]].append(group[v]) else: graphs[group[u]].add((u, v)) frees = [] for i in range(cnt + m): if degrees[i] == 0: frees.append(i) group_seq = [] while frees: node = frees.pop() group_seq.append(node) for nei in follows[node]: degrees[nei] -= 1 if degrees[nei] == 0: frees.append(nei) if len(group_seq) != m + cnt: return [] ans = [] for gidx in group_seq: if len(groups[gidx]) == 1: ans.append(groups[gidx].pop()) else: eles = groups[gidx] edges = graphs[gidx] degrees = {e : 0 for e in eles} follows = collections.defaultdict(set) for u, v in edges: degrees[v] += 1 follows[u].add(v) frees = [] for e in eles: if degrees[e] == 0: frees.append(e) seq = [] while frees: node = frees.pop() seq.append(node) for nei in follows[node]: degrees[nei] -= 1 if degrees[nei] == 0: frees.append(nei) if len(seq) == len(eles): ans.extend(seq) else: return [] return ans
def calc_eccentricity(dist_list): """Calculate and return eccentricity from list of radii.""" apoapsis = max(dist_list) periapsis = min(dist_list) eccentricity = (apoapsis - periapsis) / (apoapsis + periapsis) return eccentricity
description = 'NICOS demo startup setup' group = 'lowlevel' # startupcode = ''' # printinfo("============================================================") # printinfo("Welcome to the NICOS demo.") # printinfo("Run one of the following commands to set up either a triple-axis") # printinfo("or a SANS demo setup:") # printinfo(" > NewSetup('tas')") # printinfo(" > NewSetup('sans')") # '''
#!/usr/bin/env python class Life: def __init__(self, name='unknown'): print('Hello ' + name) self.name = name def live(self): print(self.name) def __del__(self): print('Goodbye ' + self.name) brian = Life('Brian') brian.live() brian = 'leretta'
# Articles and their urls. topics_links = { "документи для в'їзду в ірландію":""" Документі необхідні для в’їзду до Ірландії\: На даний час Ірландія приймає: 1\. Міжнародний паспорт, з біометрією або без неї, прострочений в тому числі\. 2\. Внутрішній паспорт України\. В тому числі прострочений\. 3\. Свідоцтво про народження\. Незважаючи на те, що більшість авіакомпаній підтримують ці лояльні правила в’їзду, якщо ви маєте українські документи, краще приїхати до аєропорту трохи раніше, щоб мати змогу вирішити всі непорозуміння, якщо вони виникнуть\. Питання та відповіді\: 1\. Чи потрібна мені віза, якщо я не громадянин України, але знаходився в Україні станом на початок військових дій або маю вид на проживання в Україні та хочу отримати Temporary Protection / Asylum в Ірландії? \- Якщо ви маєте вид на проживання та ваш чоловік\дружина\дитина є громадянами України ви можете отримати цей статус, але всі випадки розглядаються індивідуально\. 2\. Чи потрібен мені ПЛР тест або сертифікат про вакцинацію при в’їзді до Ірландії? \- Ні, зараз не потрібні\. """, "документи, які вам потрібні в ірландії":""" Список документів які потрібно мати в Ірландії\: 1\. PPSN \(Personal Public Service Number\) \- аналогічний до нашого номера платника податків\. Зазвичай ви заповнюєте форму на нього в аеропорту\. Він потрібен вам для отримання всіх інших документів, при відкритті банківського рахунку, оренді житла та працевлаштуванні\. Він оформлюється на кожного члена сім’ї \(не виключаючи немовлят\) одразу в аєропорту або в найближчому до вас офісі INTREO \(знайдіть найближчий за гугл мапою\)\. Строк отримання: одразу або на протязі 2х тижнів за вашою поштовою адресою\. Не хвилюйтеся, надсилати документи поштою – це типово для Ірландії\. [Інструкція отримання PPSN\.](https://help\-ukraine\-ireland\.notion\.site/How\-to\-get\-a\-PPSN\-PPSN\-5eb6a10ab9bc4cc0ae465492fa08cc18\#998b833b06624700ad5055975b7b9045) 2\. PSC \(Public Services Card\) \- це картка з вашим PPS номером та вашою фотографією\. Вона необхідна для реєстрації у державних структурах Ірландії, у тому числі онлайн\. Також може бути використана для вашої ідентифікації та підтвердження PPS номера за необхідності\. Оформлювати її спеціально не потрібноі: вона надійде за вашою поштовою адресою автоматично\. Строк отримання: до 10 рабочих діб \(ймовірно\)\. Скоріш за все ви отримаєте її паперовою поштою\. 3\. Жовтий лист – лист про тимчасовий захист строком на рік для кожного члена сім’ї\. Видають одразу в аєропорту або можна отримати у INTREO на Cork street\. Якщо поселення у віддалені райони \- ситуації можуть бути різні, уточнюйте за місцем проживання\. 4\. Medical card, потрібно [завантажити та заповнити pdf форму спеціально для Українців](https://www2\.hse\.ie/services/healthcare\-in\-ireland/ukr\-medical\-card\-application\-form\.pdf) "UKR Medical Card Application Form"\. Медична картка також прийде за поштовою адресою\. """, "робота":""" Докладно про роботу в Ірладнії\: З PPSN ви можете працювати чи бути самозайнятим\. З великою вірогідністю після працевлаштування вас позбавлять соціальних виплат \(social welfare\), але це досі не підтверджено і буде розглядатись найближчим часом\. 1\. [Де шукати роботу](https://heathered\-waxflower\-01d\.notion\.site/7f06e850f71349ebab5a9762f7c95a8d) 2\. [Шаблон резюме](https://docs\.google\.com/document/d/1T2SDo\-mLWQf6MX8D1MgLHcGP\_pbN4bpZtO\-SbGAqLEw/edit) 3\. [Вакансіі для тих, хто не розмовляє англійською](https://docs\.google\.com/spreadsheets/d/12EKTPpZiYA1TfO7wTdTQV\-EKFXSZTpQVWfWUGxa4U7Q/edit) 4\. [Робота в Ірландії для спеціалістів із сфери бізнесу і технологій](https://t\.me/robotairlandia) 5\. [Робота в Ірландії з мінімальною англійською](https://t\.me/house\_ie4ua\_chat) 6\. [Робота та допомога українцям в Ірландії](https://www\.facebook\.com/groups/179415267343562/?ref\=share) """, "медицина":""" Як працює медицина в Ірландії\: 1\. [Дуже детальна інструкція як отримати медичину допомогу в Ірландії](https://docs\.google\.com/document/u/0/d/12XnkCIxw9SsC8EUPFiY9dupguPxf0zZSdvYl1hjsQaA/mobilebasic) 2\. [Як отримати медикаменти за призначенням в Ірландії pdf інструкція](https://s3\.us\-west\-2\.amazonaws\.com/secure\.notion\-static\.com/c3b1b0cd\-9bf3\-4f3f\-b982\-ac5a2f07c514/I%D0%9D%D0%A1%D0%A2%D0%A0%D0%A3%D0%9A%D0%A6I%D0%AF\_%D0%B0%D0%BF%D1%82%D0%B5%D1%86i\.pdf?X\-Amz\-Algorithm\=AWS4\-HMAC\-SHA256&X\-Amz\-Content\-Sha256\=UNSIGNED\-PAYLOAD&X\-Amz\-Credential\=AKIAT73L2G45EIPT3X45%2F20220327%2Fus\-west\-2%2Fs3%2Faws4\_request&X\-Amz\-Date\=20220327T154232Z&X\-Amz\-Expires\=86400&X\-Amz\-Signature\=3037b8daee95fb8570c9a8ba2bb39d854720f65744526a50e7f896bee17be67d&X\-Amz\-SignedHeaders\=host&response\-content\-disposition\=filename%20%3D%22I%25D0%259D%25D0%25A1%25D0%25A2%25D0%25A0%25D0%25A3%25D0%259A%25D0%25A6I%25D0%25AF%2520%25D0%25B0%25D0%25BF%25D1%2582%25D0%25B5%25D1%2586i\.pdf%22&x\-id\=GetObject) 3\. [Якщо вам терміново потрібні ліки, будь ласка, заповнюйте цю форму](https://forms\.gle/6kvAgRDX7Zq9hoXGA) """, "психологічна підтримка":""" Де можна отримати психологічну підтримку: Якщо вам потрібна психологічна підтримка, ви можете безкоштовно [отримати її тут\.](https://docs\.google\.com/spreadsheets/d/1hqiKyyJfvZSmP8Vg33hAbi3fjuy35LmUP4f280jxcXY/edit?fbclid\=IwAR1S72lnakfrBtQKRrYgnZ\-6VZ56hMAQ6Oq9dH\-Fi\-q4qkzbbGsyGOGyU6k) """, "як перевезти тварину в ірландію":""" Правила ввозу тварин до Ірландії Правила та способи ввезення [дивіться за посиланням](https://heathered\-waxflower\-01d\.notion\.site/1e75728dee3149eabc5ae778286bd1c1) """, "де, та що купувати в ірландії":""" Поради про те які товари та у яких магазинах краще шукати: [Список рекомендованих магазинів де ви зможете знайти все, що потрібно](https://help\-ukraine\-ireland\.notion\.site/Shops\-guide\-and\-discounts\-for\-Ukrainians\-446cbb2299114b58b7e8715b8a2b8f58) """, "громадський транспорт":""" Громадський транспорт Ірландії працює так: Безкоштовний проїзд надає ірландська залізниця та міжміські автобуси для того, щоб людина дісталася кінцевого пункту своєї поїздки, коли вона тільки прибула в Ірландію\. Наприклад, якщо ви прилетіли в Дублін, а житло знайшли десь в графстві Майо\. Поїзд по місту платний\. Хтось з водіїв міських автобусів чи перевірка у трамваї може пустити вас безкоштовно по українському паспорту, але це скоріше на їх розсуд\. Просимо не тикати паспортами і не вимагати більше, ніж вам можуть дати\. Як користуватись [громадським транспортом в Ірландії](https://help\-ukraine\-ireland\.notion\.site/Transport\-guide\-c48ca18d01754e5d859d40e048881d71) """, "мені потрібна допомога": """ Якщо вам потрібна допомога, ви можете звернутися до: 1\. Інформаційна [лінія українською мовою](https://www\.irishrefugeecouncil\.ie/ukrainian\-language\-information\-helpline) 2\. Дублін,Паляниця \(Palyanitsya\) \- центр благодійності в Дубліні, де можна отримати одяг, іграшки та речі першої необхідності БЕЗКОШТОВНО\. При вході в магазин перевіряють, коли ви прибули, тому треба мати документ, який підтверджує дату прибуття \- [44 Clarendon Street, D2, Dublin](https://goo\.gl/maps/kBapwRtvxhhhiu4h6) 3\. Дан Лірі \(Dun Laoghaire\) Новий Ukrainian hub – магазин безкоштовних речей та одягу для біженців\. [Unit 2, Georges Mall, Dun Laoghaire Shopping Centre](https://goo\.gl/maps/QetJAuXTAqu4vdxg8) 4\. [Корк, хаб у Мідлтон, Midleton, County Cork, P25 VR44](https://www\.facebook\.com/The\-Sunflower\-Ukrainian\-Donation\-Hub\-104590398855783/) Графік роботи: Понеділок, середа, п’ятниця 18\-20, Субота 12\-16 5\. Корк, Together Razem Center, Unit 2A, Kilnap Business Park, Old Mallow Rd, Corck T23V9K3 Графік роботи: понеділок \- четвер\. Дізнатися більше можна на сайті: www\.together\-razem\.org 6\. Cavan, Паляниця \(Palyanitsya\) – Old Dublin Road, Tullymongan Upper, Cavan, H12P4A7 7\. [Лімерик, Sacred Heart Catholic Church](https://maps\.app\.goo\.gl/bvim45rFfHSKmRLr7), до 17:00 в будні, на вихідним \- під час служіння\. \(061\) 315 812\. 8\. Arklow, графство Віклоу, Паляниця \(Palyanitsya\) – 2nd Floor, Bridgewater Shopping Centre, Wicklow 9\. Palyanytsya is opening on 23rd April – Old Library Building, Wicklow Town\. 10\. Tramore, графство Waterford, 3 Queen street \(двері поряд з бутіком Satina\)\. Запрошуємо з 17:30 до 19:30 з понеділка по п'ятницю 11\. Підтримка для мам, дитячі речі та візочки \- https://www\.mums2mums\.ie/ """, "в мене ще є питання":""" Якщо у вас залишились питання, пошукайте відповіді тут: 1\. [FAQ від Українського кризового центру в Ірландії](https://help\-ukraine\-ireland\.notion\.site/FAQ\-9846d8ef1d8d4eefa2a6113dc2cc46be) 2\. [FAQ від волонтерської організації допомоги “першого дня”](https://docs\.google\.com/document/d/1BSCfl2HvXvwHz51SL1w413OrWroLS6\_9InhVy\-lTwd8/edit) 3\. [FAQ від центра благодійності “Паляниця”](https://palianytsiainireland\.wordpress\.com/) """, "чати, канали та інші корисні ресурси":""" Українські чати в телеграмі: [Чат переселенців](https://t\.me/ukrainianinireland) [Канал з основною інформацією](https://t\.me/helpinireland) [Український кризовий центр](https://t\.me/volunteersneededireland) [Бьюті\-майстри](https://t\.me/\+sbjpCKO\-JoI1OWJi) [Маркетологи України](https://t\.me/\+Tpq21wX9wsUyYWYy) [Канал для волонтерів](https://t\.me/\+dP4OhXF3A0QwZGZi) Українські групи в фб: https://www\.facebook\.com/groups/Ukrainians\.in\.Ireland https://www\.facebook\.com/groups/787279257984036 https://www\.facebook\.com/groups/151187490507560 Російськомовні чати в телеграмі: Флудилка — [ссылка на вступление](https://t\.me/\+Huo4ZjEABM8yYTM0) \(если не работает напишите @cee\_aitch\) Чат только для постоянно проживающих в Ирландии и для тех, у кого на руках документы для переезда\. Авто чат — [ссылка на вступление](https://t\.me/joinchat/ZFeJVBRJ2jM4NTk0) Детский чат — [ссылка на вступление](https://t\.me/joinchat/AApSpA\_SlHc\-b2jKwpEBOA) Чатик про питомцев — [ссылка на вступление](https://t\.me/joinchat/YmB0SCunt64zZTdk) Хобби\-чат — [@irhobby](http://t\.me/irhobby) Концертный чат — [@gigrlnd](http://t\.me/gigrlnd) Чат с гаражной распродажей — [@garage\_sale\_ie](https://t\.me/garage\_sale\_ie) IT чатик — [ссылка на вступление](https://t\.me/irelandIT) Лингвочат — [ссылка на вступление](https://t\.me/joinchat/VrQrJA9PIpYRb8Mf) """, "вивчення англійської":""" [Варіанти безкоштовного чи дисконтного вивчення англійської](https://docs\.google\.com/spreadsheets/d/145gifnMrtuzRtJWNO1V\_SOigQFznxnH5yn3JsgGXDAg/edit\#gid\=0) """, "освіта для дітей":""" Садочки в Ірландії приватні і платні\. Для дітей від 2\.8 до 5 років є державна програма ЕССЕ, яка компенсує садочку 3 ранкові години навчання вашої дитини на день \(09:00\-12:00 з пн по пт\)\. З 4\-5 років можна віддавати дитину до безкоштовної школи, [Як працюють школи в Ірландії](https://docs\.google\.com/document/d/1qUPbxDI5lmWutfbeJ8dKP14i2K7XGPQRhM9eFqSr\-Ms/edit) """, "як дістатися до ірландії":""" Літаком\. ВАЖЛИВО\! Щоб летіти з пересадкою в будь\-якому аеропорту Великої Британії потрібна транзитна віза\. Для інших країн, будь ласка перевірте якщо вам потрібні транзитні візи\. В Ірландії 4 міжнародних аеропорти, куди можна прилетіти: Дублін, Корк, Шенное, Нок Паромом з міста Шербур, Франція\. Паром компанії StenaLine безкоштовний для Українців, вам видадуть каюту та харчування\. Доїхати до парома можна поїздами по Європі\. Якщо ви їдете автомобілем, то вам також треба буде їхати на паромі\. Увага: для вʼїзда в Ірландію вам потрібна Грін карта для авто для Європи\. Ви можете їздити з Грін картою на Українськими номерами не більш 6 місяців\. Оформити місцеву страховку на ліворульну машину ви не зможете\. Ваші Українські права будуть дійсні протягом 12 місяців з моменту приїзду\. """, "соціальні виплати":""" Станом на 27 березня виплачують так: На дорослого старше 25 років \- 206 євро на тиждень\. Якщо в сімʼї двоє і більше дорослих старше 25, то на наступного \- 137 євро на тиждень\. Якщо є діти, то на дитину до 12 років \- 40 євро на тиждень\. На дитину старше 12 років \- 48 євро на тиждень\. На людину 18\-24 роки \- 117\.7 євро на тиждень\. Плюс на дитину до 18 років є ще щомісячна виплата 140 євро на місяць \- child benefit\. Прочитати [про виплати можна ось тут](https://www\.gov\.ie/en/publication/abf3e\-social\-welfare\-supports\-for\-ukrainian\-citizens\-arriving\-in\-ireland\-under\-the\-temporary\-protection\-directive/\#getting\-a\-payment) З великою вірогідністю після працевлаштування вас позбавлять соціальних виплат \(social welfare\), але це досі не підтверджено і буде розглядатись найближчим часом\. """, "проживання":""" Якщо вам нема де жити в Ірландії, то ви маєте сказати про це під час перетину кордону\. Тоді служба IPAS \(International Protection Accommodation Services\) вас поселить в одному з наступних варіантів розташувань по Ірландії: \- в готель \- в хостел \- в спортзал \- в колишній монастир/церкву \- в наметове містечко Волонтери не знають заздалегідь куди вас селитимуть\. Це лотерея і вплинути не можливо\. Сімʼям з маленькими діткам намагаються підібрати кращі варіанти\. Вже зʼявилась інформація про організацію наметових містечок для біженців з України\. Якщо вас не влаштовують умови, куди вас поселили, можете поскаржитися написавши email сюди ipasinbox@equality\.gov\.ie Ви також можете самі знайті собі вариант житла у волонтерів на сайтах: https://www\.eu4ua\.org/uk https://mapahelp\.me https://www\.ukrainetakeshelter\.com https://www\.host4ukraine\.com https://icanhelp\.host https://www\.shelter4ua\.com/ua """, "державні ресурси":""" Багато корисної інформації є на ірландських державних сайтах\. Радимо їх читати, дещо, навіть, перекладено українською мовою\. 1\.[Головний державний сайт](https://www\.gov\.ie/en/campaigns/bc537\-irelands\-response\-to\-the\-situation\-in\-ukraine/) 2\.[Інформація для громадян, резидентів та біженців](https://www\.citizensinformation\.ie/en/moving\_country/asylum\_seekers\_and\_refugees/the\_asylum\_process\_in\_ireland/coming\_to\_ireland\_from\_ukraine\.html) 3\.[Сайт іміграційної служби](https://www\.irishimmigration\.ie/faqs\-for\-ukraine\-nationals\-and\-residents\-of\-ukraine/) 4\.[Сайт ради біженців](https://www\.irishrefugeecouncil\.ie/ukraine\-information\-note?fbclid\=IwAR1m2kXRTluWYSlCCz2fdWErzAH9wrJ6c7jhAzy7Xe7r98tOkO5giMXH\-aA) 5\.[Посольство України в Ірландії](https://ireland\.mfa\.gov\.ua/) 6\.[Сайт Українського Кризового Центру\.](www\.iamukrainian\.ie) На ньому вже є безліч інформації для приїжджих до Ірландії, включаючи як, що і де купити, посилання на групи в WhatsApp і канали в Telegram, де ви можете безпосередньо зв'язатися з іншими людьми, які приїхали з України\. """, "що подивитись в дубліні":""" Якщо ви живете в Дубліні або плануєте приїхати подивитись місто, ми зібрали [список рекомендацій з найгарнішими, найпопулярнішими місцями](https://docs\.google\.com/document/d/1oDW8PUhnlNpr6udtiqzG3ixE6zTqa1g0SRMYh2uwhv8/edit\#heading\=h\.f0mcwaa51y7o) """, }
# Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. { 'variables': { 'lzma_sdk_sources': [ '7z.h', '7zAlloc.c', '7zAlloc.h', '7zArcIn.c', '7zBuf.c', '7zBuf.h', '7zCrc.c', '7zCrc.h', '7zCrcOpt.c', '7zDec.c', '7zFile.c', '7zFile.h', '7zStream.c', '7zTypes.h', 'Alloc.c', 'Alloc.h', 'Bcj2.c', 'Bcj2.h', 'Bra.c', 'Bra.h', 'Bra86.c', 'Compiler.h', 'CpuArch.c', 'CpuArch.h', 'Delta.c', 'Delta.h', 'LzFind.c', 'LzFind.h', 'LzHash.h', 'Lzma2Dec.c', 'Lzma2Dec.h', 'LzmaEnc.c', 'LzmaEnc.h', 'LzmaDec.c', 'LzmaDec.h', 'LzmaLib.c', 'LzmaLib.h', 'Precomp.h', ], }, 'targets': [ { 'target_name': 'lzma_sdk', 'type': 'static_library', 'defines': [ '_7ZIP_ST', '_7Z_NO_METHODS_FILTERS', '_LZMA_PROB32', ], 'variables': { # Upstream uses self-assignment to avoid warnings. 'clang_warning_flags': [ '-Wno-self-assign' ] }, 'sources': [ '<@(lzma_sdk_sources)', ], 'include_dirs': [ '.', ], 'direct_dependent_settings': { 'include_dirs': [ '.', ], }, }, ], 'conditions': [ ['OS=="win"', { 'targets': [ { 'target_name': 'lzma_sdk64', 'type': 'static_library', 'defines': [ '_7ZIP_ST', '_LZMA_PROB32', ], 'variables': { # Upstream uses self-assignment to avoid warnings. 'clang_warning_flags': [ '-Wno-self-assign' ] }, 'include_dirs': [ '.', ], 'sources': [ '<@(lzma_sdk_sources)', ], 'configurations': { 'Common_Base': { 'msvs_target_platform': 'x64', }, }, 'direct_dependent_settings': { 'include_dirs': [ '.', ], }, }, ], }], ], }
config = { 'sampling_rate': 22050, 'hop_size': 256, 'model_type': 'hifigan_generator', 'hifigan_generator_params': { 'out_channels': 1, 'kernel_size': 7, 'filters': 128, 'use_bias': True, 'upsample_scales': [8, 8, 2, 2], 'stacks': 3, 'stack_kernel_size': [3, 7, 11], 'stack_dilation_rate': [[1, 3, 5], [1, 3, 5], [1, 3, 5]], 'use_final_nolinear_activation': True, 'is_weight_norm': False, }, 'hifigan_discriminator_params': { 'out_channels': 1, 'period_scales': [2, 3, 5, 7, 11], 'n_layers': 5, 'kernel_size': 5, 'strides': 3, 'filters': 8, 'filter_scales': 4, 'max_filters': 512, 'is_weight_norm': False, }, 'melgan_discriminator_params': { 'out_channels': 1, 'scales': 3, 'downsample_pooling': 'AveragePooling1D', 'downsample_pooling_params': {'pool_size': 4, 'strides': 2}, 'kernel_sizes': [5, 3], 'filters': 16, 'max_downsample_filters': 512, 'downsample_scales': [4, 4, 4, 4], 'nonlinear_activation': 'LeakyReLU', 'nonlinear_activation_params': {'alpha': 0.2}, 'is_weight_norm': False, }, 'stft_loss_params': { 'fft_lengths': [1024, 2048, 512], 'frame_steps': [120, 240, 50], 'frame_lengths': [600, 1200, 240], }, 'lambda_feat_match': 10.0, 'lambda_adv': 4.0, 'batch_size': 16, 'batch_max_steps': 8192, 'batch_max_steps_valid': 81920, 'remove_short_samples': True, 'allow_cache': True, 'is_shuffle': True, }
def countdown(num): print(num) if num == 0: return else: countdown(num - 1) if __name__ == "__main__": countdown(10)
class GridNode(object): """ A structure that represents a particular location in (U,V) from a grid. GridNode(uIndex: int,vIndex: int) """ @staticmethod def __new__(self,uIndex,vIndex): """ __new__[GridNode]() -> GridNode __new__(cls: type,uIndex: int,vIndex: int) """ pass UIndex=property(lambda self: object(),lambda self,v: None,lambda self: None) """The node's index along the U axis. Get: UIndex(self: GridNode) -> int Set: UIndex(self: GridNode)=value """ VIndex=property(lambda self: object(),lambda self,v: None,lambda self: None) """The node's index along the V axis. Get: VIndex(self: GridNode) -> int Set: VIndex(self: GridNode)=value """
""" You are given an m x n matrix M initialized with all 0's and an array of operations ops, where ops[i] = [ai, bi] means M[x][y] should be incremented by one for all 0 <= x < ai and 0 <= y < bi. Count and return the number of maximum integers in the matrix after performing all the operations.   Example 1: Input: m = 3, n = 3, ops = [[2,2],[3,3]] Output: 4 Explanation: The maximum integer in M is 2, and there are four of it in M. So return 4. Example 2: Input: m = 3, n = 3, ops = [[2,2],[3,3],[3,3],[3,3],[2,2],[3,3],[3,3],[3,3],[2,2],[3,3],[3,3],[3,3]] Output: 4 Example 3: Input: m = 3, n = 3, ops = [] Output: 9   Constraints: 1 <= m, n <= 4 * 104 1 <= ops.length <= 104 ops[i].length == 2 1 <= ai <= m 1 <= bi <= n """ class Solution(object): def maxCount(self, m, n, ops): """ :type m: int :type n: int :type ops: List[List[int]] :rtype: int """ my, mx = m, n for op in ops: my = min(my, op[0]) mx = min(mx, op[1]) return my * mx
class LocationPathFormatError(Exception): pass class LocationStepFormatError(Exception): pass class NodenameFormatError(Exception): pass class PredicateFormatError(Exception): pass class PredicatesFormatError(Exception): pass
class Estado: nome_estado: str sigla: str pais: str qt_estado: int def __init__(self, nome_estado, sigla): self.nome_estado = nome_estado self.sigla = sigla self.pais = 'Brasil' self.qtd_estado = 0 # é a soma dos qt_casos da classe Cidade def __str__(self): return '> ' + self.nome_estado + '.............. - total de casos: ' + str(self.qtd_estado) + ' - País: ' + self.pais def adicionar_casos(self, novos_casos): self.qtd_estado += novos_casos
burst_time=[] print("Enter the number of process: ") n=int(input()) print("Enter the burst time of the processes: \n") burst_time=list(map(int, input().split())) waiting_time=[] avg_waiting_time=0 turnaround_time=[] avg_turnaround_time=0 waiting_time.insert(0,0) turnaround_time.insert(0,burst_time[0]) for i in range(1,len(burst_time)): waiting_time.insert(i,waiting_time[i-1]+burst_time[i-1]) turnaround_time.insert(i,waiting_time[i]+burst_time[i]) avg_waiting_time+=waiting_time[i] avg_turnaround_time+=turnaround_time[i] avg_waiting_time=float(avg_waiting_time)/n avg_turnaround_time=float(avg_turnaround_time)/n print("\n") print("Process\t Burst Time\t Waiting Time\t Turn Around Time") for i in range(0,n): print(str(i)+"\t\t"+str(burst_time[i])+"\t\t"+str(waiting_time[i])+"\t\t"+str(turnaround_time[i])) print("\n") print("Average Waiting time is: "+str(avg_waiting_time)) print("Average Turn Arount Time is: "+str(avg_turnaround_time))
""" link: https://leetcode.com/problems/wildcard-matching/ problem: 问类正则表达式p是否能完全匹配s,其中p的匹配规则为 * -> 0+ any chars && ? -> 1 any char solution: DP,定义 dp[i][j] 为s[:i]是否匹配p[:j],注意是dp[0][0]代表空字符串和空正则允许匹配 初始化dp[0][k]后分情况讨论即可(注意实际代码为了方便处理,将s,p均右移了一位): dp[i][j] = (p[j] == '*' && dp[i][j-1]) # '*' 匹配空值 = (p[j] == '*' && dp[i-1][j]) # '*' 匹配1+个任意字符 = (p[j] == '*' && dp[i-1][j-1]) # '*' 匹配1个任意字符 = (p[j] == '?' || s[i] == p[j] && dp[i-1][j-1]) # ? 或其他字符精确匹配 solution-fix: 剪枝搜索,"*" 是个很神奇的匹配,可以将模式串抽象成 p1*p2*p3*p4 这样的序列,多个连续"*" 可以合并成一个,这时只需要确认s存在子序列 p1p2p3p4 即可 """ class Solution: def isMatch(self, s: str, p: str) -> bool: ls, lp = len(s), len(p) dp = [[False for i in range(lp+1)] for j in range(ls+1)] s, p = '*' + s, '*' + p dp[0][0] = True for i in range(1, lp+1): if p[i] == '*': dp[0][i] = True else: break for i in range(1, ls+1): for j in range(1, lp+1): if ((dp[i][j - 1] or dp[i - 1][j] or dp[i - 1][j - 1]) and p[j] == '*') or \ (dp[i - 1][j - 1] and (p[j] == '?' or s[i] == p[j])): dp[i][j] = True return dp[ls][lp] # --- class Solution: def isMatch(self, s: str, p: str) -> bool: i, j, confirm_j, pre_i = 0, 0, 0, 0 while not (i == len(s) and j == len(p)): if i < len(s) and j < len(p) and (s[i] == p[j] or p[j] == '?'): i += 1 j += 1 elif j < len(p) and p[j] == '*': j += 1 pre_i = i confirm_j = j else: if confirm_j == 0 or pre_i >= len(s): return False j = confirm_j i = pre_i + 1 pre_i = i while j < len(p) and p[j] == '*': j += 1 return i == len(s) and j == len(p)
lista = [ [1,2,3,4,5,6,7,9,8,10], [1,3,3,4,5,6,7,8,9,10], [1,7,3,4,5,6,7,8,9,10], [1,2,3,4,5,6,7,8,9,10], [1,2,3,4,5,6,7,8,9,10], [1,2,3,4,5,6,7,8,9,10], [1,8,3,4,5,6,7,8,9,10], ] def verificar(lista): ls = lista for index_lista in lista: for aux in index_lista: contador = 0 for lista in index_lista: print(f'aux : {aux} lista: {lista}') if aux == lista: contador += 1 print('contaador ', contador) if contador == 2: ind = ls.index(index_lista) print(f'no index da lista numero {ind} o numero: {aux} se repete') return 0 # print(aux) #print('============') verificar(lista)
#Leia duas notas e diga a média: abaixo de 5 reprovado; 5 a 6.9 recuperação; 7 ou mais aprovado n1= int(input('Digite a sua primeira nota: ')) n2= int(input('Digite a sua segunda nota: ')) media = (n1+n2)/2 if media < 5: print('Você foi reprovado por ter média igual a {} !!'.format(media)) elif 5<= media < 7: print('Você está de recuperação por ter média igual a {} !!'.format(media)) elif media>=7: print('Voce está aprovado, sua nota foi {}, PARABÉNS!!!!'.format(media)) else: print('FIM')
# Problem0019 - Counting Sundays # # https: // github.com/agileshaw/Project-Euler def totalDays(month, year): month_list = [4, 6, 9, 11] if month == 2: if year % 400 == 0 or ((year % 4 == 0) and year % 100 != 0): return 29 else: return 28 elif month in month_list: return 30 return 31 if __name__ == "__main__": count = 0 weekday = 0 for year in range(1900, 2001): for month in range(1, 13): for day in range(1, totalDays(month, year)+1): weekday = (weekday + 1) % 7 if weekday == 0 and day == 1 and year != 1900: count += 1 print("The total number of Sundays is: %d" % count)
def get_integer_input(message): """ This function will display the message to the user and request that they input an integer. If the user enters something that is not a number then the input will be rejected and an error message will be displayed. The user will then be asked to try again.""" value_as_string = input(message) while not value_as_string.isnumeric(): print('The input must be an integer') value_as_string = input(message) return int(value_as_string) age = get_integer_input('Please input your age: ') print('age is', age) print(get_integer_input.__doc__)
N = int(input()) a = list(map(int, input().split())) # 1開始にする A = [0]+a # いい入れ方(1はボールが入っている) B = [0]*(N+1) # ボールが入っている箱の番号 ans = [] # Nから1までループ for i in range(N, 0, -1): # iの1つ目の倍数からNまでの倍数の箱にボールが入っている箱の個数を求める tmp = 0 for j in range(i*2, N+1, i): tmp += B[j] # 合計%2がA[i]と不一致ならボールを入れる if tmp % 2 != A[i]: B[i] = 1 ans.append(i) if len(ans) == 0: print(0) else: print(len(ans)) print(' '.join(map(str, ans)))
def lower_bound(arr, value, first, last): """Find the lower bound of the value in the array lower bound: the first element in arr that is larger than or equal to value Args: arr : input array value : target value first : starting point of the search, inclusive last : ending point of the search, exclusive Return index : integer if index == last => lower bound does not exist else => arr[index] >= value Note: 1. use first + (last - first) // 2 to avoid overflow in old language 2. invariant: 1. all values in the range [initial_first, first) is smaller than value 2. all values in the range [last, initial_last) is greater than or equal to value 3. first < last at the end of the iteration, first = last if a value greter than or equal to value exists, we simply return the first element in the range [last, initial_last) else we can return anything (last, -1, etc) to denote that such a value does not exist note also that at the end first and last will always be the same so it does not matter which one we return """ while first < last: mid = first + (last - first) // 2 if arr[mid] < value: first = mid + 1 else: last = mid return first def upper_bound(arr, value, first, last): """Find the upper bound of the value in the array upper bound: the first element in arr that is larger than value Args: arr : input array value : target value first : starting point of the search, inclusive last : ending point of the search, exclusive Return index : integer if index == last => upper bound does not exist else => arr[index] > value """ while first < last: mid = first + (last - first) // 2 if arr[mid] <= value: first = mid + 1 else: last = mid return first
class CraftParser: @staticmethod def calculate_mass(craft_filepath: str, masses: dict) -> int: parts = [] craft_lines = [] with open(craft_filepath) as craft: craft_lines = [line.strip() for line in craft.readlines()] for index, line in enumerate(craft_lines): if "part = " in line: # Replacing period with underscore because in craft files some parts # are stored with periods even though their names in cfg files # use underscores partname = line.split()[2].split('_')[0].replace('.', '_') parts.append((partname, 1)) elif 'RESOURCE' in line: resourcename = craft_lines[index + 2].split()[2] amount = float(craft_lines[index + 3].split()[2]) parts.append((resourcename, amount)) mass = 0 for part in parts: mass += masses[part[0]] * part[1] return mass @staticmethod def calculate_mass_distribution_3d(craft_filepath: str, masses: dict): parts = [] craft_lines = [] with open(craft_filepath) as craft: craft_lines = [line.strip() for line in craft.readlines()] for index, line in enumerate(craft_lines): if line == "PART": # Replacing period with underscore because in craft files some parts # are stored with periods even though their names in cfg files # use underscores partname = craft_lines[index + 2].split()[2].split('_')[0].replace('.', '_') for i in range(3, 7): if "pos = " in craft_lines[index + i]: pos = [float(coord) for coord in craft_lines[index + i].split()[2].split(',')] break parts.append([masses[partname], pos]) elif 'RESOURCE' in line: resourcename = craft_lines[index + 2].split()[2] amount = float(craft_lines[index + 3].split()[2]) parts[-1][0] += amount * masses[resourcename] return parts
# -*- coding: utf-8 -*- """ Created on Mon Feb 4 23:24:41 2019 @author: rocco """ #function to convert datetime to seconds def datetime2seconds(date_time): return time.mktime(date_time.timetuple()) #function to convert datetime to seconds def dateinterv2date(interval): return interval.left.to_pydatetime().date() #map list1 = list(map(datetime2seconds, idx)) #map list3 = list(map(dateinterv2date, ser)) #bin the latitude lat_min = [-90.000000, -77.800003, -72.713684, -68.787941, -65.458900, -62.508518, -59.825134, -57.342499] lat_max = [-77.800003, -72.713684, -68.787941, -65.458900, -62.508518, -59.825134, -57.342499, -55.017498] a_tot = 46178707.119740881 bins = pd.IntervalIndex.from_tuples([(lat_min[0], lat_max[0]), (lat_min[1], lat_max[1]), (lat_min[2], lat_max[2]),\ (lat_min[3], lat_max[3]), (lat_min[4], lat_max[4]), (lat_min[5], lat_max[5]), \ (lat_min[6], lat_max[6]), (lat_min[7], lat_max[7])]) #binning sr_binned = pd.cut(df_lt["lat"], bins) sr_binned_total, bins_date = pd.cut(df_lt.date, 10, retbins = True) bins_date = pd.to_datetime(bins_date) sr_binned_clouds = pd.Series(pd.cut(df_data.index, bins_date)) #count counts = pd.value_counts(sr_binned) counts_clouds = pd.value_counts(sr_binned_clouds) #fun to compute , c1 is cloud counts, c2 is total counts def counts_ratio(c1, c2): return c1/c2 #map list2 = list(map(counts_ratio, counts_cl, counts)) #compute mean np.asarray(list2).mean() #covered area #fun to extract info (df_data["lat"] < lat_max[0]) & (df_data["lat"] > lat_min[0]) #histogram plt.hist2d(list1, df_data["htang"], bins=[10, 20]) p1 = pd.value_counts(df_data[df_data["data_range"] == counts.index[0]]["lat_range"]).sort_index()[7] pd.date_range(start='2/1/2018', periods=11, freq='3D')[-1]
""" Author: Shengjia Yan Date: 2018-05-11 Friday Email: [email protected] Time Complexity: O(n) Space Complexity: O(n) """ class Solution: def reverseWords(self, s): """ :type s: str :rtype: str """ words = s.split(' ') res = [] for word in words: l = len(word) new_word = '' for i in range(l): new_word += word[l-i-1] res.append(new_word) new_s = (' ').join(res) return new_s
"""You are given an integer n, the number of teams in a tournament that has strange rules: If the current number of teams is even, each team gets paired with another team. A total of n / 2 matches are played, and n / 2 teams advance to the next round. If the current number of teams is odd, one team randomly advances in the tournament, and the rest gets paired. A total of (n - 1) / 2 matches are played, and (n - 1) / 2 + 1 teams advance to the next round. Return the number of matches played in the tournament until a winner is decided. Example 1: Input: n = 7 Output: 6 Explanation: Details of the tournament: - 1st Round: Teams = 7, Matches = 3, and 4 teams advance. - 2nd Round: Teams = 4, Matches = 2, and 2 teams advance. - 3rd Round: Teams = 2, Matches = 1, and 1 team is declared the winner. Total number of matches = 3 + 2 + 1 = 6.""" n = 14 # number of matchs played until winnner is decided matches = [] while n != 1: if n % 2 == 0: matches.append(n // 2) n = n // 2 else: matches.append((n - 1) // 2) n = ((n - 1) // 2) + 1 print(matches) print(sum(matches))
# flake8: noqa responses = { "success": { "status_code": 200, "content": { "resourceType":"Bundle", "id":"389a548b-9c85-4491-9795-9306a957030b", "meta":{ "lastUpdated":"2019-12-18T13:40:02.792-05:00" }, "type":"searchset", "total":1, "link":[ { "relation":"first", "url":"https://sandbox.bluebutton.cms.gov/v1/fhir/Patient?_count=10&startIndex=0&_id=-20000000002346" }, { "relation":"last", "url":"https://sandbox.bluebutton.cms.gov/v1/fhir/Patient?_count=10&startIndex=0&_id=-20000000002346" }, { "relation":"self", "url":"https://sandbox.bluebutton.cms.gov/v1/fhir/Patient/?_count=10&_format=application%2Fjson%2Bfhir&_id=-20000000002346&startIndex=0" } ], "entry":[ { "resource":{ "resourceType":"Patient", "id":"-20000000002346", "extension":[ { "url":"https://bluebutton.cms.gov/resources/variables/race", "valueCoding":{ "system":"https://bluebutton.cms.gov/resources/variables/race", "code":"1", "display":"White" } } ], "identifier":[ { "system":"https://bluebutton.cms.gov/resources/variables/bene_id", "value":"-20000000002346" }, { "system":"https://bluebutton.cms.gov/resources/identifier/mbi-hash", "value":"98765432137efea543f4f370f96f1dbf01c3e3129041dba3ea43675987654321" } ], "name":[ { "use":"usual", "family":"Doe", "given":[ "John", "X" ] } ], "gender":"male", "birthDate":"2000-06-01", "address":[ { "district":"999", "state":"48", "postalCode":"99999" } ] } } ] }, }, "not_found": { "status_code": 200, "content": { "resourceType":"Bundle", "id":"389a548b-9c85-4491-9795-9306a957030b", "meta":{ "lastUpdated":"2019-12-18T13:40:02.792-05:00" }, "type":"searchset", "total":0, "link":[ { "relation":"first", "url":"https://sandbox.bluebutton.cms.gov/v1/fhir/Patient?_count=10&startIndex=0&_id=-20000000002346" }, { "relation":"last", "url":"https://sandbox.bluebutton.cms.gov/v1/fhir/Patient?_count=10&startIndex=0&_id=-20000000002346" }, { "relation":"self", "url":"https://sandbox.bluebutton.cms.gov/v1/fhir/Patient/?_count=10&_format=application%2Fjson%2Bfhir&_id=-20000000002346&startIndex=0" } ], }, }, "error": { "status_code": 500, }, "duplicates": { "status_code": 200, "content": { "resourceType":"Bundle", "id":"389a548b-9c85-4491-9795-9306a957030b", "meta":{ "lastUpdated":"2019-12-18T13:40:02.792-05:00" }, "type":"searchset", "total":2, "link":[ { "relation":"first", "url":"https://sandbox.bluebutton.cms.gov/v1/fhir/Patient?_count=10&startIndex=0&_id=-20000000002346" }, { "relation":"last", "url":"https://sandbox.bluebutton.cms.gov/v1/fhir/Patient?_count=10&startIndex=0&_id=-20000000002346" }, { "relation":"self", "url":"https://sandbox.bluebutton.cms.gov/v1/fhir/Patient/?_count=10&_format=application%2Fjson%2Bfhir&_id=-20000000002346&startIndex=0" } ], "entry":[ { "resource":{ "resourceType":"Patient", "id":"-20000000002346", "extension":[ { "url":"https://bluebutton.cms.gov/resources/variables/race", "valueCoding":{ "system":"https://bluebutton.cms.gov/resources/variables/race", "code":"1", "display":"White" } } ], "identifier":[ { "system":"https://bluebutton.cms.gov/resources/variables/bene_id", "value":"-20000000002346" }, { "system":"https://bluebutton.cms.gov/resources/identifier/mbi-hash", "value":"98765432137efea543f4f370f96f1dbf01c3e3129041dba3ea43675987654321" } ], "name":[ { "use":"usual", "family":"Doe", "given":[ "John", "X" ] } ], "gender":"male", "birthDate":"2000-06-01", "address":[ { "district":"999", "state":"48", "postalCode":"99999" } ] } }, { "resource":{ "resourceType":"Patient", "id":"-20000000002346", "extension":[ { "url":"https://bluebutton.cms.gov/resources/variables/race", "valueCoding":{ "system":"https://bluebutton.cms.gov/resources/variables/race", "code":"1", "display":"White" } } ], "identifier":[ { "system":"https://bluebutton.cms.gov/resources/variables/bene_id", "value":"-20000000002346" }, { "system":"https://bluebutton.cms.gov/resources/identifier/mbi-hash", "value":"98765432137efea543f4f370f96f1dbf01c3e3129041dba3ea43675987654321" } ], "name":[ { "use":"usual", "family":"Doe", "given":[ "John", "X" ] } ], "gender":"male", "birthDate":"2000-06-01", "address":[ { "district":"999", "state":"48", "postalCode":"99999" } ] } } ] }, }, "malformed": { "status_code": 200, "content": { "resourceType":"Bundle", "id":"389a548b-9c85-4491-9795-9306a957030b", "meta":{ "lastUpdated":"2019-12-18T13:40:02.792-05:00" }, "type":"searchset", "total":1, "link":[ { "relation":"first", "url":"https://sandbox.bluebutton.cms.gov/v1/fhir/Patient?_count=10&startIndex=0&_id=-20000000002346" }, { "relation":"last", "url":"https://sandbox.bluebutton.cms.gov/v1/fhir/Patient?_count=10&startIndex=0&_id=-20000000002346" }, { "relation":"self", "url":"https://sandbox.bluebutton.cms.gov/v1/fhir/Patient/?_count=10&_format=application%2Fjson%2Bfhir&_id=-20000000002346&startIndex=0" } ], "entry":[ { "resource":{ "resourceType":"Patient", "_id":"-20000000002346", "extension":[ { "url":"https://bluebutton.cms.gov/resources/variables/race", "valueCoding":{ "system":"https://bluebutton.cms.gov/resources/variables/race", "code":"1", "display":"White" } } ], "identifier":[ { "system":"https://bluebutton.cms.gov/resources/variables/bene_id", "value":"-20000000002346" }, { "system":"https://bluebutton.cms.gov/resources/identifier/mbi-hash", "value":"98765432137efea543f4f370f96f1dbf01c3e3129041dba3ea43675987654321" } ], "name":[ { "use":"usual", "family":"Doe", "given":[ "John", "X" ] } ], "gender":"male", "birthDate":"2000-06-01", "address":[ { "district":"999", "state":"48", "postalCode":"99999" } ] } } ] }, }, "lying": { "status_code": 200, "content": { "resourceType":"Bundle", "id":"389a548b-9c85-4491-9795-9306a957030b", "meta":{ "lastUpdated":"2019-12-18T13:40:02.792-05:00" }, "type":"searchset", "total":1, "link":[ { "relation":"first", "url":"https://sandbox.bluebutton.cms.gov/v1/fhir/Patient?_count=10&startIndex=0&_id=-20000000002346" }, { "relation":"last", "url":"https://sandbox.bluebutton.cms.gov/v1/fhir/Patient?_count=10&startIndex=0&_id=-20000000002346" }, { "relation":"self", "url":"https://sandbox.bluebutton.cms.gov/v1/fhir/Patient/?_count=10&_format=application%2Fjson%2Bfhir&_id=-20000000002346&startIndex=0" } ], "entry":[ { "resource":{ "resourceType":"Patient", "id":"-20000000002346", "extension":[ { "url":"https://bluebutton.cms.gov/resources/variables/race", "valueCoding":{ "system":"https://bluebutton.cms.gov/resources/variables/race", "code":"1", "display":"White" } } ], "identifier":[ { "system":"https://bluebutton.cms.gov/resources/variables/bene_id", "value":"-20000000002346" }, { "system":"https://bluebutton.cms.gov/resources/identifier/mbi-hash", "value":"98765432137efea543f4f370f96f1dbf01c3e3129041dba3ea43675987654321" } ], "name":[ { "use":"usual", "family":"Doe", "given":[ "John", "X" ] } ], "gender":"male", "birthDate":"2000-06-01", "address":[ { "district":"999", "state":"48", "postalCode":"99999" } ] } }, { "resource":{ "resourceType":"Patient", "id":"-20000000002346", "extension":[ { "url":"https://bluebutton.cms.gov/resources/variables/race", "valueCoding":{ "system":"https://bluebutton.cms.gov/resources/variables/race", "code":"1", "display":"White" } } ], "identifier":[ { "system":"https://bluebutton.cms.gov/resources/variables/bene_id", "value":"-20000000002346" }, { "system":"https://bluebutton.cms.gov/resources/identifier/mbi-hash", "value":"98765432137efea543f4f370f96f1dbf01c3e3129041dba3ea43675987654321" } ], "name":[ { "use":"usual", "family":"Doe", "given":[ "John", "X" ] } ], "gender":"male", "birthDate":"2000-06-01", "address":[ { "district":"999", "state":"48", "postalCode":"99999" } ] } } ] }, }, }
# Problem: https://leetcode.com/problems/range-sum-query-2d-immutable/submissions/ #["NumMatrix", "sumRegion", "sumRegion", "sumRegion"] null_matrix= [[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]] row1 = 1 col1 = 2 row2 = 2 col2 = 4 # Prefix Sum of NullMatrix prefix = null_matrix[:] row = len(prefix) col = len(prefix[0]) for i in range(row): for j in range(1, col): prefix[i][j] += prefix[i][j-1] # print(prefix) for i in range(1, row): for j in range(col): prefix[i][j] += prefix[i-1][j] # print(prefix) # Answer: (area0 - area1 - area2 + common_area) # Edge cases handled with if statements area0 = prefix[row2][col2] area1 = 0 if row1 - 1 >= 0: area1 = prefix[row1-1][col2] area2 = 0 if col1 -1 >= 0: area2 = prefix[row2][col1-1] common_area = 0 if area1 > 0 and area2 > 0: common_area = prefix[row1-1][col1-1] ans = area0 - area1 - area2 + common_area print(ans) # ____________________________________________________ """ #["Matrix", "sumRegion", "sumRegion", "sumRegion"] matrix= [[3, 0, 1, 4, 2], [5, 6, 3, 2, 1], [1, 2, 0, 1, 5], [4, 1, 0, 1, 7], [1, 0, 3, 0, 5]] row1 = 2 col1 = 1 row2 = 4 col2 = 3 # Prefix Sum of Matrix row = len(matrix) col = len(matrix[0]) for i in range(row): for j in range(1, col): matrix[i][j] += matrix[i][j-1] # print(prefix) for i in range(1, row): for j in range(col): matrix[i][j] += matrix[i-1][j] # print(prefix) # Answer: (area0 - area1 - area2 + common_area) # Edge cases exists: handled with if statements area0 = matrix[row2][col2] area1 = 0 if row1 - 1 >= 0: area1 = matrix[row1-1][col2] area2 = 0 if col1 -1 >= 0: area2 = matrix[row2][col1-1] common_area = 0 if area1 > 0 and area2 > 0: common_area = matrix[row1-1][col1-1] ans = area0 - area1 - area2 + common_area print(ans) """
def log_info(func): def wrapper(): print("Wywołuję funkcję...") func() print("Już po wszystkim :)") return wrapper def say_hello(): print("Hello World!") def run_example(): say_hello_with_log_info = log_info(say_hello) say_hello_with_log_info() if __name__ == '__main__': run_example()
__version__ = "3.0.0-beta" VERSION = __version__ DOMAIN = "krisinfo" BASE_URL = "https://api.krisinformation.se/v3/" NEWS_PARAMETER = "news?format=json" VMAS_PARAMETER = "vmas?format=json" LANGUAGE_PARAMETER = "&language=" USER_AGENT = "homeassistant_krisinfo/" + VERSION
# Road of Regrets 2 (270020200) => Resting Spot of Regret # The One Who Walks Down the Road of Regrets2 if sm.hasQuestCompleted(3509): sm.warp(270020210, 3) else: sm.chat("Those who do not have the Goddess' permission may not move against the flow of time, and will be sent back to their previous location.") sm.warp(270020100)
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Created by tianhao.wang at 9/6/18 """
class Solution(object): def climbStairs(self, n): """ :type n: int :rtype: int """ if n <= 2: return n pre1 = 2 pre2 = 1 cur = 0 while(n>2): cur = pre1 + pre2 pre2 = pre1 pre1 = cur n -= 1 return cur
"""Constants for the AlarmDecoder component.""" CONF_ALT_NIGHT_MODE = "alt_night_mode" CONF_AUTO_BYPASS = "auto_bypass" CONF_CODE_ARM_REQUIRED = "code_arm_required" CONF_DEVICE_BAUD = "device_baudrate" CONF_DEVICE_PATH = "device_path" CONF_RELAY_ADDR = "zone_relayaddr" CONF_RELAY_CHAN = "zone_relaychan" CONF_ZONE_LOOP = "zone_loop" CONF_ZONE_NAME = "zone_name" CONF_ZONE_NUMBER = "zone_number" CONF_ZONE_RFID = "zone_rfid" CONF_ZONE_TYPE = "zone_type" DATA_AD = "alarmdecoder" DATA_REMOVE_STOP_LISTENER = "rm_stop_listener" DATA_REMOVE_UPDATE_LISTENER = "rm_update_listener" DATA_RESTART = "restart" DEFAULT_ALT_NIGHT_MODE = False DEFAULT_AUTO_BYPASS = False DEFAULT_CODE_ARM_REQUIRED = True DEFAULT_DEVICE_BAUD = 115200 DEFAULT_DEVICE_HOST = "alarmdecoder" DEFAULT_DEVICE_PATH = "/dev/ttyUSB0" DEFAULT_DEVICE_PORT = 10000 DEFAULT_ZONE_TYPE = "window" DEFAULT_ARM_OPTIONS = { CONF_ALT_NIGHT_MODE: DEFAULT_ALT_NIGHT_MODE, CONF_AUTO_BYPASS: DEFAULT_AUTO_BYPASS, CONF_CODE_ARM_REQUIRED: DEFAULT_CODE_ARM_REQUIRED, } DEFAULT_ZONE_OPTIONS: dict = {} DOMAIN = "alarmdecoder" OPTIONS_ARM = "arm_options" OPTIONS_ZONES = "zone_options" PROTOCOL_SERIAL = "serial" PROTOCOL_SOCKET = "socket" SIGNAL_PANEL_MESSAGE = "alarmdecoder.panel_message" SIGNAL_REL_MESSAGE = "alarmdecoder.rel_message" SIGNAL_RFX_MESSAGE = "alarmdecoder.rfx_message" SIGNAL_ZONE_FAULT = "alarmdecoder.zone_fault" SIGNAL_ZONE_RESTORE = "alarmdecoder.zone_restore"
# Collaborators (including web sites where you got help: (enter none if you didn't need help) # # Write a program that asks for the user's name and another piece of information.Then prints a response using both of the inputs. x = input("What is your name?") y = input("How old are you?") print("Hello " + x + ", you are " + y + " years old.")
_base_ = './upernet_vit-b16_mln_512x512_160k_ade20k.py' model = dict( pretrained='pretrain/deit_base_patch16_224-b5f2ef4d.pth', backbone=dict(drop_path_rate=0.1), )
#!/usr/bin/env python3 """Error exceptions.""" class InputError(Exception): """Raised on invalid user input."""
#coding=utf-8 ''' Created on 2015-10-10 @author: Devuser ''' class Tag(object): def __init__(self,tagid,name,color): self.tagid=tagid self.tagname=name self.tagcolor=color
def log(str): ENABLED = False # Set False to disable loggin if ENABLED: print(str)
# add 6 _ name = 'Mark' align_right = f'{name:_>10}' print(align_right) # '______Mark'
def main(n): ret = 1 while 1: if n == 1: break n = (n // 2, 3 * n + 1)[n & 1] ret += 1 return ret if __name__ == '__main__': print(main(int(input())))
t = '########### ###########\n########## ##########\n######### #########\n######## ########\n####### #######\n###### ######\n##### #####\n#### ####\n### ###\n## ##\n# #\n \n' def invert_triangle(t): temp = t.replace(" ","a") temp = temp.replace("#"," ") temp = temp.replace("a","#") return("\n".join(temp.split('\n')[-1::-1]))
""" Copyright (C) 2015, MuChu Hsu Contributed by Muchu Hsu ([email protected]) This file is part of BSD license <https://opensource.org/licenses/BSD-3-Clause> """
# # PySNMP MIB module CISCO-EPM-NOTIFICATION-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-EPM-NOTIFICATION-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:40:04 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsIntersection, SingleValueConstraint, ConstraintsUnion, ValueRangeConstraint, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "SingleValueConstraint", "ConstraintsUnion", "ValueRangeConstraint", "ValueSizeConstraint") ciscoMgmt, = mibBuilder.importSymbols("CISCO-SMI", "ciscoMgmt") InetAddressType, InetAddress = mibBuilder.importSymbols("INET-ADDRESS-MIB", "InetAddressType", "InetAddress") SnmpAdminString, = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString") ModuleCompliance, ObjectGroup, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "ObjectGroup", "NotificationGroup") MibIdentifier, Unsigned32, MibScalar, MibTable, MibTableRow, MibTableColumn, Counter64, Bits, TimeTicks, Counter32, Gauge32, ModuleIdentity, ObjectIdentity, NotificationType, Integer32, IpAddress, iso = mibBuilder.importSymbols("SNMPv2-SMI", "MibIdentifier", "Unsigned32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Counter64", "Bits", "TimeTicks", "Counter32", "Gauge32", "ModuleIdentity", "ObjectIdentity", "NotificationType", "Integer32", "IpAddress", "iso") DisplayString, TimeStamp, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TimeStamp", "TextualConvention") ciscoEpmNotificationMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 9, 9, 311)) ciscoEpmNotificationMIB.setRevisions(('2004-06-07 00:00', '2003-08-21 00:00', '2002-07-28 14:20',)) if mibBuilder.loadTexts: ciscoEpmNotificationMIB.setLastUpdated('200406070000Z') if mibBuilder.loadTexts: ciscoEpmNotificationMIB.setOrganization('Cisco Systems, Inc.') ciscoEpmNotificationMIBNotifs = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 311, 0)) ciscoEpmNotificationMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 311, 1)) ciscoEpmNotificationMIBConform = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 311, 2)) cenAlarmData = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 311, 1, 1)) cenAlarmTableMaxLength = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 311, 1, 1, 1), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1, 4294967295)).clone(1)).setMaxAccess("readwrite") if mibBuilder.loadTexts: cenAlarmTableMaxLength.setStatus('current') cenAlarmTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 311, 1, 1, 2), ) if mibBuilder.loadTexts: cenAlarmTable.setStatus('current') cenAlarmEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 311, 1, 1, 2, 1), ).setIndexNames((0, "CISCO-EPM-NOTIFICATION-MIB", "cenAlarmIndex")) if mibBuilder.loadTexts: cenAlarmEntry.setStatus('current') cenAlarmIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 311, 1, 1, 2, 1, 1), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1, 4294967295))) if mibBuilder.loadTexts: cenAlarmIndex.setStatus('current') cenAlarmVersion = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 311, 1, 1, 2, 1, 2), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 16))).setMaxAccess("readonly") if mibBuilder.loadTexts: cenAlarmVersion.setStatus('current') cenAlarmTimestamp = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 311, 1, 1, 2, 1, 3), TimeStamp()).setMaxAccess("readonly") if mibBuilder.loadTexts: cenAlarmTimestamp.setStatus('current') cenAlarmUpdatedTimestamp = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 311, 1, 1, 2, 1, 4), TimeStamp()).setMaxAccess("readonly") if mibBuilder.loadTexts: cenAlarmUpdatedTimestamp.setStatus('current') cenAlarmInstanceID = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 311, 1, 1, 2, 1, 5), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 20))).setMaxAccess("readonly") if mibBuilder.loadTexts: cenAlarmInstanceID.setStatus('current') cenAlarmStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 311, 1, 1, 2, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 250))).setMaxAccess("readonly") if mibBuilder.loadTexts: cenAlarmStatus.setStatus('current') cenAlarmStatusDefinition = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 311, 1, 1, 2, 1, 7), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 255))).setMaxAccess("readonly") if mibBuilder.loadTexts: cenAlarmStatusDefinition.setStatus('current') cenAlarmType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 311, 1, 1, 2, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("unknown", 1), ("direct", 2), ("indirect", 3), ("mixed", 4)))).setMaxAccess("readonly") if mibBuilder.loadTexts: cenAlarmType.setStatus('current') cenAlarmCategory = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 311, 1, 1, 2, 1, 9), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 250))).setMaxAccess("readonly") if mibBuilder.loadTexts: cenAlarmCategory.setStatus('current') cenAlarmCategoryDefinition = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 311, 1, 1, 2, 1, 10), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 255))).setMaxAccess("readonly") if mibBuilder.loadTexts: cenAlarmCategoryDefinition.setStatus('current') cenAlarmServerAddressType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 311, 1, 1, 2, 1, 11), InetAddressType()).setMaxAccess("readonly") if mibBuilder.loadTexts: cenAlarmServerAddressType.setStatus('current') cenAlarmServerAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 311, 1, 1, 2, 1, 12), InetAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: cenAlarmServerAddress.setStatus('current') cenAlarmManagedObjectClass = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 311, 1, 1, 2, 1, 13), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 255))).setMaxAccess("readonly") if mibBuilder.loadTexts: cenAlarmManagedObjectClass.setStatus('current') cenAlarmManagedObjectAddressType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 311, 1, 1, 2, 1, 14), InetAddressType()).setMaxAccess("readonly") if mibBuilder.loadTexts: cenAlarmManagedObjectAddressType.setStatus('current') cenAlarmManagedObjectAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 311, 1, 1, 2, 1, 15), InetAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: cenAlarmManagedObjectAddress.setStatus('current') cenAlarmDescription = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 311, 1, 1, 2, 1, 16), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 1024))).setMaxAccess("readonly") if mibBuilder.loadTexts: cenAlarmDescription.setStatus('current') cenAlarmSeverity = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 311, 1, 1, 2, 1, 17), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 100))).setMaxAccess("readonly") if mibBuilder.loadTexts: cenAlarmSeverity.setStatus('current') cenAlarmSeverityDefinition = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 311, 1, 1, 2, 1, 18), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 255))).setMaxAccess("readonly") if mibBuilder.loadTexts: cenAlarmSeverityDefinition.setStatus('current') cenAlarmTriageValue = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 311, 1, 1, 2, 1, 19), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 100))).setMaxAccess("readonly") if mibBuilder.loadTexts: cenAlarmTriageValue.setStatus('current') cenEventIDList = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 311, 1, 1, 2, 1, 20), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 1024))).setMaxAccess("readonly") if mibBuilder.loadTexts: cenEventIDList.setStatus('current') cenUserMessage1 = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 311, 1, 1, 2, 1, 21), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 255))).setMaxAccess("readonly") if mibBuilder.loadTexts: cenUserMessage1.setStatus('current') cenUserMessage2 = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 311, 1, 1, 2, 1, 22), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 255))).setMaxAccess("readonly") if mibBuilder.loadTexts: cenUserMessage2.setStatus('current') cenUserMessage3 = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 311, 1, 1, 2, 1, 23), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 255))).setMaxAccess("readonly") if mibBuilder.loadTexts: cenUserMessage3.setStatus('current') cenAlarmMode = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 311, 1, 1, 2, 1, 24), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("unknown", 1), ("alert", 2), ("event", 3)))).setMaxAccess("readonly") if mibBuilder.loadTexts: cenAlarmMode.setStatus('current') cenPartitionNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 311, 1, 1, 2, 1, 25), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(0, 100))).setMaxAccess("readonly") if mibBuilder.loadTexts: cenPartitionNumber.setStatus('current') cenPartitionName = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 311, 1, 1, 2, 1, 26), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 255))).setMaxAccess("readonly") if mibBuilder.loadTexts: cenPartitionName.setStatus('current') cenCustomerIdentification = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 311, 1, 1, 2, 1, 27), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 255))).setMaxAccess("readonly") if mibBuilder.loadTexts: cenCustomerIdentification.setStatus('current') cenCustomerRevision = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 311, 1, 1, 2, 1, 28), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 255))).setMaxAccess("readonly") if mibBuilder.loadTexts: cenCustomerRevision.setStatus('current') cenAlertID = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 311, 1, 1, 2, 1, 29), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 20))).setMaxAccess("readonly") if mibBuilder.loadTexts: cenAlertID.setStatus('current') ciscoEpmNotificationAlarm = NotificationType((1, 3, 6, 1, 4, 1, 9, 9, 311, 0, 1)).setObjects(("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmVersion"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmTimestamp"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmUpdatedTimestamp"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmInstanceID"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmStatus"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmStatusDefinition"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmType"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmCategory"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmCategoryDefinition"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmServerAddressType"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmServerAddress"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmManagedObjectClass"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmManagedObjectAddressType"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmManagedObjectAddress"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmDescription"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmSeverity"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmSeverityDefinition"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmTriageValue"), ("CISCO-EPM-NOTIFICATION-MIB", "cenEventIDList"), ("CISCO-EPM-NOTIFICATION-MIB", "cenUserMessage1"), ("CISCO-EPM-NOTIFICATION-MIB", "cenUserMessage2"), ("CISCO-EPM-NOTIFICATION-MIB", "cenUserMessage3")) if mibBuilder.loadTexts: ciscoEpmNotificationAlarm.setStatus('deprecated') ciscoEpmNotificationAlarmRev1 = NotificationType((1, 3, 6, 1, 4, 1, 9, 9, 311, 0, 2)).setObjects(("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmVersion"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmTimestamp"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmUpdatedTimestamp"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmInstanceID"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmStatus"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmStatusDefinition"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmType"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmCategory"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmCategoryDefinition"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmServerAddressType"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmServerAddress"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmManagedObjectClass"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmManagedObjectAddressType"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmManagedObjectAddress"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmDescription"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmSeverity"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmSeverityDefinition"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmTriageValue"), ("CISCO-EPM-NOTIFICATION-MIB", "cenEventIDList"), ("CISCO-EPM-NOTIFICATION-MIB", "cenUserMessage1"), ("CISCO-EPM-NOTIFICATION-MIB", "cenUserMessage2"), ("CISCO-EPM-NOTIFICATION-MIB", "cenUserMessage3"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmMode"), ("CISCO-EPM-NOTIFICATION-MIB", "cenPartitionNumber"), ("CISCO-EPM-NOTIFICATION-MIB", "cenPartitionName"), ("CISCO-EPM-NOTIFICATION-MIB", "cenCustomerIdentification"), ("CISCO-EPM-NOTIFICATION-MIB", "cenCustomerRevision"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlertID")) if mibBuilder.loadTexts: ciscoEpmNotificationAlarmRev1.setStatus('current') ciscoEpmNotificationMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 311, 2, 1)) ciscoEpmNotificationMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 311, 2, 2)) ciscoEpmNotificationMIBCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 311, 2, 1, 1)).setObjects(("CISCO-EPM-NOTIFICATION-MIB", "ciscoEpmNotificationObjectsGroup"), ("CISCO-EPM-NOTIFICATION-MIB", "ciscoEpmNotificationAlarmGroup"), ("CISCO-EPM-NOTIFICATION-MIB", "ciscoEpmAlarmConfigGroup")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoEpmNotificationMIBCompliance = ciscoEpmNotificationMIBCompliance.setStatus('deprecated') ciscoEpmNotificationMIBComplianceRev1 = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 311, 2, 1, 1, 2)).setObjects(("CISCO-EPM-NOTIFICATION-MIB", "ciscoEpmNotificationObjectsGroupRev1"), ("CISCO-EPM-NOTIFICATION-MIB", "ciscoEpmNotificationAlarmGroupRev1"), ("CISCO-EPM-NOTIFICATION-MIB", "ciscoEpmAlarmConfigGroup")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoEpmNotificationMIBComplianceRev1 = ciscoEpmNotificationMIBComplianceRev1.setStatus('current') ciscoEpmNotificationAlarmGroup = NotificationGroup((1, 3, 6, 1, 4, 1, 9, 9, 311, 2, 2, 1)).setObjects(("CISCO-EPM-NOTIFICATION-MIB", "ciscoEpmNotificationAlarm")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoEpmNotificationAlarmGroup = ciscoEpmNotificationAlarmGroup.setStatus('deprecated') ciscoEpmNotificationObjectsGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 311, 2, 2, 2)).setObjects(("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmVersion"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmTimestamp"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmUpdatedTimestamp"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmInstanceID"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmStatus"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmStatusDefinition"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmType"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmCategory"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmCategoryDefinition"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmServerAddressType"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmServerAddress"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmManagedObjectClass"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmManagedObjectAddressType"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmManagedObjectAddress"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmDescription"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmSeverity"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmSeverityDefinition"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmTriageValue"), ("CISCO-EPM-NOTIFICATION-MIB", "cenEventIDList"), ("CISCO-EPM-NOTIFICATION-MIB", "cenUserMessage1"), ("CISCO-EPM-NOTIFICATION-MIB", "cenUserMessage2"), ("CISCO-EPM-NOTIFICATION-MIB", "cenUserMessage3")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoEpmNotificationObjectsGroup = ciscoEpmNotificationObjectsGroup.setStatus('deprecated') ciscoEpmAlarmConfigGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 311, 2, 2, 3)).setObjects(("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmTableMaxLength")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoEpmAlarmConfigGroup = ciscoEpmAlarmConfigGroup.setStatus('current') ciscoEpmNotificationAlarmGroupRev1 = NotificationGroup((1, 3, 6, 1, 4, 1, 9, 9, 311, 2, 2, 4)).setObjects(("CISCO-EPM-NOTIFICATION-MIB", "ciscoEpmNotificationAlarmRev1")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoEpmNotificationAlarmGroupRev1 = ciscoEpmNotificationAlarmGroupRev1.setStatus('current') ciscoEpmNotificationObjectsGroupRev1 = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 311, 2, 2, 5)).setObjects(("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmVersion"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmTimestamp"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmUpdatedTimestamp"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmInstanceID"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmStatus"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmStatusDefinition"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmType"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmCategory"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmCategoryDefinition"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmServerAddressType"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmServerAddress"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmManagedObjectClass"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmManagedObjectAddressType"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmManagedObjectAddress"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmDescription"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmSeverity"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmSeverityDefinition"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmTriageValue"), ("CISCO-EPM-NOTIFICATION-MIB", "cenEventIDList"), ("CISCO-EPM-NOTIFICATION-MIB", "cenUserMessage1"), ("CISCO-EPM-NOTIFICATION-MIB", "cenUserMessage2"), ("CISCO-EPM-NOTIFICATION-MIB", "cenUserMessage3"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlarmMode"), ("CISCO-EPM-NOTIFICATION-MIB", "cenPartitionNumber"), ("CISCO-EPM-NOTIFICATION-MIB", "cenPartitionName"), ("CISCO-EPM-NOTIFICATION-MIB", "cenCustomerIdentification"), ("CISCO-EPM-NOTIFICATION-MIB", "cenCustomerRevision"), ("CISCO-EPM-NOTIFICATION-MIB", "cenAlertID")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoEpmNotificationObjectsGroupRev1 = ciscoEpmNotificationObjectsGroupRev1.setStatus('current') mibBuilder.exportSymbols("CISCO-EPM-NOTIFICATION-MIB", ciscoEpmNotificationMIB=ciscoEpmNotificationMIB, cenAlarmIndex=cenAlarmIndex, cenAlarmDescription=cenAlarmDescription, cenAlarmManagedObjectAddressType=cenAlarmManagedObjectAddressType, cenAlarmTriageValue=cenAlarmTriageValue, cenAlarmManagedObjectAddress=cenAlarmManagedObjectAddress, ciscoEpmNotificationMIBComplianceRev1=ciscoEpmNotificationMIBComplianceRev1, cenAlarmTable=cenAlarmTable, cenAlarmSeverity=cenAlarmSeverity, cenAlarmInstanceID=cenAlarmInstanceID, cenAlarmEntry=cenAlarmEntry, cenPartitionNumber=cenPartitionNumber, cenPartitionName=cenPartitionName, ciscoEpmNotificationAlarmGroupRev1=ciscoEpmNotificationAlarmGroupRev1, cenUserMessage2=cenUserMessage2, ciscoEpmNotificationMIBCompliance=ciscoEpmNotificationMIBCompliance, cenAlarmStatusDefinition=cenAlarmStatusDefinition, ciscoEpmNotificationMIBObjects=ciscoEpmNotificationMIBObjects, ciscoEpmNotificationObjectsGroup=ciscoEpmNotificationObjectsGroup, cenUserMessage1=cenUserMessage1, cenAlarmData=cenAlarmData, cenAlarmVersion=cenAlarmVersion, cenUserMessage3=cenUserMessage3, ciscoEpmNotificationObjectsGroupRev1=ciscoEpmNotificationObjectsGroupRev1, ciscoEpmNotificationAlarm=ciscoEpmNotificationAlarm, cenCustomerIdentification=cenCustomerIdentification, ciscoEpmNotificationAlarmGroup=ciscoEpmNotificationAlarmGroup, cenCustomerRevision=cenCustomerRevision, ciscoEpmAlarmConfigGroup=ciscoEpmAlarmConfigGroup, ciscoEpmNotificationMIBCompliances=ciscoEpmNotificationMIBCompliances, cenAlarmManagedObjectClass=cenAlarmManagedObjectClass, ciscoEpmNotificationMIBGroups=ciscoEpmNotificationMIBGroups, cenAlarmCategoryDefinition=cenAlarmCategoryDefinition, cenAlarmMode=cenAlarmMode, ciscoEpmNotificationAlarmRev1=ciscoEpmNotificationAlarmRev1, cenAlarmTableMaxLength=cenAlarmTableMaxLength, cenAlarmStatus=cenAlarmStatus, cenAlarmServerAddress=cenAlarmServerAddress, cenAlarmSeverityDefinition=cenAlarmSeverityDefinition, ciscoEpmNotificationMIBNotifs=ciscoEpmNotificationMIBNotifs, cenAlarmType=cenAlarmType, cenEventIDList=cenEventIDList, cenAlarmTimestamp=cenAlarmTimestamp, ciscoEpmNotificationMIBConform=ciscoEpmNotificationMIBConform, PYSNMP_MODULE_ID=ciscoEpmNotificationMIB, cenAlarmServerAddressType=cenAlarmServerAddressType, cenAlertID=cenAlertID, cenAlarmUpdatedTimestamp=cenAlarmUpdatedTimestamp, cenAlarmCategory=cenAlarmCategory)
# Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Represent the interface for Query. This is important because our access control logic needs a unified way to specify conditions for both BigQuery query and Datastore query. This must be compatible with libs.filters and libs.crash_access.""" class Query(object): """Represent the interface for Query.""" def filter(self, field, value, operator='='): """Filter by a single value.""" raise NotImplementedError def filter_in(self, field, values): """Filter by multiple values.""" raise NotImplementedError def union(self, *queries): """Union all queries with OR conditions.""" raise NotImplementedError def new_subquery(self): """Instantiate a query that is compatible with the current query.""" raise NotImplementedError
# coding=utf8 # Copyright 2018 JDCLOUD.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. # # NOTE: This class is auto generated by the jdcloud code generator program. class AppInfoObject(object): def __init__(self, appId=None, appName=None, status=None, roomType=None, billType=None, createTime=None): """ :param appId: (Optional) 应用ID :param appName: (Optional) 应用名称 :param status: (Optional) 应用状态: OPEN-启用, CLOSE-停用 :param roomType: (Optional) 应用默认创建的房间类型 1-小房间;2-大房间 :param billType: (Optional) 计费类型: Duration-按时长 :param createTime: (Optional) 创建时间(UTC) """ self.appId = appId self.appName = appName self.status = status self.roomType = roomType self.billType = billType self.createTime = createTime
# Project Euler - Problem 9 # Aidan O'Connor_G00364756_01/03/2018 # A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, # a^2 + b^2 = c^2 # For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2. # There exists exactly one Pythagorean triplet for which a + b + c = 1000. # Find the product abc. def Ptriplet(number): """Returns the Pythagorean triplet for which a + b + c = 1000""" m = 3 limit = 1000 for a in range(m,500,1): for b in range(a,500,1): for c in range (b,500,1): ram = a + b + c zig = a**2 zag = b**2 zigzag = zig + zag bag = c**2 if ram == limit and zigzag == bag and a < b: return (a, b, c) ans = Ptriplet(1) print(ans)
# # Copyright (C) 2019 Databricks, 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. # """ Exceptions/Errors used in databricks-koalas. """ class SparkPandasIndexingError(Exception): pass def code_change_hint(pandas_function, spark_target_function): if pandas_function is not None and spark_target_function is not None: return "You are trying to use pandas function {}, use spark function {}" \ .format(pandas_function, spark_target_function) elif pandas_function is not None and spark_target_function is None: return ("You are trying to use pandas function {}, checkout the spark " "user guide to find a relevant function").format(pandas_function) elif pandas_function is None and spark_target_function is not None: return "Use spark function {}".format(spark_target_function) else: # both none return "Checkout the spark user guide to find a relevant function" class SparkPandasNotImplementedError(NotImplementedError): def __init__(self, pandas_function=None, spark_target_function=None, description=""): self.pandas_source = pandas_function self.spark_target = spark_target_function hint = code_change_hint(pandas_function, spark_target_function) if len(description) > 0: description += " " + hint else: description = hint super(SparkPandasNotImplementedError, self).__init__(description) class PandasNotImplementedError(NotImplementedError): def __init__(self, class_name, method_name, arg_name=None): self.class_name = class_name self.method_name = method_name self.arg_name = arg_name if arg_name is not None: msg = "The method `{0}.{1}()` does not support `{2}` parameter" \ .format(class_name, method_name, arg_name) else: msg = "The method `{0}.{1}()` is not implemented yet.".format(class_name, method_name) super(NotImplementedError, self).__init__(msg)
'''https: // practice.geeksforgeeks.org/problems/permutations-of-a-given-string2041/1 Permutations of a given string Basic Accuracy: 49.85 % Submissions: 31222 Points: 1 Given a string S. The task is to print all permutations of a given string. Example 1: Input: ABC Output: ABC ACB BAC BCA CAB CBA Explanation: Given string ABC has permutations in 6 forms as ABC, ACB, BAC, BCA, CAB and CBA . Example 2: Input: ABSG Output: ABGS ABSG AGBS AGSB ASBG ASGB BAGS BASG BGAS BGSA BSAG BSGA GABS GASB GBAS GBSA GSAB GSBA SABG SAGB SBAG SBGA SGAB SGBA Explanation: Given string ABSG has 24 permutations. Your Task: You don't need to read input or print anything. Your task is to complete the function find_permutaion() which takes the string S as input parameter and returns a vector of string in lexicographical order. Expected Time Complexity: O(n! * n) Expected Space Complexity: O(n) Constraints: 1 <= length of string <= 5 ''' class Solution: def permute(self, curr, S, N, words=[]): if(len(curr) == N): words.append(curr) return for ch in S: self.permute(curr+ch, S.replace(ch, ""), N, words) def find_permutation(self, S): words = [] N = len(S) self.permute("", ''.join(sorted(S)), N, words) return words class Solution: def find_permutation(self, S): # Code here l = [S[-1]] for i in S[0:len(S)-1]: l1 = [] for x in l: for j in range(0, len(x)+1): l1.append(x[0:j]+i+x[j:len(x)]) l = l1 return sorted(l)
class TreeNode: """Definition for a binary tree node.""" def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def is_balanced(self, root: TreeNode) -> bool: return self.depth(root) != -1 def depth(self, node: TreeNode) -> int: if not node: return 0 else: left_depth = self.depth(node.left) right_depth = self.depth(node.right) if -1 == left_depth or -1 == right_depth or abs(left_depth - right_depth) > 1: return -1 else: return max(left_depth, right_depth) + 1
s = input() y = s[0] w = s[2] if int(y) > int(w): p = 7 - int(y) else: p = 7 - int(w) if p == 1: print('1/6') if p == 2: print('1/3') if p == 3: print('1/2') if p == 4: print('2/3') if p == 5: print('5/6') if p == 6: print('1/1')
# -*- coding: utf-8 -*- """ Jokes from stackoverflow - provided under CC BY-SA 3.0 http://stackoverflow.com/questions/234075/what-is-your-best-programmer-joke?page=4&tab=votes#tab-top """ neutral = [ "Trionfalmente, Beth ha rimosso Python 2.7 dal server nel 2020.'Finalmente!' ha detto con gioia, solo per vedere l'annuncio di Python 4.4.", "Una query SQL entra in un bar, cammina verso a due table e chiede: 'Posso unirvi?'.", "Quando il tuo martello e` C ++, tutto inizia a sembrare un pollice.", "Se metti un milione di scimmie su un milione di tastiere, uno di loro alla fine scrivera` un programma Java, il resto scrivera` Perl.", "Per comprendere la ricorsione devi prima capire la ricorsione.", "Gli amici non permettono agli amici di usare Python 2.7.", "Ho suggerito di tenere un 'Python Object Oriented Programming Seminar', ma l'acronimo era impopolare.", "'toc, toc'. 'Chi e` la`?' ... pausa molto lunga ... Java.", "Quanti programmatori ci vogliono per cambiare una lampadina? Nessuno, e` un problema hardware.", "Qual e` il modo orientato agli oggetti per diventare ricchi? Ereditarieta`.", "Quanti programmatori ci vogliono per cambiare una lampadina? Nessuno, possono rendere l'oscurita` uno standard.", "I vecchi programmatori C non muoiono, sono solo gettati nel void.", "Gli sviluppatori di software amano risolvere i problemi: se non ci sono problemi facilmente disponibili li creeranno.", ".NET e` stato chiamato .NET in modo che non si visualizzasse in un elenco di directory Unix.", "Hardware: la parte di un computer che puoi calciare.", "Un programmatore e` stato trovato morto nella doccia, accanto al corpo c'era uno shampoo con le istruzioni:Insapona, risciacqua ripeti.", "Ottimista: il bicchiere e` mezzo pieno Pessimista: il bicchiere e` mezzo vuoto Programmatore: il bicchiere e` il doppio del necessario.", "In C abbiamo dovuto codificare i nostri bug. In C ++ possiamo ereditarli.", "Come mai non c'e` una gara Perl offuscato? Perche` tutti vincerebbero.", "Se riproduci un CD di Windows all'indietro, ascolterai il canto satanico ... peggio ancora, se lo riproduci in avanti, installa Windows.", "Quanti programmatori ci vogliono per uccidere uno scarafaggio? Due: uno tiene, l'altro installa Windows su di esso.", "Come si chiama un programmatore finlandese? Nerdic.", "Cosa ha detto il codice Java al codice C? : Non hai classe.", "Perche` Microsoft ha chiamato il proprio motore di ricerca BING? Because It's Not Google.", "I venditori di software e i venditori di auto usate si differenziano perche` questi ultimi sanno quando mentono.", "Bambino: 'papa', perche` il sole sorge ad est e tramonta ad ovest?' Papa': 'figlio, sta funzionando, non toccarlo'.", "Quanti programmatori Prolog ci vogliono per cambiare una lampadina? Falso.", "I veri programmatori possono scrivere codice assembly in qualsiasi lingua.", "Cameriere: 'le piacerebbe un caffe` o un te`?' Programmatore: 'Si'.", "Un programmatore entra in un foo ...", "Qual e` il secondo nome di Benoit B. Mandelbrot? Benoit B. Mandelbrot.", "Perche` sorridi sempre? Questa e` solo la mia ... espressione regolare.", "Domanda stupida ASCII, ottiene uno stupido ANSI.", "Un programmatore aveva un problema: penso` tra se stesso: 'lo risolvo con i threads!', ora ha due problemi.", "Java: scrivi una volta e scappa.", "Ti direi una battuta su UDP, ma non lo capiresti mai.", "Un ingegnere di QA entra in un bar, si imbatte in un bar, striscia in un bar, balla in un bar, punta i piedi in un bar...", "Ho avuto un problema quindi ho pensato di utilizzare Java. Ora ho una ProblemFactory.", "L'ingegnere del QA entra in un bar, ordina una birra, ordina 0 birre, 99999 birre, una lucertola, -1 birre, uno sfdeljknesv.", "Un responsabile di prodotto entra in un bar, chiede un drink, il barista dice NO, ma prendera` in considerazione l'aggiunta successiva.", "Come si genera una stringa casuale? Metti uno studente di Informatica del primo anno davanti a Vim e gli chiedi di salvare ed uscire.", "Uso Vim da molto tempo ormai, principalmente perche` non riesco a capire come uscire.", "Come fai a sapere se una persona e` un utente Vim? Non ti preoccupare, te lo diranno.", "un cameriere urla: 'sta soffocando! Qualcuno e` un dottore?' Programmatore: 'sono un utente Vim'.", "3 Database Admins sono entrati in un bar NoSQL e poco dopo sono usciti perche` non sono riusciti a trovare un table.", "Come spiegare il film Inception a un programmatore? Quando esegui una VM dentro una VM dentro un' altra VM tutto procede molto lentamente.", "Come si chiama un pappagallo che dice 'Squawk! Pezzi di nove! Pezzi di nove!' Un errore a pappagallo.", "Ci sono solo due problemi difficili in Informatica: invalidazione della cache, denominazione delle cose e errori di off-by-one.", "Ci sono 10 tipi di persone: quelli che comprendono il binario e quelli che non lo sanno.", "Ci sono 2 tipi di persone: quelli che possono estrapolare dati da insiemi incompleti ...", "Esistono II tipi di persone: quelli che comprendono i numeri romani e quelli che non li conoscono.", "Ci sono 10 tipi di persone: quelli che comprendono l'esadecimale e altri 15.", "Ci sono 10 tipi di persone: quelli che capiscono il trinario, quelli che non lo fanno e quelli che non ne hanno mai sentito parlare.", "Come chiami otto hobbit? Un hob byte.", "La cosa migliore di un booleano e` che anche se ti sbagli, sei solo fuori di un bit.", "Un buon programmatore e` qualcuno che guarda sempre in entrambe le direzioni prima di attraversare una strada a senso unico.", "Esistono due modi per scrivere programmi privi di errori: solo il terzo funziona.", "I controlli di qualita` consistono nel 55% di acqua, 30% di sangue e 15% di ticket in Jira.", "Quanti QA servono per cambiare una lampadina? Hanno notato che la stanza era buia,: non risolvono i problemi, li trovano.", "Un programmatore si schianta contro un'auto , l'uomo chiede 'cosa e` successo', l'altro risponde'Non so. Facciamo il backup e riprova'.", "Scrivere PHP e` come fare pipi` in piscina, tutti lo hanno fatto, ma non hanno bisogno di renderlo pubblico.", "Numero di giorni da quando ho riscontrato un errore di indice di array: -1.", "gli appuntamenti veloci sono inutili, 5 minuti non sono sufficienti per spiegare correttamente i benefici della filosofia Unix.", "Microsoft ha ogni quindici giorni una 'settimana produttiva' dove usa Google invece di Bing.", "Trovare un buon sviluppatore PHP e` come cercare un ago in un pagliaio o e` un hackstack in un ago?.", "Unix e` user friendly, e` solo molto particolare nella scelta di chi siano i suoi amici.", "Un programmatore COBOL guadagna milioni con la riparazione Y2K e decide di congelarsi criogenicamente. L'anno e` 9999.", "Il linguaggio C combina tutta la potenza del linguaggio assembly con tutta la facilita` d'uso del linguaggio assembly.", "Un esperto SEO entra in un bar, pub, pub irlandese, taverna, barista, birra, liquore, vino, alcolici, liquori ...", "Che cosa significa Emacs? Utilizzato esclusivamente dagli scienziati informatici di mezza eta`.", "Che cosa hanno in comune le battute di PyJokes con Adobe Flash? Si aggiornano sempre, ma non migliorano.", "Quanti demosceners sono necessari per cambiare una lampadina? Meta`. Con uno intero non ci sono sfide.", ] """ Jokes from The Internet Chuck Norris DB (ICNDB) (http://www.icndb.com/) - provided under CC BY-SA 3.0 http://api.icndb.com/jokes/ """ chuck = [ "Tutti gli array che Chuck Norris dichiara sono di dimensioni infinite, perche` Chuck Norris non conosce limiti.", "Chuck Norris non ha la latenza del disco perche` il disco rigido sa sbrigarsi, altrimenti sono guai.", "Chuck Norris scrive codice che si ottimizza da solo.", "Chuck Norris non puo` testare l'uguaglianza perche` non ha eguali.", "Chuck Norris non ha bisogno di garbage collection perche` non chiama .Dispose (), chiama .DropKick ().", "Il primo programma di Chuck Norris e` stato kill -9.", "Chuck Norris ha scoppiato la bolla delle dot com.", "Tutti i browser supportano le definizioni esadecimali #chuck e #norris per i colori nero e blu.", "MySpace non e` proprio il tuo spazio, e` di Chuck (te lo lascia solo usare).", "Chuck Norris puo` scrivere funzioni infinitamente ricorsive e farle tornare.", "Chuck Norris puo` risolvere le Torri di Hanoi in una mossa.", "L'unico modello di design che Chuck Norris conosce e` il God Object Pattern.", "Chuck Norris ha terminato World of Warcraft.", "I project manager non chiedono mai a Chuck Norris le stime.", "Chuck Norris non usa gli standard web in quanto il web si conformera` a lui.", "'Funziona sulla mia macchina' e` sempre vero per Chuck Norris.", "Chuck Norris non fa i grafici di Burn Down, fa i grafici di Smack Down.", "Chuck Norris puo` cancellare il cestino.", "La barba di Chuck Norris puo` scrivere 140 parole al minuto.", "Chuck Norris puo` testare tutte le applicazioni con un'unica affermazione, 'funziona'.", "La tastiera di Chuck Norris non ha un tasto Ctrl perche` niente controlla Chuck Norris.", "Chuck Norris puo` far traboccare il tuo stack solo guardandolo.", "Per Chuck Norris, tutto contiene una vulnerabilita`.", "Chuck Norris non usa sudo, la shell sa solo che e` lui e fa quello che gli viene detto.", "Chuck Norris non ha bisogno di un debugger, si limita a fissare il codice finche` non confessa.", "Chuck Norris puo` accedere a metodi privati.", "Chuck Norris puo` istanziare una classe astratta.", "L'oggetto classe eredita da Chuck Norris.", "Chuck Norris conosce l'ultima cifra del Pi greco.", "La connessione di Chuck Norris e` piu' veloce in up che in down perche` i dati sono incentivati a correre via da lui.", "Nessuna affermazione puo` prendere la ChuckNorrisException.", "Chuck Norris puo` scrivere applicazioni multi-thread con un singolo thread.", "Chuck Norris non ha bisogno di usare AJAX perche` le pagine hanno troppa paura di postback comunque.", "Chuck Norris non usa la riflessione, la riflessione chiede educatamente il suo aiuto.", "Non c'e` alcun tasto Esc sulla tastiera di Chuck Norris, perche` nessuno sfugge a Chuck Norris.", "Chuck Norris puo` eseguire la ricerca binaria di dati non ordinati.", "Chuck Norris non ha bisogno di tentativi di cattura, le eccezioni sono troppo spaventate da sollevarsi.", "Chuck Norris e` uscito da un ciclo infinito.", "Se Chuck Norris scrive codice con bug, gli errori si risolvono da soli.", "L'hosting di Chuck Norris e` garantito al 101% di uptime.", "La tastiera di Chuck Norris ha il tasto Any.", "Chuck Norris puo` accedere al database dall'interfaccia utente.", "I programmi di Chuck Norris non escono mai, sono terminati.", "I programmi di Chuck Norris occupano il 150% della CPU, anche quando non sono in esecuzione.", "Chuck Norris puo` generare thread che si completano prima di essere avviati.", "I programmi di Chuck Norris non accettano input.", "Chuck Norris puo` installare iTunes senza installare Quicktime.", "Chuck Norris non ha bisogno di un sistema operativo.", "Il modello di rete OSI di Chuck Norris ha un solo livello: fisico.", "Chuck Norris puo` compilare errori di sintassi.", "Chuck Norris non ha bisogno di digitare cast. Il Chuck-Norris Compiler (CNC) vede attraverso le cose, fino in fondo sempre.", "Chuck Norris comprime i suoi file con un calcio rotante sul disco rigido.", "Con Chuck Norris P = NP. Non c'e` alcun nondeterminismo con le decisioni di Chuck Norris.", "Chuck Norris puo` recuperare qualsiasi cosa da / dev / null.", "Nessuno ha mai programmato in coppia con Chuck Norris ed e`vissuto per raccontare la storia.", "Nessuno ha mai parlato durante la revisione del codice di Chuck Norris ed e` vissuto per raccontare la storia.", "Chuck Norris non usa una GUI, preferisce la linea di comando.", "Chuck Norris non usa Oracle, lui e` l'Oracle.", "Chuck Norris puo` dereferenziare NULL.", "Una differenza tra il tuo codice e quello di Chuck Norris e` infinita.", "Il plugin Chuck Norris Eclipse e` diventato un contatto alieno.", "Chuck Norris e` l'ultimo mutex, tutti i thread lo temono.", "Non preoccuparti dei test, i test case di Chuck Norris coprono anche il tuo codice.", "Le dichiarazioni del registro di Chuck Norris sono sempre al livello FATAL.", "Chuck Norris ha completato World of Warcraft.", "Quando Chuck Norris rompe la build, non e` possibile risolverla, perche` non c'e` una sola riga di codice.", "Chuck Norris scrive con un dito, lo punta alla tastiera e la tastiera fa il resto.", "I programmi di Chuck Norris possono superare il test di Turing fissando l'interrogatore.", "Se provi kill -9 con i programmi di Chuck Norris, si ritorce contro.", "Chuck Norris esegue loop infiniti in meno di 4 secondi.", "Chuck Norris puo` sovrascrivere una variabile bloccata.", "Chuck Norris conosce il valore di NULL.", "Chuck Norris puo` installare un sistema operativo a 64 bit su macchine a 32 bit.", "Chuck Norris puo` scrivere su un flusso di output.", "Chuck Norris puo` leggere da un flusso di input.", "Chuck Norris non ha mai scritto il suo programma in codice macchina. Le macchine hanno imparato a interpretare il codice di Chuck Norris.", "I test unitari di Chuck Norris non girano, muoiono.", "Chuck Norris causa la schermata blu della morte.", "Chuck Norris puo` fare una classe che e` sia astratta che finale.", "Chuck Norris potrebbe usare qualsiasi cosa in java.util.* per ucciderti, inclusi i javadoc.", "Il codice gira piu` velocemente quando Chuck Norris lo guarda.", "Chuck Norris non usa REST, lui aspetta.", "Su Facebook a tutti piace Chuck Norris, che lo scelgano o no.", "Non puoi seguire Chuck Norris su Twitter, perche` lui ti segue.", "La calcolatrice di Chuck Norris ha solo 3 tasti: 0, 1 e NAND.", "Chuck Norris utilizza solo variabili globali. Non ha nulla da nascondere.", "Chuck Norris scrive direttamente in binario. Quindi scrive il codice sorgente come documentazione per altri programmatori.", ] jokes_it = { 'neutral': neutral, 'chuck': chuck, 'all': neutral + chuck, }
'''Question 1: Given a two integer numbers return their product and if the product is greater than 1000, then return their sum''' num1=int(input("Enter the first no:")) num2=int(input("Enter the second no:")) product=num1*num2 if(product>1000): print("sum is:",num1+num2) else: print("Invalid numbers") #output ''' Enter the first no:32 Enter the second no:200 sum is: 232 '''
def collection_json(): """Returns JSON skeleton for Postman schema.""" collection_json = { "info": { "name": "Test_collection", "description": "Generic text used for documentation.", "schema": "https://schema.getpostman.com/json/collection/v2.1.0/collection.json", }, "item": [], } return collection_json def atomic_request(): """Returns an atomic Postman request dictionary.""" request = { "name": "test request", "request": { "method": "GET", "header": [], "url": { "raw": "{{target_url}}endpoint", "host": ["{{target_url}}endpoint"], }, "description": "This description can come from docs strings", }, "response": [], } return request def basic_JSON(collection_name, app, api_json=collection_json()): """Formats the Postman collection with 'collection_name' and doc string from Sanic app. Returns JSON dictionary.""" api_json["info"]["name"] = collection_name api_json["info"]["description"] = app.__doc__ return api_json
"""Constants for the Alexa integration.""" DOMAIN = 'alexa' # Flash briefing constants CONF_UID = 'uid' CONF_TITLE = 'title' CONF_AUDIO = 'audio' CONF_TEXT = 'text' CONF_DISPLAY_URL = 'display_url' CONF_FILTER = 'filter' CONF_ENTITY_CONFIG = 'entity_config' CONF_ENDPOINT = 'endpoint' CONF_CLIENT_ID = 'client_id' CONF_CLIENT_SECRET = 'client_secret' ATTR_UID = 'uid' ATTR_UPDATE_DATE = 'updateDate' ATTR_TITLE_TEXT = 'titleText' ATTR_STREAM_URL = 'streamUrl' ATTR_MAIN_TEXT = 'mainText' ATTR_REDIRECTION_URL = 'redirectionURL' SYN_RESOLUTION_MATCH = 'ER_SUCCESS_MATCH' DATE_FORMAT = '%Y-%m-%dT%H:%M:%S.0Z' DEFAULT_TIMEOUT = 30
''' Author: Aditya Mangal Date: 20 september,2020 Purpose: python practise problem ''' def input_matrixes(m, n): output = [] for i in range(m): row = [] for j in range(n): user_matrixes = int(input(f'Enter number on [{i}][{j}]\n')) row.append(user_matrixes) output.append(row) return output def sum(A, B): output2 = [] for i in range(len(A)): row2 = [A[i][j] + B[i][j] for j in range(len(A[0]))] output2.append(row2) return output2 if __name__ == "__main__": rows = int(input('Enter the m rows of matrixes.\n')) columns = int(input('Enter the n columns of matrixes.\n')) print('Enter your first matrix.\n') A = input_matrixes(rows, columns) print('Enter your secound matrix.\n') B = input_matrixes(rows, columns) result = sum(A, B) print('Your sum of matrixes are :-\n') for i in range(len(result)): print(result[i])
d=int(input()) m=int(input()) n=int(input()) x=[int(z) for z in input().split(" ")] dist_travelled=0 i=0 refuel=0 while(dist_travelled<d and i<n-1): if(dist_travelled+m>=d): break if(dist_travelled+m>=x[i] and dist_travelled+m<x[i+1]): dist_travelled=x[i] refuel+=1 elif(dist_travelled+m<x[i]): refuel=-1 break i+=1 if(dist_travelled+m>=x[n-1] and dist_travelled+m<d): refuel+=1 dist_travelled=x[n-1] if(dist_travelled+m<d): refuel=-1 print(refuel)
def palin(n): if n == n[::-1]: return True def main(): n = str(input('insira a palavra: ')) n = n.upper() palin(n) if palin(n) == True: print('É palindromo') else: print('Não é palindromo') main()
# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class AgentBase(object): """`AgentBase` is the base class of the `parl.Agent` in different frameworks. `parl.Agent` is responsible for the general data flow outside the algorithm. """ def __init__(self, algorithm): """ Args: algorithm (`AlgorithmBase`): an instance of `AlgorithmBase` """ self.alg = algorithm def get_weights(self, model_ids=None): """Get weights of the agent. If `model_ids` is not None, will only return weights of models whose model_id are in `model_ids`. Note: `ModelBase` in list, tuple and dict will be included. But `ModelBase` in nested list, tuple and dict won't be included. Args: model_ids (List/Set): list/set of model_id, will only return weights of models whiose model_id in the `model_ids`. Returns: (Dict): Dict of weights ({attribute name: numpy array/List/Dict}) """ return self.alg.get_weights(model_ids=model_ids) def set_weights(self, weights, model_ids=None): """Set weights of the agent with given weights. If `model_ids` is not None, will only set weights of models whose model_id are in `model_ids`. Note: `ModelBase` in list, tuple and dict will be included. But `ModelBase` in nested list, tuple and dict won't be included. Args: weights (Dict): Dict of weights ({attribute name: numpy array/List/Dict}) model_ids (List/Set): list/set of model_id, will only set weights of models whiose model_id in the `model_ids`. """ self.alg.set_weights(weights, model_ids=model_ids) def get_model_ids(self): """Get all model ids of the self.alg in the agent. Returns: List of model_id """ return self.alg.get_model_ids() @property def model_ids(self): return self.get_model_ids() def learn(self, *args, **kwargs): """The training interface for Agent. This function will usually do the following things: 1. Accept numpy data as input; 2. Feed numpy data or onvert numpy data to tensor (optional); 3. Call learn function in `Algorithm`. """ raise NotImplementedError def predict(self, *args, **kwargs): """Predict the action when given the observation of the enviroment. In general, this function is used in test process. This function will usually do the following things: 1. Accept numpy data as input; 2. Feed numpy data or onvert numpy data to tensor (optional); 3. Call predict function in `Algorithm`. """ raise NotImplementedError def sample(self, *args, **kwargs): """Sample the action when given the observation of the enviroment. In general, this function is used in train process. This function will usually do the following things: 1. Accept numpy data as input; 2. Feed numpy data or onvert numpy data to tensor (optional); 3. Call predict or sample function in `Algorithm`; 4. Add sampling operation in numpy level. (unnecessary if sampling operation have done in `Algorithm`). """ raise NotImplementedError