content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
"""
All that is open must be closed...
http://www.codewars.com/kata/55679d644c58e2df2a00009c/train/python
"""
def is_balanced(source, caps):
count = {}
stack = []
for c in source:
if c in caps:
i = caps.index(c)
if i % 2 == 0:
if caps[i] == caps[i + 1]:
if caps[i] in count:
count[caps[i]] += 1
else:
count[caps[i]] = 1
else:
stack.append(c)
else:
if caps[i - 1] == caps[i]:
if caps[i] in count:
count[caps[i]] += 1
else:
count[caps[i]] = 1
else:
if len(stack) == 0 or stack.pop() != caps[i - 1]:
return False
return (len(stack) == 0) and ((sum([v for k, v in count.items()])) % 2 == 0)
print(is_balanced("(Sensei says yes!)", "()") == True)
print(is_balanced("(Sensei says no!", "()") == False)
print(is_balanced("(Sensei [says] yes!)", "()[]") == True)
print(is_balanced("(Sensei [says) no!]", "()[]") == False)
print(is_balanced("Sensei says -yes-!", "--") == True)
print(is_balanced("Sensei -says no!", "--") == False)
| """
All that is open must be closed...
http://www.codewars.com/kata/55679d644c58e2df2a00009c/train/python
"""
def is_balanced(source, caps):
count = {}
stack = []
for c in source:
if c in caps:
i = caps.index(c)
if i % 2 == 0:
if caps[i] == caps[i + 1]:
if caps[i] in count:
count[caps[i]] += 1
else:
count[caps[i]] = 1
else:
stack.append(c)
elif caps[i - 1] == caps[i]:
if caps[i] in count:
count[caps[i]] += 1
else:
count[caps[i]] = 1
elif len(stack) == 0 or stack.pop() != caps[i - 1]:
return False
return len(stack) == 0 and sum([v for (k, v) in count.items()]) % 2 == 0
print(is_balanced('(Sensei says yes!)', '()') == True)
print(is_balanced('(Sensei says no!', '()') == False)
print(is_balanced('(Sensei [says] yes!)', '()[]') == True)
print(is_balanced('(Sensei [says) no!]', '()[]') == False)
print(is_balanced('Sensei says -yes-!', '--') == True)
print(is_balanced('Sensei -says no!', '--') == False) |
#python program to display odd numbers
print("Odd numbers are as follows")
for i in range(1,100,2):
print(i)
print("End of the program")
| print('Odd numbers are as follows')
for i in range(1, 100, 2):
print(i)
print('End of the program') |
#!/usr/bin/python3
def img_splitter(img):
img_lines = img.splitlines()
longest = 0
for ind, line in enumerate(img_lines):
if line == "":
img_lines.pop(ind)
if len(line) > longest:
longest = len(line)
for line in img_lines:
if len(line) < longest:
line.format(n=longest, c=" ")
return img_lines
def encrypt():
imgList = []
letterDICT = {'A': path + 'A.txt', 'B': path + 'B.txt', 'C': path + 'C.txt', 'D': path + 'D.txt',
'E': path + 'E.txt',
'F': path + 'F.txt', 'G': path + 'G.txt', 'H': path + 'H.txt', 'I': path + 'I.txt',
'J': path + 'J.txt',
'K': path + 'K.txt', 'L': path + 'L.txt', 'M': path + 'M.txt', 'N': path + 'N.txt',
'O': path + 'O.txt',
'P': path + 'P.txt', 'Q': path + 'Q.txt', 'R': path + 'R.txt', 'S': path + 'S.txt',
'T': path + 'T.txt',
'U': path + 'U.txt', 'V': path + 'V.txt', 'W': path + 'W.txt', 'X': path + 'X.txt',
'Y': path + 'Y.txt',
'Z': path + 'Z.txt'}
letterScan = list(engLetters)
for alphabet in letterScan:
if alphabet in letterDICT:
txtScan = letterDICT[alphabet]
with open(txtScan, 'r') as fr:
data = fr.read()
imgList.append(img_splitter(data))
numLetters = len(imgList)
zipped = zip(*imgList)
for line in zipped:
match numLetters:
case 1:
print(line[0])
case 2:
print(line[0], line[1])
case 3:
print(line[0], line[1], line[2])
case 4:
print(line[0], line[1], line[2], line[3])
case 5:
print(line[0], line[1], line[2], line[3], line[4])
case 6:
print(line[0], line[1], line[2], line[3], line[4], line[5])
case 7:
print(line[0], line[1], line[2], line[3], line[4], line[5],
line[6])
case 8:
print(line[0], line[1], line[2], line[3], line[4], line[5],
line[6].line[7])
case 9:
print(line[0], line[1], line[2], line[3], line[4], line[5],
line[6].line[7], line[8])
case 10:
print(line[0], line[1], line[2], line[3], line[4], line[5],
line[6].line[7], line[8], line[9])
case 11:
print(line[0], line[1], line[2], line[3], line[4], line[5],
line[6].line[7], line[8], line[9], line[10])
case 12:
print(line[0], line[1], line[2], line[3], line[4], line[5],
line[6].line[7], line[8], line[9], line[10], line[11])
case 13:
print(line[0], line[1], line[2], line[3], line[4], line[5],
line[6].line[7], line[8], line[9], line[10], line[11], line[12])
case 14:
print(line[0], line[1], line[2], line[3], line[4], line[5],
line[6].line[7], line[8], line[9], line[10], line[11], line[12], line[13])
print('\n')
path = 'ASCII arts/'
message = input("What is your name: ")
engLetters = message.upper()
encrypt()
vm = path + "vending_machine.txt"
with open(vm, 'r') as fr:
print(fr.read(), end='\n')
exchange = input("Would you like something to drink? Enter Y/N ")
if exchange.upper() == 'Y':
print("Sorry the machine is being hacked by the Aliens")
print("They want to know your choice by using their language")
decision = input("Would you like do use the decoder to purchase the drink [Y/N]")
if decision.upper() == 'N':
message = "bye"
engLetters = message.upper()
print(message)
encrypt()
elif decision.upper() == 'Y':
bev_choice = input("Enter you drink types [coke], [sprite], [fanta], [water], and [lemonade]")
bev_choice = bev_choice.upper()
engLetters = bev_choice
encrypt()
bev_dict = {'COKE': path + "coke.txt",
'SPRITE': path + 'sprite.txt',
'FANTA': path + 'fanta.txt',
'WATER': path + 'water.txt',
'LEMONADE': path + 'lemonade.txt'}
if bev_choice in bev_dict:
bevtxt = bev_dict[bev_choice]
print("Getting your item... please wait...")
with open(str(bevtxt), "r") as bf:
# indent to keep the building object open
# loop across the lines in the file
for svr in bf:
# print and end without a newline
print(svr, end="")
print()
print("Here you go! Enjoy it!")
print("Thanks for purchasing! ")
elif exchange.upper() == 'N':
print("Please Come back when you are thirsty")
| def img_splitter(img):
img_lines = img.splitlines()
longest = 0
for (ind, line) in enumerate(img_lines):
if line == '':
img_lines.pop(ind)
if len(line) > longest:
longest = len(line)
for line in img_lines:
if len(line) < longest:
line.format(n=longest, c=' ')
return img_lines
def encrypt():
img_list = []
letter_dict = {'A': path + 'A.txt', 'B': path + 'B.txt', 'C': path + 'C.txt', 'D': path + 'D.txt', 'E': path + 'E.txt', 'F': path + 'F.txt', 'G': path + 'G.txt', 'H': path + 'H.txt', 'I': path + 'I.txt', 'J': path + 'J.txt', 'K': path + 'K.txt', 'L': path + 'L.txt', 'M': path + 'M.txt', 'N': path + 'N.txt', 'O': path + 'O.txt', 'P': path + 'P.txt', 'Q': path + 'Q.txt', 'R': path + 'R.txt', 'S': path + 'S.txt', 'T': path + 'T.txt', 'U': path + 'U.txt', 'V': path + 'V.txt', 'W': path + 'W.txt', 'X': path + 'X.txt', 'Y': path + 'Y.txt', 'Z': path + 'Z.txt'}
letter_scan = list(engLetters)
for alphabet in letterScan:
if alphabet in letterDICT:
txt_scan = letterDICT[alphabet]
with open(txtScan, 'r') as fr:
data = fr.read()
imgList.append(img_splitter(data))
num_letters = len(imgList)
zipped = zip(*imgList)
for line in zipped:
match numLetters:
case 1:
print(line[0])
case 2:
print(line[0], line[1])
case 3:
print(line[0], line[1], line[2])
case 4:
print(line[0], line[1], line[2], line[3])
case 5:
print(line[0], line[1], line[2], line[3], line[4])
case 6:
print(line[0], line[1], line[2], line[3], line[4], line[5])
case 7:
print(line[0], line[1], line[2], line[3], line[4], line[5], line[6])
case 8:
print(line[0], line[1], line[2], line[3], line[4], line[5], line[6].line[7])
case 9:
print(line[0], line[1], line[2], line[3], line[4], line[5], line[6].line[7], line[8])
case 10:
print(line[0], line[1], line[2], line[3], line[4], line[5], line[6].line[7], line[8], line[9])
case 11:
print(line[0], line[1], line[2], line[3], line[4], line[5], line[6].line[7], line[8], line[9], line[10])
case 12:
print(line[0], line[1], line[2], line[3], line[4], line[5], line[6].line[7], line[8], line[9], line[10], line[11])
case 13:
print(line[0], line[1], line[2], line[3], line[4], line[5], line[6].line[7], line[8], line[9], line[10], line[11], line[12])
case 14:
print(line[0], line[1], line[2], line[3], line[4], line[5], line[6].line[7], line[8], line[9], line[10], line[11], line[12], line[13])
print('\n')
path = 'ASCII arts/'
message = input('What is your name: ')
eng_letters = message.upper()
encrypt()
vm = path + 'vending_machine.txt'
with open(vm, 'r') as fr:
print(fr.read(), end='\n')
exchange = input('Would you like something to drink? Enter Y/N ')
if exchange.upper() == 'Y':
print('Sorry the machine is being hacked by the Aliens')
print('They want to know your choice by using their language')
decision = input('Would you like do use the decoder to purchase the drink [Y/N]')
if decision.upper() == 'N':
message = 'bye'
eng_letters = message.upper()
print(message)
encrypt()
elif decision.upper() == 'Y':
bev_choice = input('Enter you drink types [coke], [sprite], [fanta], [water], and [lemonade]')
bev_choice = bev_choice.upper()
eng_letters = bev_choice
encrypt()
bev_dict = {'COKE': path + 'coke.txt', 'SPRITE': path + 'sprite.txt', 'FANTA': path + 'fanta.txt', 'WATER': path + 'water.txt', 'LEMONADE': path + 'lemonade.txt'}
if bev_choice in bev_dict:
bevtxt = bev_dict[bev_choice]
print('Getting your item... please wait...')
with open(str(bevtxt), 'r') as bf:
for svr in bf:
print(svr, end='')
print()
print('Here you go! Enjoy it!')
print('Thanks for purchasing! ')
elif exchange.upper() == 'N':
print('Please Come back when you are thirsty') |
class BinaryMatrix(object):
def __init__(self, mat):
self.mat = mat
def get(self, x: int, y: int) -> int:
return self.mat[x][y]
def dimensions(self):
n = len(self.mat)
m = len(self.mat[0])
return n, m
class Solution:
def leftMostColumnWithOne(self, binaryMatrix: 'BinaryMatrix') -> int:
n, m = binaryMatrix.dimensions()
res = float('inf')
for i in range(n):
low = 0
high = m - 1
while low + 1 < high:
mid = low + (high - low) // 2
if binaryMatrix.get(i, mid) == 1:
high = mid
else:
low = mid
if binaryMatrix.get(i, low) == 1:
res = min(res, low)
elif binaryMatrix.get(i, high) == 1:
res = min(res, high)
return res
if __name__ == '__main__':
s = Solution()
mat = [[0,0,0,1],[0,0,1,1],[0,1,1,1]]
matrix = BinaryMatrix(mat)
res = s.leftMostColumnWithOne(matrix)
print(res) | class Binarymatrix(object):
def __init__(self, mat):
self.mat = mat
def get(self, x: int, y: int) -> int:
return self.mat[x][y]
def dimensions(self):
n = len(self.mat)
m = len(self.mat[0])
return (n, m)
class Solution:
def left_most_column_with_one(self, binaryMatrix: 'BinaryMatrix') -> int:
(n, m) = binaryMatrix.dimensions()
res = float('inf')
for i in range(n):
low = 0
high = m - 1
while low + 1 < high:
mid = low + (high - low) // 2
if binaryMatrix.get(i, mid) == 1:
high = mid
else:
low = mid
if binaryMatrix.get(i, low) == 1:
res = min(res, low)
elif binaryMatrix.get(i, high) == 1:
res = min(res, high)
return res
if __name__ == '__main__':
s = solution()
mat = [[0, 0, 0, 1], [0, 0, 1, 1], [0, 1, 1, 1]]
matrix = binary_matrix(mat)
res = s.leftMostColumnWithOne(matrix)
print(res) |
USER_AGENTS = [
(
"Mozilla/5.0 (X11; Linux x86_64) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/57.0.2987.110 "
"Safari/537.36"
), # chrome
(
"Mozilla/5.0 (X11; Linux x86_64) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/61.0.3163.79 "
"Safari/537.36"
), # chrome
(
"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:55.0) "
"Gecko/20100101 "
"Firefox/55.0"
), # firefox
(
"Mozilla/5.0 (X11; Linux x86_64) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/61.0.3163.91 "
"Safari/537.36"
), # chrome
(
"Mozilla/5.0 (X11; Linux x86_64) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/62.0.3202.89 "
"Safari/537.36"
), # chrome
(
"Mozilla/5.0 (X11; Linux x86_64) "
"AppleWebKit/537.36 (KHTML, like Gecko) "
"Chrome/63.0.3239.108 "
"Safari/537.36"
), # chrome
]
BaseURL = "https://azemikalaw.com/"
# BaseURL = "https://forum.mobilism.org/viewtopic.php?f=399&t=3558945"
WEB_DRIVER_PATH = "/usr/bin/firefox-dev"
| user_agents = ['Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.110 Safari/537.36', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.79 Safari/537.36', 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:55.0) Gecko/20100101 Firefox/55.0', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.91 Safari/537.36', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/62.0.3202.89 Safari/537.36', 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36']
base_url = 'https://azemikalaw.com/'
web_driver_path = '/usr/bin/firefox-dev' |
# Block No 99997
# Block Bits 453281356
# Difficulty 14,484.16
_bits = input("* block's BITS ? : ");
hexBits = hex(int(_bits));
_hexHead = hexBits[:4];
_hexTail = '0x'+hexBits[4:];
print("- BITS in hexadecimal : ", hexBits);
print(" ", _hexHead);
print(" ", _hexTail);
# print hex(int("0xAD4", 16) + int("0x200", 16)) # 0xcd4
max_difficulty = hex(0x00000000FFFF0000000000000000000000000000000000000000000000000000);
cur_difficulty = hex(int(_hexTail, 16)*2**(8*(int(_hexHead, 16)-3)));
print("- maximum difficulty : ", max_difficulty);
print("- this block's difficulty : ", cur_difficulty);
print("- this block's NONCE : ", (int(max_difficulty, 16)/int(cur_difficulty, 16)));
| _bits = input("* block's BITS ? : ")
hex_bits = hex(int(_bits))
_hex_head = hexBits[:4]
_hex_tail = '0x' + hexBits[4:]
print('- BITS in hexadecimal : ', hexBits)
print(' ', _hexHead)
print(' ', _hexTail)
max_difficulty = hex(26959535291011309493156476344723991336010898738574164086137773096960)
cur_difficulty = hex(int(_hexTail, 16) * 2 ** (8 * (int(_hexHead, 16) - 3)))
print('- maximum difficulty : ', max_difficulty)
print("- this block's difficulty : ", cur_difficulty)
print("- this block's NONCE : ", int(max_difficulty, 16) / int(cur_difficulty, 16)) |
class BaseConfig:
SECRET_KEY = None
class DevelopmentConfig(BaseConfig):
FLASK_ENV="development"
class ProductionConfig(BaseConfig):
FLASK_ENV="production" | class Baseconfig:
secret_key = None
class Developmentconfig(BaseConfig):
flask_env = 'development'
class Productionconfig(BaseConfig):
flask_env = 'production' |
class Analyzer():
'''
Analyzer holds image data, hooks to pre-processed and intermediate data
and the methods to analyze and output visualizations
start: 2017-05-27, Nathan Ing
'''
def __init__(self):
pass | class Analyzer:
"""
Analyzer holds image data, hooks to pre-processed and intermediate data
and the methods to analyze and output visualizations
start: 2017-05-27, Nathan Ing
"""
def __init__(self):
pass |
"""
The Elves think their skill will improve after making a few recipes.
However, that could take ages; you can speed this up considerably by identifying
the scores of the ten recipes after that.
What are the scores of the ten recipes immediately after the number of recipes
in your puzzle input?
"""
class Scoreboard:
def __init__(self, values):
self.board = values
self.elf_1 = 0
self.elf_2 = 1
def __str__(self):
return f"Current board: {self.board}\nElf 1: {self.board[self.elf_1]}\nElf 2: {self.board[self.elf_2]}"
def create_recipe(self):
sum_recipes = self.board[self.elf_1] + self.board[self.elf_2]
for i in str(sum_recipes):
self.board.append(int(i))
def get_new_recipe(self):
self.elf_1 += (1 + self.board[self.elf_1]) % len(self.board)
self.elf_1 = self.elf_1 % len(self.board)
self.elf_2 += (1 + self.board[self.elf_2]) % len(self.board)
self.elf_2 = self.elf_2 % len(self.board)
def move_forward(self, n=1):
for _ in range(n):
self.create_recipe()
self.get_new_recipe()
def score_check(self, n):
while len(self.board) < n + 10:
self.move_forward()
score = self.board[n : n + 10]
return "".join(str(i) for i in score)
def recipes_before_sequence(self, seq):
"""Move forward while the last len(seq) recipes are not seq"""
target = [int(i) for i in str(seq)]
seq_len = len(target)
while True:
if self.board[-seq_len:] == target:
return len(self.board) - seq_len
elif self.board[-seq_len - 1 : -1] == target:
return len(self.board) - seq_len - 1
self.move_forward()
N = 825_401
scoreboard = Scoreboard([3, 7]) # Part 1
print(f"The scores of ten recipes after {N} recipes is {scoreboard.score_check(N)}")
scoreboard_2 = Scoreboard([3, 7]) # Part 2
print(
f"{scoreboard_2.recipes_before_sequence(N)} recipes appear on the scoreboard to the left of {N}"
) | """
The Elves think their skill will improve after making a few recipes.
However, that could take ages; you can speed this up considerably by identifying
the scores of the ten recipes after that.
What are the scores of the ten recipes immediately after the number of recipes
in your puzzle input?
"""
class Scoreboard:
def __init__(self, values):
self.board = values
self.elf_1 = 0
self.elf_2 = 1
def __str__(self):
return f'Current board: {self.board}\nElf 1: {self.board[self.elf_1]}\nElf 2: {self.board[self.elf_2]}'
def create_recipe(self):
sum_recipes = self.board[self.elf_1] + self.board[self.elf_2]
for i in str(sum_recipes):
self.board.append(int(i))
def get_new_recipe(self):
self.elf_1 += (1 + self.board[self.elf_1]) % len(self.board)
self.elf_1 = self.elf_1 % len(self.board)
self.elf_2 += (1 + self.board[self.elf_2]) % len(self.board)
self.elf_2 = self.elf_2 % len(self.board)
def move_forward(self, n=1):
for _ in range(n):
self.create_recipe()
self.get_new_recipe()
def score_check(self, n):
while len(self.board) < n + 10:
self.move_forward()
score = self.board[n:n + 10]
return ''.join((str(i) for i in score))
def recipes_before_sequence(self, seq):
"""Move forward while the last len(seq) recipes are not seq"""
target = [int(i) for i in str(seq)]
seq_len = len(target)
while True:
if self.board[-seq_len:] == target:
return len(self.board) - seq_len
elif self.board[-seq_len - 1:-1] == target:
return len(self.board) - seq_len - 1
self.move_forward()
n = 825401
scoreboard = scoreboard([3, 7])
print(f'The scores of ten recipes after {N} recipes is {scoreboard.score_check(N)}')
scoreboard_2 = scoreboard([3, 7])
print(f'{scoreboard_2.recipes_before_sequence(N)} recipes appear on the scoreboard to the left of {N}') |
# bubble sort function
def bubble_sort(arr):
n = len(arr)
# Repeat loop N times
# equivalent to: for(i = 0; i < n-1; i++)
for i in range(0, n-1):
# Repeat internal loop for (N-i)th largest element
for j in range(0, n-i-1):
# if jth value is greater than (j+1) value
if arr[j] > arr[j+1]:
# swap the values at j and j+1 index
# Pythonic way to swap 2 variable values -> x, y = y, x
arr[j], arr[j+1] = arr[j+1], arr[j]
arr = [64, 34, 25, 12, 22, 11, 90]
print('Before sorting:', arr)
# call bubble sort function on the array
bubble_sort(arr)
print('After sorting:', arr)
"""
Output:
Before sorting: [64, 34, 25, 12, 22, 11, 90]
After sorting: [11, 12, 22, 25, 34, 64, 90]
""" | def bubble_sort(arr):
n = len(arr)
for i in range(0, n - 1):
for j in range(0, n - i - 1):
if arr[j] > arr[j + 1]:
(arr[j], arr[j + 1]) = (arr[j + 1], arr[j])
arr = [64, 34, 25, 12, 22, 11, 90]
print('Before sorting:', arr)
bubble_sort(arr)
print('After sorting:', arr)
'\nOutput:\nBefore sorting: [64, 34, 25, 12, 22, 11, 90]\nAfter sorting: [11, 12, 22, 25, 34, 64, 90]\n' |
arr = []
for i in range(5):
dum = list(map(int, input().split()))
arr.append(dum)
def sol(arr):
for i in range(5):
for j in range(5):
if arr[i][j] == 1:
return abs(2-i) + abs(2-j)
print(sol(arr)) | arr = []
for i in range(5):
dum = list(map(int, input().split()))
arr.append(dum)
def sol(arr):
for i in range(5):
for j in range(5):
if arr[i][j] == 1:
return abs(2 - i) + abs(2 - j)
print(sol(arr)) |
"""
*args
A special operator we can pass to functions.
Gathers remaining arguments as a tuple.
"""
def sum_all_nums(num1, num2, num3):
return num1 + num2 + num3
print(sum_all_nums(4, 6, 9)) # 19
print(sum_all_nums(4, 6)) # Error: no value for argument num3
def sum_with_args(*args):
total = 0
for num in args:
total += num
return total
print(sum_with_args(4, 6, 9)) # 19
print(sum_with_args(4, 6)) # 10 | """
*args
A special operator we can pass to functions.
Gathers remaining arguments as a tuple.
"""
def sum_all_nums(num1, num2, num3):
return num1 + num2 + num3
print(sum_all_nums(4, 6, 9))
print(sum_all_nums(4, 6))
def sum_with_args(*args):
total = 0
for num in args:
total += num
return total
print(sum_with_args(4, 6, 9))
print(sum_with_args(4, 6)) |
# coding: utf-8
# This example is the python implementation of nowait.1.f from OpenMP 4.5 examples
n = 100
m = 100
a = zeros(n, double)
b = zeros(n, double)
y = zeros(m, double)
z = zeros(m, double)
#$ omp parallel
#$ omp do schedule(runtime)
for i in range(0, m):
z[i] = i*1.0
#$ omp end do nowait
#$ omp do
for i in range(1, n):
b[i] = (a[i] + a[i-1]) / 2.0
#$ omp end do nowait
#$ omp do
for i in range(1, m):
y[i] = sqrt(z[i])
#$ omp end do nowait
#$ omp end parallel
| n = 100
m = 100
a = zeros(n, double)
b = zeros(n, double)
y = zeros(m, double)
z = zeros(m, double)
for i in range(0, m):
z[i] = i * 1.0
for i in range(1, n):
b[i] = (a[i] + a[i - 1]) / 2.0
for i in range(1, m):
y[i] = sqrt(z[i]) |
#!/usr/bin/env python3v
## create file object in "r"ead mode
filename = input("Name of file: ")
with open(f"{filename}", "r") as configfile:
## readlines() creates a list by reading target
## file line by line
configlist = configfile.readlines()
## file was just auto closed (no more indenting)
## each item of the list now has the "\n" characters back
print(configlist)
num_lines = len(configlist)
print(f"Using the len() function, we see there are: {num_lines} line")
| filename = input('Name of file: ')
with open(f'{filename}', 'r') as configfile:
configlist = configfile.readlines()
print(configlist)
num_lines = len(configlist)
print(f'Using the len() function, we see there are: {num_lines} line') |
class Solution:
def preorderTraversal(self, root):
ret = []
s = [root]
while s:
cur = s.pop()
if not cur:
continue
ret.append(cur.val)
if cur.right:
s.append(cur.right)
if cur.left:
s.append(cur.left)
return ret
# def preorderTraversal(self, root):
# """
# :type root: TreeNode
# :rtype: List[int]
# root
# left
# right
# """
# ret = []
# def traverse(node):
# if not node:
# return
# ret.append(node.val)
# traverse(node.left)
# traverse(node.right)
# traverse(root)
# return ret
| class Solution:
def preorder_traversal(self, root):
ret = []
s = [root]
while s:
cur = s.pop()
if not cur:
continue
ret.append(cur.val)
if cur.right:
s.append(cur.right)
if cur.left:
s.append(cur.left)
return ret |
execfile('ex-3.02.py')
assert dtype.size == MPI.DOUBLE.size + MPI.CHAR.size
assert dtype.extent >= dtype.size
dtype.Free()
| execfile('ex-3.02.py')
assert dtype.size == MPI.DOUBLE.size + MPI.CHAR.size
assert dtype.extent >= dtype.size
dtype.Free() |
"""
--- Day 6: Custom Customs ---
As your flight approaches the regional airport where you'll switch to a much larger plane,
customs declaration forms are distributed to the passengers.
The form asks a series of 26 yes-or-no questions marked a through z. All you need to do is
identify the questions for which anyone in your group answers "yes". Since your group is just you,
this doesn't take very long.
However, the person sitting next to you seems to be experiencing a language barrier and asks
if you can help. For each of the people in their group, you write down the questions for which
they answer "yes", one per line. For example:
abcx
abcy
abcz
In this group, there are 6 questions to which anyone answered "yes": a, b, c, x, y,
and z. (Duplicate answers to the same question don't count extra; each question counts at most once.)
Another group asks for your help, then another, and eventually you've collected answers from every
group on the plane (your puzzle input). Each group's answers are separated by a blank line, and
within each group, each person's answers are on a single line. For example:
abc
a
b
c
ab
ac
a
a
a
a
b
This list represents answers from five groups:
The first group contains one person who answered "yes" to 3 questions: a, b, and c.
The second group contains three people; combined, they answered "yes" to 3 questions: a, b, and c.
The third group contains two people; combined, they answered "yes" to 3 questions: a, b, and c.
The fourth group contains four people; combined, they answered "yes" to only 1 question, a.
The last group contains one person who answered "yes" to only 1 question, b.
In this example, the sum of these counts is 3 + 3 + 3 + 1 + 1 = 11.
For each group, count the number of questions to which anyone answered "yes". What is the
sum of those counts?
Your puzzle answer was 6351.
--- Part Two ---
As you finish the last group's customs declaration, you notice that you misread one word in
the instructions:
You don't need to identify the questions to which anyone answered "yes"; you need to identify
the questions to which everyone answered "yes"!
Using the same example as above:
abc
a
b
c
ab
ac
a
a
a
a
b
This list represents answers from five groups:
In the first group, everyone (all 1 person) answered "yes" to 3 questions: a, b, and c.
In the second group, there is no question to which everyone answered "yes".
In the third group, everyone answered yes to only 1 question, a. Since some people did not
answer "yes" to b or c, they don't count.
In the fourth group, everyone answered yes to only 1 question, a.
In the fifth group, everyone (all 1 person) answered "yes" to 1 question, b.
In this example, the sum of these counts is 3 + 0 + 1 + 1 + 1 = 6.
For each group, count the number of questions to which everyone answered "yes". What is the sum
of those counts?
Your puzzle answer was 3143.
"""
def count_answers(text_input):
""" aoc day6 part 1:
Count the number of questions for which anyone answered 'yes' from the puzzle input """
total = 0
target = 'abcdefghijklmnopqrstuvwxyz'
for group in text_input:
for char in target:
if char in group:
total += 1
return total
def count_unanimous_answers(text_input):
""" aoc day6 part 2:
Count the number of questions for which at everyone answered 'yes' from the puzzle input """
count = 0
for group in text_input:
group = group.splitlines()
ans = set(group[0])
for person in group:
ans = ans & set(person)
count = count + len(ans)
return count
file = open("./data/6_input.txt").read()
answers = file.split("\n\n")
print(count_answers(answers))
print(count_unanimous_answers(answers))
| """
--- Day 6: Custom Customs ---
As your flight approaches the regional airport where you'll switch to a much larger plane,
customs declaration forms are distributed to the passengers.
The form asks a series of 26 yes-or-no questions marked a through z. All you need to do is
identify the questions for which anyone in your group answers "yes". Since your group is just you,
this doesn't take very long.
However, the person sitting next to you seems to be experiencing a language barrier and asks
if you can help. For each of the people in their group, you write down the questions for which
they answer "yes", one per line. For example:
abcx
abcy
abcz
In this group, there are 6 questions to which anyone answered "yes": a, b, c, x, y,
and z. (Duplicate answers to the same question don't count extra; each question counts at most once.)
Another group asks for your help, then another, and eventually you've collected answers from every
group on the plane (your puzzle input). Each group's answers are separated by a blank line, and
within each group, each person's answers are on a single line. For example:
abc
a
b
c
ab
ac
a
a
a
a
b
This list represents answers from five groups:
The first group contains one person who answered "yes" to 3 questions: a, b, and c.
The second group contains three people; combined, they answered "yes" to 3 questions: a, b, and c.
The third group contains two people; combined, they answered "yes" to 3 questions: a, b, and c.
The fourth group contains four people; combined, they answered "yes" to only 1 question, a.
The last group contains one person who answered "yes" to only 1 question, b.
In this example, the sum of these counts is 3 + 3 + 3 + 1 + 1 = 11.
For each group, count the number of questions to which anyone answered "yes". What is the
sum of those counts?
Your puzzle answer was 6351.
--- Part Two ---
As you finish the last group's customs declaration, you notice that you misread one word in
the instructions:
You don't need to identify the questions to which anyone answered "yes"; you need to identify
the questions to which everyone answered "yes"!
Using the same example as above:
abc
a
b
c
ab
ac
a
a
a
a
b
This list represents answers from five groups:
In the first group, everyone (all 1 person) answered "yes" to 3 questions: a, b, and c.
In the second group, there is no question to which everyone answered "yes".
In the third group, everyone answered yes to only 1 question, a. Since some people did not
answer "yes" to b or c, they don't count.
In the fourth group, everyone answered yes to only 1 question, a.
In the fifth group, everyone (all 1 person) answered "yes" to 1 question, b.
In this example, the sum of these counts is 3 + 0 + 1 + 1 + 1 = 6.
For each group, count the number of questions to which everyone answered "yes". What is the sum
of those counts?
Your puzzle answer was 3143.
"""
def count_answers(text_input):
""" aoc day6 part 1:
Count the number of questions for which anyone answered 'yes' from the puzzle input """
total = 0
target = 'abcdefghijklmnopqrstuvwxyz'
for group in text_input:
for char in target:
if char in group:
total += 1
return total
def count_unanimous_answers(text_input):
""" aoc day6 part 2:
Count the number of questions for which at everyone answered 'yes' from the puzzle input """
count = 0
for group in text_input:
group = group.splitlines()
ans = set(group[0])
for person in group:
ans = ans & set(person)
count = count + len(ans)
return count
file = open('./data/6_input.txt').read()
answers = file.split('\n\n')
print(count_answers(answers))
print(count_unanimous_answers(answers)) |
class Solution:
def largestBSTSubtree(self, root: TreeNode) -> int:
return self._post_order(root)[0]
def _post_order(self, root):
if not root:
return 0, True, None, None
if not root.left and not root.right:
return 1, True, root.val, root.val
ln, lbst, lmin, lmax = self._post_order(root.left)
rn, rbst, rmin, rmax = self._post_order(root.right)
if not lbst or not rbst or (lmax and root.val <= lmax) or (rmin and root.val >= rmin):
return max(ln, rn), False, None, None
return ln + rn + 1, True, lmin if lmin else root.val, rmax if rmax else root.val
| class Solution:
def largest_bst_subtree(self, root: TreeNode) -> int:
return self._post_order(root)[0]
def _post_order(self, root):
if not root:
return (0, True, None, None)
if not root.left and (not root.right):
return (1, True, root.val, root.val)
(ln, lbst, lmin, lmax) = self._post_order(root.left)
(rn, rbst, rmin, rmax) = self._post_order(root.right)
if not lbst or not rbst or (lmax and root.val <= lmax) or (rmin and root.val >= rmin):
return (max(ln, rn), False, None, None)
return (ln + rn + 1, True, lmin if lmin else root.val, rmax if rmax else root.val) |
# print function range value
for value in range(1, 5):
print(value)
numbers = list(range(1, 6))
print(numbers)
even_numbers = list(range(2, 11))
print(even_numbers)
| for value in range(1, 5):
print(value)
numbers = list(range(1, 6))
print(numbers)
even_numbers = list(range(2, 11))
print(even_numbers) |
def is_odd(n):
return n % 2 == 1
def is_weird(n):
if is_odd(n):
return True
else:
# n is even
if 2 <= n <= 5:
return False
elif 6 <= n <= 20:
return True
elif 20 < n:
return False
n = int(input())
if (is_weird(n)):
print("Weird")
else:
print("Not Weird")
| def is_odd(n):
return n % 2 == 1
def is_weird(n):
if is_odd(n):
return True
elif 2 <= n <= 5:
return False
elif 6 <= n <= 20:
return True
elif 20 < n:
return False
n = int(input())
if is_weird(n):
print('Weird')
else:
print('Not Weird') |
class calculos():
def __init__(self):
self.funcoes = {
"soma": self.soma,
"subtracao": self.subtracao,
"multiplicacao": self.multiplicacao,
"divisao": self.divisao,
"quadrado": self.quadrado,
"raiz_quadrada": self.raiz_quadrada,
"porcentagem": self.porcentagem
}
def soma(self, x, y):
return x + y
def subtracao(self, x, y):
return x - y
def multiplicacao(self, x, y):
return x * y
def divisao(self, x, y):
return x / y
def quadrado(self, x):
return x ** 2
def raiz_quadrada(self, x):
return x ** (1/2)
def porcentagem(self, x, y):
return (x * y) / 100
if __name__ == '__main__':
calculos = calculos()
resultado = calculos.funcoes['soma'](1, 4)
print(resultado) | class Calculos:
def __init__(self):
self.funcoes = {'soma': self.soma, 'subtracao': self.subtracao, 'multiplicacao': self.multiplicacao, 'divisao': self.divisao, 'quadrado': self.quadrado, 'raiz_quadrada': self.raiz_quadrada, 'porcentagem': self.porcentagem}
def soma(self, x, y):
return x + y
def subtracao(self, x, y):
return x - y
def multiplicacao(self, x, y):
return x * y
def divisao(self, x, y):
return x / y
def quadrado(self, x):
return x ** 2
def raiz_quadrada(self, x):
return x ** (1 / 2)
def porcentagem(self, x, y):
return x * y / 100
if __name__ == '__main__':
calculos = calculos()
resultado = calculos.funcoes['soma'](1, 4)
print(resultado) |
# Print the list created by using list comprehension
names = ['George', 'Harry', 'Weasely', 'Ron', 'Potter', 'Hermione']
best_list = [name for name in names if len(name) >= 6]
print(best_list)
# Range Objects
# Create a range object that goes from 0 to 5
nums = range(6)
print(type(nums))
# Convert nums to a list
nums_list = list(nums)
print(nums_list)
# Create a new list of odd numbers from 1 to 11 by unpacking a range object
nums_list2 = [*range(1,12,2)]
# This unpacks the range object to a list
print(nums_list2)
# Enumerate Objects
names = ['Jerry', 'Kramer', 'Elaine', 'George', 'Newman']
# Rewrite the for loop to use enumerate
indexed_names = []
for i,name in enumerate(names):
index_name = (i,name)
indexed_names.append(index_name)
print(indexed_names)
# Rewrite the above for loop using list comprehension
indexed_names_comp = [(i,name) for i,name in enumerate(names)]
print(indexed_names_comp)
# Unpack an enumerate object with a starting index of one
indexed_names_unpack = [*enumerate(names, start=1)]
print(indexed_names_unpack)
# Map Objects
# Use map to apply str.upper to each element in names
names_map = map(str.upper, names)
# Print the type of the names_map
print(type(names_map))
# Unpack names_map into a list
names_uppercase = [*names_map]
# Print the list created above
print(names_uppercase)
| names = ['George', 'Harry', 'Weasely', 'Ron', 'Potter', 'Hermione']
best_list = [name for name in names if len(name) >= 6]
print(best_list)
nums = range(6)
print(type(nums))
nums_list = list(nums)
print(nums_list)
nums_list2 = [*range(1, 12, 2)]
print(nums_list2)
names = ['Jerry', 'Kramer', 'Elaine', 'George', 'Newman']
indexed_names = []
for (i, name) in enumerate(names):
index_name = (i, name)
indexed_names.append(index_name)
print(indexed_names)
indexed_names_comp = [(i, name) for (i, name) in enumerate(names)]
print(indexed_names_comp)
indexed_names_unpack = [*enumerate(names, start=1)]
print(indexed_names_unpack)
names_map = map(str.upper, names)
print(type(names_map))
names_uppercase = [*names_map]
print(names_uppercase) |
# -*- coding:utf-8 -*-
def read_files(path):
file = open(path, 'r+')
str_ = file.read()
print(str_)
file.close()
| def read_files(path):
file = open(path, 'r+')
str_ = file.read()
print(str_)
file.close() |
#!/usr/bin/python3
""" 4-main """
MRUCache = __import__('4-mru_cache').MRUCache
my_cache = MRUCache()
my_cache.put("A", "Hello")
my_cache.put("B", "World")
my_cache.put("C", "Holberton")
my_cache.put("D", "School")
my_cache.print_cache()
print(my_cache.get("B"))
my_cache.put("E", "Battery")
my_cache.print_cache()
my_cache.put("C", "Street")
my_cache.print_cache()
print(my_cache.get("A"))
print(my_cache.get("B"))
print(my_cache.get("C"))
my_cache.put("F", "Mission")
my_cache.print_cache()
my_cache.put("G", "San Francisco")
my_cache.print_cache()
my_cache.put("H", "H")
my_cache.print_cache()
my_cache.put("I", "I")
my_cache.print_cache()
my_cache.put("J", "J")
my_cache.print_cache()
my_cache.put("K", "K")
my_cache.print_cache()
| """ 4-main """
mru_cache = __import__('4-mru_cache').MRUCache
my_cache = mru_cache()
my_cache.put('A', 'Hello')
my_cache.put('B', 'World')
my_cache.put('C', 'Holberton')
my_cache.put('D', 'School')
my_cache.print_cache()
print(my_cache.get('B'))
my_cache.put('E', 'Battery')
my_cache.print_cache()
my_cache.put('C', 'Street')
my_cache.print_cache()
print(my_cache.get('A'))
print(my_cache.get('B'))
print(my_cache.get('C'))
my_cache.put('F', 'Mission')
my_cache.print_cache()
my_cache.put('G', 'San Francisco')
my_cache.print_cache()
my_cache.put('H', 'H')
my_cache.print_cache()
my_cache.put('I', 'I')
my_cache.print_cache()
my_cache.put('J', 'J')
my_cache.print_cache()
my_cache.put('K', 'K')
my_cache.print_cache() |
class Solution(object):
def findComplement(self, num):
"""
:type num: int
:rtype: int
"""
def change(i):
if i == '0':
return '1'
return '0'
l = ''
print(bin(num)[2:])
for i in bin(num)[2:]:
l += change(i)
return int(l, 2)
| class Solution(object):
def find_complement(self, num):
"""
:type num: int
:rtype: int
"""
def change(i):
if i == '0':
return '1'
return '0'
l = ''
print(bin(num)[2:])
for i in bin(num)[2:]:
l += change(i)
return int(l, 2) |
for a in range (2,21):
if a > 1:
for i in range(2,a):
if (a % i) == 0:
break
else:
print(a) | for a in range(2, 21):
if a > 1:
for i in range(2, a):
if a % i == 0:
break
else:
print(a) |
#!/usr/bin/env python3
# Simple data processing, extraction of GPGGA and GPRMC entries
# Source filename
FILENAME = "../data/GNSS_34_2020-02-23_16-20-44.txt"
# Output filename
OUTFILE = "../output/track.nmea"
if __name__ == "__main__":
outfile = open(OUTFILE, 'w')
with open(FILENAME, 'r') as f:
for line in f.readlines():
try:
data = line.split(';')[1].strip()
if data.startswith("$GPGGA") or data.startswith("$GPRMC"):
print(data)
outfile.write(data + '\n')
except:
pass
outfile.close()
f.close()
| filename = '../data/GNSS_34_2020-02-23_16-20-44.txt'
outfile = '../output/track.nmea'
if __name__ == '__main__':
outfile = open(OUTFILE, 'w')
with open(FILENAME, 'r') as f:
for line in f.readlines():
try:
data = line.split(';')[1].strip()
if data.startswith('$GPGGA') or data.startswith('$GPRMC'):
print(data)
outfile.write(data + '\n')
except:
pass
outfile.close()
f.close() |
registry = {}
def unmarshal(typestr, x):
try:
unmarshaller = registry[typestr]
except KeyError:
raise TypeError("No unmarshaller registered for '{}'".format(typestr))
return unmarshaller(x)
def register(typestr, unmarshaller):
if typestr in registry:
raise NameError(
"An unmarshaller is already registered for '{}'".format(typestr)
)
registry[typestr] = unmarshaller
def identity(x):
return x
def astype(typ):
"Unmarshal by casting into ``typ``, if not already an instance of ``typ``"
def unmarshaller(x):
return typ(x) if not isinstance(x, typ) else x
return unmarshaller
def unpack_into(typ):
"Unmarshal by unpacking a dict into the constructor for ``typ``"
def unmarshaller(x):
return typ(**x)
return unmarshaller
__all__ = ["unmarshal", "register", "identity", "unpack_into"]
| registry = {}
def unmarshal(typestr, x):
try:
unmarshaller = registry[typestr]
except KeyError:
raise type_error("No unmarshaller registered for '{}'".format(typestr))
return unmarshaller(x)
def register(typestr, unmarshaller):
if typestr in registry:
raise name_error("An unmarshaller is already registered for '{}'".format(typestr))
registry[typestr] = unmarshaller
def identity(x):
return x
def astype(typ):
"""Unmarshal by casting into ``typ``, if not already an instance of ``typ``"""
def unmarshaller(x):
return typ(x) if not isinstance(x, typ) else x
return unmarshaller
def unpack_into(typ):
"""Unmarshal by unpacking a dict into the constructor for ``typ``"""
def unmarshaller(x):
return typ(**x)
return unmarshaller
__all__ = ['unmarshal', 'register', 'identity', 'unpack_into'] |
def play(n=None):
if n is None:
while True:
try:
n = int(input('Input the grid size: '))
except ValueError:
print('Invalid input')
continue
if n <= 0:
print('Invalid input')
continue
break
grids = [[0]*n for _ in range(n)]
user = 1
print('Current board:')
print(*grids, sep='\n')
while True:
user_input = get_input(user, grids, n)
place_piece(user_input, user, grids)
print('Current board:')
print(*grids, sep='\n')
if check_won(user_input, user, n, grids):
print('Player', user, 'has won')
return
if not any(0 in grid for grid in grids):
return
user = 2 if user == 1 else 1
def get_input(user, grids, n):
instr = 'Input a slot player {0} from 1 to {1}: '.format(user, n)
while True:
try:
user_input = int(input(instr))
except ValueError:
print('invalid input:', user_input)
continue
if 0 > user_input or user_input > n+1:
print('invalid input:', user_input)
elif grids[0][user_input-1] != 0:
print('slot', user_input, 'is full try again')
else:
return user_input-1
def place_piece(user_input, user, grids):
for grid in grids[::-1]:
if not grid[user_input]:
grid[user_input] = user
return
# def check_won(user_input, user, n, grids):
# column = [i[user_input] for i in grids]
# print("column")
# print(column)
# if grids[user_input].count(user) == 4:
# print("aaaa"+ grids[user_input])
# return True
# index = 0
# for i in column:
# if i == 0:
# index += 1
# print(index)
# print("index: "+str(index))
# if column.count(user) == 4:
# return True
#play() | def play(n=None):
if n is None:
while True:
try:
n = int(input('Input the grid size: '))
except ValueError:
print('Invalid input')
continue
if n <= 0:
print('Invalid input')
continue
break
grids = [[0] * n for _ in range(n)]
user = 1
print('Current board:')
print(*grids, sep='\n')
while True:
user_input = get_input(user, grids, n)
place_piece(user_input, user, grids)
print('Current board:')
print(*grids, sep='\n')
if check_won(user_input, user, n, grids):
print('Player', user, 'has won')
return
if not any((0 in grid for grid in grids)):
return
user = 2 if user == 1 else 1
def get_input(user, grids, n):
instr = 'Input a slot player {0} from 1 to {1}: '.format(user, n)
while True:
try:
user_input = int(input(instr))
except ValueError:
print('invalid input:', user_input)
continue
if 0 > user_input or user_input > n + 1:
print('invalid input:', user_input)
elif grids[0][user_input - 1] != 0:
print('slot', user_input, 'is full try again')
else:
return user_input - 1
def place_piece(user_input, user, grids):
for grid in grids[::-1]:
if not grid[user_input]:
grid[user_input] = user
return |
def get_rate(numbers,
is_o2):
nb_bits = len(numbers[0])
assert all([len(n) == nb_bits for n in numbers])
current_numbers = [n for n in numbers]
i = 0
while len(current_numbers) > 1:
nb_ones = sum([elem[i] == '1' for elem in current_numbers])
nb_zeros = sum([elem[i] == '0' for elem in current_numbers])
bit_o2 = '1' if nb_ones >= nb_zeros else '0'
bit_co2 = '0' if nb_zeros <= nb_ones else '1'
bit = bit_o2 if is_o2 else bit_co2
current_numbers = [n for n in current_numbers if n[i] == bit]
i += 1
assert(1 == len(current_numbers))
result = int(current_numbers[0], base=2)
return result
def get_life_support(numbers):
o2_rate = get_rate(numbers, is_o2=True)
co2_rate = get_rate(numbers, is_o2=False)
result = o2_rate * co2_rate
return result
if __name__ == '__main__':
input_filename = 'input.txt'
# input_filename = 'sample-input.txt'
with open(input_filename, 'r') as input_file:
fc = input_file.read()
split = fc.split()
print(get_life_support(split))
| def get_rate(numbers, is_o2):
nb_bits = len(numbers[0])
assert all([len(n) == nb_bits for n in numbers])
current_numbers = [n for n in numbers]
i = 0
while len(current_numbers) > 1:
nb_ones = sum([elem[i] == '1' for elem in current_numbers])
nb_zeros = sum([elem[i] == '0' for elem in current_numbers])
bit_o2 = '1' if nb_ones >= nb_zeros else '0'
bit_co2 = '0' if nb_zeros <= nb_ones else '1'
bit = bit_o2 if is_o2 else bit_co2
current_numbers = [n for n in current_numbers if n[i] == bit]
i += 1
assert 1 == len(current_numbers)
result = int(current_numbers[0], base=2)
return result
def get_life_support(numbers):
o2_rate = get_rate(numbers, is_o2=True)
co2_rate = get_rate(numbers, is_o2=False)
result = o2_rate * co2_rate
return result
if __name__ == '__main__':
input_filename = 'input.txt'
with open(input_filename, 'r') as input_file:
fc = input_file.read()
split = fc.split()
print(get_life_support(split)) |
# Returns the sum of all multipliers of x for numbers from 1 to end.
def sumOfMultipliers(end, x):
n = end / x
return (n * (n + 1) / 2) * x
end = 999 # below 1000
x = 3
y = 5
# We have to subtract one sum of the multipliers of x * y because these multipliers take part in both of the sums of the multipliers of x and y and hence contribute twice in the final sum.
sum = sumOfMultipliers(end, x) + sumOfMultipliers(end, y) - sumOfMultipliers(end, x * y)
print(sum)
| def sum_of_multipliers(end, x):
n = end / x
return n * (n + 1) / 2 * x
end = 999
x = 3
y = 5
sum = sum_of_multipliers(end, x) + sum_of_multipliers(end, y) - sum_of_multipliers(end, x * y)
print(sum) |
def cmdissue(toissue, activesession):
ssh_stdin, ssh_stdout, ssh_stderr = activesession.exec_command(toissue)
return ssh_stdout.read().decode('UTF-8')
def commands_list(sshsession, commands):
for x in commands:
## call our imported function and save the value returned
resp = cmdissue(x, sshsession)
## if returned response is not null, print it out
if resp != "":
print(resp)
| def cmdissue(toissue, activesession):
(ssh_stdin, ssh_stdout, ssh_stderr) = activesession.exec_command(toissue)
return ssh_stdout.read().decode('UTF-8')
def commands_list(sshsession, commands):
for x in commands:
resp = cmdissue(x, sshsession)
if resp != '':
print(resp) |
List1 = []
List2 = []
List3 = []
List4 = []
List5 = [13,31,2,19,96]
statusList1 = 0
while statusList1 < 13:
inputList1 = str(input("Masukkan hewan bersayap : "))
statusList1 += 1
List1.append(inputList1)
print()
statusList2 = 0
while statusList2 < 5:
inputList2 = str(input("Masukkan hewan berkaki 2 : "))
statusList2 += 1
List2.append(inputList2)
print()
statusList3 = 0
while statusList3 < 5:
inputList3 = str(input("Masukkan nama teman terdekat anda : "))
statusList3 += 1
List3.append(inputList3)
print()
statusList4 = 0
while statusList4 < 5:
inputList4 = int(input("Masukkan tanggal lahir teman tersebut : "))
statusList4 += 1
List4.append(inputList4)
print(List1[0:5]+List4,'\n')
List3[4] = 'Rio'
print(List3,'\n')
tempList5 = List5.copy()
del tempList5[4]
del tempList5[2]
print(tempList5,'\n')
print(List4 + List5)
print("Nilai Max dari List 4 dan List 5 adalah",max(List4 + List5))
print("Nilai Min dari List 4 dan List 5 adalah",min(List4 + List5)) | list1 = []
list2 = []
list3 = []
list4 = []
list5 = [13, 31, 2, 19, 96]
status_list1 = 0
while statusList1 < 13:
input_list1 = str(input('Masukkan hewan bersayap : '))
status_list1 += 1
List1.append(inputList1)
print()
status_list2 = 0
while statusList2 < 5:
input_list2 = str(input('Masukkan hewan berkaki 2 : '))
status_list2 += 1
List2.append(inputList2)
print()
status_list3 = 0
while statusList3 < 5:
input_list3 = str(input('Masukkan nama teman terdekat anda : '))
status_list3 += 1
List3.append(inputList3)
print()
status_list4 = 0
while statusList4 < 5:
input_list4 = int(input('Masukkan tanggal lahir teman tersebut : '))
status_list4 += 1
List4.append(inputList4)
print(List1[0:5] + List4, '\n')
List3[4] = 'Rio'
print(List3, '\n')
temp_list5 = List5.copy()
del tempList5[4]
del tempList5[2]
print(tempList5, '\n')
print(List4 + List5)
print('Nilai Max dari List 4 dan List 5 adalah', max(List4 + List5))
print('Nilai Min dari List 4 dan List 5 adalah', min(List4 + List5)) |
class dataStore:
dataList=[]
symbolList=[]
optionList=[]
def __init__(self):
self.dataList=[]
self.symbolList=[]
self.optionList=[]
def reset(self):
self.dataList=[]
self.symbolList=[]
self.optionList=[]
| class Datastore:
data_list = []
symbol_list = []
option_list = []
def __init__(self):
self.dataList = []
self.symbolList = []
self.optionList = []
def reset(self):
self.dataList = []
self.symbolList = []
self.optionList = [] |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# @author jsbxyyx
# @since 1.0
class MessageType(object):
TYPE_GLOBAL_BEGIN = 1
TYPE_GLOBAL_BEGIN_RESULT = 2
TYPE_GLOBAL_COMMIT = 7
TYPE_GLOBAL_COMMIT_RESULT = 8
TYPE_GLOBAL_ROLLBACK = 9
TYPE_GLOBAL_ROLLBACK_RESULT = 10
TYPE_GLOBAL_STATUS = 15
TYPE_GLOBAL_STATUS_RESULT = 16
TYPE_GLOBAL_REPORT = 17
TYPE_GLOBAL_REPORT_RESULT = 18
TYPE_GLOBAL_LOCK_QUERY = 21
TYPE_GLOBAL_LOCK_QUERY_RESULT = 22
TYPE_BRANCH_COMMIT = 3
TYPE_BRANCH_COMMIT_RESULT = 4
TYPE_BRANCH_ROLLBACK = 5
TYPE_BRANCH_ROLLBACK_RESULT = 6
TYPE_BRANCH_REGISTER = 11
TYPE_BRANCH_REGISTER_RESULT = 12
TYPE_BRANCH_STATUS_REPORT = 13
TYPE_BRANCH_STATUS_REPORT_RESULT = 14
TYPE_SEATA_MERGE = 59
TYPE_SEATA_MERGE_RESULT = 60
TYPE_REG_CLT = 101
TYPE_REG_CLT_RESULT = 102
TYPE_REG_RM = 103
TYPE_REG_RM_RESULT = 104
TYPE_RM_DELETE_UNDOLOG = 111
TYPE_HEARTBEAT_MSG = 120
def __init__(self):
pass
| class Messagetype(object):
type_global_begin = 1
type_global_begin_result = 2
type_global_commit = 7
type_global_commit_result = 8
type_global_rollback = 9
type_global_rollback_result = 10
type_global_status = 15
type_global_status_result = 16
type_global_report = 17
type_global_report_result = 18
type_global_lock_query = 21
type_global_lock_query_result = 22
type_branch_commit = 3
type_branch_commit_result = 4
type_branch_rollback = 5
type_branch_rollback_result = 6
type_branch_register = 11
type_branch_register_result = 12
type_branch_status_report = 13
type_branch_status_report_result = 14
type_seata_merge = 59
type_seata_merge_result = 60
type_reg_clt = 101
type_reg_clt_result = 102
type_reg_rm = 103
type_reg_rm_result = 104
type_rm_delete_undolog = 111
type_heartbeat_msg = 120
def __init__(self):
pass |
def scoreOfParentheses(S):
total = 0
cur = 0
for i in range(len(S)):
if S[i] == "(":
cur += 1
elif S[i] == ")":
cur -= 1
if S[i-1] == "(":
total += 2**cur
return total
print(scoreOfParentheses("()")) # 1
print(scoreOfParentheses("()()")) # 2
print(scoreOfParentheses("((()))")) # 4
print(scoreOfParentheses("(()(()))")) # 6
print(scoreOfParentheses("(((()))()())")) # 12 | def score_of_parentheses(S):
total = 0
cur = 0
for i in range(len(S)):
if S[i] == '(':
cur += 1
elif S[i] == ')':
cur -= 1
if S[i - 1] == '(':
total += 2 ** cur
return total
print(score_of_parentheses('()'))
print(score_of_parentheses('()()'))
print(score_of_parentheses('((()))'))
print(score_of_parentheses('(()(()))'))
print(score_of_parentheses('(((()))()())')) |
c = input().split()
W, H, x, y, r = int(c[0]), int(c[1]), int(c[2]), int(c[3]), int(c[4])
if r <= x <= W - r and r <= y <= H - r:
print("Yes")
else:
print("No")
| c = input().split()
(w, h, x, y, r) = (int(c[0]), int(c[1]), int(c[2]), int(c[3]), int(c[4]))
if r <= x <= W - r and r <= y <= H - r:
print('Yes')
else:
print('No') |
# -*- coding: utf-8 -*-
numeros = []
for x in range(100):
numeros.append(int(input()))
print(max(numeros))
print(numeros.index(max(numeros))+1)
| numeros = []
for x in range(100):
numeros.append(int(input()))
print(max(numeros))
print(numeros.index(max(numeros)) + 1) |
# Python Program to Differentiate Between type() and isinstance()
class Polygon:
def sides_no(self):
pass
class Triangle(Polygon):
def area(self):
pass
obj_polygon = Polygon()
obj_triangle = Triangle()
print(type(obj_triangle) == Triangle) # true
print(type(obj_triangle) == Polygon) # false
print(isinstance(obj_polygon, Polygon)) # true
print(isinstance(obj_triangle, Polygon)) # true
| class Polygon:
def sides_no(self):
pass
class Triangle(Polygon):
def area(self):
pass
obj_polygon = polygon()
obj_triangle = triangle()
print(type(obj_triangle) == Triangle)
print(type(obj_triangle) == Polygon)
print(isinstance(obj_polygon, Polygon))
print(isinstance(obj_triangle, Polygon)) |
s1 = (2, 1.3, 'love', 5.6, 9, 12, False)
s2 = [True, 5, 'smile']
print('s1=',s1)
print('s1[:5]=',s1[:5])
print('s1[2:]=',s1[2:])
print('s1[0:5:2]=',s1[0:5:2])
print('s1[2:0:-1]=',s1[2:0:-1])
print('s1[-1]=',s1[-1])
print('s1[-3]=',s1[-3])
| s1 = (2, 1.3, 'love', 5.6, 9, 12, False)
s2 = [True, 5, 'smile']
print('s1=', s1)
print('s1[:5]=', s1[:5])
print('s1[2:]=', s1[2:])
print('s1[0:5:2]=', s1[0:5:2])
print('s1[2:0:-1]=', s1[2:0:-1])
print('s1[-1]=', s1[-1])
print('s1[-3]=', s1[-3]) |
r = requests.get('https://api.github.com/user', auth=('user', 'pass'))
r.status_code # -> 200
r.headers['content-type']
# -> 'application/json; charset=utf8'
r.encoding # -> 'utf-8'
r.text # -> u'{"type":"User"...'
r.json()
# -> {u'private_gists': 419, u'total_private_repos': 77, ...}
| r = requests.get('https://api.github.com/user', auth=('user', 'pass'))
r.status_code
r.headers['content-type']
r.encoding
r.text
r.json() |
class AttachedFile:
def __init__(self, original_name: str, tmp_file_path: str, need_content_analysis: bool, uid: str) -> None:
"""
Holds information about attached files.
:param original_name: Name of the file from which the attachments are extracted
:param tmp_file_path: path to the attachment file.
"""
self.original_name = original_name
self.tmp_file_path = tmp_file_path
self.need_content_analysis = need_content_analysis
self.uid = uid
def get_filename_in_path(self) -> str:
return self.tmp_file_path
def get_original_filename(self) -> str:
return self.original_name
| class Attachedfile:
def __init__(self, original_name: str, tmp_file_path: str, need_content_analysis: bool, uid: str) -> None:
"""
Holds information about attached files.
:param original_name: Name of the file from which the attachments are extracted
:param tmp_file_path: path to the attachment file.
"""
self.original_name = original_name
self.tmp_file_path = tmp_file_path
self.need_content_analysis = need_content_analysis
self.uid = uid
def get_filename_in_path(self) -> str:
return self.tmp_file_path
def get_original_filename(self) -> str:
return self.original_name |
class Joint:
def __init__(self, name, min_angle: float, max_angle: float):
self.name = name
self.min_angle = min_angle
self.max_angle = max_angle | class Joint:
def __init__(self, name, min_angle: float, max_angle: float):
self.name = name
self.min_angle = min_angle
self.max_angle = max_angle |
class Solution:
def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
wordSet = set(wordDict) # Converted to set for O(1)
# table to map a string to its corresponding words break
# {string: [['word1', 'word2'...], ['word3', 'word4', ...]]}
mem = defaultdict(list)
def _wordBreak_topdown(s):
""" return list of word lists """
# Because word is empty
if not s:
return [[]] # list of empty list
# return cached solution
if s in mem:
return mem[s]
# Start top-down hunt
for endIndex in range(1, len(s)+1):
# Prefix word (all prefix words)
word = s[:endIndex]
if word in wordSet:
# Like subsentence would be ("cat" + _wordBreak_topdown("sanddog")
for subsentence in _wordBreak_topdown(s[endIndex:]):
mem[s].append([word] + subsentence)
return mem[s]
# break the input string into lists of words list
_wordBreak_topdown(s)
# print(mem)
# chain up the lists of words into sentences.
return [" ".join(words) for words in mem[s]]
| class Solution:
def word_break(self, s: str, wordDict: List[str]) -> List[str]:
word_set = set(wordDict)
mem = defaultdict(list)
def _word_break_topdown(s):
""" return list of word lists """
if not s:
return [[]]
if s in mem:
return mem[s]
for end_index in range(1, len(s) + 1):
word = s[:endIndex]
if word in wordSet:
for subsentence in _word_break_topdown(s[endIndex:]):
mem[s].append([word] + subsentence)
return mem[s]
_word_break_topdown(s)
return [' '.join(words) for words in mem[s]] |
#
# PySNMP MIB module SONOMASYSTEMS-SONOMA-ATM-E3-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SONOMASYSTEMS-SONOMA-ATM-E3-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:09:18 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
ObjectIdentifier, Integer, OctetString = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "Integer", "OctetString")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
SingleValueConstraint, ValueRangeConstraint, ConstraintsIntersection, ValueSizeConstraint, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ValueRangeConstraint", "ConstraintsIntersection", "ValueSizeConstraint", "ConstraintsUnion")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
iso, Gauge32, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, NotificationType, ObjectIdentity, Bits, Counter32, Integer32, ModuleIdentity, IpAddress, Counter64, MibIdentifier, Unsigned32 = mibBuilder.importSymbols("SNMPv2-SMI", "iso", "Gauge32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "TimeTicks", "NotificationType", "ObjectIdentity", "Bits", "Counter32", "Integer32", "ModuleIdentity", "IpAddress", "Counter64", "MibIdentifier", "Unsigned32")
TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString")
sonomaATM, = mibBuilder.importSymbols("SONOMASYSTEMS-SONOMA-MIB", "sonomaATM")
sonomaE3ATMAdapterGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3))
atmE3ConfGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 1))
atmE3StatsGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2))
atmE3ConfPhyTable = MibTable((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 1, 1), )
if mibBuilder.loadTexts: atmE3ConfPhyTable.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3ConfPhyTable.setDescription('A table of physical layer configuration for the E3 interface')
atmE3ConfPhyEntry = MibTableRow((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 1, 1, 1), ).setIndexNames((0, "SONOMASYSTEMS-SONOMA-ATM-E3-MIB", "atmE3ConfPhysIndex"))
if mibBuilder.loadTexts: atmE3ConfPhyEntry.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3ConfPhyEntry.setDescription('A entry in the table, containing information about the physical layer of a E3 interface')
atmE3ConfPhysIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 1, 1, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: atmE3ConfPhysIndex.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3ConfPhysIndex.setDescription('The physical interface index.')
atmE3ConfFraming = MibTableColumn((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 1, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(2))).clone(namedValues=NamedValues(("framingE3", 2))).clone('framingE3')).setMaxAccess("readonly")
if mibBuilder.loadTexts: atmE3ConfFraming.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3ConfFraming.setDescription('Indicates the type of framing supported.')
atmE3ConfInsGFCBits = MibTableColumn((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 1, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone('disabled')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: atmE3ConfInsGFCBits.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3ConfInsGFCBits.setDescription('Enable/disable the insertion of GFC bits.')
atmE3ConfSerBipolarIO = MibTableColumn((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 1, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone('enabled')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: atmE3ConfSerBipolarIO.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3ConfSerBipolarIO.setDescription('Enable/disable bipolar serial I/O.')
atmE3ConfPayloadScrambling = MibTableColumn((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 1, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone('enabled')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: atmE3ConfPayloadScrambling.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3ConfPayloadScrambling.setDescription('Enable/disable payload scrambling.')
atmE3ConfOverheadProcessing = MibTableColumn((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 1, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone('enabled')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: atmE3ConfOverheadProcessing.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3ConfOverheadProcessing.setDescription('Enable/disable Overhead processing.')
atmE3ConfHDB3Encoding = MibTableColumn((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 1, 1, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone('enabled')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: atmE3ConfHDB3Encoding.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3ConfHDB3Encoding.setDescription('Enable/disable HDB3 (High Density Bipolar 3) Encoding.')
atmE3ConfLoopback = MibTableColumn((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 1, 1, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("disabled", 1), ("internal", 2), ("external", 3))).clone('disabled')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: atmE3ConfLoopback.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3ConfLoopback.setDescription('This object is used to modify the state of internal loopback....')
atmE3ConfCableLength = MibTableColumn((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 1, 1, 1, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("notGreaterThan225Feet", 1), ("greaterThan225Feet", 2))).clone('notGreaterThan225Feet')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: atmE3ConfCableLength.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3ConfCableLength.setDescription('Configure for the length of the cable.')
atmE3ConfInternalEqualizer = MibTableColumn((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 1, 1, 1, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("use", 1), ("bypass", 2))).clone('use')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: atmE3ConfInternalEqualizer.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3ConfInternalEqualizer.setDescription('Configure to use or bypass the internal equalizer.')
atmE3ConfFillerCells = MibTableColumn((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 1, 1, 1, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("unassigned", 1), ("idle", 2))).clone('unassigned')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: atmE3ConfFillerCells.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3ConfFillerCells.setDescription('This parameter indicates the type of filler cells to send when there are no data cells.')
atmE3ConfGenerateClock = MibTableColumn((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 1, 1, 1, 12), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2))).clone('disabled')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: atmE3ConfGenerateClock.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3ConfGenerateClock.setDescription('Enable/disable clock generation.')
atmE3StatsTable = MibTable((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1), )
if mibBuilder.loadTexts: atmE3StatsTable.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3StatsTable.setDescription('A table of physical layer statistics information for the E3 interface')
atmE3StatsEntry = MibTableRow((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1, 1), ).setIndexNames((0, "SONOMASYSTEMS-SONOMA-ATM-E3-MIB", "atmE3StatsPhysIndex"))
if mibBuilder.loadTexts: atmE3StatsEntry.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3StatsEntry.setDescription('A entry in the table, containing information about the physical layer of a E3 interface')
atmE3StatsPhysIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: atmE3StatsPhysIndex.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3StatsPhysIndex.setDescription('The physical interface index.')
atmE3StatsNoSignals = MibTableColumn((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1, 1, 2), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: atmE3StatsNoSignals.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3StatsNoSignals.setDescription('No signal error counter.')
atmE3StatsNoE3Frames = MibTableColumn((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1, 1, 3), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: atmE3StatsNoE3Frames.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3StatsNoE3Frames.setDescription('No E3 frames error counter.')
atmE3StatsFrameErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1, 1, 4), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: atmE3StatsFrameErrors.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3StatsFrameErrors.setDescription('A count of the number of Frames in error.')
atmE3StatsHECErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1, 1, 5), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: atmE3StatsHECErrors.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3StatsHECErrors.setDescription('HEC (Header Error Check) error counter.')
atmE3StatsEMErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1, 1, 6), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: atmE3StatsEMErrors.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3StatsEMErrors.setDescription('EM (error monitoring) error counter.')
atmE3StatsFeBlockErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1, 1, 7), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: atmE3StatsFeBlockErrors.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3StatsFeBlockErrors.setDescription('Far End Block error counter.')
atmE3StatsBpvErrors = MibTableColumn((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1, 1, 8), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: atmE3StatsBpvErrors.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3StatsBpvErrors.setDescription('Bipolar Violation error counter.')
atmE3StatsPayloadTypeMismatches = MibTableColumn((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1, 1, 9), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: atmE3StatsPayloadTypeMismatches.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3StatsPayloadTypeMismatches.setDescription('Payload Type Mismatches error counter.')
atmE3StatsTimingMarkers = MibTableColumn((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1, 1, 10), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: atmE3StatsTimingMarkers.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3StatsTimingMarkers.setDescription('Timing Markers error counter.')
atmE3StatsAISDetects = MibTableColumn((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1, 1, 11), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: atmE3StatsAISDetects.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3StatsAISDetects.setDescription('AIS (Alarm Indication Signal) detect counter.')
atmE3StatsRDIDetects = MibTableColumn((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1, 1, 12), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: atmE3StatsRDIDetects.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3StatsRDIDetects.setDescription('RDI (Remote Defect Indication) error counter.')
atmE3StatsSignalLoss = MibTableColumn((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1, 1, 13), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("true", 1), ("false", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: atmE3StatsSignalLoss.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3StatsSignalLoss.setDescription('Signal loss indication.')
atmE3StatsFrameLoss = MibTableColumn((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1, 1, 14), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("true", 1), ("false", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: atmE3StatsFrameLoss.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3StatsFrameLoss.setDescription('Frame loss indication.')
atmE3StatsSyncLoss = MibTableColumn((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1, 1, 15), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("true", 1), ("false", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: atmE3StatsSyncLoss.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3StatsSyncLoss.setDescription('Synchronization loss counter.')
atmE3StatsOutOfCell = MibTableColumn((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1, 1, 16), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("true", 1), ("false", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: atmE3StatsOutOfCell.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3StatsOutOfCell.setDescription('ATM out-of-cell delineation.')
atmE3StatsFIFOOverflow = MibTableColumn((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1, 1, 17), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("true", 1), ("false", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: atmE3StatsFIFOOverflow.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3StatsFIFOOverflow.setDescription('ATM FIFO overflow.')
atmE3StatsPayloadTypeMismatch = MibTableColumn((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1, 1, 18), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("true", 1), ("false", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: atmE3StatsPayloadTypeMismatch.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3StatsPayloadTypeMismatch.setDescription('The Payload Type Mismatch state.')
atmE3StatsTimingMarker = MibTableColumn((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1, 1, 19), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("true", 1), ("false", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: atmE3StatsTimingMarker.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3StatsTimingMarker.setDescription('The Timing Marker state.')
atmE3StatsAISDetect = MibTableColumn((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1, 1, 20), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("true", 1), ("false", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: atmE3StatsAISDetect.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3StatsAISDetect.setDescription('The AIS (Alarm Indication Signal) state.')
atmE3StatsRDIDetect = MibTableColumn((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1, 1, 21), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("true", 1), ("false", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: atmE3StatsRDIDetect.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3StatsRDIDetect.setDescription('RDI (Remote Defect Indication) state.')
atmE3StatsClearCounters = MibTableColumn((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1, 1, 22), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("true", 1), ("false", 2))).clone('false')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: atmE3StatsClearCounters.setStatus('mandatory')
if mibBuilder.loadTexts: atmE3StatsClearCounters.setDescription('Clear all counters in this group ONLY.')
mibBuilder.exportSymbols("SONOMASYSTEMS-SONOMA-ATM-E3-MIB", atmE3ConfLoopback=atmE3ConfLoopback, atmE3StatsRDIDetect=atmE3StatsRDIDetect, atmE3StatsOutOfCell=atmE3StatsOutOfCell, atmE3ConfPhyTable=atmE3ConfPhyTable, atmE3ConfInternalEqualizer=atmE3ConfInternalEqualizer, atmE3StatsNoE3Frames=atmE3StatsNoE3Frames, atmE3StatsHECErrors=atmE3StatsHECErrors, atmE3ConfSerBipolarIO=atmE3ConfSerBipolarIO, atmE3ConfOverheadProcessing=atmE3ConfOverheadProcessing, atmE3ConfHDB3Encoding=atmE3ConfHDB3Encoding, atmE3StatsFeBlockErrors=atmE3StatsFeBlockErrors, atmE3StatsSignalLoss=atmE3StatsSignalLoss, atmE3ConfPhysIndex=atmE3ConfPhysIndex, atmE3ConfPhyEntry=atmE3ConfPhyEntry, atmE3StatsFrameLoss=atmE3StatsFrameLoss, atmE3ConfPayloadScrambling=atmE3ConfPayloadScrambling, atmE3StatsNoSignals=atmE3StatsNoSignals, atmE3StatsTimingMarker=atmE3StatsTimingMarker, atmE3StatsEMErrors=atmE3StatsEMErrors, atmE3StatsClearCounters=atmE3StatsClearCounters, atmE3ConfGenerateClock=atmE3ConfGenerateClock, atmE3StatsTable=atmE3StatsTable, sonomaE3ATMAdapterGroup=sonomaE3ATMAdapterGroup, atmE3StatsPayloadTypeMismatch=atmE3StatsPayloadTypeMismatch, atmE3ConfInsGFCBits=atmE3ConfInsGFCBits, atmE3ConfFraming=atmE3ConfFraming, atmE3StatsRDIDetects=atmE3StatsRDIDetects, atmE3StatsEntry=atmE3StatsEntry, atmE3ConfFillerCells=atmE3ConfFillerCells, atmE3StatsPhysIndex=atmE3StatsPhysIndex, atmE3ConfCableLength=atmE3ConfCableLength, atmE3StatsBpvErrors=atmE3StatsBpvErrors, atmE3StatsTimingMarkers=atmE3StatsTimingMarkers, atmE3StatsAISDetect=atmE3StatsAISDetect, atmE3ConfGroup=atmE3ConfGroup, atmE3StatsFrameErrors=atmE3StatsFrameErrors, atmE3StatsPayloadTypeMismatches=atmE3StatsPayloadTypeMismatches, atmE3StatsSyncLoss=atmE3StatsSyncLoss, atmE3StatsGroup=atmE3StatsGroup, atmE3StatsAISDetects=atmE3StatsAISDetects, atmE3StatsFIFOOverflow=atmE3StatsFIFOOverflow)
| (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, value_range_constraint, constraints_intersection, value_size_constraint, constraints_union) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'SingleValueConstraint', 'ValueRangeConstraint', 'ConstraintsIntersection', 'ValueSizeConstraint', 'ConstraintsUnion')
(notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance')
(iso, gauge32, mib_scalar, mib_table, mib_table_row, mib_table_column, time_ticks, notification_type, object_identity, bits, counter32, integer32, module_identity, ip_address, counter64, mib_identifier, unsigned32) = mibBuilder.importSymbols('SNMPv2-SMI', 'iso', 'Gauge32', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'TimeTicks', 'NotificationType', 'ObjectIdentity', 'Bits', 'Counter32', 'Integer32', 'ModuleIdentity', 'IpAddress', 'Counter64', 'MibIdentifier', 'Unsigned32')
(textual_convention, display_string) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'DisplayString')
(sonoma_atm,) = mibBuilder.importSymbols('SONOMASYSTEMS-SONOMA-MIB', 'sonomaATM')
sonoma_e3_atm_adapter_group = mib_identifier((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3))
atm_e3_conf_group = mib_identifier((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 1))
atm_e3_stats_group = mib_identifier((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2))
atm_e3_conf_phy_table = mib_table((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 1, 1))
if mibBuilder.loadTexts:
atmE3ConfPhyTable.setStatus('mandatory')
if mibBuilder.loadTexts:
atmE3ConfPhyTable.setDescription('A table of physical layer configuration for the E3 interface')
atm_e3_conf_phy_entry = mib_table_row((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 1, 1, 1)).setIndexNames((0, 'SONOMASYSTEMS-SONOMA-ATM-E3-MIB', 'atmE3ConfPhysIndex'))
if mibBuilder.loadTexts:
atmE3ConfPhyEntry.setStatus('mandatory')
if mibBuilder.loadTexts:
atmE3ConfPhyEntry.setDescription('A entry in the table, containing information about the physical layer of a E3 interface')
atm_e3_conf_phys_index = mib_table_column((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 1, 1, 1, 1), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
atmE3ConfPhysIndex.setStatus('mandatory')
if mibBuilder.loadTexts:
atmE3ConfPhysIndex.setDescription('The physical interface index.')
atm_e3_conf_framing = mib_table_column((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 1, 1, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(2))).clone(namedValues=named_values(('framingE3', 2))).clone('framingE3')).setMaxAccess('readonly')
if mibBuilder.loadTexts:
atmE3ConfFraming.setStatus('mandatory')
if mibBuilder.loadTexts:
atmE3ConfFraming.setDescription('Indicates the type of framing supported.')
atm_e3_conf_ins_gfc_bits = mib_table_column((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 1, 1, 1, 3), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('enabled', 1), ('disabled', 2))).clone('disabled')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
atmE3ConfInsGFCBits.setStatus('mandatory')
if mibBuilder.loadTexts:
atmE3ConfInsGFCBits.setDescription('Enable/disable the insertion of GFC bits.')
atm_e3_conf_ser_bipolar_io = mib_table_column((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 1, 1, 1, 4), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('enabled', 1), ('disabled', 2))).clone('enabled')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
atmE3ConfSerBipolarIO.setStatus('mandatory')
if mibBuilder.loadTexts:
atmE3ConfSerBipolarIO.setDescription('Enable/disable bipolar serial I/O.')
atm_e3_conf_payload_scrambling = mib_table_column((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 1, 1, 1, 5), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('enabled', 1), ('disabled', 2))).clone('enabled')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
atmE3ConfPayloadScrambling.setStatus('mandatory')
if mibBuilder.loadTexts:
atmE3ConfPayloadScrambling.setDescription('Enable/disable payload scrambling.')
atm_e3_conf_overhead_processing = mib_table_column((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 1, 1, 1, 6), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('enabled', 1), ('disabled', 2))).clone('enabled')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
atmE3ConfOverheadProcessing.setStatus('mandatory')
if mibBuilder.loadTexts:
atmE3ConfOverheadProcessing.setDescription('Enable/disable Overhead processing.')
atm_e3_conf_hdb3_encoding = mib_table_column((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 1, 1, 1, 7), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('enabled', 1), ('disabled', 2))).clone('enabled')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
atmE3ConfHDB3Encoding.setStatus('mandatory')
if mibBuilder.loadTexts:
atmE3ConfHDB3Encoding.setDescription('Enable/disable HDB3 (High Density Bipolar 3) Encoding.')
atm_e3_conf_loopback = mib_table_column((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 1, 1, 1, 8), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('disabled', 1), ('internal', 2), ('external', 3))).clone('disabled')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
atmE3ConfLoopback.setStatus('mandatory')
if mibBuilder.loadTexts:
atmE3ConfLoopback.setDescription('This object is used to modify the state of internal loopback....')
atm_e3_conf_cable_length = mib_table_column((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 1, 1, 1, 9), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('notGreaterThan225Feet', 1), ('greaterThan225Feet', 2))).clone('notGreaterThan225Feet')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
atmE3ConfCableLength.setStatus('mandatory')
if mibBuilder.loadTexts:
atmE3ConfCableLength.setDescription('Configure for the length of the cable.')
atm_e3_conf_internal_equalizer = mib_table_column((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 1, 1, 1, 10), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('use', 1), ('bypass', 2))).clone('use')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
atmE3ConfInternalEqualizer.setStatus('mandatory')
if mibBuilder.loadTexts:
atmE3ConfInternalEqualizer.setDescription('Configure to use or bypass the internal equalizer.')
atm_e3_conf_filler_cells = mib_table_column((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 1, 1, 1, 11), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('unassigned', 1), ('idle', 2))).clone('unassigned')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
atmE3ConfFillerCells.setStatus('mandatory')
if mibBuilder.loadTexts:
atmE3ConfFillerCells.setDescription('This parameter indicates the type of filler cells to send when there are no data cells.')
atm_e3_conf_generate_clock = mib_table_column((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 1, 1, 1, 12), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('enabled', 1), ('disabled', 2))).clone('disabled')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
atmE3ConfGenerateClock.setStatus('mandatory')
if mibBuilder.loadTexts:
atmE3ConfGenerateClock.setDescription('Enable/disable clock generation.')
atm_e3_stats_table = mib_table((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1))
if mibBuilder.loadTexts:
atmE3StatsTable.setStatus('mandatory')
if mibBuilder.loadTexts:
atmE3StatsTable.setDescription('A table of physical layer statistics information for the E3 interface')
atm_e3_stats_entry = mib_table_row((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1, 1)).setIndexNames((0, 'SONOMASYSTEMS-SONOMA-ATM-E3-MIB', 'atmE3StatsPhysIndex'))
if mibBuilder.loadTexts:
atmE3StatsEntry.setStatus('mandatory')
if mibBuilder.loadTexts:
atmE3StatsEntry.setDescription('A entry in the table, containing information about the physical layer of a E3 interface')
atm_e3_stats_phys_index = mib_table_column((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1, 1, 1), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
atmE3StatsPhysIndex.setStatus('mandatory')
if mibBuilder.loadTexts:
atmE3StatsPhysIndex.setDescription('The physical interface index.')
atm_e3_stats_no_signals = mib_table_column((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1, 1, 2), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
atmE3StatsNoSignals.setStatus('mandatory')
if mibBuilder.loadTexts:
atmE3StatsNoSignals.setDescription('No signal error counter.')
atm_e3_stats_no_e3_frames = mib_table_column((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1, 1, 3), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
atmE3StatsNoE3Frames.setStatus('mandatory')
if mibBuilder.loadTexts:
atmE3StatsNoE3Frames.setDescription('No E3 frames error counter.')
atm_e3_stats_frame_errors = mib_table_column((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1, 1, 4), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
atmE3StatsFrameErrors.setStatus('mandatory')
if mibBuilder.loadTexts:
atmE3StatsFrameErrors.setDescription('A count of the number of Frames in error.')
atm_e3_stats_hec_errors = mib_table_column((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1, 1, 5), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
atmE3StatsHECErrors.setStatus('mandatory')
if mibBuilder.loadTexts:
atmE3StatsHECErrors.setDescription('HEC (Header Error Check) error counter.')
atm_e3_stats_em_errors = mib_table_column((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1, 1, 6), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
atmE3StatsEMErrors.setStatus('mandatory')
if mibBuilder.loadTexts:
atmE3StatsEMErrors.setDescription('EM (error monitoring) error counter.')
atm_e3_stats_fe_block_errors = mib_table_column((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1, 1, 7), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
atmE3StatsFeBlockErrors.setStatus('mandatory')
if mibBuilder.loadTexts:
atmE3StatsFeBlockErrors.setDescription('Far End Block error counter.')
atm_e3_stats_bpv_errors = mib_table_column((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1, 1, 8), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
atmE3StatsBpvErrors.setStatus('mandatory')
if mibBuilder.loadTexts:
atmE3StatsBpvErrors.setDescription('Bipolar Violation error counter.')
atm_e3_stats_payload_type_mismatches = mib_table_column((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1, 1, 9), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
atmE3StatsPayloadTypeMismatches.setStatus('mandatory')
if mibBuilder.loadTexts:
atmE3StatsPayloadTypeMismatches.setDescription('Payload Type Mismatches error counter.')
atm_e3_stats_timing_markers = mib_table_column((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1, 1, 10), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
atmE3StatsTimingMarkers.setStatus('mandatory')
if mibBuilder.loadTexts:
atmE3StatsTimingMarkers.setDescription('Timing Markers error counter.')
atm_e3_stats_ais_detects = mib_table_column((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1, 1, 11), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
atmE3StatsAISDetects.setStatus('mandatory')
if mibBuilder.loadTexts:
atmE3StatsAISDetects.setDescription('AIS (Alarm Indication Signal) detect counter.')
atm_e3_stats_rdi_detects = mib_table_column((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1, 1, 12), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
atmE3StatsRDIDetects.setStatus('mandatory')
if mibBuilder.loadTexts:
atmE3StatsRDIDetects.setDescription('RDI (Remote Defect Indication) error counter.')
atm_e3_stats_signal_loss = mib_table_column((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1, 1, 13), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('true', 1), ('false', 2)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
atmE3StatsSignalLoss.setStatus('mandatory')
if mibBuilder.loadTexts:
atmE3StatsSignalLoss.setDescription('Signal loss indication.')
atm_e3_stats_frame_loss = mib_table_column((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1, 1, 14), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('true', 1), ('false', 2)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
atmE3StatsFrameLoss.setStatus('mandatory')
if mibBuilder.loadTexts:
atmE3StatsFrameLoss.setDescription('Frame loss indication.')
atm_e3_stats_sync_loss = mib_table_column((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1, 1, 15), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('true', 1), ('false', 2)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
atmE3StatsSyncLoss.setStatus('mandatory')
if mibBuilder.loadTexts:
atmE3StatsSyncLoss.setDescription('Synchronization loss counter.')
atm_e3_stats_out_of_cell = mib_table_column((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1, 1, 16), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('true', 1), ('false', 2)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
atmE3StatsOutOfCell.setStatus('mandatory')
if mibBuilder.loadTexts:
atmE3StatsOutOfCell.setDescription('ATM out-of-cell delineation.')
atm_e3_stats_fifo_overflow = mib_table_column((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1, 1, 17), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('true', 1), ('false', 2)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
atmE3StatsFIFOOverflow.setStatus('mandatory')
if mibBuilder.loadTexts:
atmE3StatsFIFOOverflow.setDescription('ATM FIFO overflow.')
atm_e3_stats_payload_type_mismatch = mib_table_column((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1, 1, 18), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('true', 1), ('false', 2)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
atmE3StatsPayloadTypeMismatch.setStatus('mandatory')
if mibBuilder.loadTexts:
atmE3StatsPayloadTypeMismatch.setDescription('The Payload Type Mismatch state.')
atm_e3_stats_timing_marker = mib_table_column((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1, 1, 19), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('true', 1), ('false', 2)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
atmE3StatsTimingMarker.setStatus('mandatory')
if mibBuilder.loadTexts:
atmE3StatsTimingMarker.setDescription('The Timing Marker state.')
atm_e3_stats_ais_detect = mib_table_column((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1, 1, 20), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('true', 1), ('false', 2)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
atmE3StatsAISDetect.setStatus('mandatory')
if mibBuilder.loadTexts:
atmE3StatsAISDetect.setDescription('The AIS (Alarm Indication Signal) state.')
atm_e3_stats_rdi_detect = mib_table_column((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1, 1, 21), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('true', 1), ('false', 2)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
atmE3StatsRDIDetect.setStatus('mandatory')
if mibBuilder.loadTexts:
atmE3StatsRDIDetect.setDescription('RDI (Remote Defect Indication) state.')
atm_e3_stats_clear_counters = mib_table_column((1, 3, 6, 1, 4, 1, 2926, 25, 7, 3, 2, 1, 1, 22), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('true', 1), ('false', 2))).clone('false')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
atmE3StatsClearCounters.setStatus('mandatory')
if mibBuilder.loadTexts:
atmE3StatsClearCounters.setDescription('Clear all counters in this group ONLY.')
mibBuilder.exportSymbols('SONOMASYSTEMS-SONOMA-ATM-E3-MIB', atmE3ConfLoopback=atmE3ConfLoopback, atmE3StatsRDIDetect=atmE3StatsRDIDetect, atmE3StatsOutOfCell=atmE3StatsOutOfCell, atmE3ConfPhyTable=atmE3ConfPhyTable, atmE3ConfInternalEqualizer=atmE3ConfInternalEqualizer, atmE3StatsNoE3Frames=atmE3StatsNoE3Frames, atmE3StatsHECErrors=atmE3StatsHECErrors, atmE3ConfSerBipolarIO=atmE3ConfSerBipolarIO, atmE3ConfOverheadProcessing=atmE3ConfOverheadProcessing, atmE3ConfHDB3Encoding=atmE3ConfHDB3Encoding, atmE3StatsFeBlockErrors=atmE3StatsFeBlockErrors, atmE3StatsSignalLoss=atmE3StatsSignalLoss, atmE3ConfPhysIndex=atmE3ConfPhysIndex, atmE3ConfPhyEntry=atmE3ConfPhyEntry, atmE3StatsFrameLoss=atmE3StatsFrameLoss, atmE3ConfPayloadScrambling=atmE3ConfPayloadScrambling, atmE3StatsNoSignals=atmE3StatsNoSignals, atmE3StatsTimingMarker=atmE3StatsTimingMarker, atmE3StatsEMErrors=atmE3StatsEMErrors, atmE3StatsClearCounters=atmE3StatsClearCounters, atmE3ConfGenerateClock=atmE3ConfGenerateClock, atmE3StatsTable=atmE3StatsTable, sonomaE3ATMAdapterGroup=sonomaE3ATMAdapterGroup, atmE3StatsPayloadTypeMismatch=atmE3StatsPayloadTypeMismatch, atmE3ConfInsGFCBits=atmE3ConfInsGFCBits, atmE3ConfFraming=atmE3ConfFraming, atmE3StatsRDIDetects=atmE3StatsRDIDetects, atmE3StatsEntry=atmE3StatsEntry, atmE3ConfFillerCells=atmE3ConfFillerCells, atmE3StatsPhysIndex=atmE3StatsPhysIndex, atmE3ConfCableLength=atmE3ConfCableLength, atmE3StatsBpvErrors=atmE3StatsBpvErrors, atmE3StatsTimingMarkers=atmE3StatsTimingMarkers, atmE3StatsAISDetect=atmE3StatsAISDetect, atmE3ConfGroup=atmE3ConfGroup, atmE3StatsFrameErrors=atmE3StatsFrameErrors, atmE3StatsPayloadTypeMismatches=atmE3StatsPayloadTypeMismatches, atmE3StatsSyncLoss=atmE3StatsSyncLoss, atmE3StatsGroup=atmE3StatsGroup, atmE3StatsAISDetects=atmE3StatsAISDetects, atmE3StatsFIFOOverflow=atmE3StatsFIFOOverflow) |
def shift(a):
last = a[-1]
a.insert(0, last)
a.pop()
return a
def f(a,b):
a = list(a)
b = list(b)
for i in range(len(a)):
a = shift(a)
if a == b:
return True
return False
f('abcde', 'abced')
| def shift(a):
last = a[-1]
a.insert(0, last)
a.pop()
return a
def f(a, b):
a = list(a)
b = list(b)
for i in range(len(a)):
a = shift(a)
if a == b:
return True
return False
f('abcde', 'abced') |
def extractBinggoCorp(item):
"""
# Binggo & Corp Translations
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or 'preview' in item['title'].lower():
return None
if 'Jiang Ye' in item['title'] and 'Chapter' in item['title']:
return buildReleaseMessageWithType(item, 'Jiang Ye', vol, chp, frag=frag, postfix=postfix)
if 'Ze Tian Ji' in item['title'] and 'Chapter' in item['title']:
return buildReleaseMessageWithType(item, 'Ze Tian Ji', vol, chp, frag=frag, postfix=postfix)
return False
| def extract_binggo_corp(item):
"""
# Binggo & Corp Translations
"""
(vol, chp, frag, postfix) = extract_vol_chapter_fragment_postfix(item['title'])
if not (chp or vol) or 'preview' in item['title'].lower():
return None
if 'Jiang Ye' in item['title'] and 'Chapter' in item['title']:
return build_release_message_with_type(item, 'Jiang Ye', vol, chp, frag=frag, postfix=postfix)
if 'Ze Tian Ji' in item['title'] and 'Chapter' in item['title']:
return build_release_message_with_type(item, 'Ze Tian Ji', vol, chp, frag=frag, postfix=postfix)
return False |
class BaloneyInterpreter(object):
def __init__(self, prog):
self.prog = prog
def run(self):
self.vars = {} # All variables
self.lists = {} # List variables
self.error = 0 # Indicates program error
self.stat = list(self.prog) # Ordered list of all line numbers
self.stat.sort()
print(self.stat)
| class Baloneyinterpreter(object):
def __init__(self, prog):
self.prog = prog
def run(self):
self.vars = {}
self.lists = {}
self.error = 0
self.stat = list(self.prog)
self.stat.sort()
print(self.stat) |
#!/bin/python3
def plus_minus(array):
ratio_positive = round(sum(i > 0 for i in array) / len(array), 6)
ratio_negative = round(sum(i < 0 for i in array) / len(array), 6)
ratio_zero = round(sum(i == 0 for i in array) / len(array), 6)
return ratio_positive, ratio_negative, ratio_zero
def test_plus_minus():
"""Test for plus_minus function."""
assert plus_minus(array=[1, 1, 0, -1, -1]) == (
0.400000,
0.400000,
0.200000,
)
assert plus_minus(array=[-4, 3, -9, 0, 4, 1]) == (
0.500000,
0.333333,
0.166667,
)
test_plus_minus()
n = int(input())
array = list(map(int, input().rstrip().split()))
for ratio in plus_minus(array):
print(ratio)
| def plus_minus(array):
ratio_positive = round(sum((i > 0 for i in array)) / len(array), 6)
ratio_negative = round(sum((i < 0 for i in array)) / len(array), 6)
ratio_zero = round(sum((i == 0 for i in array)) / len(array), 6)
return (ratio_positive, ratio_negative, ratio_zero)
def test_plus_minus():
"""Test for plus_minus function."""
assert plus_minus(array=[1, 1, 0, -1, -1]) == (0.4, 0.4, 0.2)
assert plus_minus(array=[-4, 3, -9, 0, 4, 1]) == (0.5, 0.333333, 0.166667)
test_plus_minus()
n = int(input())
array = list(map(int, input().rstrip().split()))
for ratio in plus_minus(array):
print(ratio) |
"""
Dictionary examples.
The intention is that you would use the code in the functions rather
than the functions themselves.
"""
def create_dict():
"""
Create a new dictionary.
Example from: https://docs.python.org/3/library/stdtypes.html#mapping-types-dict
>>> a = dict(one=1, two=2, three=3)
>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> e = dict({'three': 3, 'one': 1, 'two': 2})
>>> a == b == c == d == e
True
"""
return dict()
def copy_dict(other_dict):
"""
Returns a copy of the dictionary, separate from the original.
This separation is only at the top-level keys.
If you delete a key in the original, it will not change the copy.
>>> d1 = dict(a=1, b=2)
>>> d2 = dict(**d1)
>>> del d1['a']
>>> 'a' in d1
False
>>> 'a' in d2
True
If any of the top-level values are mutable (list, dict) then changes
to the original will appear in the copy.
>>> d1 = dict(a=[1, 2], b=[3, 4])
>>> d2 = dict(**d1)
>>> d1['a'].pop()
2
>>> d1['a']
[1]
>>> d1['a'] == d2['a']
True
Tested in Python 3.4.
"""
new_dict = dict(**other_dict)
return new_dict
def update_dict(original, other):
"""
Update the original dict with values from the other.
If you delete a key in the other, it will not change the original.
>>> d1 = dict(a=1)
>>> d2 = dict(b=2)
>>> d1
{'a': 1}
>>> d2
{'b': 2}
>>> d1.update(d2)
>>> d1
{'a': 1, 'b': 2}
>>> d2
{'b': 2}
Tested in Python 3.4.
"""
original.update(other)
return original
| """
Dictionary examples.
The intention is that you would use the code in the functions rather
than the functions themselves.
"""
def create_dict():
"""
Create a new dictionary.
Example from: https://docs.python.org/3/library/stdtypes.html#mapping-types-dict
>>> a = dict(one=1, two=2, three=3)
>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> e = dict({'three': 3, 'one': 1, 'two': 2})
>>> a == b == c == d == e
True
"""
return dict()
def copy_dict(other_dict):
"""
Returns a copy of the dictionary, separate from the original.
This separation is only at the top-level keys.
If you delete a key in the original, it will not change the copy.
>>> d1 = dict(a=1, b=2)
>>> d2 = dict(**d1)
>>> del d1['a']
>>> 'a' in d1
False
>>> 'a' in d2
True
If any of the top-level values are mutable (list, dict) then changes
to the original will appear in the copy.
>>> d1 = dict(a=[1, 2], b=[3, 4])
>>> d2 = dict(**d1)
>>> d1['a'].pop()
2
>>> d1['a']
[1]
>>> d1['a'] == d2['a']
True
Tested in Python 3.4.
"""
new_dict = dict(**other_dict)
return new_dict
def update_dict(original, other):
"""
Update the original dict with values from the other.
If you delete a key in the other, it will not change the original.
>>> d1 = dict(a=1)
>>> d2 = dict(b=2)
>>> d1
{'a': 1}
>>> d2
{'b': 2}
>>> d1.update(d2)
>>> d1
{'a': 1, 'b': 2}
>>> d2
{'b': 2}
Tested in Python 3.4.
"""
original.update(other)
return original |
# Heap
# CLRS Chapter 6 Page 152, 154, 157, 163, 164
# For CPython's implementation see:
# https://hg.python.org/cpython/file/2.7/Lib/heapq.py
def max_heapify(heap, node):
left = _left(node)
right = _right(node)
largest = node
if left < size(heap) and heap[largest] < heap[left]:
largest = left
if right < size(heap) and heap[largest] < heap[right]:
largest = right
if largest != node:
_swap(heap, node, largest)
max_heapify(heap, largest)
def build_max_heap(heap):
# Run max_heapify buttom-up.
for node in reversed(range((len(heap) - 1) // 2 + 1)):
max_heapify(heap, node)
return heap
def remove_last(heap):
return heap.pop()
def remove(heap, node):
if node >= size(heap):
raise Exception("Node does not exist in the heap.")
# Swap the item with the last item if needed.
last = size(heap) - 1
if node != last:
_swap(heap, node, last)
# Remove the last item.
item = remove_last(heap)
# Fix the heap property.
max_heapify(heap, node)
return item
def remove_top(heap):
return remove(heap, _root())
def decrease_key(heap, node, item):
if heap[node] < item:
raise Exception("The new key is lsrger than the current key.")
heap[node] = item
_move_down(heap, node)
def increase_key(heap, node, item):
if item < heap[node]:
raise Exception("The new key is smaller than the current key.")
heap[node] = item
_move_up(heap, node)
def insert(heap, item):
# Put the item at the end.
node = size(heap)
heap.append(item)
_move_up(heap, node)
def top(heap):
"""Returns the top item in the heap."""
return heap[_root()]
def size(heap):
"""The number of items in the heap."""
return len(heap)
def empty(heap):
"""Check if the heap is empty."""
return size(heap) == 0
def _swap(heap, i, j):
"""Swaps nodes i and j in heap."""
heap[i], heap[j] = heap[j], heap[i]
def _parent(node):
"""Parent of a node. The root points to itself."""
if node == _root():
return _root()
return (node + 1) // 2 - 1
def _left(node):
"""The _left child of a node."""
return 2 * node + 1
def _right(node):
"""The right child of a node."""
return 2 * node + 2
def _root():
"""Returns the root node."""
return 0
def _move_down(heap, node):
# Move down the item as long as needed.
# This is an iterative version of max_heapify.
while node < size(heap):
left = _left(node)
right = _right(node)
largest = node
if left < size(heap) and heap[largest] < heap[left]:
largest = left
if right < size(heap) and heap[largest] < heap[right]:
largest = right
if largest == node:
break
_swap(heap, node, largest)
node = largest
def _move_up(heap, node):
# Move up the item as long as needed.
while node != _root() and heap[_parent(node)] < item:
_swap(heap, node, _parent(node))
node = _parent(node)
| def max_heapify(heap, node):
left = _left(node)
right = _right(node)
largest = node
if left < size(heap) and heap[largest] < heap[left]:
largest = left
if right < size(heap) and heap[largest] < heap[right]:
largest = right
if largest != node:
_swap(heap, node, largest)
max_heapify(heap, largest)
def build_max_heap(heap):
for node in reversed(range((len(heap) - 1) // 2 + 1)):
max_heapify(heap, node)
return heap
def remove_last(heap):
return heap.pop()
def remove(heap, node):
if node >= size(heap):
raise exception('Node does not exist in the heap.')
last = size(heap) - 1
if node != last:
_swap(heap, node, last)
item = remove_last(heap)
max_heapify(heap, node)
return item
def remove_top(heap):
return remove(heap, _root())
def decrease_key(heap, node, item):
if heap[node] < item:
raise exception('The new key is lsrger than the current key.')
heap[node] = item
_move_down(heap, node)
def increase_key(heap, node, item):
if item < heap[node]:
raise exception('The new key is smaller than the current key.')
heap[node] = item
_move_up(heap, node)
def insert(heap, item):
node = size(heap)
heap.append(item)
_move_up(heap, node)
def top(heap):
"""Returns the top item in the heap."""
return heap[_root()]
def size(heap):
"""The number of items in the heap."""
return len(heap)
def empty(heap):
"""Check if the heap is empty."""
return size(heap) == 0
def _swap(heap, i, j):
"""Swaps nodes i and j in heap."""
(heap[i], heap[j]) = (heap[j], heap[i])
def _parent(node):
"""Parent of a node. The root points to itself."""
if node == _root():
return _root()
return (node + 1) // 2 - 1
def _left(node):
"""The _left child of a node."""
return 2 * node + 1
def _right(node):
"""The right child of a node."""
return 2 * node + 2
def _root():
"""Returns the root node."""
return 0
def _move_down(heap, node):
while node < size(heap):
left = _left(node)
right = _right(node)
largest = node
if left < size(heap) and heap[largest] < heap[left]:
largest = left
if right < size(heap) and heap[largest] < heap[right]:
largest = right
if largest == node:
break
_swap(heap, node, largest)
node = largest
def _move_up(heap, node):
while node != _root() and heap[_parent(node)] < item:
_swap(heap, node, _parent(node))
node = _parent(node) |
def ascii(arg): pass
def filter(pred, iterable): pass
def hex(arg): pass
def map(func, *iterables): pass
def oct(arg): pass
| def ascii(arg):
pass
def filter(pred, iterable):
pass
def hex(arg):
pass
def map(func, *iterables):
pass
def oct(arg):
pass |
#!/usr/bin/python3
'''General Class which is used for all the class
'''
class GeneralSeller:
def __init__(self,mechant_i):
pass
def start_product(self):
pass
class WishSeller(GeneralSeller):
'''
'''
class AmazonSeller(GeneralSeller):
pass
class AlibabaSeller(GeneralSeller):
pass
class EbaySeller(GeneralSeller):
pass
class DhgateSeller(GeneralSeller):
pass
| """General Class which is used for all the class
"""
class Generalseller:
def __init__(self, mechant_i):
pass
def start_product(self):
pass
class Wishseller(GeneralSeller):
"""
"""
class Amazonseller(GeneralSeller):
pass
class Alibabaseller(GeneralSeller):
pass
class Ebayseller(GeneralSeller):
pass
class Dhgateseller(GeneralSeller):
pass |
upTo = int(input())
res = 0
for i in range(upTo):
res += i
print(res)
| up_to = int(input())
res = 0
for i in range(upTo):
res += i
print(res) |
class Solution(object):
def intersect(self, nums1, nums2):
nums1_counter = collections.Counter(nums1)
nums2_counter = collections.Counter(nums2)
result = []
for k in nums1_counter.keys():
if k in nums2_counter:
result.extend([k] * min(nums1_counter[k], nums2_counter[k]))
return result
| class Solution(object):
def intersect(self, nums1, nums2):
nums1_counter = collections.Counter(nums1)
nums2_counter = collections.Counter(nums2)
result = []
for k in nums1_counter.keys():
if k in nums2_counter:
result.extend([k] * min(nums1_counter[k], nums2_counter[k]))
return result |
class CandidateViewer:
def __init__(self, df):
self.df = df
def show_candidates(self):
best_players_selections = ['2 players', '3 players', '4 players', '5 or more players']
weight_selections = [(1, 1.4), (1.5, 1.9), (1.9, 2.5), (2.5, 3.1), (3.1, 4)]
cols = ['title', 'year', 'weight', 'best_for', 'final_score', 'category-cluster',
'mechanics-cluster', 'url']
for n_players in best_players_selections:
for weight_range in weight_selections:
selection = (self.df['best_for'] == n_players) & (self.df['weight'] >= weight_range[0]) & \
(self.df['weight'] <= weight_range[1]) & (self.df['year'] >= 2000) & (self.df['weight_votes'] >= 10) & \
(self.df['final_score'] >= 15)
print('Weight: {} to {} - Best for {}'.format(weight_range[0], weight_range[1], n_players))
print('-'*80)
selected = self.df[selection][cols].sort_values('final_score', ascending=False).head(10)
for idx, row in selected.iterrows():
print('{:<35} ({}) - {:.2f}, {}, {:.1f}, Cat: {}, Mech: {}\n\t\t{}'\
.format(row['title'][:35], row['year'], row['weight'], row['best_for'], row['final_score'],
row['category-cluster'][0], row['mechanics-cluster'][0], row['url']))
print('\n\n')
| class Candidateviewer:
def __init__(self, df):
self.df = df
def show_candidates(self):
best_players_selections = ['2 players', '3 players', '4 players', '5 or more players']
weight_selections = [(1, 1.4), (1.5, 1.9), (1.9, 2.5), (2.5, 3.1), (3.1, 4)]
cols = ['title', 'year', 'weight', 'best_for', 'final_score', 'category-cluster', 'mechanics-cluster', 'url']
for n_players in best_players_selections:
for weight_range in weight_selections:
selection = (self.df['best_for'] == n_players) & (self.df['weight'] >= weight_range[0]) & (self.df['weight'] <= weight_range[1]) & (self.df['year'] >= 2000) & (self.df['weight_votes'] >= 10) & (self.df['final_score'] >= 15)
print('Weight: {} to {} - Best for {}'.format(weight_range[0], weight_range[1], n_players))
print('-' * 80)
selected = self.df[selection][cols].sort_values('final_score', ascending=False).head(10)
for (idx, row) in selected.iterrows():
print('{:<35} ({}) - {:.2f}, {}, {:.1f}, Cat: {}, Mech: {}\n\t\t{}'.format(row['title'][:35], row['year'], row['weight'], row['best_for'], row['final_score'], row['category-cluster'][0], row['mechanics-cluster'][0], row['url']))
print('\n\n') |
def main():
q = int(input())
pre = [
3, 5, 13, 37, 61, 73, 157, 193, 277, 313, 397, 421, 457, 541, 613, 661, 673, 733, 757, 877, 997, 1093, 1153, 1201, 1213, 1237, 1321, 1381, 1453, 1621, 1657, 1753, 1873, 1933, 1993, 2017, 2137, 2341, 2473, 2557, 2593, 2797, 2857, 2917,
3061, 3217, 3253, 3313, 3517, 3733, 4021, 4057, 4177, 4261, 4273, 4357, 4441, 4561, 4621, 4933, 5077, 5101, 5113, 5233, 5413, 5437, 5581, 5701, 6037, 6073, 6121, 6133, 6217, 6337, 6361, 6373, 6637, 6661, 6781, 6997, 7057, 7213, 7393, 7417, 7477, 7537, 7753, 7933, 8053, 8101, 8221, 8317, 8353, 8461, 8521, 8677, 8713, 8893, 9013, 9133, 9181, 9241, 9277,
9601, 9661, 9721, 9817, 9901, 9973, 10333, 10357, 10453, 10837, 10861, 10957, 11113, 11161, 11317, 11497, 11677, 11701, 12073, 12157, 12241, 12301, 12421, 12433, 12457, 12541, 12553, 12601, 12721, 12757, 12841, 12853, 13093, 13381, 13417, 13681, 13921, 13933, 14437, 14593, 14737, 14821, 15013, 15073, 15121, 15241, 15277, 15361, 15373, 15733, 15901, 16033, 16333, 16381, 16417, 16573, 16633, 16657, 16921, 17041, 17053, 17077, 17257, 17293, 17377, 17881, 18013, 18097, 18133, 18181, 18217, 18253, 18301, 18313, 18397, 18481, 18553, 18637, 18793, 19237, 19441, 19477, 19717, 19801, 19813, 19861, 20353, 20533, 20641, 20857, 21001, 21061, 21193, 21277, 21313, 21577, 21661, 21673, 21817, 22093, 22501, 22573,
22621, 22993, 23053, 23173, 23557, 23677, 23773, 23917, 24097, 24421, 24481, 24781, 24841, 25033, 25153, 25237, 25561, 25657, 25933, 26017, 26293, 26317, 26437, 26497, 26821, 26833, 26881, 26953, 27073, 27253, 27337, 27361, 27457, 27997, 28057, 28297, 28393, 28813, 28837, 28921, 29101, 29473, 29641, 30181, 30241, 30517, 30553, 30577, 30637, 30661, 30697, 30781, 30853, 31081, 31237, 31321, 31333, 31357, 31477, 31573, 31873, 31981, 32173, 32377, 32497, 32533, 32833, 33037, 33301, 33457, 33493, 33757, 33961, 34057, 34213, 34273, 34381, 34513, 34897, 34981, 35317, 35521, 35677, 35977, 36097, 36241, 36433, 36457, 36793, 36877, 36901, 36913, 37273, 37321, 37357, 37573, 37717, 37957, 38281, 38461, 38833, 38953, 38977, 39217, 39373, 39397, 39733, 40093, 40177, 40213, 40693, 40813, 41017, 41221, 41281, 41413, 41617, 41893,
42061, 42337, 42373, 42793, 42961, 43117, 43177, 43201, 43321, 43573, 43597, 43633, 43717, 44053, 44101, 44221, 44257, 44293, 44893, 45061, 45337, 45433, 45481, 45553, 45613, 45841, 46021, 46141, 46261, 46861, 46993, 47017, 47161, 47353, 47521, 47533, 47653, 47713, 47737, 47797, 47857, 48121, 48193, 48337, 48673, 48757, 48781, 49033, 49261, 49393, 49417, 49597, 49681, 49957, 50221, 50341, 50377, 50821, 50893, 51157, 51217, 51241, 51481, 51517, 51637, 52057, 52081, 52237, 52321, 52453, 52501, 52813, 52861, 52957, 53077, 53113, 53281, 53401, 53917, 54121, 54133, 54181, 54217, 54421, 54517, 54541, 54673, 54721, 54973, 55057, 55381, 55501, 55633, 55837, 55921, 55933, 56053, 56101, 56113, 56197, 56401, 56437, 56701, 56773, 56821, 56857, 56893, 57073, 57097, 57193, 57241, 57373, 57457, 57853, 58153, 58417, 58441, 58537,
58573, 58693, 59053, 59197, 59221, 59281, 59341, 59833, 60217, 60337, 60373, 60637, 60733, 60937, 61057, 61153, 61261, 61297, 61561, 61657, 61681, 61717, 61861, 62137, 62473, 62497, 62533, 62653, 62773, 63313, 63397, 63541, 63697, 63781, 63913, 64153, 64237, 64381, 64513, 64717, 65173, 65293, 65413, 65437, 65497, 65557, 65677, 65881, 66301, 66361, 66601, 66697, 66853, 66973, 67057, 67153, 67273, 67477, 67537, 67741, 67777, 67933, 67993, 68113, 68281, 68521, 68737, 69001, 69073, 69457, 69493, 69697, 69877, 70117, 70177, 70297, 70501, 70621, 70921, 70981, 71233, 71341, 71353, 71593, 71821, 72073, 72481, 72613, 72901, 72937, 73141, 73417, 73477, 73561, 73693, 74077, 74317, 74377, 74713, 75013, 75133, 75181, 75721, 75793, 75913, 76333, 76561, 76597, 76753, 77137, 77641, 78157, 78193, 78277, 78877, 78901, 79333, 79357,
79537, 79657, 79693, 79801, 79873, 80077, 80173, 80221, 80473, 80701, 80713, 80917, 81013, 81181, 81517, 81637, 81853, 82021, 82153, 82261, 82561, 82981, 83077, 83221, 83233, 83437, 83617, 83701, 83773, 84121, 84313, 84673, 84697, 84793, 84913, 85297, 85333, 85453, 85717, 85933, 86353, 86413, 87181, 87253, 87337, 87421, 87433, 87517, 87553, 87973, 88117, 88177, 88237, 88261, 88513, 88741, 88897, 88993, 89293, 89833, 89917, 90121, 91081, 91381, 91393, 91513, 91957, 92041, 92557, 92761, 92821, 92893, 92941, 93097, 93133, 93493, 93637, 93913, 94033, 94117, 94273, 94321, 94441, 94573, 94777, 94837, 94993, 95257, 95317, 95401, 95581, 95617, 95713, 95737, 96097, 96157, 96181, 96493, 96517, 96973, 97081, 97177, 97501, 97561, 97777, 97813, 98017, 98737, 98953, 99277, 99577, 99661, 99877
]
for _ in range(q):
l,r = map(int,input().split())
ans = 0
for e in pre:
if e > r:
break
if e >= l:
ans += 1
print(ans)
if __name__ == "__main__":
main() | def main():
q = int(input())
pre = [3, 5, 13, 37, 61, 73, 157, 193, 277, 313, 397, 421, 457, 541, 613, 661, 673, 733, 757, 877, 997, 1093, 1153, 1201, 1213, 1237, 1321, 1381, 1453, 1621, 1657, 1753, 1873, 1933, 1993, 2017, 2137, 2341, 2473, 2557, 2593, 2797, 2857, 2917, 3061, 3217, 3253, 3313, 3517, 3733, 4021, 4057, 4177, 4261, 4273, 4357, 4441, 4561, 4621, 4933, 5077, 5101, 5113, 5233, 5413, 5437, 5581, 5701, 6037, 6073, 6121, 6133, 6217, 6337, 6361, 6373, 6637, 6661, 6781, 6997, 7057, 7213, 7393, 7417, 7477, 7537, 7753, 7933, 8053, 8101, 8221, 8317, 8353, 8461, 8521, 8677, 8713, 8893, 9013, 9133, 9181, 9241, 9277, 9601, 9661, 9721, 9817, 9901, 9973, 10333, 10357, 10453, 10837, 10861, 10957, 11113, 11161, 11317, 11497, 11677, 11701, 12073, 12157, 12241, 12301, 12421, 12433, 12457, 12541, 12553, 12601, 12721, 12757, 12841, 12853, 13093, 13381, 13417, 13681, 13921, 13933, 14437, 14593, 14737, 14821, 15013, 15073, 15121, 15241, 15277, 15361, 15373, 15733, 15901, 16033, 16333, 16381, 16417, 16573, 16633, 16657, 16921, 17041, 17053, 17077, 17257, 17293, 17377, 17881, 18013, 18097, 18133, 18181, 18217, 18253, 18301, 18313, 18397, 18481, 18553, 18637, 18793, 19237, 19441, 19477, 19717, 19801, 19813, 19861, 20353, 20533, 20641, 20857, 21001, 21061, 21193, 21277, 21313, 21577, 21661, 21673, 21817, 22093, 22501, 22573, 22621, 22993, 23053, 23173, 23557, 23677, 23773, 23917, 24097, 24421, 24481, 24781, 24841, 25033, 25153, 25237, 25561, 25657, 25933, 26017, 26293, 26317, 26437, 26497, 26821, 26833, 26881, 26953, 27073, 27253, 27337, 27361, 27457, 27997, 28057, 28297, 28393, 28813, 28837, 28921, 29101, 29473, 29641, 30181, 30241, 30517, 30553, 30577, 30637, 30661, 30697, 30781, 30853, 31081, 31237, 31321, 31333, 31357, 31477, 31573, 31873, 31981, 32173, 32377, 32497, 32533, 32833, 33037, 33301, 33457, 33493, 33757, 33961, 34057, 34213, 34273, 34381, 34513, 34897, 34981, 35317, 35521, 35677, 35977, 36097, 36241, 36433, 36457, 36793, 36877, 36901, 36913, 37273, 37321, 37357, 37573, 37717, 37957, 38281, 38461, 38833, 38953, 38977, 39217, 39373, 39397, 39733, 40093, 40177, 40213, 40693, 40813, 41017, 41221, 41281, 41413, 41617, 41893, 42061, 42337, 42373, 42793, 42961, 43117, 43177, 43201, 43321, 43573, 43597, 43633, 43717, 44053, 44101, 44221, 44257, 44293, 44893, 45061, 45337, 45433, 45481, 45553, 45613, 45841, 46021, 46141, 46261, 46861, 46993, 47017, 47161, 47353, 47521, 47533, 47653, 47713, 47737, 47797, 47857, 48121, 48193, 48337, 48673, 48757, 48781, 49033, 49261, 49393, 49417, 49597, 49681, 49957, 50221, 50341, 50377, 50821, 50893, 51157, 51217, 51241, 51481, 51517, 51637, 52057, 52081, 52237, 52321, 52453, 52501, 52813, 52861, 52957, 53077, 53113, 53281, 53401, 53917, 54121, 54133, 54181, 54217, 54421, 54517, 54541, 54673, 54721, 54973, 55057, 55381, 55501, 55633, 55837, 55921, 55933, 56053, 56101, 56113, 56197, 56401, 56437, 56701, 56773, 56821, 56857, 56893, 57073, 57097, 57193, 57241, 57373, 57457, 57853, 58153, 58417, 58441, 58537, 58573, 58693, 59053, 59197, 59221, 59281, 59341, 59833, 60217, 60337, 60373, 60637, 60733, 60937, 61057, 61153, 61261, 61297, 61561, 61657, 61681, 61717, 61861, 62137, 62473, 62497, 62533, 62653, 62773, 63313, 63397, 63541, 63697, 63781, 63913, 64153, 64237, 64381, 64513, 64717, 65173, 65293, 65413, 65437, 65497, 65557, 65677, 65881, 66301, 66361, 66601, 66697, 66853, 66973, 67057, 67153, 67273, 67477, 67537, 67741, 67777, 67933, 67993, 68113, 68281, 68521, 68737, 69001, 69073, 69457, 69493, 69697, 69877, 70117, 70177, 70297, 70501, 70621, 70921, 70981, 71233, 71341, 71353, 71593, 71821, 72073, 72481, 72613, 72901, 72937, 73141, 73417, 73477, 73561, 73693, 74077, 74317, 74377, 74713, 75013, 75133, 75181, 75721, 75793, 75913, 76333, 76561, 76597, 76753, 77137, 77641, 78157, 78193, 78277, 78877, 78901, 79333, 79357, 79537, 79657, 79693, 79801, 79873, 80077, 80173, 80221, 80473, 80701, 80713, 80917, 81013, 81181, 81517, 81637, 81853, 82021, 82153, 82261, 82561, 82981, 83077, 83221, 83233, 83437, 83617, 83701, 83773, 84121, 84313, 84673, 84697, 84793, 84913, 85297, 85333, 85453, 85717, 85933, 86353, 86413, 87181, 87253, 87337, 87421, 87433, 87517, 87553, 87973, 88117, 88177, 88237, 88261, 88513, 88741, 88897, 88993, 89293, 89833, 89917, 90121, 91081, 91381, 91393, 91513, 91957, 92041, 92557, 92761, 92821, 92893, 92941, 93097, 93133, 93493, 93637, 93913, 94033, 94117, 94273, 94321, 94441, 94573, 94777, 94837, 94993, 95257, 95317, 95401, 95581, 95617, 95713, 95737, 96097, 96157, 96181, 96493, 96517, 96973, 97081, 97177, 97501, 97561, 97777, 97813, 98017, 98737, 98953, 99277, 99577, 99661, 99877]
for _ in range(q):
(l, r) = map(int, input().split())
ans = 0
for e in pre:
if e > r:
break
if e >= l:
ans += 1
print(ans)
if __name__ == '__main__':
main() |
# pkg.mod
# descr
#
# Author: Benjamin Bengfort <benjamin@bengfort.com>
# Created: timestamp
#
# Copyright (C) 2013 Bengfort.com
# For license information, see LICENSE.txt
#
# ID: __init__.py [] benjamin@bengfort.com $
"""
"""
##########################################################################
## Imports
##########################################################################
| """
""" |
class FileListing:
dictionary: dict
def __init__(self, dictionary: dict):
self.dictionary = dictionary
def __eq__(self, other):
return self.dictionary == other.dictionary
def __repr__(self):
return {'dictionary': self.dictionary}
@property
def tenant(self):
return self.dictionary.get("tenant")
@property
def file_path(self):
return self.dictionary.get("filePath")
@property
def last_modified(self):
return self.dictionary.get("lastModified")
@property
def size(self):
return self.dictionary.get("size")
| class Filelisting:
dictionary: dict
def __init__(self, dictionary: dict):
self.dictionary = dictionary
def __eq__(self, other):
return self.dictionary == other.dictionary
def __repr__(self):
return {'dictionary': self.dictionary}
@property
def tenant(self):
return self.dictionary.get('tenant')
@property
def file_path(self):
return self.dictionary.get('filePath')
@property
def last_modified(self):
return self.dictionary.get('lastModified')
@property
def size(self):
return self.dictionary.get('size') |
# Builds
#T# Table of contents
#C# Compiling to bytecode
#C# Building a project to binary
#T# Beginning of content
#C# Compiling to bytecode
# |-------------------------------------------------------------
#T# Python code is compiled from .py source code files, to .pyc bytecode files
#T# in the operating system shell, the py_compile script can be run to compile a .py file into .pyc
# SYNTAX python3 -m py_compile script1.py
#T# the script1.py is compiled, python3 is the Python executable, -m is a Python option to run py_compile (see the file titled Interpreter)
#T# the output file is stored in a directory named __pycache__/ under the directory of script1.py, named something like __pycache__/script1.cpython-38.pyc, the cpython-38 part of the name stands for the Python version, in this case version 3.8
#T# in the operating system shell, a compiled .pyc file can be executed like a source code script
# SYNTAX python3 __pycache__/script1.cpython-38.pyc
#T# python3 is the Python executable, this syntax executes script1.cpython-38.pyc which gives the same output as executing script1.py
# |-------------------------------------------------------------
#C# Building a project to binary
# |-------------------------------------------------------------
#T# a Python project is formed by several related Python files whose execution starts at a main file, a project can be built into a binary executable so that the whole project resides in a single file, which doesn't depend on the Python interpreter to be executed
#T# in the operating system shell, the PyInstaller module can be executed to build a Python project (it can be installed with pip)
# SYNTAX pyinstaller --onefile main1.py dir1/module1.py dir1/dir1_1/script1.py
#T# this creates an executable file named main1 in a directory under the working directory named dist/, so the executable file is dist/main1, the --onefile option makes it so that dist/ only contains one file
print("Built")
# |------------------------------------------------------------- | print('Built') |
def get_profile(name, age: int, *sports, **awards):
if type(age) != int:
raise ValueError
if len(sports) > 5:
raise ValueError
if sports and not awards:
sports = sorted(list(sports))
return {'name': name, 'age': age, 'sports': sports}
if not sports and awards:
return {'name': name, 'age': age, 'awards': awards}
if not sports and not awards:
return {'name': name, 'age': age}
sports = sorted(list(sports))
return {'name': name, 'age': age, 'sports': sports, 'awards': awards}
pass | def get_profile(name, age: int, *sports, **awards):
if type(age) != int:
raise ValueError
if len(sports) > 5:
raise ValueError
if sports and (not awards):
sports = sorted(list(sports))
return {'name': name, 'age': age, 'sports': sports}
if not sports and awards:
return {'name': name, 'age': age, 'awards': awards}
if not sports and (not awards):
return {'name': name, 'age': age}
sports = sorted(list(sports))
return {'name': name, 'age': age, 'sports': sports, 'awards': awards}
pass |
a = int(input("a= "))
b = int(input("b= "))
c = int(input("c= "))
if a == 0:
if b != 0:
print("La solution est", -c / b)
else:
if c == 0:
print("INF")
else:
print("Aucune solution")
else:
delta = (b ** 2) - 4 * a * c
if delta > 0:
print(
"Les deux solutions sont ",
(- b - (delta ** 0.5)) / (2 * a),
"et",
(- b + (delta ** 0.5)) / (2 * a),
)
elif delta == 0:
print("La solution est", -b / (2 * a))
else:
print("Pas de solutions reelles")
| a = int(input('a= '))
b = int(input('b= '))
c = int(input('c= '))
if a == 0:
if b != 0:
print('La solution est', -c / b)
elif c == 0:
print('INF')
else:
print('Aucune solution')
else:
delta = b ** 2 - 4 * a * c
if delta > 0:
print('Les deux solutions sont ', (-b - delta ** 0.5) / (2 * a), 'et', (-b + delta ** 0.5) / (2 * a))
elif delta == 0:
print('La solution est', -b / (2 * a))
else:
print('Pas de solutions reelles') |
# -*- coding: utf-8 -*-
"""
Solution to Project Euler problem 6
Author: Jaime Liew
https://github.com/jaimeliew1/Project_Euler_Solutions
"""
def run():
N = 100
return sum(i for i in range(N+1))**2 - sum(i**2 for i in range(N+1))
if __name__ == "__main__":
print(run())
| """
Solution to Project Euler problem 6
Author: Jaime Liew
https://github.com/jaimeliew1/Project_Euler_Solutions
"""
def run():
n = 100
return sum((i for i in range(N + 1))) ** 2 - sum((i ** 2 for i in range(N + 1)))
if __name__ == '__main__':
print(run()) |
# --
# Copyright (c) 2008-2021 Net-ng.
# All rights reserved.
#
# This software is licensed under the BSD License, as described in
# the file LICENSE.txt, which you should have received as part of
# this distribution.
# --
class SessionError(LookupError):
def name(self):
return self.__class__.__name__
# =================================================================================
class CriticalSessionError(SessionError):
pass
class LockError(CriticalSessionError):
"""Raised when an exclusive lock on a session can't be acquired
"""
pass
class StateError(CriticalSessionError):
"""Raise when a state can't be deserialized
'"""
pass
class StorageError(CriticalSessionError):
"""Raised when the serialized session can't be stored / retreived
"""
pass
# =================================================================================
class InvalidSessionError(SessionError):
pass
class ExpirationError(InvalidSessionError):
"""Raised when a session or a state id is no longer valid
"""
pass
class SessionSecurityError(InvalidSessionError):
"""Raised when the secure id of a session is not valid
"""
pass
| class Sessionerror(LookupError):
def name(self):
return self.__class__.__name__
class Criticalsessionerror(SessionError):
pass
class Lockerror(CriticalSessionError):
"""Raised when an exclusive lock on a session can't be acquired
"""
pass
class Stateerror(CriticalSessionError):
"""Raise when a state can't be deserialized
'"""
pass
class Storageerror(CriticalSessionError):
"""Raised when the serialized session can't be stored / retreived
"""
pass
class Invalidsessionerror(SessionError):
pass
class Expirationerror(InvalidSessionError):
"""Raised when a session or a state id is no longer valid
"""
pass
class Sessionsecurityerror(InvalidSessionError):
"""Raised when the secure id of a session is not valid
"""
pass |
class Solution:
def checkIfExist(self, arr: List[int]) -> bool:
s = set()
for v in arr:
if v * 2 in s or (v % 2 == 0 and v / 2 in s): return True
s.add(v)
return False
| class Solution:
def check_if_exist(self, arr: List[int]) -> bool:
s = set()
for v in arr:
if v * 2 in s or (v % 2 == 0 and v / 2 in s):
return True
s.add(v)
return False |
n = int(input("Dame un numero entero: "))
def factorial( n ):
if n == 1:
return n
else:
#llamada recursiva
return n * factorial( n - 1 )
print("El factorial de: ",n,"es", factorial(n)) | n = int(input('Dame un numero entero: '))
def factorial(n):
if n == 1:
return n
else:
return n * factorial(n - 1)
print('El factorial de: ', n, 'es', factorial(n)) |
#!/bin/python3
rd = open("06.input", "r")
fullSum = 0
validLetters = {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z" }
while True:
letters = {}
count = 0
while True:
line = rd.readline().strip()
if not line or line == "":
break
count += 1
for c in line:
if c in validLetters:
if c in letters:
letters[c] += 1
else:
letters[c] = 1
if len(letters) == 0:
break
for key in letters.keys():
if letters[key] == count:
fullSum += 1
print(fullSum)
| rd = open('06.input', 'r')
full_sum = 0
valid_letters = {'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}
while True:
letters = {}
count = 0
while True:
line = rd.readline().strip()
if not line or line == '':
break
count += 1
for c in line:
if c in validLetters:
if c in letters:
letters[c] += 1
else:
letters[c] = 1
if len(letters) == 0:
break
for key in letters.keys():
if letters[key] == count:
full_sum += 1
print(fullSum) |
'''
done
'''
ipAddress = '127.0.0.1'
port = 21
name = "Pustakalupi"
pi = 3.14 #tidak ada constant dalam Python 3
print("ipAddress bertipe :", type(ipAddress))
print("port bertipe :", type(port))
print("name bertipe :", type(name))
print("pi bertipe :", type(pi))
print(pi)
del pi
print(pi) | """
done
"""
ip_address = '127.0.0.1'
port = 21
name = 'Pustakalupi'
pi = 3.14
print('ipAddress bertipe :', type(ipAddress))
print('port bertipe :', type(port))
print('name bertipe :', type(name))
print('pi bertipe :', type(pi))
print(pi)
del pi
print(pi) |
class Originator:
_state = None
class Memento:
def __init__(self, state):
self._state = state
def setState(self, state):
self._state = state
def getState(self):
return self._state
def __init__(self, state = None):
self._state = state
def set(self, state):
if state != None:
self._state = state
def createMemento(self):
return self.Memento(self._state)
def restore(self, memento):
self._state = memento.getState()
return self._state
class Caretaker:
pointer = 0
savedStates = []
def saveMemento(self, element):
self.pointer += 1
self.savedStates.append(element)
def getMemento(self, index):
return self.savedStates[index-1]
def undo(self):
if self.pointer > 0:
self.pointer -= 1
return self.getMemento(self.pointer)
else:
return None
def redo(self):
if self.pointer < len(self.savedStates):
self.pointer += 1
return self.getMemento(self.pointer)
else:
return None
caretaker = Caretaker()
originator = Originator()
#Testing code
originator.set("Message")
caretaker.saveMemento(originator.createMemento())
print(originator.restore(caretaker.getMemento(caretaker.pointer)))
originator.set("Typo")
caretaker.saveMemento(originator.createMemento())
print(originator.restore(caretaker.getMemento(caretaker.pointer)))
originator.set(caretaker.undo())
print(originator.restore(caretaker.getMemento(caretaker.pointer)))
originator.set(caretaker.redo())
print(originator.restore(caretaker.getMemento(caretaker.pointer)))
| class Originator:
_state = None
class Memento:
def __init__(self, state):
self._state = state
def set_state(self, state):
self._state = state
def get_state(self):
return self._state
def __init__(self, state=None):
self._state = state
def set(self, state):
if state != None:
self._state = state
def create_memento(self):
return self.Memento(self._state)
def restore(self, memento):
self._state = memento.getState()
return self._state
class Caretaker:
pointer = 0
saved_states = []
def save_memento(self, element):
self.pointer += 1
self.savedStates.append(element)
def get_memento(self, index):
return self.savedStates[index - 1]
def undo(self):
if self.pointer > 0:
self.pointer -= 1
return self.getMemento(self.pointer)
else:
return None
def redo(self):
if self.pointer < len(self.savedStates):
self.pointer += 1
return self.getMemento(self.pointer)
else:
return None
caretaker = caretaker()
originator = originator()
originator.set('Message')
caretaker.saveMemento(originator.createMemento())
print(originator.restore(caretaker.getMemento(caretaker.pointer)))
originator.set('Typo')
caretaker.saveMemento(originator.createMemento())
print(originator.restore(caretaker.getMemento(caretaker.pointer)))
originator.set(caretaker.undo())
print(originator.restore(caretaker.getMemento(caretaker.pointer)))
originator.set(caretaker.redo())
print(originator.restore(caretaker.getMemento(caretaker.pointer))) |
# please excuse me, I'm a C# and Rust developer with only minor Python experience :D
# let's give it a go though!
MAP = {
'a': "100000", 'n': "101110",
'b': "110000", 'o': "101010",
'c': "100100", 'p': "111100",
'd': "100110", 'q': "111110",
'e': "100010", 'r': "111010",
'f': "110100", 's': "011100",
'g': "110110", 't': "011110",
'h': "110010", 'u': "101001",
'i': "010100", 'v': "111001",
'j': "010110", 'w': "010111",
'k': "101000", 'x': "101101",
'l': "111000", 'y': "101111",
'm': "101100", 'z': "101011",
' ': "000000"
}
def solution(s):
mapped = []
for c in s:
if c.isupper():
# upper-case escape string
mapped.append("000001")
mapped.append(MAP[c.lower()])
return "".join(mapped)
if __name__ == "__main__":
assert solution("The quick brown fox jumps over the lazy dog") == "000001011110110010100010000000111110101001010100100100101000000000110000111010101010010111101110000000110100101010101101000000010110101001101100111100011100000000101010111001100010111010000000011110110010100010000000111000100000101011101111000000100110101010110110" | map = {'a': '100000', 'n': '101110', 'b': '110000', 'o': '101010', 'c': '100100', 'p': '111100', 'd': '100110', 'q': '111110', 'e': '100010', 'r': '111010', 'f': '110100', 's': '011100', 'g': '110110', 't': '011110', 'h': '110010', 'u': '101001', 'i': '010100', 'v': '111001', 'j': '010110', 'w': '010111', 'k': '101000', 'x': '101101', 'l': '111000', 'y': '101111', 'm': '101100', 'z': '101011', ' ': '000000'}
def solution(s):
mapped = []
for c in s:
if c.isupper():
mapped.append('000001')
mapped.append(MAP[c.lower()])
return ''.join(mapped)
if __name__ == '__main__':
assert solution('The quick brown fox jumps over the lazy dog') == '000001011110110010100010000000111110101001010100100100101000000000110000111010101010010111101110000000110100101010101101000000010110101001101100111100011100000000101010111001100010111010000000011110110010100010000000111000100000101011101111000000100110101010110110' |
"""
252. Meeting Rooms
Easy
Given an array of meeting time intervals where intervals[i] = [starti, endi], determine if a person could attend all meetings.
Example 1:
Input: intervals = [[0,30],[5,10],[15,20]]
Output: false
Example 2:
Input: intervals = [[7,10],[2,4]]
Output: true
Constraints:
0 <= intervals.length <= 104
intervals[i].length == 2
0 <= starti < endi <= 106
"""
# Time: O(nlogn)
# Space: O(n)
#
# Definition for an interval.
# class Interval:
# def __init__(self, s=0, e=0):
# self.start = s
# self.end = e
# V0
class Solution:
def canAttendMeetings(self, intervals):
"""
NOTE this
"""
intervals.sort(key=lambda x: x[0])
for i in range(1, len(intervals)):
"""
NOTE this :
-> we compare ntervals[i][0] and ntervals[i-1][1]
"""
if intervals[i][0] < intervals[i-1][1]:
return False
return True
# V0'
# IDEA : SORT
class Solution(object):
def canAttendMeetings(self, intervals):
# edge case
if not intervals or len(intervals) == 1:
return True
intervals.sort(key = lambda x : [x[0], -x[1]])
if len(intervals) == 2:
return intervals[0][0] < intervals[1][0] and intervals[0][1] < intervals[1][1]
last = intervals[0]
for i in range(1, len(intervals)):
# CASE 1 : last and intervals[i] overlap (3 situations)
if (last[1] > intervals[i][0] and intervals[i][0] < last[1]) or\
(last[0] == intervals[i][0] and last[1] == intervals[i][1]) or\
(last[0] < intervals[i][1] and last[1] > intervals[i][1]):
return False
# CASE 2 : last and intervals[i] NOT overlap
else:
last = intervals[i]
return True
# V1
class Solution:
# @param {Interval[]} intervals
# @return {boolean}
def canAttendMeetings(self, intervals):
intervals.sort(key=lambda x: x[0])
for i in range(len(intervals)-1):
if intervals[i][1] > intervals[i+1][0]:
return False
return True
# V1'
# IDEA : BRUTE FORCE
# https://leetcode.com/problems/meeting-rooms/solution/
# JAVA
# public static boolean overlap(int[] interval1, int[] interval2) {
# return (Math.min(interval1[1], interval2[1]) >
# Math.max(interval1[0], interval2[0]));
# }
# V1''
# IDEA : SORTING
# https://leetcode.com/problems/meeting-rooms/solution/
class Solution:
def canAttendMeetings(self, intervals):
intervals.sort()
for i in range(len(intervals) - 1):
if intervals[i][1] > intervals[i + 1][0]:
return False
return True
# V1''''
# https://blog.csdn.net/qq508618087/article/details/50750465
class Solution(object):
def canAttendMeetings(self, v):
"""
:type intervals: List[Interval]
:rtype: bool
"""
v.sort(key = lambda val: val.start)
return not any(v[i].start < v[i-1].end for i in range(1,len(v)))
# V1''''
# https://www.jiuzhang.com/solution/meeting-rooms/
# JAVA
# public class Solution {
# public boolean canAttendMeetings(Interval[] intervals) {
# if(intervals == null || intervals.length == 0) return true;
# Arrays.sort(intervals, new Comparator<Interval>(){
# public int compare(Interval i1, Interval i2){
# return i1.start - i2.start;
# }
# });
# int end = intervals[0].end;
# for(int i = 1; i < intervals.length; i++){
# if(intervals[i].start < end) {
# return false;
# }
# end = Math.max(end, intervals[i].end);
# }
# return true;
# }
# }
# V2
class Solution:
# @param {Interval[]} intervals
# @return {boolean}
def canAttendMeetings(self, intervals):
intervals.sort(key=lambda x: x.start)
for i in range(1, len(intervals)):
if intervals[i].start < intervals[i-1].end:
return False
return True | """
252. Meeting Rooms
Easy
Given an array of meeting time intervals where intervals[i] = [starti, endi], determine if a person could attend all meetings.
Example 1:
Input: intervals = [[0,30],[5,10],[15,20]]
Output: false
Example 2:
Input: intervals = [[7,10],[2,4]]
Output: true
Constraints:
0 <= intervals.length <= 104
intervals[i].length == 2
0 <= starti < endi <= 106
"""
class Solution:
def can_attend_meetings(self, intervals):
"""
NOTE this
"""
intervals.sort(key=lambda x: x[0])
for i in range(1, len(intervals)):
'\n NOTE this : \n -> we compare ntervals[i][0] and ntervals[i-1][1]\n '
if intervals[i][0] < intervals[i - 1][1]:
return False
return True
class Solution(object):
def can_attend_meetings(self, intervals):
if not intervals or len(intervals) == 1:
return True
intervals.sort(key=lambda x: [x[0], -x[1]])
if len(intervals) == 2:
return intervals[0][0] < intervals[1][0] and intervals[0][1] < intervals[1][1]
last = intervals[0]
for i in range(1, len(intervals)):
if last[1] > intervals[i][0] and intervals[i][0] < last[1] or (last[0] == intervals[i][0] and last[1] == intervals[i][1]) or (last[0] < intervals[i][1] and last[1] > intervals[i][1]):
return False
else:
last = intervals[i]
return True
class Solution:
def can_attend_meetings(self, intervals):
intervals.sort(key=lambda x: x[0])
for i in range(len(intervals) - 1):
if intervals[i][1] > intervals[i + 1][0]:
return False
return True
class Solution:
def can_attend_meetings(self, intervals):
intervals.sort()
for i in range(len(intervals) - 1):
if intervals[i][1] > intervals[i + 1][0]:
return False
return True
class Solution(object):
def can_attend_meetings(self, v):
"""
:type intervals: List[Interval]
:rtype: bool
"""
v.sort(key=lambda val: val.start)
return not any((v[i].start < v[i - 1].end for i in range(1, len(v))))
class Solution:
def can_attend_meetings(self, intervals):
intervals.sort(key=lambda x: x.start)
for i in range(1, len(intervals)):
if intervals[i].start < intervals[i - 1].end:
return False
return True |
# Desafio066: Desafio criar um programa que leia varios numeros de o valor total digitado e pare quando digitado 999.
nu = int (0)
controle = int(0)
print('Se precisar sair digite 999')
while True:
nu = int(input('Digite um numero '))
if nu == 999:
break
controle = controle + nu
print(controle)
| nu = int(0)
controle = int(0)
print('Se precisar sair digite 999')
while True:
nu = int(input('Digite um numero '))
if nu == 999:
break
controle = controle + nu
print(controle) |
__author__ = 'tony petrov'
DEFAULT_SOCIAL_MEDIA_CYCLE = 3600 # 1 hour since most social media websites have a 1 hour timeout
# tasks
TASK_EXPLORE = 0
TASK_BULK_RETRIEVE = 1
TASK_FETCH_LISTS = 2
TASK_FETCH_USER = 3
TASK_UPDATE_WALL = 4
TASK_FETCH_STREAM = 5
TASK_GET_DASHBOARD = 6
TASK_GET_TAGGED = 7
TASK_GET_BLOG_POSTS = 8
TASK_GET_FACEBOOK_WALL = 9
TASK_FETCH_FACEBOOK_USERS = 10
TASK_TWITTER_SEARCH = 11
TOTAL_TASKS = 12
# twitter control constants
POLITENESS_VALUE = 0.5 # how long the worker should sleep for used to prevent twitter from getting overloaded
TWITTER_MAX_LIST_SIZE = 5000
TWITTER_MAX_NUMBER_OF_LISTS = 900 #can be changed to 1000 but retrieval of tweets from all lists not guaranteed
TWITTER_MAX_NUMBER_OF_NON_FOLLOWED_USERS = 900
TWITTER_BULK_LIST_SIZE = 100
TWITTER_MAX_NUM_OF_BULK_LISTS_PER_REQUEST_CYCLE = 900
TWITTER_MAX_NUM_OF_REQUESTS_PER_CYCLE = 180
TWITTER_MAX_FOLLOW_REQUESTS = 10
TWITTER_ADD_TO_LIST_LIMIT = 100
MAX_TWITTER_TRENDS_REQUESTS = 15
TWITTER_CYCLES_PER_HOUR = 4
TWITTER_CYCLE_DURATION = 15
RUNNING_CYCLE = 900 # 15*60seconds
MAX_TWEETS_PER_CYCLE = 25
MAX_TRACKABLE_TOPICS = 400
MAX_FOLLOWABLE_USERS = 5000
# tumblr control
TUMBLR_MAX_REQUESTS_PER_DAY = 5000
TUMBLR_MAX_REQUESTS_PER_HOUR = 250
# facebook control
FACEBOOK_MAX_REQUESTS_PER_HOUR = 200
# storage locations
TWITTER_BULK_LIST_STORAGE = 'data/twitter/bulk_lists'
TWITTER_LIST_STORAGE = 'data/twitter/lists'
TWITTER_USER_STORAGE = 'data/twitter/users'
TWITTER_WALL_STORAGE = 'data/twitter/home'
TWITTER_CANDIDATES_STORAGE = 'data/twitter/remaining'
TWITTER_CREDENTIALS = 'data/twitter/login'
PROXY_LOCATION = 'data/proxies'
RANKING_FILTER_CLASSIFIER = 'data/classifier'
RANKING_FILTER_TOPIC_CLASSIFIER = 'data/topic_classifier'
# Model names
TWITTER_STREAMING_BUCKET_MODEL = 'stream'
TWITTER_CYCLE_HARVESTER = 'harvester'
TWITTER_HYBRID_MODEL = 'hybrid'
TWITTER_STREAMING_HARVESTER_NON_HYBRID = 'both'
# Service plugins
CRAWLER_PLUGIN_SERVICE = 1 # redirect all outputs to the plugin
TWITTER_PLUGIN_SERVICE = 100 # redirect output from all twitter crawler models to the plugin
TWITTER_HARVESTER_PLUGIN_SERVICE = 101 # redirect output from the twitter model to the plugin
TWITTER_STREAMING_PLUGIN_SERVICE = 102 # redirect output from the twitter stream api to the plugin
TUMBLR_PLUGIN_SERVICE = 103 # redirect tumblr output to plugin
FACEBOOK_PLUGIN_SERVICE = 104 # redirect facebook output to plugin
# Ranking Classifiers
PERCEPTRON_CLASSIFIER = 201
DEEP_NEURAL_NETWORK_CLASSIFIER = 202
K_MEANS_CLASSIFIER = 203
# other control constants and variables
TESTING = False
EXPLORING = False
COLLECTING_DATA_ONLY = False
RANK_RESET_TIME = 600 # every 10 mins
TIME_TO_UPDATE_TRENDS = 0
FILTER_STREAM = False
FRESH_TWEETS_ONLY = False # set to true to reduce the number of overlapping tweets
PARTITION_FACTOR = 0.5
TWITTER_ACCOUNTS_COUNT = 1
MIN_TWITTER_STATUSES_COUNT = 150
| __author__ = 'tony petrov'
default_social_media_cycle = 3600
task_explore = 0
task_bulk_retrieve = 1
task_fetch_lists = 2
task_fetch_user = 3
task_update_wall = 4
task_fetch_stream = 5
task_get_dashboard = 6
task_get_tagged = 7
task_get_blog_posts = 8
task_get_facebook_wall = 9
task_fetch_facebook_users = 10
task_twitter_search = 11
total_tasks = 12
politeness_value = 0.5
twitter_max_list_size = 5000
twitter_max_number_of_lists = 900
twitter_max_number_of_non_followed_users = 900
twitter_bulk_list_size = 100
twitter_max_num_of_bulk_lists_per_request_cycle = 900
twitter_max_num_of_requests_per_cycle = 180
twitter_max_follow_requests = 10
twitter_add_to_list_limit = 100
max_twitter_trends_requests = 15
twitter_cycles_per_hour = 4
twitter_cycle_duration = 15
running_cycle = 900
max_tweets_per_cycle = 25
max_trackable_topics = 400
max_followable_users = 5000
tumblr_max_requests_per_day = 5000
tumblr_max_requests_per_hour = 250
facebook_max_requests_per_hour = 200
twitter_bulk_list_storage = 'data/twitter/bulk_lists'
twitter_list_storage = 'data/twitter/lists'
twitter_user_storage = 'data/twitter/users'
twitter_wall_storage = 'data/twitter/home'
twitter_candidates_storage = 'data/twitter/remaining'
twitter_credentials = 'data/twitter/login'
proxy_location = 'data/proxies'
ranking_filter_classifier = 'data/classifier'
ranking_filter_topic_classifier = 'data/topic_classifier'
twitter_streaming_bucket_model = 'stream'
twitter_cycle_harvester = 'harvester'
twitter_hybrid_model = 'hybrid'
twitter_streaming_harvester_non_hybrid = 'both'
crawler_plugin_service = 1
twitter_plugin_service = 100
twitter_harvester_plugin_service = 101
twitter_streaming_plugin_service = 102
tumblr_plugin_service = 103
facebook_plugin_service = 104
perceptron_classifier = 201
deep_neural_network_classifier = 202
k_means_classifier = 203
testing = False
exploring = False
collecting_data_only = False
rank_reset_time = 600
time_to_update_trends = 0
filter_stream = False
fresh_tweets_only = False
partition_factor = 0.5
twitter_accounts_count = 1
min_twitter_statuses_count = 150 |
class Professor:
def __init__(self, nome):
self.__nome = nome #conceito de encapusulamento
self.__salaDeAula = None
def nome(self):
return self.__nome
def salaDeAula(self, sala):
self.__salaDeAula = sala
def EmAula(self):
return 'Em aula'
class Sala:
def __init__(self, numero):
self.__numero = numero
def numero(self):
return self.__numero
def FecharSala(self):
return 'Porta foi fechada!'
| class Professor:
def __init__(self, nome):
self.__nome = nome
self.__salaDeAula = None
def nome(self):
return self.__nome
def sala_de_aula(self, sala):
self.__salaDeAula = sala
def em_aula(self):
return 'Em aula'
class Sala:
def __init__(self, numero):
self.__numero = numero
def numero(self):
return self.__numero
def fechar_sala(self):
return 'Porta foi fechada!' |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
def init():
pass
def servers():
return {}
| def init():
pass
def servers():
return {} |
def processArray(l2):
loss=[];mloss=0
for i in range(0,len(l2)):
loss.append(l2[i][0]-l2[i][len(l2[i])-1])
if(len(loss)>0):
mloss=loss.index(max(loss))
print(len(l2[mloss]))
l=[]
while True:
a=int(input())
if(a<0):
break
l.append(a)
ans=[]
i=0
while(i<len(l)):
k=l[i]
tmp=[]
tmp.append(l[i])
for j in range(i+1,len(l)):
if(l[j]>k):
break
else:
tmp.append(l[j])
k=l[j]
i=j+1
print(tmp)
if(len(tmp)>1):
ans.append(tmp)
processArray(ans)
| def process_array(l2):
loss = []
mloss = 0
for i in range(0, len(l2)):
loss.append(l2[i][0] - l2[i][len(l2[i]) - 1])
if len(loss) > 0:
mloss = loss.index(max(loss))
print(len(l2[mloss]))
l = []
while True:
a = int(input())
if a < 0:
break
l.append(a)
ans = []
i = 0
while i < len(l):
k = l[i]
tmp = []
tmp.append(l[i])
for j in range(i + 1, len(l)):
if l[j] > k:
break
else:
tmp.append(l[j])
k = l[j]
i = j + 1
print(tmp)
if len(tmp) > 1:
ans.append(tmp)
process_array(ans) |
class Solution:
def hammingWeight(self, n: int) -> int:
n = bin(n)[2:]
str_n = str(n)
return str_n.count("1")
| class Solution:
def hamming_weight(self, n: int) -> int:
n = bin(n)[2:]
str_n = str(n)
return str_n.count('1') |
def coordinate_input():
x, y = input("X, Y Coordinates ==> ").strip().split(",")
return float(x), float(y)
def main():
coordinates = []
print("Type the coordinates in order; it means A,B,C...")
while True:
try:
point = coordinate_input()
coordinates.append(point)
except:
break
sumatory = 0
for index, point in enumerate(coordinates):
if index == len(coordinates) - 1:
sumatory += point[0] * coordinates[0][1] - point[1] * coordinates[0][0]
else:
sumatory += point[0] * coordinates[index+1][1] - point[1] * coordinates[index+1][0]
print("Area:", abs(sumatory / 2))
if __name__ == '__main__':
main() | def coordinate_input():
(x, y) = input('X, Y Coordinates ==> ').strip().split(',')
return (float(x), float(y))
def main():
coordinates = []
print('Type the coordinates in order; it means A,B,C...')
while True:
try:
point = coordinate_input()
coordinates.append(point)
except:
break
sumatory = 0
for (index, point) in enumerate(coordinates):
if index == len(coordinates) - 1:
sumatory += point[0] * coordinates[0][1] - point[1] * coordinates[0][0]
else:
sumatory += point[0] * coordinates[index + 1][1] - point[1] * coordinates[index + 1][0]
print('Area:', abs(sumatory / 2))
if __name__ == '__main__':
main() |
''' Exemplo 1
c = 1
while c < 11:
print(c)
c += 1
print('Fim')
'''
'''eXEMPLO 2
n = 1
while n!= 0:
n = int(input('Digite um valor: '))
print('Fim') '''
''' Exemplo 3
r = 'S'
while r == 'S':
n = int(input('Digite um valor: '))
r = str(input('Quer continuar? [S/N] ')).upper()
print('Fim')'''
''' Exemplo 4
n = 1
par = impar = 0
while n != 0:
n = int(input('Digite um numero: '))
if n != 0:
if n % 2 == 0:
par +=1
else:
impar += 1
print('Voce digitou {} numeros pares e {} numeros impares!'.format(par, impar))'''
'''Exemplo 5
from random import randint
computador = randint(1, 10)
print('Sou seu computador... Acabei de pensar em um numero entre 0 e 10.')
acertou = False
palpites = 0
while not acertou:
jogador = int(input('Qual o seu palpite: '))
palpites += 1
if jogador == computador:
acertou = True
else:
if jogador < computador:
print('Mais... tente mais uma vez.')
elif jogador > computador:
print('Menos... tente mais uma vez')
print('Acertou com {} tentativas. Parabens!!'.format(palpites))'''
n = int(input('digite um numero:'))
c = 0
while c < 5:
c += 1
print('Menor ' if n < 3 else 'Maior') | """ Exemplo 1
c = 1
while c < 11:
print(c)
c += 1
print('Fim')
"""
"eXEMPLO 2 \nn = 1\nwhile n!= 0:\n n = int(input('Digite um valor: '))\nprint('Fim') "
" Exemplo 3\nr = 'S'\nwhile r == 'S':\n n = int(input('Digite um valor: '))\n r = str(input('Quer continuar? [S/N] ')).upper()\nprint('Fim')"
" Exemplo 4\nn = 1\npar = impar = 0\nwhile n != 0:\n n = int(input('Digite um numero: '))\n if n != 0:\n if n % 2 == 0:\n par +=1\n else:\n impar += 1\nprint('Voce digitou {} numeros pares e {} numeros impares!'.format(par, impar))"
"Exemplo 5\nfrom random import randint\ncomputador = randint(1, 10)\nprint('Sou seu computador... Acabei de pensar em um numero entre 0 e 10.')\nacertou = False\npalpites = 0\nwhile not acertou:\n jogador = int(input('Qual o seu palpite: '))\n palpites += 1\n if jogador == computador:\n acertou = True\n else:\n if jogador < computador:\n print('Mais... tente mais uma vez.')\n elif jogador > computador:\n print('Menos... tente mais uma vez')\nprint('Acertou com {} tentativas. Parabens!!'.format(palpites))"
n = int(input('digite um numero:'))
c = 0
while c < 5:
c += 1
print('Menor ' if n < 3 else 'Maior') |
#!/home/user/code/Django-Sample/django_venv/bin/python2.7
# EASY-INSTALL-SCRIPT: 'Django==1.11.3','django-admin.py'
__requires__ = 'Django==1.11.3'
__import__('pkg_resources').run_script('Django==1.11.3', 'django-admin.py')
| __requires__ = 'Django==1.11.3'
__import__('pkg_resources').run_script('Django==1.11.3', 'django-admin.py') |
def LB2idx(lev, band, nlevs, nbands):
''' convert level and band to dictionary index '''
# reset band to match matlab version
band += (nbands-1)
if band > nbands-1:
band = band - nbands
if lev == 0:
idx = 0
elif lev == nlevs-1:
# (Nlevels - ends)*Nbands + ends -1 (because zero indexed)
idx = (((nlevs-2)*nbands)+2)-1
else:
# (level-first level) * nbands + first level + current band
idx = (nbands*lev)-band - 1
return idx
| def lb2idx(lev, band, nlevs, nbands):
""" convert level and band to dictionary index """
band += nbands - 1
if band > nbands - 1:
band = band - nbands
if lev == 0:
idx = 0
elif lev == nlevs - 1:
idx = (nlevs - 2) * nbands + 2 - 1
else:
idx = nbands * lev - band - 1
return idx |
# https://www.hackerrank.com/challenges/s10-standard-deviation/problem
# Enter your code here. Read input from STDIN. Print output to STDOUT
n = int(input().strip())
all1 = [int(i) for i in input().strip().split()]
u = sum(all1) / n
v = sum(((i - u) ** 2) for i in all1)/n
sd = v ** 0.5
print("{0:0.1f}".format(sd)) | n = int(input().strip())
all1 = [int(i) for i in input().strip().split()]
u = sum(all1) / n
v = sum(((i - u) ** 2 for i in all1)) / n
sd = v ** 0.5
print('{0:0.1f}'.format(sd)) |
context_mapping = {
"schema": "http://www.w3.org/2001/XMLSchema#",
"brick": "http://brickschema.org/schema/1.0.3/Brick#",
"brickFrame": "http://brickschema.org/schema/1.0.3/BrickFrame#",
"BUDO-M": "https://git.rwth-aachen.de/EBC/Team_BA/misc/Machine-Learning/tree/MA_fst-bll/building_ml_platform/BUDO-M/Platform_Application_AI_Buildings_MA_Llopis/OntologyToModelica/CoTeTo/ebc_jsonld#",
"rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
"rdfs": "http://www.w3.org/2000/01/rdf-schema#",
"Equipment": {"@id": "brick: Equipment"},
"Point": {"@id": "brick: Point"},
"BUDOSystem": {"@id": "BUDO-M: BUDOSystem"},
"ModelicaModel": {"@id": "BUDO-M: ModelicaModel"},
"portHeatflow": {"@id": "BUDO-M: portHeatflow"},
"EquipmentPointParameter": {"@id": "BUDO-M: EquipmentPointParameter"},
"EquipmentPointUnits": {"@id": "BUDO-M: EquipmentPointUnits"},
"EquipmentPointExplanation": {"@id": "BUDO-M: EquipmentPointExplanation"},
"portParameter": {"@id": "BUDO-M: portParameter"},
"portUnits": {"@id": "BUDO-M: portUnits"},
"portExplanation": {"@id": "BUDO-M: portExplanation"},
"Pump": {"@id":"brick:Pump"},
"Boiler": {"@id":"brick:Boiler"},
"Valve": {"@id":"brick:Valve"},
"Temperature_Sensor": {"@id":"brick:Temperature_Sensor"},
"Heat_Pump": {"@id":"brick:Heat_Pump"},
"Combined_Heat_Power": {"@id":"brick:Combined_Heat_Power"},
"Heat_Exchanger": {"@id":"brick:Heat_Exchanger"},
"ItemList": {"@id":"schema:ItemList"},
"itemListElement": {"@id":"schema:itemListElement"},
"T_Piece": {"@id":"BUDO-M:T_Piece"}
}
doc_mapping_brick={
"@context": context_mapping,
"@type": "ItemList",
"itemListElement": [{
"Pump":{
"Point":"Hot_Water_Pump/Chilled_Water_Pump",
"BUDOSystem":"PU", "ModelicaModel": "1",
"portHeatflow": "1",
"EquipmentPointParameter":"signalpath.massflow",
"EquipmentPointUnits":"kg/s",
"EquipmentPointExplanation":"mat file directory for input signal: prescribed mass flow rate for pump",
"portParameter":"massFlow.nominal/massFlow.nominal.Pipe.out/pressureDifference.nominal.Pipe.out/medium",
"portUnits":"kg/s,kg/s,pa,-",
"portExplanation":"-/nominal mass flow rate in the pipe connected to this port /nominal pressure drop in the pipe connected to this port /medium flowing in this component, example: AixLib.Media.Specialized.Water.TemperatureDependentDensity"
} },
{
"Boiler": {
"Point":"Boiler",
"BUDOSystem":"BOI",
"ModelicaModel": "5",
"portHeatflow": "1",
"EquipmentPointParameter": "signalpath.status/signalpath.mode/signalpath.temperature",
"EquipmentPointUnits":"-,-,K",
"EquipmentPointExplanation": "mat file directory for input signal: boiler on off status , boolean value required/mat file directory for input signal: boiler switch to night mode, boolean value required/mat file directory for input signal: ambient temperature",
"portParameter":"massFlow.nominal/massFlow.nominal.Pipe.out/pressureDifference.nominal.Pipe.out/medium",
"portUnits":"kg/s,kg/s,pa,-",
"portExplanation":"-/nominal mass flow rate in the pipe connected to this port /nominal pressure drop in the pipe connected to this port /medium flowing in this component, example: AixLib.Media.Specialized.Water.TemperatureDependentDensity"
}
},
{
"Valve": {
"Point":"Heating_Valve",
"BUDOSystem":"VAL",
"ModelicaModel": "1",
"portHeatflow": "2",
"EquipmentPointParameter":"signalpath.position",
"EquipmentPointUnits":"-",
"EquipmentPointExplanation":"mat file directory for input signal: actuator position, value in range [0,1] required (0: closed, 1: open)",
"portParameter":"massFlow.nominal/pressureDifference.nominal/massFlow.nominal.Pipe.out/pressureDifference.nominal.Pipe.out/medium",
"portUnits":"kg/s,pa,kg/s,pa,-",
"portExplanation":"-/-/nominal mass flow rate in the pipe connected to this port /nominal pressure drop in the pipe connected to this port /medium flowing in this component, example: AixLib.Media.Specialized.Water.TemperatureDependentDensity"
}
},
{
"Temperature_Sensor": {
"Point":"Hot_Water_Supply_Temperature_Sensor/Hot_Water_Return_Temperature_Sensor/Chilled_Water_Supply_Temperature_Sensor/Chilled_Water_Return_Temperature_Sensor",
"BUDOSystem":"MEA.T",
"ModelicaModel": "0",
"portHeatflow": "0",
"EquipmentPointParameter": "massFlow.nominal/medium",
"EquipmentPointUnits": "kg/s,-",
"EquipmentPointExplanation":"- /medium flowing in this component, example: AixLib.Media.Specialized.Water.TemperatureDependentDensity",
"portParameter":"",
"portUnits":"",
"portExplanation":""
}
},
{
"Heat_Pump": {
"Point":"Heat_Pump",
"BUDOSystem":"HP",
"ModelicaModel": "1",
"portHeatflow": "2",
"EquipmentPointParameter":"CoefficientOfPerformance/compressorPower.nominal/signalpath.loadratio",
"EquipmentPointUnits":"-,W,-",
"EquipmentPointExplanation":"-/-/mat file directory for input signal: part load ratio of compressor in heat pump, value in range [0,1] required",
"portParameter":"massFlow.nominal/pressureDifference.nominal/massFlow.nominal.Pipe.out/pressureDifference.nominal.Pipe.out/temperatureDifference.nominal/temperature.average.nominal/medium",
"portUnits":"kg/s,pa,kg/s,pa,K,K,-",
"portExplanation":"-/-/nominal mass flow rate in the pipe connected to this port /nominal pressure drop in the pipe connected to this port /temperature difference outlet-inlet in condenser for portHeatflow.prim, in evaporator for portHeatflow .sec/nominal average temperature in condenser for portHeatflow.prim, in evaporator for portHeatflow .sec/medium flowing in this component, example: AixLib.Media.Specialized.Water.TemperatureDependentDensity"
}
},
{
"Combined_Heat_Power": {
"Point":"Combined_Heat_Power",
"BUDOSystem":"CHP",
"ModelicaModel": "3",
"portHeatflow":"1",
"EquipmentPointParameter":"signalpath.status/signalpath.temperature",
"EquipmentPointUnits":"-,K",
"EquipmentPointExplanation":"mat file directory for input signal: CHP on off status, boolean value required/mat file directory for input signal: CHP temperature setpoint, boolean value required",
"portParameter":"massFlow.nominal/medium",
"portUnits":"kg/s,-",
"portExplanation":"-/medium flowing in this component, example: AixLib.Media.Specialized.Water.TemperatureDependentDensity"
}
},
{
"Heat_Exchanger": {
"Point":"Heat_Exchanger",
"BUDOSystem":"HX",
"ModelicaModel":"0",
"portHeatflow":"2",
"EquipmentPointParameter":"",
"EquipmentPointUnits":"",
"EquipmentPointExplanation":"",
"portParameter":"massFlow.nominal/pressureDifference.nominal/massFlow.nominal.Pipe.out/pressureDifference.nominal.Pipe.out/medium",
"portUnits":"kg/s,pa,kg/s,pa,K,K,-",
"portExplanation":"-/-/nominal mass flow rate in the pipe connected to this port /nominal pressure drop in the pipe connected to this port /-/-/medium flowing in this component, example: AixLib.Media.Specialized.Water.TemperatureDependentDensity "
}
}]
}
doc_mapping_BUDO={
"@context": context_mapping,
"@type": "ItemList",
"itemListElement": [
{
"T_Piece": {
"Point":"T_Piece",
"BUDOSystem":"TP",
"ModelicaModel": "0",
"portHeatflow": "2",
"EquipmentPointParameter": "0",
"EquipmentPointUnits": "0",
"EquipmentPointExplanation": "0",
"portParameter": "medium",
"portUnits":"-",
"portExplanation":"medium in modelica model"
}
}
]
}
| context_mapping = {'schema': 'http://www.w3.org/2001/XMLSchema#', 'brick': 'http://brickschema.org/schema/1.0.3/Brick#', 'brickFrame': 'http://brickschema.org/schema/1.0.3/BrickFrame#', 'BUDO-M': 'https://git.rwth-aachen.de/EBC/Team_BA/misc/Machine-Learning/tree/MA_fst-bll/building_ml_platform/BUDO-M/Platform_Application_AI_Buildings_MA_Llopis/OntologyToModelica/CoTeTo/ebc_jsonld#', 'rdf': 'http://www.w3.org/1999/02/22-rdf-syntax-ns#', 'rdfs': 'http://www.w3.org/2000/01/rdf-schema#', 'Equipment': {'@id': 'brick: Equipment'}, 'Point': {'@id': 'brick: Point'}, 'BUDOSystem': {'@id': 'BUDO-M: BUDOSystem'}, 'ModelicaModel': {'@id': 'BUDO-M: ModelicaModel'}, 'portHeatflow': {'@id': 'BUDO-M: portHeatflow'}, 'EquipmentPointParameter': {'@id': 'BUDO-M: EquipmentPointParameter'}, 'EquipmentPointUnits': {'@id': 'BUDO-M: EquipmentPointUnits'}, 'EquipmentPointExplanation': {'@id': 'BUDO-M: EquipmentPointExplanation'}, 'portParameter': {'@id': 'BUDO-M: portParameter'}, 'portUnits': {'@id': 'BUDO-M: portUnits'}, 'portExplanation': {'@id': 'BUDO-M: portExplanation'}, 'Pump': {'@id': 'brick:Pump'}, 'Boiler': {'@id': 'brick:Boiler'}, 'Valve': {'@id': 'brick:Valve'}, 'Temperature_Sensor': {'@id': 'brick:Temperature_Sensor'}, 'Heat_Pump': {'@id': 'brick:Heat_Pump'}, 'Combined_Heat_Power': {'@id': 'brick:Combined_Heat_Power'}, 'Heat_Exchanger': {'@id': 'brick:Heat_Exchanger'}, 'ItemList': {'@id': 'schema:ItemList'}, 'itemListElement': {'@id': 'schema:itemListElement'}, 'T_Piece': {'@id': 'BUDO-M:T_Piece'}}
doc_mapping_brick = {'@context': context_mapping, '@type': 'ItemList', 'itemListElement': [{'Pump': {'Point': 'Hot_Water_Pump/Chilled_Water_Pump', 'BUDOSystem': 'PU', 'ModelicaModel': '1', 'portHeatflow': '1', 'EquipmentPointParameter': 'signalpath.massflow', 'EquipmentPointUnits': 'kg/s', 'EquipmentPointExplanation': 'mat file directory for input signal: prescribed mass flow rate for pump', 'portParameter': 'massFlow.nominal/massFlow.nominal.Pipe.out/pressureDifference.nominal.Pipe.out/medium', 'portUnits': 'kg/s,kg/s,pa,-', 'portExplanation': '-/nominal mass flow rate in the pipe connected to this port /nominal pressure drop in the pipe connected to this port /medium flowing in this component, example: AixLib.Media.Specialized.Water.TemperatureDependentDensity'}}, {'Boiler': {'Point': 'Boiler', 'BUDOSystem': 'BOI', 'ModelicaModel': '5', 'portHeatflow': '1', 'EquipmentPointParameter': 'signalpath.status/signalpath.mode/signalpath.temperature', 'EquipmentPointUnits': '-,-,K', 'EquipmentPointExplanation': 'mat file directory for input signal: boiler on off status , boolean value required/mat file directory for input signal: boiler switch to night mode, boolean value required/mat file directory for input signal: ambient temperature', 'portParameter': 'massFlow.nominal/massFlow.nominal.Pipe.out/pressureDifference.nominal.Pipe.out/medium', 'portUnits': 'kg/s,kg/s,pa,-', 'portExplanation': '-/nominal mass flow rate in the pipe connected to this port /nominal pressure drop in the pipe connected to this port /medium flowing in this component, example: AixLib.Media.Specialized.Water.TemperatureDependentDensity'}}, {'Valve': {'Point': 'Heating_Valve', 'BUDOSystem': 'VAL', 'ModelicaModel': '1', 'portHeatflow': '2', 'EquipmentPointParameter': 'signalpath.position', 'EquipmentPointUnits': '-', 'EquipmentPointExplanation': 'mat file directory for input signal: actuator position, value in range [0,1] required (0: closed, 1: open)', 'portParameter': 'massFlow.nominal/pressureDifference.nominal/massFlow.nominal.Pipe.out/pressureDifference.nominal.Pipe.out/medium', 'portUnits': 'kg/s,pa,kg/s,pa,-', 'portExplanation': '-/-/nominal mass flow rate in the pipe connected to this port /nominal pressure drop in the pipe connected to this port /medium flowing in this component, example: AixLib.Media.Specialized.Water.TemperatureDependentDensity'}}, {'Temperature_Sensor': {'Point': 'Hot_Water_Supply_Temperature_Sensor/Hot_Water_Return_Temperature_Sensor/Chilled_Water_Supply_Temperature_Sensor/Chilled_Water_Return_Temperature_Sensor', 'BUDOSystem': 'MEA.T', 'ModelicaModel': '0', 'portHeatflow': '0', 'EquipmentPointParameter': 'massFlow.nominal/medium', 'EquipmentPointUnits': 'kg/s,-', 'EquipmentPointExplanation': '- /medium flowing in this component, example: AixLib.Media.Specialized.Water.TemperatureDependentDensity', 'portParameter': '', 'portUnits': '', 'portExplanation': ''}}, {'Heat_Pump': {'Point': 'Heat_Pump', 'BUDOSystem': 'HP', 'ModelicaModel': '1', 'portHeatflow': '2', 'EquipmentPointParameter': 'CoefficientOfPerformance/compressorPower.nominal/signalpath.loadratio', 'EquipmentPointUnits': '-,W,-', 'EquipmentPointExplanation': '-/-/mat file directory for input signal: part load ratio of compressor in heat pump, value in range [0,1] required', 'portParameter': 'massFlow.nominal/pressureDifference.nominal/massFlow.nominal.Pipe.out/pressureDifference.nominal.Pipe.out/temperatureDifference.nominal/temperature.average.nominal/medium', 'portUnits': 'kg/s,pa,kg/s,pa,K,K,-', 'portExplanation': '-/-/nominal mass flow rate in the pipe connected to this port /nominal pressure drop in the pipe connected to this port /temperature difference outlet-inlet in condenser for portHeatflow.prim, in evaporator for portHeatflow .sec/nominal average temperature in condenser for portHeatflow.prim, in evaporator for portHeatflow .sec/medium flowing in this component, example: AixLib.Media.Specialized.Water.TemperatureDependentDensity'}}, {'Combined_Heat_Power': {'Point': 'Combined_Heat_Power', 'BUDOSystem': 'CHP', 'ModelicaModel': '3', 'portHeatflow': '1', 'EquipmentPointParameter': 'signalpath.status/signalpath.temperature', 'EquipmentPointUnits': '-,K', 'EquipmentPointExplanation': 'mat file directory for input signal: CHP on off status, boolean value required/mat file directory for input signal: CHP temperature setpoint, boolean value required', 'portParameter': 'massFlow.nominal/medium', 'portUnits': 'kg/s,-', 'portExplanation': '-/medium flowing in this component, example: AixLib.Media.Specialized.Water.TemperatureDependentDensity'}}, {'Heat_Exchanger': {'Point': 'Heat_Exchanger', 'BUDOSystem': 'HX', 'ModelicaModel': '0', 'portHeatflow': '2', 'EquipmentPointParameter': '', 'EquipmentPointUnits': '', 'EquipmentPointExplanation': '', 'portParameter': 'massFlow.nominal/pressureDifference.nominal/massFlow.nominal.Pipe.out/pressureDifference.nominal.Pipe.out/medium', 'portUnits': 'kg/s,pa,kg/s,pa,K,K,-', 'portExplanation': '-/-/nominal mass flow rate in the pipe connected to this port /nominal pressure drop in the pipe connected to this port /-/-/medium flowing in this component, example: AixLib.Media.Specialized.Water.TemperatureDependentDensity '}}]}
doc_mapping_budo = {'@context': context_mapping, '@type': 'ItemList', 'itemListElement': [{'T_Piece': {'Point': 'T_Piece', 'BUDOSystem': 'TP', 'ModelicaModel': '0', 'portHeatflow': '2', 'EquipmentPointParameter': '0', 'EquipmentPointUnits': '0', 'EquipmentPointExplanation': '0', 'portParameter': 'medium', 'portUnits': '-', 'portExplanation': 'medium in modelica model'}}]} |
"""Relaydomains app constants."""
PERMISSIONS = {
"Resellers": [
("relaydomains", "relaydomain", "add_relaydomain"),
("relaydomains", "relaydomain", "change_relaydomain"),
("relaydomains", "relaydomain", "delete_relaydomain"),
("relaydomains", "service", "add_service"),
("relaydomains", "service", "change_service"),
("relaydomains", "service", "delete_service")
]
}
| """Relaydomains app constants."""
permissions = {'Resellers': [('relaydomains', 'relaydomain', 'add_relaydomain'), ('relaydomains', 'relaydomain', 'change_relaydomain'), ('relaydomains', 'relaydomain', 'delete_relaydomain'), ('relaydomains', 'service', 'add_service'), ('relaydomains', 'service', 'change_service'), ('relaydomains', 'service', 'delete_service')]} |
"""Defines error messages and functions."""
_BAD_NAME = "Bad name '{name}'."
_BAD_LITERAL = "Bad literal '{literal}'."
_NOT_IMPLEMENTED = "Not implemented:"
class CheckError(Exception):
def __init__(self, message):
self.message = message
def bad_name(name):
_error(_BAD_NAME, name=name)
def bad_literal(literal):
_error(_BAD_LITERAL, literal=literal)
def not_implemented(message):
_error(" ".join([_NOT_IMPLEMENTED, "".join([message, "."])]))
def _error(message, **keywords):
raise CheckError(message.format_map(keywords))
| """Defines error messages and functions."""
_bad_name = "Bad name '{name}'."
_bad_literal = "Bad literal '{literal}'."
_not_implemented = 'Not implemented:'
class Checkerror(Exception):
def __init__(self, message):
self.message = message
def bad_name(name):
_error(_BAD_NAME, name=name)
def bad_literal(literal):
_error(_BAD_LITERAL, literal=literal)
def not_implemented(message):
_error(' '.join([_NOT_IMPLEMENTED, ''.join([message, '.'])]))
def _error(message, **keywords):
raise check_error(message.format_map(keywords)) |
OBJECT( 'VALUE',
attributes = [
A( 'ANY', 'value' ),
]
)
| object('VALUE', attributes=[a('ANY', 'value')]) |
# Reading Error Messages
# Read the Python code and the resulting traceback below,
# and answer the following questions:
# How many levels does the traceback have?
# What is the function name where the error occurred?
# On which line number in this function did the error occur?
# What is the type of error?
# What is the error message?
# This code has an intentional error. Do not type it directly;
# use it for reference to understand the error message below.
def print_message(day):
messages = {
"monday": "Hello, world!",
"tuesday": "Today is Tuesday!",
"wednesday": "It is the middle of the week.",
"thursday": "Today is Donnerstag in German!",
"friday": "Last day of the week!",
"saturday": "Hooray for the weekend!",
"sunday": "Aw, the weekend is almost over."
}
print(messages[day])
def print_friday_message():
print_message("Friday")
print_friday_message() | def print_message(day):
messages = {'monday': 'Hello, world!', 'tuesday': 'Today is Tuesday!', 'wednesday': 'It is the middle of the week.', 'thursday': 'Today is Donnerstag in German!', 'friday': 'Last day of the week!', 'saturday': 'Hooray for the weekend!', 'sunday': 'Aw, the weekend is almost over.'}
print(messages[day])
def print_friday_message():
print_message('Friday')
print_friday_message() |
"""
This is a config file that will be used to generate the .piwall file
"""
# Network information
master_ip = "0.0.0.0"
# Wall.py for PiWall
configs = {
'walls': {
'wall_name': {
'name': 'wall_name',
'height': '270',
'width': '1080',
'master_ip': '0.0.0.0'
}
},
'num_of_tiles': 4,
'tiles': [
{
'name': 'tile_name',
'wall': 'wall_name',
'width': '270',
'height': '270',
'x': '0',
'y': '0',
'ip': '0.0.0.0',
'id': 'tile1'
},
{
'name': 'tile_name',
'wall': 'wall_name',
'width': '270',
'height': '270',
'x': '270',
'y': '0',
'ip': '0.0.0.0',
'id': 'tile2'
},
{
'name': 'tile_name',
'wall': 'wall_name',
'width': '270',
'height': '270',
'x': '540',
'y': '0',
'ip': '0.0.0.0',
'id': 'tile3'
},
{
'name': 'tile_name',
'wall': 'wall_name',
'width': '270',
'height': '270',
'x': '810',
'y': '0',
'ip': '0.0.0.0',
'id': 'tile4'
}
],
'config': [
{
'name': 'wall_config',
'tile': [
{
'id': 'tile1'
},
{
'id': 'tile2'
},
{
'id': 'tile3'
},
{
'id': 'tile4'
}
]
}
]
}
# String new /etc/network/interfaces
replace_str = """auto lo
iface lo inet loopback
iface eth0 inet static
address {0}
netmask 255.255.255.0
up route add -net 224.0.0.0 netmask 240.0.0.0 eth0
"""
| """
This is a config file that will be used to generate the .piwall file
"""
master_ip = '0.0.0.0'
configs = {'walls': {'wall_name': {'name': 'wall_name', 'height': '270', 'width': '1080', 'master_ip': '0.0.0.0'}}, 'num_of_tiles': 4, 'tiles': [{'name': 'tile_name', 'wall': 'wall_name', 'width': '270', 'height': '270', 'x': '0', 'y': '0', 'ip': '0.0.0.0', 'id': 'tile1'}, {'name': 'tile_name', 'wall': 'wall_name', 'width': '270', 'height': '270', 'x': '270', 'y': '0', 'ip': '0.0.0.0', 'id': 'tile2'}, {'name': 'tile_name', 'wall': 'wall_name', 'width': '270', 'height': '270', 'x': '540', 'y': '0', 'ip': '0.0.0.0', 'id': 'tile3'}, {'name': 'tile_name', 'wall': 'wall_name', 'width': '270', 'height': '270', 'x': '810', 'y': '0', 'ip': '0.0.0.0', 'id': 'tile4'}], 'config': [{'name': 'wall_config', 'tile': [{'id': 'tile1'}, {'id': 'tile2'}, {'id': 'tile3'}, {'id': 'tile4'}]}]}
replace_str = 'auto lo\n\niface lo inet loopback\niface eth0 inet static\n\taddress {0}\n\tnetmask 255.255.255.0\n\tup route add -net 224.0.0.0 netmask 240.0.0.0 eth0\n' |
def cons(a, b):
def pair(f):
return f(a, b)
return pair
def car(pair):
return pair((lambda a, b: a))
def cdr(pair):
return pair((lambda a, b: a)) | def cons(a, b):
def pair(f):
return f(a, b)
return pair
def car(pair):
return pair(lambda a, b: a)
def cdr(pair):
return pair(lambda a, b: a) |
"""Sub-module of the package."""
def hello_world():
"""Print "Hello World"."""
print("Hello World")
| """Sub-module of the package."""
def hello_world():
"""Print "Hello World"."""
print('Hello World') |
# Testing site
base_url = 'http://localhost:80/demo'
# Login account
admin_auth_data = {'name': 'admin', 'password': 'admin'}
login_url = base_url + '/api/auth'
header = dict()
| base_url = 'http://localhost:80/demo'
admin_auth_data = {'name': 'admin', 'password': 'admin'}
login_url = base_url + '/api/auth'
header = dict() |
def add(x,y):
'''Add two nos'''
return x+y
def subtract(x,y):
'''Subtract two nos'''
return y-x
| def add(x, y):
"""Add two nos"""
return x + y
def subtract(x, y):
"""Subtract two nos"""
return y - x |
"""
Given a string S, you are allowed to convert it to a palindrome by adding characters in front of it. Find and return the
shortest palindrome you can find by performing this transformation.
For example:
Given "aacecaaa", return "aaacecaaa".
Given "abcd", return "dcbabcd".
"""
__author__ = 'Daniel'
class Solution:
def shortestPalindrome(self, s):
"""
KMP
:type s: str
:rtype: str
"""
s_r = s[::-1]
l = len(s)
if l < 2:
return s
# construct T
T = [0 for _ in xrange(l+1)]
T[0] = -1
pos = 2
cnd = 0
while pos <= l:
if s[pos-1] == s[cnd]:
T[pos] = cnd+1
cnd += 1
pos += 1
elif T[cnd] != -1:
cnd = T[cnd]
else:
T[pos] = 0
cnd = 0
pos += 1
# search
i = 0
b = 0
while i+b < l:
if s[i] == s_r[i+b]:
i += 1
if i == l:
return s
elif T[i] != -1:
b = b+i-T[i]
i = T[i]
else:
b += 1
i = 0
# where it falls off
return s_r+s[i:]
if __name__ == "__main__":
assert Solution().shortestPalindrome("abcd") == "dcbabcd"
| """
Given a string S, you are allowed to convert it to a palindrome by adding characters in front of it. Find and return the
shortest palindrome you can find by performing this transformation.
For example:
Given "aacecaaa", return "aaacecaaa".
Given "abcd", return "dcbabcd".
"""
__author__ = 'Daniel'
class Solution:
def shortest_palindrome(self, s):
"""
KMP
:type s: str
:rtype: str
"""
s_r = s[::-1]
l = len(s)
if l < 2:
return s
t = [0 for _ in xrange(l + 1)]
T[0] = -1
pos = 2
cnd = 0
while pos <= l:
if s[pos - 1] == s[cnd]:
T[pos] = cnd + 1
cnd += 1
pos += 1
elif T[cnd] != -1:
cnd = T[cnd]
else:
T[pos] = 0
cnd = 0
pos += 1
i = 0
b = 0
while i + b < l:
if s[i] == s_r[i + b]:
i += 1
if i == l:
return s
elif T[i] != -1:
b = b + i - T[i]
i = T[i]
else:
b += 1
i = 0
return s_r + s[i:]
if __name__ == '__main__':
assert solution().shortestPalindrome('abcd') == 'dcbabcd' |
def word2features(sent, i):
word = sent[i][0]
postag = sent[i][1]
features = [
'bias',
'word.lower=' + word.lower(),
'word[-3:]=' + word[-3:],
'word[-2:]=' + word[-2:],
'word.isupper=%s' % word.isupper(),
'word.istitle=%s' % word.istitle(),
'word.isdigit=%s' % word.isdigit(),
'postag=' + postag,
'postag[:2]=' + postag[:2],
]
if i > 0:
word1 = sent[i-1][0]
postag1 = sent[i-1][1]
features.extend([
'-1:word.lower=' + word1.lower(),
'-1:word.istitle=%s' % word1.istitle(),
'-1:word.isupper=%s' % word1.isupper(),
'-1:postag=' + postag1,
'-1:postag[:2]=' + postag1[:2],
])
else:
features.append('BOS')
if i < len(sent)-1:
word1 = sent[i+1][0]
postag1 = sent[i+1][1]
features.extend([
'+1:word.lower=' + word1.lower(),
'+1:word.istitle=%s' % word1.istitle(),
'+1:word.isupper=%s' % word1.isupper(),
'+1:postag=' + postag1,
'+1:postag[:2]=' + postag1[:2],
])
else:
features.append('EOS')
return features
def sent2features(sent):
return [word2features(sent, i) for i in range(len(sent))]
def sent2labels(sent):
return [label for token, postag, label in sent]
def sent2tokens(sent):
return [token for token, postag, label in sent]
| def word2features(sent, i):
word = sent[i][0]
postag = sent[i][1]
features = ['bias', 'word.lower=' + word.lower(), 'word[-3:]=' + word[-3:], 'word[-2:]=' + word[-2:], 'word.isupper=%s' % word.isupper(), 'word.istitle=%s' % word.istitle(), 'word.isdigit=%s' % word.isdigit(), 'postag=' + postag, 'postag[:2]=' + postag[:2]]
if i > 0:
word1 = sent[i - 1][0]
postag1 = sent[i - 1][1]
features.extend(['-1:word.lower=' + word1.lower(), '-1:word.istitle=%s' % word1.istitle(), '-1:word.isupper=%s' % word1.isupper(), '-1:postag=' + postag1, '-1:postag[:2]=' + postag1[:2]])
else:
features.append('BOS')
if i < len(sent) - 1:
word1 = sent[i + 1][0]
postag1 = sent[i + 1][1]
features.extend(['+1:word.lower=' + word1.lower(), '+1:word.istitle=%s' % word1.istitle(), '+1:word.isupper=%s' % word1.isupper(), '+1:postag=' + postag1, '+1:postag[:2]=' + postag1[:2]])
else:
features.append('EOS')
return features
def sent2features(sent):
return [word2features(sent, i) for i in range(len(sent))]
def sent2labels(sent):
return [label for (token, postag, label) in sent]
def sent2tokens(sent):
return [token for (token, postag, label) in sent] |
words_single = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
words_teens = ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen']
words_tens = ['','ten', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety']
hudred = 'hundred'
def spell_out(num):
if num > 1000 or num < 0:
raise Exception('no man')
if num == 1000:
return 'one thousand'
if num < 10:
return words_single[num]
if num < 20:
return words_teens[num-10]
if num < 100:
return words_tens[int(num/10)] + (spell_out(num%10) if num%10 > 0 else '')
return words_single[int(num/100)] + ' hundred ' + (('and ' + spell_out(num%100)) if num%100 > 0 else '')
def count(words):
return len(words.translate(str.maketrans('', '', ' ')))
total = 0
for i in range(1,1001):
print(spell_out(i))
spelled = spell_out(i)
total += count(spelled)
print(total)
| words_single = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine']
words_teens = ['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen']
words_tens = ['', 'ten', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety']
hudred = 'hundred'
def spell_out(num):
if num > 1000 or num < 0:
raise exception('no man')
if num == 1000:
return 'one thousand'
if num < 10:
return words_single[num]
if num < 20:
return words_teens[num - 10]
if num < 100:
return words_tens[int(num / 10)] + (spell_out(num % 10) if num % 10 > 0 else '')
return words_single[int(num / 100)] + ' hundred ' + ('and ' + spell_out(num % 100) if num % 100 > 0 else '')
def count(words):
return len(words.translate(str.maketrans('', '', ' ')))
total = 0
for i in range(1, 1001):
print(spell_out(i))
spelled = spell_out(i)
total += count(spelled)
print(total) |
#!/usr/bin/env python3
"""
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13,
we can see that the 6th prime is 13.
What is the 10,001st prime number?
https://projecteuler.net/problem=7
"""
| """
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13,
we can see that the 6th prime is 13.
What is the 10,001st prime number?
https://projecteuler.net/problem=7
""" |
def ping():
"""Always returns 'pong'."""
return 'pong'
def cowsay():
return r"""
___________________
< Hello Resource Hub! >
===================
\
\
^__^
(oo)\_______
(__)\ )\/\
||----w |
|| ||
"""
| def ping():
"""Always returns 'pong'."""
return 'pong'
def cowsay():
return '\n ___________________\n < Hello Resource Hub! >\n ===================\n \\\n \\\n ^__^\n (oo)\\_______\n (__)\\ )\\/\\\n ||----w |\n || ||\n ' |
def same_wind(history, **kwargs):
"""Set the tropopause wind at their previous values for the new state
:param history: Current history of state
:type history: :class:`History` object
"""
assert history.size > 1
previous_state = history.state_list[-2]
current_state = history.state_list[-1]
update_var = ['ut','vt','us','vs']
for var in update_var:
current_state.vrs[var] = previous_state.vrs[var]
| def same_wind(history, **kwargs):
"""Set the tropopause wind at their previous values for the new state
:param history: Current history of state
:type history: :class:`History` object
"""
assert history.size > 1
previous_state = history.state_list[-2]
current_state = history.state_list[-1]
update_var = ['ut', 'vt', 'us', 'vs']
for var in update_var:
current_state.vrs[var] = previous_state.vrs[var] |
def test_Compare():
a: bool
a = 5 > 4
a = 5 <= 4
a = 5 < 4
a = 5.6 >= 5.59999
a = 3.3 == 3.3
a = 3.3 != 3.4
a = complex(3, 4) == complex(3., 4.)
| def test__compare():
a: bool
a = 5 > 4
a = 5 <= 4
a = 5 < 4
a = 5.6 >= 5.59999
a = 3.3 == 3.3
a = 3.3 != 3.4
a = complex(3, 4) == complex(3.0, 4.0) |
def spaces(n, i):
countSpace= n-i
spaces = " "*countSpace
return spaces
def staircase(n):
for i in range(1, n+1):
cadena = spaces(n,i)
steps = "#"*i
cadena = cadena+steps
print(cadena)
if __name__ == "__main__":
tamanio = int(input("Ingresa el numero de escalones: "))
staircase(tamanio) | def spaces(n, i):
count_space = n - i
spaces = ' ' * countSpace
return spaces
def staircase(n):
for i in range(1, n + 1):
cadena = spaces(n, i)
steps = '#' * i
cadena = cadena + steps
print(cadena)
if __name__ == '__main__':
tamanio = int(input('Ingresa el numero de escalones: '))
staircase(tamanio) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.