content
stringlengths
7
1.05M
# Python - 3.6.0 Test.describe('thirt') Test.it('Basic tests') Test.assert_equals(thirt(8529), 79) Test.assert_equals(thirt(85299258), 31) Test.assert_equals(thirt(5634), 57) Test.assert_equals(thirt(1111111111), 71) Test.assert_equals(thirt(987654321), 30)
class HistMovementManager: def __init__(self): self.boards_hist = [] self.cur_board = -1 self.offset = 0 def make_screen(self, board): if self.cur_board != -1 and self.boards_hist[self.cur_board] == board: return self.boards_hist.append(board) self.cur_board += 1 def get_prev(self): if self.cur_board + self.offset > 0: self.offset -= 1 return self.boards_hist[self.cur_board + self.offset] def get_next(self): if self.offset < 0: self.offset += 1 return self.boards_hist[self.cur_board + self.offset] def clear(self): self.boards_hist = [] self.cur_board = -1 self.offset = 0 def get_hist_board(self): return self.boards_hist[self.cur_board + self.offset] def up_to_date(self): return self.offset == 0 def reset_offset(self): self.offset = 0
""" """ def map_int(to_int) -> int: """Maps value to integer from a string. Parameters ---------- to_int: various (usually str) Value to be converted to integer Returns ------- mapped_int: int Value mapped to integer. Examples -------- >>> number_one = "1" >>> error_value = "will cause error" >>> one_to_float = map_int(number_one) # will convert to 1 >>> error_to_float = map_int(error_value) # will cause exception """ try: mapped_int = int(to_int) except ValueError: raise ValueError("Integer Value Expected Got '{}'".format(to_int)) return mapped_int def map_float(to_float) -> float: """Maps value to float from a string. Parameters ---------- to_float: various (usually str) Value to be converted to float. Returns ------- mapped_float: float Value mapped to float. Examples -------- >>> number_one = "1" >>> error_value = "will cause error" >>> one_to_float = map_float(number_one) # will convert to 1.0 >>> error_to_float = map_float(error_value) # will cause exception """ try: mapped_float = float(to_float) except ValueError: raise ValueError("Float Value Expected Got '{}'".format(to_float)) return mapped_float def map_bool(to_bool) -> bool: """Maps value to boolean from a string. Parameters ---------- to_bool: str Value to be converted to boolean. Returns ------- mapped_bool: bool Boolean value converted from string. Example ------- >>> boolean_string = "True" # can also be lower case >>> boolean_value = map_bool(boolean_string) """ try: boolean_map = {"true": True, "false": False} mapped_bool = boolean_map[to_bool.lower()] except KeyError: raise KeyError("Boolean Value Expected got '{}'".format(to_bool)) return mapped_bool def map_list(to_list, type_table) -> list: """Maps list values with specific data types. Parameters ---------- to_list: str String containing a list for conversion. type_table: list, tuple Contains the data type strings corresponding to CONVERSION_TABLE. Returns ------- mapped_list: list List converted from string. Example ------- >>> list_string = ["1", "3", "True", "5"] >>> conversion_table = ["int", "float", "bool", "float"] >>> mapped_list = map_list(list_string, conversion_table) """ try: brackets = ["[", "]", "(", ")", "{", "}"] translation_dict = {bracket:"" for bracket in brackets} translated_list = to_list.translate(str.maketrans(translation_dict)) mapped_list = [value.strip() for value in translated_list.split(",")] if len(mapped_list) != len(type_table): raise ValueError("Values Do Not Match Number Of Conversions") for i in range(len(mapped_list)): mapped_list[i] = CONVERSION_TABLE[type_table[i]](mapped_list[i]) except KeyError: raise KeyError("Type Given Was Not Found In Conversion Table Got {}".format(type_table[i])) return mapped_list def map_choice(value) -> str: """ Parameters ---------- value: str Returns ------- value: str Value that was chosen. """ return value CONVERSION_TABLE = { "str": str, "int": map_int, "bool": map_bool, "list": map_list, "float": map_float, "choices": map_choice }
# -*- coding: utf-8 -*- """ defs_newton defines e constantes válidas localmente revision 0.2 2015/nov mlabru pep8 style conventions revision 0.1 2014/out mlabru initial release (Python/Linux) """ # < enums >---------------------------------------------------------------------------------------- # estado operacional (newton) E_AUTOMATICA, E_CONTROLADA = range(2) SET_EST_OPE = [E_AUTOMATICA, E_CONTROLADA] # estado de ativação da aeronave (newton) E_ATIVA, E_CANCELADA, E_FINALIZADA, E_PENDENTE, E_QUEUED = range(5) SET_EST_ATV = [E_ATIVA, E_CANCELADA, E_FINALIZADA, E_PENDENTE, E_QUEUED] # função operacional (newton) E_ALT, E_APROXIMACAO, E_APXPERDIDA, E_CANCELA, E_CDIR, E_CESQ, E_CMNR, E_DECOLAGEM, E_DES, \ E_DIRFIXO, E_DIRPNTO, E_ESPERA, E_IAS, E_ILS, E_INTRADIAL, E_MACH, E_MANUAL, E_MOV, E_NIV, \ E_NOPROC, E_ORBITA, E_POUSO, E_PROA, E_SSR, E_SUB, E_SUBIDA, E_TRAJETORIA, E_VEL, E_VISU = range(29) SET_FNC_OPE = [E_ALT, E_APROXIMACAO, E_APXPERDIDA, E_CANCELA, E_CDIR, E_CESQ, E_CMNR, E_DECOLAGEM, E_DES, E_DIRFIXO, E_DIRPNTO, E_ESPERA, E_IAS, E_ILS, E_INTRADIAL, E_MACH, E_MANUAL, E_MOV, E_NIV, E_NOPROC, E_ORBITA, E_POUSO, E_PROA, E_SSR, E_SUB, E_SUBIDA, E_TRAJETORIA, E_VEL, E_VISU] DCT_FNC_OPE = {E_ALT:"ALT", E_APROXIMACAO:"APROXIMACAO", E_APXPERDIDA:"APXPERDIDA", E_CANCELA:"CANCELA", E_CDIR:"CDIR", E_CESQ:"CESQ", E_CMNR:"CMNR", E_DECOLAGEM:"DECOLAGEM", E_DES:"DES", E_DIRFIXO:"DIRFIXO", E_DIRPNTO:"DIRPNTO", E_ESPERA:"ESPERA", E_IAS:"IAS", E_ILS:"ILS", E_INTRADIAL:"INTRADIAL", E_MACH:"MACH", E_MANUAL:"MANUAL", E_MOV:"MOV", E_NIV:"NIV", E_NOPROC:"NOPROC", E_ORBITA:"ORBITA", E_POUSO:"POUSO", E_PROA:"PROA", E_SSR:"SSR", E_SUBIDA:"SUBIDA", E_SUB:"SUB", E_TRAJETORIA:"TRAJETORIA", E_VEL:"VEL", E_VISU:"VISU"} # fases de processamento da cinemática (newton) E_FASE_2R, E_FASE_AFASTA, E_FASE_ALINHAR, E_FASE_APXALINHAR, E_FASE_ASSOCIADO, \ E_FASE_BREAKPOINT, E_FASE_CRVAFASTA, E_FASE_CURVA, E_FASE_DECOLAGEM, E_FASE_DIRFIXO, \ E_FASE_DIRPONTO, E_FASE_EIXO, E_FASE_ESPERA, E_FASE_ESTABILIZADA, E_FASE_FIXO, \ E_FASE_INTERCEPTACAO, E_FASE_OPOSTA, E_FASE_PISTA, E_FASE_PROAINT, E_FASE_RAMPA, \ E_FASE_RUMOALT, E_FASE_SETOR1, E_FASE_SETOR2, E_FASE_SETOR3, E_FASE_SUBIDA, E_FASE_TEMPO, \ E_FASE_TEMPOSETOR, E_FASE_VOLTA, E_FASE_ZERO = range(29) SET_FASE = [E_FASE_2R, E_FASE_AFASTA, E_FASE_ALINHAR, E_FASE_APXALINHAR, E_FASE_ASSOCIADO, E_FASE_BREAKPOINT, E_FASE_CRVAFASTA, E_FASE_CURVA, E_FASE_DECOLAGEM, E_FASE_DIRFIXO, E_FASE_DIRPONTO, E_FASE_EIXO, E_FASE_ESPERA, E_FASE_ESTABILIZADA, E_FASE_FIXO, E_FASE_INTERCEPTACAO, E_FASE_OPOSTA, E_FASE_PISTA, E_FASE_PROAINT, E_FASE_RAMPA, E_FASE_RUMOALT, E_FASE_SETOR1, E_FASE_SETOR2, E_FASE_SETOR3, E_FASE_SUBIDA, E_FASE_TEMPO, E_FASE_TEMPOSETOR, E_FASE_VOLTA, E_FASE_ZERO] DCT_FASE = {E_FASE_2R: "2R", E_FASE_AFASTA: "AFASTA", E_FASE_ALINHAR: "ALINHAR", E_FASE_APXALINHAR: "APXALINHAR", E_FASE_ASSOCIADO: "ASSOCIADO", E_FASE_BREAKPOINT: "BREAKPOINT", E_FASE_CRVAFASTA: "CRVAFASTA", E_FASE_CURVA: "CURVA", E_FASE_DECOLAGEM: "DECOLAGEM", E_FASE_DIRFIXO: "DIRFIXO", E_FASE_DIRPONTO: "DIRPONTO", E_FASE_EIXO: "EIXO", E_FASE_ESPERA: "ESPERA", E_FASE_ESTABILIZADA: "ESTABILIZADA", E_FASE_FIXO: "FIXO", E_FASE_INTERCEPTACAO: "INTERCEPTACAO", E_FASE_OPOSTA: "OPOSTA", E_FASE_PISTA: "PISTA", E_FASE_PROAINT: "PROAINT", E_FASE_RAMPA: "RAMPA", E_FASE_RUMOALT: "RUMOALT", E_FASE_SETOR1: "SETOR1", E_FASE_SETOR2: "SETOR2", E_FASE_SETOR3: "SETOR3", E_FASE_SUBIDA: "SUBIDA", E_FASE_TEMPO: "TEMPO", E_FASE_TEMPOSETOR: "TEMPOSETOR", E_FASE_VOLTA: "VOLTA", E_FASE_ZERO: "ZERO"} # sentidos de curva (D = direita, E = esquerda, M = menor ângulo) (newton) E_DIREITA, E_ESQUERDA, E_MENOR = range(3) SET_SENTIDOS_CURVA = [E_DIREITA, E_ESQUERDA, E_MENOR] DCT_SENTIDOS_CURVA = {E_DIREITA:'D', E_ESQUERDA:'E', E_MENOR:'M'} DCT_SENTIDOS_CURVA_INV = {v:k for k, v in DCT_SENTIDOS_CURVA.items()} # tipos de fixos (' ' = s/tipo, 'D' = DME, 'N' = NDB, 'V' = VOR) E_BRANCO, E_DME, E_NDB, E_VOR = range(4) SET_TIPOS_FIXOS = [E_BRANCO, E_DME, E_NDB, E_VOR] DCT_TIPOS_FIXOS = {E_BRANCO:"s/tipo", E_DME:"DME", E_NDB:"NDB", E_VOR:"VOR"} DCT_TIPOS_FIXOS_INV = {'D':E_DME, 'N':E_NDB, 'V':E_VOR} # < formats >-------------------------------------------------------------------------------------- D_FMT_APX = "APX{:03d}" D_FMT_ESP = "ESP{:03d}" D_FMT_FIX = "{}" D_FMT_SUB = "SUB{:03d}" D_FMT_TRJ = "TRJ{:04d}" # < aeronaves >------------------------------------------------------------------------------------ # RotacaoSolo = 15. # graus/seg # RotacaoSolo8 = 45. # graus/seg (família 8) # VarAngTrafego = 6. # graus/seg # VarAngTrafego8 = 15. # graus/seg (família 8) # VarAngRota = 3. # graus/seg # VarAngRota8 = 7. # graus/seg (família 8) # < máximos >-------------------------------------------------------------------------------------- # quantidade máxima de aerádromos # D_MAX_Aerodromos = 1 # quantidade máxima de aeronaves # D_MAX_Aeronaves = 50 # quantidade máxima de aeronaves ativas # D_MAX_Ativas = 12 # para resolução de ( 800, 600 ) # D_MAX_Ativas = 13 # para resolução de ( 1024, 768 ) # D_MAX_Ativas = 17 # para resolução de ( 1280, 960 ) # D_MAX_Ativas = 15 # para resolução de ( 1280, 990 ) # D_MAX_Ativas = 19 # para resolução de ( 1280, 1024 ) # D_MAX_Ativas = 5000 # para resolução de ( 1280, 990 ) # quantidade máxima de cabeceiras # D_MAX_Cabeceiras = 2 # quantidade máxima de circuitos # D_MAX_Circuitos = 3 # quantidade de desenhos de aeronaves # D_MAX_Desenhos = 5 # quantidade máxima de escalas # D_MAX_Escalas = 3 # quantidade máxima de famílias # D_MAX_Familias = 8 # quantidade máxima de figuras do cenário # D_MAX_Figuras = 40 # quantidade máxima de gravações para replay # D_MAX_Gravações = 5000 # quantidade máxima de pistas # D_MAX_Pistas = 2 # quantidade máxima de pontos adjacentes # D_MAX_PontosAdjs = 5 # quantidade máxima de pontos de saída de pista # D_MAX_PontosArr = 6 # quantidade máxima de pontos de decolagem # D_MAX_PontosDep = 3 # quantidade máxima de pontos no solo # D_MAX_PontosNoSolo = 45 # quantidade máxima de segmentos # D_MAX_Segmentos = 4 # quantidade máxima de trechos no percurso # D_MAX_Trechos = 30 # quantidade máxima de vértices de um polígono # D_MAX_Vertices = 40 # < quantidades >---------------------------------------------------------------------------------- # quantidade de atributos dos dados de aeronaves # D_QTD_AtribAnv = 13 # quantidade de atributos dos dados gerais do exercício # D_QTD_AtribExe = 12 # quantidade de atributos das aeronaves # D_QTD_AtribAer = 9 # quantidade de atributos das pistas # D_QTD_AtribPista = 17 # quantidade de atributos dos dados iniciais do cenário. Os atributos quantidade de Pistas e # quantidade de Pontos no Solo ficam em posições dos outros seis atributos diferentes no arquivo # D_QTD_AtribIniciais = 8 # quantidade de itens da tabela de performace # D_QTD_ItensPerform = 16 # < sets >----------------------------------------------------------------------------------------- # S_ConfValidas = ['S', 'N'] # S_EscalasValidas = [1, 2, 3] # S_SentidosGiro = ['A', 'H', 'I'] # S_STATUS_Aeronaves = ['A', 'E'] # S_STATUS_Circuitos = ['C', 'K', 'V'] # S_STATUS_Exercicio = ['D', 'G', 'T'] # status solo (newton) # !V!S_STATUS_SOLO = ['C', 'D', 'P'] # status vôo (newton) SET_STATUS_VOO = ['C', 'D', 'P'] # S_ProasValidas = [ x for x in xrange ( 360 ) ] # S_DifAngValidas = [x for x in xrange(160, 200)] # S_DifAngAceitaveis = [x for x in xrange(0, 20)] # S_AeronavesValidas = [ ( x + 1 ) for x in xrange ( xMAX_Aeronaves ) ] # S_FamiliasValidas = [ ( x + 1 ) for x in xrange ( xMAX_Familias ) ] # S_CircuitosValidos = [ ( x + 1 ) for x in xrange ( xMAX_Circuitos ) ] # < texts >---------------------------------------------------------------------------------------- # versão # D_TXT_Mjr = "0" # D_TXT_Mnr = "1" # D_TXT_Rls = "0.1p" # D_TXT_Vrs = D_TXT_Mjr + "." + D_TXT_Mnr # D_TXT_Bld = D_TXT_Vrs + "-" + D_TXT_Rls # programa # D_TXT_Prg = "newton" # D_TXT_Tit = D_TXT_Prg + " " + D_TXT_Vrs # D_TXT_Hdr = D_TXT_Prg + " " + D_TXT_Bld # mensagens de erro (gvm) # D_MSG_MNA = u"Máquina não autorizada. Terminando !!!" # mensagens ao piloto # D_MSG_01 = 1 # D_MSG_45 = 45 # D_MSG_46 = 46 # D_MSG_47 = 47 # D_MSG_48 = 48 # D_MSG_49 = 49 # D_MSG_50 = 50 # < defines >-------------------------------------------------------------------------------------- # fator de aceleração na fase de decolagem (from cfg) D_FATOR_ACEL = 2 # altitude máxima na TMA (from cfg) D_ALT_MAX_TMA = 50000 # era 10000 # velocidade máxima na TMA (from cfg) D_VEL_MAX_TMA = 500 # era 250 # variação de temperatura G_EXE_VAR_TEMP_ISA = 10 # flight levels (newton) # D_FL250 = 7620.0 # Fl 250 em metros (25000 x FT2M = 7620.0 m) # D_FL280 = 8534.4 # Fl 280 em metros (28000 x FT2M = 8534.4 m) # D_GAMA = 1.4 # razão de calor específico para o ar nas CNTP. # D_RGAS = 1718 # modelo da atmosfera terrestre da NASA, baseada em valores de densidade, pressão e temperatura do ar # definição para pouso e ILS (newton) D_DST_RAMPA = 3 # D_FAIXA_MT = 15.2392563 # D_RAZAO_LIM = 5.5877 # definição para interceptação de radial # D_ESQUERDA = 1 # D_DIREITA = -1 # D_RAD_C = -1 # D_RAD_S = 1 # D_QDM = -1 # D_QDR = 1 # < the end >--------------------------------------------------------------------------------------
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- __all__ = [ "functions", "dbcontent", "sqlite_helper", "global_variable" ]
def distributeCoins(self, root: TreeNode) -> int: num_opt = 0 def dfs(node): """ >>> DFS Traverse the tree, for each node, the number of moves is the absolute values between 1 and the left/right node values. Also remember to update the node values. """ nonlocal num_opt if not node: return 1 L, R = dfs(node.left), dfs(node.right) num_opt += abs(L-1)+abs(R-1) node.val += L+R-2 return node.val dfs(root) return num_opt
# Copyright 2020 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 # # https://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 that defines custom errors for picatrix.""" class Error(Exception): """Base error class.""" class ArgParserNonZeroStatus(Error): """Raised when the argument parser has exited with non-zero status."""
float_type = type(1.0) int_type = type(1) string_type = type('') date_type = 'iso8601' unicode_type = type(u'') bool_type = type(True) map_type = type({}) seq_type = type([]) tuple_type = type(()) def is_string(obj): t = type(obj) return t is string_type or t is unicode_type def is_int(obj): return type(obj) is int_type def is_float(obj): return type(obj) is float_type def is_number(obj): t = type(obj) return t is int_type or t is float_type def is_map(obj): return type(obj) is map_type def is_seq(obj): return type(obj) is seq_type def is_tuple(obj): return type(obj) is tuple_type def is_bool(obj): return type(obj) is bool_type def is_scalar(obj): t = type(obj) return not (t is map_type or t is seq_type or t is tuple_type) def get_simple_type_name(obj): if is_string(obj): return 'str' if is_map(obj): return 'map' if is_seq(obj): return 'seq' if is_tuple(obj): return 'tuple' if is_int(obj): return 'int' if is_float(obj): return 'float' if is_bool(obj): return 'bool' if obj is None: return 'null' return str(type(obj))
class Field(object): sql_type = None py_type = None def __init__(self, name=None, value=None, pk=None, unique=None, not_null=None): self.name = name self.pk = pk self.unique = unique self.not_null = not_null self.value = value def set_name(self, name): self.name = name def set_value(self, value): self.value = value def get_sql_ddl(self): ret = f'{self.name} {self.sql_type.name}' if self.pk: ret += ' PRIMARY KEY' if self.unique: ret += ' UNIQUE' if self.not_null: ret += ' NOT NULL' return ret def from_sql_to_python(self): return self.py_type(self.value) def from_python_to_sql(self): return self.sql_type.from_python_to_sql(self.value) class SqlType(object): name = None def from_python_to_sql(self, value): raise NotImplemented class IntegerType(SqlType): name = 'INT' def from_python_to_sql(self, value): return str(value) class TextType(SqlType): name = 'TEXT' def from_python_to_sql(self, value): return f"'{value}'"
# Copyright 2018 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 # # https://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. """Rules for generating Protos from Profiles and StructureDefinitions""" STU3_STRUCTURE_DEFINITION_DEP = "//testdata/stu3:fhir" PROTO_GENERATOR = "//java:ProtoGenerator" PROFILE_GENERATOR = "//java:ProfileGenerator" FHIR_PROTO_ROOT = "proto/stu3" def zip_file(name, srcs = []): native.genrule( name = name, srcs = srcs, outs = [name], cmd = "zip --quiet -j $@ $(SRCS)", ) def structure_definition_package(package_name, structure_definitions_zip, package_info): if _get_zip_for_pkg(package_name) != structure_definitions_zip: native.alias( name = _get_zip_for_pkg(package_name), actual = structure_definitions_zip, ) native.alias( name = _get_package_info_for_pkg(package_name), actual = package_info, ) def gen_fhir_protos( name, package, package_deps = [], additional_proto_imports = [], separate_extensions = False, add_apache_license = False): """Generates a proto file from a structure_definition_package These rules should be run by the generate_protos.sh script, which will generate the protos and move them into the source directory. e.g., for a gen_fhir_protos rule in foo/bar with name = quux, bazel/generate_protos.sh foo/bar:quux Args: name: The name for the generated proto file (without .proto) package: The structure_definition_package to generate protos for. package_deps: Any package_deps these definitions depend on. Core fhir structure definitions are automatically included. additional_proto_imports: Additional proto files the generated protos should import FHIR datatypes, annotations, and codes are included automatically. separate_extensions: If true, will produce two proto files, one for extensions and one for profiles. add_apache_license: Whether or not to include the apache license """ all_struct_def_pkgs = package_deps + [STU3_STRUCTURE_DEFINITION_DEP, package] struct_def_dep_flags = " ".join([ "--struct_def_dep_pkg \"$(location %s)|$(location %s)\"" % (_get_zip_for_pkg(dep), _get_package_info_for_pkg(dep)) for dep in all_struct_def_pkgs ]) additional_proto_imports_flags = " ".join([ "--additional_import %s" % proto_import for proto_import in additional_proto_imports ]) cmd = """ $(location %s) \ --emit_proto \ --output_directory $(@D) \ --package_info $(location %s) \ --fhir_proto_root %s \ --output_name _genfiles_%s \ --input_zip $(location %s) \ """ % ( PROTO_GENERATOR, _get_package_info_for_pkg(package), FHIR_PROTO_ROOT, name, _get_zip_for_pkg(package), ) cmd += additional_proto_imports_flags + " " + struct_def_dep_flags if add_apache_license: cmd += " --add_apache_license " if separate_extensions: outs = ["_genfiles_" + name + ".proto", "_genfiles_" + name + "_extensions.proto"] cmd += " --separate_extensions " else: outs = ["_genfiles_" + name + ".proto"] srcs = ([_get_zip_for_pkg(pkg) for pkg in all_struct_def_pkgs] + [_get_package_info_for_pkg(pkg) for pkg in all_struct_def_pkgs]) native.genrule( name = name + "_proto_files", outs = outs, srcs = srcs, tools = [PROTO_GENERATOR], cmd = cmd, ) def gen_fhir_definitions_and_protos( name, package_info, extensions = [], profiles = [], package_deps = [], additional_proto_imports = [], separate_extensions = False, add_apache_license = False): """Generates structure definitions and protos based on Extensions and Profiles protos. These rules should be run by bazel/generate_protos.sh, which will generate the profiles and protos and move them into the source directory. e.g., bazel/generate_protos.sh foo/bar:quux This also exports the package_info and a zip of structure definitions, so that this target can be used as a dependency of other gen_fhir_definitions_and_protos. Args: name: name prefix for all generated rules package_info: Metadata shared by all generated Structure Definitions. extensions: List of Extensions prototxt files profiles: List of Profiles prototxt files. package_deps: Any package_deps these definitions depend on. Core fhir structure definitions are automatically included. additional_proto_imports: Additional proto files the generated profiles should import FHIR datatypes, annotations, and codes are included automatically. separate_extensions: If true, will produce two proto files, one for extensions and one for profiles. add_apache_license: Whether or not to include the apache license """ extension_flags = " ".join([("--extensions $(location %s) " % extension) for extension in extensions]) profile_flags = " ".join([("--profiles $(location %s) " % profile) for profile in profiles]) all_struct_def_deps = [STU3_STRUCTURE_DEFINITION_DEP] + package_deps struct_def_dep_zip_flags = " ".join([ ("--struct_def_dep_zip $(location %s) " % _get_zip_for_pkg(dep)) for dep in all_struct_def_deps ]) structure_definition_srcs = ([package_info] + extensions + profiles + [_get_zip_for_pkg(dep) for dep in all_struct_def_deps]) native.genrule( name = name + "_structure_definitions", outs = ["_genfiles_" + name + "_extensions.json", "_genfiles_" + name + ".json"], srcs = structure_definition_srcs, tools = [ PROFILE_GENERATOR, ], cmd = (""" $(location %s) \ --output_directory $(@D) \ --name _genfiles_%s \ --package_info $(location %s) \ %s %s %s""" % ( PROFILE_GENERATOR, name, package_info, struct_def_dep_zip_flags, extension_flags, profile_flags, )), ) zip_file( name = name + "_structure_definitions.zip", srcs = [name + "_extensions.json", name + ".json"], ) structure_definition_package( package_name = name, structure_definitions_zip = name + "_structure_definitions.zip", package_info = package_info, ) gen_fhir_protos( name = name, package = name, package_deps = package_deps, additional_proto_imports = additional_proto_imports, separate_extensions = separate_extensions, add_apache_license = add_apache_license, ) def _get_zip_for_pkg(pkg): return pkg + "_structure_definitions_zip" def _get_package_info_for_pkg(pkg): return pkg + "_package_info_prototxt"
# cypher.py - encrypt and decrypt messages def cypher(message, key): result = "" for ch in message: ch = chr(ord(ch) ^ key) result += ch return result def run(): plaintext = input("message? ") key = input("hex number for key? ") key = int(key, 16) cyphertext = cypher(plaintext, key) print(cyphertext)
"""Constants for the Automate Pulse Hub v2 integration.""" DOMAIN = "automate" AUTOMATE_HUB_UPDATE = "automate_hub_update_{}" AUTOMATE_ENTITY_REMOVE = "automate_entity_remove_{}"
""" The parsed output of the knowledge,json is used to create the Knowledge object consisting of the target and rules """ class Rule: """ Class to store the rule in the string format Attributes ----------- __rule: str rule for the knowledge """ def __init__(self, rule: str): self.__rule = rule def getRule(self): """ Get the rule Returns ------- str rule of the current object """ return self.__rule def __eq__(self, other): """ Comparison of two rules. Substring and more complex comparison Parameters ---------- other : Rule object of the Rule Returns ------- bool True if a match """ if other.__rule.__contains__(self.__rule): return True return False def __str__(self): """ Print the rule string Returns ------- str rule """ return self.__rule class Knowledge: """ Class that connects the target with the rules (Rule objects). Attributes ---------- __target : str name of the target or the output __rules : list list of the Rule objects """ def __init__(self): self.__target = None self.__rules = list() def addRule(self, target, rule): """ Add new rule to the Knowledge Parameters ---------- target : str output or the name of the target rule : str rule for the Knowledge """ self.__target = target self.__rules.append(Rule(rule)) def __str__(self): """ Printing the knowledge base with some formatting Returns ------- str put together string """ data = list() data.append(self.__target) data.append(" =====> \n") for rule in self.__rules: data.append("\t <<< ") data.append(rule.getRule()) data.append(" >>> \n") data.append("\n\n") return "".join(data) def getTarget(self): """ Get the name of the output Returns ------- str name of the target """ return self.__target def getRules(self): """ Get the list of all the rules of the Knowledge Returns ------- list all rules """ return self.__rules
__all__ = [ 'q1_itertools_product', 'q2_itertools_permutations', 'q3_itertools_combinations', 'q4_itertools_combinations_with_replacement', 'q5_compress_the_string', 'q6_iterables_and_iterators', 'q7_maximize_it' ]
# This file is part of LibCSS. # Licensed under the MIT License, # http://www.opensource.org/licenses/mit-license.php # Copyright 2017 Lucas Neves <lcneves@gmail.com> # Configuration of CSS values. # The tuples in this set will be unpacked as arguments to the CSSValue # class. # Args: see docstring for class CSSValue in select_generator.py. values = { ('length', 'css_fixed', 4, '0', 'unit', 'css_unit', 5, 'CSS_UNIT_PX'), ('integer', 'int32_t', 4, '0'), ('fixed', 'css_fixed', 4, '0'), ('color', 'css_color', 4, '0'), ('string', 'lwc_string*'), ('string_arr', 'lwc_string**'), ('counter_arr', 'css_computed_counter*'), ('content_item', 'css_computed_content_item*') } # Configuration of property groups. # The tuples in these sets will be unpacked as arguments to the # CSSproperty class. # Args: see docstring for class CSSProperty in select_generator.py. style = { # Style group, only opcode ('align_content', 3), ('align_items', 3), ('align_self', 3), ('background_attachment', 2), ('background_repeat', 3), ('border_collapse', 2), ('border_top_style', 4), ('border_right_style', 4), ('border_bottom_style', 4), ('border_left_style', 4), ('box_sizing', 2), ('caption_side', 2), ('clear', 3), ('direction', 2), ('display', 5), ('empty_cells', 2), ('flex_direction', 3), ('flex_wrap', 2), ('float', 2), ('font_style', 2), ('font_variant', 2), ('font_weight', 4), ('justify_content', 3), ('list_style_position', 2), ('list_style_type', 4), ('overflow_x', 3), ('overflow_y', 3), ('outline_style', 4), ('position', 3), ('table_layout', 2), ('text_align', 4), ('text_decoration', 5), ('text_transform', 3), ('unicode_bidi', 2), ('visibility', 2), ('white_space', 3), # Style group, with additional value ('background_color', 2, 'color'), ('background_image', 1, 'string'), ('background_position', 1, (('length',), ('length',)), 'CSS_BACKGROUND_POSITION_SET'), ('border_top_color', 2, 'color'), ('border_right_color', 2, 'color'), ('border_bottom_color', 2, 'color'), ('border_left_color', 2, 'color'), ('border_top_width', 3, 'length', 'CSS_BORDER_WIDTH_WIDTH'), ('border_right_width', 3, 'length', 'CSS_BORDER_WIDTH_WIDTH'), ('border_bottom_width', 3, 'length', 'CSS_BORDER_WIDTH_WIDTH'), ('border_left_width', 3, 'length', 'CSS_BORDER_WIDTH_WIDTH'), ('top', 2, 'length', 'CSS_TOP_SET', None, None, 'get'), ('right', 2, 'length', 'CSS_RIGHT_SET', None, None, 'get'), ('bottom', 2, 'length', 'CSS_BOTTOM_SET', None, None, 'get'), ('left', 2, 'length', 'CSS_LEFT_SET', None, None, 'get'), ('color', 1, 'color'), ('flex_basis', 2, 'length', 'CSS_FLEX_BASIS_SET'), ('flex_grow', 1, 'fixed', 'CSS_FLEX_GROW_SET'), ('flex_shrink', 1, 'fixed', 'CSS_FLEX_SHRINK_SET'), ('font_size', 4, 'length', 'CSS_FONT_SIZE_DIMENSION'), ('height', 2, 'length', 'CSS_HEIGHT_SET'), ('line_height', 2, 'length', None, None, None, 'get'), ('list_style_image', 1, 'string'), ('margin_top', 2, 'length', 'CSS_MARGIN_SET'), ('margin_right', 2, 'length', 'CSS_MARGIN_SET'), ('margin_bottom', 2, 'length', 'CSS_MARGIN_SET'), ('margin_left', 2, 'length', 'CSS_MARGIN_SET'), ('max_height', 2, 'length', 'CSS_MAX_HEIGHT_SET'), ('max_width', 2, 'length', 'CSS_MAX_WIDTH_SET'), ('min_height', 2, 'length', 'CSS_MIN_HEIGHT_SET'), ('min_width', 2, 'length', 'CSS_MIN_WIDTH_SET'), ('opacity', 1, 'fixed', 'CSS_OPACITY_SET'), ('order', 1, 'integer', 'CSS_ORDER_SET'), ('padding_top', 1, 'length', 'CSS_PADDING_SET'), ('padding_right', 1, 'length', 'CSS_PADDING_SET'), ('padding_left', 1, 'length', 'CSS_PADDING_SET'), ('padding_bottom', 1, 'length', 'CSS_PADDING_SET'), ('text_indent', 1, 'length', 'CSS_TEXT_INDENT_SET'), ('vertical_align', 4, 'length', 'CSS_VERTICAL_ALIGN_SET'), ('width', 2, 'length', 'CSS_WIDTH_SET'), ('z_index', 2, 'integer'), # Style group, arrays ('font_family', 3, 'string_arr', None, None, 'Encode font family as an array of string objects, terminated with a ' 'blank entry.'), ('quotes', 1, 'string_arr', None, None, 'Encode quotes as an array of string objects, terminated with a ' 'blank entry.'), # Style group, w3d properties ('depth', 2, 'length', 'CSS_DEPTH_SET'), ('max_depth', 2, 'length', 'CSS_MAX_DEPTH_SET'), ('min_depth', 2, 'length', 'CSS_MIN_DEPTH_SET'), ('far', 2, 'length', 'CSS_FAR_SET', None, None, 'get'), ('near', 2, 'length', 'CSS_NEAR_SET', None, None, 'get'), ('margin_far', 2, 'length', 'CSS_MARGIN_SET'), ('margin_near', 2, 'length', 'CSS_MARGIN_SET'), ('padding_far', 1, 'length', 'CSS_PADDING_SET'), ('padding_near', 1, 'length', 'CSS_PADDING_SET'), ('overflow_z', 3) } page = { # Page group ('page_break_after', 3, None, None, 'CSS_PAGE_BREAK_AFTER_AUTO'), ('page_break_before', 3, None, None, 'CSS_PAGE_BREAK_BEFORE_AUTO'), ('page_break_inside', 2, None, None, 'CSS_PAGE_BREAK_INSIDE_AUTO'), ('widows', 1, (('integer', '2'),), None, 'CSS_WIDOWS_SET'), ('orphans', 1, (('integer', '2'),), None, 'CSS_ORPHANS_SET') } uncommon = { # Uncommon group ('border_spacing', 1, (('length',), ('length',)), 'CSS_BORDER_SPACING_SET', 'CSS_BORDER_SPACING_SET'), ('break_after', 4, None, None, 'CSS_BREAK_AFTER_AUTO'), ('break_before', 4, None, None, 'CSS_BREAK_BEFORE_AUTO'), ('break_inside', 4, None, None, 'CSS_BREAK_INSIDE_AUTO'), ('clip', 6, (('length',), ('length',), ('length',), ('length',)), 'CSS_CLIP_RECT', 'CSS_CLIP_AUTO', None, ('get', 'set')), ('column_count', 2, 'integer', None, 'CSS_COLUMN_COUNT_AUTO'), ('column_fill', 2, None, None, 'CSS_COLUMN_FILL_BALANCE'), ('column_gap', 2, 'length', 'CSS_COLUMN_GAP_SET', 'CSS_COLUMN_GAP_NORMAL'), ('column_rule_color', 2, 'color', None, 'CSS_COLUMN_RULE_COLOR_CURRENT_COLOR'), ('column_rule_style', 4, None, None, 'CSS_COLUMN_RULE_STYLE_NONE'), ('column_rule_width', 3, 'length', 'CSS_COLUMN_RULE_WIDTH_WIDTH', 'CSS_COLUMN_RULE_WIDTH_MEDIUM'), ('column_span', 2, None, None, 'CSS_COLUMN_SPAN_NONE'), ('column_width', 2, 'length', 'CSS_COLUMN_WIDTH_SET', 'CSS_COLUMN_WIDTH_AUTO'), ('letter_spacing', 2, 'length', 'CSS_LETTER_SPACING_SET', 'CSS_LETTER_SPACING_NORMAL'), ('outline_color', 2, 'color', 'CSS_OUTLINE_COLOR_COLOR', 'CSS_OUTLINE_COLOR_INVERT'), ('outline_width', 3, 'length', 'CSS_OUTLINE_WIDTH_WIDTH', 'CSS_OUTLINE_WIDTH_MEDIUM'), ('word_spacing', 2, 'length', 'CSS_WORD_SPACING_SET', 'CSS_WORD_SPACING_NORMAL'), ('writing_mode', 2, None, None, 'CSS_WRITING_MODE_HORIZONTAL_TB'), # Uncommon group, arrays ('counter_increment', 1, 'counter_arr', None, 'CSS_COUNTER_INCREMENT_NONE', 'Encode counter_increment as an array of name, value pairs, ' 'terminated with a blank entry.'), ('counter_reset', 1, 'counter_arr', None, 'CSS_COUNTER_RESET_NONE', 'Encode counter_reset as an array of name, value pairs, ' 'terminated with a blank entry.'), ('cursor', 5, 'string_arr', None, 'CSS_CURSOR_AUTO', 'Encode cursor uri(s) as an array of string objects, terminated ' 'with a blank entry'), ('content', 2, 'content_item', 'CSS_CONTENT_NORMAL', 'CSS_CONTENT_NORMAL', 'Encode content as an array of content items, terminated with ' 'a blank entry.', 'set') } groups = [ { 'name': 'uncommon', 'props': uncommon }, { 'name': 'page', 'props': page }, { 'name': 'style', 'props': style } ]
class CSharpReference(): def __init__(self,): self.reference_object = None self.line_in_file = -1 self.file_name = ''
# -*- coding: utf-8 - # # This file is part of gunicorn released under the MIT license. # See the NOTICE for more information. version_info = (20, 0, 4, "custom") __version__ = ".".join([str(v) for v in version_info]) SERVER = "gunicorn" SERVER_SOFTWARE = "%s/%s" % (SERVER, __version__)
''' 03 - Creating histograms Histograms show the full distribution of a variable. In this exercise, we will display the distribution of weights of medalists in gymnastics and in rowing in the 2016 Olympic games for a comparison between them. You will have two DataFrames to use. The first is called mens_rowing and includes information about the medalists in the men's rowing events. The other is called mens_gymnastics and includes information about medalists in all of the Gymnastics events. Instructions: - Use the ax.hist method to add a histogram of the "Weight" column from the mens_rowing DataFrame. - Use ax.hist to add a histogram of "Weight" for the mens_gymnastics DataFrame. - Set the x-axis label to "Weight (kg)" and the y-axis label to "# of observations". ''' fig, ax = plt.subplots() # Plot a histogram of "Weight" for mens_rowing ax.hist(mens_rowing['Weight']) # Compare to histogram of "Weight" for mens_gymnastics ax.hist(mens_gymnastics['Weight']) # Set the x-axis label to "Weight (kg)" ax.set_xlabel('Weight (kg)') # Set the y-axis label to "# of observations" ax.set_ylabel('# of observations') plt.show()
"""camera_settings.py Note: Currently not used. Proof of concept to show how to change camera settings in one file and have them applied to a camera from a different script. """ def apply_settings(camera): """Changes the settings of a camera.""" camera.clear_mode = 0 camera.exp_mode = "Internal Trigger" camera.readout_port = 0 camera.speed_table_index = 0 camera.gain = 1
# model settings norm_cfg = dict(type='SyncBN', requires_grad=True) model = dict( type='EncoderDecoder', pretrained=None, backbone=dict( type='MixVisionTransformer', in_channels=3, embed_dims=32, num_stages=4, num_layers=[2, 2, 2, 2], num_heads=[1, 2, 5, 8], patch_sizes=[7, 3, 3, 3], sr_ratios=[8, 4, 2, 1], out_indices=(0, 1, 2, 3), mlp_ratio=4, qkv_bias=True, drop_rate=0.0, attn_drop_rate=0.0, drop_path_rate=0.1), decode_head=dict( type='SegformerHead', in_channels=[32, 64, 160, 256], in_index=[0, 1, 2, 3], channels=256, dropout_ratio=0.1, num_classes=3, norm_cfg=norm_cfg, align_corners=False, loss_decode=dict( type='CrossEntropyLoss', use_sigmoid=False, loss_weight=1.0)), # model training and testing settings train_cfg=dict(), test_cfg=dict(mode='whole'))
# how to create a function def greet(): print("Hello") print("welcome, Edgar") greet() # prints greet() # prints(2) greet() # prints(3) # arguments and parameters def greet(name): # name is a parameter print('hello') print('welcome, ', name) greet('Edgar') # Edgar is the argument # return def greet(name): if name == 'Edgar': return else: print('hello') print('welcome, ', name) greet('Edgar') # return values def greet(name): if name == 'Jose': return 'Go away' return "hello ", name, "Welcome to my app" returned = greet('Edgar') print(returned)
#! /usr/bin/env python3 """ constants.py - Contains all constants used by the device manager Author: - Nidesh Chitrakar (nideshchitrakar@bennington.edu) - Hoanh An (hoanhan@bennington.edu) Date: 12/07/2017 """ number_of_rows = 3 # total number rows of Index Servers number_of_links = 5 # number of links to be sent to Crawler number_of_chunks = 5 # number of chunks to be sent to Index Builder number_of_comps = 10 # number of components managed by each watchdog
def convert_date_string_to_period(timestamp) -> int: try: month = int(timestamp.month) except AttributeError: return -1 else: return month
exe = "tester.exe" toolchain = "msvc" # optional link_pool_depth = 1 # optional builddir = { "gnu" : "build" , "msvc" : "build" , "clang" : "build" } includes = { "gnu" : [ "-I." ] , "msvc" : [ "/I." ] , "clang" : [ "-I." ] } defines = { "gnu" : [ "-DEXAMPLE=1" ] , "msvc" : [ "/DEXAMPLE=1" ] , "clang" : [ "-DEXAMPLE=1" ] } cflags = { "gnu" : [ "-O2", "-g" ] , "msvc" : [ "/O2" ] , "clang" : [ "-O2", "-g" ] } cxxflags = { "gnu" : [ "-O2", "-g" ] , "msvc" : [ "/O2", "/W4", "/EHsc"] , "clang" : [ "-O2", "-g", "-fsanitize=address" ] } ldflags = { "gnu" : [ ] , "msvc" : [ ] , "clang" : [ "-fsanitize=address" ] } # optionsl cxx_files = [ "tester.cc" ] c_files = [ ] # You can register your own toolchain through register_toolchain function def register_toolchain(ninja): pass
# Problem: https://www.hackerrank.com/challenges/alphabet-rangoli/problem def print_rangoli(size): alorder = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' alorder = ''.join([i.lower() for i in alorder]) string, width , side_l, side_str = alorder[:size], (size-1)*4+1, [], '' # top half for i in range(size-1): print((side_str + '-' + string[size-1-i] + '-' + side_str[::-1]).center(width,'-')) side_l.append(string[size-1-i]) side_str = '-'.join(side_l) # middle if size == 1: print(string[0]) else: print(side_str+'-'+string[0]+'-'+side_str[::-1]) # lower half for i in range(size-1): center_str = side_l.pop() side_str = '-'.join(side_l) print((side_str + '-' + center_str + '-' + side_str[::-1]).center(width,'-')) n = int(input("Enter alphabet rangoli's size: ")) print_rangoli(n)
# Cooling Settings cool_circuit = \ {'label': 'Activate Cooling:', 'value': True, 'sticky': ['NW', 'NWE'], 'sim_name': ['stack', 'cool_flow'], 'type': 'CheckButtonSet', 'specifier': 'checklist_activate_cooling', 'command': {'function': 'set_status', 'args': [[[1, 0], [1, 1], [1, 2], [2, 0], [2, 1], [2, 2], [3, 0], [3, 1], [3, 2], [4, 0], [4, 1], [4, 2], [5, 0], [5, 1], [5, 2], [6, 0], [6, 1], [6, 2], [7, 0], [7, 1], [7, 2], [8, 0], [8, 1], [8, 2]]]}} # 'args2': [1, 2, 3, 4, 5, 6, 7]}} cool_channel_length = \ {'label': 'Coolant Channel Length:', 'value': 0.4, 'sim_name': ['coolant_channel', 'length'], 'specifier': 'disabled_cooling', 'dtype': 'float', 'dimensions': 'm', 'type': 'EntrySet'} cool_channel_height = \ {'label': 'Coolant Channel Height:', 'value': 1e-3, 'sim_name': ['coolant_channel', 'height'], 'specifier': 'disabled_cooling', 'dtype': 'float', 'dimensions': 'm', 'type': 'EntrySet'} cool_channel_width = \ {'label': 'Coolant Channel Width:', 'value': 1e-3, 'sim_name': ['coolant_channel', 'width'], 'specifier': 'disabled_cooling', 'dtype': 'float', 'dimensions': 'm', 'type': 'EntrySet'} cool_channel_number = \ {'label': 'Coolant Channel Number:', 'value': 2, 'sim_name': ['temperature_system', 'cool_ch_numb'], 'specifier': 'disabled_cooling', 'type': 'EntrySet'} cool_channel_bends = \ {'label': 'Number of Coolant Channel Bends:', 'value': 0, 'sim_name': ['coolant_channel', 'bend_number'], 'specifier': 'disabled_cooling', 'type': 'EntrySet'} cool_bend_pressure_loss_coefficient = \ {'label': 'Pressure Loss Coefficient for Coolant Channel Bend:', 'sim_name': ['coolant_channel', 'bend_friction_factor'], 'specifier': 'disabled_cooling', 'value': 0.5, 'dimensions': '-', 'type': 'EntrySet'} cool_flow_end_cells = \ {'label': 'Activate Cooling Flow at End Plates:', 'value': False, 'sim_name': ['temperature_system', 'cool_ch_bc'], 'specifier': 'disabled_cooling', 'sticky': ['NW', 'NWE'], 'type': 'CheckButtonSet'} channel_flow_direction = \ {'label': 'Channel Flow Direction (1 or -1):', 'value': 1, 'sim_name': ['coolant_channel', 'flow_direction'], 'specifier': 'disabled_cooling', 'dtype': 'int', 'type': 'EntrySet', 'sticky': ['NW', 'NWE']} cool_frame_dict = \ {'title': 'Cooling Settings', 'show_title': False, 'font': 'Arial 10 bold', 'sticky': 'WEN', 'size_label': 'xl', 'size_unit': 's', 'widget_dicts': [cool_circuit, cool_channel_number, cool_channel_length, cool_channel_height, cool_channel_width, cool_channel_bends, cool_bend_pressure_loss_coefficient, channel_flow_direction, cool_flow_end_cells], # 'highlightbackground': 'grey', 'highlightthickness': 1 } tab_dict = {'title': 'Cooling', 'show_title': False, 'sub_frame_dicts': [cool_frame_dict]} # geometry_frame_dict = \ # {'title': 'Geometry', 'show_title': False, 'font': 'Arial 10 bold', # 'sub_frame_dicts': [cool_frame_dict, manifold_frame_dict, # cell_frame_dict], # 'highlightbackground': 'grey', 'highlightthickness': 1} # main_frame_dicts = [geometry_frame_dict, simulation_frame_dict]
class Solution: # @param {integer} n # @param {integer} k # @return {string} def getPermutation(self, n, k): nums = [i+1 for i in xrange(n)] facts = [0 for i in xrange(n)] facts[0] = 1 for i in range(1,n): facts[i] = i*facts[i-1] k = k-1 res = [] for i in range(n,0,-1): idx = k/facts[i-1] k = k%facts[i-1] res.append(nums[idx]) nums.pop(idx) return ''.join([str(i) for i in res])
# Python 3 compatibility (no longer includes `basestring`): try: basestring except NameError: basestring = str class Item(object): '''Common logic shared across all kinds of objects.''' class UnknownAttributeError(ValueError): def __init__(self, attributes): super(Item.UnknownAttributeError, self).__init__( "Unknown attributes: {0}".format(attributes)) COMMON_ATTRIBUTES = ('name', 'namespace', 'labels') def __init__(self, config, info): self._config = config for attr in self.COMMON_ATTRIBUTES: val = info.get(attr) if not val and 'metadata' in info: val = info['metadata'].get(attr) if val: setattr(self, attr, val) def __repr__(self): return '<{0}: {1}>'.format( self.__class__.__name__, ' '.join('{0}={1}'.format(a, v) for a, v in self._simple_attrvals) ) def attrvals(self, attributes): unknown = set(attributes) - set(self.ATTRIBUTES) if unknown: raise self.UnknownAttributeError(unknown) return ((a, getattr(self, a)) for a in attributes) @property def _simple_attrvals(self): for attr in self.COMMON_ATTRIBUTES: av = self._attrval_if_simple(attr) if av: yield av for attr in self.PRIMARY_ATTRIBUTES: if attr not in self.COMMON_ATTRIBUTES: av = self._attrval_if_simple(attr) if av: yield av def _attrval_if_simple(self, attr): if hasattr(self, attr): if not self._property(attr): val = getattr(self, attr) if self._simple(val): return (attr, val) @staticmethod def _simple(val): return isinstance(val, (basestring, int, float, None.__class__)) def _property(self, attr): return isinstance(getattr(type(self), attr, None), property)
word = input().lower() ans = [] vowels = ('a', 'i', 'u', 'e', 'o', 'y') filtered_word = word for i in word: if i in vowels: filtered_word = filtered_word.replace(i, "") for i in filtered_word: ans.append('.') ans.append(i) print(''.join(ans))
def ft_map(function_to_apply, list_of_inputs): return [function_to_apply(x) for x in list_of_inputs] c = [0,1,2,3,4,5] def add1(t): return t+1 print(list(map(lambda x: x+1,c))) print(ft_map(lambda x: x+1,c))
#!/bin/python2.7 #CLASS PARA VERIFICAR OS GRUPOS DE CONFLITO class ScdGrupoConflito(object): def __init__(self): self.in_port = False self.ip_src = False self.ip_dst = False self.dl_src = False self.dl_dst = False self.tp_src = False self.tp_dst = False self.dl_type = False self.solucao = str("") #CLASS PARA VERIFICAR SE OS CAMPOS SAO WILDCARDS class ScdWildcards(object): def __init__(self): self.in_port = False self.ip_src = False self.ip_dst = False self.dl_src = False self.dl_dst = False self.tp_src = False self.tp_dst = False self.dl_type = False #CLASS PARA CONTAR O TOTAL DE WILDCARDS class ScdWildcardsTotal(object): def __init__(self): self.in_port = 0 self.ip = 0 self.dl = 0 self.tp = 0 class ScdRegraGenerica(object): def __init__(self): self.in_port = False self.ip = False self.dl = False self.tp = False class ScdSugestao(object): def __init__(self): self.sugestao_resolucao = None self.nivel_conflito = 0 #QUANTO AO NIVEL, DEFINIDO COMO # 0 - Nenhum # 1 - Medio # 2 - Alto def analise_Conflito(pscd_rule_1, pscd_rule_2): # Inicia a verificacao das rules ##DECLARACAO DAS VARIAVEIS UTILIZADAS NA FUNCTION grp_conflito = ScdGrupoConflito() wildcards_rule_1 = ScdWildcards() wildcards_rule_2 = ScdWildcards() wildcards_total_1 = ScdWildcardsTotal() wildcards_total_2 = ScdWildcardsTotal() regra_generica = ScdRegraGenerica() sugestao = ScdSugestao() #print "Iniciando verificacao de Conflitos" #print "################################################" #PRIMEIRO VERIFICA SE SAO DO MESMA SWITCH if pscd_rule_1.switch == pscd_rule_2.switch: #VERIFICA SE SAO DA MESMA PORTA DE ENTRADA E DO MESMO TIPO (DL_TYPE) if pscd_rule_1.dl_type != pscd_rule_2.dl_type: #print "REGRAS NAO SAO DO MESMO DL_TYPE" return sugestao else: #print "REGRAS SAO DO MESMO DL_TYPE" grp_conflito.dl_type = True #print "------------------------------------" #print "----> VERIFICA IN_PORT - GRUPO 1" #print "------------------------------------" #SE UMA DAS IN_PORT FOR WILDCARD OU AS DUAS FOREM IGUAIS, PROSSEGUE if (((pscd_rule_1.in_port == None) and (pscd_rule_2.in_port == None)) or (pscd_rule_1.in_port == pscd_rule_2.in_port)): if (pscd_rule_1.in_port == None): #print "IN_PORT 1 EH WILDCARD" grp_conflito.in_port = True if (pscd_rule_2.in_port == None): #print "IN_PORT 2 EH WILDCARD" grp_conflito.in_port = True if (pscd_rule_1.in_port == pscd_rule_2.in_port): #print "IN_PORT IGUAIS" grp_conflito.in_port = True #print ("Conflito Grupo 1: %s" %grp_conflito.in_port) ####FIM GRUPO 1 ## Verifica IP_SRC e IP_DST - GRUPO 2 ################################### #print "------------------------------------" #print "----> GRUPO 2 - VERIFICA IP SRC/DST" #print "------------------------------------" ##IP_SRC if pscd_rule_1.nw_src == pscd_rule_2.nw_src: #print "GRUPO 2 - IP_SRC iguais" grp_conflito.ip_src = True if pscd_rule_1.nw_src == None and pscd_rule_2.nw_src == None: #print "GRUPO 2 - IP_SRC 1 e 2 Wildcards" wildcards_rule_1.ip_src = True wildcards_rule_2.ip_src = True else: if pscd_rule_1.nw_src == None: #print "GRUPO 2 - IP_SRC 1 Wildcard" grp_conflito.ip_src = True wildcards_rule_1.ip_src = True if pscd_rule_2.nw_src == None: #print "GRUPO 2 - IP_SRC 2 Wildcard" grp_conflito.ip_src = True wildcards_rule_2.ip_src = True elif pscd_rule_1.nw_src is not None and pscd_rule_2.nw_src is not None: mask = 0 if pscd_rule_1.nw_src[0] == pscd_rule_2.nw_src[0]: if pscd_rule_1.nw_src[1] == pscd_rule_2.nw_src[1]: if pscd_rule_1.nw_src[2] == pscd_rule_2.nw_src[2]: if pscd_rule_1.nw_src[3] == pscd_rule_2.nw_src[3]: mask = 1 else: if pscd_rule_1.nw_src[3] == 0: mask = 1 elif pscd_rule_2.nw_src[3] == 0: mask = 1 else: if pscd_rule_1.nw_src[2] == 0 and pscd_rule_1.nw_src[3] == 0: mask = 1 elif pscd_rule_2.nw_src[2] == 0 and pscd_rule_2.nw_src[3] == 0: mask = 1 else: if pscd_rule_1.nw_src[1] == 0 and pscd_rule_1.nw_src[2] == 0 and pscd_rule_1.nw_src[3] == 0: mask = 1 elif pscd_rule_2.nw_src[1] == 0 and pscd_rule_2.nw_src[2] == 0 and pscd_rule_2.nw_src[3] == 0: mask = 1 else: if pscd_rule_1.nw_src[0] == 0 and pscd_rule_1.nw_src[1] == 0 and pscd_rule_1.nw_src[2] == 0 and pscd_rule_1.nw_src[3] == 0: mask = 1 elif pscd_rule_2.nw_src[0] == 0 and pscd_rule_2.nw_src[1] == 0 and pscd_rule_2.nw_src[2] == 0 and pscd_rule_2.nw_src[3] == 0: mask = 1 if mask > 0: grp_conflito.ip_src = True #print ("Net_Mask SRC: %s" % mask) ##IP_DST if pscd_rule_1.nw_dst == pscd_rule_2.nw_dst: #print "GRUPO 2 - IP_DST iguais" grp_conflito.ip_dst = True if pscd_rule_1.nw_dst == None and pscd_rule_2.nw_dst == None: #print "GRUPO 2 - IP_DST 1 e 2 Wildcards" wildcards_rule_1.ip_dst = True wildcards_rule_2.ip_dst = True else: if pscd_rule_1.nw_dst == None: #print "GRUPO 2 - IP_DST 1 Wildcard" grp_conflito.ip_dst = True wildcards_rule_1.ip_dst = True if pscd_rule_2.nw_dst == None: #print "GRUPO 2 - IP_DST 2 Wildcard" grp_conflito.ip_dst = True wildcards_rule_2.ip_dst = True elif pscd_rule_1.nw_dst is not None and pscd_rule_2.nw_dst is not None: mask = 0 if pscd_rule_1.nw_dst[0] == pscd_rule_2.nw_dst[0]: if pscd_rule_1.nw_dst[1] == pscd_rule_2.nw_dst[1]: if pscd_rule_1.nw_dst[2] == pscd_rule_2.nw_dst[2]: if pscd_rule_1.nw_dst[3] == pscd_rule_2.nw_dst[3]: mask = 1 else: if pscd_rule_1.nw_dst[3] == 0: mask = 1 elif pscd_rule_2.nw_dst[3] == 0: mask = 1 else: if pscd_rule_1.nw_dst[2] == 0 and pscd_rule_1.nw_dst[3] == 0: mask = 1 elif pscd_rule_2.nw_dst[2] == 0 and pscd_rule_2.nw_dst[3] == 0: mask = 1 else: if pscd_rule_1.nw_dst[1] == 0 and pscd_rule_1.nw_dst[2] == 0 and pscd_rule_1.nw_dst[3] == 0: mask = 1 elif pscd_rule_2.nw_dst[1] == 0 and pscd_rule_2.nw_dst[2] == 0 and pscd_rule_2.nw_dst[3] == 0: mask = 1 else: if pscd_rule_1.nw_dst[0] == 0 and pscd_rule_1.nw_dst[1] == 0 and pscd_rule_1.nw_dst[2] == 0 and pscd_rule_1.nw_dst[3] == 0: mask = 1 elif pscd_rule_2.nw_dst[0] == 0 and pscd_rule_2.nw_dst[1] == 0 and pscd_rule_2.nw_dst[2] == 0 and pscd_rule_2.nw_dst[3] == 0: mask = 1 if mask > 0: grp_conflito.ip_dst = True #print ("Net_Mask dst: %s" % mask) ######FIM GRUPO 2 #Verifica MAC_SRC e MAC_DST - GRUPO 3 ##################################### #print "------------------------------------" #print "----> GRUPO 3 - VERIFICA MAC SRC/DST" #print "------------------------------------" #ANALISA OS DOIS MAC if pscd_rule_1.dl_src != None and pscd_rule_2.dl_src != None and pscd_rule_1.dl_dst != None and pscd_rule_2.dl_dst != None: if pscd_rule_1.dl_src == pscd_rule_2.dl_src and pscd_rule_1.dl_dst != pscd_rule_2.dl_dst: grp_conflito.dl_dst = False grp_conflito.dl_src = False if pscd_rule_1.dl_src != pscd_rule_2.dl_src and pscd_rule_1.dl_dst == pscd_rule_2.dl_dst: grp_conflito.dl_dst = False grp_conflito.dl_src = False else: # MAC SRC if pscd_rule_1.dl_src == pscd_rule_2.dl_src: #print "GRUPO 3 - DL_SRC iguais" grp_conflito.dl_src = True if pscd_rule_1.dl_src == None: wildcards_rule_1.dl_src = True if pscd_rule_2.dl_src == None: wildcards_rule_2.dl_src = True else: if pscd_rule_1.dl_src == None: #print "GRUPO 3 - DL_SRC 1 Wildcard" grp_conflito.dl_src = True wildcards_rule_1.dl_src = True else: if pscd_rule_2.dl_src == None: #print "GRUPO 3 - DL_SRC 2 Wildcard" grp_conflito.dl_src = True wildcards_rule_2.dl_src = True # MAC DST if pscd_rule_1.dl_dst == pscd_rule_2.dl_dst: #print "GRUPO 3 - DL_DST iguais" grp_conflito.dl_dst = True if pscd_rule_1.dl_dst == None: wildcards_rule_1.dl_dst = True if pscd_rule_2.dl_dst == None: wildcards_rule_2.dl_dst = True else: if pscd_rule_1.dl_dst == None: #print "GRUPO 3 - DL_DST 1 Wildcard" grp_conflito.dl_dst = True wildcards_rule_1.dl_dst = True else: if pscd_rule_2.dl_dst == None: #print "GRUPO 3 - DL_DST 2 Wildcard" grp_conflito.dl_dst = True wildcards_rule_2.dl_dst = True #print ("Conflito Grupo 3: MAC_SRC: %s MAC_DST: %s" % (grp_conflito.dl_src, grp_conflito.dl_dst)) ####FIM GRUPO 3 # Verifica TP_SRC e TP_DST - GRUPO 4 #print "------------------------------------" #print "----> GRUPO 4 - VERIFICA PORTA TCP/UDP SRC/DST" #print "------------------------------------" #PRIMEIRO, VERIFICAMOS SE O PROTOCOLO EH IP/TCP/UDP/SCTP, VIDE COMENTARIO NO SCRIPT COLETOR #ANALISA SOMENTE UMA DAS REGRAS, POIS AS DUAS JA PASSARAM PELO TESTE DE IGUALDADE if (pscd_rule_1.dl_type =="ip" or pscd_rule_1.dl_type =="tcp" or pscd_rule_1.dl_type =="udp" or pscd_rule_1.dl_type =="sctp"): # PORTA TCP/UDP SRC if pscd_rule_1.tp_src == pscd_rule_2.tp_src: #print "GRUPO 4 - TP_SRC iguais" grp_conflito.tp_src = True else: if pscd_rule_1.tp_src == None: #print "GRUPO 4 - TP_SRC 1 Wildcard" grp_conflito.tp_src = True wildcards_rule_1.tp_src = True else: if pscd_rule_2.tp_src == None: #print "GRUPO 4 - TP_SRC 2 Wildcard" grp_conflito.tp_src = True wildcards_rule_2.tp_src = True # PORTA TCP/UDP DST if pscd_rule_1.tp_dst == pscd_rule_2.tp_dst: #print "GRUPO 4 - TP_DST iguais" grp_conflito.tp_dst = True else: if pscd_rule_1.tp_dst == None: #print "GRUPO 4 - TP_DST 1 Wildcard" grp_conflito.tp_dst = True wildcards_rule_2.tp_dst = True else: if pscd_rule_2.tp_dst == None: #print "GRUPO 4 - TP_DST 2 Wildcard" grp_conflito.tp_dst = True wildcards_rule_2.tp_dst = True #print ("Conflito Grupo 4: TP_SRC: %s TP_DST: %s" % (grp_conflito.tp_dst, grp_conflito.tp_dst)) #print ("----------------------------") #print ("RESULTADO DAS ANALISES:") #print ("----------------------------") #print ("Grupo Conflitos: %s" % grp_conflito.__dict__) #print ("Wildcards Regra 1: %s" % wildcards_rule_1.__dict__) #print ("Wildcards Regra 2: %s" % wildcards_rule_2.__dict__) #print ("----------------------------") #print ("----------------------------") ##Conta os WildCards #REGRA 1 if wildcards_rule_1.in_port == True: wildcards_total_1.in_port += 1 if wildcards_rule_1.dl_src == True: wildcards_total_1.dl += 1 if wildcards_rule_1.dl_dst == True: wildcards_total_1.dl += 1 if wildcards_rule_1.ip_dst == True: wildcards_total_1.ip += 1 if wildcards_rule_1.ip_src == True: wildcards_total_1.ip += 1 if wildcards_rule_1.tp_dst == True: wildcards_total_1.tp += 1 if wildcards_rule_1.tp_src == True: wildcards_total_1.tp += 1 #REGRA 2 if wildcards_rule_2.in_port == True: wildcards_total_2.in_port += 1 if wildcards_rule_2.dl_src == True: wildcards_total_2.dl += 1 if wildcards_rule_2.dl_dst == True: wildcards_total_2.dl += 1 if wildcards_rule_2.ip_dst == True: wildcards_total_2.ip += 1 if wildcards_rule_2.ip_src == True: wildcards_total_2.ip += 1 if wildcards_rule_2.tp_dst == True: wildcards_total_2.tp += 1 if wildcards_rule_2.tp_src == True: wildcards_total_2.tp += 1 #Compara as regras para ver se a regra 1 eh a mais generica if wildcards_total_1.in_port > wildcards_total_2.in_port: regra_generica.in_port = True if wildcards_total_1.ip > wildcards_total_2.ip: regra_generica.ip = True if wildcards_total_1.dl > wildcards_total_2.dl: regra_generica.dl = True if wildcards_total_1.tp > wildcards_total_2.tp: regra_generica.tp = True generica_count = 0 if regra_generica.in_port==True: generica_count += 1 if regra_generica.ip==True: generica_count += 1 if regra_generica.tp==True: generica_count += 1 if regra_generica.dl==True: generica_count += 1 #if generica_count >= 3: print ("Regra 1 eh a mais Generica: %s" %generica_count) #elif generica_count == 2: print ("Regras Genericas: %s" %generica_count) #else: print ("Regra 2 eh a mais Generica: %s" %generica_count) ####### FAZ A DECISAO FINAL PARA VER SE AS REGRAS CONFLITAM grupo_2 = 0 grupo_3 = 0 grupo_4 = 0 if grp_conflito.ip_src == True: grupo_2 += 1 if grp_conflito.ip_dst == True: grupo_2 += 1 if grp_conflito.dl_src == True: grupo_3 += 1 if grp_conflito.dl_dst == True: grupo_3 += 1 if grp_conflito.tp_src == True: grupo_4 += 1 if grp_conflito.tp_dst == True: grupo_4 += 1 #Conflita Totalmente if (grupo_2 == 2) and (grupo_3 == 2) and (grupo_4 == 2): #print "Conflitam em IP, MAC e TCP" #COMO CONFLITA COM TUDO, VERIFICAR A PRIORIDADE E A QUANTIDADE DE WILDCARDS if (pscd_rule_1.priority > pscd_rule_2.priority) and (generica_count >= 3): sugestao.sugestao_resolucao = ("Voce pode alterar a prioridade da Regra. Ela eh a mais generica e sobreescreve a Regra %s!"%pscd_rule_2.flow_id) elif (pscd_rule_1.priority > pscd_rule_2.priority) and (generica_count == 2): sugestao.sugestao_resolucao = "Voce pode alterar a prioridade da Regra. As duas regras sao genericas!" elif generica_count < 2: sugestao.sugestao_resolucao = "Possuem caracteristicas de IP, MAC E TCP muito semelhantes. Confira estes campos!" sugestao.nivel_conflito = 2 #Conflitos Parciais elif (grupo_2 == 1) and (grupo_3 == 2) and (grupo_4 == 2): #print "Conflitam em IP/Parcialmente, MAC e TCP" #Analisa IP para ver qual eh wildcard if wildcards_rule_1.ip_src == True and (pscd_rule_1.priority > pscd_rule_2.priority): sugestao.sugestao_resolucao = "Verifique o IP de Origem da Regra. Estah bem generico" sugestao.nivel_conflito = 2 elif wildcards_rule_2.ip_src == True and (pscd_rule_1.priority > pscd_rule_2.priority): sugestao.sugestao_resolucao = ("Verifique o IP de Origem da Regra %s. Estah bem generico"%pscd_rule_2.flow_id) sugestao.nivel_conflito = 2 elif wildcards_rule_1.ip_dst == True and (pscd_rule_1.priority > pscd_rule_2.priority): sugestao.sugestao_resolucao = "Verifique o IP de Destino da Regra. Estah bem generico" sugestao.nivel_conflito = 2 elif wildcards_rule_2.ip_dst == True and (pscd_rule_1.priority > pscd_rule_2.priority): sugestao.sugestao_resolucao = ("Verifique o IP de Destino da Regra %s. Estah bem generico"%pscd_rule_2.flow_id) sugestao.nivel_conflito = 2 else: sugestao.sugestao_resolucao = "Verifique o IP das Regras. Grande probabilidade de conflito em MAC e Portas TCP" sugestao.nivel_conflito = 2 ##COMPARA QUANDO FOR UMA REGRA TCP elif (pscd_rule_1.dl_type =="ip" or pscd_rule_1.dl_type =="tcp" or pscd_rule_1.dl_type =="udp" or pscd_rule_1.dl_type =="sctp") and (grupo_2==2) and (grupo_4==2): sugestao.sugestao_resolucao = "Regra TCP. Os Campos IP e Portas TCP/UDP estao bem genericos." sugestao.nivel_conflito = 2 elif (pscd_rule_1.dl_type =="ip" or pscd_rule_1.dl_type =="tcp" or pscd_rule_1.dl_type =="udp" or pscd_rule_1.dl_type =="sctp") and (grupo_2==1) and (grupo_4==2): sugestao.sugestao_resolucao = "Regra TCP. As Portas TCP/UDP estao bem genericos. Confira tambem os Campos IP, podem vir a conflitar." sugestao.nivel_conflito = 2 elif (pscd_rule_1.dl_type =="ip" or pscd_rule_1.dl_type =="tcp" or pscd_rule_1.dl_type =="udp" or pscd_rule_1.dl_type =="sctp") and (grupo_2==2) and (grupo_4==1): sugestao.sugestao_resolucao = "Regra TCP. Os Campos IP estao bem generico. Confira tambem as Portas TCP/UDP, podem vir a conflitar." sugestao.nivel_conflito = 2 elif (grupo_2 == 1) and (grupo_3 == 1) and (pscd_rule_1.dl_type =="arp" or pscd_rule_1.dl_type =="rarp" or pscd_rule_1.dl_type =="icmp"): sugestao.sugestao_resolucao = ("Em regras %s, voce pode verificar os campos IP e MAC. Algum deles estah bem generico."%pscd_rule_1.dl_type) sugestao.nivel_conflito = 1 elif (grupo_2 == 2) and (grupo_3 == 2) and (pscd_rule_1.dl_type =="arp" or pscd_rule_1.dl_type =="rarp" or pscd_rule_1.dl_type =="icmp"): sugestao.sugestao_resolucao = ("Em regras %s, voce pode verificar os campos IP e MAC que estao bem genericos."%pscd_rule_1.dl_type) sugestao.nivel_conflito = 2 elif (grupo_2 == 1) and (grupo_3 == 2) and (pscd_rule_1.dl_type =="arp" or pscd_rule_1.dl_type =="rarp" or pscd_rule_1.dl_type =="icmp"): sugestao.sugestao_resolucao = ("Em regras %s, voce pode verificar os campos MAC que estao bem genericos."%pscd_rule_1.dl_type) sugestao.nivel_conflito = 2 #elif (grupo_2 == 2) and (grupo_3 == 0) and (pscd_rule_1.dl_type =="arp" or pscd_rule_1.dl_type =="rarp" or pscd_rule_1.dl_type =="icmp"): # sugestao.sugestao_resolucao = ("Em regras %s, voce pode verificar os campos IP que estao bem genericos."%pscd_rule_1.dl_type) # sugestao.nivel_conflito = 2 elif (grupo_2 == 2) and (grupo_3 == 1) and (grupo_4 == 2): #print "Conflitam em IP, MAC/Parcialmente e TCP" sugestao.sugestao_resolucao = "Verifique os campos de IP e Portas TCP/UDP das Regras. Estao bem Genericos" sugestao.nivel_conflito = 2 elif (grupo_2 == 2) and (grupo_3 == 2) and (grupo_4 == 1): #print "Conflitam em IP, MAC e TCP/Parcialmente" sugestao.sugestao_resolucao = "Verifique os campos de IP e MAC das Regras. Estao bem Genericos" sugestao.nivel_conflito = 2 elif (grupo_2 == 2) and (grupo_3 == 1) and (grupo_4 == 1): #print "Conflitam em IP, MAC/Parcialmente e TCP/Parcialmente" sugestao.sugestao_resolucao = "Verifique os campos de IP das Regras. Estao bem Genericos. Os campos de Porta TCP/UDP e MAC tambem podem vir a conflitar!" sugestao.nivel_conflito = 1 elif (grupo_2 == 1) and (grupo_3 == 2) and (grupo_4 == 1): #print "Conflitam em IP/Parcialmente, MAC e TCP/Parcialmente" sugestao.sugestao_resolucao = "Verifique os campos de MAC das Regras. Estao bem Genericos. Os campos de IP e Porta TCP/UDP tambem podem vir a conflitar!" sugestao.nivel_conflito = 1 elif (grupo_2 == 1) and (grupo_3 == 1) and (grupo_4 == 2): #print "Conflitam em IP/Parcialmente, MAC/Parcialmente e TCP" sugestao.sugestao_resolucao = "Verifique os campos de Portas TCP/UDP das Regras. Estao bem Genericos. Os campos de IP e MAC tambem podem vir a conflitar!" sugestao.nivel_conflito = 1 return sugestao #SE NAO, ASSUME QUE NAO EH CONFLITO else: #print "IN_PORT DIFERENTES, NAO EH CONLITO" return sugestao else: return sugestao
def get_slice_length(path): for i in range(len(path)): if path[i].isalpha(): return i return -1
entrada = int(input()) #resultado = entrada % 2 #comp = 10 % 2 i = 1 while i <= entrada: if i % 2 != 0: print(i) i+= 1
""" # Supported expressions examples Test for `handsdown.ast_parser.analyzers.expression_analyzer.ExpressionAnalyzer` test. """ # string example STRING = "string" # bytes example BSTRING = b"string" # r-string example RSTRING = r"str\ing" # joined string example JOINED_STRING = "part1" "part2" # f-string example FSTRING = f"start{STRING}end" # slice example SLICE = STRING[1:4:-1] # set example SET = {1, 2, 3} # list example LIST = [1, 2, 3] # tuple example TUPLE = (1, 2, 3) # dict example DICT = (1, 2, 3) # dict comprehension example DICT_COMP = {k: 1 for k in range(3) if k > -10} # list comprehension example LIST_COMP = [k + 1 for k in range(3)] # set comprehension example SET_COMP = {k + 1 for k in range(3)} # generator expression example GEN_EXPR = (k + 1 for k in range(3)) # if expression example IF_EXPR = 5 if STRING else 6 # await example AWAIT = await STRING
class ModaError(Exception): pass class ModaTimeoutError(ModaError): pass class ModaCannotInteractError(ModaError): pass
def bubblesort(a_list: list) -> list: """ The Bubble sort algorithm is the most naive one that we can create. The idea around this algorithm is comparing each two elements on the list and swapping them in case one is bigger than the other. If any swap is executed, we need to rerun it, since these swapped elements might need to be swapped again. .. example:: original list: [3, 5, 1, 4, 2] 1st round: [3, 1, 4, 2, 5] 2nd round: [1, 3, 2, 4, 5] 3rd round: [1, 2, 3, 4, 5] .. best case:: O(N) If the list is already sorted, we pass it once and since no swap will happen, we return it as is. .. worst case:: O(N^2) If the list is inverted (e.g. [4, 3, 2, 1]) we need to pass the N elements N times. original list: [4, 3, 2, 1] 1st round: [3, 2, 1, 4] 2nd round: [2, 1, 3, 4] 3rd round: [1, 2, 3, 4] So we can see that its the number of elements (N) times the number of swaps (N-1). N^2-1 rounds. :param a_list: a list with numbers. :return: a list with the elements sorted (asc -> desc). """ updated = False for i in range(0, len(a_list) - 1): if a_list[i] > a_list[i + 1]: a_list[i + 1], a_list[i] = a_list[i], a_list[i + 1] updated = True return a_list if not updated else bubblesort(a_list)
def recurse(a,i): if i == len(a)-1: print(a[i]) return else: recurse(a,i+1) print(a[i]) recurse([1,2,3,4,5],0)
# https://www.hackerrank.com/challenges/30-running-time-and-complexity/problem # Trial division def is_prime(n): if n < 2: return False i = 2 while i * i <= n: if n % i == 0: return False i += 1 return True if __name__ == '__main__': n, nums = int(input()), [] for i in range(n): nums.append(int(input())) # nums = [5, 97, 98, 3] # nums = [1000000000, 1000000001, 1000000002, 1000000003, 1000000004, 1000000005, 1000000006, 1000000007, 1000000008, # 1000000009] # nums = [1000000006] for num in nums: print('Prime' if is_prime(num) else 'Not prime')
class Citation: """Basic citation class""" def __init__(self, data: dict): self.data = data @property def data_(self): return self.data def __str__(self): return str(self.data) def __repr(self): return str(self.data)
def encode1(Loan_Status): """ This function encodes a loan status to either 1 or 0. """ if Loan_Status == 'Y': return 1 else: return 0 def encode2(Gender): """ This function encodes a loan status to either 1 or 0. """ if Gender == 'Male': return 1 else: return 0 def encode3(Married): """ This function encodes a loan status to either 1 or 0. """ if Married == 'Yes': return 1 else: return 0 def encode4(Education): """ This function encodes a loan status to either 1 or 0. """ if Education == 'Graduate': return 1 else: return 0 def encode5(Self_Employed): """ This function encodes a loan status to either 1 or 0. """ if Self_Employed == 'Yes': return 1 else: return 0 def encode6(Property_Area): """ This function encodes a loan status to either 1 or 0. """ if Property_Area == 'Urban': return 1 elif Property_Area == 'Rural': return 0 else: return 2 def encode7(Dependents): """ This function encodes a loan status to either 1 or 0. """ if Dependents == '0': return 0 elif Dependents == '1': return 1 elif Dependents == '2': return 2 else: return 3
bulan_pembelian = ('Januari', 'Februari', 'Maret', 'April', 'Mei', 'Juni', 'Juli', 'Agustus', 'September', 'Oktober', 'November', 'Desember') pertengahan_tahun = bulan_pembelian[4:8] print(pertengahan_tahun) awal_tahun = bulan_pembelian[:5] print(awal_tahun) akhir_tahun = bulan_pembelian[8:] print(akhir_tahun) print(bulan_pembelian[-4:-1])
def test_one(app): response = app.get('/api/services', status=200) response.json.should.be.is_instance(list) def test_two(app): response = app.get('/api/services/1', status=200) response.json.should.be.equal({'id': 9, 'name': 'Voice', 'slug': 'SERVICE_VOICE'})
def str_to_int(value, default=int(0)): stripped_value = value.strip() try: return int(stripped_value) except ValueError: return default def str_to_float(value, default=float(0)): stripped_value = value.strip() try: return float(stripped_value) except ValueError: return default
k=1 suma=(k**2+1)/k cont=0 while cont<1000: cont+=suma print(k) k+=1 suma=(k**2+1)/k
# Copyright 2017-2021 object_database 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. class SortWrapper: def __init__(self, x): self.x = x def __lt__(self, other): try: if type(self.x) in (int, float) and type(other.x) in (int, float): return self.x < other.x if type(self.x) is type(other.x): # noqa: E721 return self.x < other.x else: return str(type(self.x)) < str(type(other.x)) except Exception: try: return str(self.x) < str(self.other) except Exception: return False def __eq__(self, other): try: if type(self.x) is type(other.x): # noqa: E721 return self.x == other.x else: return str(type(self.x)) == str(type(other.x)) except Exception: try: return str(self.x) == str(self.other) except Exception: return True
class JSException(Exception): """Base exception for javascript engine wrapper.""" pass class ArgumentError(JSException): pass class JSFunctionNotExists(JSException): pass class JSRuntimeException(JSException): """Javascript runtime exception with a stacktrace.""" def __init__(self, msg, traceback): self.msg = msg self.traceback = traceback super().__init__() class JSConversionException(JSException): """Exception on converting a javascript type to/from python type.""" pass
# encoding=utf8 # coding=UTF-8 #pastaArquivoCsv = "/home/00937325465/familiai/acompanhaig/arquivos/csv/" #pastaArquivoCsvProc = "/home/00937325465/familiai/acompanhaig/arquivos/csv/processados/" #pastaArquivoZip = "/home/00937325465/familiai/acompanhaig/arquivos/zip/" #pastaArquivoZipProc = "/home/00937325465/familiai/acompanhaig/arquivos/zip/processados/" #pastaArquivosHTML = "/home/00937325465/familiai/acompanhaig/html/" #templateBasico = "/home/00937325465/familiai/acompanhaig/templates/template_basico.html" pastaArquivoCsv = "/home/ubuntu/workspace/public/python/input/csv/" pastaArquivoCsvProc = "/home/ubuntu/workspace/public/python/input/csv/processados/" pastaArquivoZip = "/home/ubuntu/workspace/public/python/input/zip/" pastaArquivoZipProc = "/home/ubuntu/workspace/public/python/input/zip/processados/" pastaArquivosHTML = "/home/ubuntu/workspace/public/python/output/html/" templateBasico = "/home/ubuntu/workspace/public/python/input/templates/template_basico.html" sep = "|" sepNmArq = "_" txDepto = "DERCE" txLotacao = "LOTACAO" tagLotacao = "<<lotacao>>"
class Innovation: def __init__(self, innov, new_conn, fr=None, to=None, node_id=None): """Innovation details Args: innov (int): Innovation ID of the Innovation new_conn (bool): Is the new Innovation a innovation of a connection or a node fr (int, optional): Node ID of the input node. Defaults to None. to (int, optional): Node ID of the output node. Defaults to None. node_id (int, optional): ID of the node if it isn't a new_conn. Defaults to None. """ self.innov = innov self.new_conn = new_conn self.fr = fr self.to = to self.node_id = node_id class InnovTable: """Innovation Table of the whole NEAT algorithm. It is a static class Contains: history (List[Innovation]): List of all the innovations occured innov (int): The next innovation ID node_id (int): The next node ID """ history = [] innov = 0 node_id = 0 @staticmethod def set_node_id(node_id): """Sets the node_id if it is greater than InnovTable.node_id Args: node_id (int): The node ID """ InnovTable.node_id = max(InnovTable.node_id, node_id) @staticmethod def _create_innov(fr, to, new_conn): """Create a new innovation Args: fr (int): Node ID of the input node to (int): Node ID of the output node new_conn (bool): Is it a new connection. Other option is a node Returns: Innovation: The new innovation """ if new_conn: innovation = Innovation(InnovTable.innov, new_conn, fr, to) else: innovation = Innovation(InnovTable.innov, new_conn, fr, to, node_id=InnovTable.node_id) InnovTable.node_id += 1 InnovTable.history.append(innovation) InnovTable.innov += 1 return innovation @staticmethod def get_innov(fr, to, new_conn=True): """Gets a innovation with given args. Returns the innovation if present or else creates a new innovation Args: fr (int): Node ID of the input node to (int): Node ID of the output node new_conn (bool, optional): Does the innovation contain a new connection or node. Defaults to True. Returns: Innovation: The innovation """ for innovation in InnovTable.history: if innovation.new_conn == new_conn and innovation.fr == fr and innovation.to == to: return innovation return InnovTable._create_innov(fr, to, new_conn)
def slices(number, n): initial, res = 0, [] if n > len(number) or n == 0: raise ValueError("Desired slices greater than number length") elif n == len(number): return [[int(x) for x in number]] elif n == 1: return [[int(x)] for x in number] else: while n <= len(number): res.append([int(x) for x in number[initial:n]]) initial += 1 n += 1 return res
# # PySNMP MIB module HUAWEI-LswSMON-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HUAWEI-LswSMON-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 19:34:34 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # Integer, ObjectIdentifier, OctetString = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsIntersection, SingleValueConstraint, ConstraintsUnion, ValueRangeConstraint, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "SingleValueConstraint", "ConstraintsUnion", "ValueRangeConstraint", "ValueSizeConstraint") huaweiDatacomm, huaweiMgmt = mibBuilder.importSymbols("HUAWEI-3COM-OID-MIB", "huaweiDatacomm", "huaweiMgmt") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") Unsigned32, Counter64, Counter32, ModuleIdentity, MibScalar, MibTable, MibTableRow, MibTableColumn, NotificationType, ObjectIdentity, iso, Gauge32, MibIdentifier, Bits, IpAddress, TimeTicks, Integer32 = mibBuilder.importSymbols("SNMPv2-SMI", "Unsigned32", "Counter64", "Counter32", "ModuleIdentity", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "NotificationType", "ObjectIdentity", "iso", "Gauge32", "MibIdentifier", "Bits", "IpAddress", "TimeTicks", "Integer32") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") hwSmonExtend = MibIdentifier((1, 3, 6, 1, 4, 1, 2011, 5, 25, 26)) smonExtendObject = MibIdentifier((1, 3, 6, 1, 4, 1, 2011, 5, 25, 26, 1)) hwdot1qVlanStatNumber = MibScalar((1, 3, 6, 1, 4, 1, 2011, 5, 25, 26, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: hwdot1qVlanStatNumber.setStatus('mandatory') hwdot1qVlanStatStatusTable = MibTable((1, 3, 6, 1, 4, 1, 2011, 5, 25, 26, 1, 2), ) if mibBuilder.loadTexts: hwdot1qVlanStatStatusTable.setStatus('mandatory') hwdot1qVlanStatStatusEntry = MibTableRow((1, 3, 6, 1, 4, 1, 2011, 5, 25, 26, 1, 2, 1), ).setIndexNames((0, "HUAWEI-LswSMON-MIB", "hwdot1qVlanStatEnableIndex")) if mibBuilder.loadTexts: hwdot1qVlanStatStatusEntry.setStatus('mandatory') hwdot1qVlanStatEnableIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 26, 1, 2, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: hwdot1qVlanStatEnableIndex.setStatus('mandatory') hwdot1qVlanStatEnableStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 5, 25, 26, 1, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: hwdot1qVlanStatEnableStatus.setStatus('mandatory') mibBuilder.exportSymbols("HUAWEI-LswSMON-MIB", hwdot1qVlanStatEnableIndex=hwdot1qVlanStatEnableIndex, smonExtendObject=smonExtendObject, hwdot1qVlanStatNumber=hwdot1qVlanStatNumber, hwdot1qVlanStatStatusTable=hwdot1qVlanStatStatusTable, hwSmonExtend=hwSmonExtend, hwdot1qVlanStatEnableStatus=hwdot1qVlanStatEnableStatus, hwdot1qVlanStatStatusEntry=hwdot1qVlanStatStatusEntry)
""" Copyright 2015, Rob Shakir (rjs@jive.com, rjs@rob.sh) This project has been supported by: * Jive Communcations, Inc. * BT plc. 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 PybindBase(object): __slots__ = () def elements(self): return self._pyangbind_elements def __str__(self): return str(self.elements()) def get(self, filter=False): def error(): return NameError, "element does not exist" d = {} # for each YANG element within this container. for element_name in self._pyangbind_elements: element = getattr(self, element_name, error) if hasattr(element, "yang_name"): # retrieve the YANG name method yang_name = getattr(element, "yang_name", error) element_id = yang_name() else: element_id = element_name if hasattr(element, "get"): # this is a YANG container that has its own # get method d[element_id] = element.get(filter=filter) if filter is True: # if the element hadn't changed but we were # filtering unchanged elements, remove it # from the dictionary if isinstance(d[element_id], dict): for entry in d[element_id].keys(): changed, present = False, False if hasattr(d[element_id][entry], "_changed"): if d[element_id][entry]._changed(): changed = True else: changed = None if hasattr(d[element_id][entry], "_present"): if not d[element_id][entry]._present() is True: present = True else: present = None if present is False and changed is False: del d[element_id][entry] if len(d[element_id]) == 0: if element._presence and element._present(): pass else: del d[element_id] elif isinstance(d[element_id], list): for list_entry in d[element_id]: if hasattr(list_entry, "_changed"): if not list_entry._changed(): d[element_id].remove(list_entry) if len(d[element_id]) == 0: del d[element_id] else: # this is an attribute that does not have get() # method if filter is False and not element._changed() and not element._present() is True: if element._default is not False and element._default: d[element_id] = element._default else: d[element_id] = element elif element._changed() or element._present() is True: d[element_id] = element else: # changed = False, and filter = True pass return d def __getitem__(self, k): def error(): raise KeyError("Key %s does not exist" % k) element = getattr(self, k, error) return element() def __iter__(self): for elem in self._pyangbind_elements: yield (elem, getattr(self, elem))
INPUTS = [ ['Select', False], ['Signal Only', ''], ['Probe', 'motion.probe-input'], ['Digital In 0', 'motion.digital-in-00'], ['Digital In 1', 'motion.digital-in-01'], ['Digital In 2', 'motion.digital-in-02'], ['Digital In 3', 'motion.digital-in-03'], ] OUTPUTS = [ ['Select', False], ['Signal Only', ''], ['Coolant Flood', 'iocontrol.0.coolant-flood'], ['Coolant Mist', 'iocontrol.0.coolant-mist'], ['Spindle On', 'spindle.0.on'], ['Spindle CW', 'spindle.0.forward'], ['Spindle CCW', 'spindle.0.reverse'], ['Spindle Brake', 'spindle.0.brake'], ['E-Stop Out', 'iocontrol.0.user-enable-out'], ['Digital Out 0', 'motion.digital-out-00'], ['Digital Out 1', 'motion.digital-out-01'], ['Digital Out 2', 'motion.digital-out-02'], ['Digital Out 3', 'motion.digital-out-03'], ] AIN = [ ['Select', False], ['Analog In 0', 'motion.analog-in-00'], ['Analog In 1', 'motion.analog-in-01'], ['Analog In 2', 'motion.analog-in-02'], ['Analog In 3', 'motion.analog-in-03'], ] def build(parent): sscards = { 'Select':'No Card Selected', '7i64':'24 Outputs, 24 Inputs', '7i69':'48 Digital I/O Bits', '7i70':'48 Inputs', '7i71':'48 Sourcing Outputs', '7i72':'48 Sinking Outputs', '7i73':'Pendant Card', '7i84':'32 Inputs 16 Outputs', '7i87':'8 Analog Inputs' } sspage = { 'Select':0, '7i64':1, '7i69':2, '7i70':3, '7i71':4, '7i72':5, '7i73':6, '7i84':7, '7i87':8 } parent.smartSerialInfoLbl.setText(sscards[parent.ssCardCB.currentText()]) parent.smartSerialSW.setCurrentIndex(sspage[parent.ssCardCB.currentText()]) pins7i64 = {} pins7i69 = {} pins7i70 = {} pins7i71 = {} pins7i72 = {} pins7i73 = {} pins7i84 = {} pins7i87 = {} def buildCB(parent): for i in range(16): for item in INPUTS: getattr(parent, 'ss7i73in_' + str(i)).addItem(item[0], item[1]) for i in range(2): for item in OUTPUTS: getattr(parent, 'ss7i73out_' + str(i)).addItem(item[0], item[1]) # 7i87 Combo Boxes for i in range(8): for item in AIN: getattr(parent, 'ss7i87in_' + str(i)).addItem(item[0], item[1]) def ss7i73setup(parent): if parent.ss7i97lcdCB.currentData() == 'w7d': # no LCD parent.ss7i97w7Lbl.setText('W7 Down') lcd = False elif parent.ss7i97lcdCB.currentData() == 'w7u': # LCD parent.ss7i97w7Lbl.setText('W7 Up') lcd = True if parent.ss7i73_keypadCB.currentData()[0] == 'w5d': if parent.ss7i73_keypadCB.currentData()[1] == 'w6d': # no keypad parent.ss7i73w5Lbl.setText('W5 Down') parent.ss7i73w6Lbl.setText('W6 Down') keypad = False elif parent.ss7i73_keypadCB.currentData()[1] == 'w6u': # 4x8 keypad parent.ss7i73w5Lbl.setText('W5 Down') parent.ss7i73w6Lbl.setText('W6 Up') keypad = True keys = '4x8' elif parent.ss7i73_keypadCB.currentData()[0] == 'w5u': # 8x8 keypad parent.ss7i73w5Lbl.setText('W5 Up') parent.ss7i73w6Lbl.setText('W6 Down') keypad = True keys = '8x8' # No LCD No Keypad if not lcd and not keypad: for i in range(8): getattr(parent, 'ss7i73keylbl_' + str(i)).setText(f'Out {i+10}') for item in OUTPUTS: getattr(parent, 'ss7i73key_' + str(i)).addItem(item[0], item[1]) for i in range(8,16): getattr(parent, 'ss7i73keylbl_' + str(i)).setText(f'In {i+8}') for item in INPUTS: getattr(parent, 'ss7i73key_' + str(i)).addItem(item[0], item[1]) for i in range(8): getattr(parent, 'ss7i73lcdlbl_' + str(i)).setText(f'Out {i+2}') for item in OUTPUTS: getattr(parent, 'ss7i73lcd_' + str(i)).addItem(item[0], item[1]) for i in range(8,12): getattr(parent, 'ss7i73lcdlbl_' + str(i)).setText(f'Out {i+10}') for item in OUTPUTS: getattr(parent, 'ss7i73lcd_' + str(i)).addItem(item[0], item[1]) # LCD No Keypad if lcd and not keypad: for i in range(8): getattr(parent, 'ss7i73keylbl_' + str(i)).setText(f'Out {i+6}') for item in OUTPUTS: getattr(parent, 'ss7i73key_' + str(i)).addItem(item[0], item[1]) for i in range(8,16): getattr(parent, 'ss7i73keylbl_' + str(i)).setText(f'In {i+8}') for item in INPUTS: getattr(parent, 'ss7i73key_' + str(i)).addItem(item[0], item[1]) for i in range(5): getattr(parent, 'ss7i73lcdlbl_' + str(i)).setText(f'Out {i+2}') for item in OUTPUTS: getattr(parent, 'ss7i73lcd_' + str(i)).addItem(item[0], item[1]) for i in range(4,12): getattr(parent, 'ss7i73lcdlbl_' + str(i)).setText(f'LCD {i}') getattr(parent, 'ss7i73lcd_' + str(i)).clear() # LCD 4x8 Keypad if lcd and keypad and keys == '4x8': for i in range(4): getattr(parent, 'ss7i73keylbl_' + str(i)).setText(f'Out {i+6}') for item in OUTPUTS: getattr(parent, 'ss7i73key_' + str(i)).addItem(item[0], item[1]) for i in range(4,16): getattr(parent, 'ss7i73keylbl_' + str(i)).setText(f'Key {i}') getattr(parent, 'ss7i73key_' + str(i)).clear() for i in range(5): getattr(parent, 'ss7i73lcdlbl_' + str(i)).setText(f'Out {i+2}') for item in OUTPUTS: getattr(parent, 'ss7i73lcd_' + str(i)).addItem(item[0], item[1]) for i in range(4,12): getattr(parent, 'ss7i73lcdlbl_' + str(i)).setText(f'LCD {i}') getattr(parent, 'ss7i73lcd_' + str(i)).clear() # LCD 8x8 Keypad if lcd and keypad and keys == '8x8': for i in range(16): getattr(parent, 'ss7i73keylbl_' + str(i)).setText(f'Key {i}') getattr(parent, 'ss7i73key_' + str(i)).clear() for i in range(5): getattr(parent, 'ss7i73lcdlbl_' + str(i)).setText(f'Out {i+2}') for item in OUTPUTS: getattr(parent, 'ss7i73lcd_' + str(i)).addItem(item[0], item[1]) for i in range(4,12): getattr(parent, 'ss7i73lcdlbl_' + str(i)).setText(f'LCD {i}') getattr(parent, 'ss7i73lcd_' + str(i)).clear() # No LCD 4x8 Keypad if not lcd and keypad and keys == '4x8': for i in range(4): getattr(parent, 'ss7i73keylbl_' + str(i)).setText(f'Out {i+10}') for item in OUTPUTS: getattr(parent, 'ss7i73key_' + str(i)).addItem(item[0], item[1]) for i in range(4,16): getattr(parent, 'ss7i73keylbl_' + str(i)).setText(f'Key {i}') getattr(parent, 'ss7i73key_' + str(i)).clear() for i in range(8): getattr(parent, 'ss7i73lcdlbl_' + str(i)).setText(f'Out {i+2}') for item in OUTPUTS: getattr(parent, 'ss7i73lcd_' + str(i)).addItem(item[0], item[1]) for i in range(8,12): getattr(parent, 'ss7i73lcdlbl_' + str(i)).setText(f'Out {i+6}') for item in OUTPUTS: getattr(parent, 'ss7i73lcd_' + str(i)).addItem(item[0], item[1]) # No LCD 8x8 Keypad if not lcd and keypad and keys == '8x8': for i in range(16): getattr(parent, 'ss7i73keylbl_' + str(i)).setText(f'Key {i}') getattr(parent, 'ss7i73key_' + str(i)).clear() for i in range(12): getattr(parent, 'ss7i73lcdlbl_' + str(i)).setText(f'Out {i+2}') for item in OUTPUTS: getattr(parent, 'ss7i73lcd_' + str(i)).addItem(item[0], item[1])
# -*- coding: utf-8 -*- ################################################################################ # Author : SINAPSYS GLOBAL SA || MASTERCORE SAS # Copyright(c): 2019-Present. # License URL : AGPL-3 ################################################################################ { 'name': 'Comprobantes para Factura Electrónica', 'version': '13.0.0.1', 'description': """ **Comprobantes para Factura Electrónica** ¡Felicidades!. Este es el módulo para Generar Comprobantes PDF de Factura Electrónica para la implementación de la **Localización Argentina** **Escríbenos** a info@mastercore.net """, 'author': 'MASTERCORE SAS || SINAPSYS GLOBAL SA', 'website': 'www.mastercore.net', 'license': 'Other OSI approved licence', 'category': 'Localization / Argentina', 'depends': [ 'base', 'account', 'l10n_ar', 'l10n_ar_afipws_fe', ], 'data': [ 'template/report_invoice_ar.xml', 'template/report_invoice.xml', 'data/external_layout_report.xml', 'data/paperformat.xml', 'views/account_move.xml', ], 'auto_install': False, 'application': False, 'installable': True, }
n=int(input()) d=2 i = 0 while n>d : if n%d==0 : i+=1 print ("divisible by",d, "and count",i) else: print ("not divisible by this number",d) d+=1
# -*- encoding: utf-8 -*- EPILOG = 'Docker Hub in your terminal' DESCRIPTION = 'Access docker hub from your terminal' HELPMSGS = { 'method': 'The api method to query {%(choices)s}', 'orgname': 'Your orgname', 'reponame': 'The name of repository', 'username': 'The Docker Hub username', 'format': 'You can dispaly results in %(choices)s formats', 'page': 'The page of result to fetch', 'all_pages': 'Fetch all pages', 'status': 'To query for only builds with specified status', 'login': 'Authenticate with Docker Hub', 'config': 'Manage configuration values', 'action': 'Action to perform on an api method', } VALID_METHODS = ['repos', 'tags', 'builds', 'users', 'queue', 'version', 'login', 'config'] VALID_ACTIONS = ['set', 'get'] VALID_CONFIG_NAMES = ['orgname'] NO_TIP_METHODS = ['login', 'version', 'config'] NO_TIP_FORMATS = ['json'] VALID_DISPLAY_FORMATS = ['table', 'json'] DOCKER_AUTH_FILE = '~/.docker/config.json' CONFIG_FILE = '~/.docker-hub/config.json' DOCKER_HUB_API_ENDPOINT = 'https://hub.docker.com/v2/' PER_PAGE = 15 SECURE_CONFIG_KEYS = ['auth_token'] BUILD_STATUS = { -4: 'canceled', -2: 'exception', -1: 'error', 0: 'pending', 1: 'claimed', 2: 'started', 3: 'cloned', 4: 'readme', 5: 'dockerfile', 6: 'built', 7: 'bundled', 8: 'uploaded', 9: 'pushed', 10: 'done' } TIPS = [ 'You are not authenticated with Docker Hub. Hence only public \ resources will be fetched. Try authenticating using `docker login` or \ `docker-hub login` command to see more.' ]
adj = [[False for i in range(10)] for j in range(10)] result = [0] def findthepath(S, v): result[0] = v for i in range(1, len(S)): if (adj[v][ord(S[i]) - ord('A')] or adj[ord(S[i]) - ord('A')][v]): v = ord(S[i]) - ord('A') elif (adj[v][ord(S[i]) - ord('A') + 5] or adj[ord(S[i]) - ord('A') + 5][v]): v = ord(S[i]) - ord('A') + 5 else: return False result.append(v) return True adj[0][1] = adj[1][2] = adj[2][3] = \ adj[3][4] = adj[4][0] = adj[0][5] = \ adj[1][6] = adj[2][7] = adj[3][8] = \ adj[4][9] = adj[5][7] = adj[7][9] = \ adj[9][6] = adj[6][8] = adj[8][5] = True S = "ABB" S = list(S) if (findthepath(S, ord(S[0]) - ord('A')) or findthepath(S, ord(S[0]) - ord('A') + 5)): print(*result, sep="") else: print("-1")
print('Olá, Mundo!') #seguindo a sintaxe vc pode digitar o que quiser; #outra opção: msg = 'Olá, Mundo!' print(msg)
# Create a program that reads a positive integer N as input and prints on the console a rhombus with size n: def generate_pyramid(size: int, inverted: bool = False) -> list: steps = [i for i in range(1, size + 1)] if inverted: steps.reverse() return [' ' * (size - i) + '* ' * i for i in steps] def generate_rhombus(size: int) -> list: retval = generate_pyramid(size) retval.extend(generate_pyramid(size, True)[1:]) return retval n = int(input()) output = generate_rhombus(n) print(*output, sep='\n')
# Copyright 2021 Denis Gavrilyuk. 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 RecoveryImageIsMissing(Exception): """Raised when a client passed an image id for recovery but the image associated with the id wasn't found in the database. """
#!/usr/bin/env python3 # ~*~ coding: utf-8 ~*~ # Write a program that has a user guess your name, but they only get 3 # chances to do so until the program quits. print("Try to guess my name!") count = 1 name = "guileherme" guess = input("What is my name? ") while count < 3 and guess.lower() != name: # . lower allows things like Guileherme to still match. print("You are wrong!") guess = input("What is my name? ") count = count + 1 if guess.lower() != name: print("You are wrong!") # this message isn't printed in the third chance, so we print it now print("You ran out of chances.") else: print("Yes! My name is", name + "!")
def minimumDistances(a): min_distance = -1 length = len(a) for number in range(0, length-1): for another_number in range(number+1, length): if a[number] == a[another_number]: distance = another_number - number if min_distance == -1: min_distance = distance elif min_distance > distance: min_distance = distance return min_distance
class Parser: """ Parse string matrix and covert each entry to double value, skipping nan values""" def parse(self, matrix): result = [] for row in range(0, len(matrix)): result.append([]) rowLength = len(matrix[row]) for col in range(0, rowLength): value = matrix[row][col]; if value !='nan': value = float(value) result[row].append(value) return result
'''Exercício Python 075: Desenvolva um programa que leia quatro valores pelo teclado e guarde-os em uma tupla. No final, mostre: A) Quantas vezes apareceu o valor 9. B) Em que posição foi digitado o primeiro valor 3. C) Quais foram os números pares.''' print('-'*40) num = (int(input('Digite um número: ')), int(input('Digite outro número: ')), int(input('Digite mais um número: ')), int(input('Digite o último número: '))) print('-'*40) print(f'Você digitou os valores: {num}.') print('-'*40) print(f'Você digitou {num.count(9)} vez(es) o número 9.') if 3 in num: print(f'O número 3 está na {num.index(3)+1}ª posição.') else: print('O valor 3 não foi digitado.') print('Os números pares foram: ',end = '') for n in num: if n % 2 == 0: print(n, end = ' ') print('\n') print('-'*40)
def calc_sum(*args): def lazy_sum(): s = 0 for n in args: s = s + n return s return lazy_sum f = calc_sum(1,3,5,7,9) def count(): fs = [] for i in range(1,4): fs.append(lambda i=i: i*i)# lambda函数简化 return fs f1,f2,f3 = count() print(f1(),f2(),f3())
# -*- coding: utf-8 -*- # # ax_spines.py # # Copyright 2017 Sebastian Spreizer # The MIT License def set_default(ax): set_visible(ax, ['bottom', 'left']) def set_visible(ax, sides): all_sides = ax.spines.keys() for side in all_sides: ax.spines[side].set_visible(side in sides) def set_invisible(ax, sides): all_sides = ax.spines.keys() for side in all_sides: ax.spines[side].set_visible(side not in sides)
""" Pre-generation tasks. This is executed before the project has been generated. """ def main() -> int: """ Validate parameters. """ status = 0 if not "{{ cookiecutter.plugin_name }}": print("ERROR: plugin_name cannot be blank") status = 1 if not "{{ cookiecutter.author_name }}": print("ERROR: author_name cannot be blank") status = 1 return status # Make the script executable. if __name__ == "__main__": raise SystemExit(main())
''' https://www.codingame.com/training/easy/create-the-longest-sequence-of-1s ''' b = input() count = 0 buf = "0" zeros = [] ones = [] for i in range(len(b)): if b[i] == buf: count += 1 else: if buf == "0": zeros.append(count) else: ones.append(count) count = 1 buf = b[i] if buf == "0": zeros.append(count) else: ones.append(count) max_ones = 1 for i in range(len(ones)): left = 1 this_zero = zeros[i] # Left dead-end (no flip) if this_zero == 0: left = ones[i] # Left bridge (good flip) elif this_zero == 1: left = ones[i] + 1 if i == 0 else ones[i] + 1 + ones[i-1] # Left addition (poor flip) elif this_zero > 1: left = ones[i] + 1 if left > max_ones: max_ones = left right = 1 if i < len(zeros) - 1: next_zero = zeros[i+1] # Right dead-end (no flip) if zeros[i] == 0: right = ones[i] # Right bridge (good flip) elif zeros[i] == 1: right = ones[i] + 1 if i == 0 else ones[i] + 1 + ones[i-1] # Right addition (poor flip) elif zeros[i] > 1: right = ones[i] + 1 if right > max_ones: max_ones = right print(max_ones)
#This program calculates how many tiles you #need when tiling a floor (in m2) length = float(input("Enter room length:")) width = float(input("Enter room width:")) area = length * width needed = area * 1.05 print("You need", needed, "tiles in squared metres")
t = int(input('Digite um número para ver sua tabudada: ')) print('-='*6) # o {:2} é pra deixar alinhadinho unidade com unidade e dezena com dezena print('{} * {:2} = {}'.format(t, 1, t*1)) print('{} * {:2} = {}'.format(t, 2, t*2)) print('{} * {:2} = {}'.format(t, 3, t*3)) print('{} * {:2} = {}'.format(t, 4, t*4)) print('{} * {:2} = {}'.format(t, 5, t*5)) print('{} * {:2} = {}'.format(t, 6, t*6)) print('{} * {:2} = {}'.format(t, 7, t*7)) print('{} * {:2} = {}'.format(t, 8, t*8)) print('{} * {:2} = {}'.format(t, 9, t*9)) print('{} * {:2} = {}'.format(t, 10, t*10)) print('-='*6)
# # PySNMP MIB module ZYXEL-CLUSTER-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ZYXEL-CLUSTER-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:49:17 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, ValueSizeConstraint, ValueRangeConstraint, SingleValueConstraint, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ValueSizeConstraint", "ValueRangeConstraint", "SingleValueConstraint", "ConstraintsUnion") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") iso, Counter32, Unsigned32, Counter64, Gauge32, Integer32, Bits, MibIdentifier, ObjectIdentity, MibScalar, MibTable, MibTableRow, MibTableColumn, IpAddress, TimeTicks, NotificationType, ModuleIdentity = mibBuilder.importSymbols("SNMPv2-SMI", "iso", "Counter32", "Unsigned32", "Counter64", "Gauge32", "Integer32", "Bits", "MibIdentifier", "ObjectIdentity", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "IpAddress", "TimeTicks", "NotificationType", "ModuleIdentity") MacAddress, DisplayString, TextualConvention, RowStatus = mibBuilder.importSymbols("SNMPv2-TC", "MacAddress", "DisplayString", "TextualConvention", "RowStatus") esMgmt, = mibBuilder.importSymbols("ZYXEL-ES-SMI", "esMgmt") zyxelCluster = ModuleIdentity((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14)) if mibBuilder.loadTexts: zyxelCluster.setLastUpdated('201207010000Z') if mibBuilder.loadTexts: zyxelCluster.setOrganization('Enterprise Solution ZyXEL') if mibBuilder.loadTexts: zyxelCluster.setContactInfo('') if mibBuilder.loadTexts: zyxelCluster.setDescription('The subtree for cluster') zyxelClusterSetup = MibIdentifier((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1)) zyxelClusterStatus = MibIdentifier((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2)) zyxelClusterManager = MibIdentifier((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 1)) zyClusterManagerMaxNumberOfManagers = MibScalar((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: zyClusterManagerMaxNumberOfManagers.setStatus('current') if mibBuilder.loadTexts: zyClusterManagerMaxNumberOfManagers.setDescription('The maximum number of cluster managers that can be created.') zyxelClusterManagerTable = MibTable((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 1, 2), ) if mibBuilder.loadTexts: zyxelClusterManagerTable.setStatus('current') if mibBuilder.loadTexts: zyxelClusterManagerTable.setDescription('The table contains cluster manager configuration.') zyxelClusterManagerEntry = MibTableRow((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 1, 2, 1), ).setIndexNames((0, "ZYXEL-CLUSTER-MIB", "zyClusterManagerVid")) if mibBuilder.loadTexts: zyxelClusterManagerEntry.setStatus('current') if mibBuilder.loadTexts: zyxelClusterManagerEntry.setDescription('An entry contains cluster manager configuration. ') zyClusterManagerVid = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 1, 2, 1, 1), Integer32()) if mibBuilder.loadTexts: zyClusterManagerVid.setStatus('current') if mibBuilder.loadTexts: zyClusterManagerVid.setDescription('This is the VLAN ID and is only applicable if the switch is set to 802.1Q VLAN. All switches must be directly connected and in the same VLAN group to belong to the same cluster.') zyClusterManagerName = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 1, 2, 1, 2), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: zyClusterManagerName.setStatus('current') if mibBuilder.loadTexts: zyClusterManagerName.setDescription('Type a name to identify the cluster manager.') zyClusterManagerRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 1, 2, 1, 3), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: zyClusterManagerRowStatus.setStatus('current') if mibBuilder.loadTexts: zyClusterManagerRowStatus.setDescription('This object allows cluster manager entries to be created and deleted from cluster manager table.') zyxelClusterMembers = MibIdentifier((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 2)) zyClusterMemberMaxNumberOfMembers = MibScalar((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 2, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: zyClusterMemberMaxNumberOfMembers.setStatus('current') if mibBuilder.loadTexts: zyClusterMemberMaxNumberOfMembers.setDescription('The maximum number of cluster members that can be created.') zyxelClusterMemberTable = MibTable((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 2, 2), ) if mibBuilder.loadTexts: zyxelClusterMemberTable.setStatus('current') if mibBuilder.loadTexts: zyxelClusterMemberTable.setDescription('The table contains cluster member configuration.') zyxelClusterMemberEntry = MibTableRow((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 2, 2, 1), ).setIndexNames((0, "ZYXEL-CLUSTER-MIB", "zyClusterMemberMacAddress")) if mibBuilder.loadTexts: zyxelClusterMemberEntry.setStatus('current') if mibBuilder.loadTexts: zyxelClusterMemberEntry.setDescription('An entry contains cluster member configuration.') zyClusterMemberMacAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 2, 2, 1, 1), MacAddress()) if mibBuilder.loadTexts: zyClusterMemberMacAddress.setStatus('current') if mibBuilder.loadTexts: zyClusterMemberMacAddress.setDescription("This is the cluster member switch's hardware MAC address.") zyClusterMemberName = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 2, 2, 1, 2), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: zyClusterMemberName.setStatus('current') if mibBuilder.loadTexts: zyClusterMemberName.setDescription("This is the cluster member switch's system name.") zyClusterMemberModel = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 2, 2, 1, 3), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: zyClusterMemberModel.setStatus('current') if mibBuilder.loadTexts: zyClusterMemberModel.setDescription("This is the cluster member switch's model name.") zyClusterMemberPassword = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 2, 2, 1, 4), DisplayString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: zyClusterMemberPassword.setStatus('current') if mibBuilder.loadTexts: zyClusterMemberPassword.setDescription("Each cluster member's password is its administration password.") zyClusterMemberRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 1, 2, 2, 1, 5), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: zyClusterMemberRowStatus.setStatus('current') if mibBuilder.loadTexts: zyClusterMemberRowStatus.setDescription('This object allows cluster member entries to be created and deleted from cluster member table.') zyxelClusterCandidate = MibIdentifier((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2, 1)) zyxelClusterCandidateTable = MibTable((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2, 1, 1), ) if mibBuilder.loadTexts: zyxelClusterCandidateTable.setStatus('current') if mibBuilder.loadTexts: zyxelClusterCandidateTable.setDescription('The table contains cluster candidate information.') zyxelClusterCandidateEntry = MibTableRow((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2, 1, 1, 1), ).setIndexNames((0, "ZYXEL-CLUSTER-MIB", "zyClusterCandidateMacAddress")) if mibBuilder.loadTexts: zyxelClusterCandidateEntry.setStatus('current') if mibBuilder.loadTexts: zyxelClusterCandidateEntry.setDescription('An entry contains cluster candidate information.') zyClusterCandidateMacAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2, 1, 1, 1, 1), MacAddress()) if mibBuilder.loadTexts: zyClusterCandidateMacAddress.setStatus('current') if mibBuilder.loadTexts: zyClusterCandidateMacAddress.setDescription("This is the cluster candidate switch's hardware MAC address.") zyClusterCandidateName = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2, 1, 1, 1, 2), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: zyClusterCandidateName.setStatus('current') if mibBuilder.loadTexts: zyClusterCandidateName.setDescription("This is the cluster candidate switch's system name.") zyClusterCandidateModel = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2, 1, 1, 1, 3), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: zyClusterCandidateModel.setStatus('current') if mibBuilder.loadTexts: zyClusterCandidateModel.setDescription("This is the cluster candidate switch's model name.") zyClusterRole = MibScalar((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("none", 0), ("manager", 1), ("member", 2)))).setMaxAccess("readonly") if mibBuilder.loadTexts: zyClusterRole.setStatus('current') if mibBuilder.loadTexts: zyClusterRole.setDescription('The role of this switch within the cluster.') zyClusterInfoManager = MibScalar((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2, 3), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: zyClusterInfoManager.setStatus('current') if mibBuilder.loadTexts: zyClusterInfoManager.setDescription("The cluster manager switch's hardware MAC address.") zyxelClusterInfoMemberTable = MibTable((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2, 4), ) if mibBuilder.loadTexts: zyxelClusterInfoMemberTable.setStatus('current') if mibBuilder.loadTexts: zyxelClusterInfoMemberTable.setDescription('The table contains cluster member information.') zyxelClusterInfoMemberEntry = MibTableRow((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2, 4, 1), ).setIndexNames((0, "ZYXEL-CLUSTER-MIB", "zyClusterInfoMemberMacAddress")) if mibBuilder.loadTexts: zyxelClusterInfoMemberEntry.setStatus('current') if mibBuilder.loadTexts: zyxelClusterInfoMemberEntry.setDescription('An entry contains cluster member information.') zyClusterInfoMemberMacAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2, 4, 1, 1), MacAddress()) if mibBuilder.loadTexts: zyClusterInfoMemberMacAddress.setStatus('current') if mibBuilder.loadTexts: zyClusterInfoMemberMacAddress.setDescription("This is the cluster member switch's hardware MAC address.") zyClusterInfoMemberName = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2, 4, 1, 2), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: zyClusterInfoMemberName.setStatus('current') if mibBuilder.loadTexts: zyClusterInfoMemberName.setDescription("This is the cluster member switch's system name.") zyClusterInfoMemberModel = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2, 4, 1, 3), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: zyClusterInfoMemberModel.setStatus('current') if mibBuilder.loadTexts: zyClusterInfoMemberModel.setDescription("This is the cluster member switch's model name.") zyClusterInfoMemberStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 890, 1, 15, 3, 14, 2, 4, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("error", 0), ("online", 1), ("offline", 2)))).setMaxAccess("readonly") if mibBuilder.loadTexts: zyClusterInfoMemberStatus.setStatus('current') if mibBuilder.loadTexts: zyClusterInfoMemberStatus.setDescription('There are three types in cluster status. Online(the cluster member switch is accessible), Error (for example, the cluster member switch password was changed or the switch was set as the manager and so left the member list, etc.), Offline (the switch is disconnected - Offline shows approximately 1.5 minutes after the link between cluster member and manager goes down).') mibBuilder.exportSymbols("ZYXEL-CLUSTER-MIB", zyClusterCandidateModel=zyClusterCandidateModel, zyxelClusterManager=zyxelClusterManager, zyxelClusterCandidateEntry=zyxelClusterCandidateEntry, zyxelClusterMembers=zyxelClusterMembers, zyxelCluster=zyxelCluster, zyClusterInfoManager=zyClusterInfoManager, zyClusterInfoMemberModel=zyClusterInfoMemberModel, zyxelClusterSetup=zyxelClusterSetup, zyxelClusterInfoMemberTable=zyxelClusterInfoMemberTable, zyClusterMemberName=zyClusterMemberName, zyClusterCandidateName=zyClusterCandidateName, zyxelClusterStatus=zyxelClusterStatus, zyClusterManagerRowStatus=zyClusterManagerRowStatus, zyxelClusterManagerEntry=zyxelClusterManagerEntry, zyClusterManagerVid=zyClusterManagerVid, zyClusterInfoMemberMacAddress=zyClusterInfoMemberMacAddress, zyxelClusterManagerTable=zyxelClusterManagerTable, zyxelClusterInfoMemberEntry=zyxelClusterInfoMemberEntry, zyxelClusterMemberEntry=zyxelClusterMemberEntry, zyClusterInfoMemberStatus=zyClusterInfoMemberStatus, zyClusterRole=zyClusterRole, zyClusterMemberRowStatus=zyClusterMemberRowStatus, zyxelClusterCandidateTable=zyxelClusterCandidateTable, zyClusterMemberMaxNumberOfMembers=zyClusterMemberMaxNumberOfMembers, zyxelClusterMemberTable=zyxelClusterMemberTable, zyClusterInfoMemberName=zyClusterInfoMemberName, zyClusterManagerName=zyClusterManagerName, zyClusterMemberModel=zyClusterMemberModel, zyClusterMemberMacAddress=zyClusterMemberMacAddress, zyClusterCandidateMacAddress=zyClusterCandidateMacAddress, PYSNMP_MODULE_ID=zyxelCluster, zyClusterMemberPassword=zyClusterMemberPassword, zyxelClusterCandidate=zyxelClusterCandidate, zyClusterManagerMaxNumberOfManagers=zyClusterManagerMaxNumberOfManagers)
# import math # def squareRoot(a): # return round(math.sqrt(float(a)),9) def squareRoot(a): return round(float(a)**(1/2),8)
class WesternDigitalRuleChecker(object): def __init__(self): self.estimated_value = 0 self.standard_deviation = 0 def __init__(self, estimated_value, standard_deviation): self.estimated_value = estimated_value self.standard_deviation = standard_deviation def check_rule_1(self, datapoints): #TODO Vervollstaendige die Methode und gebe true zurueck, # wenn die Regel erfuellt wird und false, wenn gegen die Regel verstossen wird. # Das "pass" kann geloescht werden, sobald du deinen Code schreibst. """Any single data point falls outside the 3σ limit from the centerline""" pass def check_rule_2(self, datapoints): """Two out of three consecutive points fall beyond the 2σ limit (in zone A or beyond), on the same side of the centerline""" if (len(datapoints) >= 3): number_of_points_outside_2_deviations = 0 for item in datapoints[len(datapoints) - 3:len(datapoints)]: if (self.estimated_value + 2 * self.standard_deviation < item): number_of_points_outside_2_deviations += 1 if (self.estimated_value - 2 * self.standard_deviation > item): number_of_points_outside_2_deviations -= 1 if number_of_points_outside_2_deviations >= 2 or number_of_points_outside_2_deviations <= -2: print("Rule 2 failed") return False return True def check_rule_3(self, datapoints): """Four out of five consecutive points fall beyond the 1σ limit (in zone B or beyond), on the same side of the centerline""" if (len(datapoints) >= 5): number_of_points_outside_1_deviation = 0 for item in datapoints[len(datapoints) - 5:len(datapoints)]: if (self.estimated_value + self.standard_deviation < item): number_of_points_outside_1_deviation += 1 if (self.estimated_value - self.standard_deviation > item): number_of_points_outside_1_deviation -= 1 if (number_of_points_outside_1_deviation >= 4 or number_of_points_outside_1_deviation <= -4): print("Rule 3 failed") return False return True def check_rule_4(self, datapoints): """Nine consecutive points fall on the same side of the centerline (in zone C or beyond)""" if (len(datapoints) >= 9): relevant_points = datapoints[len(datapoints) - 9:len(datapoints)] for index, item in enumerate(relevant_points): if (index > 0): if relevant_points[index - 1] > self.estimated_value: if item < self.estimated_value: return True if relevant_points[index - 1] < self.estimated_value: if item > self.estimated_value: return True if item == self.estimated_value: return True elif index == 0: if item == self.estimated_value: return True print("Rule 4 failed") return False return True
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def removeElements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]: if not head: return None dummyHead = currentNode = ListNode() dummyHead.next = head while currentNode.next: if currentNode.next.val == val: currentNode.next = currentNode.next.next else: currentNode = currentNode.next return dummyHead.next
#Crie um programa que simule o funcionamento de um caixa eletrônico. No inicio, pergunte ao usuário qual o valor sacado (número inteiro) e o #programa vai informar quantas cédulas de cada valor serão entregues.] #obs: Considere que o caixa possui cédulas de R$50,R$20,R$10 e R$1. print('Caixa Eletrônico') print('Cédulas de R$50, R$20, R$10 e R$1') valor = int(input('Qual valor deseja sacar hoje?')) total = valor ced = 50 total_ced = 0 while True: if total >= ced: total -= ced total_ced += 1 else: if total_ced > 0: print('{} total de cédulas {}'.format(total_ced,ced)) if ced == 50: ced = 20 elif ced == 20: ced = 10 elif ced == 10: ced = 1 total_ced = 0 if total == 0: break ''' inteira = 0 resto = 0 inteira = valor // 100 resto = valor % 100 if inteira !=0: if resto !=0: if resto >= 50: print('Serão entregues {} de R$50'.format((inteira * 2)+ 1)) inteira = resto // 50 resto = resto % 50 if inteira != 0: print('Serão entregues {} de R$50'.format(inteira)) if resto <= 50: inteira = resto // 20 resto = resto % 20 if inteira != 0: print('Serão entregues {} de R$20'.format(inteira)) inteira = resto // 10 resto = resto % 10 if inteira != 0: print('Serão entregues {} de R$10'.format(inteira)) inteira = resto // 1 resto = resto % 1 if inteira != 0 or resto != 0: print('Serão entregues {} de R$1'.format(inteira + resto)) else: print('Serão entregues {} de R$50'.format(inteira * 2)) inteira = resto // 50 resto = resto % 50 if inteira != 0: print('Serão entregues {} de R$50'.format(inteira)) if resto <= 50: inteira = resto // 20 resto = resto % 20 if inteira != 0: print('Serão entregues {} de R$20'.format(inteira)) inteira = resto // 10 resto = resto % 10 if inteira != 0: print('Serão entregues {} de R$10'.format(inteira)) inteira = resto // 1 resto = resto % 1 if inteira != 0 or resto != 0: print('Serão entregues {} de R$1'.format(inteira + resto)) else: print('Serão entregues {} de R$50'.format(inteira * 2)) else: inteira = resto // 50 resto = resto % 50 if inteira != 0: print('Serão entregues {} de R$50'.format(inteira)) if resto >= 50: print('Resto >=50') else: inteira = resto // 20 resto = resto % 20 if inteira !=0: print('Serão entregues {} de R$20'.format(inteira)) inteira = resto // 10 resto = resto % 10 if inteira !=0: print('Serão entregues {} de R$10'.format(inteira)) inteira = resto // 1 resto = resto % 1 if inteira !=0 or resto !=0: print('Serão entregues {} de R$1'.format(inteira + resto))'''
alist = [10, 20, 23, 26, 27, 35, 38, 41, 46, 49, 54, 56, 64, 70, 81, 87, 88, 90, 92, 96, 98] temp = None def binary_search(left: int, right: int, key: int) -> int: global temp if len(alist) == 1: if alist[left] == key: return alist[left] else: return 0 else: mid = (left + right) // 2 print("mid ", mid) if mid == temp or mid > len(alist) - 1: # Condition for preventing the deep recursion. return 0 else: temp = mid if alist[mid] == key: return alist[mid] elif key < alist[mid]: return binary_search(left, mid - 1, key) else: return binary_search(mid + 1, right, key) """ This segment for dynamic of the program """ # while True: # a = input("Enter the element of the list = ") # if a == "": # break # else: # alist.append(int(a)) alist.sort() print(alist) print(len(alist)) search_key = int(input("Enter the number you want to search = ")) result = binary_search(0, len(alist), search_key) print(result)
class HTTPError(Exception): """Http Error Exception""" pass
# 2021 April 16. Surrendered entirely. # 2-d dp. # text1 = "abcba", text2 = "abcbcba" # At any two positions i, j in t1 and t2, if 1) t1[i] == t2[j] # then the length of common subsequence count should increment by 1 and # we then check from t1[i+1] and t2[j+1]. If 2) t1[i] != t2[j], then we # should keep on finding common susbequence of t1[i], t2[j+1] and t1[i+1] # and t2[j], whichever includes a bigger common subsequence. So in the # example, checking from the left to the right, "abcb" is common (logic 1) # at work). Then we are left with "a" vs. "cba", "a","c" don't match, so # dp of "a","c" refers to "","c" (0) and "a","b", which in turn refers # to "", "b"(0) and "a", "a". Since "a","a" is a match, dp of it is 1 # plus that of "", "", which is 0. So the boundary of common subseq # length all 0, propagates the value back to the topleft corner # dp[0][0] that we want, through some route that is determined by the # matchings in the two texts. But algo won't know which route it takes # beforehand, so solving the entire matrix, from bottom right to top left # , would be necessary. # dp a b c b a "" # a 1 0 # b 1 0 # c 1 0 # b 1 0 # c *,1 0 # b *,1 0 # a 1 0 # "" 0 0 0 0 0 0 # * represents not knowing the value first, have to check right and # downward. This checking keeps going until it reaches the bottom. class Solution: def longestCommonSubsequence(self, text1: str, text2: str) -> int: # One additional row and col to store bounary conditions. # 0, 1, ..., len(text1) - 1, for each char in text1, then len(text1) for boundary 0. ROWS, COLS = len(text1) + 1, len(text2) + 1 dp = [[0 for _ in range(COLS)] for _ in range(ROWS)] for row in range(ROWS - 2, -1, -1): for col in range(COLS - 2, -1, -1): if text1[row] == text2[col]: dp[row][col] = 1 + dp[row+1][col+1] else: dp[row][col] = max(dp[row+1][col], dp[row][col+1]) return dp[0][0] if __name__ == "__main__": print(Solution().longestCommonSubsequence("papmretkborsrurgtina", "nsnupotstmnkfcfavaxgl"))
class PxLoadBar(object): """ Visualizes system load in a horizontal bar. Inputs are: * System load * Number of physical cores * Number of logical cores * How many columns wide the horizontal bar should be The output is a horizontal bar string. Load below the number of physical cores is visualized in green. Load between the number of physical cores and logical cores is visualized in yellow. Load above of the number of logical cores is visualized in red. As long as load is below the number of physical cores, it will use only the first half of the output string. Load up to twice the number of physical cores will go up to the end of the string. """ def __init__(self, physical=None, logical=None): if physical is None or physical < 1: raise ValueError("Physical must be a positive integer, was: %r" % (physical,)) if logical is None or logical < physical: raise ValueError("Logical must be >= physical, was: %r (vs %r)" % (logical, physical)) self._physical = physical self._logical = logical CSI = b"\x1b[" self.normal = CSI + b"m" self.inverse = CSI + b"0;7m" self.red = CSI + b"27;1;37;41m" self.yellow = CSI + b"27;1;37;43m" self.green = CSI + b"27;1;37;42m" def _get_colored_bytes(self, load=None, columns=None, text=""): "Yields pairs, with each pair containing a color and a byte" maxlength = columns - 2 # Leave room for a starting and an ending space if len(text) > maxlength: text = text[0:(maxlength - 1)] text = text + ' ' * (maxlength - len(text)) text = " " + text + " " assert len(text) == columns max_value = self._physical if load > max_value: max_value = 1.0 * load UNUSED = 1000 * max_value if load < self._physical: yellow_start = UNUSED red_start = UNUSED inverse_start = load normal_start = self._physical else: yellow_start = self._physical red_start = self._logical inverse_start = UNUSED normal_start = load # Scale the values to the number of columns yellow_start = yellow_start * columns / max_value - 0.5 red_start = red_start * columns / max_value - 0.5 inverse_start = inverse_start * columns / max_value - 0.5 normal_start = normal_start * columns / max_value - 0.5 for i in range(columns): # We always start out green color = self.green if i >= yellow_start: color = self.yellow if i >= red_start: color = self.red if i >= inverse_start: color = self.inverse if i >= normal_start: color = self.normal yield (color, text[i].encode('utf-8')) def get_bar(self, load=None, columns=None, text=""): if load is None: raise ValueError("Missing required parameter load=") if columns is None: raise ValueError("Missing required parameter columns=") return_me = b'' color = self.normal for color_and_byte in self._get_colored_bytes(load=load, columns=columns, text=text): if color_and_byte[0] != color: return_me += color_and_byte[0] color = color_and_byte[0] return_me += color_and_byte[1] if color != self.normal: return_me += self.normal return return_me
""" FizzBuzz is a classical interview question. We will implement a modified version of it, however, you can also find the original version on the web if you are interested. Write a program that takes a number from the user. If this number is negative, print an error message if this number is a multiple of 3, print 'Fizz' if this number is a multiple of 5, print 'Buzz' if this number is a multiple of 15, print 'FizzBuzz' otherwise, print the number itself. You can assume user will enter a valid integer value. Examples: Please enter a number: 25 Buzz Please enter a number: -5 You entered a negative number! Please enter a number: 2 2 Please enter a number: 36 Fizz Please enter a number: 3330 FizzBuzz """ number = int(input('Enter a number: ')) if number < 0: print('You entered a negative number!') elif number % 15 == 0: print('FizzBuzz') elif number % 3 == 0: print('Fizz') elif number % 5 == 0: print('Buzz') else: print(number)
class BaseSensor(): def __init__(self): self.null_value = 0 self.sensor = None self.measurements = [] self.upper_reasonable_bound = 200 self.lower_reasonable_bound = 0 def setup(self): self.sensor = None def read(self): return None def average(self, measurements): if len(measurements) != 0: return sum(measurements)/len(measurements) else: return self.null_value def rolling_average(self, measurement, measurements, size): if measurement == None: return None if self.lower_reasonable_bound < measurement < self.upper_reasonable_bound: if len(measurements) >= size: measurements.pop(0) measurements.append(measurement) return self.average(measurements) def mapNum(self, val, old_max, old_min, new_max, new_min): try: old_range = float(old_max - old_min) new_range = float(new_max - new_min) new_value = float(((val - old_min) * new_range) / old_range) + new_min return new_value except Exception: return val
def time_in_range(data, bg_range=(4.0, 7.0)): # data[0] is the time values - assume they are equally spaced, so we can ignore values = data[1] return 100.0 * sum([bg_range[0] <= v <= bg_range[1] for v in values]) / len(values) def mean(data): values = data[1] return float(sum(values)) / len(values) def estimated_hba1c(data): # from https://www.ncbi.nlm.nih.gov/pmc/articles/PMC2742903/ return hba1c_ngsp_to_ifcc((mean(data) + 2.59) / 1.59) def hba1c_ngsp_to_ifcc(ngsp): # from http://www.ngsp.org/ifccngsp.asp return 10.93 * ngsp - 23.50
def maior_primo(x) -> object: for maior in reversed(range(1,x+1)): if all(maior%n!=0 for n in range(2,maior)): return maior
USER_CREATED = "user_created" USER_ADDED = "user_added_to_request" USER_REMOVED = "user_removed_from_request" USER_PERM_CHANGED = "user_permissions_changed" USER_STATUS_CHANGED = "user_status_changed" # user, admin, super USER_INFO_EDITED = "user_information_edited" REQUESTER_INFO_EDITED = "requester_information_edited" REQ_CREATED = "request_created" AGENCY_REQ_CREATED = "agency_submitted_request" REQ_ACKNOWLEDGED = "request_acknowledged" REQ_DENIED = "request_denied" REQ_STATUS_CHANGED = "request_status_changed" REQ_EXTENDED = "request_extended" REQ_CLOSED = "request_closed" REQ_REOPENED = "request_reopened" REQ_TITLE_EDITED = "request_title_edited" REQ_AGENCY_REQ_SUM_EDITED = "request_agency_request_summary_edited" REQ_TITLE_PRIVACY_EDITED = "request_title_privacy_edited" REQ_AGENCY_REQ_SUM_PRIVACY_EDITED = "request_agency_request_summary_privacy_edited" REQ_AGENCY_REQ_SUM_DATE_SET = "request_agency_request_summary_date_set" REQ_POINT_OF_CONTACT_ADDED = "request_point_of_contact_added" REQ_POINT_OF_CONTACT_REMOVED = "request_point_of_contact_removed" EMAIL_NOTIFICATION_SENT = "email_notification_sent" FILE_ADDED = "file_added" FILE_EDITED = "file_edited" FILE_PRIVACY_EDITED = "file_privacy_edited" FILE_REPLACED = "file_replaced" FILE_REMOVED = "file_removed" LINK_ADDED = "link_added" LINK_EDITED = "link_edited" LINK_PRIVACY_EDITED = "link_privacy_edited" LINK_REMOVED = "link_removed" INSTRUCTIONS_ADDED = "instructions_added" INSTRUCTIONS_EDITED = "instructions_edited" INSTRUCTIONS_PRIVACY_EDITED = "instructions_privacy_edited" INSTRUCTIONS_REMOVED = "instructions_removed" NOTE_ADDED = "note_added" NOTE_EDITED = "note_edited" NOTE_PRIVACY_EDITED = "note_privacy_edited" NOTE_REMOVED = "note_removed" AGENCY_ACTIVATED = "agency_activated" AGENCY_DEACTIVATED = "agency_deactivated" AGENCY_USER_ACTIVATED = "agency_user_activated" AGENCY_USER_DEACTIVATED = "agency_user_deactivated" CONTACT_EMAIL_SENT = "contact_email_sent" USER_LOGIN = "user_logged_in" USER_AUTHORIZED = "user_authorized" USER_LOGGED_OUT = "user_logged_out" USER_MADE_AGENCY_ADMIN = "user_made_agency_admin" USER_MADE_AGENCY_USER = "user_made_agency_user" USER_PROFILE_UPDATED = "user_profile_updated" ACKNOWLEDGMENT_LETTER_CREATED = 'acknowledgment_letter_created' DENIAL_LETTER_CREATED = 'denial_letter_created' CLOSING_LETTER_CREATED = 'closing_letter_created' EXTENSION_LETTER_CREATED = 'extension_letter_created' ENVELOPE_CREATED = 'envelope_created' RESPONSE_LETTER_CREATED = 'response_letter_created' REOPENING_LETTER_CREATED = 'reopening_letter_created' FOR_REQUEST_HISTORY = [ USER_ADDED, USER_REMOVED, USER_PERM_CHANGED, REQUESTER_INFO_EDITED, REQ_CREATED, AGENCY_REQ_CREATED, REQ_STATUS_CHANGED, REQ_ACKNOWLEDGED, REQ_EXTENDED, REQ_CLOSED, REQ_REOPENED, REQ_TITLE_EDITED, REQ_AGENCY_REQ_SUM_EDITED, REQ_TITLE_PRIVACY_EDITED, REQ_AGENCY_REQ_SUM_PRIVACY_EDITED, FILE_ADDED, FILE_EDITED, FILE_REMOVED, LINK_ADDED, LINK_EDITED, LINK_REMOVED, INSTRUCTIONS_ADDED, INSTRUCTIONS_EDITED, INSTRUCTIONS_REMOVED, NOTE_ADDED, NOTE_EDITED, NOTE_REMOVED, ENVELOPE_CREATED, RESPONSE_LETTER_CREATED ] RESPONSE_ADDED_TYPES = [ FILE_ADDED, LINK_ADDED, INSTRUCTIONS_ADDED, NOTE_ADDED, ] RESPONSE_EDITED_TYPES = [ FILE_EDITED, FILE_REPLACED, FILE_PRIVACY_EDITED, LINK_EDITED, LINK_PRIVACY_EDITED, INSTRUCTIONS_EDITED, INSTRUCTIONS_PRIVACY_EDITED, NOTE_ADDED, NOTE_PRIVACY_EDITED ] RESPONSE_REMOVED_TYPES = [ FILE_REMOVED, LINK_REMOVED, INSTRUCTIONS_REMOVED, NOTE_REMOVED ] SYSTEM_TYPES = [ AGENCY_ACTIVATED, AGENCY_DEACTIVATED, AGENCY_USER_ACTIVATED, AGENCY_USER_DEACTIVATED, CONTACT_EMAIL_SENT, USER_LOGIN, USER_AUTHORIZED, USER_LOGGED_OUT, USER_MADE_AGENCY_ADMIN, USER_MADE_AGENCY_USER, USER_PROFILE_UPDATED ]
# Find the sum of the numbers 8, 9, 10 # Var declarations num1 = 8 num2 = 9 num3 = 10 # Code sum = num1 + num2 + num3 # Result print(sum)
# Write your make_spoonerism function here: def make_spoonerism(word1, word2): a = word1[0] b = word2[0] c = word1[0].replace(a,b) + word1[1:] d = word2[0].replace(b,a) + word2[1:] e = c + ' ' + d return e # Uncomment these function calls to test your function: print(make_spoonerism("Codecademy", "Learn")) # should print Lodecademy Cearn print(make_spoonerism("Hello", "world!")) # should print wello Horld! print(make_spoonerism("a", "b")) # should print b a # OR # OR # # Write your make_spoonerism function here: # def make_spoonerism(word1, word2): # return word2[0]+word1[1:]+" "+word1[0]+word2[1:] # # Uncomment these function calls to test your tip function: # print(make_spoonerism("Codecademy", "Learn")) # # should print Lodecademy Cearn # print(make_spoonerism("Hello", "world!")) # # should print wello Horld! # print(make_spoonerism("a", "b")) # # should print b a
# AUTOGENERATED BY NBDEV! DO NOT EDIT! __all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {"trace_log": "01_convert_time_log.ipynb", "format_value": "01_convert_time_log.ipynb", "strip_extra_EnmacClientTime_elements": "01_convert_time_log.ipynb", "unix_time_milliseconds": "01_convert_time_log.ipynb", "parse_dt": "01_convert_time_log.ipynb", "parse_dt_to_milliseconds": "01_convert_time_log.ipynb", "parse_httpd_dt": "01_convert_time_log.ipynb", "parse_httpd_dt_to_milliseconds": "01_convert_time_log.ipynb", "match_last2digits": "01_convert_time_log.ipynb", "parse_timing_log": "01_convert_time_log.ipynb", "parse_log_line": "01_convert_time_log.ipynb", "parse_log_line_to_dict": "01_convert_time_log.ipynb", "parse_httpd_log": "01_convert_time_log.ipynb", "log_re": "01_convert_time_log.ipynb", "request_re": "01_convert_time_log.ipynb", "parse_httpd_log_file": "01_convert_time_log.ipynb", "parse_timing_log_file": "01_convert_time_log.ipynb"} modules = ["convert_time_log.py"] doc_url = "https://3ideas.github.io/cronos/" git_url = "https://github.com/3ideas/cronos/tree/master/" def custom_doc_links(name): return None
#Planetary database #Source for planetary data, and some of the data on #the moons, is http://nssdc.gsfc.nasa.gov/planetary/factsheet/ class Planet: ''' A Planet object contains basic planetary data. If P is a Planet object, the data are: P.name = Name of the planet P.a = Mean radius of planet (m) P.g = Surface gravitational acceleration (m/s**2) P.L = Annual mean solar constant (current) (W/m**2) P.albedo Bond albedo (fraction) P.rsm = Semi-major axis of orbit about Sun (m) P.year = Sidereal length of year (s) P.eccentricity = Eccentricity (unitless) P.day = Mean tropical length of day (s) P.obliquity = Obliquity to orbit (degrees) P.Lequinox = Longitude of equinox (degrees) P.Tsbar = Mean surface temperature (K) P.Tsmax = Maximum surface temperature (K) For gas giants, "surface" quantities are given at the 1 bar level ''' #__repr__ object prints out a help string when help is #invoked on the planet object or the planet name is typed def __repr__(self): line1 =\ 'This planet object contains information on %s\n'%self.name line2 = 'Type \"help(Planet)\" for more information\n' return line1+line2 def __init__(self): self.name = None #Name of the planet self.a = None #Mean radius of planet self.g = None #Surface gravitational acceleration self.L = None #Annual mean solar constant (current) self.albedo = None #Bond albedo self.rsm = None #Semi-major axis self.year = None #Sidereal length of year self.eccentricity = None # Eccentricity self.day = None #Mean tropical length of day self.obliquity = None #Obliquity to orbit self.Lequinox = None #Longitude of equinox self.Tsbar = None #Mean surface temperature self.Tsmax = None #Maximum surface temperature #---------------------------------------------------- Mercury = Planet() Mercury.name = 'Mercury' #Name of the planet Mercury.a = 2.4397e6 #Mean radius of planet Mercury.g = 3.70 #Surface gravitational acceleration Mercury.albedo = .119 #Bond albedo Mercury.L = 9126.6 #Annual mean solar constant (current) # Mercury.rsm = 57.91e9 #Semi-major axis Mercury.year = 87.969*24.*3600. #Sidereal length of year Mercury.eccentricity = .2056 # Eccentricity Mercury.day = 4222.6*3600. #Mean tropical length of day Mercury.obliquity = .01 #Obliquity to orbit (deg) Mercury.Lequinox = None #Longitude of equinox (deg) # Mercury.Tsbar = 440. #Mean surface temperature Mercury.Tsmax = 725. #Maximum surface temperature #---------------------------------------------------- Venus = Planet() Venus.name = 'Venus' #Name of the planet Venus.a = 6.0518e6 #Mean radius of planet Venus.g = 8.87 #Surface gravitational acceleration Venus.albedo = .750 #Bond albedo Venus.L = 2613.9 #Annual mean solar constant (current) # Venus.rsm = 108.21e9 #Semi-major axis Venus.year = 224.701*24.*3600. #Sidereal length of year Venus.eccentricity = .0067 # Eccentricity Venus.day = 2802.*3600. #Mean tropical length of day Venus.obliquity = 177.36 #Obliquity to orbit (deg) Venus.Lequinox = None #Longitude of equinox (deg) # Venus.Tsbar = 737. #Mean surface temperature Venus.Tsmax = 737. #Maximum surface temperature #---------------------------------------------------- Earth = Planet() Earth.name = 'Earth' #Name of the planet Earth.a = 6.371e6 #Mean radius of planet Earth.g = 9.798 #Surface gravitational acceleration Earth.albedo = .306 #Bond albedo Earth.L = 1367.6 #Annual mean solar constant (current) # Earth.rsm = 149.60e9 #Semi-major axis Earth.year = 365.256*24.*3600. #Sidereal length of year Earth.eccentricity = .0167 # Eccentricity Earth.day = 24.000*3600. #Mean tropical length of day Earth.obliquity = 23.45 #Obliquity to orbit (deg) Earth.Lequinox = None #Longitude of equinox (deg) # Earth.Tsbar = 288. #Mean surface temperature Earth.Tsmax = None #Maximum surface temperature #---------------------------------------------------- Mars = Planet() Mars.name = 'Mars' #Name of the planet Mars.a = 3.390e6 #Mean radius of planet Mars.g = 3.71 #Surface gravitational acceleration Mars.albedo = .250 #Bond albedo Mars.L = 589.2 #Annual mean solar constant (current) # Mars.rsm = 227.92e9 #Semi-major axis Mars.year = 686.98*24.*3600. #Sidereal length of year Mars.eccentricity = .0935 # Eccentricity Mars.day = 24.6597*3600. #Mean tropical length of day Mars.obliquity = 25.19 #Obliquity to orbit (deg) Mars.Lequinox = None #Longitude of equinox (deg) # Mars.Tsbar = 210. #Mean surface temperature Mars.Tsmax = 295. #Maximum surface temperature #---------------------------------------------------- Jupiter = Planet() Jupiter.name = 'Jupiter' #Name of the planet Jupiter.a = 69.911e6 #Mean radius of planet Jupiter.g = 24.79 #Surface gravitational acceleration Jupiter.albedo = .343 #Bond albedo Jupiter.L = 50.5 #Annual mean solar constant (current) # Jupiter.rsm = 778.57e9 #Semi-major axis Jupiter.year = 4332.*24.*3600. #Sidereal length of year Jupiter.eccentricity = .0489 # Eccentricity Jupiter.day = 9.9259*3600. #Mean tropical length of day Jupiter.obliquity = 3.13 #Obliquity to orbit (deg) Jupiter.Lequinox = None #Longitude of equinox (deg) # Jupiter.Tsbar = 165. #Mean surface temperature Jupiter.Tsmax = None #Maximum surface temperature #---------------------------------------------------- Saturn = Planet() Saturn.name = 'Saturn' #Name of the planet Saturn.a = 58.232e6 #Mean radius of planet Saturn.g = 10.44 #Surface gravitational acceleration Saturn.albedo = .342 #Bond albedo Saturn.L = 14.90 #Annual mean solar constant (current) # Saturn.rsm = 1433.e9 #Semi-major axis Saturn.year = 10759.*24.*3600. #Sidereal length of year Saturn.eccentricity = .0565 # Eccentricity Saturn.day = 10.656*3600. #Mean tropical length of day Saturn.obliquity = 26.73 #Obliquity to orbit (deg) Saturn.Lequinox = None #Longitude of equinox (deg) # Saturn.Tsbar = 134. #Mean surface temperature Saturn.Tsmax = None #Maximum surface temperature #---------------------------------------------------- Uranus = Planet() Uranus.name = 'Uranus' #Name of the planet Uranus.a = 25.362e6 #Mean radius of planet Uranus.g = 8.87 #Surface gravitational acceleration Uranus.albedo = .300 #Bond albedo Uranus.L = 3.71 #Annual mean solar constant (current) # Uranus.rsm = 2872.46e9 #Semi-major axis Uranus.year = 30685.4*24.*3600. #Sidereal length of year Uranus.eccentricity = .0457 # Eccentricity Uranus.day = 17.24*3600. #Mean tropical length of day Uranus.obliquity = 97.77 #Obliquity to orbit (deg) Uranus.Lequinox = None #Longitude of equinox (deg) # Uranus.Tsbar = 76. #Mean surface temperature Uranus.Tsmax = None #Maximum surface temperature #---------------------------------------------------- Neptune = Planet() Neptune.name = 'Neptune' #Name of the planet Neptune.a = 26.624e6 #Mean radius of planet Neptune.g = 11.15 #Surface gravitational acceleration Neptune.albedo = .290 #Bond albedo Neptune.L = 1.51 #Annual mean solar constant (current) # Neptune.rsm = 4495.06e9 #Semi-major axis Neptune.year = 60189.0*24.*3600. #Sidereal length of year Neptune.eccentricity = .0113 # Eccentricity Neptune.day = 16.11*3600. #Mean tropical length of day Neptune.obliquity = 28.32 #Obliquity to orbit (deg) Neptune.Lequinox = None #Longitude of equinox (deg) # Neptune.Tsbar = 72. #Mean surface temperature Neptune.Tsmax = None #Maximum surface temperature #---------------------------------------------------- Pluto = Planet() Pluto.name = 'Pluto' #Name of the planet Pluto.a = 1.195e6 #Mean radius of planet Pluto.g = .58 #Surface gravitational acceleration Pluto.albedo = .5 #Bond albedo Pluto.L = .89 #Annual mean solar constant (current) # Pluto.rsm = 5906.e9 #Semi-major axis Pluto.year = 90465.*24.*3600. #Sidereal length of year Pluto.eccentricity = .2488 # Eccentricity Pluto.day = 153.2820*3600. #Mean tropical length of day Pluto.obliquity = 122.53 #Obliquity to orbit (deg) Pluto.Lequinox = None #Longitude of equinox (deg) # Pluto.Tsbar = 50. #Mean surface temperature Pluto.Tsmax = None #Maximum surface temperature #Selected moons #---------------------------------------------------- Moon = Planet() Moon.name = 'Moon' #Name of the planet Moon.a = 1.737e6 #Mean radius of planet Moon.g = 1.62 #Surface gravitational acceleration Moon.albedo = .11 #Bond albedo Moon.L = 1367.6 #Annual mean solar constant (current) # Moon.rsm = Earth.rsm #Semi-major axis Moon.year = Earth.year #Sidereal length of year Moon.eccentricity = None # Eccentricity Moon.day = 28.*24.*3600. #Mean tropical length of day (approx) Moon.obliquity = None #Obliquity to orbit (deg) Moon.Lequinox = None #Longitude of equinox (deg) # Moon.Tsbar = None #Mean surface temperature Moon.Tsmax = 400. #Maximum surface temperature Moon.Tsmin = 100. #Minimum surface temperature Titan = Planet() Titan.name = 'Titan' #Name of the planet Titan.a = 2.575e6 #Mean radius of planet Titan.g = 1.35 #Surface gravitational acceleration Titan.L = Saturn.L #Annual mean solar constant (current) Titan.albedo = .21 #Bond albedo (Not yet updated from Cassini) # Titan.rsm = None #Semi-major axis Titan.year = Saturn.year #Sidereal length of year Titan.eccentricity = Saturn.eccentricity # Eccentricity ABOUT SUN Titan.day = 15.9452*24.*3600. #Mean tropical length of day Titan.obliquity = Saturn.obliquity #Obliquity to plane of Ecliptic #(Titan's rotation axis approx parallel # to Saturn's Titan.Lequinox = Saturn.Lequinox #Longitude of equinox # Titan.Tsbar = 95. #Mean surface temperature Titan.Tsmax = None #Maximum surface temperature Europa = Planet() Europa.name = 'Europa' #Name of the planet Europa.a = 1.560e6 #Mean radius of planet Europa.g = 1.31 #Surface gravitational acceleration Europa.L = Jupiter.L #Annual mean solar constant (current) Europa.albedo = .67 #Bond albedo # Europa.rsm = Jupiter.rsm #Semi-major axis Europa.year = Jupiter.year #Sidereal length of year Europa.eccentricity = Jupiter.eccentricity # Eccentricity Europa.day = 3.551*24.*3600. #Mean tropical length of day Europa.obliquity = Jupiter.obliquity #Obliquity to plane of ecliptic Europa.Lequinox = None #Longitude of equinox # Europa.Tsbar = 103. #Mean surface temperature Europa.Tsmax = 125. #Maximum surface temperature Triton = Planet() Triton.name = 'Triton' #Name of the planet Triton.a = 2.7068e6/2. #Mean radius of planet Triton.g = .78 #Surface gravitational acceleration Triton.L = Neptune.L #Annual mean solar constant (current) Triton.albedo = .76 #Bond albedo # Triton.rsm = Neptune.rsm #Semi-major axis Triton.year = Neptune.year #Sidereal length of year Triton.eccentricity = Neptune.eccentricity # Eccentricity about Sun Triton.day = 5.877*24.*3600. #Mean tropical length of day #Triton's rotation is retrograde Triton.obliquity = 156. #Obliquity to ecliptic **ToDo: Check this. #Note: Seasons are influenced by the inclination #of Triton's orbit? (About 20 degrees to #Neptune's equator Triton.Lequinox = None #Longitude of equinox # Triton.Tsbar = 34.5 #Mean surface temperature #This is probably a computed blackbody #temperature, rather than an observation Triton.Tsmax = None #Maximum surface temperature
palavras = {} arquivo = open('words.txt', 'r') for p in arquivo.readlines(): palavra = p.split(' ') for l in palavra: try: palavras[l] += 1 except: palavras[l] = 1 arquivo.close() print(palavras)
def getKey(dictionary, svalue): for key, value in dictionary.items(): if value == svalue: return key # def hasKey(dictionary, key): # if key in dictionary: # return True # return False
# https://www.codewars.com/kata/529872bdd0f550a06b00026e/ ''' Instructions : Complete the greatestProduct method so that it'll find the greatest product of five consecutive digits in the given string of digits. For example: greatestProduct("123834539327238239583") // should return 3240 The input string always has more than five digits. Adapted from Project Euler. ''' def product(n): p = 1 for i in n: p *= int(i) return p def greatest_product(n): res = [] mul = 1 digit = 5 while len(n)>= digit: res.append(product(n[:digit])) n = n[1:] print(res) print(n) return(max(res))
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. def drop_view_if_exists(cr, viewname): cr.execute("DROP view IF EXISTS %s CASCADE" % (viewname,)) cr.commit() def escape_psql(to_escape): return to_escape.replace('\\', r'\\').replace('%', '\%').replace('_', '\_') def pg_varchar(size=0): """ Returns the VARCHAR declaration for the provided size: * If no size (or an empty or negative size is provided) return an 'infinite' VARCHAR * Otherwise return a VARCHAR(n) :type int size: varchar size, optional :rtype: str """ if size: if not isinstance(size, int): raise ValueError("VARCHAR parameter should be an int, got %s" % type(size)) if size > 0: return 'VARCHAR(%d)' % size return 'VARCHAR' def reverse_order(order): """ Reverse an ORDER BY clause """ items = [] for item in order.split(','): item = item.lower().split() direction = 'asc' if item[1:] == ['desc'] else 'desc' items.append('%s %s' % (item[0], direction)) return ', '.join(items)
""" You are given three inputs, all of which are instances of a class that have an "ancestor" property pointing to their youngest ancestor. The first input is the top ancestor in an ancestral tree(i.e. the only instance that has no ancestor), and the other two inputs are descendants in the ancestral tree. Write a functions that returns the youngest common ancestor to the two descendants. for input Node A, Node E, Node I from this ancestral A / \ B C / \ / \ D EF G / \ H I Returns node B """ def get_youngest_common_ancestor(top_ancestor, descendant_one, descendant_two): pass
@auth.route('/login', methods=['GET', 'POST']) # define login page path def login(): # define login page fucntion if request.method=='GET': # if the request is a GET we return the login page return render_template('login.html') else: # if the request is POST the we check if the user exist # and with te right password email = request.form.get('email') password = request.form.get('password') remember = True if request.form.get('remember') else False user = User.query.filter_by(email=email).first() # check if the user actually exists # take the user-supplied password, hash it, and compare it # to the hashed password in the database if not user: flash('Please sign up before!') return redirect(url_for('auth.signup')) elif not check_password_hash(user.password, password): flash('Please check your login details and try again.') return redirect(url_for('auth.login')) # if the user #doesn't exist or password is wrong, reload the page # if the above check passes, then we know the user has the # right credentials login_user(user, remember=remember) return redirect(url_for('main.profile'))
# AUTOGENERATED BY NBDEV! DO NOT EDIT! __all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {"get_norm_stats": "00_utils.ipynb", "draw_rect": "00_utils.ipynb", "convert_cords": "00_utils.ipynb", "resize": "00_utils.ipynb", "noise": "00_utils.ipynb", "get_prompt_points": "00_utils.ipynb", "yolo_to_coco": "00_utils.ipynb", "PTBDataset": "01_data.ipynb", "PTBTransform": "01_data.ipynb", "PTBImage": "01_data.ipynb", "ConversionDataset": "01_data.ipynb", "EfficientLoc": "02_model.ipynb", "CIoU": "02_model.ipynb"} modules = ["utils.py", "data.py", "model.py", "fastai.py", "None.py"] doc_url = "https://BavarianToolbox.github.io/point_to_box/" git_url = "https://github.com/BavarianToolbox/point_to_box/tree/master/" def custom_doc_links(name): return None
tabela = ('Flamengo', 'Internacional', 'Atletico-MG', 'São Paulo', 'Fluminense', 'Gremio', 'Palmeiras', 'Santos', 'Athletico -PR', 'Bragantino', 'Ceara SC', 'Corinthians', 'Atletico-GO', 'Bahia', 'Sport Recife', 'Fortaleza', 'Vasco da Gama', 'Goiás', 'Coritiba', 'Botafogo') print('-='*20) print(f'A classificação atual do brasileirão é: {tabela}') print('-='*20) print(f'Os 5 primeiros colocados são: {tabela[:5]}') print('-='*20) print(f'Os 4 ultimos colocados são: {tabela[-4:]}') print('-='*20) print(f'os times em ordem alfabetica são: {sorted(tabela)}') print('-='*20) print(f'O Palmeiras esta na {tabela.index("Palmeiras") + 1}ª posição.') print('-='*20) #print(len(tabela))
class OutcomeInfo: '''Details for individual outcomes of a Market.''' def __init__(self, id, volume, price, description): self._id = id self._volume = volume self._price = price self._description = description @property def id(self): '''Market Outcome ID Returns int ''' return self._id @property def volume(self): '''Trading volume for this Outcome. Returns decimal.Decimal ''' return self._volume @property def price(self): '''Last price at which the outcome was traded. If no trades have taken place in the Market, this value is set to the Market midpoint. If there is no volume on this Outcome, but there is volume on another Outcome in the Market, price is set to 0 for Yes/No Markets and Categorical Markets. Returns decimal.Decimal ''' return self._price @property def description(self): '''Description for the Outcome. Returns str ''' return self._description
''' @author: Jakob Prange (jakpra) @copyright: Copyright 2020, Jakob Prange @license: Apache 2.0 ''' LETTERS = '_YZWVUTS' def index_category(category, nargs, result_index=0, arg_index=1, self_index=0): attr_str = ''.join((f'[{a}]' for a in category.attr - {'conj'})) + ('[conj]' if 'conj' in category.attr else '') if category.result is None: result_str = '' else: if category.result.equals(category.arg, ignore_attr=True): if len(category.arg.attr) == 0 or (category.arg.attr == category.result.attr): result_index = arg_index result_str, result_index, arg_index, self_index = index_category(category.result, nargs-1, result_index, arg_index, result_index) # if category.result.has_children(): # result_str = f'({result_str})' if category.arg is None: arg_str = '' else: arg_str, result_index, arg_index, self_index = index_category(category.arg, -1, arg_index, arg_index+1, arg_index) # if category.arg.has_children(): # arg_str = f'({arg_str})' if not category.has_children(): cat_str = f'{category.root}{attr_str}{{{LETTERS[self_index]}}}' elif nargs < 0: cat_str = f'({result_str}{category.root}{arg_str}){attr_str}{{{LETTERS[self_index]}}}' else: cat_str = f'({result_str}{category.root}{arg_str}<{nargs}>){attr_str}{{{LETTERS[self_index]}}}' return cat_str, result_index, arg_index, self_index def make_rule(category): result = str(category) nargs = category.nargs() indexed, _, _, _ = index_category(category, nargs) result += f'\n {nargs} {indexed}' cat = category for n in range(nargs): result += f'\n {n+1} ignore' cat = cat.result return result
# One Gold Star # Question 1-star: Stirling and Bell Numbers # The number of ways of splitting n items in k non-empty sets is called # the Stirling number, S(n,k), of the second kind. For example, the group # of people Dave, Sarah, Peter and Andy could be split into two groups in # the following ways. # 1. Dave, Sarah, Peter Andy # 2. Dave, Sarah, Andy Peter # 3. Dave, Andy, Peter Sarah # 4. Sarah, Andy, Peter Dave # 5. Dave, Sarah Andy, Peter # 6. Dave, Andy Sarah, Peter # 7. Dave, Peter Andy, Sarah # so S(4,2) = 7 # If instead we split the group into one group, we have just one way to # do it. # 1. Dave, Sarah, Peter, Andy # so S(4,1) = 1 # or into four groups, there is just one way to do it as well # 1. Dave Sarah Peter Andy # so S(4,4) = 1 # If we try to split into more groups than we have people, there are no # ways to do it. # The formula for calculating the Stirling numbers is # S(n, k) = k*S(n-1, k) + S(n-1, k-1) # Furthermore, the Bell number B(n) is the number of ways of splitting n # into any number of parts, that is, # B(n) is the sum of S(n,k) for k =1,2, ... , n. # Write two procedures, stirling and bell. The first procedure, stirling # takes as its inputs two positive integers of which the first is the # number of items and the second is the number of sets into which those # items will be split. The second procedure, bell, takes as input a # positive integer n and returns the Bell number B(n). def stirling(n_items, k_sets): """ Takes as its inputs two positive integers of which the first is the number of items and the second is the number of sets into which those items will be split. Returns total number of k_sets created from n_items. """ if n_items < k_sets: return 0 if k_sets == 1 or k_sets == n_items: return 1 return k_sets * stirling(n_items-1, k_sets) + stirling(n_items-1, k_sets-1) def bell(n_items): """ Returns the total number of k_sets of stirling numbers for k_sets = 1, 2, ... , n. """ return sum([stirling(n_items, k) for k in range(1, n_items+1)]) print(stirling(1, 1)) # 1 print(stirling(2, 1)) # 1 print(stirling(2, 2)) # 1 print(stirling(2, 3)) # 0 print(stirling(3, 1)) # 1 print(stirling(3, 2)) # 3 print(stirling(3, 3)) # 1 print(stirling(4, 1)) # 1 print(stirling(4, 2)) # 7 print(stirling(4, 3)) # 6 print(stirling(4, 4)) # 1 print(stirling(5, 1)) # 1 print(stirling(5, 2)) # 15 print(stirling(5, 3)) # 25 print(stirling(5, 4)) # 10 print(stirling(5, 5)) # 1 print(stirling(20, 15)) # 452329200 print("***********") print(bell(1)) # 1 print(bell(2)) # 2 print(bell(3)) # 5 print(bell(4)) # 15 print(bell(5)) # 52 print(bell(15)) # 1382958545
def cpu_bound(n): return sum(i * i for i in range(n)) if __name__ == "__main__": n = int(input()) res = cpu_bound(n) print(res)
# Implement a queue using two stacks. Recall that a queue is a FIFO # (first-in, first-out) data structure with the following methods: enqueue, # which inserts an element into the queue, and dequeue, which removes it. class Queue: def __init__(self): self.ins = [] self.out = [] def enqueue(self, value): self.ins.append(value) def dequeue(self): if not self.out: while self.ins: self.out.append(self.ins.pop()) return self.out.pop() if __name__ == '__main__': q = Queue() for i in range(5): q.enqueue(i) for _ in range(3): print(q.dequeue()) for i in range(5, 10): q.enqueue(i) for _ in range(7): print(q.dequeue())