content
stringlengths 7
1.05M
| fixed_cases
stringlengths 1
1.28M
|
---|---|
'''
>List of functions
1. contain(value,limit) - contains a value between 0 to limit
'''
def contain(value,limit):
if value<0:
return value+limit
elif value>=limit:
return value-limit
else:
return value | """
>List of functions
1. contain(value,limit) - contains a value between 0 to limit
"""
def contain(value, limit):
if value < 0:
return value + limit
elif value >= limit:
return value - limit
else:
return value |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# from unittest import mock
# from datakit_dworld.push import Push
def test_push(capsys):
"""Sample pytest test function with a built-in pytest fixture as an argument.
"""
# cmd = Greeting(None, None, cmd_name='dworld push')
# parsed_args = mock.Mock()
# parsed_args.greeting = 'Hello world!'
# cmd.run(parsed_args)
# out, err = capsys.readouterr()
# assert 'Hello world!' in out
| def test_push(capsys):
"""Sample pytest test function with a built-in pytest fixture as an argument.
""" |
# -*- coding: utf-8 -*-
"""
.. module:: pytfa
:platform: Unix, Windows
:synopsis: Simple Kinetic Models in Python
.. moduleauthor:: SKiMPy team
[---------]
Copyright 2017 Laboratory of Computational Systems Biotechnology (LCSB),
Ecole Polytechnique Federale de Lausanne (EPFL), Switzerland
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
""" Simulation types """
QSSA = 'qssa'
TQSSA = 'tqssa'
MCA = 'mca'
ODE = 'ode'
ELEMENTARY = 'elementary'
""" Jacobian Types"""
NUMERICAL = 'numerical'
SYMBOLIC = 'symbolic'
""" MCA Types """
NET = 'net'
SPLIT = 'split'
""" Item types """
PARAMETER = 'parameter'
VARIABLE = 'variable'
""" Units """
KCAL = 'kcal'
KJ = 'kJ'
JOULE = 'JOULE'
""" OTHER """
WATER_FORMULA = 'H2O'
| """
.. module:: pytfa
:platform: Unix, Windows
:synopsis: Simple Kinetic Models in Python
.. moduleauthor:: SKiMPy team
[---------]
Copyright 2017 Laboratory of Computational Systems Biotechnology (LCSB),
Ecole Polytechnique Federale de Lausanne (EPFL), Switzerland
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
' Simulation types '
qssa = 'qssa'
tqssa = 'tqssa'
mca = 'mca'
ode = 'ode'
elementary = 'elementary'
' Jacobian Types'
numerical = 'numerical'
symbolic = 'symbolic'
' MCA Types '
net = 'net'
split = 'split'
' Item types '
parameter = 'parameter'
variable = 'variable'
' Units '
kcal = 'kcal'
kj = 'kJ'
joule = 'JOULE'
' OTHER '
water_formula = 'H2O' |
class URLShortener:
def __init__(self):
self.id_counter = 0
self.links = {}
def getURL(self, short_id):
return self.links.get(short_id)
def shorten(self, url):
short_id = self.getNextId()
self.links.update({short_id: url})
return short_id
def getNextId(self):
self.id_counter += 1
# Id got from a URL is type str anyway so it is easiest to just use
# type str everywhere after this point.
return str(self.id_counter)
| class Urlshortener:
def __init__(self):
self.id_counter = 0
self.links = {}
def get_url(self, short_id):
return self.links.get(short_id)
def shorten(self, url):
short_id = self.getNextId()
self.links.update({short_id: url})
return short_id
def get_next_id(self):
self.id_counter += 1
return str(self.id_counter) |
print ('hello world')
print ('hey i did something')
print ('what happens if i do a ;');
print ('apparently nothing')
| print('hello world')
print('hey i did something')
print('what happens if i do a ;')
print('apparently nothing') |
class Bank:
def __init__(self):
self.__agencies = [1111, 2222, 3333]
self.__costumers = []
self.__accounts = []
def insert_costumers(self, costumer):
self.__costumers.append(costumer)
def insert_accounts(self, account):
self.__accounts.append(account)
def authenticate(self, costumer):
if costumer not in self.__costumers:
return None
| class Bank:
def __init__(self):
self.__agencies = [1111, 2222, 3333]
self.__costumers = []
self.__accounts = []
def insert_costumers(self, costumer):
self.__costumers.append(costumer)
def insert_accounts(self, account):
self.__accounts.append(account)
def authenticate(self, costumer):
if costumer not in self.__costumers:
return None |
'''
Python program to determine which triples sum to zero from a given list of lists.
Input: [[1343532, -2920635, 332], [-27, 18, 9], [4, 0, -4], [2, 2, 2], [-20, 16, 4]]
Output:
[False, True, True, False, True]
Input: [[1, 2, -3], [-4, 0, 4], [0, 1, -5], [1, 1, 1], [-2, 4, -1]]
Output:
[True, True, False, False, False]
'''
#License: https://bit.ly/3oLErEI
def test(nums):
return [sum(t)==0 for t in nums]
nums = [[1343532, -2920635, 332], [-27, 18, 9], [4, 0, -4], [2, 2, 2], [-20, 16, 4]]
print("Original list of lists:",nums)
print("Determine which triples sum to zero:")
print(test(nums))
nums = [[1, 2, -3], [-4, 0, 4], [0, 1, -5], [1, 1, 1], [-2, 4, -1]]
print("\nOriginal list of lists:",nums)
print("Determine which triples sum to zero:")
print(test(nums))
| """
Python program to determine which triples sum to zero from a given list of lists.
Input: [[1343532, -2920635, 332], [-27, 18, 9], [4, 0, -4], [2, 2, 2], [-20, 16, 4]]
Output:
[False, True, True, False, True]
Input: [[1, 2, -3], [-4, 0, 4], [0, 1, -5], [1, 1, 1], [-2, 4, -1]]
Output:
[True, True, False, False, False]
"""
def test(nums):
return [sum(t) == 0 for t in nums]
nums = [[1343532, -2920635, 332], [-27, 18, 9], [4, 0, -4], [2, 2, 2], [-20, 16, 4]]
print('Original list of lists:', nums)
print('Determine which triples sum to zero:')
print(test(nums))
nums = [[1, 2, -3], [-4, 0, 4], [0, 1, -5], [1, 1, 1], [-2, 4, -1]]
print('\nOriginal list of lists:', nums)
print('Determine which triples sum to zero:')
print(test(nums)) |
class AliasNotFound(Exception):
def __init__(self, alias):
self.alias = alias
class AliasAlreadyExists(Exception):
def __init__(self, alias):
self.alias = alias
class UnexpectedServerResponse(Exception):
def __init__(self, response):
self.response = response
| class Aliasnotfound(Exception):
def __init__(self, alias):
self.alias = alias
class Aliasalreadyexists(Exception):
def __init__(self, alias):
self.alias = alias
class Unexpectedserverresponse(Exception):
def __init__(self, response):
self.response = response |
def differentiate(fxn: str) -> str:
if fxn == "x":
return "1"
dividedFxn = getFirstLevel(fxn)
coeffOrTrig: str = dividedFxn[0]
exponent: str = dividedFxn[2]
insideParentheses: str = dividedFxn[1]
if coeffOrTrig.isalpha():
ans = computeTrig(coeffOrTrig, insideParentheses)
ans = ans + "*" + differentiate(insideParentheses)
if ans.endswith("*1"):
ans = list(ans)
ans.pop()
ans.pop()
ans = "".join(ans)
return ans
if len(exponent) != 0:
if len(coeffOrTrig) != 0 and coeffOrTrig.isnumeric():
ans = computeExpWithCoeff(coeffOrTrig, insideParentheses, exponent)
ans = ans + "*" + differentiate(insideParentheses)
ans = ans.replace("^1", "")
if ans.endswith("*1"):
ans = list(ans)
ans.pop()
ans.pop()
ans = "".join(ans)
return ans
else:
ans = computeExpWithoutCoeff(insideParentheses, exponent)
ans = ans + "*" + differentiate(insideParentheses)
ans = ans.replace("^1", "")
if ans.endswith("*1"):
ans = list(ans)
ans.pop()
ans.pop()
ans = "".join(ans)
return ans
if len(coeffOrTrig) == 0 and len(exponent) == 0:
ans = "1" + "*" + differentiate(insideParentheses)
ans = ans.replace("^1", "")
if ans.endswith("*1"):
ans = list(ans)
ans.pop()
ans.pop()
ans = "".join(ans)
return ans
def getFirstLevel(function: str) -> list:
indexOfOpen = function.find("(")
indexOfClose = function.rfind(")")
function = list(function)
function[indexOfOpen] = "|"
function[indexOfClose] = "|"
function = "".join(function)
assert function.count("|") == 2, "| != 2" # assert division by 2
return function.split("|")
def computeTrig(trig: str, inside: str) -> str:
if trig == "sin":
return "(cos({}))".format(inside)
elif trig == "cos":
return "(-sin({}))".format(inside)
elif trig == "tan":
return "(sec({})^2)".format(inside)
if trig == "sec":
return "(sec({})tan({}))".format(inside, inside)
if trig == "csc":
return "(-csc({})cot({}))".format(inside, inside)
if trig == "cot":
return "(-csc({})^2)".format(inside)
def computeExpWithCoeff(coeff: str, inside: str, exp: str) -> str:
cf = int(coeff)
expnt = int(exp.replace("^", ""))
cf = cf * expnt
expnt -= 1
return "{}({})^{}".format(cf, inside, expnt)
def computeExpWithoutCoeff(inside: str, exp: str) -> str:
expnt = int(exp.replace("^", ""))
cf = int(exp.replace("^", ""))
expnt -= 1
return "{}({})^{}".format(cf, inside, expnt)
OTHER_RECURSIVE_FUNCTIONS = [
"getFirstLevel",
"computeTrig",
"computeExpWithCoeff",
"computeExpWithoutCoeff",
]
print(differentiate("3(x)^3"))
| def differentiate(fxn: str) -> str:
if fxn == 'x':
return '1'
divided_fxn = get_first_level(fxn)
coeff_or_trig: str = dividedFxn[0]
exponent: str = dividedFxn[2]
inside_parentheses: str = dividedFxn[1]
if coeffOrTrig.isalpha():
ans = compute_trig(coeffOrTrig, insideParentheses)
ans = ans + '*' + differentiate(insideParentheses)
if ans.endswith('*1'):
ans = list(ans)
ans.pop()
ans.pop()
ans = ''.join(ans)
return ans
if len(exponent) != 0:
if len(coeffOrTrig) != 0 and coeffOrTrig.isnumeric():
ans = compute_exp_with_coeff(coeffOrTrig, insideParentheses, exponent)
ans = ans + '*' + differentiate(insideParentheses)
ans = ans.replace('^1', '')
if ans.endswith('*1'):
ans = list(ans)
ans.pop()
ans.pop()
ans = ''.join(ans)
return ans
else:
ans = compute_exp_without_coeff(insideParentheses, exponent)
ans = ans + '*' + differentiate(insideParentheses)
ans = ans.replace('^1', '')
if ans.endswith('*1'):
ans = list(ans)
ans.pop()
ans.pop()
ans = ''.join(ans)
return ans
if len(coeffOrTrig) == 0 and len(exponent) == 0:
ans = '1' + '*' + differentiate(insideParentheses)
ans = ans.replace('^1', '')
if ans.endswith('*1'):
ans = list(ans)
ans.pop()
ans.pop()
ans = ''.join(ans)
return ans
def get_first_level(function: str) -> list:
index_of_open = function.find('(')
index_of_close = function.rfind(')')
function = list(function)
function[indexOfOpen] = '|'
function[indexOfClose] = '|'
function = ''.join(function)
assert function.count('|') == 2, '| != 2'
return function.split('|')
def compute_trig(trig: str, inside: str) -> str:
if trig == 'sin':
return '(cos({}))'.format(inside)
elif trig == 'cos':
return '(-sin({}))'.format(inside)
elif trig == 'tan':
return '(sec({})^2)'.format(inside)
if trig == 'sec':
return '(sec({})tan({}))'.format(inside, inside)
if trig == 'csc':
return '(-csc({})cot({}))'.format(inside, inside)
if trig == 'cot':
return '(-csc({})^2)'.format(inside)
def compute_exp_with_coeff(coeff: str, inside: str, exp: str) -> str:
cf = int(coeff)
expnt = int(exp.replace('^', ''))
cf = cf * expnt
expnt -= 1
return '{}({})^{}'.format(cf, inside, expnt)
def compute_exp_without_coeff(inside: str, exp: str) -> str:
expnt = int(exp.replace('^', ''))
cf = int(exp.replace('^', ''))
expnt -= 1
return '{}({})^{}'.format(cf, inside, expnt)
other_recursive_functions = ['getFirstLevel', 'computeTrig', 'computeExpWithCoeff', 'computeExpWithoutCoeff']
print(differentiate('3(x)^3')) |
class register:
plugin_dict = {}
plugin_name = []
@classmethod
def register(cls, plugin_name):
def wrapper(plugin):
cls.plugin_dict[plugin_name] = plugin
return plugin
return wrapper | class Register:
plugin_dict = {}
plugin_name = []
@classmethod
def register(cls, plugin_name):
def wrapper(plugin):
cls.plugin_dict[plugin_name] = plugin
return plugin
return wrapper |
#B
def average(As :list) -> float:
return float(sum(As)/len(As))
def main():
# input
As = list(map(int, input().split()))
# compute
# output
print(average(As))
if __name__ == '__main__':
main()
| def average(As: list) -> float:
return float(sum(As) / len(As))
def main():
as = list(map(int, input().split()))
print(average(As))
if __name__ == '__main__':
main() |
if __name__ == '__main__':
pass
RESULT = 1
# DO NOT REMOVE NEXT LINE - KEEP IT INTENTIONALLY LAST
assert RESULT == 1, ''
| if __name__ == '__main__':
pass
result = 1
assert RESULT == 1, '' |
class ToolNameAPI:
thing = 'thing'
toolname_tool = 'example'
tln = ToolNameAPI()
the_repo = "reponame"
author = "authorname"
profile = "authorprofile" | class Toolnameapi:
thing = 'thing'
toolname_tool = 'example'
tln = tool_name_api()
the_repo = 'reponame'
author = 'authorname'
profile = 'authorprofile' |
class BaseFunction:
def __init__(self, name, n_calls, internal_ns):
self._name = name
self._n_calls = n_calls
self._internal_ns = internal_ns
@property
def name(self):
return self._name
@property
def n_calls(self):
return self._n_calls
@property
def internal_ns(self):
return self._internal_ns
class Lines:
def __init__(self, line_str, n_calls, internal, external):
self._line_str = line_str
self._n_calls = n_calls
self._internal = internal
self._external = external
@property
def text(self):
return self._line_str
@property
def n_calls(self):
return self._n_calls
@property
def internal(self):
return self._internal
@property
def external(self):
return self._external
@property
def total(self):
return self.internal + self.external
class Function(BaseFunction):
def __init__(self, name, lines, n_calls, internal_ns):
self._name = name
self._lines = lines
self._n_calls = n_calls
self._internal_ns = internal_ns
@property
def lines(self):
return self._lines
@property
def name(self):
return self._name
@property
def n_calls(self):
return self._n_calls
@property
def internal_ns(self):
return self._internal_ns
@property
def total(self):
tot = 0
for line in self.lines:
tot += line.total
return tot + self.internal_ns
class Profile:
@staticmethod
def from_data(data):
profile = Profile()
profile._functions = []
for key, fdata in data['functions'].items():
lines = []
for line in fdata['lines']:
line = Lines(line['line_str'], line['n_calls'],
line['internal_ns'], line['external_ns'])
lines.append(line)
func = Function(lines=lines, name=fdata['name'],
n_calls=fdata['n_calls'],
internal_ns=fdata['internal_ns'])
profile._functions.append(func)
return profile
@property
def functions(self):
return self._functions
| class Basefunction:
def __init__(self, name, n_calls, internal_ns):
self._name = name
self._n_calls = n_calls
self._internal_ns = internal_ns
@property
def name(self):
return self._name
@property
def n_calls(self):
return self._n_calls
@property
def internal_ns(self):
return self._internal_ns
class Lines:
def __init__(self, line_str, n_calls, internal, external):
self._line_str = line_str
self._n_calls = n_calls
self._internal = internal
self._external = external
@property
def text(self):
return self._line_str
@property
def n_calls(self):
return self._n_calls
@property
def internal(self):
return self._internal
@property
def external(self):
return self._external
@property
def total(self):
return self.internal + self.external
class Function(BaseFunction):
def __init__(self, name, lines, n_calls, internal_ns):
self._name = name
self._lines = lines
self._n_calls = n_calls
self._internal_ns = internal_ns
@property
def lines(self):
return self._lines
@property
def name(self):
return self._name
@property
def n_calls(self):
return self._n_calls
@property
def internal_ns(self):
return self._internal_ns
@property
def total(self):
tot = 0
for line in self.lines:
tot += line.total
return tot + self.internal_ns
class Profile:
@staticmethod
def from_data(data):
profile = profile()
profile._functions = []
for (key, fdata) in data['functions'].items():
lines = []
for line in fdata['lines']:
line = lines(line['line_str'], line['n_calls'], line['internal_ns'], line['external_ns'])
lines.append(line)
func = function(lines=lines, name=fdata['name'], n_calls=fdata['n_calls'], internal_ns=fdata['internal_ns'])
profile._functions.append(func)
return profile
@property
def functions(self):
return self._functions |
"""The PWM channel to use."""
CHANNEL0 = 0
"""Channel zero."""
CHANNEL1 = 1
"""Channel one."""
| """The PWM channel to use."""
channel0 = 0
'Channel zero.'
channel1 = 1
'Channel one.' |
S = str(input())
if S[0]==S[1] or S[1]==S[2] or S[2]==S[3]:
print("Bad")
else:
print("Good") | s = str(input())
if S[0] == S[1] or S[1] == S[2] or S[2] == S[3]:
print('Bad')
else:
print('Good') |
def main():
squareSum = 0 #(1 + 2)^2 square of the sums
sumSquare = 0 #1^2 + 2^2 sum of the squares
for i in range(1, 101):
sumSquare += i ** 2
squareSum += i
squareSum = squareSum ** 2
print(str(squareSum - sumSquare))
if __name__ == '__main__':
main()
| def main():
square_sum = 0
sum_square = 0
for i in range(1, 101):
sum_square += i ** 2
square_sum += i
square_sum = squareSum ** 2
print(str(squareSum - sumSquare))
if __name__ == '__main__':
main() |
def find_space(board):
for i in range(0,9):
for j in range(0,9):
if board[i][j]==0:
return (i,j)
return None
def check(board,num,r,c):
for i in range(0,9):
if board[r][i]==num and c!=i:
return False
for i in range(0,9):
if board[i][c]==num and r!=i:
return False
x=r//3
y=c//3
for i in range(x*3,x*3+3):
for j in range(y*3,y*3+3):
if board[i][j]==num and r!=i and c!=j:
return False
return True
def enter_datas(board):
for i in range(1,10):
print("Enter the Datas in Row ",i)
x=[int(i) for i in input().split()]
board.append(x)
def show(board):
for i in range(0,9):
for j in range(0,9):
if j==2 or j==5:
print(board[i][j]," | ",end="")
else:
print(board[i][j],end=" ")
if i==2 or i==5:
print("\n-----------------------\n")
else:
print("\n")
def solve(board):
x=find_space(board)
if not x:
return True
else:
r,c=x
for i in range(1,10):
if check(board,i,r,c):
board[r][c]=i
if solve(board):
return True
board[r][c]=0
return False
board=[]
enter_datas(board)
show(board)
solve(board)
print("\n\n")
show(board)
'''
Enter the Datas in a Row
7 8 0 4 0 0 1 2 0
Enter the Datas in a Row
6 0 0 0 7 5 0 0 9
Enter the Datas in a Row
0 0 0 6 0 1 0 7 8
Enter the Datas in a Row
0 0 7 0 4 0 2 6 0
Enter the Datas in a Row
0 0 1 0 5 0 9 3 0
Enter the Datas in a Row
9 0 4 0 6 0 0 0 5
Enter the Datas in a Row
0 7 0 3 0 0 0 1 2
Enter the Datas in a Row
1 2 0 0 0 7 4 0 0
Enter the Datas in a Row
0 4 9 2 0 6 0 0 7
''' | def find_space(board):
for i in range(0, 9):
for j in range(0, 9):
if board[i][j] == 0:
return (i, j)
return None
def check(board, num, r, c):
for i in range(0, 9):
if board[r][i] == num and c != i:
return False
for i in range(0, 9):
if board[i][c] == num and r != i:
return False
x = r // 3
y = c // 3
for i in range(x * 3, x * 3 + 3):
for j in range(y * 3, y * 3 + 3):
if board[i][j] == num and r != i and (c != j):
return False
return True
def enter_datas(board):
for i in range(1, 10):
print('Enter the Datas in Row ', i)
x = [int(i) for i in input().split()]
board.append(x)
def show(board):
for i in range(0, 9):
for j in range(0, 9):
if j == 2 or j == 5:
print(board[i][j], ' | ', end='')
else:
print(board[i][j], end=' ')
if i == 2 or i == 5:
print('\n-----------------------\n')
else:
print('\n')
def solve(board):
x = find_space(board)
if not x:
return True
else:
(r, c) = x
for i in range(1, 10):
if check(board, i, r, c):
board[r][c] = i
if solve(board):
return True
board[r][c] = 0
return False
board = []
enter_datas(board)
show(board)
solve(board)
print('\n\n')
show(board)
'\nEnter the Datas in a Row\n7 8 0 4 0 0 1 2 0\nEnter the Datas in a Row\n6 0 0 0 7 5 0 0 9\nEnter the Datas in a Row\n0 0 0 6 0 1 0 7 8\nEnter the Datas in a Row\n0 0 7 0 4 0 2 6 0\nEnter the Datas in a Row\n0 0 1 0 5 0 9 3 0\nEnter the Datas in a Row\n9 0 4 0 6 0 0 0 5\nEnter the Datas in a Row\n0 7 0 3 0 0 0 1 2\nEnter the Datas in a Row\n1 2 0 0 0 7 4 0 0\nEnter the Datas in a Row\n0 4 9 2 0 6 0 0 7\n' |
# A simple list
myList = [10,20,4,5,6,2,9,10,2,3,34,14]
#print the whole list
print("The List is {}".format(myList))
# printing elemts of the list one by one
print("printing elemts of the list one by one")
for elements in myList:
print(elements)
print("")
#printing elements that are greater than 10 only
print("printing elements that are greater than 10 only")
for elements in myList:
if(elements>10):
print(elements)
#printing elements that are greater that 10 but by using a list and appending the elements on it
newList = []
for elements in myList:
if(elements <10):
newList.append(elements)
print("")
print("Print the new List \n{}".format(newList))
#print the above list part using a single line
print(" The list is {}".format([item for item in myList if item < 10]))
# here [item { This is the out put} for item { the is the for part} in myList {This Is the input list} if item <10 {This is the condition}]
#Ask the user for an input and print the elemets of list less than that number
print("Input a number : ")
num = int(input())
print(" The elemnts of the list less that {} are {}".format(num,[item for item in myList if item < num]))
| my_list = [10, 20, 4, 5, 6, 2, 9, 10, 2, 3, 34, 14]
print('The List is {}'.format(myList))
print('printing elemts of the list one by one')
for elements in myList:
print(elements)
print('')
print('printing elements that are greater than 10 only')
for elements in myList:
if elements > 10:
print(elements)
new_list = []
for elements in myList:
if elements < 10:
newList.append(elements)
print('')
print('Print the new List \n{}'.format(newList))
print(' The list is {}'.format([item for item in myList if item < 10]))
print('Input a number : ')
num = int(input())
print(' The elemnts of the list less that {} are {}'.format(num, [item for item in myList if item < num])) |
#!/usr/bin/env python
# encoding: utf-8
'''
@author: yuxiqian
@license: MIT
@contact: akaza_akari@sjtu.edu.cn
@software: electsys-api
@file: electsysApi/shared/exception.py
@time: 2019/1/9
'''
class RequestError(BaseException):
pass
class ParseError(BaseException):
pass
class ParseWarning(Warning):
pass
| """
@author: yuxiqian
@license: MIT
@contact: akaza_akari@sjtu.edu.cn
@software: electsys-api
@file: electsysApi/shared/exception.py
@time: 2019/1/9
"""
class Requesterror(BaseException):
pass
class Parseerror(BaseException):
pass
class Parsewarning(Warning):
pass |
class Solution:
def duplicateZeros(self, arr: List[int]) -> None:
"""
Do not return anything, modify arr in-place instead.
"""
i = 0
for num in list(arr):
if i >= len(arr): break
arr[i] = num
if not num:
i += 1
if i < len(arr):
arr[i] = num
i += 1 | class Solution:
def duplicate_zeros(self, arr: List[int]) -> None:
"""
Do not return anything, modify arr in-place instead.
"""
i = 0
for num in list(arr):
if i >= len(arr):
break
arr[i] = num
if not num:
i += 1
if i < len(arr):
arr[i] = num
i += 1 |
def extractKaedesan721TumblrCom(item):
'''
Parser for 'kaedesan721.tumblr.com'
'''
bad_tags = [
'FanArt',
"htr asks",
'Spanish translations',
'htr anime','my thoughts',
'Cats',
'answered',
'ask meme',
'relay convos',
'translation related post',
'nightmare fuel',
'htr manga',
'memes',
'htrweek',
'Video Games',
'Animation',
'replies',
'jazz',
'Music',
]
if any([bad in item['tags'] for bad in bad_tags]):
return None
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
if "my translations" in item['tags']:
tagmap = [
('Hakata Tonkotsu Ramens', 'Hakata Tonkotsu Ramens', 'translated'),
('hakata tonktosu ramens', 'Hakata Tonkotsu Ramens', 'translated'),
('PRC', 'PRC', 'translated'),
('Loiterous', 'Loiterous', 'oel'),
]
for tagname, name, tl_type in tagmap:
if tagname in item['tags']:
return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
return False | def extract_kaedesan721_tumblr_com(item):
"""
Parser for 'kaedesan721.tumblr.com'
"""
bad_tags = ['FanArt', 'htr asks', 'Spanish translations', 'htr anime', 'my thoughts', 'Cats', 'answered', 'ask meme', 'relay convos', 'translation related post', 'nightmare fuel', 'htr manga', 'memes', 'htrweek', 'Video Games', 'Animation', 'replies', 'jazz', 'Music']
if any([bad in item['tags'] for bad in bad_tags]):
return None
(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 'my translations' in item['tags']:
tagmap = [('Hakata Tonkotsu Ramens', 'Hakata Tonkotsu Ramens', 'translated'), ('hakata tonktosu ramens', 'Hakata Tonkotsu Ramens', 'translated'), ('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')]
for (tagname, name, tl_type) in tagmap:
if tagname in item['tags']:
return build_release_message_with_type(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
return False |
#!/usr/bin/python3
# --- 001 > U5W2P1_Task3_w1
def solution(i):
return float(i)
if __name__ == "__main__":
print('----------start------------')
i = 12
print(solution( i ))
print('------------end------------')
| def solution(i):
return float(i)
if __name__ == '__main__':
print('----------start------------')
i = 12
print(solution(i))
print('------------end------------') |
n = int(input())
intz = [int(x) for x in input().split()]
alice = 0
bob = 0
for i, num in zip(range(n), sorted(intz)[::-1]):
if i%2 == 0:
alice += num
else:
bob += num
print(alice, bob) | n = int(input())
intz = [int(x) for x in input().split()]
alice = 0
bob = 0
for (i, num) in zip(range(n), sorted(intz)[::-1]):
if i % 2 == 0:
alice += num
else:
bob += num
print(alice, bob) |
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 13 13:35:33 2020
"""
#for finding loss of significances
x=1e-1
flag = True
a=0
while (flag):
print (((2*x)/(1-(x**2))),"......",(1/(1+x))-(1/(1-x)))
x= x*(1e-1)
a=a+1
if(a==25):
flag=False
| """
Created on Mon Apr 13 13:35:33 2020
"""
x = 0.1
flag = True
a = 0
while flag:
print(2 * x / (1 - x ** 2), '......', 1 / (1 + x) - 1 / (1 - x))
x = x * 0.1
a = a + 1
if a == 25:
flag = False |
class Test:
def __init__(self):
pass
def hi(self):
print("hello world") | class Test:
def __init__(self):
pass
def hi(self):
print('hello world') |
def rec_sum(n):
if(n<=1):
return n
else:
return(n+rec_sum(n-1))
| def rec_sum(n):
if n <= 1:
return n
else:
return n + rec_sum(n - 1) |
class Solution(object):
def twoSum(self, nums, target):
seen = {}
output = []
for i in range(len(nums)):
k = target - nums[i]
if k in seen:
output.append(seen[k])
output.append(i)
del seen[k]
else:
seen[nums[i]] = i
return output
class Solution2(object):
"""
If there is exactly one solution
"""
def twoSum(self, nums, target):
h = {}
for i, num in enumerate(nums):
n = target - num
if n not in h:
h[num] = i
else:
return [h[n], i]
if __name__ == '__main__':
sol = Solution()
print(sol.twoSum([2,7,11,15], 9))
print(sol.twoSum([3,3], 6)) | class Solution(object):
def two_sum(self, nums, target):
seen = {}
output = []
for i in range(len(nums)):
k = target - nums[i]
if k in seen:
output.append(seen[k])
output.append(i)
del seen[k]
else:
seen[nums[i]] = i
return output
class Solution2(object):
"""
If there is exactly one solution
"""
def two_sum(self, nums, target):
h = {}
for (i, num) in enumerate(nums):
n = target - num
if n not in h:
h[num] = i
else:
return [h[n], i]
if __name__ == '__main__':
sol = solution()
print(sol.twoSum([2, 7, 11, 15], 9))
print(sol.twoSum([3, 3], 6)) |
#
# PySNMP MIB module HPN-ICF-VOICE-IF-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HPN-ICF-VOICE-IF-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:41:57 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, ValueSizeConstraint, ConstraintsUnion, ConstraintsIntersection, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ValueSizeConstraint", "ConstraintsUnion", "ConstraintsIntersection", "ValueRangeConstraint")
hpnicfVoice, = mibBuilder.importSymbols("HPN-ICF-OID-MIB", "hpnicfVoice")
ifIndex, = mibBuilder.importSymbols("IF-MIB", "ifIndex")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
TimeTicks, Unsigned32, Gauge32, NotificationType, MibIdentifier, ModuleIdentity, Counter32, IpAddress, iso, Counter64, ObjectIdentity, Integer32, MibScalar, MibTable, MibTableRow, MibTableColumn, Bits = mibBuilder.importSymbols("SNMPv2-SMI", "TimeTicks", "Unsigned32", "Gauge32", "NotificationType", "MibIdentifier", "ModuleIdentity", "Counter32", "IpAddress", "iso", "Counter64", "ObjectIdentity", "Integer32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Bits")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
hpnicfVoiceInterface = ModuleIdentity((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 39, 13))
hpnicfVoiceInterface.setRevisions(('2007-12-10 17:00',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: hpnicfVoiceInterface.setRevisionsDescriptions(('The initial version of this MIB file.',))
if mibBuilder.loadTexts: hpnicfVoiceInterface.setLastUpdated('200712101700Z')
if mibBuilder.loadTexts: hpnicfVoiceInterface.setOrganization('')
if mibBuilder.loadTexts: hpnicfVoiceInterface.setContactInfo('')
if mibBuilder.loadTexts: hpnicfVoiceInterface.setDescription('This MIB file is to provide the definition of the voice interface general configuration.')
hpnicfVoiceIfObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 39, 13, 1))
hpnicfVoiceIfConfigTable = MibTable((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 39, 13, 1, 1), )
if mibBuilder.loadTexts: hpnicfVoiceIfConfigTable.setStatus('current')
if mibBuilder.loadTexts: hpnicfVoiceIfConfigTable.setDescription('The table contains configurable parameters for both analog voice interface and digital voice interface.')
hpnicfVoiceIfConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 39, 13, 1, 1, 1), ).setIndexNames((0, "IF-MIB", "ifIndex"))
if mibBuilder.loadTexts: hpnicfVoiceIfConfigEntry.setStatus('current')
if mibBuilder.loadTexts: hpnicfVoiceIfConfigEntry.setDescription('The entry of voice interface table.')
hpnicfVoiceIfCfgCngOn = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 39, 13, 1, 1, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('enable')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hpnicfVoiceIfCfgCngOn.setStatus('current')
if mibBuilder.loadTexts: hpnicfVoiceIfCfgCngOn.setDescription('This object indicates whether the silence gaps should be filled with background noise. It is applicable to FXO, FXS, E&M subscriber lines and E1/T1 voice subscriber line.')
hpnicfVoiceIfCfgNonLinearSwitch = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 39, 13, 1, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('enable')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hpnicfVoiceIfCfgNonLinearSwitch.setStatus('current')
if mibBuilder.loadTexts: hpnicfVoiceIfCfgNonLinearSwitch.setDescription('This object expresses the nonlinear processing is enable or disable for the voice interface. It is applicable to FXO, FXS, E&M subscriber lines and E1/T1 voice subscriber line. Currently, only digital voice subscriber lines can be set disabled.')
hpnicfVoiceIfCfgInputGain = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 39, 13, 1, 1, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-140, 139))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hpnicfVoiceIfCfgInputGain.setStatus('current')
if mibBuilder.loadTexts: hpnicfVoiceIfCfgInputGain.setDescription('This object indicates the amount of gain added to the receiver side of the voice interface. Unit is 0.1 db. It is applicable to FXO, FXS, E&M subscriber lines and E1/T1 voice subscriber line.')
hpnicfVoiceIfCfgOutputGain = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 39, 13, 1, 1, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-140, 139))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hpnicfVoiceIfCfgOutputGain.setStatus('current')
if mibBuilder.loadTexts: hpnicfVoiceIfCfgOutputGain.setDescription('This object indicates the amount of gain added to the send side of the voice interface. Unit is 0.1 db. It is applicable to FXO, FXS, E&M subscriber lines and E1/T1 voice subscriber line.')
hpnicfVoiceIfCfgEchoCancelSwitch = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 39, 13, 1, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('enable')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hpnicfVoiceIfCfgEchoCancelSwitch.setStatus('current')
if mibBuilder.loadTexts: hpnicfVoiceIfCfgEchoCancelSwitch.setDescription('This object indicates whether the echo cancellation is enabled. It is applicable to FXO, FXS, E&M subscriber lines and E1/T1 voice subscriber line.')
hpnicfVoiceIfCfgEchoCancelDelay = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 39, 13, 1, 1, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 64))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hpnicfVoiceIfCfgEchoCancelDelay.setStatus('current')
if mibBuilder.loadTexts: hpnicfVoiceIfCfgEchoCancelDelay.setDescription("This object indicates the delay of the echo cancellation for the voice interface. This value couldn't be modified unless hpnicfVoiceIfCfgEchoCancelSwitch is enable. Unit is milliseconds. It is applicable to FXO, FXS, E&M subscriber lines and E1/T1 voice subscriber line. The default value of this object is 32.")
hpnicfVoiceIfCfgTimerDialInterval = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 39, 13, 1, 1, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 300))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hpnicfVoiceIfCfgTimerDialInterval.setStatus('current')
if mibBuilder.loadTexts: hpnicfVoiceIfCfgTimerDialInterval.setDescription('The interval, in seconds, between two dialing numbers. The default value of this object is 10 seconds. It is applicable to FXO, FXS, E&M subscriber lines and E1/T1 with loop-start or ground-start protocol voice subscriber line.')
hpnicfVoiceIfCfgTimerFirstDial = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 39, 13, 1, 1, 1, 8), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 300))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hpnicfVoiceIfCfgTimerFirstDial.setStatus('current')
if mibBuilder.loadTexts: hpnicfVoiceIfCfgTimerFirstDial.setDescription('The period of time, in seconds, before dialing the first number. The default value of this object is 10 seconds. It is applicable to FXO, FXS subscriber lines and E1/T1 with loop-start or ground-start protocol voice subscriber line.')
hpnicfVoiceIfCfgPrivateline = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 39, 13, 1, 1, 1, 9), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 31))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hpnicfVoiceIfCfgPrivateline.setStatus('current')
if mibBuilder.loadTexts: hpnicfVoiceIfCfgPrivateline.setDescription('This object indicates the E.164 phone number for plar mode. It is applicable to FXO, FXS, E&M subscriber lines and E1/T1 voice subscriber line.')
hpnicfVoiceIfCfgRegTone = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 39, 13, 1, 1, 1, 10), OctetString().subtype(subtypeSpec=ConstraintsUnion(ValueSizeConstraint(0, 0), ValueSizeConstraint(2, 3), ))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hpnicfVoiceIfCfgRegTone.setStatus('current')
if mibBuilder.loadTexts: hpnicfVoiceIfCfgRegTone.setDescription('This object uses 2 or 3 letter country code specify voice parameters of different countrys. This value will take effect on all voice interfaces of all cards on the device.')
mibBuilder.exportSymbols("HPN-ICF-VOICE-IF-MIB", hpnicfVoiceInterface=hpnicfVoiceInterface, hpnicfVoiceIfCfgEchoCancelDelay=hpnicfVoiceIfCfgEchoCancelDelay, hpnicfVoiceIfConfigEntry=hpnicfVoiceIfConfigEntry, PYSNMP_MODULE_ID=hpnicfVoiceInterface, hpnicfVoiceIfObjects=hpnicfVoiceIfObjects, hpnicfVoiceIfCfgNonLinearSwitch=hpnicfVoiceIfCfgNonLinearSwitch, hpnicfVoiceIfCfgTimerFirstDial=hpnicfVoiceIfCfgTimerFirstDial, hpnicfVoiceIfCfgPrivateline=hpnicfVoiceIfCfgPrivateline, hpnicfVoiceIfCfgInputGain=hpnicfVoiceIfCfgInputGain, hpnicfVoiceIfCfgRegTone=hpnicfVoiceIfCfgRegTone, hpnicfVoiceIfCfgTimerDialInterval=hpnicfVoiceIfCfgTimerDialInterval, hpnicfVoiceIfCfgCngOn=hpnicfVoiceIfCfgCngOn, hpnicfVoiceIfCfgEchoCancelSwitch=hpnicfVoiceIfCfgEchoCancelSwitch, hpnicfVoiceIfCfgOutputGain=hpnicfVoiceIfCfgOutputGain, hpnicfVoiceIfConfigTable=hpnicfVoiceIfConfigTable)
| (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, value_size_constraint, constraints_union, constraints_intersection, value_range_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'SingleValueConstraint', 'ValueSizeConstraint', 'ConstraintsUnion', 'ConstraintsIntersection', 'ValueRangeConstraint')
(hpnicf_voice,) = mibBuilder.importSymbols('HPN-ICF-OID-MIB', 'hpnicfVoice')
(if_index,) = mibBuilder.importSymbols('IF-MIB', 'ifIndex')
(notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance')
(time_ticks, unsigned32, gauge32, notification_type, mib_identifier, module_identity, counter32, ip_address, iso, counter64, object_identity, integer32, mib_scalar, mib_table, mib_table_row, mib_table_column, bits) = mibBuilder.importSymbols('SNMPv2-SMI', 'TimeTicks', 'Unsigned32', 'Gauge32', 'NotificationType', 'MibIdentifier', 'ModuleIdentity', 'Counter32', 'IpAddress', 'iso', 'Counter64', 'ObjectIdentity', 'Integer32', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'Bits')
(display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention')
hpnicf_voice_interface = module_identity((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 39, 13))
hpnicfVoiceInterface.setRevisions(('2007-12-10 17:00',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts:
hpnicfVoiceInterface.setRevisionsDescriptions(('The initial version of this MIB file.',))
if mibBuilder.loadTexts:
hpnicfVoiceInterface.setLastUpdated('200712101700Z')
if mibBuilder.loadTexts:
hpnicfVoiceInterface.setOrganization('')
if mibBuilder.loadTexts:
hpnicfVoiceInterface.setContactInfo('')
if mibBuilder.loadTexts:
hpnicfVoiceInterface.setDescription('This MIB file is to provide the definition of the voice interface general configuration.')
hpnicf_voice_if_objects = mib_identifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 39, 13, 1))
hpnicf_voice_if_config_table = mib_table((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 39, 13, 1, 1))
if mibBuilder.loadTexts:
hpnicfVoiceIfConfigTable.setStatus('current')
if mibBuilder.loadTexts:
hpnicfVoiceIfConfigTable.setDescription('The table contains configurable parameters for both analog voice interface and digital voice interface.')
hpnicf_voice_if_config_entry = mib_table_row((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 39, 13, 1, 1, 1)).setIndexNames((0, 'IF-MIB', 'ifIndex'))
if mibBuilder.loadTexts:
hpnicfVoiceIfConfigEntry.setStatus('current')
if mibBuilder.loadTexts:
hpnicfVoiceIfConfigEntry.setDescription('The entry of voice interface table.')
hpnicf_voice_if_cfg_cng_on = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 39, 13, 1, 1, 1, 1), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('enable', 1), ('disable', 2))).clone('enable')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
hpnicfVoiceIfCfgCngOn.setStatus('current')
if mibBuilder.loadTexts:
hpnicfVoiceIfCfgCngOn.setDescription('This object indicates whether the silence gaps should be filled with background noise. It is applicable to FXO, FXS, E&M subscriber lines and E1/T1 voice subscriber line.')
hpnicf_voice_if_cfg_non_linear_switch = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 39, 13, 1, 1, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('enable', 1), ('disable', 2))).clone('enable')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
hpnicfVoiceIfCfgNonLinearSwitch.setStatus('current')
if mibBuilder.loadTexts:
hpnicfVoiceIfCfgNonLinearSwitch.setDescription('This object expresses the nonlinear processing is enable or disable for the voice interface. It is applicable to FXO, FXS, E&M subscriber lines and E1/T1 voice subscriber line. Currently, only digital voice subscriber lines can be set disabled.')
hpnicf_voice_if_cfg_input_gain = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 39, 13, 1, 1, 1, 3), integer32().subtype(subtypeSpec=value_range_constraint(-140, 139))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
hpnicfVoiceIfCfgInputGain.setStatus('current')
if mibBuilder.loadTexts:
hpnicfVoiceIfCfgInputGain.setDescription('This object indicates the amount of gain added to the receiver side of the voice interface. Unit is 0.1 db. It is applicable to FXO, FXS, E&M subscriber lines and E1/T1 voice subscriber line.')
hpnicf_voice_if_cfg_output_gain = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 39, 13, 1, 1, 1, 4), integer32().subtype(subtypeSpec=value_range_constraint(-140, 139))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
hpnicfVoiceIfCfgOutputGain.setStatus('current')
if mibBuilder.loadTexts:
hpnicfVoiceIfCfgOutputGain.setDescription('This object indicates the amount of gain added to the send side of the voice interface. Unit is 0.1 db. It is applicable to FXO, FXS, E&M subscriber lines and E1/T1 voice subscriber line.')
hpnicf_voice_if_cfg_echo_cancel_switch = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 39, 13, 1, 1, 1, 5), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('enable', 1), ('disable', 2))).clone('enable')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
hpnicfVoiceIfCfgEchoCancelSwitch.setStatus('current')
if mibBuilder.loadTexts:
hpnicfVoiceIfCfgEchoCancelSwitch.setDescription('This object indicates whether the echo cancellation is enabled. It is applicable to FXO, FXS, E&M subscriber lines and E1/T1 voice subscriber line.')
hpnicf_voice_if_cfg_echo_cancel_delay = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 39, 13, 1, 1, 1, 6), integer32().subtype(subtypeSpec=value_range_constraint(0, 64))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
hpnicfVoiceIfCfgEchoCancelDelay.setStatus('current')
if mibBuilder.loadTexts:
hpnicfVoiceIfCfgEchoCancelDelay.setDescription("This object indicates the delay of the echo cancellation for the voice interface. This value couldn't be modified unless hpnicfVoiceIfCfgEchoCancelSwitch is enable. Unit is milliseconds. It is applicable to FXO, FXS, E&M subscriber lines and E1/T1 voice subscriber line. The default value of this object is 32.")
hpnicf_voice_if_cfg_timer_dial_interval = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 39, 13, 1, 1, 1, 7), integer32().subtype(subtypeSpec=value_range_constraint(1, 300))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
hpnicfVoiceIfCfgTimerDialInterval.setStatus('current')
if mibBuilder.loadTexts:
hpnicfVoiceIfCfgTimerDialInterval.setDescription('The interval, in seconds, between two dialing numbers. The default value of this object is 10 seconds. It is applicable to FXO, FXS, E&M subscriber lines and E1/T1 with loop-start or ground-start protocol voice subscriber line.')
hpnicf_voice_if_cfg_timer_first_dial = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 39, 13, 1, 1, 1, 8), integer32().subtype(subtypeSpec=value_range_constraint(1, 300))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
hpnicfVoiceIfCfgTimerFirstDial.setStatus('current')
if mibBuilder.loadTexts:
hpnicfVoiceIfCfgTimerFirstDial.setDescription('The period of time, in seconds, before dialing the first number. The default value of this object is 10 seconds. It is applicable to FXO, FXS subscriber lines and E1/T1 with loop-start or ground-start protocol voice subscriber line.')
hpnicf_voice_if_cfg_privateline = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 39, 13, 1, 1, 1, 9), display_string().subtype(subtypeSpec=value_size_constraint(0, 31))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
hpnicfVoiceIfCfgPrivateline.setStatus('current')
if mibBuilder.loadTexts:
hpnicfVoiceIfCfgPrivateline.setDescription('This object indicates the E.164 phone number for plar mode. It is applicable to FXO, FXS, E&M subscriber lines and E1/T1 voice subscriber line.')
hpnicf_voice_if_cfg_reg_tone = mib_table_column((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 39, 13, 1, 1, 1, 10), octet_string().subtype(subtypeSpec=constraints_union(value_size_constraint(0, 0), value_size_constraint(2, 3)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
hpnicfVoiceIfCfgRegTone.setStatus('current')
if mibBuilder.loadTexts:
hpnicfVoiceIfCfgRegTone.setDescription('This object uses 2 or 3 letter country code specify voice parameters of different countrys. This value will take effect on all voice interfaces of all cards on the device.')
mibBuilder.exportSymbols('HPN-ICF-VOICE-IF-MIB', hpnicfVoiceInterface=hpnicfVoiceInterface, hpnicfVoiceIfCfgEchoCancelDelay=hpnicfVoiceIfCfgEchoCancelDelay, hpnicfVoiceIfConfigEntry=hpnicfVoiceIfConfigEntry, PYSNMP_MODULE_ID=hpnicfVoiceInterface, hpnicfVoiceIfObjects=hpnicfVoiceIfObjects, hpnicfVoiceIfCfgNonLinearSwitch=hpnicfVoiceIfCfgNonLinearSwitch, hpnicfVoiceIfCfgTimerFirstDial=hpnicfVoiceIfCfgTimerFirstDial, hpnicfVoiceIfCfgPrivateline=hpnicfVoiceIfCfgPrivateline, hpnicfVoiceIfCfgInputGain=hpnicfVoiceIfCfgInputGain, hpnicfVoiceIfCfgRegTone=hpnicfVoiceIfCfgRegTone, hpnicfVoiceIfCfgTimerDialInterval=hpnicfVoiceIfCfgTimerDialInterval, hpnicfVoiceIfCfgCngOn=hpnicfVoiceIfCfgCngOn, hpnicfVoiceIfCfgEchoCancelSwitch=hpnicfVoiceIfCfgEchoCancelSwitch, hpnicfVoiceIfCfgOutputGain=hpnicfVoiceIfCfgOutputGain, hpnicfVoiceIfConfigTable=hpnicfVoiceIfConfigTable) |
# standard traversal problem
class Solution(object):
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
# leaf condition
if root == None:
return 0
# skeleton, since function has return, need to assign variables for following usage
left_depth = self.maxDepth(root.left)
right_depth = self.maxDepth(root.right)
# this is according to the definition
return max(left_depth, right_depth) + 1 | class Solution(object):
def max_depth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if root == None:
return 0
left_depth = self.maxDepth(root.left)
right_depth = self.maxDepth(root.right)
return max(left_depth, right_depth) + 1 |
class GlobalOptions:
""" Class to evaluate global options for example: project path"""
@staticmethod
def evaluate_project_path(path):
""" Method to parse the project path provided by the user"""
first_dir_from_end = None
if path[-1] != "/":
path = path + "/"
new_path = path.rsplit('/')[-2]
for directory in new_path[::-1]:
if directory != " ":
first_dir_from_end = new_path
break
return first_dir_from_end
| class Globaloptions:
""" Class to evaluate global options for example: project path"""
@staticmethod
def evaluate_project_path(path):
""" Method to parse the project path provided by the user"""
first_dir_from_end = None
if path[-1] != '/':
path = path + '/'
new_path = path.rsplit('/')[-2]
for directory in new_path[::-1]:
if directory != ' ':
first_dir_from_end = new_path
break
return first_dir_from_end |
gScore = 0 #use this to index g(n)
fScore = 1 #use this to index f(n)
previous = 2 #use this to index previous node
inf = 10000 #use this for value of infinity
#we represent the graph usind adjacent list
#as dictionary of dictionaries
G = {
'biratnagar' : {'itahari' : 22, 'biratchowk' : 30, 'rangeli': 25},
'itahari' : {'biratnagar' : 22, 'dharan' : 20, 'biratchowk' : 11},
'dharan' : {'itahari' : 20},
'biratchowk' : {'biratnagar' : 30, 'itahari' : 11, 'kanepokhari' :10},
'rangeli' : {'biratnagar' : 25, 'kanepokhari' : 25, 'urlabari' : 40},
'kanepokhari' : {'rangeli' : 25, 'biratchowk' : 10, 'urlabari' : 12},
'urlabari' : {'rangeli' : 40, 'kanepokhari' : 12, 'damak' : 6},
'damak' : {'urlabari' : 6}
}
def h(city):
#returns straight line distance from a city to damak
h = {
'biratnagar' : 46,
'itahari' : 39,
'dharan' : 41,
'rangeli' : 28,
'biratchowk' : 29,
'kanepokhari' : 17,
'urlabari' : 6,
'damak' : 0
}
return h[city]
def getMinimum(unvisited):
#returns city with minimum f(n)
currDist = inf
leastFScoreCity = ''
for city in unvisited:
if unvisited[city][fScore] < currDist:
currDist = unvisited[city][fScore]
leastFScoreCity = city
return leastFScoreCity
def aStar(G, start, goal):
visited = {} #we declare visited list as empty dict
unvisited = {} #we declare unvisited list as empty dict
#we now add every city to the unvisited
for city in G.keys():
unvisited[city] = [inf, inf, ""]
hScore = h(start)
#for starting node, the g(n) is 0, so f(n) will be h(n)
unvisited[start] = [0, hScore, ""]
finished = False
while finished == False:
#if there are no nodes to evaluate in unvisited
if len(unvisited) == 0:
finished = True
else:
#find the node with lowest f(n) from open list
currentNode = getMinimum(unvisited)
if currentNode == goal:
finished = True
#copy data to visited list
visited[currentNode] = unvisited[currentNode]
else:
#we examine the neighbors of currentNode
for neighbor in G[currentNode]:
#we only check unvisited neighbors
if neighbor not in visited:
newGScore = unvisited[currentNode][gScore] + G[currentNode][neighbor]
if newGScore < unvisited[neighbor][gScore]:
unvisited[neighbor][gScore] = newGScore
unvisited[neighbor][fScore] = newGScore + h(neighbor)
unvisited[neighbor][previous] = currentNode
#we now add currentNode to the visited list
visited[currentNode] = unvisited[currentNode]
#we now remove the currentNode from unvisited
del unvisited[currentNode]
return visited
def findPath(visitSequence, goal):
answer = []
answer.append(goal)
currCity = goal
while visitSequence[currCity][previous] != '':
prevCity = visitSequence[currCity][previous]
answer.append(prevCity)
currCity = prevCity
return answer[::-1]
start = 'biratnagar'
goal = 'damak'
visitSequence = aStar(G, start, goal)
path = findPath(visitSequence, goal)
print(path)
| g_score = 0
f_score = 1
previous = 2
inf = 10000
g = {'biratnagar': {'itahari': 22, 'biratchowk': 30, 'rangeli': 25}, 'itahari': {'biratnagar': 22, 'dharan': 20, 'biratchowk': 11}, 'dharan': {'itahari': 20}, 'biratchowk': {'biratnagar': 30, 'itahari': 11, 'kanepokhari': 10}, 'rangeli': {'biratnagar': 25, 'kanepokhari': 25, 'urlabari': 40}, 'kanepokhari': {'rangeli': 25, 'biratchowk': 10, 'urlabari': 12}, 'urlabari': {'rangeli': 40, 'kanepokhari': 12, 'damak': 6}, 'damak': {'urlabari': 6}}
def h(city):
h = {'biratnagar': 46, 'itahari': 39, 'dharan': 41, 'rangeli': 28, 'biratchowk': 29, 'kanepokhari': 17, 'urlabari': 6, 'damak': 0}
return h[city]
def get_minimum(unvisited):
curr_dist = inf
least_f_score_city = ''
for city in unvisited:
if unvisited[city][fScore] < currDist:
curr_dist = unvisited[city][fScore]
least_f_score_city = city
return leastFScoreCity
def a_star(G, start, goal):
visited = {}
unvisited = {}
for city in G.keys():
unvisited[city] = [inf, inf, '']
h_score = h(start)
unvisited[start] = [0, hScore, '']
finished = False
while finished == False:
if len(unvisited) == 0:
finished = True
else:
current_node = get_minimum(unvisited)
if currentNode == goal:
finished = True
visited[currentNode] = unvisited[currentNode]
else:
for neighbor in G[currentNode]:
if neighbor not in visited:
new_g_score = unvisited[currentNode][gScore] + G[currentNode][neighbor]
if newGScore < unvisited[neighbor][gScore]:
unvisited[neighbor][gScore] = newGScore
unvisited[neighbor][fScore] = newGScore + h(neighbor)
unvisited[neighbor][previous] = currentNode
visited[currentNode] = unvisited[currentNode]
del unvisited[currentNode]
return visited
def find_path(visitSequence, goal):
answer = []
answer.append(goal)
curr_city = goal
while visitSequence[currCity][previous] != '':
prev_city = visitSequence[currCity][previous]
answer.append(prevCity)
curr_city = prevCity
return answer[::-1]
start = 'biratnagar'
goal = 'damak'
visit_sequence = a_star(G, start, goal)
path = find_path(visitSequence, goal)
print(path) |
t=int(input(""))
while (t>0):
n=int(input(""))
f=1
for i in range(1,n+1):
f=f*i
print(f)
t=t-1
| t = int(input(''))
while t > 0:
n = int(input(''))
f = 1
for i in range(1, n + 1):
f = f * i
print(f)
t = t - 1 |
class Solution(object):
def isUgly(self, num):
"""
:type num: int
:rtype: bool
"""
if num <= 0:
return False
for x in [2,3,5]:
while(num % x ==0):
num /= x
return num==1 | class Solution(object):
def is_ugly(self, num):
"""
:type num: int
:rtype: bool
"""
if num <= 0:
return False
for x in [2, 3, 5]:
while num % x == 0:
num /= x
return num == 1 |
#Area of a rectangle = width x length
#Perimeter of a rectangle = 2 x [length + width#
width_input = float (input("\nPlease enter width: "))
length_input = float (input("Please enter length: "))
areaofRectangle = width_input * length_input
perimeterofRectangle = 2 * (width_input * length_input)
print ("\nArea of Rectangle is: " , areaofRectangle, "CM")
print("\nPerimeter of Rectangle is: ", perimeterofRectangle, "CM")
| width_input = float(input('\nPlease enter width: '))
length_input = float(input('Please enter length: '))
areaof_rectangle = width_input * length_input
perimeterof_rectangle = 2 * (width_input * length_input)
print('\nArea of Rectangle is: ', areaofRectangle, 'CM')
print('\nPerimeter of Rectangle is: ', perimeterofRectangle, 'CM') |
class DNASuitEdge:
COMPONENT_CODE = 22
def __init__(self, startPoint, endPoint, zoneId):
self.startPoint = startPoint
self.endPoint = endPoint
self.zoneId = zoneId
def setStartPoint(self, startPoint):
self.startPoint = startPoint
def setEndPoint(self, endPoint):
self.endPoint = endPoint
def setZoneId(self, zoneId):
self.zoneId = zoneId
| class Dnasuitedge:
component_code = 22
def __init__(self, startPoint, endPoint, zoneId):
self.startPoint = startPoint
self.endPoint = endPoint
self.zoneId = zoneId
def set_start_point(self, startPoint):
self.startPoint = startPoint
def set_end_point(self, endPoint):
self.endPoint = endPoint
def set_zone_id(self, zoneId):
self.zoneId = zoneId |
# This just shifts 1 to i th BIT
def BIT(i: int) -> int:
return int(1 << i)
# This class is equvalent to a C++ enum
class EventType:
Null, \
WindowClose, WindowResize, WindowFocus, WindowMoved, \
AppTick, AppUpdate, AppRender, \
KeyPressed, KeyReleased, CharInput, \
MouseButtonPressed, MouseButtonReleased, MouseMoved, MouseScrolled \
= range(0, 15)
# This class is equvalent to a C++ enum
# It uses bitstream to represent flags, so
# a single Event can have multiple flags
class EventCategory:
Null = 0
Application = BIT(0)
Input = BIT(1)
Keyboard = BIT(2)
Mouse = BIT(3)
MouseButton = BIT(4)
class Event:
Handled = False
@property
def EventType(self) -> int:
pass
@property
def Name(self) -> str:
return type(self)
@property
def CategoryFlags(self) -> int:
pass
def ToString(self) -> str:
return self.GetName()
def IsInCategory(self, category: int) -> bool:
return bool(self.CategoryFlags & category)
def __repr__(self) -> str:
return self.ToString()
class EventDispatcher:
__slots__ = ("_Event",)
def __init__(self, event: Event) -> None:
self._Event = event
def Dispach(self, func, eventType: int) -> bool:
if (self._Event.EventType == eventType):
handeled = func(self._Event)
self._Event.Handled = handeled
return True
return False
| def bit(i: int) -> int:
return int(1 << i)
class Eventtype:
(null, window_close, window_resize, window_focus, window_moved, app_tick, app_update, app_render, key_pressed, key_released, char_input, mouse_button_pressed, mouse_button_released, mouse_moved, mouse_scrolled) = range(0, 15)
class Eventcategory:
null = 0
application = bit(0)
input = bit(1)
keyboard = bit(2)
mouse = bit(3)
mouse_button = bit(4)
class Event:
handled = False
@property
def event_type(self) -> int:
pass
@property
def name(self) -> str:
return type(self)
@property
def category_flags(self) -> int:
pass
def to_string(self) -> str:
return self.GetName()
def is_in_category(self, category: int) -> bool:
return bool(self.CategoryFlags & category)
def __repr__(self) -> str:
return self.ToString()
class Eventdispatcher:
__slots__ = ('_Event',)
def __init__(self, event: Event) -> None:
self._Event = event
def dispach(self, func, eventType: int) -> bool:
if self._Event.EventType == eventType:
handeled = func(self._Event)
self._Event.Handled = handeled
return True
return False |
class Users:
usernamep = 'your_user_email'
passwordp = 'your_password'
linkp = 'https://www.instagram.com/stories/cznburak/'
| class Users:
usernamep = 'your_user_email'
passwordp = 'your_password'
linkp = 'https://www.instagram.com/stories/cznburak/' |
INSTANCES = 405
ITERS = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 50, 100]
N_ITERS = len(ITERS)
# === RESULTS GATHERING ====================================================== #
# results_m is a [INSTANCES][N_ITERS] matrix to store every test result
results_m = [[0 for x in range(N_ITERS)] for y in range(INSTANCES)]
for I in range(N_ITERS):
fin = open("tests/" + str(ITERS[I]))
out = fin.read()
fin.close()
counter = 0
for line in out.splitlines():
results_m[counter][I] = int(line)
counter += 1
# === CALCULATING AVERAGES =================================================== #
averages = [0.0 for x in range(N_ITERS)]
for I in range(INSTANCES):
for J in range(N_ITERS):
results_m[I][J] = results_m[I][J] - results_m[I][0]
if (results_m[I][N_ITERS-1] != 0):
results_m[I][J] = float(results_m[I][J] / results_m[I][N_ITERS-1])
averages[J] += results_m[I][J]
for J in range(N_ITERS):
averages[J] = averages[J]/INSTANCES
for J in range(N_ITERS-1, 1, -1):
averages[J] -= averages[J-1]
# === PRINTING RESULTS ======================================================= #
print("========================================")
print(" all tests:")
for J in range(1, N_ITERS):
if (ITERS[J] < 10):
print(" " + str(ITERS[J]) + ": " + str(100 * averages[J]) + '%')
elif (ITERS[J] < 100):
print(" " + str(ITERS[J]) + ": " + str(100 * averages[J]) + '%')
else:
print(" " + str(ITERS[J]) + ": " + str(100 * averages[J]) + '%')
print("========================================")
# ============================================================================ #
| instances = 405
iters = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 50, 100]
n_iters = len(ITERS)
results_m = [[0 for x in range(N_ITERS)] for y in range(INSTANCES)]
for i in range(N_ITERS):
fin = open('tests/' + str(ITERS[I]))
out = fin.read()
fin.close()
counter = 0
for line in out.splitlines():
results_m[counter][I] = int(line)
counter += 1
averages = [0.0 for x in range(N_ITERS)]
for i in range(INSTANCES):
for j in range(N_ITERS):
results_m[I][J] = results_m[I][J] - results_m[I][0]
if results_m[I][N_ITERS - 1] != 0:
results_m[I][J] = float(results_m[I][J] / results_m[I][N_ITERS - 1])
averages[J] += results_m[I][J]
for j in range(N_ITERS):
averages[J] = averages[J] / INSTANCES
for j in range(N_ITERS - 1, 1, -1):
averages[J] -= averages[J - 1]
print('========================================')
print(' all tests:')
for j in range(1, N_ITERS):
if ITERS[J] < 10:
print(' ' + str(ITERS[J]) + ': ' + str(100 * averages[J]) + '%')
elif ITERS[J] < 100:
print(' ' + str(ITERS[J]) + ': ' + str(100 * averages[J]) + '%')
else:
print(' ' + str(ITERS[J]) + ': ' + str(100 * averages[J]) + '%')
print('========================================') |
# -*- coding: utf-8 -*-
# Copyright 1996-2015 PSERC. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
# Copyright (c) 2016-2020 by University of Kassel and Fraunhofer Institute for Energy Economics
# and Energy System Technology (IEE), Kassel. All rights reserved.
"""Defines constants for named column indices to bus matrix.
Some examples of usage, after defining the constants using the line above,
are::
Pd = bus[3, PD] # get the real power demand at bus 4
bus[:, VMIN] = 0.95 # set the min voltage magnitude to 0.95 at all buses
The index, name and meaning of each column of the bus matrix is given
below:
columns 0-12 must be included in input matrix (in case file)
0. C{BUS_I} bus number (1 to 29997)
1. C{BUS_TYPE} bus type (1 = PQ, 2 = PV, 3 = ref, 4 = isolated)
2. C{PD} real power demand (MW)
3. C{QD} reactive power demand (MVAr)
4. C{GS} shunt conductance (MW at V = 1.0 p.u.)
5. C{BS} shunt susceptance (MVAr at V = 1.0 p.u.)
6. C{BUS_AREA} area number, 1-100
7. C{VM} voltage magnitude (p.u.)
8. C{VA} voltage angle (degrees)
9. C{BASE_KV} base voltage (kV)
10. C{ZONE} loss zone (1-999)
11. C{VMAX} maximum voltage magnitude (p.u.)
12. C{VMIN} minimum voltage magnitude (p.u.)
columns 13-16 are added to matrix after OPF solution
they are typically not present in the input matrix
(assume OPF objective function has units, u)
13. C{LAM_P} Lagrange multiplier on real power mismatch (u/MW)
14. C{LAM_Q} Lagrange multiplier on reactive power mismatch (u/MVAr)
15. C{MU_VMAX} Kuhn-Tucker multiplier on upper voltage limit (u/p.u.)
16. C{MU_VMIN} Kuhn-Tucker multiplier on lower voltage limit (u/p.u.)
additional constants, used to assign/compare values in the C{BUS_TYPE} column
1. C{PQ} PQ bus
2. C{PV} PV bus
3. C{REF} reference bus
4. C{NONE} isolated bus
@author: Ray Zimmerman (PSERC Cornell)
@author: Richard Lincoln
"""
# define bus types
PQ = 1
PV = 2
REF = 3
NONE = 4
# define the indices
BUS_I = 0 # bus number (1 to 29997)
BUS_TYPE = 1 # bus type
PD = 2 # Pd, real power demand (MW)
QD = 3 # Qd, reactive power demand (MVAr)
GS = 4 # Gs, shunt conductance (MW at V = 1.0 p.u.)
BS = 5 # Bs, shunt susceptance (MVAr at V = 1.0 p.u.)
BUS_AREA = 6 # area number, 1-100
VM = 7 # Vm, voltage magnitude (p.u.)
VA = 8 # Va, voltage angle (degrees)
BASE_KV = 9 # baseKV, base voltage (kV)
ZONE = 10 # zone, loss zone (1-999)
VMAX = 11 # maxVm, maximum voltage magnitude (p.u.)
VMIN = 12 # minVm, minimum voltage magnitude (p.u.)
# included in opf solution, not necessarily in input
# assume objective function has units, u
LAM_P = 13 # Lagrange multiplier on real power mismatch (u/MW)
LAM_Q = 14 # Lagrange multiplier on reactive power mismatch (u/MVAr)
MU_VMAX = 15 # Kuhn-Tucker multiplier on upper voltage limit (u/p.u.)
MU_VMIN = 16 # Kuhn-Tucker multiplier on lower voltage limit (u/p.u.)
# Additional pandapower extensions to ppc
CID = 13 # coefficient of constant current load at rated voltage in range [0,1]
CZD = 14 # coefficient of constant impedance load at rated voltage in range [0,1]
bus_cols = 15
| """Defines constants for named column indices to bus matrix.
Some examples of usage, after defining the constants using the line above,
are::
Pd = bus[3, PD] # get the real power demand at bus 4
bus[:, VMIN] = 0.95 # set the min voltage magnitude to 0.95 at all buses
The index, name and meaning of each column of the bus matrix is given
below:
columns 0-12 must be included in input matrix (in case file)
0. C{BUS_I} bus number (1 to 29997)
1. C{BUS_TYPE} bus type (1 = PQ, 2 = PV, 3 = ref, 4 = isolated)
2. C{PD} real power demand (MW)
3. C{QD} reactive power demand (MVAr)
4. C{GS} shunt conductance (MW at V = 1.0 p.u.)
5. C{BS} shunt susceptance (MVAr at V = 1.0 p.u.)
6. C{BUS_AREA} area number, 1-100
7. C{VM} voltage magnitude (p.u.)
8. C{VA} voltage angle (degrees)
9. C{BASE_KV} base voltage (kV)
10. C{ZONE} loss zone (1-999)
11. C{VMAX} maximum voltage magnitude (p.u.)
12. C{VMIN} minimum voltage magnitude (p.u.)
columns 13-16 are added to matrix after OPF solution
they are typically not present in the input matrix
(assume OPF objective function has units, u)
13. C{LAM_P} Lagrange multiplier on real power mismatch (u/MW)
14. C{LAM_Q} Lagrange multiplier on reactive power mismatch (u/MVAr)
15. C{MU_VMAX} Kuhn-Tucker multiplier on upper voltage limit (u/p.u.)
16. C{MU_VMIN} Kuhn-Tucker multiplier on lower voltage limit (u/p.u.)
additional constants, used to assign/compare values in the C{BUS_TYPE} column
1. C{PQ} PQ bus
2. C{PV} PV bus
3. C{REF} reference bus
4. C{NONE} isolated bus
@author: Ray Zimmerman (PSERC Cornell)
@author: Richard Lincoln
"""
pq = 1
pv = 2
ref = 3
none = 4
bus_i = 0
bus_type = 1
pd = 2
qd = 3
gs = 4
bs = 5
bus_area = 6
vm = 7
va = 8
base_kv = 9
zone = 10
vmax = 11
vmin = 12
lam_p = 13
lam_q = 14
mu_vmax = 15
mu_vmin = 16
cid = 13
czd = 14
bus_cols = 15 |
#
# PySNMP MIB module SW-VLAN-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/SW-VLAN-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:12:44 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
Integer, ObjectIdentifier, OctetString = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueRangeConstraint, ValueSizeConstraint, ConstraintsUnion, ConstraintsIntersection, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ValueSizeConstraint", "ConstraintsUnion", "ConstraintsIntersection", "SingleValueConstraint")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
enterprises, iso, ModuleIdentity, MibScalar, MibTable, MibTableRow, MibTableColumn, Bits, Counter32, Integer32, Unsigned32, Gauge32, IpAddress, ObjectIdentity, MibIdentifier, Counter64, TimeTicks, NotificationType = mibBuilder.importSymbols("SNMPv2-SMI", "enterprises", "iso", "ModuleIdentity", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Bits", "Counter32", "Integer32", "Unsigned32", "Gauge32", "IpAddress", "ObjectIdentity", "MibIdentifier", "Counter64", "TimeTicks", "NotificationType")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
class MacAddress(OctetString):
subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(6, 6)
fixedLength = 6
class VlanIndex(Integer32):
subtypeSpec = Integer32.subtypeSpec + ValueRangeConstraint(1, 4094)
class PortList(OctetString):
subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(12, 12)
fixedLength = 12
marconi = MibIdentifier((1, 3, 6, 1, 4, 1, 326))
systems = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2))
external = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 20))
dlink = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1))
dlinkcommon = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 1))
golf = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2))
golfproducts = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 1))
es2000 = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 1, 3))
golfcommon = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2))
marconi_mgmt = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2)).setLabel("marconi-mgmt")
es2000Mgmt = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28))
swL2Mgmt = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2))
swVlan = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8))
swVlanCtrl = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 1))
swMacBaseVlan = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 2))
swPortBaseVlan = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 3))
swVlanCtrlMode = MibScalar((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("other", 1), ("disabled", 2), ("mac-base", 3), ("ieee8021q", 4), ("port-base", 5)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: swVlanCtrlMode.setStatus('mandatory')
if mibBuilder.loadTexts: swVlanCtrlMode.setDescription('This object controls which Vlan function will be enable (or disable) when the switch hub restart at the startup (power on) or warm start.')
swVlanInfoStatus = MibScalar((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("other", 1), ("disabled", 2), ("mac-base", 3), ("ieee8021q", 4), ("port-base", 5)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: swVlanInfoStatus.setStatus('mandatory')
if mibBuilder.loadTexts: swVlanInfoStatus.setDescription('This object indicates which Vlan function be enable (or disable) in mandatoryly stage. There are no effect when change swVlanCtrlMode vlaue in the system running.')
swVlanSnmpPortVlan = MibScalar((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 1, 3), VlanIndex()).setMaxAccess("readonly")
if mibBuilder.loadTexts: swVlanSnmpPortVlan.setStatus('mandatory')
if mibBuilder.loadTexts: swVlanSnmpPortVlan.setDescription('Indicates the Vlan which the SNMP port belongs to. The value range is 1 to 4094.')
swMacBaseVlanInfo = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 2, 1))
swMacBaseVlanMaxNum = MibScalar((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 2, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: swMacBaseVlanMaxNum.setStatus('mandatory')
if mibBuilder.loadTexts: swMacBaseVlanMaxNum.setDescription('The maximum number of Mac base Vlan allowed by the system.')
swMacBaseVlanAddrMaxNum = MibScalar((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 2, 1, 2), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: swMacBaseVlanAddrMaxNum.setStatus('mandatory')
if mibBuilder.loadTexts: swMacBaseVlanAddrMaxNum.setDescription('The maximum number of entries in Mac-based Vlan address table.')
swMacBaseVlanCtrlTable = MibTable((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 2, 2), )
if mibBuilder.loadTexts: swMacBaseVlanCtrlTable.setStatus('mandatory')
if mibBuilder.loadTexts: swMacBaseVlanCtrlTable.setDescription('A table that contains information about MAC base Vlan entries for which the switch has forwarding and/or filtering information. This information is used by the transparent switching function in determining how to propagate a received frame.')
swMacBaseVlanCtrlEntry = MibTableRow((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 2, 2, 1), ).setIndexNames((0, "SW-VLAN-MIB", "swMacBaseVlanDesc"))
if mibBuilder.loadTexts: swMacBaseVlanCtrlEntry.setStatus('mandatory')
if mibBuilder.loadTexts: swMacBaseVlanCtrlEntry.setDescription('A list of information about a specific MAC base Vlan configuration portlist for which the switch has some forwarding and/or filtering information.')
swMacBaseVlanDesc = MibTableColumn((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 2, 2, 1, 1), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 12))).setMaxAccess("readonly")
if mibBuilder.loadTexts: swMacBaseVlanDesc.setStatus('mandatory')
if mibBuilder.loadTexts: swMacBaseVlanDesc.setDescription('A textual description of the Mac Base Vlan for memorization. The string cannot set to empty string. There is a default value for this string.')
swMacBaseVlanMacMember = MibTableColumn((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 2, 2, 1, 2), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: swMacBaseVlanMacMember.setStatus('mandatory')
if mibBuilder.loadTexts: swMacBaseVlanMacMember.setDescription('This object indicates the total number of MAC addresses contained in the VLAN entry.')
swMacBaseVlanCtrlState = MibTableColumn((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 2, 2, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("other", 1), ("disabled", 2), ("enabled", 3)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: swMacBaseVlanCtrlState.setStatus('mandatory')
if mibBuilder.loadTexts: swMacBaseVlanCtrlState.setDescription('This object indicates the MacBase Vlan state.')
swMacBaseVlanAddrTable = MibTable((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 2, 3), )
if mibBuilder.loadTexts: swMacBaseVlanAddrTable.setStatus('mandatory')
if mibBuilder.loadTexts: swMacBaseVlanAddrTable.setDescription('A table that contains information about unicast or multicast entries for which the switch has forwarding and/or filtering information. This information is used by the transparent switching function in determining how to propagate a received frame. Note that the priority of MacBaseVlanAddr table entries is lowest than Filtering Table and FDB Table, i.e. if there is a table hash collision between the entries of MacBaseVlanAddr Table and Filtering Table inside the switch H/W address table, then Filtering Table entry overwrite the colliding entry of MacBaseVlanAddr Table. This state is same of FDB table. See swFdbFilterTable and swFdbStaticTable description also.')
swMacBaseVlanAddrEntry = MibTableRow((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 2, 3, 1), ).setIndexNames((0, "SW-VLAN-MIB", "swMacBaseVlanAddr"))
if mibBuilder.loadTexts: swMacBaseVlanAddrEntry.setStatus('mandatory')
if mibBuilder.loadTexts: swMacBaseVlanAddrEntry.setDescription('A list of information about a specific unicast or multicast MAC address for which the switch has some forwarding and/or filtering information.')
swMacBaseVlanAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 2, 3, 1, 1), MacAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: swMacBaseVlanAddr.setStatus('mandatory')
if mibBuilder.loadTexts: swMacBaseVlanAddr.setDescription('This object indictaes a unicast or multicast MAC address for which the bridge has forwarding and/or filtering information.')
swMacBaseVlanAddrVlanDesc = MibTableColumn((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 2, 3, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 64))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: swMacBaseVlanAddrVlanDesc.setStatus('mandatory')
if mibBuilder.loadTexts: swMacBaseVlanAddrVlanDesc.setDescription('A textual description of the Mac Base Vlan for memorization.')
swMacBaseVlanAddrState = MibTableColumn((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 2, 3, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("other", 1), ("invalid", 2), ("valid", 3)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: swMacBaseVlanAddrState.setStatus('mandatory')
if mibBuilder.loadTexts: swMacBaseVlanAddrState.setDescription('This object indicates the MacBase Vlan Address entry state. other(1) - this entry is currently in use but the conditions under which it will remain so are different from each of the following values. invalid(2) - writing this value to the object, and then the corresponding entry will be removed from the table. valid(3) - this entry is reside in the table.')
swMacBaseVlanAddrStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 2, 3, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("other", 1), ("apply", 2), ("not-apply", 3)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: swMacBaseVlanAddrStatus.setStatus('mandatory')
if mibBuilder.loadTexts: swMacBaseVlanAddrStatus.setDescription('This object indicates the MacBase Vlan Address entry state. other(1) - this entry is currently in use but the conditions under which it will remain so are different from each of the following values. apply(2) - this entry is currently in use and reside in the table. not-apply(3) - this entry is reside in the table but currently not in use due to conflict with filter table.')
swPortBaseVlanTotalNum = MibScalar((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 3, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: swPortBaseVlanTotalNum.setStatus('mandatory')
if mibBuilder.loadTexts: swPortBaseVlanTotalNum.setDescription('The total number of Port-Base Vlan which is in enabled state within this switch hub.')
swPortBaseVlanDefaultVlanTable = MibTable((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 3, 2), )
if mibBuilder.loadTexts: swPortBaseVlanDefaultVlanTable.setStatus('mandatory')
if mibBuilder.loadTexts: swPortBaseVlanDefaultVlanTable.setDescription('A table that contains default Port-Based VLAN list entries for the switch. The entry (Vid = 1,i.e. swPortBaseVlanDefaultPvid = 1) is defalut Port-Based VLAN , maintained by system.')
swPortBaseVlanDefaultVlanEntry = MibTableRow((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 3, 2, 1), ).setIndexNames((0, "SW-VLAN-MIB", "swPortBaseVlanDefaultPvid"))
if mibBuilder.loadTexts: swPortBaseVlanDefaultVlanEntry.setStatus('mandatory')
if mibBuilder.loadTexts: swPortBaseVlanDefaultVlanEntry.setDescription('A list of default Port-Based VLAN information in swPortBaseVlanDefaultVlanTable.')
swPortBaseVlanDefaultPvid = MibTableColumn((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 3, 2, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: swPortBaseVlanDefaultPvid.setStatus('mandatory')
if mibBuilder.loadTexts: swPortBaseVlanDefaultPvid.setDescription('This object indicates the default Port-Base Vlan ID. It occupies only 1 entry in VLAN table, with VID=1.')
swPortBaseVlanDefaultDesc = MibTableColumn((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 3, 2, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 12))).setMaxAccess("readonly")
if mibBuilder.loadTexts: swPortBaseVlanDefaultDesc.setStatus('mandatory')
if mibBuilder.loadTexts: swPortBaseVlanDefaultDesc.setDescription('A textual description of the Port-Base Vlan.')
swPortBaseVlanDefaultPortList = MibTableColumn((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 3, 2, 1, 3), PortList()).setMaxAccess("readonly")
if mibBuilder.loadTexts: swPortBaseVlanDefaultPortList.setStatus('mandatory')
if mibBuilder.loadTexts: swPortBaseVlanDefaultPortList.setDescription('This object indicates the port member set of the specified Vlan. Each Vlan has a octect string to indicate the port map. The most significant bit represents the lowest numbered port, and the least significant bit represents the highest numbered port.')
swPortBaseVlanDefaultPortNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 3, 2, 1, 4), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: swPortBaseVlanDefaultPortNumber.setStatus('mandatory')
if mibBuilder.loadTexts: swPortBaseVlanDefaultPortNumber.setDescription('This object indicates the number of ports of the entry.')
swPortBaseVlanConfigTable = MibTable((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 3, 3), )
if mibBuilder.loadTexts: swPortBaseVlanConfigTable.setStatus('mandatory')
if mibBuilder.loadTexts: swPortBaseVlanConfigTable.setDescription("A table that contains Port-Based VLAN list entries for the switch. The device can't support port overlapping in Port-Based VLAN.")
swPortBaseVlanConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 3, 3, 1), ).setIndexNames((0, "SW-VLAN-MIB", "swPortBaseVlanConfigPvid"))
if mibBuilder.loadTexts: swPortBaseVlanConfigEntry.setStatus('mandatory')
if mibBuilder.loadTexts: swPortBaseVlanConfigEntry.setDescription('A list of information about a specific Port-Based VLAN configuration in swPortBaseVlanConfigTable.')
swPortBaseVlanConfigPvid = MibTableColumn((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 3, 3, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(2, 12))).setMaxAccess("readonly")
if mibBuilder.loadTexts: swPortBaseVlanConfigPvid.setStatus('mandatory')
if mibBuilder.loadTexts: swPortBaseVlanConfigPvid.setDescription('This object indicates the Port-Base Vlan ID. There are up to 11 entries for current product now. The object range varies from 2 to 12.')
swPortBaseVlanConfigDesc = MibTableColumn((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 3, 3, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 12))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: swPortBaseVlanConfigDesc.setStatus('mandatory')
if mibBuilder.loadTexts: swPortBaseVlanConfigDesc.setDescription('A textual description of the Port-Base Vlan. It cannot be a null string. And each description must be unique in the table.')
swPortBaseVlanConfigPortList = MibTableColumn((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 3, 3, 1, 3), PortList()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: swPortBaseVlanConfigPortList.setStatus('mandatory')
if mibBuilder.loadTexts: swPortBaseVlanConfigPortList.setDescription('This object indicates which ports are belong to the Vlan. Each Vlan has a octect string to indicate with port map. The most significant bit represents the lowest numbered port, and the least significant bit represents the highest numbered port.')
swPortBaseVlanConfigPortNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 3, 3, 1, 4), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: swPortBaseVlanConfigPortNumber.setStatus('mandatory')
if mibBuilder.loadTexts: swPortBaseVlanConfigPortNumber.setDescription('This object indicates the number of ports of the entry.')
mibBuilder.exportSymbols("SW-VLAN-MIB", marconi=marconi, swPortBaseVlanDefaultVlanEntry=swPortBaseVlanDefaultVlanEntry, swVlan=swVlan, swPortBaseVlanConfigTable=swPortBaseVlanConfigTable, golf=golf, swVlanCtrl=swVlanCtrl, swMacBaseVlanAddrEntry=swMacBaseVlanAddrEntry, swPortBaseVlanDefaultDesc=swPortBaseVlanDefaultDesc, swMacBaseVlanAddr=swMacBaseVlanAddr, swMacBaseVlanMacMember=swMacBaseVlanMacMember, swPortBaseVlanConfigPortNumber=swPortBaseVlanConfigPortNumber, swPortBaseVlanDefaultVlanTable=swPortBaseVlanDefaultVlanTable, swPortBaseVlan=swPortBaseVlan, swMacBaseVlanAddrMaxNum=swMacBaseVlanAddrMaxNum, swL2Mgmt=swL2Mgmt, dlinkcommon=dlinkcommon, swPortBaseVlanConfigEntry=swPortBaseVlanConfigEntry, swPortBaseVlanConfigPortList=swPortBaseVlanConfigPortList, swVlanSnmpPortVlan=swVlanSnmpPortVlan, swMacBaseVlanCtrlState=swMacBaseVlanCtrlState, PortList=PortList, external=external, swMacBaseVlanAddrStatus=swMacBaseVlanAddrStatus, swPortBaseVlanTotalNum=swPortBaseVlanTotalNum, swMacBaseVlan=swMacBaseVlan, swVlanInfoStatus=swVlanInfoStatus, swMacBaseVlanDesc=swMacBaseVlanDesc, swPortBaseVlanDefaultPvid=swPortBaseVlanDefaultPvid, dlink=dlink, MacAddress=MacAddress, swVlanCtrlMode=swVlanCtrlMode, golfproducts=golfproducts, systems=systems, swMacBaseVlanCtrlTable=swMacBaseVlanCtrlTable, swMacBaseVlanAddrVlanDesc=swMacBaseVlanAddrVlanDesc, marconi_mgmt=marconi_mgmt, swMacBaseVlanMaxNum=swMacBaseVlanMaxNum, swMacBaseVlanCtrlEntry=swMacBaseVlanCtrlEntry, swPortBaseVlanDefaultPortList=swPortBaseVlanDefaultPortList, swMacBaseVlanAddrTable=swMacBaseVlanAddrTable, swPortBaseVlanConfigPvid=swPortBaseVlanConfigPvid, swPortBaseVlanConfigDesc=swPortBaseVlanConfigDesc, VlanIndex=VlanIndex, swPortBaseVlanDefaultPortNumber=swPortBaseVlanDefaultPortNumber, golfcommon=golfcommon, swMacBaseVlanAddrState=swMacBaseVlanAddrState, es2000Mgmt=es2000Mgmt, es2000=es2000, swMacBaseVlanInfo=swMacBaseVlanInfo)
| (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, value_size_constraint, constraints_union, constraints_intersection, single_value_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueRangeConstraint', 'ValueSizeConstraint', 'ConstraintsUnion', 'ConstraintsIntersection', 'SingleValueConstraint')
(module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup')
(enterprises, iso, module_identity, mib_scalar, mib_table, mib_table_row, mib_table_column, bits, counter32, integer32, unsigned32, gauge32, ip_address, object_identity, mib_identifier, counter64, time_ticks, notification_type) = mibBuilder.importSymbols('SNMPv2-SMI', 'enterprises', 'iso', 'ModuleIdentity', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'Bits', 'Counter32', 'Integer32', 'Unsigned32', 'Gauge32', 'IpAddress', 'ObjectIdentity', 'MibIdentifier', 'Counter64', 'TimeTicks', 'NotificationType')
(display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention')
class Macaddress(OctetString):
subtype_spec = OctetString.subtypeSpec + value_size_constraint(6, 6)
fixed_length = 6
class Vlanindex(Integer32):
subtype_spec = Integer32.subtypeSpec + value_range_constraint(1, 4094)
class Portlist(OctetString):
subtype_spec = OctetString.subtypeSpec + value_size_constraint(12, 12)
fixed_length = 12
marconi = mib_identifier((1, 3, 6, 1, 4, 1, 326))
systems = mib_identifier((1, 3, 6, 1, 4, 1, 326, 2))
external = mib_identifier((1, 3, 6, 1, 4, 1, 326, 2, 20))
dlink = mib_identifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1))
dlinkcommon = mib_identifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 1))
golf = mib_identifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2))
golfproducts = mib_identifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 1))
es2000 = mib_identifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 1, 3))
golfcommon = mib_identifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2))
marconi_mgmt = mib_identifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2)).setLabel('marconi-mgmt')
es2000_mgmt = mib_identifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28))
sw_l2_mgmt = mib_identifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2))
sw_vlan = mib_identifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8))
sw_vlan_ctrl = mib_identifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 1))
sw_mac_base_vlan = mib_identifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 2))
sw_port_base_vlan = mib_identifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 3))
sw_vlan_ctrl_mode = mib_scalar((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 1, 1), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4, 5))).clone(namedValues=named_values(('other', 1), ('disabled', 2), ('mac-base', 3), ('ieee8021q', 4), ('port-base', 5)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
swVlanCtrlMode.setStatus('mandatory')
if mibBuilder.loadTexts:
swVlanCtrlMode.setDescription('This object controls which Vlan function will be enable (or disable) when the switch hub restart at the startup (power on) or warm start.')
sw_vlan_info_status = mib_scalar((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4, 5))).clone(namedValues=named_values(('other', 1), ('disabled', 2), ('mac-base', 3), ('ieee8021q', 4), ('port-base', 5)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
swVlanInfoStatus.setStatus('mandatory')
if mibBuilder.loadTexts:
swVlanInfoStatus.setDescription('This object indicates which Vlan function be enable (or disable) in mandatoryly stage. There are no effect when change swVlanCtrlMode vlaue in the system running.')
sw_vlan_snmp_port_vlan = mib_scalar((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 1, 3), vlan_index()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
swVlanSnmpPortVlan.setStatus('mandatory')
if mibBuilder.loadTexts:
swVlanSnmpPortVlan.setDescription('Indicates the Vlan which the SNMP port belongs to. The value range is 1 to 4094.')
sw_mac_base_vlan_info = mib_identifier((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 2, 1))
sw_mac_base_vlan_max_num = mib_scalar((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 2, 1, 1), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
swMacBaseVlanMaxNum.setStatus('mandatory')
if mibBuilder.loadTexts:
swMacBaseVlanMaxNum.setDescription('The maximum number of Mac base Vlan allowed by the system.')
sw_mac_base_vlan_addr_max_num = mib_scalar((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 2, 1, 2), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
swMacBaseVlanAddrMaxNum.setStatus('mandatory')
if mibBuilder.loadTexts:
swMacBaseVlanAddrMaxNum.setDescription('The maximum number of entries in Mac-based Vlan address table.')
sw_mac_base_vlan_ctrl_table = mib_table((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 2, 2))
if mibBuilder.loadTexts:
swMacBaseVlanCtrlTable.setStatus('mandatory')
if mibBuilder.loadTexts:
swMacBaseVlanCtrlTable.setDescription('A table that contains information about MAC base Vlan entries for which the switch has forwarding and/or filtering information. This information is used by the transparent switching function in determining how to propagate a received frame.')
sw_mac_base_vlan_ctrl_entry = mib_table_row((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 2, 2, 1)).setIndexNames((0, 'SW-VLAN-MIB', 'swMacBaseVlanDesc'))
if mibBuilder.loadTexts:
swMacBaseVlanCtrlEntry.setStatus('mandatory')
if mibBuilder.loadTexts:
swMacBaseVlanCtrlEntry.setDescription('A list of information about a specific MAC base Vlan configuration portlist for which the switch has some forwarding and/or filtering information.')
sw_mac_base_vlan_desc = mib_table_column((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 2, 2, 1, 1), display_string().subtype(subtypeSpec=value_size_constraint(1, 12))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
swMacBaseVlanDesc.setStatus('mandatory')
if mibBuilder.loadTexts:
swMacBaseVlanDesc.setDescription('A textual description of the Mac Base Vlan for memorization. The string cannot set to empty string. There is a default value for this string.')
sw_mac_base_vlan_mac_member = mib_table_column((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 2, 2, 1, 2), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
swMacBaseVlanMacMember.setStatus('mandatory')
if mibBuilder.loadTexts:
swMacBaseVlanMacMember.setDescription('This object indicates the total number of MAC addresses contained in the VLAN entry.')
sw_mac_base_vlan_ctrl_state = mib_table_column((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 2, 2, 1, 3), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('other', 1), ('disabled', 2), ('enabled', 3)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
swMacBaseVlanCtrlState.setStatus('mandatory')
if mibBuilder.loadTexts:
swMacBaseVlanCtrlState.setDescription('This object indicates the MacBase Vlan state.')
sw_mac_base_vlan_addr_table = mib_table((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 2, 3))
if mibBuilder.loadTexts:
swMacBaseVlanAddrTable.setStatus('mandatory')
if mibBuilder.loadTexts:
swMacBaseVlanAddrTable.setDescription('A table that contains information about unicast or multicast entries for which the switch has forwarding and/or filtering information. This information is used by the transparent switching function in determining how to propagate a received frame. Note that the priority of MacBaseVlanAddr table entries is lowest than Filtering Table and FDB Table, i.e. if there is a table hash collision between the entries of MacBaseVlanAddr Table and Filtering Table inside the switch H/W address table, then Filtering Table entry overwrite the colliding entry of MacBaseVlanAddr Table. This state is same of FDB table. See swFdbFilterTable and swFdbStaticTable description also.')
sw_mac_base_vlan_addr_entry = mib_table_row((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 2, 3, 1)).setIndexNames((0, 'SW-VLAN-MIB', 'swMacBaseVlanAddr'))
if mibBuilder.loadTexts:
swMacBaseVlanAddrEntry.setStatus('mandatory')
if mibBuilder.loadTexts:
swMacBaseVlanAddrEntry.setDescription('A list of information about a specific unicast or multicast MAC address for which the switch has some forwarding and/or filtering information.')
sw_mac_base_vlan_addr = mib_table_column((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 2, 3, 1, 1), mac_address()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
swMacBaseVlanAddr.setStatus('mandatory')
if mibBuilder.loadTexts:
swMacBaseVlanAddr.setDescription('This object indictaes a unicast or multicast MAC address for which the bridge has forwarding and/or filtering information.')
sw_mac_base_vlan_addr_vlan_desc = mib_table_column((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 2, 3, 1, 2), display_string().subtype(subtypeSpec=value_size_constraint(1, 64))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
swMacBaseVlanAddrVlanDesc.setStatus('mandatory')
if mibBuilder.loadTexts:
swMacBaseVlanAddrVlanDesc.setDescription('A textual description of the Mac Base Vlan for memorization.')
sw_mac_base_vlan_addr_state = mib_table_column((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 2, 3, 1, 3), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('other', 1), ('invalid', 2), ('valid', 3)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
swMacBaseVlanAddrState.setStatus('mandatory')
if mibBuilder.loadTexts:
swMacBaseVlanAddrState.setDescription('This object indicates the MacBase Vlan Address entry state. other(1) - this entry is currently in use but the conditions under which it will remain so are different from each of the following values. invalid(2) - writing this value to the object, and then the corresponding entry will be removed from the table. valid(3) - this entry is reside in the table.')
sw_mac_base_vlan_addr_status = mib_table_column((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 2, 3, 1, 4), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('other', 1), ('apply', 2), ('not-apply', 3)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
swMacBaseVlanAddrStatus.setStatus('mandatory')
if mibBuilder.loadTexts:
swMacBaseVlanAddrStatus.setDescription('This object indicates the MacBase Vlan Address entry state. other(1) - this entry is currently in use but the conditions under which it will remain so are different from each of the following values. apply(2) - this entry is currently in use and reside in the table. not-apply(3) - this entry is reside in the table but currently not in use due to conflict with filter table.')
sw_port_base_vlan_total_num = mib_scalar((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 3, 1), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
swPortBaseVlanTotalNum.setStatus('mandatory')
if mibBuilder.loadTexts:
swPortBaseVlanTotalNum.setDescription('The total number of Port-Base Vlan which is in enabled state within this switch hub.')
sw_port_base_vlan_default_vlan_table = mib_table((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 3, 2))
if mibBuilder.loadTexts:
swPortBaseVlanDefaultVlanTable.setStatus('mandatory')
if mibBuilder.loadTexts:
swPortBaseVlanDefaultVlanTable.setDescription('A table that contains default Port-Based VLAN list entries for the switch. The entry (Vid = 1,i.e. swPortBaseVlanDefaultPvid = 1) is defalut Port-Based VLAN , maintained by system.')
sw_port_base_vlan_default_vlan_entry = mib_table_row((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 3, 2, 1)).setIndexNames((0, 'SW-VLAN-MIB', 'swPortBaseVlanDefaultPvid'))
if mibBuilder.loadTexts:
swPortBaseVlanDefaultVlanEntry.setStatus('mandatory')
if mibBuilder.loadTexts:
swPortBaseVlanDefaultVlanEntry.setDescription('A list of default Port-Based VLAN information in swPortBaseVlanDefaultVlanTable.')
sw_port_base_vlan_default_pvid = mib_table_column((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 3, 2, 1, 1), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
swPortBaseVlanDefaultPvid.setStatus('mandatory')
if mibBuilder.loadTexts:
swPortBaseVlanDefaultPvid.setDescription('This object indicates the default Port-Base Vlan ID. It occupies only 1 entry in VLAN table, with VID=1.')
sw_port_base_vlan_default_desc = mib_table_column((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 3, 2, 1, 2), display_string().subtype(subtypeSpec=value_size_constraint(1, 12))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
swPortBaseVlanDefaultDesc.setStatus('mandatory')
if mibBuilder.loadTexts:
swPortBaseVlanDefaultDesc.setDescription('A textual description of the Port-Base Vlan.')
sw_port_base_vlan_default_port_list = mib_table_column((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 3, 2, 1, 3), port_list()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
swPortBaseVlanDefaultPortList.setStatus('mandatory')
if mibBuilder.loadTexts:
swPortBaseVlanDefaultPortList.setDescription('This object indicates the port member set of the specified Vlan. Each Vlan has a octect string to indicate the port map. The most significant bit represents the lowest numbered port, and the least significant bit represents the highest numbered port.')
sw_port_base_vlan_default_port_number = mib_table_column((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 3, 2, 1, 4), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
swPortBaseVlanDefaultPortNumber.setStatus('mandatory')
if mibBuilder.loadTexts:
swPortBaseVlanDefaultPortNumber.setDescription('This object indicates the number of ports of the entry.')
sw_port_base_vlan_config_table = mib_table((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 3, 3))
if mibBuilder.loadTexts:
swPortBaseVlanConfigTable.setStatus('mandatory')
if mibBuilder.loadTexts:
swPortBaseVlanConfigTable.setDescription("A table that contains Port-Based VLAN list entries for the switch. The device can't support port overlapping in Port-Based VLAN.")
sw_port_base_vlan_config_entry = mib_table_row((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 3, 3, 1)).setIndexNames((0, 'SW-VLAN-MIB', 'swPortBaseVlanConfigPvid'))
if mibBuilder.loadTexts:
swPortBaseVlanConfigEntry.setStatus('mandatory')
if mibBuilder.loadTexts:
swPortBaseVlanConfigEntry.setDescription('A list of information about a specific Port-Based VLAN configuration in swPortBaseVlanConfigTable.')
sw_port_base_vlan_config_pvid = mib_table_column((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 3, 3, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(2, 12))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
swPortBaseVlanConfigPvid.setStatus('mandatory')
if mibBuilder.loadTexts:
swPortBaseVlanConfigPvid.setDescription('This object indicates the Port-Base Vlan ID. There are up to 11 entries for current product now. The object range varies from 2 to 12.')
sw_port_base_vlan_config_desc = mib_table_column((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 3, 3, 1, 2), display_string().subtype(subtypeSpec=value_size_constraint(1, 12))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
swPortBaseVlanConfigDesc.setStatus('mandatory')
if mibBuilder.loadTexts:
swPortBaseVlanConfigDesc.setDescription('A textual description of the Port-Base Vlan. It cannot be a null string. And each description must be unique in the table.')
sw_port_base_vlan_config_port_list = mib_table_column((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 3, 3, 1, 3), port_list()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
swPortBaseVlanConfigPortList.setStatus('mandatory')
if mibBuilder.loadTexts:
swPortBaseVlanConfigPortList.setDescription('This object indicates which ports are belong to the Vlan. Each Vlan has a octect string to indicate with port map. The most significant bit represents the lowest numbered port, and the least significant bit represents the highest numbered port.')
sw_port_base_vlan_config_port_number = mib_table_column((1, 3, 6, 1, 4, 1, 326, 2, 20, 1, 2, 2, 2, 28, 2, 8, 3, 3, 1, 4), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
swPortBaseVlanConfigPortNumber.setStatus('mandatory')
if mibBuilder.loadTexts:
swPortBaseVlanConfigPortNumber.setDescription('This object indicates the number of ports of the entry.')
mibBuilder.exportSymbols('SW-VLAN-MIB', marconi=marconi, swPortBaseVlanDefaultVlanEntry=swPortBaseVlanDefaultVlanEntry, swVlan=swVlan, swPortBaseVlanConfigTable=swPortBaseVlanConfigTable, golf=golf, swVlanCtrl=swVlanCtrl, swMacBaseVlanAddrEntry=swMacBaseVlanAddrEntry, swPortBaseVlanDefaultDesc=swPortBaseVlanDefaultDesc, swMacBaseVlanAddr=swMacBaseVlanAddr, swMacBaseVlanMacMember=swMacBaseVlanMacMember, swPortBaseVlanConfigPortNumber=swPortBaseVlanConfigPortNumber, swPortBaseVlanDefaultVlanTable=swPortBaseVlanDefaultVlanTable, swPortBaseVlan=swPortBaseVlan, swMacBaseVlanAddrMaxNum=swMacBaseVlanAddrMaxNum, swL2Mgmt=swL2Mgmt, dlinkcommon=dlinkcommon, swPortBaseVlanConfigEntry=swPortBaseVlanConfigEntry, swPortBaseVlanConfigPortList=swPortBaseVlanConfigPortList, swVlanSnmpPortVlan=swVlanSnmpPortVlan, swMacBaseVlanCtrlState=swMacBaseVlanCtrlState, PortList=PortList, external=external, swMacBaseVlanAddrStatus=swMacBaseVlanAddrStatus, swPortBaseVlanTotalNum=swPortBaseVlanTotalNum, swMacBaseVlan=swMacBaseVlan, swVlanInfoStatus=swVlanInfoStatus, swMacBaseVlanDesc=swMacBaseVlanDesc, swPortBaseVlanDefaultPvid=swPortBaseVlanDefaultPvid, dlink=dlink, MacAddress=MacAddress, swVlanCtrlMode=swVlanCtrlMode, golfproducts=golfproducts, systems=systems, swMacBaseVlanCtrlTable=swMacBaseVlanCtrlTable, swMacBaseVlanAddrVlanDesc=swMacBaseVlanAddrVlanDesc, marconi_mgmt=marconi_mgmt, swMacBaseVlanMaxNum=swMacBaseVlanMaxNum, swMacBaseVlanCtrlEntry=swMacBaseVlanCtrlEntry, swPortBaseVlanDefaultPortList=swPortBaseVlanDefaultPortList, swMacBaseVlanAddrTable=swMacBaseVlanAddrTable, swPortBaseVlanConfigPvid=swPortBaseVlanConfigPvid, swPortBaseVlanConfigDesc=swPortBaseVlanConfigDesc, VlanIndex=VlanIndex, swPortBaseVlanDefaultPortNumber=swPortBaseVlanDefaultPortNumber, golfcommon=golfcommon, swMacBaseVlanAddrState=swMacBaseVlanAddrState, es2000Mgmt=es2000Mgmt, es2000=es2000, swMacBaseVlanInfo=swMacBaseVlanInfo) |
class DFA:
current_state = None
current_letter = None
valid = True
def __init__(
self, name, alphabet, states, delta_function, start_state, final_states
):
self.name = name
self.alphabet = alphabet
self.states = states
self.delta_function = delta_function
self.start_state = start_state
self.final_states = final_states
self.current_state = start_state
def transition_to_state_with_input(self, letter):
if self.valid:
if (self.current_state, letter) not in self.delta_function.keys():
self.valid = False
return
self.current_state = self.delta_function[(self.current_state, letter)]
self.current_letter = letter
else:
return
def in_accept_state(self):
return self.current_state in self.final_states and self.valid
def go_to_initial_state(self):
self.current_letter = None
self.valid = True
self.current_state = self.start_state
def run_with_word(self, word):
self.go_to_initial_state()
for letter in word:
self.transition_to_state_with_input(letter)
continue
return self.in_accept_state()
def run_with_letters(self, word):
self.go_to_initial_state()
for letter in word:
if self.run_with_letter(letter):
return
else:
return
def run_with_letter(self, letter):
self.transition_to_state_with_input(letter)
return self.current_state
def __len__(self):
return len(self.states)
| class Dfa:
current_state = None
current_letter = None
valid = True
def __init__(self, name, alphabet, states, delta_function, start_state, final_states):
self.name = name
self.alphabet = alphabet
self.states = states
self.delta_function = delta_function
self.start_state = start_state
self.final_states = final_states
self.current_state = start_state
def transition_to_state_with_input(self, letter):
if self.valid:
if (self.current_state, letter) not in self.delta_function.keys():
self.valid = False
return
self.current_state = self.delta_function[self.current_state, letter]
self.current_letter = letter
else:
return
def in_accept_state(self):
return self.current_state in self.final_states and self.valid
def go_to_initial_state(self):
self.current_letter = None
self.valid = True
self.current_state = self.start_state
def run_with_word(self, word):
self.go_to_initial_state()
for letter in word:
self.transition_to_state_with_input(letter)
continue
return self.in_accept_state()
def run_with_letters(self, word):
self.go_to_initial_state()
for letter in word:
if self.run_with_letter(letter):
return
else:
return
def run_with_letter(self, letter):
self.transition_to_state_with_input(letter)
return self.current_state
def __len__(self):
return len(self.states) |
class LambdaError(Exception):
def __init__(self, description):
self.description = description
class BadRequestError(LambdaError):
pass
class ForbiddenError(LambdaError):
pass
class InternalServerError(LambdaError):
pass
class NotFoundError(LambdaError):
pass
class ValidationError(LambdaError):
pass
class FormattingError(LambdaError):
pass
class EventValidationError(ValidationError):
pass
class ResultValidationError(ValidationError):
pass
| class Lambdaerror(Exception):
def __init__(self, description):
self.description = description
class Badrequesterror(LambdaError):
pass
class Forbiddenerror(LambdaError):
pass
class Internalservererror(LambdaError):
pass
class Notfounderror(LambdaError):
pass
class Validationerror(LambdaError):
pass
class Formattingerror(LambdaError):
pass
class Eventvalidationerror(ValidationError):
pass
class Resultvalidationerror(ValidationError):
pass |
"""
# Sample code to perform I/O:
name = input() # Reading input from STDIN
print('Hi, %s.' % name) # Writing output to STDOUT
# Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
"""
# Write your code here
n, m = map(int, input().strip().split())
a = sorted(map(int, input().strip().split()), reverse=True)
b = sorted(map(int, input().strip().split()), reverse=True)
if a[0] > b[0]:
print(-1)
else:
min_time = 1
i = j = 0
while i < len(a):
if j < len(b) and a[i] <= b[j]:
j += 1
elif a[i] <= b[j - 1]:
min_time += 2
i += 1
print(min_time)
| """
# Sample code to perform I/O:
name = input() # Reading input from STDIN
print('Hi, %s.' % name) # Writing output to STDOUT
# Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
"""
(n, m) = map(int, input().strip().split())
a = sorted(map(int, input().strip().split()), reverse=True)
b = sorted(map(int, input().strip().split()), reverse=True)
if a[0] > b[0]:
print(-1)
else:
min_time = 1
i = j = 0
while i < len(a):
if j < len(b) and a[i] <= b[j]:
j += 1
elif a[i] <= b[j - 1]:
min_time += 2
i += 1
print(min_time) |
pkgname = "xrandr"
pkgver = "1.5.1"
pkgrel = 0
build_style = "gnu_configure"
hostmakedepends = ["pkgconf"]
makedepends = ["libxrandr-devel"]
pkgdesc = "Command line interface to X RandR extension"
maintainer = "q66 <q66@chimera-linux.org>"
license = "MIT"
url = "https://xorg.freedesktop.org"
source = f"$(XORG_SITE)/app/{pkgname}-{pkgver}.tar.xz"
sha256 = "7bc76daf9d72f8aff885efad04ce06b90488a1a169d118dea8a2b661832e8762"
def post_install(self):
self.install_license("COPYING")
| pkgname = 'xrandr'
pkgver = '1.5.1'
pkgrel = 0
build_style = 'gnu_configure'
hostmakedepends = ['pkgconf']
makedepends = ['libxrandr-devel']
pkgdesc = 'Command line interface to X RandR extension'
maintainer = 'q66 <q66@chimera-linux.org>'
license = 'MIT'
url = 'https://xorg.freedesktop.org'
source = f'$(XORG_SITE)/app/{pkgname}-{pkgver}.tar.xz'
sha256 = '7bc76daf9d72f8aff885efad04ce06b90488a1a169d118dea8a2b661832e8762'
def post_install(self):
self.install_license('COPYING') |
# Validate input
while True:
print('Enter your age:')
age = input()
if age.isdecimal():
break
print('Pleas enter a number for your age.')
| while True:
print('Enter your age:')
age = input()
if age.isdecimal():
break
print('Pleas enter a number for your age.') |
#
# PySNMP MIB module Fore-Common-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Fore-Common-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:14:34 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueRangeConstraint, ConstraintsUnion, SingleValueConstraint, ConstraintsIntersection, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ConstraintsUnion", "SingleValueConstraint", "ConstraintsIntersection", "ValueSizeConstraint")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
Bits, MibIdentifier, enterprises, Counter64, Unsigned32, ModuleIdentity, Counter32, TimeTicks, NotificationType, ObjectIdentity, IpAddress, Gauge32, Integer32, iso, MibScalar, MibTable, MibTableRow, MibTableColumn = mibBuilder.importSymbols("SNMPv2-SMI", "Bits", "MibIdentifier", "enterprises", "Counter64", "Unsigned32", "ModuleIdentity", "Counter32", "TimeTicks", "NotificationType", "ObjectIdentity", "IpAddress", "Gauge32", "Integer32", "iso", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn")
TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString")
fore = ModuleIdentity((1, 3, 6, 1, 4, 1, 326))
if mibBuilder.loadTexts: fore.setLastUpdated('9911050000Z')
if mibBuilder.loadTexts: fore.setOrganization('Marconi Communications')
if mibBuilder.loadTexts: fore.setContactInfo(' Postal: Marconi Communications, Inc. 5000 Marconi Drive Warrendale, PA 15086-7502 Tel: +1 724 742 6999 Email: bbrs-mibs@marconi.com Web: http://www.marconi.com')
if mibBuilder.loadTexts: fore.setDescription('Definitions common to all FORE private MIBS.')
admin = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 1))
systems = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2))
foreExperiment = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 3))
operations = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 1, 1))
snmpErrors = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 1, 2))
snmpTrapDest = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 1, 3))
snmpAccess = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 1, 4))
assembly = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 1, 5))
fileXfr = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 1, 6))
rmonExtensions = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 1, 7))
preDot1qVlanMIB = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 1, 8))
snmpTrapLog = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 1, 9))
ilmisnmp = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 1, 10))
entityExtensionMIB = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 1, 11))
ilmiRegistry = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 1, 14))
foreIfExtension = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 1, 15))
frameInternetworking = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 1, 16))
ifExtensions = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 1, 17))
atmAdapter = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 1))
atmSwitch = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 2))
etherSwitch = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 3))
atmAccess = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 5))
hubSwitchRouter = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 6))
ipoa = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 7))
stackSwitch = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 10))
switchRouter = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 15))
software = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 2))
asxd = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 2, 1))
hardware = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 1))
asx = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 1, 1))
asx200wg = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 4))
asx200bx = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 5))
asx200bxe = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 6))
cabletron9A000 = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 7))
asx1000 = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 8))
le155 = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 9))
sfcs200wg = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 10))
sfcs200bx = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 11))
sfcs1000 = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 12))
tnx210 = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 15))
tnx1100 = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 16))
asx1200 = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 17))
asx4000 = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 18))
le25 = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 19))
esx3000 = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 20))
tnx1100b = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 21))
asx150 = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 22))
bxr48000 = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 24))
asx4000m = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 25))
axhIp = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 26))
axhSig = MibIdentifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 27))
class SpansAddress(OctetString):
subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(8, 8)
fixedLength = 8
class AtmAddress(OctetString):
subtypeSpec = OctetString.subtypeSpec + ConstraintsUnion(ValueSizeConstraint(8, 8), ValueSizeConstraint(20, 20), )
class NsapPrefix(OctetString):
subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(13, 13)
fixedLength = 13
class NsapAddr(OctetString):
subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(20, 20)
fixedLength = 20
class TransitNetwork(DisplayString):
subtypeSpec = DisplayString.subtypeSpec + ValueSizeConstraint(1, 4)
class TrapNumber(Integer32):
pass
class EntryStatus(Integer32):
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))
namedValues = NamedValues(("valid", 1), ("createRequest", 2), ("underCreation", 3), ("invalid", 4))
class AtmSigProtocol(Integer32):
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13))
namedValues = NamedValues(("other", 1), ("spans", 2), ("q2931", 3), ("pvc", 4), ("spvc", 5), ("oam", 6), ("spvcSpans", 7), ("spvcPnni", 8), ("rcc", 9), ("fsig", 10), ("mpls", 11), ("ipCtl", 12), ("oam-ctl", 13))
class GeneralState(Integer32):
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2))
namedValues = NamedValues(("normal", 1), ("fail", 2))
class IntegerBitString(Integer32):
pass
class ConnectionType(Integer32):
pass
mibBuilder.exportSymbols("Fore-Common-MIB", ilmiRegistry=ilmiRegistry, fore=fore, ilmisnmp=ilmisnmp, NsapPrefix=NsapPrefix, atmAccess=atmAccess, snmpTrapDest=snmpTrapDest, rmonExtensions=rmonExtensions, preDot1qVlanMIB=preDot1qVlanMIB, operations=operations, ipoa=ipoa, software=software, tnx1100=tnx1100, snmpErrors=snmpErrors, sfcs200bx=sfcs200bx, snmpAccess=snmpAccess, sfcs200wg=sfcs200wg, le25=le25, sfcs1000=sfcs1000, esx3000=esx3000, frameInternetworking=frameInternetworking, asx4000m=asx4000m, AtmAddress=AtmAddress, assembly=assembly, ConnectionType=ConnectionType, axhIp=axhIp, bxr48000=bxr48000, ifExtensions=ifExtensions, asx=asx, asxd=asxd, asx4000=asx4000, TransitNetwork=TransitNetwork, fileXfr=fileXfr, EntryStatus=EntryStatus, foreIfExtension=foreIfExtension, asx1000=asx1000, asx200bxe=asx200bxe, axhSig=axhSig, TrapNumber=TrapNumber, SpansAddress=SpansAddress, IntegerBitString=IntegerBitString, atmSwitch=atmSwitch, cabletron9A000=cabletron9A000, AtmSigProtocol=AtmSigProtocol, tnx1100b=tnx1100b, asx200bx=asx200bx, etherSwitch=etherSwitch, asx1200=asx1200, hubSwitchRouter=hubSwitchRouter, entityExtensionMIB=entityExtensionMIB, switchRouter=switchRouter, NsapAddr=NsapAddr, asx200wg=asx200wg, systems=systems, atmAdapter=atmAdapter, foreExperiment=foreExperiment, PYSNMP_MODULE_ID=fore, admin=admin, le155=le155, GeneralState=GeneralState, hardware=hardware, stackSwitch=stackSwitch, asx150=asx150, tnx210=tnx210, snmpTrapLog=snmpTrapLog)
| (octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, constraints_union, single_value_constraint, constraints_intersection, value_size_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueRangeConstraint', 'ConstraintsUnion', 'SingleValueConstraint', 'ConstraintsIntersection', 'ValueSizeConstraint')
(module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup')
(bits, mib_identifier, enterprises, counter64, unsigned32, module_identity, counter32, time_ticks, notification_type, object_identity, ip_address, gauge32, integer32, iso, mib_scalar, mib_table, mib_table_row, mib_table_column) = mibBuilder.importSymbols('SNMPv2-SMI', 'Bits', 'MibIdentifier', 'enterprises', 'Counter64', 'Unsigned32', 'ModuleIdentity', 'Counter32', 'TimeTicks', 'NotificationType', 'ObjectIdentity', 'IpAddress', 'Gauge32', 'Integer32', 'iso', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn')
(textual_convention, display_string) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'DisplayString')
fore = module_identity((1, 3, 6, 1, 4, 1, 326))
if mibBuilder.loadTexts:
fore.setLastUpdated('9911050000Z')
if mibBuilder.loadTexts:
fore.setOrganization('Marconi Communications')
if mibBuilder.loadTexts:
fore.setContactInfo(' Postal: Marconi Communications, Inc. 5000 Marconi Drive Warrendale, PA 15086-7502 Tel: +1 724 742 6999 Email: bbrs-mibs@marconi.com Web: http://www.marconi.com')
if mibBuilder.loadTexts:
fore.setDescription('Definitions common to all FORE private MIBS.')
admin = mib_identifier((1, 3, 6, 1, 4, 1, 326, 1))
systems = mib_identifier((1, 3, 6, 1, 4, 1, 326, 2))
fore_experiment = mib_identifier((1, 3, 6, 1, 4, 1, 326, 3))
operations = mib_identifier((1, 3, 6, 1, 4, 1, 326, 1, 1))
snmp_errors = mib_identifier((1, 3, 6, 1, 4, 1, 326, 1, 2))
snmp_trap_dest = mib_identifier((1, 3, 6, 1, 4, 1, 326, 1, 3))
snmp_access = mib_identifier((1, 3, 6, 1, 4, 1, 326, 1, 4))
assembly = mib_identifier((1, 3, 6, 1, 4, 1, 326, 1, 5))
file_xfr = mib_identifier((1, 3, 6, 1, 4, 1, 326, 1, 6))
rmon_extensions = mib_identifier((1, 3, 6, 1, 4, 1, 326, 1, 7))
pre_dot1q_vlan_mib = mib_identifier((1, 3, 6, 1, 4, 1, 326, 1, 8))
snmp_trap_log = mib_identifier((1, 3, 6, 1, 4, 1, 326, 1, 9))
ilmisnmp = mib_identifier((1, 3, 6, 1, 4, 1, 326, 1, 10))
entity_extension_mib = mib_identifier((1, 3, 6, 1, 4, 1, 326, 1, 11))
ilmi_registry = mib_identifier((1, 3, 6, 1, 4, 1, 326, 1, 14))
fore_if_extension = mib_identifier((1, 3, 6, 1, 4, 1, 326, 1, 15))
frame_internetworking = mib_identifier((1, 3, 6, 1, 4, 1, 326, 1, 16))
if_extensions = mib_identifier((1, 3, 6, 1, 4, 1, 326, 1, 17))
atm_adapter = mib_identifier((1, 3, 6, 1, 4, 1, 326, 2, 1))
atm_switch = mib_identifier((1, 3, 6, 1, 4, 1, 326, 2, 2))
ether_switch = mib_identifier((1, 3, 6, 1, 4, 1, 326, 2, 3))
atm_access = mib_identifier((1, 3, 6, 1, 4, 1, 326, 2, 5))
hub_switch_router = mib_identifier((1, 3, 6, 1, 4, 1, 326, 2, 6))
ipoa = mib_identifier((1, 3, 6, 1, 4, 1, 326, 2, 7))
stack_switch = mib_identifier((1, 3, 6, 1, 4, 1, 326, 2, 10))
switch_router = mib_identifier((1, 3, 6, 1, 4, 1, 326, 2, 15))
software = mib_identifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 2))
asxd = mib_identifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 2, 1))
hardware = mib_identifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 1))
asx = mib_identifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 1, 1))
asx200wg = mib_identifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 4))
asx200bx = mib_identifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 5))
asx200bxe = mib_identifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 6))
cabletron9_a000 = mib_identifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 7))
asx1000 = mib_identifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 8))
le155 = mib_identifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 9))
sfcs200wg = mib_identifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 10))
sfcs200bx = mib_identifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 11))
sfcs1000 = mib_identifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 12))
tnx210 = mib_identifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 15))
tnx1100 = mib_identifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 16))
asx1200 = mib_identifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 17))
asx4000 = mib_identifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 18))
le25 = mib_identifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 19))
esx3000 = mib_identifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 20))
tnx1100b = mib_identifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 21))
asx150 = mib_identifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 22))
bxr48000 = mib_identifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 24))
asx4000m = mib_identifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 25))
axh_ip = mib_identifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 26))
axh_sig = mib_identifier((1, 3, 6, 1, 4, 1, 326, 2, 2, 27))
class Spansaddress(OctetString):
subtype_spec = OctetString.subtypeSpec + value_size_constraint(8, 8)
fixed_length = 8
class Atmaddress(OctetString):
subtype_spec = OctetString.subtypeSpec + constraints_union(value_size_constraint(8, 8), value_size_constraint(20, 20))
class Nsapprefix(OctetString):
subtype_spec = OctetString.subtypeSpec + value_size_constraint(13, 13)
fixed_length = 13
class Nsapaddr(OctetString):
subtype_spec = OctetString.subtypeSpec + value_size_constraint(20, 20)
fixed_length = 20
class Transitnetwork(DisplayString):
subtype_spec = DisplayString.subtypeSpec + value_size_constraint(1, 4)
class Trapnumber(Integer32):
pass
class Entrystatus(Integer32):
subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(1, 2, 3, 4))
named_values = named_values(('valid', 1), ('createRequest', 2), ('underCreation', 3), ('invalid', 4))
class Atmsigprotocol(Integer32):
subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13))
named_values = named_values(('other', 1), ('spans', 2), ('q2931', 3), ('pvc', 4), ('spvc', 5), ('oam', 6), ('spvcSpans', 7), ('spvcPnni', 8), ('rcc', 9), ('fsig', 10), ('mpls', 11), ('ipCtl', 12), ('oam-ctl', 13))
class Generalstate(Integer32):
subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(1, 2))
named_values = named_values(('normal', 1), ('fail', 2))
class Integerbitstring(Integer32):
pass
class Connectiontype(Integer32):
pass
mibBuilder.exportSymbols('Fore-Common-MIB', ilmiRegistry=ilmiRegistry, fore=fore, ilmisnmp=ilmisnmp, NsapPrefix=NsapPrefix, atmAccess=atmAccess, snmpTrapDest=snmpTrapDest, rmonExtensions=rmonExtensions, preDot1qVlanMIB=preDot1qVlanMIB, operations=operations, ipoa=ipoa, software=software, tnx1100=tnx1100, snmpErrors=snmpErrors, sfcs200bx=sfcs200bx, snmpAccess=snmpAccess, sfcs200wg=sfcs200wg, le25=le25, sfcs1000=sfcs1000, esx3000=esx3000, frameInternetworking=frameInternetworking, asx4000m=asx4000m, AtmAddress=AtmAddress, assembly=assembly, ConnectionType=ConnectionType, axhIp=axhIp, bxr48000=bxr48000, ifExtensions=ifExtensions, asx=asx, asxd=asxd, asx4000=asx4000, TransitNetwork=TransitNetwork, fileXfr=fileXfr, EntryStatus=EntryStatus, foreIfExtension=foreIfExtension, asx1000=asx1000, asx200bxe=asx200bxe, axhSig=axhSig, TrapNumber=TrapNumber, SpansAddress=SpansAddress, IntegerBitString=IntegerBitString, atmSwitch=atmSwitch, cabletron9A000=cabletron9A000, AtmSigProtocol=AtmSigProtocol, tnx1100b=tnx1100b, asx200bx=asx200bx, etherSwitch=etherSwitch, asx1200=asx1200, hubSwitchRouter=hubSwitchRouter, entityExtensionMIB=entityExtensionMIB, switchRouter=switchRouter, NsapAddr=NsapAddr, asx200wg=asx200wg, systems=systems, atmAdapter=atmAdapter, foreExperiment=foreExperiment, PYSNMP_MODULE_ID=fore, admin=admin, le155=le155, GeneralState=GeneralState, hardware=hardware, stackSwitch=stackSwitch, asx150=asx150, tnx210=tnx210, snmpTrapLog=snmpTrapLog) |
class Page(object):
def __init__(self, params):
self.size = 2 ** 10
self.Time = False
self.R = False
self.M = False
| class Page(object):
def __init__(self, params):
self.size = 2 ** 10
self.Time = False
self.R = False
self.M = False |
PROMQL = """
start: query
// Binary operations are defined separately in order to support precedence
?query\
: or_match
| matrix
| subquery
| offset
?or_match\
: and_unless_match
| or_match OR grouping? and_unless_match
?and_unless_match\
: comparison_match
| and_unless_match (AND | UNLESS) grouping? comparison_match
?comparison_match\
: sum_match
| comparison_match /==|!=|>=|<=|>|</ BOOL? grouping? sum_match
?sum_match\
: product_match
| sum_match /\\+|-/ grouping? product_match
?product_match\
: unary
| product_match /\\*|\\/|%/ grouping? unary
?unary\
: power_match
| /\\+|-/ power_match
?power_match\
: atom
| atom /\\^/ grouping? power_match
?atom\
: function
| aggregation
| instant_query
| NUMBER
| STRING
| "(" query ")"
// Selectors
instant_query\
: METRIC_NAME ("{" label_matcher_list? "}")? -> instant_query_with_metric
| "{" label_matcher_list "}" -> instant_query_without_metric
label_matcher_list: label_matcher ("," label_matcher)*
label_matcher: label_name /=~|=|!=|!~/ STRING
matrix: query "[" DURATION "]"
subquery: query "[" DURATION ":" DURATION? "]"
offset: query OFFSET DURATION
// Function
function: function_name parameter_list
parameter_list: "(" (query ("," query)*)? ")"
?function_name\
: ABS
| ABSENT
| ABSENT_OVER_TIME
| CEIL
| CHANGES
| CLAMP_MAX
| CLAMP_MIN
| DAY_OF_MONTH
| DAY_OF_WEEK
| DAYS_IN_MONTH
| DELTA
| DERIV
| EXP
| FLOOR
| HISTOGRAM_QUANTILE
| HOLT_WINTERS
| HOUR
| IDELTA
| INCREASE
| IRATE
| LABEL_JOIN
| LABEL_REPLACE
| LN
| LOG2
| LOG10
| MINUTE
| MONTH
| PREDICT_LINEAR
| RATE
| RESETS
| ROUND
| SCALAR
| SORT
| SORT_DESC
| SQRT
| TIME
| TIMESTAMP
| VECTOR
| YEAR
| AVG_OVER_TIME
| MIN_OVER_TIME
| MAX_OVER_TIME
| SUM_OVER_TIME
| COUNT_OVER_TIME
| QUANTILE_OVER_TIME
| STDDEV_OVER_TIME
| STDVAR_OVER_TIME
// Aggregations
aggregation\
: aggregation_operator parameter_list
| aggregation_operator (by | without) parameter_list
| aggregation_operator parameter_list (by | without)
by: BY label_name_list
without: WITHOUT label_name_list
?aggregation_operator\
: SUM
| MIN
| MAX
| AVG
| GROUP
| STDDEV
| STDVAR
| COUNT
| COUNT_VALUES
| BOTTOMK
| TOPK
| QUANTILE
// Vector one-to-one/one-to-many joins
grouping: (on | ignoring) (group_left | group_right)?
on: ON label_name_list
ignoring: IGNORING label_name_list
group_left: GROUP_LEFT label_name_list
group_right: GROUP_RIGHT label_name_list
// Label names
label_name_list: "(" (label_name ("," label_name)*)? ")"
?label_name: keyword | LABEL_NAME
?keyword\
: AND
| OR
| UNLESS
| BY
| WITHOUT
| ON
| IGNORING
| GROUP_LEFT
| GROUP_RIGHT
| OFFSET
| BOOL
| aggregation_operator
| function_name
// Keywords
// Function names
ABS: "abs"
ABSENT: "absent"
ABSENT_OVER_TIME: "absent_over_time"
CEIL: "ceil"
CHANGES: "changes"
CLAMP_MAX: "clamp_max"
CLAMP_MIN: "clamp_min"
DAY_OF_MONTH: "day_of_month"
DAY_OF_WEEK: "day_of_week"
DAYS_IN_MONTH: "days_in_month"
DELTA: "delta"
DERIV: "deriv"
EXP: "exp"
FLOOR: "floor"
HISTOGRAM_QUANTILE: "histogram_quantile"
HOLT_WINTERS: "holt_winters"
HOUR: "hour"
IDELTA: "idelta"
INCREASE: "increase"
IRATE: "irate"
LABEL_JOIN: "label_join"
LABEL_REPLACE: "label_replace"
LN: "ln"
LOG2: "log2"
LOG10: "log10"
MINUTE: "minute"
MONTH: "month"
PREDICT_LINEAR: "predict_linear"
RATE: "rate"
RESETS: "resets"
ROUND: "round"
SCALAR: "scalar"
SORT: "sort"
SORT_DESC: "sort_desc"
SQRT: "sqrt"
TIME: "time"
TIMESTAMP: "timestamp"
VECTOR: "vector"
YEAR: "year"
AVG_OVER_TIME: "avg_over_time"
MIN_OVER_TIME: "min_over_time"
MAX_OVER_TIME: "max_over_time"
SUM_OVER_TIME: "sum_over_time"
COUNT_OVER_TIME: "count_over_time"
QUANTILE_OVER_TIME: "quantile_over_time"
STDDEV_OVER_TIME: "stddev_over_time"
STDVAR_OVER_TIME: "stdvar_over_time"
// Aggregation operators
SUM: "sum"
MIN: "min"
MAX: "max"
AVG: "avg"
GROUP: "group"
STDDEV: "stddev"
STDVAR: "stdvar"
COUNT: "count"
COUNT_VALUES: "count_values"
BOTTOMK: "bottomk"
TOPK: "topk"
QUANTILE: "quantile"
// Aggregation modifiers
BY: "by"
WITHOUT: "without"
// Join modifiers
ON: "on"
IGNORING: "ignoring"
GROUP_LEFT: "group_left"
GROUP_RIGHT: "group_right"
// Logical operators
AND: "and"
OR: "or"
UNLESS: "unless"
OFFSET: "offset"
BOOL: "bool"
NUMBER: /[0-9]+(\\.[0-9]+)?/
STRING\
: "'" /([^'\\\\]|\\\\.)*/ "'"
| "\\"" /([^\\"\\\\]|\\\\.)*/ "\\""
DURATION: DIGIT+ ("s" | "m" | "h" | "d" | "w" | "y")
METRIC_NAME: (LETTER | "_" | ":") (DIGIT | LETTER | "_" | ":")*
LABEL_NAME: (LETTER | "_") (DIGIT | LETTER | "_")*
%import common.DIGIT
%import common.LETTER
%import common.WS
%ignore WS
"""
| promql = '\nstart: query\n\n// Binary operations are defined separately in order to support precedence\n\n?query : or_match\n | matrix\n | subquery\n | offset\n\n?or_match : and_unless_match\n | or_match OR grouping? and_unless_match\n\n?and_unless_match : comparison_match\n | and_unless_match (AND | UNLESS) grouping? comparison_match\n\n?comparison_match : sum_match\n | comparison_match /==|!=|>=|<=|>|</ BOOL? grouping? sum_match\n\n?sum_match : product_match\n | sum_match /\\+|-/ grouping? product_match\n\n?product_match : unary\n | product_match /\\*|\\/|%/ grouping? unary\n\n?unary : power_match\n | /\\+|-/ power_match\n\n?power_match : atom\n | atom /\\^/ grouping? power_match\n\n?atom : function\n | aggregation\n | instant_query\n | NUMBER\n | STRING\n | "(" query ")"\n\n// Selectors\n\ninstant_query : METRIC_NAME ("{" label_matcher_list? "}")? -> instant_query_with_metric\n | "{" label_matcher_list "}" -> instant_query_without_metric\n\nlabel_matcher_list: label_matcher ("," label_matcher)*\nlabel_matcher: label_name /=~|=|!=|!~/ STRING\n\nmatrix: query "[" DURATION "]"\n\nsubquery: query "[" DURATION ":" DURATION? "]"\n\noffset: query OFFSET DURATION\n\n// Function\n\nfunction: function_name parameter_list\nparameter_list: "(" (query ("," query)*)? ")"\n?function_name : ABS\n | ABSENT\n | ABSENT_OVER_TIME\n | CEIL\n | CHANGES\n | CLAMP_MAX\n | CLAMP_MIN\n | DAY_OF_MONTH\n | DAY_OF_WEEK\n | DAYS_IN_MONTH\n | DELTA\n | DERIV\n | EXP\n | FLOOR\n | HISTOGRAM_QUANTILE\n | HOLT_WINTERS\n | HOUR\n | IDELTA\n | INCREASE\n | IRATE\n | LABEL_JOIN\n | LABEL_REPLACE\n | LN\n | LOG2\n | LOG10\n | MINUTE\n | MONTH\n | PREDICT_LINEAR\n | RATE\n | RESETS\n | ROUND\n | SCALAR\n | SORT\n | SORT_DESC\n | SQRT\n | TIME\n | TIMESTAMP\n | VECTOR\n | YEAR\n | AVG_OVER_TIME\n | MIN_OVER_TIME\n | MAX_OVER_TIME\n | SUM_OVER_TIME\n | COUNT_OVER_TIME\n | QUANTILE_OVER_TIME\n | STDDEV_OVER_TIME\n | STDVAR_OVER_TIME\n\n// Aggregations\n\naggregation : aggregation_operator parameter_list\n | aggregation_operator (by | without) parameter_list\n | aggregation_operator parameter_list (by | without)\nby: BY label_name_list\nwithout: WITHOUT label_name_list\n?aggregation_operator : SUM\n | MIN\n | MAX\n | AVG\n | GROUP\n | STDDEV\n | STDVAR\n | COUNT\n | COUNT_VALUES\n | BOTTOMK\n | TOPK\n | QUANTILE\n\n// Vector one-to-one/one-to-many joins\n\ngrouping: (on | ignoring) (group_left | group_right)?\non: ON label_name_list\nignoring: IGNORING label_name_list\ngroup_left: GROUP_LEFT label_name_list\ngroup_right: GROUP_RIGHT label_name_list\n\n// Label names\n\nlabel_name_list: "(" (label_name ("," label_name)*)? ")"\n?label_name: keyword | LABEL_NAME\n\n?keyword : AND\n | OR\n | UNLESS\n | BY\n | WITHOUT\n | ON\n | IGNORING\n | GROUP_LEFT\n | GROUP_RIGHT\n | OFFSET\n | BOOL\n | aggregation_operator\n | function_name\n\n// Keywords\n\n// Function names\n\nABS: "abs"\nABSENT: "absent"\nABSENT_OVER_TIME: "absent_over_time"\nCEIL: "ceil"\nCHANGES: "changes"\nCLAMP_MAX: "clamp_max"\nCLAMP_MIN: "clamp_min"\nDAY_OF_MONTH: "day_of_month"\nDAY_OF_WEEK: "day_of_week"\nDAYS_IN_MONTH: "days_in_month"\nDELTA: "delta"\nDERIV: "deriv"\nEXP: "exp"\nFLOOR: "floor"\nHISTOGRAM_QUANTILE: "histogram_quantile"\nHOLT_WINTERS: "holt_winters"\nHOUR: "hour"\nIDELTA: "idelta"\nINCREASE: "increase"\nIRATE: "irate"\nLABEL_JOIN: "label_join"\nLABEL_REPLACE: "label_replace"\nLN: "ln"\nLOG2: "log2"\nLOG10: "log10"\nMINUTE: "minute"\nMONTH: "month"\nPREDICT_LINEAR: "predict_linear"\nRATE: "rate"\nRESETS: "resets"\nROUND: "round"\nSCALAR: "scalar"\nSORT: "sort"\nSORT_DESC: "sort_desc"\nSQRT: "sqrt"\nTIME: "time"\nTIMESTAMP: "timestamp"\nVECTOR: "vector"\nYEAR: "year"\nAVG_OVER_TIME: "avg_over_time"\nMIN_OVER_TIME: "min_over_time"\nMAX_OVER_TIME: "max_over_time"\nSUM_OVER_TIME: "sum_over_time"\nCOUNT_OVER_TIME: "count_over_time"\nQUANTILE_OVER_TIME: "quantile_over_time"\nSTDDEV_OVER_TIME: "stddev_over_time"\nSTDVAR_OVER_TIME: "stdvar_over_time"\n\n// Aggregation operators\n\nSUM: "sum"\nMIN: "min"\nMAX: "max"\nAVG: "avg"\nGROUP: "group"\nSTDDEV: "stddev"\nSTDVAR: "stdvar"\nCOUNT: "count"\nCOUNT_VALUES: "count_values"\nBOTTOMK: "bottomk"\nTOPK: "topk"\nQUANTILE: "quantile"\n\n// Aggregation modifiers\n\nBY: "by"\nWITHOUT: "without"\n\n// Join modifiers\n\nON: "on"\nIGNORING: "ignoring"\nGROUP_LEFT: "group_left"\nGROUP_RIGHT: "group_right"\n\n// Logical operators\n\nAND: "and"\nOR: "or"\nUNLESS: "unless"\n\nOFFSET: "offset"\n\nBOOL: "bool"\n\nNUMBER: /[0-9]+(\\.[0-9]+)?/\n\nSTRING : "\'" /([^\'\\\\]|\\\\.)*/ "\'"\n | "\\"" /([^\\"\\\\]|\\\\.)*/ "\\""\n\nDURATION: DIGIT+ ("s" | "m" | "h" | "d" | "w" | "y")\n\nMETRIC_NAME: (LETTER | "_" | ":") (DIGIT | LETTER | "_" | ":")*\n\nLABEL_NAME: (LETTER | "_") (DIGIT | LETTER | "_")*\n\n%import common.DIGIT\n%import common.LETTER\n%import common.WS\n\n%ignore WS\n' |
ftxus = {
'api_key':'YOUR_API_KEY',
'api_secret':'YOUR_API_SECRET'
}
| ftxus = {'api_key': 'YOUR_API_KEY', 'api_secret': 'YOUR_API_SECRET'} |
a = [1, 2, 3, 4]
def subset(a, n):
if n == 1:
return n
else:
return (subset(a[n - 1]), subset(a[n - 2]))
print(subset(a, n=4))
| a = [1, 2, 3, 4]
def subset(a, n):
if n == 1:
return n
else:
return (subset(a[n - 1]), subset(a[n - 2]))
print(subset(a, n=4)) |
def print_formatted(number):
# your code goes here
for i in range(1, number +1):
width = len(f"{number:b}")
print(f"{i:{width}} {i:{width}o} {i:{width}X} {i:{width}b}")
| def print_formatted(number):
for i in range(1, number + 1):
width = len(f'{number:b}')
print(f'{i:{width}} {i:{width}o} {i:{width}X} {i:{width}b}') |
class Solution:
def coinChange(self, coins: List[int], amount: int) -> int:
dp = [inf] * (amount + 1)
dp[0] = 0
for coin in coins:
for x in range(coin, amount + 1):
dp[x] = min(dp[x], dp[x - coin] + 1)
return dp[amount] if dp[amount] != inf else -1
| class Solution:
def coin_change(self, coins: List[int], amount: int) -> int:
dp = [inf] * (amount + 1)
dp[0] = 0
for coin in coins:
for x in range(coin, amount + 1):
dp[x] = min(dp[x], dp[x - coin] + 1)
return dp[amount] if dp[amount] != inf else -1 |
#
# PySNMP MIB module Intel-Common-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Intel-Common-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:54:14 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsUnion, ConstraintsIntersection, ValueRangeConstraint, ValueSizeConstraint, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "ConstraintsIntersection", "ValueRangeConstraint", "ValueSizeConstraint", "SingleValueConstraint")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
ModuleIdentity, ObjectIdentity, iso, Integer32, Bits, Counter64, Counter32, Gauge32, NotificationType, Unsigned32, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, IpAddress, TimeTicks, enterprises = mibBuilder.importSymbols("SNMPv2-SMI", "ModuleIdentity", "ObjectIdentity", "iso", "Integer32", "Bits", "Counter64", "Counter32", "Gauge32", "NotificationType", "Unsigned32", "MibIdentifier", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "IpAddress", "TimeTicks", "enterprises")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
intel = MibIdentifier((1, 3, 6, 1, 4, 1, 343))
identifiers = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 1))
products = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 2))
experimental = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 3))
information_technology = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 4)).setLabel("information-technology")
sysProducts = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 5))
mib2ext = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 6))
hw = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 7))
wekiva = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 111))
systems = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 1, 1))
objects = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 1, 2))
comm_methods = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 1, 3)).setLabel("comm-methods")
pc_systems = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 1, 1, 1)).setLabel("pc-systems")
proxy_systems = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 1, 1, 2)).setLabel("proxy-systems")
hub_systems = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 1, 1, 3)).setLabel("hub-systems")
switch_systems = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 1, 1, 4)).setLabel("switch-systems")
local_proxy_1 = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 1, 3, 1)).setLabel("local-proxy-1")
pc_novell_1 = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 1, 3, 2)).setLabel("pc-novell-1")
express10_100Stack = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 1, 1, 3, 1)).setLabel("express10-100Stack")
express12TX = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 1, 1, 3, 2))
express24TX = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 1, 1, 3, 3))
expressReserved = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 1, 1, 3, 4))
expressBridge = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 1, 1, 3, 6))
express210_12 = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 1, 1, 3, 7)).setLabel("express210-12")
express210_24 = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 1, 1, 3, 8)).setLabel("express210-24")
express220_12 = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 1, 1, 3, 9)).setLabel("express220-12")
express220_24 = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 1, 1, 3, 10)).setLabel("express220-24")
express300Stack = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 1, 1, 3, 11))
express320_16 = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 1, 1, 3, 12)).setLabel("express320-16")
express320_24 = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 1, 1, 3, 13)).setLabel("express320-24")
pc_products = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 2, 1)).setLabel("pc-products")
hub_products = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 2, 2)).setLabel("hub-products")
proxy = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 2, 3))
print_products = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 2, 4)).setLabel("print-products")
network_products = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 2, 5)).setLabel("network-products")
snmp_agents = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 2, 6)).setLabel("snmp-agents")
nic_products = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 2, 7)).setLabel("nic-products")
server_management = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 2, 10)).setLabel("server-management")
switch_products = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 2, 11)).setLabel("switch-products")
i2o = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 2, 120))
express110 = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 2, 2, 1))
netport_1 = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 2, 4, 1)).setLabel("netport-1")
netport_2 = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 2, 4, 2)).setLabel("netport-2")
netport_express = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 2, 4, 3)).setLabel("netport-express")
lanDesk = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 2, 5, 1))
ld_alarms = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 2, 5, 1, 1)).setLabel("ld-alarms")
internetServer_2 = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 2, 5, 2)).setLabel("internetServer-2")
iS_alarms = MibIdentifier((1, 3, 6, 1, 4, 1, 343, 2, 5, 2, 1)).setLabel("iS-alarms")
mibBuilder.exportSymbols("Intel-Common-MIB", express220_24=express220_24, express110=express110, snmp_agents=snmp_agents, switch_systems=switch_systems, objects=objects, proxy=proxy, lanDesk=lanDesk, express12TX=express12TX, mib2ext=mib2ext, experimental=experimental, express210_24=express210_24, sysProducts=sysProducts, netport_1=netport_1, internetServer_2=internetServer_2, intel=intel, pc_novell_1=pc_novell_1, products=products, express320_24=express320_24, proxy_systems=proxy_systems, express320_16=express320_16, identifiers=identifiers, express300Stack=express300Stack, wekiva=wekiva, express10_100Stack=express10_100Stack, hub_systems=hub_systems, ld_alarms=ld_alarms, server_management=server_management, switch_products=switch_products, i2o=i2o, netport_express=netport_express, network_products=network_products, expressBridge=expressBridge, express220_12=express220_12, local_proxy_1=local_proxy_1, systems=systems, comm_methods=comm_methods, express210_12=express210_12, pc_products=pc_products, hub_products=hub_products, expressReserved=expressReserved, netport_2=netport_2, pc_systems=pc_systems, hw=hw, express24TX=express24TX, print_products=print_products, information_technology=information_technology, iS_alarms=iS_alarms, nic_products=nic_products)
| (integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, constraints_intersection, value_range_constraint, value_size_constraint, single_value_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsUnion', 'ConstraintsIntersection', 'ValueRangeConstraint', 'ValueSizeConstraint', 'SingleValueConstraint')
(module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup')
(module_identity, object_identity, iso, integer32, bits, counter64, counter32, gauge32, notification_type, unsigned32, mib_identifier, mib_scalar, mib_table, mib_table_row, mib_table_column, ip_address, time_ticks, enterprises) = mibBuilder.importSymbols('SNMPv2-SMI', 'ModuleIdentity', 'ObjectIdentity', 'iso', 'Integer32', 'Bits', 'Counter64', 'Counter32', 'Gauge32', 'NotificationType', 'Unsigned32', 'MibIdentifier', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'IpAddress', 'TimeTicks', 'enterprises')
(display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention')
intel = mib_identifier((1, 3, 6, 1, 4, 1, 343))
identifiers = mib_identifier((1, 3, 6, 1, 4, 1, 343, 1))
products = mib_identifier((1, 3, 6, 1, 4, 1, 343, 2))
experimental = mib_identifier((1, 3, 6, 1, 4, 1, 343, 3))
information_technology = mib_identifier((1, 3, 6, 1, 4, 1, 343, 4)).setLabel('information-technology')
sys_products = mib_identifier((1, 3, 6, 1, 4, 1, 343, 5))
mib2ext = mib_identifier((1, 3, 6, 1, 4, 1, 343, 6))
hw = mib_identifier((1, 3, 6, 1, 4, 1, 343, 7))
wekiva = mib_identifier((1, 3, 6, 1, 4, 1, 343, 111))
systems = mib_identifier((1, 3, 6, 1, 4, 1, 343, 1, 1))
objects = mib_identifier((1, 3, 6, 1, 4, 1, 343, 1, 2))
comm_methods = mib_identifier((1, 3, 6, 1, 4, 1, 343, 1, 3)).setLabel('comm-methods')
pc_systems = mib_identifier((1, 3, 6, 1, 4, 1, 343, 1, 1, 1)).setLabel('pc-systems')
proxy_systems = mib_identifier((1, 3, 6, 1, 4, 1, 343, 1, 1, 2)).setLabel('proxy-systems')
hub_systems = mib_identifier((1, 3, 6, 1, 4, 1, 343, 1, 1, 3)).setLabel('hub-systems')
switch_systems = mib_identifier((1, 3, 6, 1, 4, 1, 343, 1, 1, 4)).setLabel('switch-systems')
local_proxy_1 = mib_identifier((1, 3, 6, 1, 4, 1, 343, 1, 3, 1)).setLabel('local-proxy-1')
pc_novell_1 = mib_identifier((1, 3, 6, 1, 4, 1, 343, 1, 3, 2)).setLabel('pc-novell-1')
express10_100_stack = mib_identifier((1, 3, 6, 1, 4, 1, 343, 1, 1, 3, 1)).setLabel('express10-100Stack')
express12_tx = mib_identifier((1, 3, 6, 1, 4, 1, 343, 1, 1, 3, 2))
express24_tx = mib_identifier((1, 3, 6, 1, 4, 1, 343, 1, 1, 3, 3))
express_reserved = mib_identifier((1, 3, 6, 1, 4, 1, 343, 1, 1, 3, 4))
express_bridge = mib_identifier((1, 3, 6, 1, 4, 1, 343, 1, 1, 3, 6))
express210_12 = mib_identifier((1, 3, 6, 1, 4, 1, 343, 1, 1, 3, 7)).setLabel('express210-12')
express210_24 = mib_identifier((1, 3, 6, 1, 4, 1, 343, 1, 1, 3, 8)).setLabel('express210-24')
express220_12 = mib_identifier((1, 3, 6, 1, 4, 1, 343, 1, 1, 3, 9)).setLabel('express220-12')
express220_24 = mib_identifier((1, 3, 6, 1, 4, 1, 343, 1, 1, 3, 10)).setLabel('express220-24')
express300_stack = mib_identifier((1, 3, 6, 1, 4, 1, 343, 1, 1, 3, 11))
express320_16 = mib_identifier((1, 3, 6, 1, 4, 1, 343, 1, 1, 3, 12)).setLabel('express320-16')
express320_24 = mib_identifier((1, 3, 6, 1, 4, 1, 343, 1, 1, 3, 13)).setLabel('express320-24')
pc_products = mib_identifier((1, 3, 6, 1, 4, 1, 343, 2, 1)).setLabel('pc-products')
hub_products = mib_identifier((1, 3, 6, 1, 4, 1, 343, 2, 2)).setLabel('hub-products')
proxy = mib_identifier((1, 3, 6, 1, 4, 1, 343, 2, 3))
print_products = mib_identifier((1, 3, 6, 1, 4, 1, 343, 2, 4)).setLabel('print-products')
network_products = mib_identifier((1, 3, 6, 1, 4, 1, 343, 2, 5)).setLabel('network-products')
snmp_agents = mib_identifier((1, 3, 6, 1, 4, 1, 343, 2, 6)).setLabel('snmp-agents')
nic_products = mib_identifier((1, 3, 6, 1, 4, 1, 343, 2, 7)).setLabel('nic-products')
server_management = mib_identifier((1, 3, 6, 1, 4, 1, 343, 2, 10)).setLabel('server-management')
switch_products = mib_identifier((1, 3, 6, 1, 4, 1, 343, 2, 11)).setLabel('switch-products')
i2o = mib_identifier((1, 3, 6, 1, 4, 1, 343, 2, 120))
express110 = mib_identifier((1, 3, 6, 1, 4, 1, 343, 2, 2, 1))
netport_1 = mib_identifier((1, 3, 6, 1, 4, 1, 343, 2, 4, 1)).setLabel('netport-1')
netport_2 = mib_identifier((1, 3, 6, 1, 4, 1, 343, 2, 4, 2)).setLabel('netport-2')
netport_express = mib_identifier((1, 3, 6, 1, 4, 1, 343, 2, 4, 3)).setLabel('netport-express')
lan_desk = mib_identifier((1, 3, 6, 1, 4, 1, 343, 2, 5, 1))
ld_alarms = mib_identifier((1, 3, 6, 1, 4, 1, 343, 2, 5, 1, 1)).setLabel('ld-alarms')
internet_server_2 = mib_identifier((1, 3, 6, 1, 4, 1, 343, 2, 5, 2)).setLabel('internetServer-2')
i_s_alarms = mib_identifier((1, 3, 6, 1, 4, 1, 343, 2, 5, 2, 1)).setLabel('iS-alarms')
mibBuilder.exportSymbols('Intel-Common-MIB', express220_24=express220_24, express110=express110, snmp_agents=snmp_agents, switch_systems=switch_systems, objects=objects, proxy=proxy, lanDesk=lanDesk, express12TX=express12TX, mib2ext=mib2ext, experimental=experimental, express210_24=express210_24, sysProducts=sysProducts, netport_1=netport_1, internetServer_2=internetServer_2, intel=intel, pc_novell_1=pc_novell_1, products=products, express320_24=express320_24, proxy_systems=proxy_systems, express320_16=express320_16, identifiers=identifiers, express300Stack=express300Stack, wekiva=wekiva, express10_100Stack=express10_100Stack, hub_systems=hub_systems, ld_alarms=ld_alarms, server_management=server_management, switch_products=switch_products, i2o=i2o, netport_express=netport_express, network_products=network_products, expressBridge=expressBridge, express220_12=express220_12, local_proxy_1=local_proxy_1, systems=systems, comm_methods=comm_methods, express210_12=express210_12, pc_products=pc_products, hub_products=hub_products, expressReserved=expressReserved, netport_2=netport_2, pc_systems=pc_systems, hw=hw, express24TX=express24TX, print_products=print_products, information_technology=information_technology, iS_alarms=iS_alarms, nic_products=nic_products) |
name = input()
class_school = 1
sum_of_grades = 0
ejected = False
failed = 0
while True:
grade = float(input())
if grade >= 4.00:
sum_of_grades += grade
if class_school == 12:
break
class_school += 1
else:
failed += 1
if failed == 2:
ejected = True
break
if ejected:
print(f"{name} has been excluded at {class_school} grade")
else:
average = sum_of_grades / class_school
print(f"{name} graduated. Average grade: {average:.2f}")
| name = input()
class_school = 1
sum_of_grades = 0
ejected = False
failed = 0
while True:
grade = float(input())
if grade >= 4.0:
sum_of_grades += grade
if class_school == 12:
break
class_school += 1
else:
failed += 1
if failed == 2:
ejected = True
break
if ejected:
print(f'{name} has been excluded at {class_school} grade')
else:
average = sum_of_grades / class_school
print(f'{name} graduated. Average grade: {average:.2f}') |
class Solution:
def minSwapsCouples(self, row: List[int]) -> int:
parent=[i for i in range(len(row))]
for i in range(1,len(row),2):
parent[i]-=1
def findpath(u,parent):
if parent[u]!=u:
parent[u]=findpath(parent[u],parent)
return parent[u]
for i in range(0,len(row),2):
u_parent=findpath(row[i],parent)
v_parent=findpath(row[i+1],parent)
parent[u_parent]=v_parent
return (len(row)//2)-sum([1 for i in range(0,len(row),2) if parent[i]==parent[i+1]==i])
| class Solution:
def min_swaps_couples(self, row: List[int]) -> int:
parent = [i for i in range(len(row))]
for i in range(1, len(row), 2):
parent[i] -= 1
def findpath(u, parent):
if parent[u] != u:
parent[u] = findpath(parent[u], parent)
return parent[u]
for i in range(0, len(row), 2):
u_parent = findpath(row[i], parent)
v_parent = findpath(row[i + 1], parent)
parent[u_parent] = v_parent
return len(row) // 2 - sum([1 for i in range(0, len(row), 2) if parent[i] == parent[i + 1] == i]) |
class Token:
def __init__(self, type=None, value=None):
self.type = type
self.value = value
def __str__(self):
return "Token({0}, {1})".format(self.type, self.value) | class Token:
def __init__(self, type=None, value=None):
self.type = type
self.value = value
def __str__(self):
return 'Token({0}, {1})'.format(self.type, self.value) |
"""
Define convention-based global, coordinate and variable attributes
in one place for consistent reuse
"""
DEFAULT_BEAM_COORD_ATTRS = {
"frequency": {
"long_name": "Transducer frequency",
"standard_name": "sound_frequency",
"units": "Hz",
"valid_min": 0.0,
},
"ping_time": {
"long_name": "Timestamp of each ping",
"standard_name": "time",
"axis": "T",
},
"range_bin": {"long_name": "Along-range bin (sample) number, base 0"},
}
DEFAULT_PLATFORM_COORD_ATTRS = {
"location_time": {
"axis": "T",
"long_name": "Timestamps for NMEA datagrams",
"standard_name": "time",
}
}
DEFAULT_PLATFORM_VAR_ATTRS = {
"latitude": {
"long_name": "Platform latitude",
"standard_name": "latitude",
"units": "degrees_north",
"valid_range": (-90.0, 90.0),
},
"longitude": {
"long_name": "Platform longitude",
"standard_name": "longitude",
"units": "degrees_east",
"valid_range": (-180.0, 180.0),
},
"pitch": {
"long_name": "Platform pitch",
"standard_name": "platform_pitch_angle",
"units": "arc_degree",
"valid_range": (-90.0, 90.0),
},
"roll": {
"long_name": "Platform roll",
"standard_name": "platform_roll_angle",
"units": "arc_degree",
"valid_range": (-90.0, 90.0),
},
"heave": {
"long_name": "Platform heave",
"standard_name": "platform_heave_angle",
"units": "arc_degree",
"valid_range": (-90.0, 90.0),
},
"water_level": {
"long_name": "z-axis distance from the platform coordinate system "
"origin to the sonar transducer",
"units": "m",
},
}
| """
Define convention-based global, coordinate and variable attributes
in one place for consistent reuse
"""
default_beam_coord_attrs = {'frequency': {'long_name': 'Transducer frequency', 'standard_name': 'sound_frequency', 'units': 'Hz', 'valid_min': 0.0}, 'ping_time': {'long_name': 'Timestamp of each ping', 'standard_name': 'time', 'axis': 'T'}, 'range_bin': {'long_name': 'Along-range bin (sample) number, base 0'}}
default_platform_coord_attrs = {'location_time': {'axis': 'T', 'long_name': 'Timestamps for NMEA datagrams', 'standard_name': 'time'}}
default_platform_var_attrs = {'latitude': {'long_name': 'Platform latitude', 'standard_name': 'latitude', 'units': 'degrees_north', 'valid_range': (-90.0, 90.0)}, 'longitude': {'long_name': 'Platform longitude', 'standard_name': 'longitude', 'units': 'degrees_east', 'valid_range': (-180.0, 180.0)}, 'pitch': {'long_name': 'Platform pitch', 'standard_name': 'platform_pitch_angle', 'units': 'arc_degree', 'valid_range': (-90.0, 90.0)}, 'roll': {'long_name': 'Platform roll', 'standard_name': 'platform_roll_angle', 'units': 'arc_degree', 'valid_range': (-90.0, 90.0)}, 'heave': {'long_name': 'Platform heave', 'standard_name': 'platform_heave_angle', 'units': 'arc_degree', 'valid_range': (-90.0, 90.0)}, 'water_level': {'long_name': 'z-axis distance from the platform coordinate system origin to the sonar transducer', 'units': 'm'}} |
"""
********************************************************************************
* Name: pagintate.py
* Author: nswain
* Created On: April 17, 2018
* Copyright: (c) Aquaveo 2018
********************************************************************************
"""
def paginate(objects, results_per_page, page, result_name, sort_by_raw=None, sort_reversed=False):
"""
Paginate given list of objects.
Args:
objects(list): list of objects to paginate.
results_per_page(int): maximum number of results to show on a page.
page(int): page to view.
result_name(str): name to use when referencing the objects.
sort_by_raw(str): sort field if applicable.
sort_reversed(boo): indicates whether the sort is reversed or not.
Returns:
list, dict: list of objects for current page, metadata form paginantion page.
"""
results_per_page_options = [5, 10, 20, 40, 80, 120]
num_objects = len(objects)
if num_objects <= results_per_page:
page = 1
min_index = (page - 1) * results_per_page
max_index = min(page * results_per_page, num_objects)
paginated_objects = objects[min_index:max_index]
enable_next_button = max_index < num_objects
enable_previous_button = min_index > 0
pagination_info = {
'num_results': num_objects,
'result_name': result_name,
'page': page,
'min_showing': min_index + 1 if max_index > 0 else 0,
'max_showing': max_index,
'next_page': page + 1,
'previous_page': page - 1,
'sort_by': sort_by_raw,
'sort_reversed': sort_reversed,
'enable_next_button': enable_next_button,
'enable_previous_button': enable_previous_button,
'hide_buttons': page == 1 and max_index == num_objects,
'hide_header_buttons': len(paginated_objects) < 20,
'show': results_per_page,
'results_per_page_options': [x for x in results_per_page_options if x <= num_objects],
'hide_results_per_page_options': num_objects <= results_per_page_options[0],
}
return paginated_objects, pagination_info
| """
********************************************************************************
* Name: pagintate.py
* Author: nswain
* Created On: April 17, 2018
* Copyright: (c) Aquaveo 2018
********************************************************************************
"""
def paginate(objects, results_per_page, page, result_name, sort_by_raw=None, sort_reversed=False):
"""
Paginate given list of objects.
Args:
objects(list): list of objects to paginate.
results_per_page(int): maximum number of results to show on a page.
page(int): page to view.
result_name(str): name to use when referencing the objects.
sort_by_raw(str): sort field if applicable.
sort_reversed(boo): indicates whether the sort is reversed or not.
Returns:
list, dict: list of objects for current page, metadata form paginantion page.
"""
results_per_page_options = [5, 10, 20, 40, 80, 120]
num_objects = len(objects)
if num_objects <= results_per_page:
page = 1
min_index = (page - 1) * results_per_page
max_index = min(page * results_per_page, num_objects)
paginated_objects = objects[min_index:max_index]
enable_next_button = max_index < num_objects
enable_previous_button = min_index > 0
pagination_info = {'num_results': num_objects, 'result_name': result_name, 'page': page, 'min_showing': min_index + 1 if max_index > 0 else 0, 'max_showing': max_index, 'next_page': page + 1, 'previous_page': page - 1, 'sort_by': sort_by_raw, 'sort_reversed': sort_reversed, 'enable_next_button': enable_next_button, 'enable_previous_button': enable_previous_button, 'hide_buttons': page == 1 and max_index == num_objects, 'hide_header_buttons': len(paginated_objects) < 20, 'show': results_per_page, 'results_per_page_options': [x for x in results_per_page_options if x <= num_objects], 'hide_results_per_page_options': num_objects <= results_per_page_options[0]}
return (paginated_objects, pagination_info) |
def not_found_handler():
return '404. Path not found'
def internal_error_handler():
return '500. Internal error' | def not_found_handler():
return '404. Path not found'
def internal_error_handler():
return '500. Internal error' |
# ~*~ coding: utf-8 ~*~
__doc__ = """
`opencannabis.media`
---------------------------
Records and definitions that structure digital media and related assets.
"""
# `opencannabis.media`
| __doc__ = '\n\n `opencannabis.media`\n ---------------------------\n Records and definitions that structure digital media and related assets.\n\n' |
# -*- coding: utf-8 -*-
"""
Exceptions for Arequests
Created on Tue Nov 13 08:34:14 2018
@author: gfi
"""
class ArequestsError(Exception):
"""Basic exception for errors raised by Arequests"""
pass
class AuthorizationError(ArequestsError):
'''401 error new authentification required'''
pass
class SomeClientError(ArequestsError):
'''4xx client error'''
pass
class SomeServerError(ArequestsError):
'''5xx server error'''
pass
| """
Exceptions for Arequests
Created on Tue Nov 13 08:34:14 2018
@author: gfi
"""
class Arequestserror(Exception):
"""Basic exception for errors raised by Arequests"""
pass
class Authorizationerror(ArequestsError):
"""401 error new authentification required"""
pass
class Someclienterror(ArequestsError):
"""4xx client error"""
pass
class Someservererror(ArequestsError):
"""5xx server error"""
pass |
def transform_file(infile,outfile,templates):
with open(infile,'r') as fh:
indata = fh.read()
lines = indata.split('\n')
outlines = []
for line in lines:
if '//ATL_BEGIN' in line:
start = line.find('//ATL_BEGIN')
spacing = line[:start]
start = line.find('<') + 1
end = line.find('>')
tkey = line[start:end]
ttxt = templates[tkey]
for tl in ttxt:
outlines.append(spacing + tl)
else:
outlines.append(line)
with open(outfile,'w') as fh:
for line in outlines:
fh.write(line+'\n') | def transform_file(infile, outfile, templates):
with open(infile, 'r') as fh:
indata = fh.read()
lines = indata.split('\n')
outlines = []
for line in lines:
if '//ATL_BEGIN' in line:
start = line.find('//ATL_BEGIN')
spacing = line[:start]
start = line.find('<') + 1
end = line.find('>')
tkey = line[start:end]
ttxt = templates[tkey]
for tl in ttxt:
outlines.append(spacing + tl)
else:
outlines.append(line)
with open(outfile, 'w') as fh:
for line in outlines:
fh.write(line + '\n') |
#!/usr/bin/env python
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ************************************************************************************
# YOU NEED TO MODIFY THE FOLLOWING METADATA TO ADAPT THE TRAINER TEMPLATE TO YOUR DATA
# ************************************************************************************
# Task type can be either 'classification', 'regression', or 'custom'
# This is based on the target feature in the dataset, and whether you use a canned or a custom estimator
TASK_TYPE = '' # classification | regression | custom
# A List of all the columns (header) present in the input data file(s) in order to parse it.
# Note that, not all the columns present here will be input features to your model.
HEADER = []
# List of the default values of all the columns present in the input data.
# This helps decoding the data types of the columns.
HEADER_DEFAULTS = []
# List of the feature names of type int or float.
INPUT_NUMERIC_FEATURE_NAMES = []
# Numeric features constructed, if any, in process_features function in input.py module,
# as part of reading data.
CONSTRUCTED_NUMERIC_FEATURE_NAMES = []
# Dictionary of feature names with int values, but to be treated as categorical features.
# In the dictionary, the key is the feature name, and the value is the num_buckets (count of distinct values).
INPUT_CATEGORICAL_FEATURE_NAMES_WITH_IDENTITY = {}
# Categorical features with identity constructed, if any, in process_features function in input.py module,
# as part of reading data. Usually include constructed boolean flags.
CONSTRUCTED_CATEGORICAL_FEATURE_NAMES_WITH_IDENTITY = {}
# Dictionary of categorical features with few nominal values (to be encoded as one-hot indicators).
# In the dictionary, the key is the feature name, and the value is the list of feature vocabulary.
INPUT_CATEGORICAL_FEATURE_NAMES_WITH_VOCABULARY = {}
# Dictionary of categorical features with many values (sparse features).
# In the dictionary, the key is the feature name, and the value is the bucket size.
INPUT_CATEGORICAL_FEATURE_NAMES_WITH_HASH_BUCKET = {}
# List of all the categorical feature names.
# This is programmatically created based on the previous inputs.
INPUT_CATEGORICAL_FEATURE_NAMES = list(INPUT_CATEGORICAL_FEATURE_NAMES_WITH_IDENTITY.keys()) \
+ list(INPUT_CATEGORICAL_FEATURE_NAMES_WITH_VOCABULARY.keys()) \
+ list(INPUT_CATEGORICAL_FEATURE_NAMES_WITH_HASH_BUCKET.keys())
# List of all the input feature names to be used in the model.
# This is programmatically created based on the previous inputs.
INPUT_FEATURE_NAMES = INPUT_NUMERIC_FEATURE_NAMES + INPUT_CATEGORICAL_FEATURE_NAMES
# Column includes the relative weight of each record.
WEIGHT_COLUMN_NAME = None
# Target feature name (response or class variable).
TARGET_NAME = ''
# List of the class values (labels) in a classification dataset.
TARGET_LABELS = []
# List of the columns expected during serving (which is probably different to the header of the training data).
SERVING_COLUMNS = []
# List of the default values of all the columns of the serving data.
# This helps decoding the data types of the columns.
SERVING_DEFAULTS = []
| task_type = ''
header = []
header_defaults = []
input_numeric_feature_names = []
constructed_numeric_feature_names = []
input_categorical_feature_names_with_identity = {}
constructed_categorical_feature_names_with_identity = {}
input_categorical_feature_names_with_vocabulary = {}
input_categorical_feature_names_with_hash_bucket = {}
input_categorical_feature_names = list(INPUT_CATEGORICAL_FEATURE_NAMES_WITH_IDENTITY.keys()) + list(INPUT_CATEGORICAL_FEATURE_NAMES_WITH_VOCABULARY.keys()) + list(INPUT_CATEGORICAL_FEATURE_NAMES_WITH_HASH_BUCKET.keys())
input_feature_names = INPUT_NUMERIC_FEATURE_NAMES + INPUT_CATEGORICAL_FEATURE_NAMES
weight_column_name = None
target_name = ''
target_labels = []
serving_columns = []
serving_defaults = [] |
#
#
# This is Support for Drawing Bullet Charts
#
#
#
#
#
#
#
'''
This is the return json value to the javascript front end
{ "canvasName":"canvas1","featuredColor":"Green", "featuredMeasure":14.5,
"qualScale1":14.5, "qualScale1Color":"Black","titleText":"Step 1" },
{ "canvasName":"canvas2","featuredColor":"Blue", "featuredMeasure":14.5,
"qualScale1":14.5, "qualScale1Color":"Black","titleText":"Step 2" },
{ "canvasName":"canvas3","featuredColor":"Red", "featuredMeasure":14.5,
"qualScale1":14.5, "qualScale1Color":"Black","titleText":"Step 3" },
'''
class template_support():
def __init__(self , redis_handle, statistics_module):
self.redis_handle = redis_handle
self.statistics_module = statistics_module
def generate_current_canvas_list( self, schedule_name, *args, **kwargs ):
return_value = []
self.schedule_name = schedule_name
data = self.statistics_module.schedule_data[ schedule_name ]
current_data = self.statistics_module.get_current_data( data["step_number"],schedule_name )
limit_values = self.statistics_module.get_current_limit_values( data["step_number"],schedule_name )
for i in range(0,data["step_number"]):
temp = {}
temp["canvasName"] = "canvas1" +str(i+1)
temp["titleText"] = "Step " +str(i+1)
temp["qualScale1Color"] = "Black"
temp["featuredColor"] = "Red"
temp["qualScale1"] = limit_values[i]['limit_avg']
temp["featuredMeasure"] = current_data[i]
temp["limit"] = limit_values[i]['limit_std']
temp["step"] = i
return_value.append(temp)
return return_value
def generate_canvas_list(self, schedule_name, flow_id , *args,**kwargs):
return_value = []
self.schedule_name = schedule_name
data = self.statistics_module.schedule_data[ schedule_name ]
flow_sensors = self.statistics_module.sensor_names
flow_sensor_name = flow_sensors[flow_id]
conversion_rate = self.statistics_module.conversion_rate[flow_id]
flow_data = self.statistics_module.get_average_flow_data( data["step_number"], flow_sensor_name, schedule_name )
limit_values = self.statistics_module.get_flow_limit_values( data["step_number"], flow_sensor_name, schedule_name )
for i in limit_values:
try:
i['limit_avg'] = float(i['limit_avg'])*conversion_rate
i['limit_std'] = float(i['limit_std'])*conversion_rate
except:
pass
corrected_flow = []
for i in flow_data:
temp1 = []
for j in i:
temp1.append( j *conversion_rate)
corrected_flow.append(temp1)
for i in range(0,data["step_number"]):
temp = {}
temp["canvasName"] = "canvas1" +str(i+1)
temp["titleText"] = "Step " +str(i+1)
temp["qualScale1Color"] = "Black"
temp["featuredColor"] = "Red"
try:
temp["qualScale1"] = limit_values[i]['limit_avg']
except:
temp["qualScale1"] = 0
try:
temp["featuredMeasure"] = corrected_flow[i]
except:
temp["featuredMeasure"] = 0
try:
temp["limit"] = limit_values[i]['limit_std']
except:
temp["limit"] = 0
return_value.append(temp)
return return_value
| """
This is the return json value to the javascript front end
{ "canvasName":"canvas1","featuredColor":"Green", "featuredMeasure":14.5,
"qualScale1":14.5, "qualScale1Color":"Black","titleText":"Step 1" },
{ "canvasName":"canvas2","featuredColor":"Blue", "featuredMeasure":14.5,
"qualScale1":14.5, "qualScale1Color":"Black","titleText":"Step 2" },
{ "canvasName":"canvas3","featuredColor":"Red", "featuredMeasure":14.5,
"qualScale1":14.5, "qualScale1Color":"Black","titleText":"Step 3" },
"""
class Template_Support:
def __init__(self, redis_handle, statistics_module):
self.redis_handle = redis_handle
self.statistics_module = statistics_module
def generate_current_canvas_list(self, schedule_name, *args, **kwargs):
return_value = []
self.schedule_name = schedule_name
data = self.statistics_module.schedule_data[schedule_name]
current_data = self.statistics_module.get_current_data(data['step_number'], schedule_name)
limit_values = self.statistics_module.get_current_limit_values(data['step_number'], schedule_name)
for i in range(0, data['step_number']):
temp = {}
temp['canvasName'] = 'canvas1' + str(i + 1)
temp['titleText'] = 'Step ' + str(i + 1)
temp['qualScale1Color'] = 'Black'
temp['featuredColor'] = 'Red'
temp['qualScale1'] = limit_values[i]['limit_avg']
temp['featuredMeasure'] = current_data[i]
temp['limit'] = limit_values[i]['limit_std']
temp['step'] = i
return_value.append(temp)
return return_value
def generate_canvas_list(self, schedule_name, flow_id, *args, **kwargs):
return_value = []
self.schedule_name = schedule_name
data = self.statistics_module.schedule_data[schedule_name]
flow_sensors = self.statistics_module.sensor_names
flow_sensor_name = flow_sensors[flow_id]
conversion_rate = self.statistics_module.conversion_rate[flow_id]
flow_data = self.statistics_module.get_average_flow_data(data['step_number'], flow_sensor_name, schedule_name)
limit_values = self.statistics_module.get_flow_limit_values(data['step_number'], flow_sensor_name, schedule_name)
for i in limit_values:
try:
i['limit_avg'] = float(i['limit_avg']) * conversion_rate
i['limit_std'] = float(i['limit_std']) * conversion_rate
except:
pass
corrected_flow = []
for i in flow_data:
temp1 = []
for j in i:
temp1.append(j * conversion_rate)
corrected_flow.append(temp1)
for i in range(0, data['step_number']):
temp = {}
temp['canvasName'] = 'canvas1' + str(i + 1)
temp['titleText'] = 'Step ' + str(i + 1)
temp['qualScale1Color'] = 'Black'
temp['featuredColor'] = 'Red'
try:
temp['qualScale1'] = limit_values[i]['limit_avg']
except:
temp['qualScale1'] = 0
try:
temp['featuredMeasure'] = corrected_flow[i]
except:
temp['featuredMeasure'] = 0
try:
temp['limit'] = limit_values[i]['limit_std']
except:
temp['limit'] = 0
return_value.append(temp)
return return_value |
declerations_test_text_001 = '''
list1 = [
1,
]
'''
declerations_test_text_002 = '''
list1 = [
1,
2,
]
'''
declerations_test_text_003 = '''
tuple1 = (
1,
)
'''
declerations_test_text_004 = '''
tuple1 = (
1,
2,
)
'''
declerations_test_text_005 = '''
set1 = {
1,
}
'''
declerations_test_text_006 = '''
set1 = {
1,
2,
}
'''
declerations_test_text_007 = '''
dict1 = {
'key': 1,
}
'''
declerations_test_text_008 = '''
dict1 = {
'key1': 1,
'key2': 2,
}
'''
declerations_test_text_009 = '''
return [
1,
]
'''
declerations_test_text_010 = '''
return [
1,
2,
]
'''
declerations_test_text_011 = '''
return (
1,
)
'''
declerations_test_text_012 = '''
return (
1,
2,
)
'''
declerations_test_text_013 = '''
return {
1,
}
'''
declerations_test_text_014 = '''
return {
1,
2,
}
'''
declerations_test_text_015 = '''
return {
'key': 1,
}
'''
declerations_test_text_016 = '''
return {
'key1': 1,
'key2': 2,
}
'''
declerations_test_text_017 = '''
yield [
1,
]
'''
declerations_test_text_018 = '''
yield [
1,
2,
]
'''
declerations_test_text_019 = '''
yield (
1,
)
'''
declerations_test_text_020 = '''
yield (
1,
2,
)
'''
declerations_test_text_021 = '''
yield {
1,
}
'''
declerations_test_text_022 = '''
yield {
1,
2,
}
'''
declerations_test_text_023 = '''
yield {
'key': 1,
}
'''
declerations_test_text_024 = '''
yield {
'key1': 1,
'key2': 2,
}
'''
declerations_test_text_025 = '''
list1 = [
[
1,
],
]
'''
declerations_test_text_026 = '''
list1 = [
[
1,
2,
],
]
'''
declerations_test_text_027 = '''
tuple1 = (
(
1,
),
)
'''
declerations_test_text_028 = '''
tuple1 = (
(
1,
2,
),
)
'''
declerations_test_text_029 = '''
set1 = {
{
1,
},
}
'''
declerations_test_text_030 = '''
set1 = {
{
1,
2,
},
}
'''
declerations_test_text_031 = '''
dict1 = {
'key': {
'key': 1,
},
}
'''
declerations_test_text_032 = '''
dict1 = {
'key1': {
'key1': 1,
'key2': 2,
},
'key2': {
'key1': 1,
'key2': 2,
},
}
'''
declerations_test_text_033 = '''
return [
[
1,
],
]
'''
declerations_test_text_034 = '''
return [
[
1,
2,
],
]
'''
declerations_test_text_035 = '''
return (
(
1,
),
)
'''
declerations_test_text_036 = '''
return (
(
1,
2,
),
)
'''
declerations_test_text_037 = '''
return {
{
1,
},
}
'''
declerations_test_text_038 = '''
return {
{
1,
2,
},
}
'''
declerations_test_text_039 = '''
return {
'key': {
'key': 1,
},
}
'''
declerations_test_text_040 = '''
return {
'key1': {
'key1': 1,
'key2': 2,
},
'key2': {
'key1': 1,
'key2': 2,
},
}
'''
declerations_test_text_041 = '''
yield [
[
1,
],
]
'''
declerations_test_text_042 = '''
yield [
[
1,
2,
],
]
'''
declerations_test_text_043 = '''
yield (
(
1,
),
)
'''
declerations_test_text_044 = '''
yield (
(
1,
2,
),
)
'''
declerations_test_text_045 = '''
yield {
{
1,
},
}
'''
declerations_test_text_046 = '''
yield {
{
1,
2,
},
}
'''
declerations_test_text_047 = '''
yield {
'key': {
'key': 1,
},
}
'''
declerations_test_text_048 = '''
yield {
'key1': {
'key1': 1,
'key2': 2,
},
'key2': {
'key1': 1,
'key2': 2,
},
}
'''
declerations_test_text_049 = '''
list1 = [
[
2,
],
]
'''
declerations_test_text_050 = '''
list_1 = [
[
[
2,
],
],
]
'''
declerations_test_text_051 = '''
list_1 = [
(
2,
),
]
'''
declerations_test_text_052 = '''
list_1 = [
{
'key1': 'value1',
},
]
'''
declerations_test_text_053 = '''
list_1 = [
call(
param1,
),
]
'''
declerations_test_text_054 = '''
entry_1, entry_2 = call()
'''
declerations_test_text_055 = '''
(
entry_1,
entry_2,
) = call()
'''
declerations_test_text_056 = '''
[
1
for a, b in call()
]
'''
declerations_test_text_057 = '''
{
'key': [
'entry_1',
'entry_2',
]
}
'''
declerations_test_text_058 = '''
list_1 = [instance.attribute]
'''
declerations_test_text_059 = '''
list_1 = [1]
'''
declerations_test_text_060 = '''
list_1 = [test]
'''
declerations_test_text_061 = '''
dict_1 = {}
'''
declerations_test_text_062 = '''
list_1 = [term[1]]
'''
declerations_test_text_063 = '''
test = {
'list_of_lists': [
[],
],
}
'''
declerations_test_text_064 = '''
class ClassName:
pass
'''
declerations_test_text_065 = '''
class ClassName(
Class1,
Class2,
):
pass
'''
declerations_test_text_066 = '''
class ClassName():
pass
'''
declerations_test_text_067 = '''
class ClassName(Class1, Class2):
pass
'''
declerations_test_text_068 = '''
class ClassName(
Class1,
Class2
):
pass
'''
declerations_test_text_069 = '''
def function_name():
pass
'''
declerations_test_text_070 = '''
def function_name( ):
pass
'''
declerations_test_text_071 = '''
def function_name(
):
pass
'''
declerations_test_text_072 = '''
def function_name(
):
pass
'''
declerations_test_text_073 = '''
def function_name(
arg1,
arg2,
):
pass
'''
declerations_test_text_074 = '''
def function_name(
arg1,
arg2
):
pass
'''
declerations_test_text_075 = '''
def function_name(arg1):
pass
'''
declerations_test_text_076 = '''
def function_name(
arg1, arg2,
):
pass
'''
declerations_test_text_077 = '''
def function_name(
arg1,
arg2,
):
pass
'''
declerations_test_text_078 = '''
def function_name(
arg1,
**kwargs
):
pass
'''
declerations_test_text_079 = '''
class Class:
def function_name_two(
self,
arg1,
arg2,
):
pass
'''
declerations_test_text_080 = '''
class Class:
@property
def function_name_one(
self,
):
pass
'''
declerations_test_text_081 = '''
def function_name(
*args,
**kwargs
):
pass
'''
declerations_test_text_082 = '''
class A:
def b():
class B:
pass
'''
declerations_test_text_083 = '''
@decorator(
param=1,
)
def function_name(
param_one,
param_two,
):
pass
'''
declerations_test_text_084 = '''
class ClassA:
def function_a():
pass
class TestServerHandler(
http.server.BaseHTTPRequestHandler,
):
pass
'''
declerations_test_text_085 = '''
def function(
param_a,
param_b=[
'test',
],
):
pass
'''
declerations_test_text_086 = '''
@decorator
class DecoratedClass(
ClassBase,
):
pass
'''
declerations_test_text_087 = '''
class ClassName(
object,
):
pass
'''
declerations_test_text_088 = '''
pixel[x,y] = 10
'''
declerations_test_text_089 = '''
@decorator.one
@decorator.two()
class DecoratedClass:
pass
'''
declerations_test_text_090 = '''
@staticmethod
def static_method():
pass
'''
declerations_test_text_091 = '''
@decorator1
@decorator2
def static_method(
param1,
param2,
):
pass
'''
declerations_test_text_092 = '''
@decorator1(
param=1,
)
def method():
pass
'''
declerations_test_text_093 = '''
try:
pass
except Exception:
pass
'''
declerations_test_text_094 = '''
try:
pass
except (
Exception1,
Exception2,
):
pass
'''
declerations_test_text_095 = '''
try:
pass
except Exception as exception:
pass
'''
declerations_test_text_096 = '''
try:
pass
except (
Exception1,
Exception2,
) as exception:
pass
'''
declerations_test_text_097 = '''
try:
pass
except Exception as e:
pass
'''
declerations_test_text_098 = '''
try:
pass
except (
Exception1,
Exception2,
) as e:
pass
'''
declerations_test_text_099 = '''
dict1 = {
'key_one': 1, 'key_two': 2,
}
'''
declerations_test_text_100 = '''
dict1 = {
'key_one': 1,
'key_two': 2,
}
'''
declerations_test_text_101 = '''
dict1 = {
'key_one': 1,
'key_two': 2,
}
'''
declerations_test_text_102 = '''
dict1 = {
'key_one':
1,
}
'''
declerations_test_text_103 = '''
dict_one = {
'list_comp': [
{
'key_one': 'value',
}
for i in range(5)
],
'dict_comp': {
'key_one': i
for i in range(5)
},
'set_comp': {
i
for i in range(5)
},
'generator_comp': (
i
for i in range(5)
),
}
'''
declerations_test_text_104 = '''
dict_one = {
'text_key': 'value',
f'formatted_text_key': 'value',
name_key: 'value',
1: 'value',
dictionary['name']: 'value',
object.attribute: 'value',
}
dict_two = {
'key_text_multiline': \'\'\'
text
\'\'\',
1: 'text',
function(
param=1,
): 'text',
'text'.format(
param=1,
): 'text',
'long_text': (
'first line'
'second line'
),
**other_dict,
}
'''
declerations_test_text_105 = '''
async def function(
param1,
):
pass
'''
declerations_test_text_106 = '''
def no_args_function():
pass
def no_args_function() :
pass
def no_args_function ():
pass
def no_args_function( ):
pass
def no_args_function():
pass
def no_args_function() -> None:
pass
def no_args_function() -> None :
pass
def no_args_function () -> None:
pass
def no_args_function( ) -> None:
pass
def no_args_function() -> None:
pass
'''
declerations_test_text_107 = '''
class Class:
@decorator(
param=1,
)
async def function():
pass
'''
declerations_test_text_108 = '''
list_a = [
\'\'\'
multiline
string
\'\'\',
\'\'\'
multiline
string
\'\'\',
]
'''
declerations_test_text_109 = '''
list_with_empty_tuple = [
(),
]
'''
| declerations_test_text_001 = '\nlist1 = [\n 1,\n]\n'
declerations_test_text_002 = '\nlist1 = [\n 1,\n 2,\n]\n'
declerations_test_text_003 = '\ntuple1 = (\n 1,\n)\n'
declerations_test_text_004 = '\ntuple1 = (\n 1,\n 2,\n)\n'
declerations_test_text_005 = '\nset1 = {\n 1,\n}\n'
declerations_test_text_006 = '\nset1 = {\n 1,\n 2,\n}\n'
declerations_test_text_007 = "\ndict1 = {\n 'key': 1,\n}\n"
declerations_test_text_008 = "\ndict1 = {\n 'key1': 1,\n 'key2': 2,\n}\n"
declerations_test_text_009 = '\nreturn [\n 1,\n]\n'
declerations_test_text_010 = '\nreturn [\n 1,\n 2,\n]\n'
declerations_test_text_011 = '\nreturn (\n 1,\n)\n'
declerations_test_text_012 = '\nreturn (\n 1,\n 2,\n)\n'
declerations_test_text_013 = '\nreturn {\n 1,\n}\n'
declerations_test_text_014 = '\nreturn {\n 1,\n 2,\n}\n'
declerations_test_text_015 = "\nreturn {\n 'key': 1,\n}\n"
declerations_test_text_016 = "\nreturn {\n 'key1': 1,\n 'key2': 2,\n}\n"
declerations_test_text_017 = '\nyield [\n 1,\n]\n'
declerations_test_text_018 = '\nyield [\n 1,\n 2,\n]\n'
declerations_test_text_019 = '\nyield (\n 1,\n)\n'
declerations_test_text_020 = '\nyield (\n 1,\n 2,\n)\n'
declerations_test_text_021 = '\nyield {\n 1,\n}\n'
declerations_test_text_022 = '\nyield {\n 1,\n 2,\n}\n'
declerations_test_text_023 = "\nyield {\n 'key': 1,\n}\n"
declerations_test_text_024 = "\nyield {\n 'key1': 1,\n 'key2': 2,\n}\n"
declerations_test_text_025 = '\nlist1 = [\n [\n 1,\n ],\n]\n'
declerations_test_text_026 = '\nlist1 = [\n [\n 1,\n 2,\n ],\n]\n'
declerations_test_text_027 = '\ntuple1 = (\n (\n 1,\n ),\n)\n'
declerations_test_text_028 = '\ntuple1 = (\n (\n 1,\n 2,\n ),\n)\n'
declerations_test_text_029 = '\nset1 = {\n {\n 1,\n },\n}\n'
declerations_test_text_030 = '\nset1 = {\n {\n 1,\n 2,\n },\n}\n'
declerations_test_text_031 = "\ndict1 = {\n 'key': {\n 'key': 1,\n },\n}\n"
declerations_test_text_032 = "\ndict1 = {\n 'key1': {\n 'key1': 1,\n 'key2': 2,\n },\n 'key2': {\n 'key1': 1,\n 'key2': 2,\n },\n}\n"
declerations_test_text_033 = '\nreturn [\n [\n 1,\n ],\n]\n'
declerations_test_text_034 = '\nreturn [\n [\n 1,\n 2,\n ],\n]\n'
declerations_test_text_035 = '\nreturn (\n (\n 1,\n ),\n)\n'
declerations_test_text_036 = '\nreturn (\n (\n 1,\n 2,\n ),\n)\n'
declerations_test_text_037 = '\nreturn {\n {\n 1,\n },\n}\n'
declerations_test_text_038 = '\nreturn {\n {\n 1,\n 2,\n },\n}\n'
declerations_test_text_039 = "\nreturn {\n 'key': {\n 'key': 1,\n },\n}\n"
declerations_test_text_040 = "\nreturn {\n 'key1': {\n 'key1': 1,\n 'key2': 2,\n },\n 'key2': {\n 'key1': 1,\n 'key2': 2,\n },\n}\n"
declerations_test_text_041 = '\nyield [\n [\n 1,\n ],\n]\n'
declerations_test_text_042 = '\nyield [\n [\n 1,\n 2,\n ],\n]\n'
declerations_test_text_043 = '\nyield (\n (\n 1,\n ),\n)\n'
declerations_test_text_044 = '\nyield (\n (\n 1,\n 2,\n ),\n)\n'
declerations_test_text_045 = '\nyield {\n {\n 1,\n },\n}\n'
declerations_test_text_046 = '\nyield {\n {\n 1,\n 2,\n },\n}\n'
declerations_test_text_047 = "\nyield {\n 'key': {\n 'key': 1,\n },\n}\n"
declerations_test_text_048 = "\nyield {\n 'key1': {\n 'key1': 1,\n 'key2': 2,\n },\n 'key2': {\n 'key1': 1,\n 'key2': 2,\n },\n}\n"
declerations_test_text_049 = '\nlist1 = [\n [\n 2,\n ],\n]\n'
declerations_test_text_050 = '\nlist_1 = [\n [\n [\n 2,\n ],\n ],\n]\n'
declerations_test_text_051 = '\nlist_1 = [\n (\n 2,\n ),\n]\n'
declerations_test_text_052 = "\nlist_1 = [\n {\n 'key1': 'value1',\n },\n]\n"
declerations_test_text_053 = '\nlist_1 = [\n call(\n param1,\n ),\n]\n'
declerations_test_text_054 = '\nentry_1, entry_2 = call()\n'
declerations_test_text_055 = '\n(\n entry_1,\n entry_2,\n) = call()\n'
declerations_test_text_056 = '\n[\n 1\n for a, b in call()\n]\n'
declerations_test_text_057 = "\n{\n 'key': [\n 'entry_1',\n 'entry_2',\n ]\n}\n"
declerations_test_text_058 = '\nlist_1 = [instance.attribute]\n'
declerations_test_text_059 = '\nlist_1 = [1]\n'
declerations_test_text_060 = '\nlist_1 = [test]\n'
declerations_test_text_061 = '\ndict_1 = {}\n'
declerations_test_text_062 = '\nlist_1 = [term[1]]\n'
declerations_test_text_063 = "\ntest = {\n 'list_of_lists': [\n [],\n ],\n}\n"
declerations_test_text_064 = '\nclass ClassName:\n pass\n'
declerations_test_text_065 = '\nclass ClassName(\n Class1,\n Class2,\n):\n pass\n'
declerations_test_text_066 = '\nclass ClassName():\n pass\n'
declerations_test_text_067 = '\nclass ClassName(Class1, Class2):\n pass\n'
declerations_test_text_068 = '\nclass ClassName(\n Class1,\n Class2\n):\n pass\n'
declerations_test_text_069 = '\ndef function_name():\n pass\n'
declerations_test_text_070 = '\ndef function_name( ):\n pass\n'
declerations_test_text_071 = '\ndef function_name(\n):\n pass\n'
declerations_test_text_072 = '\ndef function_name(\n\n):\n pass\n'
declerations_test_text_073 = '\ndef function_name(\n arg1,\n arg2,\n):\n pass\n'
declerations_test_text_074 = '\ndef function_name(\n arg1,\n arg2\n):\n pass\n'
declerations_test_text_075 = '\ndef function_name(arg1):\n pass\n'
declerations_test_text_076 = '\ndef function_name(\n arg1, arg2,\n):\n pass\n'
declerations_test_text_077 = '\ndef function_name(\n arg1,\n arg2,\n):\n pass\n'
declerations_test_text_078 = '\ndef function_name(\n arg1,\n **kwargs\n):\n pass\n'
declerations_test_text_079 = '\nclass Class:\n def function_name_two(\n self,\n arg1,\n arg2,\n ):\n pass\n'
declerations_test_text_080 = '\nclass Class:\n @property\n def function_name_one(\n self,\n ):\n pass\n'
declerations_test_text_081 = '\ndef function_name(\n *args,\n **kwargs\n):\n pass\n'
declerations_test_text_082 = '\nclass A:\n def b():\n class B:\n pass\n'
declerations_test_text_083 = '\n@decorator(\n param=1,\n)\ndef function_name(\n param_one,\n param_two,\n):\n pass\n'
declerations_test_text_084 = '\nclass ClassA:\n def function_a():\n pass\n\n class TestServerHandler(\n http.server.BaseHTTPRequestHandler,\n ):\n pass\n'
declerations_test_text_085 = "\ndef function(\n param_a,\n param_b=[\n 'test',\n ],\n):\n pass\n"
declerations_test_text_086 = '\n@decorator\nclass DecoratedClass(\n ClassBase,\n):\n pass\n'
declerations_test_text_087 = '\nclass ClassName(\n object,\n):\n pass\n'
declerations_test_text_088 = '\npixel[x,y] = 10\n'
declerations_test_text_089 = '\n@decorator.one\n@decorator.two()\nclass DecoratedClass:\n pass\n'
declerations_test_text_090 = '\n@staticmethod\ndef static_method():\n pass\n'
declerations_test_text_091 = '\n@decorator1\n@decorator2\ndef static_method(\n param1,\n param2,\n):\n pass\n'
declerations_test_text_092 = '\n@decorator1(\n param=1,\n)\ndef method():\n pass\n'
declerations_test_text_093 = '\ntry:\n pass\nexcept Exception:\n pass\n'
declerations_test_text_094 = '\ntry:\n pass\nexcept (\n Exception1,\n Exception2,\n):\n pass\n'
declerations_test_text_095 = '\ntry:\n pass\nexcept Exception as exception:\n pass\n'
declerations_test_text_096 = '\ntry:\n pass\nexcept (\n Exception1,\n Exception2,\n) as exception:\n pass\n'
declerations_test_text_097 = '\ntry:\n pass\nexcept Exception as e:\n pass\n'
declerations_test_text_098 = '\ntry:\n pass\nexcept (\n Exception1,\n Exception2,\n) as e:\n pass\n'
declerations_test_text_099 = "\ndict1 = {\n 'key_one': 1, 'key_two': 2,\n}\n"
declerations_test_text_100 = "\ndict1 = {\n 'key_one': 1,\n 'key_two': 2,\n}\n"
declerations_test_text_101 = "\ndict1 = {\n 'key_one': 1,\n 'key_two': 2,\n}\n"
declerations_test_text_102 = "\ndict1 = {\n 'key_one':\n 1,\n}\n"
declerations_test_text_103 = "\ndict_one = {\n 'list_comp': [\n {\n 'key_one': 'value',\n }\n for i in range(5)\n ],\n 'dict_comp': {\n 'key_one': i\n for i in range(5)\n },\n 'set_comp': {\n i\n for i in range(5)\n },\n 'generator_comp': (\n i\n for i in range(5)\n ),\n}\n"
declerations_test_text_104 = "\ndict_one = {\n 'text_key': 'value',\n f'formatted_text_key': 'value',\n name_key: 'value',\n 1: 'value',\n dictionary['name']: 'value',\n object.attribute: 'value',\n}\ndict_two = {\n 'key_text_multiline': '''\n text\n ''',\n 1: 'text',\n function(\n param=1,\n ): 'text',\n 'text'.format(\n param=1,\n ): 'text',\n 'long_text': (\n 'first line'\n 'second line'\n ),\n **other_dict,\n}\n"
declerations_test_text_105 = '\nasync def function(\n param1,\n\n):\n pass\n'
declerations_test_text_106 = '\ndef no_args_function():\n pass\ndef no_args_function() :\n pass\ndef no_args_function ():\n pass\ndef no_args_function( ):\n pass\ndef no_args_function():\n pass\n\ndef no_args_function() -> None:\n pass\ndef no_args_function() -> None :\n pass\ndef no_args_function () -> None:\n pass\ndef no_args_function( ) -> None:\n pass\ndef no_args_function() -> None:\n pass\n'
declerations_test_text_107 = '\nclass Class:\n @decorator(\n param=1,\n )\n async def function():\n pass\n'
declerations_test_text_108 = "\nlist_a = [\n '''\n multiline\n string\n ''',\n '''\n multiline\n string\n ''',\n]\n"
declerations_test_text_109 = '\nlist_with_empty_tuple = [\n (),\n]\n' |
"""Build rules to create C++ code from an Antlr4 grammar."""
def antlr4_cc_lexer(name, src, namespaces = None, imports = None, deps = None, lib_import = None):
"""Generates the C++ source corresponding to an antlr4 lexer definition.
Args:
name: The name of the package to use for the cc_library.
src: The antlr4 g4 file containing the lexer rules.
namespaces: The namespace used by the generated files. Uses an array to
support nested namespaces. Defaults to [name].
imports: A list of antlr4 source imports to use when building the lexer.
deps: Dependencies for the generated code.
lib_import: Optional target for importing grammar and token files.
"""
namespaces = namespaces or [name]
imports = imports or []
deps = deps or []
if not src.endswith(".g4"):
fail("Grammar must end with .g4", "src")
if (any([not imp.endswith(".g4") for imp in imports])):
fail("Imported files must be Antlr4 grammar ending with .g4", "imports")
file_prefix = src[:-3]
base_file_prefix = _strip_end(file_prefix, "Lexer")
out_files = [
"%sLexer.h" % base_file_prefix,
"%sLexer.cpp" % base_file_prefix,
]
native.java_binary(
name = "antlr_tool",
jvm_flags = ["-Xmx256m"],
main_class = "org.antlr.v4.Tool",
runtime_deps = ["@maven//:org_antlr_antlr4_4_7_1"],
)
command = ";\n".join([
# Use the first namespace, we'll add the others afterwards.
_make_tool_invocation_command(namespaces[0], lib_import),
_make_namespace_adjustment_command(namespaces, out_files),
])
native.genrule(
name = name + "_source",
srcs = [src] + imports,
outs = out_files,
cmd = command,
heuristic_label_expansion = 0,
tools = ["antlr_tool"],
)
native.cc_library(
name = name,
srcs = [f for f in out_files if f.endswith(".cpp")],
hdrs = [f for f in out_files if f.endswith(".h")],
deps = ["@antlr_cc_runtime//:antlr4_runtime"] + deps,
copts = [
"-fexceptions",
],
features = ["-use_header_modules"], # Incompatible with -fexceptions.
)
def antlr4_cc_parser(
name,
src,
namespaces = None,
token_vocab = None,
imports = None,
listener = True,
visitor = False,
deps = None,
lib_import = None):
"""Generates the C++ source corresponding to an antlr4 parser definition.
Args:
name: The name of the package to use for the cc_library.
src: The antlr4 g4 file containing the parser rules.
namespaces: The namespace used by the generated files. Uses an array to
support nested namespaces. Defaults to [name].
token_vocab: The antlr g4 file containing the lexer tokens.
imports: A list of antlr4 source imports to use when building the parser.
listener: Whether or not to include listener generated files.
visitor: Whether or not to include visitor generated files.
deps: Dependencies for the generated code.
lib_import: Optional target for importing grammar and token files.
"""
suffixes = ()
if listener:
suffixes += (
"%sBaseListener.cpp",
"%sListener.cpp",
"%sBaseListener.h",
"%sListener.h",
)
if visitor:
suffixes += (
"%sBaseVisitor.cpp",
"%sVisitor.cpp",
"%sBaseVisitor.h",
"%sVisitor.h",
)
namespaces = namespaces or [name]
imports = imports or []
deps = deps or []
if not src.endswith(".g4"):
fail("Grammar must end with .g4", "src")
if token_vocab != None and not token_vocab.endswith(".g4"):
fail("Token Vocabulary must end with .g4", "token_vocab")
if (any([not imp.endswith(".g4") for imp in imports])):
fail("Imported files must be Antlr4 grammar ending with .g4", "imports")
file_prefix = src[:-3]
base_file_prefix = _strip_end(file_prefix, "Parser")
out_files = [
"%sParser.h" % base_file_prefix,
"%sParser.cpp" % base_file_prefix,
] + _make_outs(file_prefix, suffixes)
if token_vocab:
imports.append(token_vocab)
command = ";\n".join([
# Use the first namespace, we'll add the others afterwardsm thi .
_make_tool_invocation_command(namespaces[0], lib_import, listener, visitor),
_make_namespace_adjustment_command(namespaces, out_files),
])
native.genrule(
name = name + "_source",
srcs = [src] + imports,
outs = out_files,
cmd = command,
heuristic_label_expansion = 0,
tools = [
":antlr_tool",
],
)
native.cc_library(
name = name,
srcs = [f for f in out_files if f.endswith(".cpp")],
hdrs = [f for f in out_files if f.endswith(".h")],
deps = ["@antlr_cc_runtime//:antlr4_runtime"] + deps,
copts = [
"-fexceptions",
# FIXME: antlr generates broken C++ code that attempts to construct
# a std::string from nullptr. It's not clear whether the relevant
# constructs are reachable.
"-Wno-nonnull",
],
features = ["-use_header_modules"], # Incompatible with -fexceptions.
)
def _make_outs(file_prefix, suffixes):
return [file_suffix % file_prefix for file_suffix in suffixes]
def _strip_end(text, suffix):
if not text.endswith(suffix):
return text
return text[:len(text) - len(suffix)]
def _to_c_macro_name(filename):
# Convert the filenames to a format suitable for C preprocessor definitions.
char_list = [filename[i].upper() for i in range(len(filename))]
return "ANTLR4_GEN_" + "".join(
[a if (("A" <= a) and (a <= "Z")) else "_" for a in char_list],
)
def _make_tool_invocation_command(package, lib_import, listener = False, visitor = False):
return "$(location :antlr_tool) " + \
"$(SRCS)" + \
(" -visitor" if visitor else " -no-visitor") + \
(" -listener" if listener else " -no-listener") + \
(" -lib $$(dirname $(location " + lib_import + "))" if lib_import else "") + \
" -Dlanguage=Cpp" + \
" -package " + package + \
" -o $(@D)" + \
" -Xexact-output-dir"
def _make_namespace_adjustment_command(namespaces, out_files):
if len(namespaces) == 1:
return "true"
commands = []
extra_header_namespaces = "\\\n".join(["namespace %s {" % namespace for namespace in namespaces[1:]])
for filepath in out_files:
if filepath.endswith(".h"):
commands.append("sed -i '/namespace %s {/ a%s' $(@D)/%s" % (namespaces[0], extra_header_namespaces, filepath))
for namespace in namespaces[1:]:
commands.append("sed -i '/} \/\/ namespace %s/i} \/\/ namespace %s' $(@D)/%s" % (namespaces[0], namespace, filepath))
else:
commands.append("sed -i 's/using namespace %s;/using namespace %s;/' $(@D)/%s" % (namespaces[0], "::".join(namespaces), filepath))
return ";\n".join(commands)
| """Build rules to create C++ code from an Antlr4 grammar."""
def antlr4_cc_lexer(name, src, namespaces=None, imports=None, deps=None, lib_import=None):
"""Generates the C++ source corresponding to an antlr4 lexer definition.
Args:
name: The name of the package to use for the cc_library.
src: The antlr4 g4 file containing the lexer rules.
namespaces: The namespace used by the generated files. Uses an array to
support nested namespaces. Defaults to [name].
imports: A list of antlr4 source imports to use when building the lexer.
deps: Dependencies for the generated code.
lib_import: Optional target for importing grammar and token files.
"""
namespaces = namespaces or [name]
imports = imports or []
deps = deps or []
if not src.endswith('.g4'):
fail('Grammar must end with .g4', 'src')
if any([not imp.endswith('.g4') for imp in imports]):
fail('Imported files must be Antlr4 grammar ending with .g4', 'imports')
file_prefix = src[:-3]
base_file_prefix = _strip_end(file_prefix, 'Lexer')
out_files = ['%sLexer.h' % base_file_prefix, '%sLexer.cpp' % base_file_prefix]
native.java_binary(name='antlr_tool', jvm_flags=['-Xmx256m'], main_class='org.antlr.v4.Tool', runtime_deps=['@maven//:org_antlr_antlr4_4_7_1'])
command = ';\n'.join([_make_tool_invocation_command(namespaces[0], lib_import), _make_namespace_adjustment_command(namespaces, out_files)])
native.genrule(name=name + '_source', srcs=[src] + imports, outs=out_files, cmd=command, heuristic_label_expansion=0, tools=['antlr_tool'])
native.cc_library(name=name, srcs=[f for f in out_files if f.endswith('.cpp')], hdrs=[f for f in out_files if f.endswith('.h')], deps=['@antlr_cc_runtime//:antlr4_runtime'] + deps, copts=['-fexceptions'], features=['-use_header_modules'])
def antlr4_cc_parser(name, src, namespaces=None, token_vocab=None, imports=None, listener=True, visitor=False, deps=None, lib_import=None):
"""Generates the C++ source corresponding to an antlr4 parser definition.
Args:
name: The name of the package to use for the cc_library.
src: The antlr4 g4 file containing the parser rules.
namespaces: The namespace used by the generated files. Uses an array to
support nested namespaces. Defaults to [name].
token_vocab: The antlr g4 file containing the lexer tokens.
imports: A list of antlr4 source imports to use when building the parser.
listener: Whether or not to include listener generated files.
visitor: Whether or not to include visitor generated files.
deps: Dependencies for the generated code.
lib_import: Optional target for importing grammar and token files.
"""
suffixes = ()
if listener:
suffixes += ('%sBaseListener.cpp', '%sListener.cpp', '%sBaseListener.h', '%sListener.h')
if visitor:
suffixes += ('%sBaseVisitor.cpp', '%sVisitor.cpp', '%sBaseVisitor.h', '%sVisitor.h')
namespaces = namespaces or [name]
imports = imports or []
deps = deps or []
if not src.endswith('.g4'):
fail('Grammar must end with .g4', 'src')
if token_vocab != None and (not token_vocab.endswith('.g4')):
fail('Token Vocabulary must end with .g4', 'token_vocab')
if any([not imp.endswith('.g4') for imp in imports]):
fail('Imported files must be Antlr4 grammar ending with .g4', 'imports')
file_prefix = src[:-3]
base_file_prefix = _strip_end(file_prefix, 'Parser')
out_files = ['%sParser.h' % base_file_prefix, '%sParser.cpp' % base_file_prefix] + _make_outs(file_prefix, suffixes)
if token_vocab:
imports.append(token_vocab)
command = ';\n'.join([_make_tool_invocation_command(namespaces[0], lib_import, listener, visitor), _make_namespace_adjustment_command(namespaces, out_files)])
native.genrule(name=name + '_source', srcs=[src] + imports, outs=out_files, cmd=command, heuristic_label_expansion=0, tools=[':antlr_tool'])
native.cc_library(name=name, srcs=[f for f in out_files if f.endswith('.cpp')], hdrs=[f for f in out_files if f.endswith('.h')], deps=['@antlr_cc_runtime//:antlr4_runtime'] + deps, copts=['-fexceptions', '-Wno-nonnull'], features=['-use_header_modules'])
def _make_outs(file_prefix, suffixes):
return [file_suffix % file_prefix for file_suffix in suffixes]
def _strip_end(text, suffix):
if not text.endswith(suffix):
return text
return text[:len(text) - len(suffix)]
def _to_c_macro_name(filename):
char_list = [filename[i].upper() for i in range(len(filename))]
return 'ANTLR4_GEN_' + ''.join([a if 'A' <= a and a <= 'Z' else '_' for a in char_list])
def _make_tool_invocation_command(package, lib_import, listener=False, visitor=False):
return '$(location :antlr_tool) ' + '$(SRCS)' + (' -visitor' if visitor else ' -no-visitor') + (' -listener' if listener else ' -no-listener') + (' -lib $$(dirname $(location ' + lib_import + '))' if lib_import else '') + ' -Dlanguage=Cpp' + ' -package ' + package + ' -o $(@D)' + ' -Xexact-output-dir'
def _make_namespace_adjustment_command(namespaces, out_files):
if len(namespaces) == 1:
return 'true'
commands = []
extra_header_namespaces = '\\\n'.join(['namespace %s {' % namespace for namespace in namespaces[1:]])
for filepath in out_files:
if filepath.endswith('.h'):
commands.append("sed -i '/namespace %s {/ a%s' $(@D)/%s" % (namespaces[0], extra_header_namespaces, filepath))
for namespace in namespaces[1:]:
commands.append("sed -i '/} \\/\\/ namespace %s/i} \\/\\/ namespace %s' $(@D)/%s" % (namespaces[0], namespace, filepath))
else:
commands.append("sed -i 's/using namespace %s;/using namespace %s;/' $(@D)/%s" % (namespaces[0], '::'.join(namespaces), filepath))
return ';\n'.join(commands) |
class AnimationException(SystemException,ISerializable,_Exception):
""" The exception that is thrown when an error occurs while animating a property. """
def add_SerializeObjectState(self,*args):
""" add_SerializeObjectState(self: Exception,value: EventHandler[SafeSerializationEventArgs]) """
pass
def remove_SerializeObjectState(self,*args):
""" remove_SerializeObjectState(self: Exception,value: EventHandler[SafeSerializationEventArgs]) """
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
def __reduce_ex__(self,*args):
pass
def __str__(self,*args):
pass
Clock=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the clock that generates the animated values.
Get: Clock(self: AnimationException) -> AnimationClock
"""
Property=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the animated dependency property.
Get: Property(self: AnimationException) -> DependencyProperty
"""
Target=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the animated object.
Get: Target(self: AnimationException) -> IAnimatable
"""
| class Animationexception(SystemException, ISerializable, _Exception):
""" The exception that is thrown when an error occurs while animating a property. """
def add__serialize_object_state(self, *args):
""" add_SerializeObjectState(self: Exception,value: EventHandler[SafeSerializationEventArgs]) """
pass
def remove__serialize_object_state(self, *args):
""" remove_SerializeObjectState(self: Exception,value: EventHandler[SafeSerializationEventArgs]) """
pass
def __init__(self, *args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
def __reduce_ex__(self, *args):
pass
def __str__(self, *args):
pass
clock = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Gets the clock that generates the animated values.\n\n\n\nGet: Clock(self: AnimationException) -> AnimationClock\n\n\n\n'
property = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Gets the animated dependency property.\n\n\n\nGet: Property(self: AnimationException) -> DependencyProperty\n\n\n\n'
target = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Gets the animated object.\n\n\n\nGet: Target(self: AnimationException) -> IAnimatable\n\n\n\n' |
file_berita = open("berita.txt", "r")
berita = file_berita.read()
berita = berita.split()
berita = [x.lower() for x in berita]
berita = list(set(berita))
berita = sorted(berita)
print (berita) | file_berita = open('berita.txt', 'r')
berita = file_berita.read()
berita = berita.split()
berita = [x.lower() for x in berita]
berita = list(set(berita))
berita = sorted(berita)
print(berita) |
"""
@Fire
https://github.com/fire717
"""
cfg = {
##### Global Setting
'GPU_ID': '0',
"num_workers":8,
"random_seed":42,
"cfg_verbose":True,
"save_dir": "output/",
"num_classes": 17,
"width_mult":1.0,
"img_size": 192,
##### Train Setting
'img_path':"./data/croped/imgs",
'train_label_path':'./data/croped/train2017.json',
'val_label_path':'./data/croped/val2017.json',
'balance_data':False,
'log_interval':10,
'save_best_only': True,
'pin_memory': True,
##### Train Hyperparameters
'learning_rate':0.001,#1.25e-4
'batch_size':64,
'epochs':120,
'optimizer':'Adam', #Adam SGD
'scheduler':'MultiStepLR-70,100-0.1', #default SGDR-5-2 CVPR step-4-0.8 MultiStepLR
'weight_decay' : 5.e-4,#0.0001,
'class_weight': None,#[1., 1., 1., 1., 1., 1., 1., ]
'clip_gradient': 5,#1,
##### Test
'test_img_path':"./data/croped/imgs",
#"../data/eval/imgs",
#"../data/eval/imgs",
#"../data/all/imgs"
#"../data/true/mypc/crop_upper1"
#../data/coco/small_dataset/imgs
#"../data/testimg"
'exam_label_path':'../data/all/data_all_new.json',
'eval_img_path':'../data/eval/imgs',
'eval_label_path':'../data/eval/mypc.json',
}
| """
@Fire
https://github.com/fire717
"""
cfg = {'GPU_ID': '0', 'num_workers': 8, 'random_seed': 42, 'cfg_verbose': True, 'save_dir': 'output/', 'num_classes': 17, 'width_mult': 1.0, 'img_size': 192, 'img_path': './data/croped/imgs', 'train_label_path': './data/croped/train2017.json', 'val_label_path': './data/croped/val2017.json', 'balance_data': False, 'log_interval': 10, 'save_best_only': True, 'pin_memory': True, 'learning_rate': 0.001, 'batch_size': 64, 'epochs': 120, 'optimizer': 'Adam', 'scheduler': 'MultiStepLR-70,100-0.1', 'weight_decay': 0.0005, 'class_weight': None, 'clip_gradient': 5, 'test_img_path': './data/croped/imgs', 'exam_label_path': '../data/all/data_all_new.json', 'eval_img_path': '../data/eval/imgs', 'eval_label_path': '../data/eval/mypc.json'} |
rzymskie={'I':1,'II':2,'III':3,'IV':4,'V':5,'VI':6,'VII':7,'VIII':8}
print(rzymskie)
print('Jeden element slownika: \n')
print(rzymskie['I'])
| rzymskie = {'I': 1, 'II': 2, 'III': 3, 'IV': 4, 'V': 5, 'VI': 6, 'VII': 7, 'VIII': 8}
print(rzymskie)
print('Jeden element slownika: \n')
print(rzymskie['I']) |
H, W = map(int, input().split())
A = [input() for _ in range(H)]
if H + W - 1 == sum(a.count('#') for a in A):
print('Possible')
else:
print('Impossible')
| (h, w) = map(int, input().split())
a = [input() for _ in range(H)]
if H + W - 1 == sum((a.count('#') for a in A)):
print('Possible')
else:
print('Impossible') |
"""
Get an Etree library. Usage::
>>> from anyetree import etree
Returns some etree library. Looks for (in order of decreasing preference):
* ``lxml.etree`` (http://cheeseshop.python.org/pypi/lxml/)
* ``xml.etree.cElementTree`` (built into Python 2.5)
* ``cElementTree`` (http://effbot.org/zone/celementtree.htm)
* ``xml.etree.ElementTree`` (built into Python 2.5)
* ``elementree.ElementTree (http://effbot.org/zone/element-index.htm)
"""
__all__ = ['etree']
SEARCH_PATHS = [
"lxml.etree",
"xml.etree.cElementTree",
"cElementTree",
"xml.etree.ElementTree",
"elementtree.ElementTree",
]
etree = None
for name in SEARCH_PATHS:
try:
etree = __import__(name, '', '', [''])
break
except ImportError:
continue
if etree is None:
raise ImportError("No suitable ElementTree implementation found.") | """
Get an Etree library. Usage::
>>> from anyetree import etree
Returns some etree library. Looks for (in order of decreasing preference):
* ``lxml.etree`` (http://cheeseshop.python.org/pypi/lxml/)
* ``xml.etree.cElementTree`` (built into Python 2.5)
* ``cElementTree`` (http://effbot.org/zone/celementtree.htm)
* ``xml.etree.ElementTree`` (built into Python 2.5)
* ``elementree.ElementTree (http://effbot.org/zone/element-index.htm)
"""
__all__ = ['etree']
search_paths = ['lxml.etree', 'xml.etree.cElementTree', 'cElementTree', 'xml.etree.ElementTree', 'elementtree.ElementTree']
etree = None
for name in SEARCH_PATHS:
try:
etree = __import__(name, '', '', [''])
break
except ImportError:
continue
if etree is None:
raise import_error('No suitable ElementTree implementation found.') |
# File: etl.py
# Purpose: To do the `Transform` step of an Extract-Transform-Load.
# Programmer: Amal Shehu
# Course: Exercism
# Date: Thursday 22 September 2016, 03:40 PM
def transform(words):
new_words = dict()
for point, letters in words.items():
for letter in letters:
new_words[letter.lower()] = point
return new_words
| def transform(words):
new_words = dict()
for (point, letters) in words.items():
for letter in letters:
new_words[letter.lower()] = point
return new_words |
def have(subj, obj):
subj.add(obj)
def change(subj, obj, state):
pass
if __name__ == '__main__':
main() | def have(subj, obj):
subj.add(obj)
def change(subj, obj, state):
pass
if __name__ == '__main__':
main() |
# A bot that picks the first action from the list for the first two rounds,
# and then exists with an exception.
# Used only for tests.
game_name = input()
play_as = int(input())
print("ready")
while True:
print("start")
num_actions = 0
while True:
message = input()
if message == "tournament over":
print("tournament over")
sys.exit(0)
if message.startswith("match over"):
print("match over")
break
public_buf, private_buf, *legal_actions = message.split(" ")
should_act = len(legal_actions) > 0
if should_act:
num_actions += 1
print(legal_actions[-1])
else:
print("ponder")
if num_actions > 2:
raise RuntimeError
| game_name = input()
play_as = int(input())
print('ready')
while True:
print('start')
num_actions = 0
while True:
message = input()
if message == 'tournament over':
print('tournament over')
sys.exit(0)
if message.startswith('match over'):
print('match over')
break
(public_buf, private_buf, *legal_actions) = message.split(' ')
should_act = len(legal_actions) > 0
if should_act:
num_actions += 1
print(legal_actions[-1])
else:
print('ponder')
if num_actions > 2:
raise RuntimeError |
'''
f we want to add a single element to an existing set, we can use the .add() operation.
It adds the element to the set and returns 'None'.
Example
>>> s = set('HackerRank')
>>> s.add('H')
>>> print s
set(['a', 'c', 'e', 'H', 'k', 'n', 'r', 'R'])
>>> print s.add('HackerRank')
None
>>> print s
set(['a', 'c', 'e', 'HackerRank', 'H', 'k', 'n', 'r', 'R'])
The first line contains an integer N, the total number of country stamps.
The next N lines contains the name of the country where the stamp is from.
Output Format
Output the total number of distinct country stamps on a single line.
'''
n = int(input())
countries = set()
for i in range(n):
countries.add(input())
print(len(countries))
| """
f we want to add a single element to an existing set, we can use the .add() operation.
It adds the element to the set and returns 'None'.
Example
>>> s = set('HackerRank')
>>> s.add('H')
>>> print s
set(['a', 'c', 'e', 'H', 'k', 'n', 'r', 'R'])
>>> print s.add('HackerRank')
None
>>> print s
set(['a', 'c', 'e', 'HackerRank', 'H', 'k', 'n', 'r', 'R'])
The first line contains an integer N, the total number of country stamps.
The next N lines contains the name of the country where the stamp is from.
Output Format
Output the total number of distinct country stamps on a single line.
"""
n = int(input())
countries = set()
for i in range(n):
countries.add(input())
print(len(countries)) |
class LeagueGame:
def __init__(self, data):
self.patch = data['patch']
self.win = data['win']
self.side = data['side']
self.opp = data['opp']
self.bans = data['bans']
self.vs_bans = data['vs_bans']
self.picks = data['picks']
self.vs_picks = data['vs_picks']
self.players = data['players']
class LeaguePlayer:
def __init__(self, n_games, n_wins, data):
self.n_games = n_games
self.n_wins = n_wins
self.K = data['K']
self.D = data['D']
self.A = data['A']
self.CS = data['CS']
self.CSM = data['CSM']
self.G = data['G']
self.GM = data['GM']
self.KPAR = data['KPAR']
self.KS = data['KS']
self.GS = data['GS']
class LeagueTeam:
def __init__(self, players, data):
self.players = players
self.region = data['region']
self.season = data['season']
self.WL = data['WL']
self.avg_gm_dur = data['avg_gm_dur']
self.most_banned_by = data['most_banned_by']
self.most_banned_vs = data['most_banned_vs']
self.economy = data['economy']
self.aggression = data['aggression']
self.objectives = data['objectives']
self.vision = data['vision']
| class Leaguegame:
def __init__(self, data):
self.patch = data['patch']
self.win = data['win']
self.side = data['side']
self.opp = data['opp']
self.bans = data['bans']
self.vs_bans = data['vs_bans']
self.picks = data['picks']
self.vs_picks = data['vs_picks']
self.players = data['players']
class Leagueplayer:
def __init__(self, n_games, n_wins, data):
self.n_games = n_games
self.n_wins = n_wins
self.K = data['K']
self.D = data['D']
self.A = data['A']
self.CS = data['CS']
self.CSM = data['CSM']
self.G = data['G']
self.GM = data['GM']
self.KPAR = data['KPAR']
self.KS = data['KS']
self.GS = data['GS']
class Leagueteam:
def __init__(self, players, data):
self.players = players
self.region = data['region']
self.season = data['season']
self.WL = data['WL']
self.avg_gm_dur = data['avg_gm_dur']
self.most_banned_by = data['most_banned_by']
self.most_banned_vs = data['most_banned_vs']
self.economy = data['economy']
self.aggression = data['aggression']
self.objectives = data['objectives']
self.vision = data['vision'] |
text1 = '''ABCDEF
GHIJKL
MNOPQRS
TUVWXYZ
'''
text2 = 'ABCDEF\
GHIJKL\
MNOPQRS\
TUVWXYZ'
text3 = 'ABCD\'EF\'GHIJKL'
text4 = 'ABCDEF\nGHIJKL\nMNOPQRS\nTUVWXYZ'
text5 = 'ABCDEF\fGHIJKL\fMNOPQRS\fTUVWXYZ'
print(text1)
print('-' * 25)
print(text2)
print('-' * 25)
print(text3)
print('-' * 25)
print(text4)
print('-' * 25)
print(text5) | text1 = 'ABCDEF\nGHIJKL\nMNOPQRS\nTUVWXYZ\n'
text2 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
text3 = "ABCD'EF'GHIJKL"
text4 = 'ABCDEF\nGHIJKL\nMNOPQRS\nTUVWXYZ'
text5 = 'ABCDEF\x0cGHIJKL\x0cMNOPQRS\x0cTUVWXYZ'
print(text1)
print('-' * 25)
print(text2)
print('-' * 25)
print(text3)
print('-' * 25)
print(text4)
print('-' * 25)
print(text5) |
# unihernandez22
# https://atcoder.jp/contests/abc166/tasks/abc166_d
# math, brute force
n = int(input())
for a in range(n):
breaked = True
for b in range(-1000, 1000):
if a**5 - b**5 == n:
print(a, b)
break;
else:
breaked = False
if breaked:
break
| n = int(input())
for a in range(n):
breaked = True
for b in range(-1000, 1000):
if a ** 5 - b ** 5 == n:
print(a, b)
break
else:
breaked = False
if breaked:
break |
T = int(input())
P = int(input())
controle = 0 #Uso para guardar o valor maior que o limite
while P != 0:
P = int(input())
if P >= T:
controle = 1 #coloquei 1 so pra ser diferente de 0
if controle == 1:
print("ALARME")
else:
print("O Havai pode dormir tranquilo") | t = int(input())
p = int(input())
controle = 0
while P != 0:
p = int(input())
if P >= T:
controle = 1
if controle == 1:
print('ALARME')
else:
print('O Havai pode dormir tranquilo') |
__all__ = [
"aggregation",
"association",
"composition",
"connection",
"containment",
"dependency",
"includes",
"membership",
"ownership",
"responsibility",
"usage"
] | __all__ = ['aggregation', 'association', 'composition', 'connection', 'containment', 'dependency', 'includes', 'membership', 'ownership', 'responsibility', 'usage'] |
class AxisIndex(): #TODO: read this value from config file
LEFT_RIGHT=0
FORWARD_BACKWARDS=1
ROTATE=2
UP_DOWN=3
class ButtonIndex():
TRIGGER = 0
SIDE_BUTTON = 1
HOVERING = 2
EXIT = 10
class ThresHold():
SENDING_TIME = 0.5 | class Axisindex:
left_right = 0
forward_backwards = 1
rotate = 2
up_down = 3
class Buttonindex:
trigger = 0
side_button = 1
hovering = 2
exit = 10
class Threshold:
sending_time = 0.5 |
#!/Users/francischen/opt/anaconda3/bin/python
#pythons sorts are STABLE: order is the same as original in tie.
# sort: key, reverse
q = ['two','twelve','One','3']
#sort q, result being a modified list. nothing is returned
q.sort()
print(q)
q = ['two','twelve','One','3',"this has lots of t's"]
q.sort(reverse=True)
print(q)
def f(x):
return x.count('t')
q.sort(key = f)
print(q)
q = ['twelve','two','One','3',"this has lots of t's"]
q.sort(key=f)
print(q)
#Multiple sorts
q = ['twelve','two','One','3',"this has lots of t's"]
q.sort()
q.sort(key=f)
# sort based on 1,2,and then 3
# sort 3, then sort 2, then sort 1
print(q)
def complicated(x):
return(x.count('t'),len(x),x)
q = ['two','otw','wot','Z','t','tt','longer t']
q.sort(key=complicated)
print(q) | q = ['two', 'twelve', 'One', '3']
q.sort()
print(q)
q = ['two', 'twelve', 'One', '3', "this has lots of t's"]
q.sort(reverse=True)
print(q)
def f(x):
return x.count('t')
q.sort(key=f)
print(q)
q = ['twelve', 'two', 'One', '3', "this has lots of t's"]
q.sort(key=f)
print(q)
q = ['twelve', 'two', 'One', '3', "this has lots of t's"]
q.sort()
q.sort(key=f)
print(q)
def complicated(x):
return (x.count('t'), len(x), x)
q = ['two', 'otw', 'wot', 'Z', 't', 'tt', 'longer t']
q.sort(key=complicated)
print(q) |
# buildifier: disable=module-docstring
load(":native_tools_toolchain.bzl", "access_tool")
def get_cmake_data(ctx):
return _access_and_expect_label_copied("@rules_foreign_cc//tools/build_defs:cmake_toolchain", ctx, "cmake")
def get_ninja_data(ctx):
return _access_and_expect_label_copied("@rules_foreign_cc//tools/build_defs:ninja_toolchain", ctx, "ninja")
def get_make_data(ctx):
return _access_and_expect_label_copied("@rules_foreign_cc//tools/build_defs:make_toolchain", ctx, "make")
def _access_and_expect_label_copied(toolchain_type_, ctx, tool_name):
tool_data = access_tool(toolchain_type_, ctx, tool_name)
if tool_data.target:
# This could be made more efficient by changing the
# toolchain to provide the executable as a target
cmd_file = tool_data
for f in tool_data.target.files.to_list():
if f.path.endswith("/" + tool_data.path):
cmd_file = f
break
return struct(
deps = [tool_data.target],
# as the tool will be copied into tools directory
path = "$EXT_BUILD_ROOT/{}".format(cmd_file.path),
)
else:
return struct(
deps = [],
path = tool_data.path,
)
| load(':native_tools_toolchain.bzl', 'access_tool')
def get_cmake_data(ctx):
return _access_and_expect_label_copied('@rules_foreign_cc//tools/build_defs:cmake_toolchain', ctx, 'cmake')
def get_ninja_data(ctx):
return _access_and_expect_label_copied('@rules_foreign_cc//tools/build_defs:ninja_toolchain', ctx, 'ninja')
def get_make_data(ctx):
return _access_and_expect_label_copied('@rules_foreign_cc//tools/build_defs:make_toolchain', ctx, 'make')
def _access_and_expect_label_copied(toolchain_type_, ctx, tool_name):
tool_data = access_tool(toolchain_type_, ctx, tool_name)
if tool_data.target:
cmd_file = tool_data
for f in tool_data.target.files.to_list():
if f.path.endswith('/' + tool_data.path):
cmd_file = f
break
return struct(deps=[tool_data.target], path='$EXT_BUILD_ROOT/{}'.format(cmd_file.path))
else:
return struct(deps=[], path=tool_data.path) |
fname = input("Enter file name: ")
if len(fname) < 1 : fname = "mbox-short.txt"
list = list()
f = open(fname)
count = 0
for line in f:
line = line.rstrip()
list = line.split()
if list == []: continue
elif list[0].lower() == 'from':
count += 1
print(list[1])
print("There were", count, "lines in the file with From as the first word") | fname = input('Enter file name: ')
if len(fname) < 1:
fname = 'mbox-short.txt'
list = list()
f = open(fname)
count = 0
for line in f:
line = line.rstrip()
list = line.split()
if list == []:
continue
elif list[0].lower() == 'from':
count += 1
print(list[1])
print('There were', count, 'lines in the file with From as the first word') |
class FollowupEvent:
def __init__(self, name, data=None):
self.name = name
self.data = data
class Response:
def __init__(self, text=None, followup_event=None):
self.speech = text
self.display_text = text
self.followup_event = followup_event
class UserInput:
def __init__(self, message: str, session_id: str, params: dict, text: str, action: str, intent: str):
self.message = message
self.session_id = session_id
self.params = params
self.raw = text
self.action = action
self.intent = intent
| class Followupevent:
def __init__(self, name, data=None):
self.name = name
self.data = data
class Response:
def __init__(self, text=None, followup_event=None):
self.speech = text
self.display_text = text
self.followup_event = followup_event
class Userinput:
def __init__(self, message: str, session_id: str, params: dict, text: str, action: str, intent: str):
self.message = message
self.session_id = session_id
self.params = params
self.raw = text
self.action = action
self.intent = intent |
# Problem Name: Suffix Trie Construction
# Problem Description:
# Write a SuffixTrie class for Suffix-Trie-like data structures. The class should have a root property set to be the root node of the trie and should support:
# - Creating the trie from a string; this will be done by calling populateSuffixTrieFrom method upon class instantiation(creation), which should populate the root of the class.
# - Searching for strings in the trie.
# Note that every string added to the trie should end with special endSymbol character: "*".
####################################
# Sample Input (for creation):
# string = "babc"
# Sample Output (for creation):
# The structure below is the root of the trie:
# {
# "c": {"*": true},
# "b": {
# "c": {"*": true},
# "a": {"b": {"c": {"*": true}}},
# },
# "a": {"b": {"c": {"*": true}}},
# }
# Sample Input (for searching in the suffix trie above):
# string = "abc"
# Sample Output (for searching in the suffix trie above):
# True
####################################
"""
Explain the solution:
- Building a suffix-trie-like data structure consists of essentially storing every suffix of a given string in a trie. To do so, iterate through the input string one character at a time, and insert every substring starting at each character and ending at the end of string into the trie.
- To insert a string into the trie, start by adding the first character of the string into the root node of the trie and map it to an empty hash table if it isin't already there. Then, iterate through the rest of the string, inserting each of the remaining characters into the previous character's corresponding node(or hash table) in the trie, making sure to add an endSymbol "*" at the end.
- Searching the trie for a specific string should follow a nearly identical logic to the one used to add a string in the trie.
# Creation: O(n^2) time | O(n^2) space - where n is the length of the input string
# Searching: O(m) time | O(1) space - where m is the length of the input string
##################
Detailed explanation of the Solution:
create a class called SuffixTrie:
initialize function takes in a string:
initialize the class with root as an empty hash table
initialize the class with a endSymbol variable that is set to "*"
create a method called populateSuffixTrieFrom with a parameter of string
# Creation:
initialize function populateSuffixTrieFrom takes in a string:
iterate as i through the string one character at a time:
use Helper function insertSubsStringStartingAt with the parameter of the string and the current character(i)
initialize function insertSubsStringStartingAt takes in a string and a character(i):
create a variable called node that is set to the root of the trie
iterate as j through the string starting at the character(i) and ending at the end of the string:
create a variable called letter that is set to the current string[j]
if the letter is not in the node:
create a new hash table and set it to the node[letter] # this is the first time we've seen this letter
create a variable called node that is set to the node[letter] # this is the node we're currently at
node[self.endSymbol] = True # insert the endSymbol "*" at the end of the string
# Searching:
initialize function contains takes in a string:
create a variable called node that is set to the root of the trie
iterate as letter through the string:
if the letter is not in the node:
return False
create a variable called node that is set to the node[letter]
return self.endSymbol in node # return True if the endSymbol "*" is in the node
"""
####################################
class SuffixTrie:
def __init__(self, string):
self.root = {}
self.endSymbol = "*"
self.populateSuffixTrieFrom(string) #call the populateSuffixTrieFrom function with the string as a parameter
# Creation
def populateSuffixTrieFrom(self, string):
for i in range(len(string)):
self.insertSubstringStartingAt(string, i) #insert the substring starting at each character and ending at the end of string into the trie
def insertSubstringStartingAt(self, string, i):
node = self.root
for j in range(i, len(string)):#iterate through the string starting at the index i
letter = string[j] #get the letter at the index j
if letter not in node:
node[letter] = {} #if the letter is not in the node, add it to the node and map it to an empty hash table
node = node[letter] # this is the node that we are currently at
node[self.endSymbol] = True
# Searching
def contains(self, string):
node = self.root #start at the root node
for letter in string:
if letter not in node: #if the current letter is not in the node, return false
return False
node = node[letter] #move to the next node
return self.endSymbol in node #return True if the endSymbol "*" is in the node
def main():
string = "babc"
trie = SuffixTrie(string)
print(trie.root)
if __name__ == '__main__':
main() | """
Explain the solution:
- Building a suffix-trie-like data structure consists of essentially storing every suffix of a given string in a trie. To do so, iterate through the input string one character at a time, and insert every substring starting at each character and ending at the end of string into the trie.
- To insert a string into the trie, start by adding the first character of the string into the root node of the trie and map it to an empty hash table if it isin't already there. Then, iterate through the rest of the string, inserting each of the remaining characters into the previous character's corresponding node(or hash table) in the trie, making sure to add an endSymbol "*" at the end.
- Searching the trie for a specific string should follow a nearly identical logic to the one used to add a string in the trie.
# Creation: O(n^2) time | O(n^2) space - where n is the length of the input string
# Searching: O(m) time | O(1) space - where m is the length of the input string
##################
Detailed explanation of the Solution:
create a class called SuffixTrie:
initialize function takes in a string:
initialize the class with root as an empty hash table
initialize the class with a endSymbol variable that is set to "*"
create a method called populateSuffixTrieFrom with a parameter of string
# Creation:
initialize function populateSuffixTrieFrom takes in a string:
iterate as i through the string one character at a time:
use Helper function insertSubsStringStartingAt with the parameter of the string and the current character(i)
initialize function insertSubsStringStartingAt takes in a string and a character(i):
create a variable called node that is set to the root of the trie
iterate as j through the string starting at the character(i) and ending at the end of the string:
create a variable called letter that is set to the current string[j]
if the letter is not in the node:
create a new hash table and set it to the node[letter] # this is the first time we've seen this letter
create a variable called node that is set to the node[letter] # this is the node we're currently at
node[self.endSymbol] = True # insert the endSymbol "*" at the end of the string
# Searching:
initialize function contains takes in a string:
create a variable called node that is set to the root of the trie
iterate as letter through the string:
if the letter is not in the node:
return False
create a variable called node that is set to the node[letter]
return self.endSymbol in node # return True if the endSymbol "*" is in the node
"""
class Suffixtrie:
def __init__(self, string):
self.root = {}
self.endSymbol = '*'
self.populateSuffixTrieFrom(string)
def populate_suffix_trie_from(self, string):
for i in range(len(string)):
self.insertSubstringStartingAt(string, i)
def insert_substring_starting_at(self, string, i):
node = self.root
for j in range(i, len(string)):
letter = string[j]
if letter not in node:
node[letter] = {}
node = node[letter]
node[self.endSymbol] = True
def contains(self, string):
node = self.root
for letter in string:
if letter not in node:
return False
node = node[letter]
return self.endSymbol in node
def main():
string = 'babc'
trie = suffix_trie(string)
print(trie.root)
if __name__ == '__main__':
main() |
def test_list_devices(client):
devices = client.devices()
assert len(devices) > 0
assert any(map(lambda device: device.serial == "emulator-5554", devices))
def test_list_devices_by_state(client):
devices = client.devices(client.BOOTLOADER)
assert len(devices) == 0
devices = client.devices(client.OFFLINE)
assert len(devices) == 0
devices = client.devices(client.DEVICE)
assert len(devices) == 1
def test_version(client):
version = client.version()
assert type(version) == int
assert version != 0
def test_list_forward(client, device):
client.killforward_all()
result = client.list_forward()
assert not result
device.forward("tcp:6000", "tcp:6000")
result = client.list_forward()
assert result["emulator-5554"]["tcp:6000"] == "tcp:6000"
client.killforward_all()
result = client.list_forward()
assert not result
def test_features(client):
assert client.features()
| def test_list_devices(client):
devices = client.devices()
assert len(devices) > 0
assert any(map(lambda device: device.serial == 'emulator-5554', devices))
def test_list_devices_by_state(client):
devices = client.devices(client.BOOTLOADER)
assert len(devices) == 0
devices = client.devices(client.OFFLINE)
assert len(devices) == 0
devices = client.devices(client.DEVICE)
assert len(devices) == 1
def test_version(client):
version = client.version()
assert type(version) == int
assert version != 0
def test_list_forward(client, device):
client.killforward_all()
result = client.list_forward()
assert not result
device.forward('tcp:6000', 'tcp:6000')
result = client.list_forward()
assert result['emulator-5554']['tcp:6000'] == 'tcp:6000'
client.killforward_all()
result = client.list_forward()
assert not result
def test_features(client):
assert client.features() |
"""Top-level package for Goldmeister."""
__author__ = """Micah Johnson"""
__email__ = 'micah.johnson150@gmail.com'
__version__ = '0.2.0'
| """Top-level package for Goldmeister."""
__author__ = 'Micah Johnson'
__email__ = 'micah.johnson150@gmail.com'
__version__ = '0.2.0' |
def si(p,r,t):
n= (p+r+t)//3
return n
| def si(p, r, t):
n = (p + r + t) // 3
return n |
#!/usr/bin/env python3
# This is gonna be up to you. But basically I envisioned a system where you have a students in a classroom. Where the
# classroom only has information, like who is the teacher, how many students are there. And it's like an online class,
# so students don't know who their peers are, or who their teacher is, but can do things like study, and take test and
# stuff. Etc. But get used to how objects interact with each other and try to call stuff from other places while being
# commanded all in main():
class Student:
def __init__(self, name, laziness=5):
self.name = name
self.preparedness = 0
self._laziness = laziness
def takeTest(self, hardness):
# TODO: return a score that's 100 - difference between hardness and preparedness (score capped at 100)
return 0
def doHomework(self):
# TODO: return a score of either 0 or 100 depending on how lazy they are. Implementation is up to you.
return 0
def study(self):
# TODO: increment preparedness by a random number between 1-10 (prerparedness capped at 100)
pass
class Teacher:
def __init__(self, name):
self.name = name
self.classroom = None
self.test_grades = {}
self.homework_grades = {}
def administerTest(self, students, hardness):
# TODO: Given a hardness of a test and list of students. Make each student take test and log their grades
pass
def giveHomework(self, students):
# TODO: Given homework to student and log in their grades
pass
def giveGrades(self, students):
# TODO: Given all the test scores and homework score in each student, give 30% to HW and 70% to test.
# TODO: Return list of passed students and remove them from classroom. Clear grades for all remaining students
pass
class ClassRoom:
def __init__(self):
self.class_size_limit = 10
self.students = {}
self.teacher = None
def addStudent(self, student):
# TODO: add student to class. Print something if they try to add the same student or go over the limit
pass
def assignTeacherToClass(self, teacher):
# TODO: Assign teacher, also prompt user if they want to switch teacher if one already assigned or same teacher
pass
def getStudents(self):
# TODO: return a list of students
return
if __name__ == '__main__':
classroom = ClassRoom()
teacher = Teacher('Doctor Jones')
mike = Student('Mike')
sally = Student('Sally', laziness=1)
lebron = Student('Lebron', laziness=10)
# TODO: Assign a teacher to the classroom and add the students to the classroom. Then make the students study
# TODO: Make Students to homework, etc, exams, then pass or fail them, etc. Play around with it.
| class Student:
def __init__(self, name, laziness=5):
self.name = name
self.preparedness = 0
self._laziness = laziness
def take_test(self, hardness):
return 0
def do_homework(self):
return 0
def study(self):
pass
class Teacher:
def __init__(self, name):
self.name = name
self.classroom = None
self.test_grades = {}
self.homework_grades = {}
def administer_test(self, students, hardness):
pass
def give_homework(self, students):
pass
def give_grades(self, students):
pass
class Classroom:
def __init__(self):
self.class_size_limit = 10
self.students = {}
self.teacher = None
def add_student(self, student):
pass
def assign_teacher_to_class(self, teacher):
pass
def get_students(self):
return
if __name__ == '__main__':
classroom = class_room()
teacher = teacher('Doctor Jones')
mike = student('Mike')
sally = student('Sally', laziness=1)
lebron = student('Lebron', laziness=10) |
# https://github.com/ArtemNikolaev/gb-hw/issues/24
def multiple_of_20_21():
return (i for i in range(20, 241) if i % 20 == 0 or i % 21 == 0)
print(list(multiple_of_20_21()))
| def multiple_of_20_21():
return (i for i in range(20, 241) if i % 20 == 0 or i % 21 == 0)
print(list(multiple_of_20_21())) |
def cc_resources(name, data):
out_inc = name + ".inc"
cmd = ('echo "static const struct FileToc kPackedFiles[] = {" > $(@); \n' +
"for j in $(SRCS); do\n" +
' echo "{\\"$$(basename "$${j}")\\"," >> $(@);\n' +
' echo "R\\"filecontent($$(< $${j}))filecontent\\"" >> $(@);\n' +
' echo "}," >> $(@);\n' +
"done &&\n" +
'echo "{nullptr, nullptr}};" >> $(@)')
if len(data) == 0:
fail("Empty `data` attribute in `%s`" % name)
native.genrule(
name = name,
outs = [out_inc],
srcs = data,
cmd = cmd,
)
# Returns the generated files directory root.
#
# Note: workaround for https://github.com/bazelbuild/bazel/issues/4463.
def gendir():
if native.repository_name() == "@":
return "$(GENDIR)"
return "$(GENDIR)/external/" + native.repository_name().lstrip("@")
| def cc_resources(name, data):
out_inc = name + '.inc'
cmd = 'echo "static const struct FileToc kPackedFiles[] = {" > $(@); \n' + 'for j in $(SRCS); do\n' + ' echo "{\\"$$(basename "$${j}")\\"," >> $(@);\n' + ' echo "R\\"filecontent($$(< $${j}))filecontent\\"" >> $(@);\n' + ' echo "}," >> $(@);\n' + 'done &&\n' + 'echo "{nullptr, nullptr}};" >> $(@)'
if len(data) == 0:
fail('Empty `data` attribute in `%s`' % name)
native.genrule(name=name, outs=[out_inc], srcs=data, cmd=cmd)
def gendir():
if native.repository_name() == '@':
return '$(GENDIR)'
return '$(GENDIR)/external/' + native.repository_name().lstrip('@') |
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def say_hello(self):
print('Hello, my name is {} and I am {} years old'.format(self.name, self.age))
if __name__ == '__main__':
person = Person('David', 34)
print('Age: {}'.format(person.age))
person.say_hello() | class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def say_hello(self):
print('Hello, my name is {} and I am {} years old'.format(self.name, self.age))
if __name__ == '__main__':
person = person('David', 34)
print('Age: {}'.format(person.age))
person.say_hello() |
num= int (input("enter number of rows="))
for i in range (1,num+1):
for j in range(1,num-i+1):
print (" ",end="")
for j in range(2 and 9):
print("2","9")
for i in range(1, 6):
for j in range(1, 10):
if i==5 or i+j==5 or j-i==4:
print("*", end="")
else:
print(end=" ")
print()
| num = int(input('enter number of rows='))
for i in range(1, num + 1):
for j in range(1, num - i + 1):
print(' ', end='')
for j in range(2 and 9):
print('2', '9')
for i in range(1, 6):
for j in range(1, 10):
if i == 5 or i + j == 5 or j - i == 4:
print('*', end='')
else:
print(end=' ')
print() |
'''
Problem:-
Given a string s, find the longest palindromic substring in s.
You may assume that the maximum length of s is 1000.
Example 1:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
'''
class Solution:
def longestPalindrome(self, s: str) -> str:
res = ""
resLen = 0
for i in range(len(s)):
# odd length
l, r = i, i
while l >= 0 and r < len(s) and s[l] == s[r]:
if (r - l + 1) > resLen:
res = s[l:r + 1]
resLen = r - l + 1
l -= 1
r += 1
# even length
l, r = i, i + 1
while l >= 0 and r < len(s) and s[l] == s[r]:
if (r - l + 1) > resLen:
res = s[l:r + 1]
resLen = r - l + 1
l -= 1
r += 1
return res | """
Problem:-
Given a string s, find the longest palindromic substring in s.
You may assume that the maximum length of s is 1000.
Example 1:
Input: "babad"
Output: "bab"
Note: "aba" is also a valid answer.
"""
class Solution:
def longest_palindrome(self, s: str) -> str:
res = ''
res_len = 0
for i in range(len(s)):
(l, r) = (i, i)
while l >= 0 and r < len(s) and (s[l] == s[r]):
if r - l + 1 > resLen:
res = s[l:r + 1]
res_len = r - l + 1
l -= 1
r += 1
(l, r) = (i, i + 1)
while l >= 0 and r < len(s) and (s[l] == s[r]):
if r - l + 1 > resLen:
res = s[l:r + 1]
res_len = r - l + 1
l -= 1
r += 1
return res |
def _doxygen_archive_impl(ctx):
"""Generate a .tar.gz archive containing documentation using Doxygen.
Args:
name: label for the generated rule. The archive will be "%{name}.tar.gz".
doxyfile: configuration file for Doxygen, @@OUTPUT_DIRECTORY@@ will be replaced with the actual output dir
srcs: source files the documentation will be generated from.
"""
doxyfile = ctx.file.doxyfile
out_file = ctx.outputs.out
out_dir_path = out_file.short_path[:-len(".tar.gz")]
commands = [
"mkdir -p %s" % out_dir_path,
"out_dir_path=$(cd %s; pwd)" % out_dir_path,
"pushd %s" % doxyfile.dirname,
"""sed -e \"s:@@OUTPUT_DIRECTORY@@:$out_dir_path/:\" <%s | doxygen -""" % doxyfile.basename,
"popd",
"tar czf %s -C %s ./" % (out_file.path, out_dir_path),
]
ctx.actions.run_shell(
inputs = ctx.files.srcs + [doxyfile],
outputs = [out_file],
use_default_shell_env = True,
command = " && ".join(commands),
)
doxygen_archive = rule(
implementation = _doxygen_archive_impl,
attrs = {
"doxyfile": attr.label(
mandatory = True,
allow_single_file = True,
),
"srcs": attr.label_list(
mandatory = True,
allow_files = True,
),
},
outputs = {
"out": "%{name}.tar.gz",
},
)
def _sphinx_archive_impl(ctx):
"""
Generates a sphinx documentation archive (.tar.gz).
The output is called <name>.tar.gz, where <name> is the
name of the rule.
Args:
config_file: sphinx conf.py file
doxygen_xml_archive: an archive that containing the generated doxygen
xml files to be consumed by the breathe sphinx plugin.
Setting this attribute automatically enables the breathe plugin
srcs: the *.rst files to consume
"""
out_file = ctx.outputs.sphinx
out_dir_path = out_file.short_path[:-len(".tar.gz")]
commands = ["mkdir _static"]
inputs = ctx.files.srcs
if ctx.attr.doxygen_xml_archive != None:
commands = commands + [
"mkdir xml",
"tar -xzf {xml} -C xml --strip-components=2".format(xml = ctx.file.doxygen_xml_archive.path),
]
inputs.append(ctx.file.doxygen_xml_archive)
commands = commands + [
"sphinx-build -M build ./ _build -q -b html -C {settings}".format(
settings = _sphinx_settings(ctx),
out_dir = out_dir_path,
),
]
commands = commands + [
"tar czf %s -C _build/build/ ./" % (out_file.path),
]
ctx.actions.run_shell(
use_default_shell_env = True,
outputs = [out_file],
inputs = inputs,
command = " && ".join(commands),
)
sphinx_archive = rule(
implementation = _sphinx_archive_impl,
attrs = {
"srcs": attr.label_list(
mandatory = True,
allow_files = True,
),
"doxygen_xml_archive": attr.label(
default = None,
allow_single_file = True,
),
"master_doc": attr.string(default = "contents"),
"version": attr.string(
mandatory = True,
),
"project": attr.string(
default = "",
),
"copyright": attr.string(default = ""),
"extensions": attr.string_list(default = [
"sphinx.ext.intersphinx",
"sphinx.ext.todo",
]),
"templates": attr.string_list(default = []),
"source_suffix": attr.string_list(default = [".rst"]),
"exclude_patterns": attr.string_list(default = ["_build", "Thumbs.db", ".DS_Store"]),
"pygments_style": attr.string(default = ""),
"language": attr.string(default = ""),
"html_theme": attr.string(default = "sphinx_rtd_theme"),
"html_theme_options": attr.string_dict(default = {}),
"html_static_path": attr.string_list(default = ["_static"]),
"html_sidebars": attr.string_dict(default = {}),
"intersphinx_mapping": attr.string_dict(default = {}),
},
outputs = {
"sphinx": "%{name}.tar.gz",
},
)
def add_option(settings, setting, value):
if value != None or len(value) == 0:
settings = settings + ["-D {setting}={value}".format(setting = setting, value = value.replace(" ", "\ "))]
return settings
def _sphinx_settings(ctx):
settings = []
extensions = ctx.attr.extensions
settings = add_option(settings, "version", ctx.attr.version)
if ctx.attr.project == "":
settings = add_option(settings, "project", ctx.workspace_name)
else:
settings = add_option(settings, "project", ctx.attr.project)
if ctx.attr.doxygen_xml_archive != None:
extensions = extensions + ["breathe"]
settings = add_option(settings, "breathe_projects." + ctx.workspace_name, "xml")
settings = add_option(settings, "breathe_default_project", ctx.workspace_name)
settings = add_option(settings, "copyright", ctx.attr.copyright)
settings = add_option(settings, "master_doc", ctx.attr.master_doc)
for extension in extensions:
settings = add_option(settings, "extensions", extension)
for template in ctx.attr.templates:
settings = add_option(settings, "templates", template)
for suffix in ctx.attr.source_suffix:
settings = add_option(settings, "source_suffix", suffix)
for pattern in ctx.attr.exclude_patterns:
settings = add_option(settings, "exclude_patterns", pattern)
settings = add_option(settings, "html_theme", ctx.attr.html_theme)
for path in ctx.attr.html_static_path:
settings = add_option(settings, "html_static_path", path)
setting_string = " ".join(settings)
return setting_string | def _doxygen_archive_impl(ctx):
"""Generate a .tar.gz archive containing documentation using Doxygen.
Args:
name: label for the generated rule. The archive will be "%{name}.tar.gz".
doxyfile: configuration file for Doxygen, @@OUTPUT_DIRECTORY@@ will be replaced with the actual output dir
srcs: source files the documentation will be generated from.
"""
doxyfile = ctx.file.doxyfile
out_file = ctx.outputs.out
out_dir_path = out_file.short_path[:-len('.tar.gz')]
commands = ['mkdir -p %s' % out_dir_path, 'out_dir_path=$(cd %s; pwd)' % out_dir_path, 'pushd %s' % doxyfile.dirname, 'sed -e "s:@@OUTPUT_DIRECTORY@@:$out_dir_path/:" <%s | doxygen -' % doxyfile.basename, 'popd', 'tar czf %s -C %s ./' % (out_file.path, out_dir_path)]
ctx.actions.run_shell(inputs=ctx.files.srcs + [doxyfile], outputs=[out_file], use_default_shell_env=True, command=' && '.join(commands))
doxygen_archive = rule(implementation=_doxygen_archive_impl, attrs={'doxyfile': attr.label(mandatory=True, allow_single_file=True), 'srcs': attr.label_list(mandatory=True, allow_files=True)}, outputs={'out': '%{name}.tar.gz'})
def _sphinx_archive_impl(ctx):
"""
Generates a sphinx documentation archive (.tar.gz).
The output is called <name>.tar.gz, where <name> is the
name of the rule.
Args:
config_file: sphinx conf.py file
doxygen_xml_archive: an archive that containing the generated doxygen
xml files to be consumed by the breathe sphinx plugin.
Setting this attribute automatically enables the breathe plugin
srcs: the *.rst files to consume
"""
out_file = ctx.outputs.sphinx
out_dir_path = out_file.short_path[:-len('.tar.gz')]
commands = ['mkdir _static']
inputs = ctx.files.srcs
if ctx.attr.doxygen_xml_archive != None:
commands = commands + ['mkdir xml', 'tar -xzf {xml} -C xml --strip-components=2'.format(xml=ctx.file.doxygen_xml_archive.path)]
inputs.append(ctx.file.doxygen_xml_archive)
commands = commands + ['sphinx-build -M build ./ _build -q -b html -C {settings}'.format(settings=_sphinx_settings(ctx), out_dir=out_dir_path)]
commands = commands + ['tar czf %s -C _build/build/ ./' % out_file.path]
ctx.actions.run_shell(use_default_shell_env=True, outputs=[out_file], inputs=inputs, command=' && '.join(commands))
sphinx_archive = rule(implementation=_sphinx_archive_impl, attrs={'srcs': attr.label_list(mandatory=True, allow_files=True), 'doxygen_xml_archive': attr.label(default=None, allow_single_file=True), 'master_doc': attr.string(default='contents'), 'version': attr.string(mandatory=True), 'project': attr.string(default=''), 'copyright': attr.string(default=''), 'extensions': attr.string_list(default=['sphinx.ext.intersphinx', 'sphinx.ext.todo']), 'templates': attr.string_list(default=[]), 'source_suffix': attr.string_list(default=['.rst']), 'exclude_patterns': attr.string_list(default=['_build', 'Thumbs.db', '.DS_Store']), 'pygments_style': attr.string(default=''), 'language': attr.string(default=''), 'html_theme': attr.string(default='sphinx_rtd_theme'), 'html_theme_options': attr.string_dict(default={}), 'html_static_path': attr.string_list(default=['_static']), 'html_sidebars': attr.string_dict(default={}), 'intersphinx_mapping': attr.string_dict(default={})}, outputs={'sphinx': '%{name}.tar.gz'})
def add_option(settings, setting, value):
if value != None or len(value) == 0:
settings = settings + ['-D {setting}={value}'.format(setting=setting, value=value.replace(' ', '\\ '))]
return settings
def _sphinx_settings(ctx):
settings = []
extensions = ctx.attr.extensions
settings = add_option(settings, 'version', ctx.attr.version)
if ctx.attr.project == '':
settings = add_option(settings, 'project', ctx.workspace_name)
else:
settings = add_option(settings, 'project', ctx.attr.project)
if ctx.attr.doxygen_xml_archive != None:
extensions = extensions + ['breathe']
settings = add_option(settings, 'breathe_projects.' + ctx.workspace_name, 'xml')
settings = add_option(settings, 'breathe_default_project', ctx.workspace_name)
settings = add_option(settings, 'copyright', ctx.attr.copyright)
settings = add_option(settings, 'master_doc', ctx.attr.master_doc)
for extension in extensions:
settings = add_option(settings, 'extensions', extension)
for template in ctx.attr.templates:
settings = add_option(settings, 'templates', template)
for suffix in ctx.attr.source_suffix:
settings = add_option(settings, 'source_suffix', suffix)
for pattern in ctx.attr.exclude_patterns:
settings = add_option(settings, 'exclude_patterns', pattern)
settings = add_option(settings, 'html_theme', ctx.attr.html_theme)
for path in ctx.attr.html_static_path:
settings = add_option(settings, 'html_static_path', path)
setting_string = ' '.join(settings)
return setting_string |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def minDiffInBST(self, root: Optional[TreeNode]) -> int:
output=[]
stack=[root]
while(stack):
cur = stack.pop(0)
output.append(cur.val)
if cur.left:
stack.append(cur.left)
if cur.right:
stack.append(cur.right)
sorted_output=sorted(output)
diff = sorted_output[1]-sorted_output[0]
for i in range(2,len(sorted_output)):
if sorted_output[i]-sorted_output[i-1]<diff:
diff=sorted_output[i]-sorted_output[i-1]
return diff | class Solution:
def min_diff_in_bst(self, root: Optional[TreeNode]) -> int:
output = []
stack = [root]
while stack:
cur = stack.pop(0)
output.append(cur.val)
if cur.left:
stack.append(cur.left)
if cur.right:
stack.append(cur.right)
sorted_output = sorted(output)
diff = sorted_output[1] - sorted_output[0]
for i in range(2, len(sorted_output)):
if sorted_output[i] - sorted_output[i - 1] < diff:
diff = sorted_output[i] - sorted_output[i - 1]
return diff |
PREFIX = "/video/tvkultura"
NAME = "TVKultura.Ru"
ICON = "tvkultura.png"
ART = "tvkultura.jpg"
BASE_URL = "https://tvkultura.ru/"
BRAND_URL = BASE_URL+"brand/"
# Channel initialization
def Start():
ObjectContainer.title1 = NAME
HTTP.Headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0'
# Main menu
@handler(PREFIX, NAME, thumb=ICON, art=ART)
def MainMenu():
brands = SharedCodeService.vgtrk.brand_menu(BRAND_URL)
oc = ObjectContainer(title1=NAME)
for brand in brands.list:
oc.add(DirectoryObject(
key=Callback(BrandMenu, url=brand.href),
title=brand.title,
summary=brand.about + ("\n\n[" + brand.schedule + "]" if brand.schedule else ''),
thumb=Resource.ContentsOfURLWithFallback(url=brand.big_thumb, fallback=brand.small_thumb),
))
return oc
@route(PREFIX+'/brand')
def BrandMenu(url):
brand = SharedCodeService.vgtrk.brand_detail(url)
if brand.video_href:
return VideoViewTypePictureMenu(brand.video_href)
@route(PREFIX+'/video/viewtype-picture')
def VideoViewTypePictureMenu(url, page=1, referer=None, page_title=None, next_title=None):
videos = SharedCodeService.vgtrk.video_menu(url, page=page, referer=referer, page_title=page_title, next_title=next_title)
video_items = videos.view_type('picture')
oc = ObjectContainer(title1=videos.title)
for video in video_items.list:
oc.add(MetadataRecordForItem(video))
next_page = video_items.next_page
if next_page is not None:
oc.add(NextPageObject(
key=Callback(
VideoViewTypePictureMenu,
url=next_page.href,
page=int(page) + 1,
referer=url if referer is None else referer,
page_title=videos.title,
next_title=next_page.title
),
title=next_page.title,
))
return oc
@route(PREFIX+'/video/viewtype-picture/children')
def VideoViewTypePictureChildren(url, referer=None, page_title=None):
video_items = SharedCodeService.vgtrk.video_children(url, referer=referer, page_title=page_title)
oc = ObjectContainer(title1=page_title)
for video in video_items.list:
oc.add(EpisodeObjectForItem(video))
return oc
def MetadataRecordForItem(video):
if video.has_children:
return DirectoryObject(
key=Callback(VideoViewTypePictureChildren, url=video.ajaxurl, referer=video.href, page_title=video.title),
title=video.title,
thumb=video.thumb,
)
return EpisodeObjectForItem(video)
def EpisodeObjectForItem(video):
callback = Callback(MetadataObjectForURL, href=video.href, thumb=video.thumb, title=video.title)
return EpisodeObject(
key=callback,
rating_key=video.href,
title=video.title,
thumb=video.thumb,
items=MediaObjectsForURL(callback),
)
def MetadataObjectForURL(href, thumb, title, **kwargs):
# This is a sort-of replacement for the similar method from the URL Services, just different parameters list.
page = SharedCodeService.vgtrk.video_page(href)
video_clip_object = VideoClipObject(
key=Callback(MetadataObjectForURL, href=href, thumb=thumb, title=title, **kwargs),
rating_key=href,
title=title,
thumb=thumb,
summary=page.full_text,
items=MediaObjectsForURL(
Callback(PlayVideo, href=href)
),
**kwargs
)
return ObjectContainer(
no_cache=True,
objects=[video_clip_object]
)
def MediaObjectsForURL(callback):
# This is a sort-of replacement for the similar method from the URL Services, just different parameters list.
return [
MediaObject(
container=Container.MP4,
video_codec=VideoCodec.H264,
audio_codec=AudioCodec.AAC,
parts=[
PartObject(key=callback)
]
)
]
@indirect
def PlayVideo(href):
page = SharedCodeService.vgtrk.video_page(href)
json = JSON.ObjectFromURL(page.datavideo_href, headers={'Referer': page.video_iframe_href})
medialist = json['data']['playlist']['medialist']
if len(medialist) > 1:
raise RuntimeWarning('More than one media found, each should have been set as a PartObject!')
quality = str(json['data']['playlist']['priority_quality'])
transport = 'http'
if 'sources' not in medialist[0] and medialist[0]['errors']:
raise Ex.PlexNonCriticalError(2005, medialist[0]['errors'])
video_url = medialist[0]['sources'][transport][quality]
Log('Redirecting to video URL: %s' % video_url)
return IndirectResponse(
VideoClipObject,
key=video_url,
http_headers={'Referer': page.video_iframe_href},
metadata_kwargs={'summary': page.full_text}
)
| prefix = '/video/tvkultura'
name = 'TVKultura.Ru'
icon = 'tvkultura.png'
art = 'tvkultura.jpg'
base_url = 'https://tvkultura.ru/'
brand_url = BASE_URL + 'brand/'
def start():
ObjectContainer.title1 = NAME
HTTP.Headers['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; WOW64; rv:47.0) Gecko/20100101 Firefox/47.0'
@handler(PREFIX, NAME, thumb=ICON, art=ART)
def main_menu():
brands = SharedCodeService.vgtrk.brand_menu(BRAND_URL)
oc = object_container(title1=NAME)
for brand in brands.list:
oc.add(directory_object(key=callback(BrandMenu, url=brand.href), title=brand.title, summary=brand.about + ('\n\n[' + brand.schedule + ']' if brand.schedule else ''), thumb=Resource.ContentsOfURLWithFallback(url=brand.big_thumb, fallback=brand.small_thumb)))
return oc
@route(PREFIX + '/brand')
def brand_menu(url):
brand = SharedCodeService.vgtrk.brand_detail(url)
if brand.video_href:
return video_view_type_picture_menu(brand.video_href)
@route(PREFIX + '/video/viewtype-picture')
def video_view_type_picture_menu(url, page=1, referer=None, page_title=None, next_title=None):
videos = SharedCodeService.vgtrk.video_menu(url, page=page, referer=referer, page_title=page_title, next_title=next_title)
video_items = videos.view_type('picture')
oc = object_container(title1=videos.title)
for video in video_items.list:
oc.add(metadata_record_for_item(video))
next_page = video_items.next_page
if next_page is not None:
oc.add(next_page_object(key=callback(VideoViewTypePictureMenu, url=next_page.href, page=int(page) + 1, referer=url if referer is None else referer, page_title=videos.title, next_title=next_page.title), title=next_page.title))
return oc
@route(PREFIX + '/video/viewtype-picture/children')
def video_view_type_picture_children(url, referer=None, page_title=None):
video_items = SharedCodeService.vgtrk.video_children(url, referer=referer, page_title=page_title)
oc = object_container(title1=page_title)
for video in video_items.list:
oc.add(episode_object_for_item(video))
return oc
def metadata_record_for_item(video):
if video.has_children:
return directory_object(key=callback(VideoViewTypePictureChildren, url=video.ajaxurl, referer=video.href, page_title=video.title), title=video.title, thumb=video.thumb)
return episode_object_for_item(video)
def episode_object_for_item(video):
callback = callback(MetadataObjectForURL, href=video.href, thumb=video.thumb, title=video.title)
return episode_object(key=callback, rating_key=video.href, title=video.title, thumb=video.thumb, items=media_objects_for_url(callback))
def metadata_object_for_url(href, thumb, title, **kwargs):
page = SharedCodeService.vgtrk.video_page(href)
video_clip_object = video_clip_object(key=callback(MetadataObjectForURL, href=href, thumb=thumb, title=title, **kwargs), rating_key=href, title=title, thumb=thumb, summary=page.full_text, items=media_objects_for_url(callback(PlayVideo, href=href)), **kwargs)
return object_container(no_cache=True, objects=[video_clip_object])
def media_objects_for_url(callback):
return [media_object(container=Container.MP4, video_codec=VideoCodec.H264, audio_codec=AudioCodec.AAC, parts=[part_object(key=callback)])]
@indirect
def play_video(href):
page = SharedCodeService.vgtrk.video_page(href)
json = JSON.ObjectFromURL(page.datavideo_href, headers={'Referer': page.video_iframe_href})
medialist = json['data']['playlist']['medialist']
if len(medialist) > 1:
raise runtime_warning('More than one media found, each should have been set as a PartObject!')
quality = str(json['data']['playlist']['priority_quality'])
transport = 'http'
if 'sources' not in medialist[0] and medialist[0]['errors']:
raise Ex.PlexNonCriticalError(2005, medialist[0]['errors'])
video_url = medialist[0]['sources'][transport][quality]
log('Redirecting to video URL: %s' % video_url)
return indirect_response(VideoClipObject, key=video_url, http_headers={'Referer': page.video_iframe_href}, metadata_kwargs={'summary': page.full_text}) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.