content
stringlengths
7
1.05M
def str_without_separators(sentence): #separators = ",.?;: " #str1 = "".join(char if char not in separators else "" for char in sentence) str1 = "".join(char if char.isalnum() else "" for char in sentence) return str1 def is_palindrome(sentence): str1 = str_without_separators(sentence) return str1[::-1].casefold() == str1.casefold() print(is_palindrome("Was it a car, or a cat, I saw?"))
c = int(input('\nHow many rows do you want? ')) print() a = [[1]] for i in range(c): b = [1] for j in range(len(a[-1]) - 1): b.append(a[-1][j] + a[-1][j + 1]) b.append(1) a.append(b) for i in range(len(a)): for j in range(len(a[i])): a[i][j] = str(a[i][j]) d = ' '.join(a[i]) for i in range(len(a)): f = ' '.join(a[i]) e = (len(d) - len(f)) // 2 print(e * ' ' + f + e * ' ') print()
name = "pymum" version = "3" requires = ["pydad-3"]
def proportion(a,b,c): try: a = int(a) b = int(b) c = int(c) ratio = a/b propor = c/ratio return propor except ZeroDivisionError: print("Error: Dividing by Zero is not valid!!") except ValueError: print ("Error: Only Numeric Values are valid!!")
datasets={'U1001': {'135058': 1,'135038': 3,'135032': 3,'135084': 2,'135076':2}, 'U1002': {'135058': 2,'135038': 2,'135032': 1,'135084': 1,'135076':3}, 'U1003': {'135058': 2,'135038': 1,'135032': 2,'135084': 3,'135076':3}, 'U1004': {'135058': 1,'135038': 3,'135032': 3,'135084': 3,'135076':3}, 'U1005': {'135058': 1,'135038': 2,'135032': 2,'135084': 2,'135076':3}, 'U1006': {'135058': 1,'135038': 3,'135032': 3,'135084': 2,'135076':1}, 'U1007': {'135058': 1,'135038': 1,'135032': 3,'135084': 2,'135076':2}, 'U1008': {'135058': 3,'135038': 3,'135032': 3,'135084': 2,'135076':3}, 'U1009': {'135058': 1,'135038': 3,'135032': 3,'135084': 1,'135076':1}, 'U1010': {'135058': 3,'135038': 3,'135032': 3,'135084': 3,'135076':3}, 'U1011': {'135015': 2,'135018': 2,'135060': 3}, 'U1012': {'135015': 3,'135018': 1,'135060': 2}, 'U1013': {'135015': 2,'135018': 2,'135060': 2}, 'U1014': {'135015': 2,'135018': 3,'135060': 3}, 'U1015': {'135015': 2,'135018': 2,'135060': 1}, 'U1016': {'135062': 2}, 'U1017': {'134983': 0}, 'U1018': {'135108': 1}, 'U1019': {'135086': 0}, 'U1020': {'135109': 2}, 'U1021': {'132715': 2}, 'U1022': {'135063': 2}, 'U1023': {'132733': 2}, 'U1024': {'135058': 2,'135038': 3,'135032': 2,'135084': 1,'135030':3}, 'U1025': {'132830': 2}, 'U1026': {'132665': 2}, 'U1027': {'135062': 1}, 'U1028': {'132613': 2}, 'U1029': {'132922': 1}, 'U1030': {'135058': 1,'135038': 2,'135032': 3,'132668': 3,'134996':3}, 'U1031': {'132668': 0}, 'U1032': {'135058': 3,'135038': 2,'135032': 2,'135084': 3,'132668':2}, 'U1033': {'135030': 2}, 'U1034': {'135035': 1}, 'U1035': {'134986': 2}, 'U1036': {'135045': 2}, 'U1037': {'132854': 1}, 'U1038': {'132862': 2}, 'U1039': {'132665': 1}, 'U1040': {'135019': 1}, 'U1041': {'135109': 1}, 'U1042': {'134992': 1}, 'U1043': {'132630': 1}, 'U1044': {'132768': 2}, 'U1045': {'135041': 1}, 'U1046': {'132861': 1}, 'U1047': {'132884': 0}, 'U1048': {'132723': 2}, 'U1049': {'135052': 0}, 'U1050': {'132584': 0}, 'U1051': {'134996': 1}, 'U1052': {'132870': 1}, 'U1053': {'135047': 2}, 'U1054': {'135045': 2}, 'U1055': {'132825': 2}, 'U1056': {'135051': 2}, 'U1057': {'132834': 1}, 'U1058': {'135055': 2}, 'U1059': {'132754': 2}, 'U1060': {'132740': 1}, 'U1061': {'132954': 2}, 'U1062': {'132834': 0}, 'U1063': {'132667': 1}, 'U1064': {'135052': 2}, 'U1065': {'132654': 1}, 'U1066': {'135013': 1}, 'U1067': {'132560': 1}, 'U1068': {'132660': 0}, 'U1069': {'132847': 0}, 'U1070': {'132613': 1}, 'U1071': {'135030': 2}, 'U1072': {'135000': 0}, 'U1073': {'132862': 0}, 'U1074': {'134976': 2}, 'U1075': {'135041': 1}, 'U1076': {'135073': 2}, 'U1077': {'135027': 0}, 'U1078': {'135052': 2}, 'U1079': {'132766': 1}, 'U1080': {'132715': 1}, 'U1081': {'135027': 0}, 'U1082': {'132733': 0}, 'U1083': {'135044': 1}, 'U1084': {'132723': 1}, 'U1085': {'132825': 2}, 'U1086': {'132951': 1}, 'U1087': {'132663': 1}, 'U1088': {'135051': 2}, 'U1089': {'135079': 0}, 'U1090': {'132925': 2}, 'U1091': {'135035': 1}, 'U1092': {'132723': 1}, 'U1093': {'135011': 1}, 'U1094': {'135069': 0}, 'U1095': {'135072': 2}, 'U1096': {'135075': 1}, 'U1097': {'132861': 2}, 'U1098': {'132921': 1}, 'U1099': {'135042': 1}, 'U1100': {'134976': 2}, 'U1101': {'135041': 0}, 'U1102': {'132847': 2}, 'U1103': {'132733': 2}, 'U1104': {'135041': 1}, 'U1105': {'135052': 0}, 'U1106': {'135064': 2}, 'U1107': {'132733': 2}, 'U1108': {'135058': 1}, 'U1109': {'132872': 1}, 'U1110': {'134999': 2}, 'U1111': {'135082': 1}, 'U1112': {'132862': 1}, 'U1113': {'132854': 0}, 'U1114': {'132755': 1}, 'U1115': {'135071': 2}, 'U1116': {'132834': 2}, 'U1117': {'135000': 1}, 'U1118': {'134992': 0}, 'U1119': {'132768': 2}, 'U1120': {'132847': 2}, 'U1121': {'134999': 2}, 'U1122': {'135053': 2}, 'U1123': {'132594': 1}, 'U1124': {'135050': 0}, 'U1125': {'135062': 1}, 'U1126': {'135108': 2}, 'U1127': {'134996': 2}, 'U1128': {'132951': 0}, 'U1129': {'132665': 0}, 'U1130': {'132706': 1}, 'U1131': {'132870': 0}, 'U1132': {'135027': 2}, 'U1133': {'135019': 1}, 'U1134': {'135074': 2}, 'U1135': {'135060': 0}, 'U1136': {'135028': 2}, 'U1137': {'135075': 2}, 'U1138': {'132925': 1}}
def isolateData(selector,channel,labels,data): selected=[] for i in range(len(labels)): if labels[i]==selector: selected.append(data[str(i)+'c'+str(channel)])#epochs with class AGMSY5 return selected
#!/usr/bin/python3 class Material: def __init__(self, color): """ A material has color as basic propriety :param color: the color of the material """ self.color = color
# ,---------------------------------------------------------------------------, # | This module is part of the krangpower electrical distribution simulation | # | suit by Federico Rosato <[email protected]> et al. | # | Please refer to the license file published together with this code. | # | All rights not explicitly granted by the license are reserved. | # '---------------------------------------------------------------------------' class AssociationError(Exception): def __init__(self, association_target_type, association_target_name, association_subject_type, association_subject_name, msg=None): if msg is None: msg = 'krangpower does not know how to associate a {0}({1}) to a {2}({3})'\ .format(association_target_type, association_target_name, association_subject_type, association_subject_name) super().__init__(msg) self.association_target_type = association_target_type self.association_subject_type = association_subject_type self.association_target_name = association_target_name self.association_subject_name = association_subject_name class TypeRecoveryError(Exception): pass class TypeUnrecoverableError(TypeRecoveryError): def __init__(self, original_type, msg=None): if msg is None: msg = 'krangpower has no options to recover a type {}'.format(str(original_type)) super().__init__(msg) self.unrecoverable_type =original_type class RecoveryTargetError(TypeRecoveryError): def __init__(self, original_type, target_type, msg=None): if msg is None: msg = 'krangpower does not know how to convert type {}---->{}'\ .format(str(original_type), str(target_type)) super().__init__(msg) self.original_type = original_type self.invalid_target_type = target_type class KrangInstancingError(Exception): def __init__(self, already_existing_krang_name, msg=None): if msg is None: msg = 'Cannot create a new Krang - A Krang ({0}) already exists.'\ 'Delete every reference to it if you want to instantiate another.'\ .format(already_existing_krang_name) super().__init__(msg) class KrangObjAdditionError(Exception): def __init__(self, object, msg=None): if msg is None: msg = 'There was a problem in adding object {} to Krang'.format(str(object)) super().__init__(msg) class ClearingAttemptError(Exception): def __init__(self, msg=None): if msg is None: msg = 'A "clear" command was passed to the text command interface.' \ 'If you wish a new circuit, delete the existing Krang.' super().__init__(msg) class UnsolvedCircuitError(Exception): def __init__(self, property_stack: str, msg=None): if msg is None: msg = 'An attempt to access the calculated property {} was made before solving the circuit.'\ .format(property_stack) super().__init__(msg)
# Faça um programa que tenha uma função chamada área(), # que receba as dimensões de um terreno retangular (largura e comprimento) e mostre a área do terreno. cores = {'limpa':'\033[m', 'bverde':'\033[1;32m', 'bvermelho': '\033[1;31m', 'pretoebranco':'\033[7:30m'} print('-=-'*10) print(cores['pretoebranco']+'_____INICIO_____'+cores['limpa']) print('-=-'*10) # função para calcular a area: def area(l, c): r = l * c print(f'A área de um terreno de {l}x{c} é de {r}m²') print(f'{"Controle de terrenos":=^30}') l = float(input('LARGURA: (m)')) c = float(input('COMPRIMENTO: (m)')) # chamada da função area() area(l,c) print('') print('-=-'*10) print(cores['pretoebranco']+'______FIM_______'+cores['limpa']) print(cores['pretoebranco']+'_Code by Rafael_'+cores['limpa']) print('-=-'*10)
peso = float(input('Indique o seu peso (Kg) - ')) alt = float(input('Indique a sua altura (m) - ')) IMC = peso / (alt ** 2) if IMC <= 18.5: print('O seu IMC é de {:.1f} e está com EXCESSO DE MAGREZA.') elif 18.5 < IMC <= 25: print('O seu IMC é de {:.1f} e está com PESO NORMAL') elif 25 < IMC <= 30: print('O seu IMC é de {:.1f} e está com EXCESSO DE PESO'.format(IMC)) elif 30 < IMC <= 35: print('O seu IMC é de {:.1f} e está com OBESIDADE GRAU I'.format(IMC)) elif 35 < IMC <= 40: print('O seu IMC é de {:.1f} e está com OBESIDADE GRAU II'.format(IMC)) else: print('O seu IMC é de {:.1f} e está com OBESIDADE GRAU III'.format(IMC))
factors_avro = { 'namespace': 'com.gilt.cerebro.job', 'type': 'record', 'name': 'AvroFactors', 'fields': [ {'name': 'id', 'type': 'string'}, {'name': 'factors', 'type': {'type': 'array', 'items': 'float'}}, {'name': 'bias', 'type': 'float'}, ], }
def fibonacci_number(num): f = 0 s = 1 for i in range(num + 1): if i <= 1: nxt = i else: nxt = f +s f = s s = nxt print (nxt) print(fibonacci_number(int(input("Enter the number:"))))
######################### # 演示字典(key value) ######################### # 字典:字典存储的是键值对,不会记住存入元素的顺序 alien = {'a': "EA", "b": "阿凡达", 'c': "异形"} print(alien) print(type(alien)) # 获取元素 print(alien['a']) # 在我们不确定字典中是否存在某个键而又想获取其值时,可以使用get方法 unknown = alien.get('f') print("unknown = %s" % type(unknown)) # 还可以设置默认值 unknown = alien.get('f', "擎天柱") print("unknown = %s" % unknown) # 增加键值对 alien['d'] = '铁血战士' print(alien) # 修改字典中的值 alien['a'] = "超人" # 遍历字典 for key, value in alien.items(): # 返回一个包含所有(键,值)元祖的列表 print("key = " + key + " value = " + value) for key in alien.keys(): print(key) for value in alien.values(): print(value) # 删除 del alien["c"] print(alien) # 清空整个字典 alien.clear() print(alien)
{ "cells": [ { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "ename": "ValueError", "evalue": "operands could not be broadcast together with shapes (4,) (100,) (4,) ", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mValueError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m<ipython-input-13-5f28594dbd6a>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[1;32m 38\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 39\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 40\u001b[0;31m \u001b[0mmaximo\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0msigma\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mmaximo_sigma\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mprior\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mx\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mposterior\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mmu\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0mx\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 41\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 42\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0;32m<ipython-input-13-5f28594dbd6a>\u001b[0m in \u001b[0;36mposterior\u001b[0;34m(H, secuencia)\u001b[0m\n\u001b[1;32m 21\u001b[0m \u001b[0mPosterior\u001b[0m \u001b[0mcalculado\u001b[0m \u001b[0mcon\u001b[0m \u001b[0mla\u001b[0m \u001b[0mnormalizacion\u001b[0m \u001b[0madecuada\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 22\u001b[0m \"\"\"\n\u001b[0;32m---> 23\u001b[0;31m \u001b[0mpost\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mlike\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mx\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0msigma\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0mmu\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;34m+\u001b[0m \u001b[0mnp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mlog\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mprior\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mmu\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 24\u001b[0m \u001b[0mevidencia\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mnp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mamax\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mpost\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 25\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0mnp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mexp\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mpost\u001b[0m\u001b[0;34m-\u001b[0m\u001b[0mevidencia\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m/\u001b[0m\u001b[0mtrapz\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mnp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mexp\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mpost\u001b[0m\u001b[0;34m-\u001b[0m\u001b[0mevidencia\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0mmu\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0;32m<ipython-input-13-5f28594dbd6a>\u001b[0m in \u001b[0;36mlike\u001b[0;34m(secuencia, sigma, mu)\u001b[0m\n\u001b[1;32m 14\u001b[0m \u001b[0mL\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mnp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mzeros\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mlen\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mx\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 15\u001b[0m \u001b[0;32mfor\u001b[0m \u001b[0mi\u001b[0m \u001b[0;32min\u001b[0m \u001b[0mrange\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mlen\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mx\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 16\u001b[0;31m \u001b[0mL\u001b[0m \u001b[0;34m+=\u001b[0m \u001b[0mnp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mlog\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m1.\u001b[0m\u001b[0;34m/\u001b[0m\u001b[0mnp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0msqrt\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m2.0\u001b[0m\u001b[0;34m*\u001b[0m\u001b[0mnp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mpi\u001b[0m\u001b[0;34m*\u001b[0m\u001b[0msigma\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0mi\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m**\u001b[0m\u001b[0;36m2\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m*\u001b[0m\u001b[0mnp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mexp\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m-\u001b[0m\u001b[0;36m0.5\u001b[0m\u001b[0;34m*\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0msecuencia\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0mi\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m-\u001b[0m\u001b[0mmu\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m**\u001b[0m\u001b[0;36m2\u001b[0m\u001b[0;34m/\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0msigma\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0mi\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m**\u001b[0m\u001b[0;36m2\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 17\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0mL\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 18\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0;31mValueError\u001b[0m: operands could not be broadcast together with shapes (4,) (100,) (4,) " ] } ], "source": [ "\n", "import numpy as np\n", "import matplotlib.pyplot as plt\n", "x =[4.6, 6.0, 2.0, 5.8] \n", "x=np.array(x)\n", "sigma =[2.0, 1.5, 5.0, 1.0]\n", "mu=np.array(mu)\n", "mu=np.linspace(10,-10,100)\n", "\n", "def prior(a):\n", " p=np.ones(len(a))\n", " return p\n", "\n", "def like(secuencia, sigma,mu):\n", " L=np.zeros(len(x))\n", " for i in range(len(x)):\n", " L += np.log(1./np.sqrt(2.0*np.pi*sigma[i]**2))*np.exp(-0.5*(secuencia[i]-mu)**2/(sigma[i]**2))\n", " return L\n", "\n", "def posterior(H, secuencia):\n", " \"\"\"\n", " Posterior calculado con la normalizacion adecuada\n", " \"\"\"\n", " post = like(x, sigma,mu) + np.log(prior(mu))\n", " evidencia = np.amax(post)\n", " return np.exp(post-evidencia)/trapz(np.exp(post-evidencia),mu)\n", " \n", "\n", "def maximo_sigma(x, y):\n", " deltax = x[1] - x[0]\n", "\n", " ii = np.argmax(y)\n", "\n", " # segunda derivada\n", " d = (y[ii+1] - 2*y[ii] + y[ii-1]) / (deltax**2)\n", "\n", " return x[ii], 1.0/np.sqrt(-d)\n", " \n", "\n", "\n", "maximo, sigma = maximo_sigma(prior(x), posterior(mu,x))\n", "\n", "\n", "\n", "plt.figure()\n", "plt.plot(H, post, label='datos={}'.format(secuencia))\n", "plt.plot(H, gauss, ':', label='Aproximacion Gaussiana')\n", "plt.title('H= {:.2f} $\\pm$ {:.2f}'.format(max, sigma))\n", "plt.xlabel('H')\n", "plt.ylabel('prob(H|datos)')\n", "plt.legend()\n", "plt.savefig('coins')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.6" } }, "nbformat": 4, "nbformat_minor": 4 }
''' You are climbing a stair case. It takes n steps to reach to the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top? Note: Given n will be a positive integer. Example 1: Input: 2 Output: 2 Explanation: There are two ways to climb to the top. 1. 1 step + 1 step 2. 2 steps Example 2: Input: 3 Output: 3 Explanation: There are three ways to climb to the top. 1. 1 step + 1 step + 1 step 2. 1 step + 2 steps 3. 2 steps + 1 step ''' class Solution(object): def climbStairs(self, n): """ :type n: int :rtype: int """ if n == 0: return 0 elif n == 1: return 1 dplist = [0 for i in range(n+1)] dplist[0] = 0 dplist[1] = 1 for i in range(2,n+1): dplist[i] = max(dplist[i-1]+1, dplist[i-2]+2) return dplist[n] sol = Solution() n = 2 print(sol.climbStairs(n))
"""Top-level package for lsmPy.""" __author__ = """Shruti Anna Samuel""" __email__ = '[email protected]' __version__ = '0.0.1'
with open("source.txt") as filehandle: lines = filehandle.readlines() with open("source.txt", 'w') as filehandle: lines = filter(lambda x: x.strip(), lines) filehandle.writelines(lines)
""" ******************************************************************************************************************* | | Name : __version__.py | Module : risksense_api | Description : Version information for risksense_api. | Copyright : (c) RiskSense, Inc. | License : Apache-2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) | ******************************************************************************************************************* """ __title__ = 'risksense_api' __description__ = 'A python module for interacting with the RiskSense API' __url__ = 'https://www.risksense.com' __version__ = '0.9.1' __author__ = 'RiskSense, Inc.' __author_email__ = '[email protected]' __license__ = 'Apache-2.0' __copyright__ = 'Copyright 2021 RiskSense' """ Copyright 2021 RiskSense, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """
#break.py for s in 'python' : if s == 't' : continue print(s,end=" ") print("over")
arr = list(range(8)) def func(x): return x*2 print(list(map(func, arr))) print(list(map(lambda x: x**3, arr)))
list1=list(map(int,input().rstrip().split())) N=list1[0] list2=list1[2:] res=[] for j in list2: if j not in res: res.append(j) for i in range(len(list2)): if list2[i] in res: res.remove(list2[i]) print(*res)
#!/bin/env python3 def puzzle1(): tree = {} acceptedBags = ['shiny gold'] foundNew = True with open('input.txt', 'r') as input: for line in input: if line[-1:] == "\n": line = line[:-1] bags = line.split(',') partName = bags[0].split(' ') name = partName[0] + ' ' + partName[1] tree[name] = {} if partName[4] == 'no': continue else: tree[name][partName[5] + ' ' + partName[6]] = int(partName[4]) if len(bags) > 1: # print(bags) for bag in bags[1:]: bag = bag[1:].split(' ') tree[name][bag[1] + ' ' + bag[2]] = int(bag[0]) while foundNew == True: foundNew = False for rootBag in tree: for bag in tree[rootBag]: if bag in acceptedBags and rootBag not in acceptedBags: acceptedBags.append(rootBag) foundNew = True print(tree) print(acceptedBags[1:]) print(len(acceptedBags[1:])) if __name__ == "__main__": puzzle1()
# -*- coding: utf-8 -*- """ Parameter-related utilities. """
LinearRegression_Params = [ {"name": "fit_intercept", "type": "select", "values": [True, False], "dtype": "boolean", "accept_none": False}, {"name": "positive", "type": "select", "values": [False, True], "dtype": "boolean", "accept_none": False} ] Ridge_Params = [ {"name": "alpha", "type": "input", "values": 1.0, "dtype": "float", "accept_none": False}, {"name": "fit_intercept", "type": "select", "values": [True, False], "dtype": "boolean", "accept_none": False}, {"name": "copy_X", "type": "select", "values": [True, False], "dtype": "boolean", "accept_none": False}, {"name": "max_iter", "type": "input", "values": "", "dtype": "int", "accept_none": True}, {"name": "tol", "type": "input", "values": 0.001, "dtype": "float", "accept_none": False}, {"name": "solver", "type": "select", "values": ["auto", "svd", "cholesky", "lsqr", "sparse_cg", "sag", "saga", "lbfgs"], "dtype": "string", "accept_none": False}, {"name": "random_state", "type": "input", "values": "", "dtype": "int", "accept_none": True} ] Lasso_Params = [ {"name": "alpha", "type": "input", "values": 1.0, "dtype": "float", "accept_none": False}, {"name": "fit_intercept", "type": "select", "values": [True, False], "dtype": "boolean", "accept_none": False}, {"name": "precompute", "type": "select", "values": [False, True], "dtype": "boolean", "accept_none": False}, {"name": "copy_X", "type": "select", "values": [True, False], "dtype": "boolean", "accept_none": False}, {"name": "max_iter", "type": "input", "values": 1000, "dtype": "int", "accept_none": False}, {"name": "tol", "type": "input", "values": 0.0001, "dtype": "float", "accept_none": False}, {"name": "warm_start", "type": "select", "values": [False, True], "dtype": "boolean", "accept_none": False}, {"name": "random_state", "type": "input", "values": 1, "dtype": "int", "accept_none": True}, {"name": "selection", "type": "select", "values": ["cyclic", "random", "auto"], "dtype": "string", "accept_none": False}] ElasticNet_Params = [ {"name": "alpha", "type": "input", "values": 1.0, "dtype": "float", "accept_none": False}, {"name": "l1_ratio", "type": "input", "values": 0.5, "dtype": "float", "accept_none": False}, {"name": "fit_intercept", "type": "select", "values": [True, False], "dtype": "boolean", "accept_none": False}, {"name": "precompute", "type": "select", "values": [False, True], "dtype": "boolean", "accept_none": False}, {"name": "max_iter", "type": "input", "values": 1000, "dtype": "int", "accept_none": False}, {"name": "copy_X", "type": "select", "values": [True, False], "dtype": "boolean", "accept_none": False}, {"name": "tol", "type": "input", "values": 0.0001, "dtype": "float", "accept_none": False}, {"name": "warm_start", "type": "select", "values": [False, True], "dtype": "boolean", "accept_none": False}, {"name": "random_state", "type": "input", "values": 1, "dtype": "int", "accept_none": True}, {"name": "selection", "type": "select", "values": ["cyclic", "random"], "dtype": "string", "accept_none": False}] DecisionTreeRegressor_Params = [ {"name": "criterion", "type": "select", "values": ["squared_error", "friedman_mse", "absolute_error", "poisson"], "dtype": "string", "accept_none": False}, {"name": "splitter", "type": "select", "values": ["best", "random"], "dtype": "string", "accept_none": False}, {"name": "max_depth", "type": "input", "values": "", "dtype": "int", "accept_none": True}, {"name": "min_samples_split", "type": "input", "values": 2, "dtype": "int", "accept_none": False}, {"name": "min_samples_leaf", "type": "input", "values": 1, "dtype": "int", "accept_none": False}, {"name": "min_weight_fraction_leaf", "type": "input", "values": 0.0, "dtype": "float", "accept_none": False}, {"name": "max_features", "type": "select", "values": ["auto", "sqrt", "log2"], "dtype": "string", "accept_none": False}, {"name": "max_leaf_nodes", "type": "input", "values": "", "dtype": "int", "accept_none": True}, {"name": "min_impurity_decrease", "type": "input", "values": 0.0, "dtype": "float", "accept_none": False}, {"name": "ccp_alpha", "type": "input", "values": 0.0, "dtype": "float", "accept_none": True} ] RandomForestRegressor_Params = [ {"name": "n_estimators", "type": "input", "values": 100, "dtype": "int", "accept_none": False}, {"name": "criterion", "type": "select", "values": ["squared_error", "absolute_error", "poisson"], "dtype": "string", "accept_none": False}, {"name": "max_depth", "type": "input", "values": 5, "dtype": "int", "accept_none": True}, {"name": "min_samples_split", "type": "input", "values": 2, "dtype": "int", "accept_none": False}, {"name": "min_samples_leaf", "type": "input", "values": 0.1, "dtype": "float", "accept_none": False}, {"name": "min_weight_fraction_leaf", "type": "input", "values": 0.0, "dtype": "float", "accept_none": False}, {"name": "max_features", "type": "select", "values": ["auto", "sqrt", "log2"], "dtype": "string", "accept_none": False}, {"name": "max_leaf_nodes", "type": "input", "values": 4, "dtype": "int", "accept_none": True}, {"name": "min_impurity_decrease", "type": "input", "values": 0.0, "dtype": "float", "accept_none": False}, {"name": "bootstrap", "type": "select", "values": [True, False], "dtype": "boolean", "accept_none": False}, {"name": "oob_score", "type": "select", "values": [False, True], "dtype": "boolean", "accept_none": False}, {"name": "n_jobs", "type": "input", "values": -1, "dtype": "int", "accept_none": True}, {"name": "random_state", "type": "input", "values": 1, "dtype": "int", "accept_none": True}, {"name": "verbose", "type": "input", "values": 0, "dtype": "int", "accept_none": False}, {"name": "warm_start", "type": "select", "values": [False, True], "dtype": "boolean", "accept_none": False}, {"name": "ccp_alpha", "type": "input", "values": 0.0, "dtype": "float", "accept_none": False}, {"name": "max_samples", "type": "input", "values": 1, "dtype": "float", "accept_none": True}] SVR_params = [{"name": "kernel", "type": "select", "values": ["rbf", "linear", "poly", "sigmoid", "precomputed"], "dtype": "string", "accept_none": False}, {"name": "degree", "type": "input", "values": 3, "dtype": "int", "accept_none": False}, {"name": "gamma", "type": "select", "values": ["scale", "auto"], "dtype": "string", "accept_none": False}, {"name": "coef0", "type": "input", "values": 0.0, "dtype": "float", "accept_none": False}, {"name": "tol", "type": "input", "values": 0.001, "dtype": "float", "accept_none": False}, {"name": "C", "type": "input", "values": 1.0, "dtype": "float", "accept_none": False}, {"name": "epsilon", "type": "input", "values": 0.1, "dtype": "float", "accept_none": False}, {"name": "shrinking", "type": "select", "values": [True, False], "dtype": "boolean", "accept_none": False}, {"name": "cache_size", "type": "input", "values": 200, "dtype": "float", "accept_none": False}, {"name": "verbose", "type": "select", "values": [False, True], "dtype": "boolean", "accept_none": False}, {"name": "max_iter", "type": "input", "values": -1, "dtype": "int", "accept_none": False}] AdabootRegressor_Params = [ {"name": "base_estimator", "type": "input", "values": None, "dtype": "object", "accept_none": True}, {"name": "n_estimators", "type": "input", "values": 50, "dtype": "int", "accept_none": False}, {"name": "learning_rate", "type": "input", "values": 1.0, "dtype": "float", "accept_none": False}, {"name": "loss", "type": "select", "values": ['linear', 'square', 'exponential'], "dtype": "string", "accept_none": False}, {"name": "random_state", "type": "input", "values": 1, "dtype": "int", "accept_none": True}] GradientBoostRegressor_Params = [ {"name": "loss", "type": "select", "values": ['squared_error', 'absolute_error', 'huber', 'quantile'], "dtype": "string", "accept_none": False}, {"name": "learning_rate", "type": "input", "values": 0.1, "dtype": "float", "accept_none": False}, {"name": "n_estimators", "type": "input", "values": 100, "dtype": "int", "accept_none": False}, {"name": "subsample", "type": "input", "values": 1.0, "dtype": "float", "accept_none": False}, {"name": "criterion", "type": "select", "values": ['friedman_mse', 'squared_error', 'mae', 'mse'], "dtype": "string", "accept_none": False}, {"name": "min_samples_split", "type": "input", "values": 2, "dtype": "int", "accept_none": False}, {"name": "min_samples_leaf", "type": "input", "values": 1, "dtype": "int", "accept_none": False}, {"name": "min_weight_fraction_leaf", "type": "input", "values": 0.0, "dtype": "float", "accept_none": False}, {"name": "max_depth", "type": "input", "values": 3, "dtype": "int", "accept_none": False}, {"name": "min_impurity_decrease", "type": "input", "values": 0.0, "dtype": "float", "accept_none": False}, {"name": "init", "type": "input", "values": "zero", "dtype": "string", "accept_none": True}, {"name": "random_state", "input": "int", "values": 1, "dtype": "int", "accept_none": True}, {"name": "max_features", "type": "select", "values": ['auto', 'sqrt', 'log2'], "dtype": "string", "accept_none": False}, {"name": "alpha", "type": "input", "values": 0.9, "dtype": "float", "accept_none": False}, {"name": "verbose", "type": "input", "values": 0, "dtype": "int", "accept_none": False}, {"name": "max_leaf_nodes", "type": "input", "values": 4, "dtype": "int", "accept_none": True}, {"name": "warm_start", "type": "select", "values": [False, True], "dtype": "boolean", "accept_none": False}, {"name": "validation_fraction", "type": "input", "values": 0.1, "dtype": "float", "accept_none": False}, {"name": "n_iter_no_change", "type": "input", "values": 95, "dtype": "int", "accept_none": True}, {"name": "tol", "type": "input", "values": 0.0001, "dtype": "float", "accept_none": False}, {"name": "ccp_alpha", "type": "input", "values": 0.0, "dtype": "float", "accept_none": False}] # ----------------------------------------------------------------------------------------------------------- # CLASSIFICATION ------------- LogisticRegression_Params = [ {"name": "penalty", "type": "select", "values": ['l2', 'l1', 'elasticnet', 'None'], "dtype": "string", "accept_none": True}, {"name": "dual", "type": "select", "values": [False, True], "dtype": "boolean", "accept_none": False}, {"name": "tol", "type": "input", "values": 0.0001, "dtype": "float", "accept_none": False}, {"name": "C", "type": "input", "values": 1.0, "dtype": "float", "accept_none": False}, {"name": "fit_intercept", "type": "select", "values": [True, False], "dtype": "boolean", "accept_none": False}, {"name": "intercept_scaling", "type": "input", "values": 1.0, "dtype": "float", "accept_none": False}, {"name": "class_weight", "type": "select", "values": ["", 'balanced'], "dtype": "string", "accept_none": True}, {"name": "random_state", "type": "input", "values": 101, "dtype": "int", "accept_none": True}, {"name": "solver", "type": "select", "values": ["lbfgs", "newton-cg", "liblinear", "sag", "saga"], "dtype": "string", "accept_none": False}, {"name": "max_iter", "type": "input", "values": 100, "dtype": "int", "accept_none": False}, {"name": "multi_class", "type": "select", "values": ["auto", "ovr", "multinomial"], "dtype": "string", "accept_none": False}, {"name": "verbose", "type": "input", "values": 0, "dtype": "int", "accept_none": False}, {"name": "warm_start", "type": "select", "values": [False, True], "dtype": "boolean", "accept_none": False}, {"name": "n_jobs", "type": "input", "values": -1, "dtype": "int", "accept_none": True}, {"name": "l1_ratio", "type": "input", "values": 0.5, "dtype": "float", "accept_none": True}] SVC_Params = [ {"name": "C", "type": "input", "values": 1.0, "dtype": "float", "accept_none": False}, {"name": "kernel", "type": "select", "values": ['rbf', 'poly', 'sigmoid', 'linear', 'precomputed'], "dtype": "string", "accept_none": False}, {"name": "degree", "type": "input", "values": 3, "dtype": "int", "accept_none": False}, {"name": "gamma", "type": "select", "values": ["scale", "auto"], "dtype": "string", "accept_none": False}, {"name": "coef0", "type": "input", "values": 0.0, "dtype": "float", "accept_none": False}, {"name": "shrinking", "type": "select", "values": [True, False], "dtype": "boolean", "accept_none": False}, {"name": "probability", "type": "select", "values": [False, True], "dtype": "boolean", "accept_none": False}, {"name": "tol", "type": "input", "values": 0.001, "dtype": "float", "accept_none": False}, {"name": "cache_size", "type": "input", "values": 200, "dtype": "float", "accept_none": False}, {"name": "class_weight", "type": "select", "values": ['balanced'], "dtype": "string", "accept_none": True}, {"name": "verbose", "type": "select", "values": [False, True], "dtype": "boolean", "accept_none": False}, {"name": "max_iter", "type": "input", "values": -1, "dtype": "int", "accept_none": False}, {"name": "break_ties", "type": "select", "values": [False, True], "dtype": "boolean", "accept_none": False}, {"name": "random_state", "type": "input", "values": 101, "dtype": "int", "accept_none": True}] KNeighborsClassifier_Params = [ {"name": "n_neighbors", "type": "input", "values": 5, "dtype": "int", "accept_none": False}, {"name": "weights", "type": "select", "values": ['uniform', 'distance'], "dtype": "string", "accept_none": False}, {"name": "algorithm", "type": "select", "values": ["auto", "ball_tree", "kd_tree", "brute"], "dtype": "string", "accept_none": False}, {"name": "leaf_size", "type": "input", "values": 30, "dtype": "int", "accept_none": False}, {"name": "p", "type": "input", "values": 2, "dtype": "int", "accept_none": True}, {"name": "metric", "type": "select", "values": ['minkowski', 'euclidean', 'manhattan', 'chebyshev', 'mahalanobis'], "dtype": "string", "accept_none": False}, {"name": "n_jobs", "type": "input", "values": -1, "dtype": "int", "accept_none": True} ] DecisionTreeClassifier_Params = [ {"name": "criterion", "type": "select", "values": ['gini', 'entropy'], "dtype": "string", "accept_none": False}, {"name": "splitter", "type": "select", "values": ['best', 'random'], "dtype": "string", "accept_none": False}, {"name": "max_depth", "type": "input", "values": 5, "dtype": "int", "accept_none": False}, {"name": "min_samples_split", "type": "input", "values": 2, "dtype": "int", "accept_none": False}, {"name": "min_samples_leaf", "type": "input", "values": 1, "dtype": "int", "accept_none": False}, {"name": "min_weight_fraction_leaf", "type": "input", "values": 0.0, "dtype": "float", "accept_none": False}, {"name": "max_features", "type": "select", "values": ["auto", "sqrt", "log2"], "dtype": "string", "accept_none": True}, {"name": "random_state", "type": "input", "values": 101, "dtype": "int", "accept_none": True}, {"name": "max_leaf_nodes", "type": "input", "values": 5, "dtype": "int", "accept_none": True}, {"name": "min_impurity_decrease", "type": "input", "values": 0.0, "dtype": "float", "accept_none": True}, {"name": "class_weight", "type": "select", "values": ["balanced"], "dtype": "string", "accept_none": True}, {"name": "ccp_alpha", "type": "input", "values": 0.0, "dtype": "float", "accept_none": True}] RandomForestClassifier_Params = [ {"name": "n_estimators", "type": "input", "values": 100, "dtype": "int", "accept_none": False}, {"name": "criterion", "type": "select", "values": ["gini", "entropy"], "dtype": "string", "accept_none": False}, {"name": "max_depth", "type": "input", "values": 5, "dtype": "int", "accept_none": True}, {"name": "min_samples_split", "type": "input", "values": 2, "dtype": "int", "accept_none": False}, {"name": "min_samples_leaf", "type": "input", "values": 1, "dtype": "int", "accept_none": False}, {"name": "min_weight_fraction_leaf", "type": "input", "values": 0.0, "dtype": "float", "accept_none": False}, {"name": "max_features", "type": "select", "values": ["auto", "sqrt", "log2"], "dtype": "string", "accept_none": True}, {"name": "max_leaf_nodes", "type": "input", "values": 5, "dtype": "int", "accept_none": True}, {"name": "min_impurity_decrease", "type": "input", "values": 0.0, "dtype": "float", "accept_none": True}, {"name": "bootstrap", "type": "select", "values": [True, False], "dtype": "boolean", "accept_none": False}, {"name": "oob_score", "type": "select", "values": [False, True], "dtype": "boolean", "accept_none": False}, {"name": "n_jobs", "type": "input", "values": -1, "dtype": "int", "accept_none": True}, {"name": "random_state", "type": "input", "values": 101, "dtype": "int", "accept_none": True}, {"name": "verbose", "type": "input", "values": 0, "dtype": "int", "accept_none": False}, {"name": "warm_start", "type": "select", "values": [False, True], "dtype": "boolean", "accept_none": False}, {"name": "class_weight", "type": "select", "values": ["balanced", "balanced_subsample"], "dtype": "string", "accept_none": True}, {"name": "ccp_alpha", "type": "input", "values": 0.0, "dtype": "float", "accept_none": True}, {"name": "max_samples", "type": "input", "values": "", "dtype": "int", "accept_none": True}] GradientBoostingClassifier_Params = [ {"name": "loss", "type": "select", "values": ["deviance", "exponential"], "dtype": "string", "accept_none": False}, {"name": "learning_rate", "type": "input", "values": 0.1, "dtype": "float", "accept_none": False}, {"name": "n_estimators", "type": "input", "values": 100, "dtype": "int", "accept_none": False}, {"name": "subsample", "type": "input", "values": 1.0, "dtype": "float", "accept_none": False}, {"name": "criterion", "type": "select", "values": ["friedman_mse", "squared_error", "mae"], "dtype": "string", "accept_none": False}, {"name": "min_samples_split", "type": "input", "values": 2, "dtype": "int", "accept_none": False}, {"name": "min_samples_leaf", "type": "input", "values": 1, "dtype": "int", "accept_none": False}, {"name": "min_weight_fraction_leaf", "type": "input", "values": 0.0, "dtype": "float", "accept_none": False}, {"name": "max_depth", "type": "input", "values": 3, "dtype": "int", "accept_none": False}, {"name": "min_impurity_decrease", "type": "input", "values": 0.0, "dtype": "float", "accept_none": False}, {"name": "random_state", "type": "input", "values": 100, "dtype": "int", "accept_none": True}, {"name": "max_features", "type": "select", "values": ["auto", "sqrt", "log2"], "dtype": "string", "accept_none": True}, {"name": "verbose", "type": "input", "values": 0, "dtype": "int", "accept_none": False}, {"name": "max_leaf_nodes", "type": "input", "values": 5, "dtype": "int", "accept_none": True}, {"name": "warm_start", "type": "select", "values": [False, True], "dtype": "boolean", "accept_none": False}, {"name": "validation_fraction", "type": "input", "values": 0.1, "dtype": "float", "accept_none": False}, {"name": "n_iter_no_change", "type": "input", "values": 5, "dtype": "int", "accept_none": True}, {"name": "tol", "type": "input", "values": 0.0001, "dtype": "float", "accept_none": False}, {"name": "ccp_alpha", "type": "input", "values": 0.0, "dtype": "float", "accept_none": False}] AdaBoostClassifier_Params = [ {"name": "base_estimator", "type": "input", "values": None, "dtype": "object", "accept_none": True}, {"name": "n_estimators", "type": "input", "values": 50, "dtype": "int", "accept_none": False}, {"name": "learning_rate", "type": "input", "values": 1.0, "dtype": "float", "accept_none": False}, {"name": "algorithm", "type": "select", "values": ["SAMME.R", "SAMME"], "dtype": "string", "accept_none": False}, {"name": "random_state", "type": "input", "values": 1, "dtype": "int", "accept_none": True}] # ----------------------------------------------------------------------------------------------------------- KmeansClustering_Params = [ {"name": "n_clusters", "type": "input", "values": 8, "dtype": "int", "accept_none": False}, {"name": "init", "type": "select", "values": ["k-means++", "random"], "dtype": "string", "accept_none": False}, {"name": "n_init", "type": "input", "values": 10, "dtype": "int", "accept_none": False}, {"name": "max_iter", "type": "input", "values": 300, "dtype": "int", "accept_none": False}, {"name": "tol", "type": "float", "values": 0.0001, "dtype": "float", "accept_none": False}, {"name": "verbose", "type": "input", "values": 0, "dtype": "int", "accept_none": False}, {"name": "random_state", "type": "input", "values": 1, "dtype": "int", "accept_none": True}, {"name": "copy_x", "type": "select", "values": [True, False], "dtype": "boolean", "accept_none": False}, {"name": "algorithm", "type": "select", "values": ["auto", "full", "elkan"], "dtype": "string", "accept_none": False}] DbscanClustering_Params = [ {"name": "eps", "type": "float", "values": 0.5, "dtype": "float", "accept_none": False}, {"name": "min_samples", "type": "input", "values": 5, "dtype": "int", "accept_none": False}, {"name": "metric", "type": "select", "values": ['euclidean', 'cityblock', 'cosine', 'l1', 'l2', 'manhattan'], "dtype": "string", "accept_none": False}, {"name": "algorithm", "type": "select", "values": ["auto", "ball_tree", "kd_tree", "brute"], "dtype": "string", "accept_none": False}, {"name": "leaf_size", "type": "input", "values": 30, "dtype": "int", "accept_none": False}, {"name": "n_jobs", "type": "input", "values": -1, "dtype": "int", "accept_none": True}] AgglomerativeClustering_Params = [ {"name": "n_clusters", "type": "input", "values": 2, "dtype": "int", "accept_none": True}, {"name": "affinity", "type": "select", "values": ["euclidean"], "dtype": "string", "accept_none": False}, {"name": "compute_full_tree", "type": "select", "values": ["auto"], "dtype": "string", "accept_none": False}, {"name": "linkage", "type": "select", "values": ["ward", "complete", "average", "single"], "dtype": "string", "accept_none": False}, {"name": "compute_distances", "type": "select", "values": [False, True], "dtype": "boolean", "accept_none": False}] Params_Mappings = { "true": True, "false": False }
class Person: __key = None __cipher_algorithm = None def get_key(self): return self.__key def set_key(self, new_key): self.__key = new_key def operate_cipher(self, encrypted_text): pass def set_cipher_algorithm(self, cipher_algorithm): self.__cipher_algorithm = cipher_algorithm def get_cipher_algorithm(self): return self.__cipher_algorithm
# coding: utf-8 # ファイル名を"my_key.py"にリネームし、 # 下記のキーをセットしておいてください。 consumer_key = "ここにコンシューマー・キーを貼り付けてください" consumer_secret = "コンシューマー・シークレットを貼り付けてください" access_token_key = "アクセス・トークン・キーを貼り付けてください" access_token_secret = "アクセス・トークン・シークレットを貼り付けてください"
def sum_list_values(list_values): return sum(list_values) def symbolic_to_octal(perm_string): perms = {"r": 4, "w": 2, "x": 1, "-": 0} string_value = [] symb_to_octal = [] slicing_values = {"0": perm_string[:3], "1": perm_string[3:6], "2":perm_string[6:9]} for perms_key, value in perms.items(): for string_values in slicing_values.items(): for v in string_values[1]: if v == perms_key: string_value.append(value) sum_strings = sum_list_values(string_value) symb_to_octal.append(sum_strings) return (symb_to_octal) #assert symbolic_to_octal('rwxr-x-w-') == 752 print(symbolic_to_octal('rwxr-x-w-'))
print(str(b'ABC'.count(b'A'))) print(str(b'ABC'.count(b'AB'))) print(str(b'ABC'.count(b'AC'))) print(str(b'AbcA'.count(b'A'))) print(str(b'AbcAbcAbc'.count(b'A', 3))) print(str(b'AbcAbcAbc'.count(b'A', 3, 5))) print() print(str(bytearray(b'ABC').count(b'A'))) print(str(bytearray(b'ABC').count(b'AB'))) print(str(bytearray(b'ABC').count(b'AC'))) print(str(bytearray(b'AbcA').count(b'A'))) print(str(bytearray(b'AbcAbcAbc').count(b'A', 3))) print(str(bytearray(b'AbcAbcAbc').count(b'A', 3, 5))) print() print(str(bytearray(b'ABC').count(bytearray(b'A')))) print(str(bytearray(b'ABC').count(bytearray(b'AB')))) print(str(bytearray(b'ABC').count(bytearray(b'AC')))) print(str(bytearray(b'AbcA').count(bytearray(b'A')))) print(str(bytearray(b'AbcAbcAbc').count(bytearray(b'A'), 3))) print(str(bytearray(b'AbcAbcAbc').count(bytearray(b'A'), 3, 5)))
"""Definition for updatesrc_diff_and_update macro.""" load("@bazel_skylib//rules:diff_test.bzl", "diff_test") load(":updatesrc_update.bzl", "updatesrc_update") def updatesrc_diff_and_update( srcs, outs, name = None, update_name = "update", diff_test_prefix = "", diff_test_suffix = "_difftest", update_visibility = None, diff_test_visibility = None): """Defines an `updatesrc_update` for the package and `diff_test` targets for each src-out pair. Args: srcs: Source files that will be updated by the files listed in the `outs` attribute. Every file listed in the `srcs` attribute must have a corresponding output file listed in the `outs` attribute. outs: Output files that will be used to update the files listed in the `srcs` attribute. Every file listed in the `outs` attribute must have a corresponding source file list in the `srcs` attribute. name: Optional. The name of the `updatesrc_update` target. update_name: Deprecated. The name of the `updatesrc_update` target. diff_test_prefix: Optional. The prefix to be used for the `diff_test` target names. diff_test_suffix: Optional. The suffix to be used for the `diff_test` target names. update_visibility: Optional. The visibility declarations for the `updatesrc_update` target. diff_test_visibility: Optional. The visibility declarations for the `diff_test` targets. """ # Make sure that we have the same number of srcs and outs. if len(srcs) != len(outs): fail("The number of srcs does not match the number of outs.") # Define the diff tests. for idx in range(len(srcs)): src = srcs[idx] out = outs[idx] src_name = src.replace("/", "_") diff_test( name = diff_test_prefix + src_name + diff_test_suffix, file1 = src, file2 = out, visibility = diff_test_visibility, ) if name == None: if update_name == None: fail("Please specify a value for the name attribute.") else: name = update_name # Define the update target updatesrc_update( name = name, srcs = srcs, outs = outs, visibility = update_visibility, )
"""Core exceptions""" class RPGTKBaseException(Exception): pass class DiceException(RPGTKBaseException): pass
""" philoseismos: with passion for the seismic method. This file is needed to run pytest from a repository directory and avoid any PYTHONPATH related import issues. @author: Ivan Dubrovin e-mail: [email protected] """
""" Given a unsorted array with integers, find the median of it. A median is the middle number of the array after it is sorted. If there are even numbers in the array, return the N/2-th number after sorted. Example Given [4, 5, 1, 2, 3], return 3 Given [7, 9, 4, 5], return 5 Challenge O(n) time. """ __author__ = 'Danyang' class Solution: def median(self, nums): """ O(n), to find k-th number partial quick sort :param nums: A list of integers. :return: An integer denotes the middle number of the array. """ n = len(nums) return self.find_kth(nums, 0, n, (n-1)/2) def find_kth(self, A, i, j, k): p = self.pivot(A, i, j) if k == p: return A[p] elif k > p: return self.find_kth(A, p+1, j, k) else: return self.find_kth(A, i, p, k) def pivot(self, A, i, j): """ Fix the pivot as the 1st element In the end, move the pivot to the end of closed set but still inside the closed set, in order to bisect pivoting algorithm: p | closed set | open set | | closed set p | open set | """ p = i closed = p for ptr in xrange(i, j): if A[ptr] < A[p]: closed += 1 A[ptr], A[closed] = A[closed], A[ptr] A[closed], A[p] = A[p], A[closed] return closed if __name__ == "__main__": assert Solution().median([4, 5, 1, 2, 3]) == 3 assert Solution().median([7, 9, 4, 5]) == 5
config ={ 'CONTEXT' : 'We are in DEV context', 'Log_bucket' : 'gc://bucketname_great', 'versionNR' : 'v12.236', 'zone' : 'europe-west1-d', }
def classify(number): if number < 1: raise ValueError("Value too small") aliquot = 0 for i in range(number-1): if number % (i+1) == 0: aliquot += i+1 return "perfect" if aliquot == number else "abundant" if aliquot > number else "deficient"
# File: taniumrest_consts.py # Copyright (c) 2019-2021 Splunk Inc. # # Licensed under Apache 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) SESSION_URL = "/api/v2/session/login" TANIUMREST_GET_SAVED_QUESTIONS = "/api/v2/saved_questions" TANIUMREST_GET_QUESTIONS = "/api/v2/questions" TANIUMREST_GET_QUESTION_RESULTS = "/api/v2/result_data/question/{question_id}" TANIUMREST_PARSE_QUESTION = "/api/v2/parse_question" TANIUMREST_EXECUTE_ACTION = "/api/v2/saved_actions" TANIUMREST_GET_ACTION_GROUP = "/api/v2/action_groups/by-name/{action_group}" TANIUMREST_GET_GROUP = "/api/v2/groups/by-name/{group_name}" TANIUMREST_GET_PACKAGE = "/api/v2/packages/by-name/{package}" TANIUMREST_GET_SAVED_QUESTION = "/api/v2/saved_questions/by-name/{saved_question}" TANIUMREST_GET_SENSOR_BY_NAME = "/api/v2/sensors/by-name/{sensor_name}" TANIUMREST_GET_SAVED_QUESTION_RESULT = "/api/v2/result_data/saved_question/{saved_question_id}" WAIT_SECONDS = 5 TANIUMREST_RESULTS_UNAVAILABLE = ["[current results unavailable]", "[current result unavailable]", "[results currently unavailable]"] # Constants relating to 'get_error_message_from_exception' ERR_CODE_MSG = "Error code unavailable" ERR_MSG_UNAVAILABLE = "Error message unavailable. Please check the asset configuration and|or action parameters" TYPE_ERR_MSG = "Error occurred while connecting to the Tanium Server. Please check the asset configuration and|or action parameters" # Constants relating to 'validate_integer' INVALID_INT_ERR_MSG = "Please provide a valid integer value in the {}" INVALID_NON_NEG_INT_ERR_MSG = "Please provide a valid non-negative integer value in the {}" INVALID_NON_NEG_NON_ZERO_ERR_MSG = "PLease provide a valid non-zero non-negative integer value in the {}" EXPIRE_SECONDS_KEY = "'expire_seconds' action parameter" DISTRIBUTE_SECONDS_KEY = "'distribute_seconds' action parameter" ISSUE_SECONDS_KEY = "'issue_seconds' action parameter" TIMEOUT_SECONDS_KEY = "'timeout_seconds' action parameter" RETURN_WHEN_N_RESULTS_AVAILABLE_KEY = "'return_when_n_results_available' action parameter" WAIT_FOR_N_RESULTS_AVAILABLE_KEY = "'wait_for_n_results_available' action parameter" RESULTS_PERCENTAGE_KEY = "'Consider question results complete at' configuration parameter" QUESTION_ID_KEY = "'question_id' action parameter"
class MlflowException(Exception): """Base exception in MLflow.""" class IllegalArtifactPathError(MlflowException): """The artifact_path parameter was invalid.""" class ExecutionException(MlflowException): """Exception thrown when executing a project fails.""" pass
Text = 'text' Audio = 'audio' Document = 'document' Animation = 'animation' Game = 'game' Photo = 'photo' Sticker = 'sticker' Video = 'video' Voice = 'voice' VideoNote = 'video_note' Contact = 'contact' Dice = 'dice' Location = 'location' Venue = 'venue' Poll = 'poll' NewChatMembers = 'new_chat_members' LeftChatMember = 'left_chat_member' NewChatTitle = 'new_chat_title' NewChatPhoto = 'new_chat_photo' DeleteChatPhoto = 'delete_chat_photo' GroupChatCreated = 'group_chat_created' SupergroupChatCreated = 'supergroup_chat_created' ChannelChatCreated = 'channel_chat_created' MigrateToChatId = 'migrate_to_chat_id' MigrateFromChatId = 'migrate_from_chat_id' PinnedMessage = 'pinned_message' Invoice = 'invoice' SuccessfulPayment = 'successful_payment' PassportData = 'passport_data'
class A: def met(self): print("this is a method from class A") class B(A): def met(self): print("this is a method from class B") class C(A): def met(self): print("this is a method from class C") class D(C,B): def met(self): print("this is a method from class D") a = A() b = B() c = C() d = D() d.met()
# -*- coding: utf-8 -*- class Solution: def nthPersonGetsNthSeat(self, n): return 1 if n == 1 else 0.5 if __name__ == '__main__': solution = Solution() assert 1 == solution.nthPersonGetsNthSeat(1) assert 0.5 == solution.nthPersonGetsNthSeat(2) assert 0.5 == solution.nthPersonGetsNthSeat(3)
# Create a function that takes a number num and returns its length. def number_length(num): if num != None: count = 1 val = num while(val // 10 != 0): count += 1 val = val // 10 return count print(number_length(392))
class Node: def __init__(self, name): self.data = name self.nextnode = None def remove(self, data, previous): if self.data == data: previous.nextnode = self.nextnode del self.data else: if self.nextnode is not None: self.nextnode.remove(data, self)
#!/usr/local/bin/python3.7 # -*- coding: utf-8 -*- # Definition for single-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class MyListNode: def __init__(self, head=None): self.head = head def get(self, index: int) -> int: """ 获取链表指定节点的值,没有找到的话返回-1 """ i = 0 list_node = self.head while list_node and i < index: list_node = list_node.next i += 1 if list_node: return list_node.val return -1 def addAtHead(self, val: int): """ 在链表头部插一个值为val的节点 """ head_node = ListNode(val) head_node.next = self.head self.head = head_node def addAtTail(self, val: int): """ 在链表尾部添加一个值为val的节点 """ tail_node = ListNode(val) if not self.head: self.head = tail_node #空链表直接赋值head return list_node = self.head while list_node.next: list_node = list_node.next if list_node: list_node.next = tail_node def addAtIndex(self, index: int, val: int): """ 在索引为index的节点之前添加值为val的节点 """ add_node = ListNode(val) if index <= 0: add_node.next = self.head self.head = add_node return i = 0 list_node = self.head while list_node and i < index - 1: #插入删除需要找到前驱节点 list_node = list_node.next i += 1 if list_node: add_node.next = list_node.next list_node.next = add_node def deleteAtIndex(self, index: int): """ 删除索引为index的节点 """ if index == 0 and self.head: del_node = self.head self.head = self.head.next del del_node return i = 0 list_node = self.head while list_node and i < index - 1: list_node = list_node.next i += 1 if not list_node: return if list_node.next: del_node = list_node.next list_node.next = del_node.next del del_node def length(self) -> int: """ 链表长度 :return: """ len = 0 list_node = self.head while list_node: len += 1 list_node = list_node.next return len def clear(self): """ 清空链表 """ # self.head = None del_node = None while self.head: del_node = self.head self.head = self.head.next del del_node def list_node_test(): my_list_node = MyListNode() my_list_node.addAtTail(5) my_list_node.addAtHead(1) my_list_node.addAtIndex(0, 10) my_list_node.addAtIndex(1, 20) my_list_node.addAtIndex(2, 30) my_list_node.addAtIndex(3, 40) my_list_node.addAtTail(50) my_list_node.addAtTail(60) node = my_list_node.head while node: print(node.val) node = node.next my_list_node.deleteAtIndex(2) print('length:', my_list_node.length()) for i in range(my_list_node.length()): print(my_list_node.get(i)) my_list_node.clear() print('length:', my_list_node.length()) if __name__ == '__main__': list_node_test()
n = float(input('Digite a velocidade do carro(KM): ')) if n > 80: multa = (n - 80) * 7 print(f'Você foi multado \nvalor da multa R${multa:.2f}') else: print(f'Sua velocidade foi de {n}KM/H, tenha um bom dia!')
expected_output = { 'vrf': {'VRF1': {'address_family': {'ipv6': {}}}, 'blue': {'address_family': {'ipv6': {'multicast_group': {'ff30::/12': {'source_address': {'*': {'flags': 'ipv6 pim6', 'incoming_interface_list': {'Null': {'rpf_nbr': '0::'}}, 'oil_count': '0', 'uptime': '10w5d'}}}}}}}, 'default': {'address_family': {'ipv6': {'multicast_group': {'ff03:3::/64': {'source_address': {'*': {'bidir': True, 'flags': 'pim6', 'incoming_interface_list': {'Null': {'rpf_nbr': '0::'}}, 'oil_count': '0', 'uptime': '10w5d'}}}, 'ff30::/12': {'source_address': {'*': {'flags': 'ipv6 pim6', 'incoming_interface_list': {'Null': {'rpf_nbr': '0::'}}, 'oil_count': '0', 'uptime': '10w5d'}}}}}}}}}
class Solution: def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None: """ Do not return anything, modify nums1 in-place instead. """ idx1 = m - 1 idx2 = n - 1 while idx1>=0 and idx2>=0: if nums1[idx1] > nums2[idx2]: nums1[idx1 + idx2 + 1] = nums1[idx1] idx1 -= 1 else: nums1[idx1 + idx2 + 1] = nums2[idx2] idx2 -= 1 if idx1 < 0: # for i in range(idx2+1): # nums1[i] = nums2[i] nums1[:idx2+1] = nums2[:idx2+1]
# The URL we will use when accessing a gulag API instance. api_url: str = "cmyui.codes" # When set to True it will allow us to make unverified HTTPS requests. (Good for testing.) unsafe_request: bool = False
{ 'target_defaults': { 'cflags': [ '-Wunused', '-Wshadow', '-Wextra', ], }, 'targets': [ # D-Bus code generator. { 'target_name': 'dbus_code_generator', 'type': 'none', 'variables': { 'dbus_service_config': 'dbus_bindings/dbus-service-config.json', 'dbus_adaptors_out_dir': 'include/authpolicy', }, 'sources': [ 'dbus_bindings/org.chromium.AuthPolicy.xml', ], 'includes': ['../common-mk/generate-dbus-adaptors.gypi'], }, # Container protos { 'target_name': 'container-protos', 'type': 'static_library', 'variables': { 'proto_in_dir': 'proto', 'proto_out_dir': 'include/bindings', }, 'sources': [ '<(proto_in_dir)/authpolicy_containers.proto', ], 'includes': ['../common-mk/protoc.gypi'], }, # Autogenerated policy sources { 'target_name': 'policy_code_generator', 'type': 'none', 'hard_dependency': 1, 'variables': { 'policy_tools_dir': '<(sysroot)/usr/share/policy_tools', 'policy_resources_dir': '<(sysroot)/usr/share/policy_resources', 'out_dir': '<(SHARED_INTERMEDIATE_DIR)/include/bindings', }, 'actions': [{ 'action_name': 'run_generate_script', 'inputs': [ '<(policy_tools_dir)/generate_policy_source.py', '<(policy_resources_dir)/policy_templates.json', '<(policy_resources_dir)/VERSION', ], 'outputs': [ '<(out_dir)/policy_constants.h', '<(out_dir)/policy_constants.cc', ], 'action': [ 'python', '<(policy_tools_dir)/generate_policy_source.py', '--cros-policy-constants-header=<(out_dir)/policy_constants.h', '--cros-policy-constants-source=<(out_dir)/policy_constants.cc', '<(policy_resources_dir)/VERSION', '<(OS)', '1', # chromeos-flag '<(policy_resources_dir)/policy_templates.json', ], }], }, # Authpolicy library. { 'target_name': 'libauthpolicy', 'type': 'static_library', 'dependencies': [ '../common-mk/external_dependencies.gyp:policy-protos', '../common-mk/external_dependencies.gyp:user_policy-protos', 'container-protos', 'dbus_code_generator', 'policy_code_generator', ], 'variables': { 'gen_src_in_dir': '<(SHARED_INTERMEDIATE_DIR)/include/bindings', 'deps': [ 'dbus-1', 'libbrillo-<(libbase_ver)', 'libchrome-<(libbase_ver)', ], }, 'sources': [ '<(gen_src_in_dir)/policy_constants.cc', 'authpolicy.cc', 'authpolicy_metrics.cc', 'constants.cc', 'jail_helper.cc', 'path_service.cc', 'platform_helper.cc', 'policy/device_policy_encoder.cc', 'policy/policy_encoder_helper.cc', 'policy/preg_policy_encoder.cc', 'policy/user_policy_encoder.cc', 'process_executor.cc', 'samba_helper.cc', 'samba_interface.cc', 'tgt_manager.cc', ], }, # Parser tool. { 'target_name': 'authpolicy_parser', 'type': 'executable', 'dependencies': ['libauthpolicy'], 'variables': { 'deps': [ 'libbrillo-<(libbase_ver)', 'libcap', 'libchrome-<(libbase_ver)', 'libmetrics-<(libbase_ver)', 'libminijail', 'protobuf-lite', ], }, 'sources': [ 'authpolicy_parser_main.cc', ], }, # Authpolicy daemon executable. { 'target_name': 'authpolicyd', 'type': 'executable', 'dependencies': [ 'libauthpolicy', 'authpolicy_parser', ], 'variables': { 'deps': [ 'libbrillo-<(libbase_ver)', 'libcap', 'libchrome-<(libbase_ver)', 'libmetrics-<(libbase_ver)', 'libminijail', # system_api depends on protobuf (or protobuf-lite). It must appear # before protobuf or the linker flags won't be in the right order. 'system_api', 'protobuf-lite', ], }, 'sources': ['authpolicy_main.cc'], 'link_settings': { 'libraries': [ '-linstallattributes-<(libbase_ver)', ], }, }, ], # Unit tests. 'conditions': [ ['USE_test == 1', { 'targets': [ { 'target_name': 'authpolicy_test', 'type': 'executable', 'includes': ['../common-mk/common_test.gypi'], 'defines': ['UNIT_TEST'], 'dependencies': [ 'libauthpolicy', 'stub_common', ], 'variables': { 'deps': [ 'libbrillo-<(libbase_ver)', 'libcap', 'libchrome-<(libbase_ver)', 'libchrome-test-<(libbase_ver)', 'libmetrics-<(libbase_ver)', 'libminijail', # system_api depends on protobuf (or protobuf-lite). It must # appear before protobuf or the linker flags won't be in the right # order. 'system_api', 'protobuf-lite', ], }, 'sources': [ 'authpolicy_testrunner.cc', 'authpolicy_unittest.cc', 'policy/device_policy_encoder_unittest.cc', 'policy/user_policy_encoder_unittest.cc', 'process_executor_unittest.cc', 'samba_helper_unittest.cc', ], }, { 'target_name': 'stub_common', 'type': 'static_library', 'variables': { 'deps': [ 'libchrome-<(libbase_ver)', ], }, 'sources': ['stub_common.cc'], }, { 'target_name': 'stub_net', 'type': 'executable', 'dependencies': [ 'libauthpolicy', 'stub_common', ], 'variables': { 'deps': [ 'libcap', 'libchrome-<(libbase_ver)', ], }, 'sources': ['stub_net_main.cc'], }, { 'target_name': 'stub_kinit', 'type': 'executable', 'dependencies': [ 'libauthpolicy', 'stub_common', ], 'variables': { 'deps': [ 'libcap', 'libchrome-<(libbase_ver)', ], }, 'sources': ['stub_kinit_main.cc'], }, { 'target_name': 'stub_klist', 'type': 'executable', 'dependencies': [ 'libauthpolicy', 'stub_common', ], 'variables': { 'deps': ['libchrome-<(libbase_ver)'], }, 'sources': ['stub_klist_main.cc'], }, { 'target_name': 'stub_smbclient', 'type': 'executable', 'dependencies': [ 'libauthpolicy', 'stub_common', ], 'variables': { 'deps': ['libchrome-<(libbase_ver)'], }, 'sources': ['stub_smbclient_main.cc'], }, ], }], ], }
# Faça um programa que leia nome e média de um aluno, guardando também a situação em um dicionário. # No final, mostre o conteúdo da estrutura na tela. cores = {'limpa':'\033[m', 'bverde':'\033[1;32m', 'bvermelho': '\033[1;31m', 'pretoebranco':'\033[7:30m'} print('-=-'*10) print(cores['pretoebranco']+'_____INICIO_____'+cores['limpa']) print('-=-'*10) aluno = dict() aluno['nome'] = str(input('Nome: ')) aluno['média'] = float(input(f'Média de {aluno["nome"]}: ')) print(f"O nome é igual a: {aluno['nome']}") print(f'A Média é igual a: {aluno["média"]}') if aluno['média'] >= 7: aluno['situação'] = 'Aprovado' if 5 <= aluno['média'] < 7: aluno['situação'] = 'Recuperação' else: aluno['situação'] = 'Reprovado' for k,v in aluno.items(): print(f' - {k} do aluno é: {v}') print('') print('-=-'*10) print(cores['pretoebranco']+'______FIM_______'+cores['limpa']) print(cores['pretoebranco']+'_Code by Rafael_'+cores['limpa']) print('-=-'*10)
ENTRY_POINT = 'is_multiply_prime' FIX = """ Fix incorrect is_prime function Add more tests """ #[PROMPT] def is_multiply_prime(a): """Write a function that returns true if the given number is the multiplication of 3 prime numbers and false otherwise. Knowing that (a) is less then 100. Example: is_multiply_prime(30) == True 30 = 2 * 3 * 5 """ #[SOLUTION] def is_prime(n): for j in range(2,n): if n%j == 0: return False return True for i in range(2,101): if not is_prime(i): continue for j in range(2,101): if not is_prime(j): continue for k in range(2,101): if not is_prime(k): continue if i*j*k == a: return True return False #[CHECK] def check(candidate): assert candidate(5) == False assert candidate(30) == True assert candidate(8) == True assert candidate(10) == False assert candidate(125) == True assert candidate(3 * 5 * 7) == True assert candidate(3 * 6 * 7) == False assert candidate(9 * 9 * 9) == False assert candidate(11 * 9 * 9) == False assert candidate(11 * 13 * 7) == True
class AbstractTransitionSystem: def __init__(self, num_labels): self.num_labels = num_labels def num_actions(self): raise NotImplementedError() def state(self, num_tokens): raise NotImplementedError() def is_final(self, state): raise NotImplementedError() def extract_parse(self, state): raise NotImplementedError() def allowed(self, state): raise NotImplementedError() def reference_policy(self): raise NotImplementedError() def action_name(self, action_index): return 'Action=' + str(action_index) def describe_action(self, state, action_index): raise self.action_name(action_index) + ' at ' + str(state) def perform(self, state, action_index): raise NotImplementedError() class AbstractReferencePolicy: def is_optimal(self): raise NotImplementedError()
Import('defenv') ### Configuration options cfg = Variables() cfg.Add( ( 'NSIS_MAX_STRLEN', 'defines the maximum string length for internal variables and stack entries. 1024 should be plenty, but if you are doing crazy registry stuff, you might want to bump it up. Generally it adds about 16-32x the memory, so setting this to 4096 from 1024 will add around 64k of memory usage (not really a big deal, but not usually needed).', 1024 ) ) cfg.Add( ( 'NSIS_MAX_INST_TYPES', 'defines the maximum install types. Note that this should not exceed 32, ever.', 32 ) ) cfg.Add( ( 'NSIS_DEFAULT_LANG', 'defines the default language id NSIS will use if nothing else is defined in the script. Default value is 1033 which is English.', 1033 ) ) cfg.Add( ( 'NSIS_VARS_SECTION', 'defines the name of the PE section containing the runtime variables', '.ndata' ) ) cfg.Add( BoolVariable( 'NSIS_CONFIG_UNINSTALL_SUPPORT', "enables the uninstaller support. Turn it off if your installers don't need uninstallers. Adds less than 1kb.", 'yes' ) ) cfg.Add( BoolVariable( 'NSIS_CONFIG_LICENSEPAGE', 'enables support for the installer to present a license page.', 'yes' ) ) cfg.Add( BoolVariable( 'NSIS_CONFIG_COMPONENTPAGE', 'enables support for the installer to present a page where you can select what sections are installed. with this disabled, all sections are installed by default', 'yes' ) ) cfg.Add( BoolVariable( 'NSIS_CONFIG_COMPONENTPAGE_ALTERNATIVE', 'enables an alternative components page behavior. Checkboxes will only be toggled when clicking on the checkbox itself and not on its label. .onMouseOverSection will only be called when the user selects the component and not when moving the mouse pointer over it.', 'no' ) ) cfg.Add( BoolVariable( 'NSIS_CONFIG_SILENT_SUPPORT', 'enables support for making installers that are completely silent.', 'yes' ) ) cfg.Add( BoolVariable( 'NSIS_CONFIG_VISIBLE_SUPPORT', 'enables support for making installers that are visible.', 'yes' ) ) cfg.Add( BoolVariable( 'NSIS_CONFIG_ENHANCEDUI_SUPPORT', 'enables support for CreateFont, SetCtlColors (used by some UIs), SetBrandingImage, .onGUIInit, etc.', 'yes' ) ) cfg.Add( BoolVariable( 'NSIS_CONFIG_COMPRESSION_SUPPORT', 'enables support for making installers that use compression (recommended).', 'yes' ) ) cfg.Add( BoolVariable( 'NSIS_COMPRESS_BZIP2_SMALLMODE', "if defined, bzip2's decompressor uses bzip2's alternative decompression method that uses less runtime memory, at the expense of speed (and executable size). not recommended.", 'no' ) ) cfg.Add( ( 'NSIS_COMPRESS_BZIP2_LEVEL', 'bzip2 compression window size. 1-9 is valid. 9 uses the most memory, but typically compresses best (recommended). 1 uses the least memory, but typically compresses the worst.', 9 ) ) cfg.Add( BoolVariable( 'NSIS_CONFIG_CRC_SUPPORT', 'enables support for installer verification. HIGHLY recommended.', 'yes' ) ) cfg.Add( BoolVariable( 'NSIS_CONFIG_CRC_ANAL', 'makes the CRC verification extremely careful, meaning extra bytes on the end of file, or the first 512 bytes changing, will give error. Enable this if you are paranoid, otherwise leaving it off seems safe (and is less prone to reporting virii). If you will be digitally signing your installers, leave this off.', 'no' ) ) cfg.Add( BoolVariable( 'NSIS_CONFIG_LOG', 'enables the logging facility. turning this on (by uncommenting it) adds about 4kb, but can be useful in debugging your installers.', 'no' ) ) cfg.Add( BoolVariable( 'NSIS_CONFIG_LOG_ODS', 'makes the logging facility use OutputDebugString instead of a file.', 'no' ) ) cfg.Add( BoolVariable( 'NSIS_CONFIG_LOG_STDOUT', 'makes the logging facility use stdout instead of a file.', 'no' ) ) cfg.Add( BoolVariable( 'NSIS_CONFIG_LOG_TIMESTAMP', 'adds a timestamp to each log line.', 'no' ) ) cfg.Add( BoolVariable( 'NSIS_SUPPORT_BGBG', 'enables support for the blue (well, whatever color you want) gradient background window.', 'yes' ) ) cfg.Add( BoolVariable( 'NSIS_SUPPORT_CODECALLBACKS', 'enables support for installer code callbacks. recommended, as it uses a minimum of space and allows for neat functionality.', 'yes' ) ) cfg.Add( BoolVariable( 'NSIS_SUPPORT_MOVEONREBOOT', 'enables support for uninstallers that automatically delete themselves from the temp directory, as well as the reboot moving/deleting modes of Delete and Rename. Adds about 512 gay bytes..', 'yes' ) ) ### Instruction enabling configuration cfg.Add( BoolVariable( 'NSIS_SUPPORT_ACTIVEXREG', 'enables activeX plug-in registration and deregistration, as well as CallInstDLL', 'yes' ) ) cfg.Add( BoolVariable( 'NSIS_SUPPORT_INTOPTS', 'enables support for IntCmp, IntCmpU, IntOp, and IntFmt.', 'yes' ) ) cfg.Add( BoolVariable( 'NSIS_SUPPORT_STROPTS', 'enables support for StrCmp, StrCpy, and StrLen, as well as Get*Local.', 'yes' ) ) cfg.Add( BoolVariable( 'NSIS_SUPPORT_STACK', 'enables support for the stack (Push, Pop, Exch)', 'yes' ) ) cfg.Add( BoolVariable( 'NSIS_SUPPORT_FILEFUNCTIONS', 'enables support for FileOpen,FileClose, FileSeek, FileRead, and FileWrite.', 'yes' ) ) cfg.Add( BoolVariable( 'NSIS_SUPPORT_FINDFIRST', 'enables support for FindFirst, FindNext, and FindClose.', 'yes' ) ) cfg.Add( BoolVariable( 'NSIS_SUPPORT_CREATESHORTCUT', 'enables support for CreateShortCut.', 'yes' ) ) cfg.Add( BoolVariable( 'NSIS_SUPPORT_INIFILES', 'enables support for ReadINIStr and WriteINIStr.', 'yes' ) ) cfg.Add( BoolVariable( 'NSIS_SUPPORT_REGISTRYFUNCTIONS', 'enables support for ReadRegStr, ReadRegDWORD, WriteRegStr, etc etc etc.', 'yes' ) ) cfg.Add( BoolVariable( 'NSIS_SUPPORT_COPYFILES', 'enables support for CopyFiles', 'yes' ) ) cfg.Add( BoolVariable( 'NSIS_SUPPORT_REBOOT', 'enables support for Reboot, IfRebootFlag, SetRebootFlag', 'yes' ) ) cfg.Add( BoolVariable( 'NSIS_SUPPORT_FNUTIL', 'enables support for GetFullPathName, GetTempFileName, and SearchPath', 'yes' ) ) cfg.Add( BoolVariable( 'NSIS_SUPPORT_EXECUTE', 'enables support for Exec and ExecWait', 'yes' ) ) cfg.Add( BoolVariable( 'NSIS_SUPPORT_SHELLEXECUTE', 'enables support for ExecShell', 'yes' ) ) cfg.Add( BoolVariable( 'NSIS_SUPPORT_GETDLLVERSION', 'enables support for GetDLLVersion', 'yes' ) ) cfg.Add( BoolVariable( 'NSIS_SUPPORT_GETFILETIME', 'enables support for GetFileTime', 'yes' ) ) cfg.Add( BoolVariable( 'NSIS_SUPPORT_GETFONTVERSION', 'enables support for GetFontversion', 'yes' ) ) cfg.Add( BoolVariable( 'NSIS_SUPPORT_GETFONTNAME', 'enables support for GetFontName', 'yes' ) ) cfg.Add( BoolVariable( 'NSIS_SUPPORT_HWNDS', 'enables support for FindWindow, SendMessage, and IsWindow', 'yes' ) ) cfg.Add( BoolVariable( 'NSIS_SUPPORT_ENVIRONMENT', 'enables support for ReadEnvStr and ExpandEnvStrings', 'yes' ) ) cfg.Add( BoolVariable( 'NSIS_SUPPORT_RMDIR', 'enables support for RMDir', 'yes' ) ) cfg.Add( BoolVariable( 'NSIS_SUPPORT_FILE', 'enables support for File (extracting files)', 'yes' ) ) cfg.Add( BoolVariable( 'NSIS_SUPPORT_DELETE', 'enables support for Delete (delete files)', 'yes' ) ) cfg.Add( BoolVariable( 'NSIS_SUPPORT_RENAME', 'enables support for Rename (rename files)', 'yes' ) ) cfg.Add( BoolVariable( 'NSIS_SUPPORT_MESSAGEBOX', 'enables support for MessageBox', 'yes' ) ) cfg.Add( BoolVariable( 'NSIS_SUPPORT_VERSION_INFO', 'enables support for version information in the installer', 'yes' ) ) cfg.Add( BoolVariable( 'NSIS_FIX_DEFINES_IN_STRINGS', 'fixes defines inside defines and handles chars $ perfectly', 'no' ) ) cfg.Add( BoolVariable( 'NSIS_SUPPORT_STANDARD_PREDEFINES', 'enables standard predefines - __FILE__, __LINE__, __DATE__, __TIME__ and __TIMESTAMP__', 'yes' ) ) cfg.Add( BoolVariable( 'NSIS_LOCKWINDOW_SUPPORT', 'enables the LockWindow command', 'yes' ) ) cfg.Add( BoolVariable( 'NSIS_CONFIG_PLUGIN_SUPPORT', 'enables installer plug-ins support', 'yes' ) ) cfg.Add( BoolVariable( 'NSIS_FIX_COMMENT_HANDLING', 'fixes comment handling', 'yes' ) ) cfg.Add( BoolVariable( 'NSIS_CONFIG_CONST_DATA_PATH', 'determines if plugins, includes, stubs etc. are located in a constant path set at build-time', defenv['PLATFORM'] != 'win32' ) ) ### Generate help Help(cfg.GenerateHelpText(defenv)) ### Apply configuration env = Environment() cfg.Update(env) def AddValuedDefine(define): defenv.Append(NSIS_CPPDEFINES = [(define, env[define])]) def AddBoolDefine(define): if env[define]: defenv.Append(NSIS_CPPDEFINES = [define]) def AddStringDefine(define): defenv.Append(NSIS_CPPDEFINES = [(define, '"%s"' % env[define])]) AddValuedDefine('NSIS_MAX_STRLEN') AddValuedDefine('NSIS_MAX_INST_TYPES') AddValuedDefine('NSIS_DEFAULT_LANG') AddBoolDefine('NSIS_CONFIG_UNINSTALL_SUPPORT') AddBoolDefine('NSIS_CONFIG_LICENSEPAGE') AddBoolDefine('NSIS_CONFIG_COMPONENTPAGE') AddBoolDefine('NSIS_CONFIG_COMPONENTPAGE_ALTERNATIVE') AddBoolDefine('NSIS_CONFIG_SILENT_SUPPORT') AddBoolDefine('NSIS_CONFIG_VISIBLE_SUPPORT') AddBoolDefine('NSIS_CONFIG_ENHANCEDUI_SUPPORT') AddBoolDefine('NSIS_CONFIG_COMPRESSION_SUPPORT') AddBoolDefine('NSIS_COMPRESS_BZIP2_SMALLMODE') AddValuedDefine('NSIS_COMPRESS_BZIP2_LEVEL') AddBoolDefine('NSIS_CONFIG_CRC_SUPPORT') AddBoolDefine('NSIS_CONFIG_CRC_ANAL') AddBoolDefine('NSIS_CONFIG_LOG') AddBoolDefine('NSIS_CONFIG_LOG_ODS') AddBoolDefine('NSIS_CONFIG_LOG_STDOUT') AddBoolDefine('NSIS_CONFIG_LOG_TIMESTAMP') AddBoolDefine('NSIS_SUPPORT_BGBG') AddBoolDefine('NSIS_SUPPORT_CODECALLBACKS') AddBoolDefine('NSIS_SUPPORT_MOVEONREBOOT') AddBoolDefine('NSIS_SUPPORT_ACTIVEXREG') AddBoolDefine('NSIS_SUPPORT_INTOPTS') AddBoolDefine('NSIS_SUPPORT_STROPTS') AddBoolDefine('NSIS_SUPPORT_STACK') AddBoolDefine('NSIS_SUPPORT_FILEFUNCTIONS') AddBoolDefine('NSIS_SUPPORT_FINDFIRST') AddBoolDefine('NSIS_SUPPORT_CREATESHORTCUT') AddBoolDefine('NSIS_SUPPORT_INIFILES') AddBoolDefine('NSIS_SUPPORT_REGISTRYFUNCTIONS') AddBoolDefine('NSIS_SUPPORT_COPYFILES') AddBoolDefine('NSIS_SUPPORT_REBOOT') AddBoolDefine('NSIS_SUPPORT_FNUTIL') AddBoolDefine('NSIS_SUPPORT_EXECUTE') AddBoolDefine('NSIS_SUPPORT_SHELLEXECUTE') AddBoolDefine('NSIS_SUPPORT_GETDLLVERSION') AddBoolDefine('NSIS_SUPPORT_GETFILETIME') AddBoolDefine('NSIS_SUPPORT_GETFONTVERSION') AddBoolDefine('NSIS_SUPPORT_GETFONTNAME') AddBoolDefine('NSIS_SUPPORT_HWNDS') AddBoolDefine('NSIS_SUPPORT_ENVIRONMENT') AddBoolDefine('NSIS_SUPPORT_RMDIR') AddBoolDefine('NSIS_SUPPORT_FILE') AddBoolDefine('NSIS_SUPPORT_DELETE') AddBoolDefine('NSIS_SUPPORT_RENAME') AddBoolDefine('NSIS_SUPPORT_MESSAGEBOX') AddBoolDefine('NSIS_SUPPORT_VERSION_INFO') AddBoolDefine('NSIS_FIX_DEFINES_IN_STRINGS') AddBoolDefine('NSIS_SUPPORT_STANDARD_PREDEFINES') AddBoolDefine('NSIS_LOCKWINDOW_SUPPORT') AddBoolDefine('NSIS_CONFIG_PLUGIN_SUPPORT') AddBoolDefine('NSIS_FIX_COMMENT_HANDLING') AddBoolDefine('NSIS_CONFIG_CONST_DATA_PATH') AddStringDefine('NSIS_VARS_SECTION')
slander = { "william": "https://giphy.com/gifs/memecandy-WTcj5b17IZ8xbdCMBs\nFucking lorte baby idiot, gå tilbage til 2017 da du blev født", "emil": "https://chinesepeopledoyoustyle.files.wordpress.com/2013/08/wpid-2013-08-29-08-13-47.png\nEmil be like: 目上長通済代日慮苦真", "noah": "https://media0.giphy.com/media/YFFNfFmlYRT6pcU7X8/giphy.gif\nIrske lorte neger trold fra Dublin", "asger": "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTN1DBCKv_2swhQ2XPikUasfR63zMwfE1-X5w&usqp=CAU\nAsger, more like asberger, fordi han er en autistisk 11 årig københavner LEL", "mads": "https://bt.bmcdn.dk/media/cache/resolve/image_1240/image/1/12215/9145576-freelance.jpg\nLeaked billede af den mentalt retarderede svineavler Mads Andreasen", "simon": "https://cdn.discordapp.com/attachments/799253856114442241/811227126740156476/unknown.png\n<@306033643564957696> this you? Dværge neger", "peter": "https://volunteerhq.galaxydigital.com/content/volunteerhq.galaxydigital.com/agency/84293-1919235-a73cad3c_f.jpg\nDette er en fisker med Down's Syndrom. Hans navn er Peter Christian Hildebrand Christensen, han er så kristen det står 2 gange i hans navn", "jeppe": "https://i.kym-cdn.com/entries/icons/facebook/000/029/959/Screen_Shot_2019-06-05_at_1.26.32_PM.jpg\nJeppe når hans aktier går op\nhttps://1648o73kablq2rveyn64glm1-wpengine.netdna-ssl.com/wp-content/uploads/2016/03/bigstock-portrait-of-young-angry-man-52068682.jpg\nJeppe når hans aktier går ned", "frederik": "haha hul mellem tænderne stor!!!" }
def search(text, pat): n = len(text) m = len(pat) skip = 0 right = {} for c in text: right[c] = -1 for j in range(0, m): right[pat[j]] = j i = 0 while i < n-m: skip = 0 for j in range(m-1, 0, -1): if pat[j] != text[i+j]: skip = max(1, j - right[text[i+j]]) break if skip == 0: return i i += skip return n
class PhysicsForce : class PhysicsGG : pass def W(self, Force, Distance) : usaha = Force * Distance return usaha class PhysicsRotation : def W(self, frequency) : omega = 2 * 3.15 * frequency return omega Rinta = PhysicsForce() Usaha = Rinta.W(3,2) print(Usaha) Marsa = PhysicsRotation() Omega = Marsa.W(4) print(Omega) # class Parrot: # def fly(self): # print("Parrot can fly") # def swim(self): # print("Parrot can't swim") # class Penguin: # def fly(self): # print("Penguin can't fly") # def swim(self): # print("Penguin can swim") # # common interface # def flying_test(bird): # bird.fly() # #instantiate objects # blu = Parrot() # peggy = Penguin() # # passing the object # flying_test(blu) # flying_test(peggy)
# gmail credentials gmail = dict( username='username', password='password' ) # number of centimeters considered to be acceptable trigger_distance = 10 # number of seconds spent below trigger distance before sending email alert_after = 20
def is_palindrome_permutation(string): char_set = [0] * 26 total_letter = 0 total_odd = 0 for char in string: if char >= 'A' and char <= 'Z': index = ord(char) + ord('A') elif char >= 'a' and char <= 'z': index = ord(char)-ord('a') if char is not ' ': total_letter += 1 char_set[index] += 1 if total_letter % 2 == 0: for i in range(26): if char_set[index] % 2: return False elif total_letter % 2 == 1: for i in range(26): if char_set[i] % 2 == 1: total_odd += 1 if total_odd > 1: return False return True print(is_palindrome_permutation('sskdfjs')) print(is_palindrome_permutation('sas')) print(is_palindrome_permutation('ssaa'))
class StockError(Exception): def __init__(self, message) -> None: module_name = self.__class__.__module__ class_name = self.__class__.__name__ error_msg = f'{message} ({module_name}.{class_name})' super().__init__(error_msg) class InvalidHttpsReqError(StockError): """ This error is raised when HTTPS request is failed. """ def __init__(self, message) -> None: super().__init__(message) class InvalidQuarterError(StockError): """ This error is raised when given quarter is out of range. """ def __init__(self, message) -> None: super().__init__(message) class InvalidFileError(StockError): """ This error is raised when the file is not exist or is not a file. """ def __init__(self, message) -> None: super().__init__(message) class StockDataKeyError(StockError): """ This error is raised when accessing the daily stock data with invalid key. The valid keys in the daily stock data are: {"date":, "trading_vol":, "turnover": "opening":, "hi":, "lo":, "closing":, "transactions":} """ def __init__(self, message) -> None: valid_keys_msg = " The valid keys are - \"date\", \"trading_vol\", " \ "\"turnover\", \"opening\", \"hi\", \"lo\", \"closing\", " \ "\"transactions\"" super().__init__(message + valid_keys_msg)
a = 1 b = 2 def index(): return 'hello world' def hello(): return 'hello 2018' def detail(): return 'detail info' c = 3 d = 4
class TrackingMode(object): PRINTING, LOGGING = range(0, 2) TRACKING = True TRACKING_MODE = TrackingMode.PRINTING class TimyConfig(object): DEFAULT_IDENT = 'Timy' def __init__(self, tracking=TRACKING, tracking_mode=TRACKING_MODE): self.tracking = tracking self.tracking_mode = tracking_mode timy_config = TimyConfig()
print("""\nInformación de utilidad:\n Cámara de retina, 40 minutos Código de acceso, 50 minutos Palabra clave, 30 minutos Código de acceso complejo, 70 minutos Puerta sin bloqueo, 0 minutos Zona 1: 3 cámaras retina, 1 palabra clave Zona 2: 2 puerta sin bloqueo, 5 código de acceso Zona 3: 3 puertas sin bloqueo, 1 cámara de retina Zona 4: 2 código de acceso, 4 palabra clave """)
# two float values val1 = 100.99 val2 = 76.15 # Adding the two given numbers sum = float(val1) + float(val2) # Displaying the addition result print("The sum of given numbers is: ", sum)
with open("dane/dane.txt") as f: lines = [] for line in f: sline = line.strip() lines.append(sline) count = 0 for line in lines: if line[0] == line[-1]: count += 1 print(f"{count=}")
def decode_orientation(n_classes, train_data, train_labels, test_data, test_labels): """ Initialize, train, and test deep network to decode binned orientation from neural responses Args: n_classes (scalar): number of classes in which to bin orientation train_data (torch.Tensor): n_train x n_neurons tensor with neural responses to train on train_labels (torch.Tensor): n_train x 1 tensor with orientations of the stimuli corresponding to each row of train_data, in radians test_data (torch.Tensor): n_test x n_neurons tensor with neural responses to train on test_labels (torch.Tensor): n_test x 1 tensor with orientations of the stimuli corresponding to each row of train_data, in radians Returns: (list, torch.Tensor): training loss over iterations, n_test x 1 tensor with predicted orientations of the stimuli from decoding neural network """ # Bin stimulus orientations in training set train_binned_labels = stimulus_class(train_labels, n_classes) # Initialize network net = DeepNetSoftmax(n_neurons, 20, n_classes) # use M=20 hidden units # Initialize built-in PyTorch MSE loss function loss_fn = nn.NLLLoss() # Run GD on training set data, using learning rate of 0.1 train_loss = train(net, loss_fn, train_data, train_binned_labels, learning_rate=0.1) # Decode neural responses in testing set data out = net(resp_test) out_labels = np.argmax(out.detach(), axis=1) # predicted classes return train_loss, out_labels # Set random seeds for reproducibility np.random.seed(1) torch.manual_seed(1) n_classes = 12 # start with 12, then (bonus) try making this as big as possible! does decoding get worse? # Initialize, train, and test network train_loss, predicted_test_labels = decode_orientation(n_classes, resp_train, stimuli_train, resp_test, stimuli_test) # Plot results with plt.xkcd(): plot_decoded_results(train_loss, stimuli_test, predicted_test_labels)
class Customer: def __init__(self, client): self.client = client self.logger = client.logger self.endpoint_base = '/data/v2/projects/{}/customers'.format(client.project_token) def get_customer(self, ids): path = '{}/export-one'.format(self.endpoint_base) payload = {'customer_ids': ids} response = self.client.post(path, payload) if response is None: return None return { 'ids': response['ids'], 'properties': response['properties'], 'events': response['events'] } def get_customer_consents(self, ids, consents): path = '{}/attributes'.format(self.endpoint_base) payload = {'customer_ids': ids, 'attributes': [{'type': 'consent', 'category': consent_type} for consent_type in consents]} response = self.client.post(path, payload) if response is None: return None result = {} for index, consent_type in enumerate(consents): # Check if user has permission to request data_type if not response['results'][index]['success']: self.logger.warning('No permission to retrieve consent {}'.format(consent_type)) result[consent_type] = None continue result[consent_type] = response['results'][index]['value'] return result def get_customer_attributes(self, customer_ids, properties=[], segmentations=[], ids=[], expressions=[], aggregations=[], predictions=[]): path = '{}/attributes'.format(self.endpoint_base) payload = { 'customer_ids': customer_ids, 'attributes': [{'type': 'property', 'property': customer_property} for customer_property in properties] + [{'type': 'segmentation', 'id': segmentation} for segmentation in segmentations] + [{'type': 'id', 'id': _id} for _id in ids] + [{'type': 'expression', 'id': expression} for expression in expressions] + [{'type': 'aggregate', 'id': aggregate} for aggregate in aggregations] + [{'type': 'prediction', 'id': prediction} for prediction in predictions] } response = self.client.post(path, payload) if response is None: return None result = {} attributes_retrieved = 0 for attribute_type in [('properties', properties), ('segmentations', segmentations), ('ids', ids), ('expressions', expressions), ('aggregations', aggregations), ('predictions', predictions)]: attribute_type_name = attribute_type[0] attribute_type_ids = attribute_type[1] if len(attribute_type_ids) == 0: continue result[attribute_type_name] = {} for _id in attribute_type_ids: # Check if user has permission to request attribute_type if not response['results'][attributes_retrieved]['success']: self.logger.warning('No permission to retrieve %s %s', attribute_type_name, _id) result[attribute_type_name][_id] = None attributes_retrieved += 1 continue result[attribute_type_name][_id] = response['results'][attributes_retrieved]['value'] attributes_retrieved += 1 return result def get_customers(self): path = '{}/export'.format(self.endpoint_base) payload = {'format': 'native_json'} response = self.client.post(path, payload) if response is None: return None users = [] ids = [field['id'] for field in filter(lambda x: x['type'] == 'id', response['fields'])] properties = [field['property'] for field in filter(lambda x: x['type'] == 'property', response['fields'])] for row in response['data']: user = {'ids': {}, 'properties': {}} for index, attribute in enumerate(row): if index < len(ids): user['ids'][ids[index]] = attribute else: user['properties'][properties[index - len(ids)]] = attribute users.append(user) return users def get_events(self, customer_ids, event_types): path = '{}/events'.format(self.endpoint_base) payload = {'customer_ids': customer_ids, 'event_types': event_types} response = self.client.post(path, payload) return None if response is None else response['data'] def anonymize_customer(self, customer_ids): path = '{}/anonymize'.format(self.endpoint_base) payload = {'customer_ids': customer_ids} response = self.client.post(path, payload) return None if response is None else response['success']
__author__ = 'wektor' class GenericBackend(object): def set(self, key, value): raise NotImplemented def get(self, key): raise NotImplemented def delete(self, key): raise NotImplemented
#!/usr/bin/env python """ generated source for module MetaGamingException """ # package: org.ggp.base.player.gamer.exception @SuppressWarnings("serial") class MetaGamingException(Exception): """ generated source for class MetaGamingException """ def __init__(self, cause): """ generated source for method __init__ """ super(MetaGamingException, self).__init__(cause) def __str__(self): """ generated source for method toString """ return "An unhandled exception occurred during metagaming: " + super(MetaGamingException, self).__str__()
# # PySNMP MIB module H3C-UNICAST-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/H3C-UNICAST-MIB # Produced by pysmi-0.3.4 at Wed May 1 13:24:11 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") ValueSizeConstraint, ConstraintsUnion, SingleValueConstraint, ConstraintsIntersection, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "ConstraintsUnion", "SingleValueConstraint", "ConstraintsIntersection", "ValueRangeConstraint") h3cCommon, = mibBuilder.importSymbols("HUAWEI-3COM-OID-MIB", "h3cCommon") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") Counter32, Integer32, iso, TimeTicks, NotificationType, Unsigned32, MibScalar, MibTable, MibTableRow, MibTableColumn, MibIdentifier, ObjectIdentity, Bits, ModuleIdentity, IpAddress, Gauge32, Counter64 = mibBuilder.importSymbols("SNMPv2-SMI", "Counter32", "Integer32", "iso", "TimeTicks", "NotificationType", "Unsigned32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "MibIdentifier", "ObjectIdentity", "Bits", "ModuleIdentity", "IpAddress", "Gauge32", "Counter64") TextualConvention, DisplayString, TruthValue = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString", "TruthValue") h3cUnicast = ModuleIdentity((1, 3, 6, 1, 4, 1, 2011, 10, 2, 44)) h3cUnicast.setRevisions(('2005-03-24 14:54',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: h3cUnicast.setRevisionsDescriptions((' Revisions made by Hangzhou MIB team.',)) if mibBuilder.loadTexts: h3cUnicast.setLastUpdated('200501311454Z') if mibBuilder.loadTexts: h3cUnicast.setOrganization('Huawei 3com Technologies Co.,Ltd') if mibBuilder.loadTexts: h3cUnicast.setContactInfo('Platform Team Hangzhou Institute Huawei-3Com Tech, Inc.') if mibBuilder.loadTexts: h3cUnicast.setDescription(' This MIB is a framework MIB for unicast related features.') h3cURPFTable = MibTable((1, 3, 6, 1, 4, 1, 2011, 10, 2, 44, 1), ) if mibBuilder.loadTexts: h3cURPFTable.setStatus('current') if mibBuilder.loadTexts: h3cURPFTable.setDescription(' Unicast Reverse Path Forwarding (URPF) is used to prevent the network attacks caused by source address spoofing. This table is used to configure URPF on specific interfaces.') h3cURPFEntry = MibTableRow((1, 3, 6, 1, 4, 1, 2011, 10, 2, 44, 1, 1), ).setIndexNames((0, "H3C-UNICAST-MIB", "h3cURPFIfIndex")) if mibBuilder.loadTexts: h3cURPFEntry.setStatus('current') if mibBuilder.loadTexts: h3cURPFEntry.setDescription(' The entry of h3cURPFTable, indexed by vlan interface index.') h3cURPFIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 10, 2, 44, 1, 1, 1), Integer32()) if mibBuilder.loadTexts: h3cURPFIfIndex.setStatus('current') if mibBuilder.loadTexts: h3cURPFIfIndex.setDescription(' The ifIndex of vlan interface.') h3cURPFEnabled = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 10, 2, 44, 1, 1, 2), TruthValue().clone('false')).setMaxAccess("readwrite") if mibBuilder.loadTexts: h3cURPFEnabled.setStatus('current') if mibBuilder.loadTexts: h3cURPFEnabled.setDescription(' This object is used to enable or disable URPF on certain vlan interfaces.') h3cURPFSlotID = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 10, 2, 44, 1, 1, 3), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: h3cURPFSlotID.setStatus('current') if mibBuilder.loadTexts: h3cURPFSlotID.setDescription(' This object specifies to which slot packets are redirected in order to perform URPF check.') h3cURPFTotalReceivedPacket = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 10, 2, 44, 1, 1, 4), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: h3cURPFTotalReceivedPacket.setStatus('current') if mibBuilder.loadTexts: h3cURPFTotalReceivedPacket.setDescription(' This object provides total received packets number.') h3cURPFDroppedPacket = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 10, 2, 44, 1, 1, 5), Counter64()).setMaxAccess("readonly") if mibBuilder.loadTexts: h3cURPFDroppedPacket.setStatus('current') if mibBuilder.loadTexts: h3cURPFDroppedPacket.setDescription(' This object provides total dropped invalid packets number.') h3cURPFClearStat = MibTableColumn((1, 3, 6, 1, 4, 1, 2011, 10, 2, 44, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("reserved", 0), ("reset", 1)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: h3cURPFClearStat.setStatus('current') if mibBuilder.loadTexts: h3cURPFClearStat.setDescription(' This object is used to clear the URPF statistics on certain vlan interfaces. This object is actually a write-only object. When read, it always returns 0. When set to 1, the objects h3cURPFTotalReceivedPacket and h3cURPFDroppedPacket are reset to 0.') mibBuilder.exportSymbols("H3C-UNICAST-MIB", h3cURPFSlotID=h3cURPFSlotID, h3cURPFEnabled=h3cURPFEnabled, h3cURPFClearStat=h3cURPFClearStat, h3cURPFTable=h3cURPFTable, h3cURPFEntry=h3cURPFEntry, h3cURPFTotalReceivedPacket=h3cURPFTotalReceivedPacket, h3cUnicast=h3cUnicast, h3cURPFIfIndex=h3cURPFIfIndex, h3cURPFDroppedPacket=h3cURPFDroppedPacket, PYSNMP_MODULE_ID=h3cUnicast)
# Andrew Ratkov 11-1 15.10.2021 words ans_1a = '''Поскольку в слове ВАРЕНЬЕ 7 букв и больше слов на букву В нет, то Петя, написав первым ходом В, заведомо выйграет, так как в слове ВАРЕНЬЕ 7 (нечётное количество) букв и Вася и Петя теперь будут его дописывать. При этой стратегии может быть сыграна только одна возможная партия - выписывание слова ВАРЕНЬЕ''' ans_1b = '''В слове НУБНУБ...НУБ 55 * 3 = 165 символов, в слове PUMAPUMA...PUMA 4 * 32 = 128 слов. Стратегия для Пети - первым ходом написать Н. Тогда слово PUMAPUMA...PUMA точно не будет выписано, а значит игроки будут дописывать слово НУБНУБ...НУБ. Поскольку в этом слове нечётное число букв, а начинал Петя, то и закончит Петя и выйграет Петя. При этой стратегии может быть сыграна только одна возможная партия - выписывание слова НУБНУБ...НУБ''' ans_2 = '''Поменяем в слове КОРОВА первую и пятую буквы местами, получим ВОРОКА. Получается, в начале даны 2 слова - ВАРЕНЬЕ и ВОРОКА и Петя должен написать букву В. Тогда останутся слова АРЕНЬЕ и ОРОКА, одно из них игроки должны написать. Стратегия Васи - написать букву О. Тогда единственное слово, которое в итоге смогут дописать Петя и Вася - ВОРОКА, при этом ВО уже написано. Осталось написать чётное число символов, продолжает Петя, а значит Вася выйграет.''' ans_3 = '''У Васи есть стратегия: П В П В П В М -> О -> Р -> С П -> Л -> А -> Т -> Ь -> Е \-> О -> М -> Б -> А ''' def winner_predicter(set_of_words): assert(len(set_of_words) > 0) all_lengths_are_even = True for word in set_of_words: if len(word) == 1: return "Petya" if len(word) % 2 == 1: all_lengths_are_even = False if all_lengths_are_even: return "Vasya" D = dict() for word in set_of_words: if word[0] not in D: D[word[0]] = set() D[word[0]].add(word[1:]) for first_symbol in D: if winner_predicter(D[first_symbol]) == "Vasya": return "Petya" return "Vasya" def solve(set_of_words): print("Если начальный набор слов:", set_of_words, ",\nто победит", winner_predicter(set_of_words)) if __name__ == '__main__': print("Формальный письменный ответ на вопросы задачи:") print("1A:", ans_1a, "1Б:", ans_1b, "2:", ans_2, "3:", ans_3, sep='\n') set1 = set(["ANDREW", "Z"]) set2 = set(["ВАРЕНЬЕ", "КОРОВА"]) set3 = set(["ВАРЕНЬЕ", "ВОРОКА"]) set4 = set(["НУБ" * 55, "PUMA" * 32]) set5 = set(["МОРОКА", "МОРС", "МОРОЗ", "ПЛАХА", "ПЛАТЬЕ", "ПЛОМБА"]) print("Сама программа по предсказыванию победителя начинает работать тут") solve(set5)
""" Il modulo module2 è caricato da subpackage """ def myMethod(*args,**kwargs): """ myMethod(*args,lang=en,newline=False) -- stampa un messaggio di saluto ad args in inglese e senza andare a capo dopo ogni saluto. lang=it saluta in italiano newline=True va a acapo dopo ogni saluto """ # valori di defalut degli argomenti saluto = 'Hello' separatore = ', ' result = '' try: if len(kwargs) >2: raise SyntaxError('Invalid arguments') else: for k in kwargs.keys(): if k not in {'lang','newline'}: raise SyntaxError('Invalid arguments') elif k == 'lang': if kwargs[k] == 'it': saluto = 'Ciao' elif k == 'newline': if kwargs[k] == True: separatore = '\n' elif (k == 'lang' and kwargs[k] != 'en') or (k == 'newline' and kwargs[k] != False): raise SyntaxError('Invalid arguments') except SyntaxError: return None raise else: for people in args: if args.index(people) == len(args) -1: result += f'{saluto} {people}! \n' else: result += f'{saluto} {people}! {separatore}' return result
''' nums: [2, 3, -2, 4] max: [2, 6, -2, 4] min: [2, 3, -12, -48] max: [2, 6, 6, 6] '''
# # @lc app=leetcode id=476 lang=python3 # # [476] Number Complement # # https://leetcode.com/problems/number-complement/description/ # # algorithms # Easy (62.87%) # Likes: 625 # Dislikes: 76 # Total Accepted: 120.1K # Total Submissions: 190.7K # Testcase Example: '5' # # Given a positive integer, output its complement number. The complement # strategy is to flip the bits of its binary representation. # # Note: # # The given integer is guaranteed to fit within the range of a 32-bit signed # integer. # You could assume no leading zero bit in the integer’s binary # representation. # # # # Example 1: # # Input: 5 # Output: 2 # Explanation: The binary representation of 5 is 101 (no leading zero bits), # and its complement is 010. So you need to output 2. # # # # Example 2: # # Input: 1 # Output: 0 # Explanation: The binary representation of 1 is 1 (no leading zero bits), and # its complement is 0. So you need to output 0. # # # # @lc code=start class Solution: def findComplement(self, num: int) -> int: nbit = len(bin(num)[2:]) return ((1<<nbit)-1)^num # @lc code=end
"""def ejercicio1(): cadena = input("Ingrese una cadena: ") abc = " abcdefghijklmnopqrstuvwxyz" listaLetras = [] almacen = [] if len(cadena) > 0: for i in cadena: if i in abc: listaLetras.append(i) cadenanueva = "".join(listaLetras) cadena = cadenanueva else: cadena = input("Ingrese una nueva cadena: ") print(cadena) ejercicio1()""" def ejercicio2(cadena): cadenaAlReves = cadena[::-1] listacadena = cadena.split(" ") listaalreves = cadenaAlReves.split(" ") almacen = [] almacen2 = [] almacen3 = [] for i in listacadena: almacen.append(i) for a in listaalreves: if a in almacen: almacen2.append(a) else: almacen3.append(a) if almacen2 == []: almacen2.append("No hay palindromos en la cadena") else: return almacen2 funcionario = ["German Alvarez","Valeria Lorenzo", "Camila Alvarez", "Jose Perez"] dicc = {} dicc["19951115"] = [funcionario[0],funcionario[3]] dicc["19970724"] = [funcionario[1]] dicc["19970309"] = [funcionario[2]] class Empleado: def __init__(self,nombre,apellido,ci,domicilio,nacimiento): self.nombre = nombre self.apellido = apellido self.ci = ci self.domicilio = domicilio self.nacimiento = nacimiento def fecha(self,nacimiento): año = int(nacimiento[0:4]) mes = int(nacimiento[4:6]) dia = int(nacimiento[6:8]) if (((año >= 1900) and (año <= 2017)) and ((mes >= 1) and (mes <= 12)) and ((dia >=1) and (dia <= 30))): print("Fecha correcta") else: print("Fecha incorrecta") def verificaCi(self,cedula): nros = "0123456789" listaCedula = [] contador = 0 for i in cedula: listaCedula.append(i) listaComprension = [a for a in listaCedula if a not in nros] if len(listaComprension) >= 1: print("Por favor solo numeros") else: print("CI correcta") def __repr__(self): return '(%s, %s, %s, %s, %s)' %(self.nombre,self.apellido,self.ci,self.domicilio,self.nacimiento) def nuevo(self,cedulanuevo): self.ci = cedulanuevo def cumple(self,fecha): funcionario = ["German Alvarez","Valeria Lorenzo", "Camila Alvarez", "Jose Perez"] dicc = {} dicc["19951115"] = [funcionario[0],funcionario[3]] dicc["19970724"] = [funcionario[1]] dicc["19970309"] = [funcionario[2]] for a in dicc: print(a) if a in dicc: return dicc[a] ##Funcion que permite verificar si la fecha es valida """funcionario = Empleado("German","Alvarez","4727623-0","carlos nery","19951115").fecha("4727623-0")""" ##Funcion que permite verificar si la cedula se ingreso correctamente """funcionario = Empleado("German","alvarez","4727623-0","carlos nery","19951115").verificaCi("4727623-0")""" ##Funcion que permite verificar si la cedula se ingreso correctamente funcionario = Empleado("German","Alvarez","4727623-0","carlos nery","19951115").cumple("19951115")
def gmt2json(pathx,hasDescColumn=True,isFuzzy=False): wordsAll = [] # secondColumn = [] with open(pathx,'r') as gf: for line in gf: line = line.strip('\r\n\t') # if not a empty line if line: words = [] i = 0 for item in line.split('\t'): if i==0: words.append(item) else: # a gene symbol cannot be a string of numbers. if item!="" and not isNumStr(item): words.append(item) wordsAll.append(words) # secondColumn.append(words[1]) gmtName = getfilename(pathx) print(gmtName) gmt = [] if not isFuzzy and hasDescColumn: for words in wordsAll: gmt.append({'gmt':gmtName,'desc':words[1], 'term':words[0],'items':words[2:]}) return gmt def getBaseDir(): currentPath = os.getcwd() while currentPath != '/': if os.path.isdir(currentPath+'/.git'): break currentPath = getParDir(currentPath) if currentPath == '/': raise Exception('Base dir not found because .git directory is not present') return currentPath
class Coordinates: """ Geo location coordinates. Reference: https://developer.twitter.com/en/docs/tweets/data-dictionary/overview/geo-objects#coordinates """ def __init__(self, data: dict = {}): if not data: return None self.coordinates = data.get('coordinates') self.type = data.get('type') class BoundingBox: """ Describes an area by coordinates. Reference: https://developer.twitter.com/en/docs/tweets/data-dictionary/overview/geo-objects#bounding-box """ def __init__(self, data: dict = {}): if not data: return None self.coordinates = [Coordinates(c) for c in data.get('coordinates')] self.type = data.get('type') class Place: """ A specific, named geo location place with defined area coordinates. Reference: https://developer.twitter.com/en/docs/tweets/data-dictionary/overview/geo-objects#place """ def __init__(self, data: dict = {}): if not data: return None self.id = data.get('id') self.url = data.get('url') self.place_type = data.get('place_type') self.name = data.get('name') self.full_name = data.get('full_name') self.country_code = data.get('country_code') self.country = data.get('country') self.bounding_box = BoundingBox(data.get('bounding_box')) if 'bounding_box' in data else None self.attributes = data.get('attributes')
#!/usr/bin/env python3 # https://codeforces.com/problemset/problem/761/A # 题目是interal, 不一定是从1开始, 所以之前做错了; 但还是很无聊的题目 # 0 0 不可能, 错第二次 def f(l): a,b = l return (b==a+1 or b==a or b==a-1) and (a+b>0) l = list(map(int,input().split())) print('YES' if f(l) else 'NO')
OCM_SIZE = 2 ** 8 READ_MODE = 0 WRITE_MODE = 1 DATA_BITWIDTH = 32 WORD_SIZE = DATA_BITWIDTH / 8 instream = CoramInStream(0, datawidth=DATA_BITWIDTH, size=64) outstream = CoramOutStream(0, datawidth=DATA_BITWIDTH, size=64) channel = CoramChannel(idx=0, datawidth=32) DOWN_LEFT = 0 DOWN_PARENT = 1 DOWN_RIGHT = 2 UP_PARENT = 1 UP_CHILD = 0 offset = 0 num_entries = 0 def downheap(): if num_entries == 0: return if num_entries + 1 >= OCM_SIZE: instream.write_nonblocking(offset + num_entries * WORD_SIZE + WORD_SIZE, 1) index = 1 while True: if index * 2 > num_entries: outstream.read_nonblocking(index * WORD_SIZE + offset, 1) break if (index * 2) >= OCM_SIZE: instream.write_nonblocking(index * WORD_SIZE * 2 + offset, 2) elif (index * 2) + 1 >= OCM_SIZE: instream.write_nonblocking(index * WORD_SIZE * 2 + offset + WORD_SIZE, 1) select = channel.read() outstream.read_nonblocking(index * WORD_SIZE + offset, 1) if select == DOWN_LEFT: index = index * 2 elif select == DOWN_RIGHT: index = index * 2 + 1 else: break def upheap(): index = num_entries while index > 1: if (index / 2) >= OCM_SIZE: instream.write_nonblocking((index / 2) * WORD_SIZE + offset, 1) select = channel.read() outstream.read_nonblocking(index * WORD_SIZE + offset, 1) index = index / 2 if select == UP_PARENT: break outstream.read_nonblocking(index * WORD_SIZE + offset, 1) def heap(): global num_entries mode = channel.read() if mode == 1: num_entries -= 1 downheap() else: num_entries += 1 upheap() while True: heap()
''' Endpoints are collected from the Market Data Endpoints api section under the official binance api docs: https://binance-docs.github.io/apidocs/spot/en/#market-data-endpoints ''' # Test Connectivity: class test_ping: params = None method = 'GET' endpoint = '/api/v3/ping' security_type = 'None' # Check Server Time: class get_serverTime: params = None method = 'GET' endpoint = '/api/v3/time' security_type = 'None' # Exchange Information: class get_exchangeInfo: params = None method = 'GET' endpoint = '/api/v3/exchangeInfo' security_type = 'None' # Order Book: class get_orderBook: params = {'R':['symbol'], 'O':['limit']} method = 'GET' endpoint = '/api/v3/depth' security_type = 'None' # Recent Trades List: class get_recentTrades: params = {'R':['symbol'], 'O':['limit']} method = 'GET' endpoint = '/api/v3/trades' security_type = 'None' # Old Trade Lookup: class get_oldTrades: params = {'R':['symbol'], 'O':['limit', 'fromId']} method = 'GET' endpoint = '/api/v3/historicalTrades' security_type = 'None' # Compressed/Aggregate Trades List: class get_aggTradeList: params = {'R':['symbol'], 'O':['limit', 'fromId', 'startTime', 'endTime', 'limit']} method = 'GET' endpoint = '/api/v3/aggTrades' security_type = 'None' # Kline/Candlestick Data: class get_candles: params = {'R':['symbol', 'interval'], 'O':['startTime', 'endTime', 'limit']} method = 'GET' endpoint = '/api/v3/klines' security_type = 'None' # Current Average Price: class get_averagePrice: params = {'R':['symbol']} method = 'GET' endpoint = '/api/v3/avgPrice' security_type = 'None' # 24hr Ticker Price Change Statistics: class get_24hTicker: params = {'O':['symbol']} method = 'GET' endpoint = '/api/v3/ticker/24hr' security_type = 'None' # Symbol Price Ticker: class get_priceTicker: params = {'O':['symbol']} method = 'GET' endpoint = '/api/v3/ticker/price' security_type = 'None' # Symbol Order Book Ticker: class get_orderbookTicker: params = {'O':['symbol']} method = 'GET' endpoint = '/api/v3/ticker/bookTicker' security_type = 'None'
## Oscillating Lambda Man ## ## Directions: ### 0: top ### 1: right ### 2: bottom ### 3: left def main(world, _ghosts): return (strategy_state(), step) def step(state, world): return (update_state(state), deduce_direction(state, world)) # Oscilation strategy state def strategy_state(): #returns (frequency, count) return (4, 0) # Increase count in oscilation def update_state(state): return (state[0], state[1:]+1) # Deduce direction based on oscillation parameter def deduce_direction(state, _world): # if self.cnt % (2 * self.frequency) < self.frequency: if state[0] > modulo(state[1:], (2 * state[0])): return 3 else: return 1 # x % y def modulo(x, y): return ( x - ( y * (x / y) ) )
url= 'http://ww.sougou.com/s?' def sougou(nets): count = 1 for net in nets: rest1 = 'res%d.txt' %count with open(rest1,'w',encoding='utf8') as f: f.write(net) print(net) count +=1 if __name__ == '__main__': nets = ('one','two','pr') sougou(nets)
class Task: def name(): raise NotImplementedError def description(): raise NotImplementedError def inputs(): raise NotImplementedError def run(inputs): raise NotImplementedError
# -------------- # Code starts here class_1 = ['Geoffrey Hinton','Andrew Ng','Sebastian Raschka','Yoshua Bengio'] class_2 = ['Hilary Mason','Carla Gentry','Corinna Cortes'] new_class = class_1 + class_2 print(new_class) new_class.append('Peter Warden') print(new_class) new_class.remove('Carla Gentry') print(new_class) # Code ends here # -------------- # Code starts here courses= {'Math':65,'English':70,'History':80,'French':70,'Science':60} total = courses['Math']+courses['English']+courses['History']+courses['French']+courses['Science'] print(total) percentage = (total/500)*100 print(percentage) # Code ends here # -------------- # Code starts here mathematics = { 'Geoffrey Hinton':78, 'Andrew Ng':95, 'Sebastian Raschka':65, 'Yoshua Benjio':50, 'Hilary Mason':70, 'Corinna Cortes':66, 'Peter Warden':75 } topper = max(mathematics,key=mathematics.get) print(topper) # Code ends here # -------------- # Given string topper = 'andrew ng' first_name,last_name= topper.split(" ") full_name = last_name+" "+first_name # Code starts here certificate_name= full_name.upper() print(certificate_name) # Code ends here
""" Enunciado Pegue a lista gerada no exercício anterior e transforme cada um dos itens dessa lista em um float. OBS: Não é para alterar o programa anterior, mas sim a lista gerada por ele. """ lista = ['1','5','2','3','6'] lista2 = [] for c in lista: lista2.append(float(c)) print(lista2)
#Updating menu to include a save option students= [] def displayMenu(): print("what would you like to do?") print("\t(a) Add new student") print("\t(v) View students") print("\t(s) Save students") print("\t(q) Quit") choice = input("type one letter (a/v/s/q):").strip() return choice def doAdd(): # you have code here to add print("in adding") def doView(): # you have code here to view print("in viewing") def doSave(): #you will put the call to save dict here print("in save") #main program choice = displayMenu() while(choice != 'q'): if choice == 'a': doAdd() elif choice == 'v': doView() elif choice == 's': doSave() elif choice !='q': print("\n\nPlease select either a,v,s or q") choice=displayMenu()
# You need the Elemental codex 1+ to cast "Haste" # You need unique hero to perform resetCooldown action # You need the Emperor's gloves to cast "Chain Lightning" hero.cast("haste", hero) hero.moveDown() hero.moveRight() hero.moveDown(0.5) enemy = hero.findNearestEnemy() hero.cast("chain-lightning", enemy) hero.resetCooldown("chain-lightning") hero.cast("chain-lightning", enemy)
""" Module: 'flashbdev' on esp32 3.0.0 """ # MCU: (sysname='esp32', nodename='esp32', release='3.0.0', version='v3.0.0 on 2020-01-29', machine='ESP32 module with ESP32') # Stubber: 1.3.2 class Partition: '' BOOT = 0 RUNNING = 1 TYPE_APP = 0 TYPE_DATA = 1 def find(): pass def get_next_update(): pass def info(): pass def ioctl(): pass def readblocks(): pass def set_boot(): pass def writeblocks(): pass bdev = None
''' Title : String Formatting Subdomain : Strings Domain : Python Author : codeperfectplus Created : 17 January 2020 ''' def print_formatted(number): # your code goes here width = len("{0:b}".format(n)) for i in range(1,n+1): print( "{0:{width}d} {0:{width}o} {0:{width}X} {0:{width}b}".format(i, width=width)) if __name__ == '__main__': n = int(input()) print_formatted(n) """ def print_formatted(number): # your code goes here for i in range(1, number+1): octa = oct(i)[2:] hexa = hex(i)[2:] bina = bin(i)[2:] print(f"{i} {octa} {hexa} {bina}") """
class FiniteAutomata: def __init__(self): Q = [] # finite set of states E = [] # finite alphabet D = {} # transition function q0 = '' # initial state F = [] # set of final states self.clear_values() def clear_values(self): self.Q = [] self.E = [] self.D = {} self.q0 = '' self.F = [] def read(self, file_name): with open(file_name) as file: line = file.readline().strip() while line != '': if line == 'Q': for state in file.readline().strip().split(' '): self.Q.append(state) if line == 'E': for state in file.readline().strip().split(' '): self.E.append(state) if line == 'D': line = file.readline() while line[0] == '(': trans_from_a, tras_from_b = line.strip().split('=')[0].replace('(', '').replace(')', '').split(',') trans_to = line.strip().split('=')[1] if (trans_from_a, tras_from_b) not in self.D.keys(): self.D[(trans_from_a, tras_from_b)] = trans_to else: self.D[(trans_from_a, tras_from_b)].append(trans_to) line = file.readline() if line == 'q0': self.q0 = file.readline() if line == 'F': for state in file.readline().strip().strip(' '): self.F.append(state) line = file.readline().strip() def checkDFA(self): for trans in self.D.values(): if len(trans) >= 2: return False return True def acceptedSequence(self, input_sequence): if self.checkDFA(): state = self.q0 for s in input_sequence: if (state, s) in self.D.keys(): state = self.D[(state, s)][0] else: return False if state in self.F: return True else: return False def getData(self): items = {} items['states'] = self.Q items['alphabet'] = self.E items['transitions'] = self.D items['final states'] = self.F return items
class Solution: """ @param n: an integer @return: the smallest 32-bit integer which has exactly the same digits existing in the integer n and is greater in value than n """ def nextGreaterElement(self, n): digits = [i for i in str(n)] digits.sort() res = self.dfs(digits, [], n) return res if res else -1 def dfs(self, digits, combi, n): if combi and int("".join(combi)) < n // 10 ** len(digits): return if not digits: res = int("".join(combi)) if res >= 2 ** 31: return -1 if res > n: return res return None for i in range(len(digits)): if i > 0 and digits[i] == digits[i - 1]: continue combi.append(digits[i]) res = self.dfs([digits[j] for j in range(len(digits)) if j != i], combi, n) if res: return res combi.pop()
tup=tuple(input("Enter the tuple").split(",")) st=tuple(input("Enter the another tuple").split(",")) tup1=tup+st print(tup1)
# -*- coding: utf-8 -*- # DATA STRUCTURES cats = [ {"name": "tom", "age": 1, "size": "small"}, {"name": "ash", "age": 2, "size": "medium"}, {"name": "hurley", "age": 5, "size": "large"}, ] print(cats)
# coding=utf-8 class JavaHeap: def __init__(self): pass
# Generated by h2py from /usr/include/netinet/in.h # Included from net/nh.h # Included from sys/machine.h LITTLE_ENDIAN = 1234 BIG_ENDIAN = 4321 PDP_ENDIAN = 3412 BYTE_ORDER = BIG_ENDIAN DEFAULT_GPR = 0xDEADBEEF MSR_EE = 0x8000 MSR_PR = 0x4000 MSR_FP = 0x2000 MSR_ME = 0x1000 MSR_FE = 0x0800 MSR_FE0 = 0x0800 MSR_SE = 0x0400 MSR_BE = 0x0200 MSR_IE = 0x0100 MSR_FE1 = 0x0100 MSR_AL = 0x0080 MSR_IP = 0x0040 MSR_IR = 0x0020 MSR_DR = 0x0010 MSR_PM = 0x0004 DEFAULT_MSR = (MSR_EE | MSR_ME | MSR_AL | MSR_IR | MSR_DR) DEFAULT_USER_MSR = (DEFAULT_MSR | MSR_PR) CR_LT = 0x80000000 CR_GT = 0x40000000 CR_EQ = 0x20000000 CR_SO = 0x10000000 CR_FX = 0x08000000 CR_FEX = 0x04000000 CR_VX = 0x02000000 CR_OX = 0x01000000 XER_SO = 0x80000000 XER_OV = 0x40000000 XER_CA = 0x20000000 def XER_COMP_BYTE(xer): return ((xer >> 8) & 0x000000FF) def XER_LENGTH(xer): return (xer & 0x0000007F) DSISR_IO = 0x80000000 DSISR_PFT = 0x40000000 DSISR_LOCK = 0x20000000 DSISR_FPIO = 0x10000000 DSISR_PROT = 0x08000000 DSISR_LOOP = 0x04000000 DSISR_DRST = 0x04000000 DSISR_ST = 0x02000000 DSISR_SEGB = 0x01000000 DSISR_DABR = 0x00400000 DSISR_EAR = 0x00100000 SRR_IS_PFT = 0x40000000 SRR_IS_ISPEC = 0x20000000 SRR_IS_IIO = 0x10000000 SRR_IS_PROT = 0x08000000 SRR_IS_LOOP = 0x04000000 SRR_PR_FPEN = 0x00100000 SRR_PR_INVAL = 0x00080000 SRR_PR_PRIV = 0x00040000 SRR_PR_TRAP = 0x00020000 SRR_PR_IMPRE = 0x00010000 def ntohl(x): return (x) def ntohs(x): return (x) def htonl(x): return (x) def htons(x): return (x) IPPROTO_IP = 0 IPPROTO_ICMP = 1 IPPROTO_GGP = 3 IPPROTO_TCP = 6 IPPROTO_EGP = 8 IPPROTO_PUP = 12 IPPROTO_UDP = 17 IPPROTO_IDP = 22 IPPROTO_TP = 29 IPPROTO_LOCAL = 63 IPPROTO_EON = 80 IPPROTO_BIP = 0x53 IPPROTO_RAW = 255 IPPROTO_MAX = 256 IPPORT_RESERVED = 1024 IPPORT_USERRESERVED = 5000 IPPORT_TIMESERVER = 37 def IN_CLASSA(i): return (((long)(i) & 0x80000000) == 0) IN_CLASSA_NET = 0xff000000 IN_CLASSA_NSHIFT = 24 IN_CLASSA_HOST = 0x00ffffff IN_CLASSA_MAX = 128 def IN_CLASSB(i): return (((long)(i) & 0xc0000000) == 0x80000000) IN_CLASSB_NET = 0xffff0000 IN_CLASSB_NSHIFT = 16 IN_CLASSB_HOST = 0x0000ffff IN_CLASSB_MAX = 65536 def IN_CLASSC(i): return (((long)(i) & 0xe0000000) == 0xc0000000) IN_CLASSC_NET = 0xffffff00 IN_CLASSC_NSHIFT = 8 IN_CLASSC_HOST = 0x000000ff def IN_CLASSD(i): return (((long)(i) & 0xf0000000) == 0xe0000000) def IN_MULTICAST(i): return IN_CLASSD(i) def IN_EXPERIMENTAL(i): return (((long)(i) & 0xe0000000) == 0xe0000000) def IN_BADCLASS(i): return (((long)(i) & 0xf0000000) == 0xf0000000) INADDR_ANY = 0x00000000 INADDR_LOOPBACK = 0x7f000001 INADDR_BROADCAST = 0xffffffff INADDR_NONE = 0xffffffff IN_LOOPBACKNET = 127 IP_OPTIONS = 1 IP_HDRINCL = 2 IP_TOS = 3 IP_TTL = 4 IP_RECVOPTS = 5 IP_RECVRETOPTS = 6 IP_RECVDSTADDR = 7 IP_RETOPTS = 8
#Inputing Age age = int(input("Enter Age : ")) # condition to check if the person is an adult or a teenager or a kid if age>=18: status="Not a teenager. You are an adult" elif age>=13: status="Teenager" elif age<=12: status="You are a kid" print("You are ",status,)# Printing the result after inputing the age of the kid
# # Множественное наследование # # разные названия методов class Sitter: def sit(self): print("sit") class Layer: def lay(self): print("lay") class SitterLayer(Sitter, Layer): pass # a = SitterLayer() # a.sit() # a.lay() # Одинаковые названия методов class SayerA: def say(self): print("a") class SayerB: def say(self): print("b") class SayerAB(SayerA, SayerB): pass class SayerBA(SayerB, SayerA): pass # в наследниках метод выбирается по первому указанному в родителях классу # ab = SayerAB() # ab.say() # ba = SayerBA() # ba.say()
# -*- coding: utf-8 -*- """ Created on Fri Nov 09 19:07:20 2018 @author: techietrader """
__author__ = 'chira' # "def" as defining mathematical functions # 18-Unpacking_args gives an alternate way to pass arguments def f(x): # function name is "f". It has ONE argument y = 2*x + 3 print("f(%d) = %d" %(x,y)) def g(x): # function name is "g". It has ONE argument y = pow(x,2) print("g(%d) = %d" %(x,y)) def h(x,y): # function name is "h". It has TWO arguments z = pow(x,2) + 3*y; print("h(%d,%d) = %d" %(x,y,z)) f(1)# call (by value) f(3) g(5) h(2,3) # for doing a function composition we need the notion of "return" values
def list_reverse(list1): new_list = [] for i in range(len(list1)-1, -1, -1): new_list.append(list1[i]) return new_list test = [1, 2, 3, 4, 5, 6] print(test) print(list_reverse(test))
# Bot information SESSION = 'LeoMediaSearchBot' USER_SESSION = 'User_Bot' API_ID = 12345 API_HASH = '0123456789abcdef0123456789abcdef' BOT_TOKEN = '123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11' USERBOT_STRING_SESSION = '' # Bot settings MAX_RESULTS = 10 CACHE_TIME = 300 USE_CAPTION_FILTER = False # Admins, Channels & Users ADMINS = [12345789, 'admin123', 98765432] CHANNELS = [-10012345678, -100987654321, 'channelusername'] AUTH_USERS = [] AUTH_CHANNEL = None # MongoDB information DATABASE_URI = "mongodb://[username:password@]host1[:port1][,...hostN[:portN]][/[defaultauthdb]?retryWrites=true&w=majority" DATABASE_NAME = 'Telegram' COLLECTION_NAME = 'channel_files' # If you are using the same database, then use different collection name for each bot # Messages START_MSG = """ **Hi {}👋 I'm PJ Search Search Bot** You can start searching by the "Search Files """ SHARE_BUTTON_TEXT = 'Checkout {username} for searching files' INVITE_MSG = 'You cant use this bot untill you join our bot🙁 So please join our Updates Channel'
"""This problem was asked by Samsung. A group of houses is connected to the main water plant by means of a set of pipes. A house can either be connected by a set of pipes extending directly to the plant, or indirectly by a pipe to a nearby house which is otherwise connected. For example, here is a possible configuration, where A, B, and C are houses, and arrows represent pipes: A <--> B <--> C <--> plant Each pipe has an associated cost, which the utility company would like to minimize. Given an undirected graph of pipe connections, return the lowest cost configuration of pipes such that each house has access to water. In the following setup, for example, we can remove all but the pipes from plant to A, plant to B, and B to C, for a total cost of 16. pipes = { 'plant': {'A': 1, 'B': 5, 'C': 20}, 'A': {'C': 15}, 'B': {'C': 10}, 'C': {} } """
""" This module contains all the exceptions that ZipTaxClient can throw See http://docs.zip-tax.com/en/latest/api_response.html#response-codes """ class ZipTaxFailure(Exception): pass class ZipTaxInvalidKey(ZipTaxFailure): pass class ZipTaxInvalidFormat(ZipTaxFailure): pass class ZipTaxInvalidData(ZipTaxFailure): pass class ZipTaxInvalidState(ZipTaxInvalidData): pass class ZipTaxInvalidCity(ZipTaxInvalidData): pass class ZipTaxInvalidPostalCode(ZipTaxInvalidData): pass class ZipTaxNoResults(ZipTaxFailure): pass class ZipTaxMultipleResults(ZipTaxFailure): pass def get_exception_for_code(code): exceptions = { 101: ZipTaxInvalidKey, 102: ZipTaxInvalidState, 103: ZipTaxInvalidCity, 104: ZipTaxInvalidPostalCode, 105: ZipTaxInvalidFormat, } return exceptions.get(code, ZipTaxFailure)