content
stringlengths 7
1.05M
| fixed_cases
stringlengths 1
1.28M
|
|---|---|
#Will add a fixed header and return a sendable string (we should add pickle support here at some point somehow), also encodes the message for you
def createMsg(data):
msg = data
msg = f'{len(msg):<10}' + msg
return msg.encode("utf-8")
#streams data from the 'target' socket with an initial buffersize of 'bufferSize' (returns the decoded data)
def streamData(target, bufferSize):
#initial data chunk (contains an int of how much data the server should expect)
data = target.recv(bufferSize)
msglen = int(data[:bufferSize].strip())
decoded_data = ''
#stream the data in with a set buffer size
while len(decoded_data) < msglen:
print(decoded_data)
decoded_data += target.recv(bufferSize).decode("utf-8")
return decoded_data
|
def create_msg(data):
msg = data
msg = f'{len(msg):<10}' + msg
return msg.encode('utf-8')
def stream_data(target, bufferSize):
data = target.recv(bufferSize)
msglen = int(data[:bufferSize].strip())
decoded_data = ''
while len(decoded_data) < msglen:
print(decoded_data)
decoded_data += target.recv(bufferSize).decode('utf-8')
return decoded_data
|
class Solution:
def maxNonOverlapping(self, nums: List[int], target: int) -> int:
last = {0:-1}
s = 0
dp = [0]*len(nums)
for i in range(len(nums)):
s += nums[i]
if s-target in last:
dp[i] = max(dp[i-1] if i-1>=0 else 0, 1+ (dp[last[s-target]] if last[s-target]>=0 else 0))
else:
dp[i] = dp[i-1] if i-1>=0 else 0
last[s] = i
return dp[-1]
|
class Solution:
def max_non_overlapping(self, nums: List[int], target: int) -> int:
last = {0: -1}
s = 0
dp = [0] * len(nums)
for i in range(len(nums)):
s += nums[i]
if s - target in last:
dp[i] = max(dp[i - 1] if i - 1 >= 0 else 0, 1 + (dp[last[s - target]] if last[s - target] >= 0 else 0))
else:
dp[i] = dp[i - 1] if i - 1 >= 0 else 0
last[s] = i
return dp[-1]
|
def ascii_cipher(message, key):
pfactor = max(
i for i in range(2, abs(key)+1)
if is_prime(i) and key%i==0
)*(-1 if key<0 else 1)
return ''.join(chr((ord(c)+pfactor)%128) for c in message)
def is_prime(n):
if n < 2: return False
return all( n%i!=0 for i in range(2, round(pow(n,0.5))+1) ) or n==2
|
def ascii_cipher(message, key):
pfactor = max((i for i in range(2, abs(key) + 1) if is_prime(i) and key % i == 0)) * (-1 if key < 0 else 1)
return ''.join((chr((ord(c) + pfactor) % 128) for c in message))
def is_prime(n):
if n < 2:
return False
return all((n % i != 0 for i in range(2, round(pow(n, 0.5)) + 1))) or n == 2
|
class Solution:
"""
@param heights: a matrix of integers
@return: an integer
"""
def trapRainWater(self, heights):
"""
:type heightMap: List[List[int]]
:rtype: int
"""
m = len(heights)
n = len(heights[0]) if m else 0
peakMap = [[0x7FFFFFFF] * n for _ in range(m)]
q = []
for x in range(m):
for y in range(n):
if x in (0, m - 1) or y in (0, n - 1):
peakMap[x][y] = heights[x][y]
q.append((x, y))
while q:
x, y = q.pop(0)
for dx, dy in zip((1, 0, -1, 0), (0, 1, 0, -1)):
nx, ny = x + dx, y + dy
if nx <= 0 or nx >= m - 1 or ny <= 0 or ny >= n - 1: continue
limit = max(peakMap[x][y], heights[nx][ny])
if peakMap[nx][ny] > limit:
peakMap[nx][ny] = limit
q.append((nx, ny))
return sum(peakMap[x][y] - heights[x][y] for x in range(m) for y in range(n))
# class Solution:
# """
# @param heights: a matrix of integers
# @return: an integer
# """
# def trapRainWater(self, heights):
# result = 0
# height_dict = dict()
# for i, rows in enumerate(heights):
# for j, height in enumerate(rows):
# if height in height_dict:
# height_dict[height].append((i,j))
# else:
# height_dict[height] = [(i,j)]
# height_dict = sorted(height_dict.items(), key=lambda d:d[0])
# while len(height_dict) > 1:
# height_positions = height_dict.pop(0)
# cur_height = height_positions[0]
# positions = height_positions[1]
# step = height_dict[0][0] - cur_height
# while positions:
# position = positions[0]
# area = [0]
# valid = [True]
# self.dfs(position[0], position[1], cur_height, heights, valid, area, step, positions, height_dict)
# if valid[0]:
# result += area[0] * step
# return result
# def dfs(self, i, j, cur_height, heights, valid, area, step, positions, height_dict):
# if not positions:
# return
# if (i, j) not in positions:
# return
# if i == 0 or i == len(heights) - 1 or j == 0 or j == len(heights[0]) - 1:
# valid[0] = False
# height_dict[0][1].append((i,j))
# positions.remove((i,j))
# area[0] += 1
# self.dfs(i + 1, j, cur_height, heights, valid, area, step, positions, height_dict)
# self.dfs(i - 1, j, cur_height, heights, valid, area, step, positions, height_dict)
# self.dfs(i, j + 1, cur_height, heights, valid, area, step, positions, height_dict)
# self.dfs(i, j - 1, cur_height, heights, valid, area, step, positions, height_dict)
|
class Solution:
"""
@param heights: a matrix of integers
@return: an integer
"""
def trap_rain_water(self, heights):
"""
:type heightMap: List[List[int]]
:rtype: int
"""
m = len(heights)
n = len(heights[0]) if m else 0
peak_map = [[2147483647] * n for _ in range(m)]
q = []
for x in range(m):
for y in range(n):
if x in (0, m - 1) or y in (0, n - 1):
peakMap[x][y] = heights[x][y]
q.append((x, y))
while q:
(x, y) = q.pop(0)
for (dx, dy) in zip((1, 0, -1, 0), (0, 1, 0, -1)):
(nx, ny) = (x + dx, y + dy)
if nx <= 0 or nx >= m - 1 or ny <= 0 or (ny >= n - 1):
continue
limit = max(peakMap[x][y], heights[nx][ny])
if peakMap[nx][ny] > limit:
peakMap[nx][ny] = limit
q.append((nx, ny))
return sum((peakMap[x][y] - heights[x][y] for x in range(m) for y in range(n)))
|
def add_two(a, b):
'''Adds two numbers together'''
return a + b
def multiply_two(a, b):
'''Multiplies two numbers together'''
return a * b
|
def add_two(a, b):
"""Adds two numbers together"""
return a + b
def multiply_two(a, b):
"""Multiplies two numbers together"""
return a * b
|
# # example string
# string = 'cat'
# width = 5
# print right justified string
# print(string.rjust(width))
# print(string.rjust(width))
# # example string
# string = 'cat'
# width = 5
# fillchar = '*'
# # print right justified string
# print(string.rjust(width, fillchar))
# # .centre function
# string = "Python is awesome"
# new_string = string.center(24)
# print(string.center(24))
# print("Centered String: ", new_string)
# print(new_string)
# s = input()
# list1 = [word.capitalize() for word in s.split(' ')]
# a = ' '.join(list1)
# print(a)
# print(list1)
size = 5
a = list(map(chr, range(97, 122)))
m = a[size-1::-1] + a[:size]
print(m)
|
size = 5
a = list(map(chr, range(97, 122)))
m = a[size - 1::-1] + a[:size]
print(m)
|
"""
In a binary tree, the root node is at depth 0, and children of each depth k node are at depth k+1.
Two nodes of a binary tree are cousins if they have the same depth, but have different parents.
We are given the root of a binary tree with unique values, and the values x and y of two different nodes in the tree.
Return true if and only if the nodes corresponding to the values x and y are cousins.
Example 1:
Input: root = [1,2,3,4], x = 4, y = 3
Output: false
Example 2:
Input: root = [1,2,3,null,4,null,5], x = 5, y = 4
Output: true
Example 3:
Input: root = [1,2,3,null,4], x = 2, y = 3
Output: false
Note:
The number of nodes in the tree will be between 2 and 100.
Each node has a unique integer value from 1 to 100.
"""
# 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 isCousins(self, root: TreeNode, x: int, y: int) -> bool:
def check(node, mom, x, level):
if not node:
return
if node.val == x:
print (mom, level)
return [mom, level]
return check(node.left, node, x, level+1) or check(node.right, node, x, level+1)
i = check(root, None, x, 0)
j = check(root, None, y, 0)
if i[0] != j[0] and i[1]==j[1]:
return True
return False
|
"""
In a binary tree, the root node is at depth 0, and children of each depth k node are at depth k+1.
Two nodes of a binary tree are cousins if they have the same depth, but have different parents.
We are given the root of a binary tree with unique values, and the values x and y of two different nodes in the tree.
Return true if and only if the nodes corresponding to the values x and y are cousins.
Example 1:
Input: root = [1,2,3,4], x = 4, y = 3
Output: false
Example 2:
Input: root = [1,2,3,null,4,null,5], x = 5, y = 4
Output: true
Example 3:
Input: root = [1,2,3,null,4], x = 2, y = 3
Output: false
Note:
The number of nodes in the tree will be between 2 and 100.
Each node has a unique integer value from 1 to 100.
"""
class Solution:
def is_cousins(self, root: TreeNode, x: int, y: int) -> bool:
def check(node, mom, x, level):
if not node:
return
if node.val == x:
print(mom, level)
return [mom, level]
return check(node.left, node, x, level + 1) or check(node.right, node, x, level + 1)
i = check(root, None, x, 0)
j = check(root, None, y, 0)
if i[0] != j[0] and i[1] == j[1]:
return True
return False
|
def test_use_provider(accounts, networks):
with networks.fantom.local.use_provider("test"):
account = accounts.test_accounts[0]
account.transfer(account, 100)
|
def test_use_provider(accounts, networks):
with networks.fantom.local.use_provider('test'):
account = accounts.test_accounts[0]
account.transfer(account, 100)
|
class Field(object):
def render(self, field):
raise NotImplementedError('Field.render needs to be defined')
class Attr(Field):
def __init__(self, attr, default=None, type=None):
self.attr = attr
self.default = default
if type is None:
self.type = lambda x: x
else:
self.type = type
def render(self, field):
try:
x = field
for attr in self.attr.split('.'):
x = getattr(x, attr)
return self.type(x)
except AttributeError:
return self.default
class Name(Field):
def render(self, field):
return field.__name__.replace('__', '.')
class Func(Field):
def __init__(self, func):
self.func = func
def render(self, field):
return self.func(field)
class Literal(Field):
def __init__(self, value):
self.value = value
def render(self, *args, **kwargs):
return self.value
|
class Field(object):
def render(self, field):
raise not_implemented_error('Field.render needs to be defined')
class Attr(Field):
def __init__(self, attr, default=None, type=None):
self.attr = attr
self.default = default
if type is None:
self.type = lambda x: x
else:
self.type = type
def render(self, field):
try:
x = field
for attr in self.attr.split('.'):
x = getattr(x, attr)
return self.type(x)
except AttributeError:
return self.default
class Name(Field):
def render(self, field):
return field.__name__.replace('__', '.')
class Func(Field):
def __init__(self, func):
self.func = func
def render(self, field):
return self.func(field)
class Literal(Field):
def __init__(self, value):
self.value = value
def render(self, *args, **kwargs):
return self.value
|
def set_elements_sum(a, b):
c = []
for i in range(len(a)):
result = a[i] + b[i]
c.append(result)
return c
ll = [1, 2, 3, 4, 5]
ll2 = [3, 4, 5, 6, 7]
print(set_elements_sum(ll, ll2))
# [4, 6, 8, 10, 12]
|
def set_elements_sum(a, b):
c = []
for i in range(len(a)):
result = a[i] + b[i]
c.append(result)
return c
ll = [1, 2, 3, 4, 5]
ll2 = [3, 4, 5, 6, 7]
print(set_elements_sum(ll, ll2))
|
# URI Online Judge 1133
X = int(input())
Y = int(input())
soma = 0
if Y < X:
X, Y = Y, X
for i in range(X,Y+1):
if i%13!=0:
soma += i
print(soma)
|
x = int(input())
y = int(input())
soma = 0
if Y < X:
(x, y) = (Y, X)
for i in range(X, Y + 1):
if i % 13 != 0:
soma += i
print(soma)
|
salario = float(input())
if (salario >= 0 and salario <= 2000.00):
print('Isento')
elif (salario >= 2000.01 and salario <= 3000.00):
resto = salario - 2000
resul = resto * 0.08
print('R$ {:.2f}'.format(resul))
elif (salario >= 3000.01 and salario <= 4500.00):
resto = salario - 3000
resul = (resto * 0.18) + (1000 * 0.08)
print('R$ {:.2f}'.format(resul))
elif (salario > 4500.00):
resto = salario - 4500
resul = (resto * 0.28) + (1500 * 0.18) + (1000 * 0.08)
print('R$ {:.2f}'.format(resul))
|
salario = float(input())
if salario >= 0 and salario <= 2000.0:
print('Isento')
elif salario >= 2000.01 and salario <= 3000.0:
resto = salario - 2000
resul = resto * 0.08
print('R$ {:.2f}'.format(resul))
elif salario >= 3000.01 and salario <= 4500.0:
resto = salario - 3000
resul = resto * 0.18 + 1000 * 0.08
print('R$ {:.2f}'.format(resul))
elif salario > 4500.0:
resto = salario - 4500
resul = resto * 0.28 + 1500 * 0.18 + 1000 * 0.08
print('R$ {:.2f}'.format(resul))
|
for i in range(int(input())):
a, b, c = map(int, input().split())
mi = min(a, b)
ma = max(a, b)
half_circle_people = (ma - mi)
full_circle_people = 2 * half_circle_people
if ma > half_circle_people * 2 or c > full_circle_people:
print(-1)
else:
print((c - half_circle_people - 1) % full_circle_people + 1)
|
for i in range(int(input())):
(a, b, c) = map(int, input().split())
mi = min(a, b)
ma = max(a, b)
half_circle_people = ma - mi
full_circle_people = 2 * half_circle_people
if ma > half_circle_people * 2 or c > full_circle_people:
print(-1)
else:
print((c - half_circle_people - 1) % full_circle_people + 1)
|
# model settings
model = dict(
type='Recognizer3DRPL',
backbone=dict(
type='ResNet3dSlowOnly',
depth=50,
pretrained='torchvision://resnet50',
lateral=False,
out_indices=(2, 3),
conv1_kernel=(1, 7, 7),
conv1_stride_t=1,
pool1_stride_t=1,
inflate=(0, 0, 1, 1),
norm_eval=False),
neck=dict(
type='TPN',
in_channels=(1024, 2048),
out_channels=1024,
spatial_modulation_cfg=dict(
in_channels=(1024, 2048), out_channels=2048),
temporal_modulation_cfg=dict(downsample_scales=(8, 8)),
upsample_cfg=dict(scale_factor=(1, 1, 1)),
downsample_cfg=dict(downsample_scale=(1, 1, 1)),
level_fusion_cfg=dict(
in_channels=(1024, 1024),
mid_channels=(1024, 1024),
out_channels=2048,
downsample_scales=((1, 1, 1), (1, 1, 1)))),
cls_head=dict(
type='TPNRPLHead',
loss_cls=dict(type='RPLoss',
temperature=1,
weight_pl=0.1),
num_classes=101,
in_channels=2048,
spatial_type='avg',
consensus=dict(type='AvgConsensus', dim=1),
dropout_ratio=0.5,
init_std=0.01))
evidence='exp' # only used for EDL
test_cfg = dict(average_clips='prob')
dataset_type = 'VideoDataset'
img_norm_cfg = dict(
mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_bgr=False)
test_pipeline = [
dict(type='OpenCVInit', num_threads=1),
dict(
type='SampleFrames',
clip_len=8,
frame_interval=8,
num_clips=10,
test_mode=True),
dict(type='OpenCVDecode'),
dict(type='Resize', scale=(-1, 256)),
dict(type='ThreeCrop', crop_size=256),
dict(type='Normalize', **img_norm_cfg),
dict(type='FormatShape', input_format='NCTHW'),
dict(type='Collect', keys=['imgs', 'label'], meta_keys=[]),
dict(type='ToTensor', keys=['imgs'])
]
data = dict(
videos_per_gpu=2,
workers_per_gpu=2,
test=dict(
type=dataset_type,
ann_file=None,
data_prefix=None,
pipeline=test_pipeline))
|
model = dict(type='Recognizer3DRPL', backbone=dict(type='ResNet3dSlowOnly', depth=50, pretrained='torchvision://resnet50', lateral=False, out_indices=(2, 3), conv1_kernel=(1, 7, 7), conv1_stride_t=1, pool1_stride_t=1, inflate=(0, 0, 1, 1), norm_eval=False), neck=dict(type='TPN', in_channels=(1024, 2048), out_channels=1024, spatial_modulation_cfg=dict(in_channels=(1024, 2048), out_channels=2048), temporal_modulation_cfg=dict(downsample_scales=(8, 8)), upsample_cfg=dict(scale_factor=(1, 1, 1)), downsample_cfg=dict(downsample_scale=(1, 1, 1)), level_fusion_cfg=dict(in_channels=(1024, 1024), mid_channels=(1024, 1024), out_channels=2048, downsample_scales=((1, 1, 1), (1, 1, 1)))), cls_head=dict(type='TPNRPLHead', loss_cls=dict(type='RPLoss', temperature=1, weight_pl=0.1), num_classes=101, in_channels=2048, spatial_type='avg', consensus=dict(type='AvgConsensus', dim=1), dropout_ratio=0.5, init_std=0.01))
evidence = 'exp'
test_cfg = dict(average_clips='prob')
dataset_type = 'VideoDataset'
img_norm_cfg = dict(mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_bgr=False)
test_pipeline = [dict(type='OpenCVInit', num_threads=1), dict(type='SampleFrames', clip_len=8, frame_interval=8, num_clips=10, test_mode=True), dict(type='OpenCVDecode'), dict(type='Resize', scale=(-1, 256)), dict(type='ThreeCrop', crop_size=256), dict(type='Normalize', **img_norm_cfg), dict(type='FormatShape', input_format='NCTHW'), dict(type='Collect', keys=['imgs', 'label'], meta_keys=[]), dict(type='ToTensor', keys=['imgs'])]
data = dict(videos_per_gpu=2, workers_per_gpu=2, test=dict(type=dataset_type, ann_file=None, data_prefix=None, pipeline=test_pipeline))
|
def make_divider():
return {"type": "divider"}
def make_markdown(text):
return {"type": "mrkdwn", "text": text }
def make_section(text):
return {"type":"section", "text": make_markdown(text)}
def make_context(*args):
return {"type":"context", "elements": [*args]}
def make_blocks(*args):
return [*args]
|
def make_divider():
return {'type': 'divider'}
def make_markdown(text):
return {'type': 'mrkdwn', 'text': text}
def make_section(text):
return {'type': 'section', 'text': make_markdown(text)}
def make_context(*args):
return {'type': 'context', 'elements': [*args]}
def make_blocks(*args):
return [*args]
|
# generated from catkin/cmake/template/pkg.context.pc.in
CATKIN_PACKAGE_PREFIX = ""
PROJECT_PKG_CONFIG_INCLUDE_DIRS = "/home/nvidia/linorobot_ws/src/imu_calib/include;/usr/local/include/eigen3".split(';') if "/home/nvidia/linorobot_ws/src/imu_calib/include;/usr/local/include/eigen3" != "" else []
PROJECT_CATKIN_DEPENDS = "cmake_modules;roscpp;sensor_msgs;lino_msgs".replace(';', ' ')
PKG_CONFIG_LIBRARIES_WITH_PREFIX = "-laccel_calib".split(';') if "-laccel_calib" != "" else []
PROJECT_NAME = "imu_calib"
PROJECT_SPACE_DIR = "/home/nvidia/linorobot_ws/devel"
PROJECT_VERSION = "0.0.0"
|
catkin_package_prefix = ''
project_pkg_config_include_dirs = '/home/nvidia/linorobot_ws/src/imu_calib/include;/usr/local/include/eigen3'.split(';') if '/home/nvidia/linorobot_ws/src/imu_calib/include;/usr/local/include/eigen3' != '' else []
project_catkin_depends = 'cmake_modules;roscpp;sensor_msgs;lino_msgs'.replace(';', ' ')
pkg_config_libraries_with_prefix = '-laccel_calib'.split(';') if '-laccel_calib' != '' else []
project_name = 'imu_calib'
project_space_dir = '/home/nvidia/linorobot_ws/devel'
project_version = '0.0.0'
|
numero = int(input("Entre com um numero inteiro e menor que 1000: "))
if numero > 1000:
print("Numero invalido")
else:
unidade = numero % 10
numero = (numero - unidade) / 10
dezena = int(numero % 10)
numero = (numero - dezena) / 10
centena = int(numero)
print(f"{centena} centena(s) , {dezena} dezena(s) e {unidade} unidade(s)")
|
numero = int(input('Entre com um numero inteiro e menor que 1000: '))
if numero > 1000:
print('Numero invalido')
else:
unidade = numero % 10
numero = (numero - unidade) / 10
dezena = int(numero % 10)
numero = (numero - dezena) / 10
centena = int(numero)
print(f'{centena} centena(s) , {dezena} dezena(s) e {unidade} unidade(s)')
|
def str_to_bool(s):
if isinstance(s, bool): # do not convert if already a boolean
return s
else:
if s == 'True' \
or s == 'true' \
or s == '1' \
or s == 1 \
or s == True:
return True
elif s == 'False' \
or s == 'false' \
or s == '0' \
or s == 0 \
or s == False:
return False
return False
|
def str_to_bool(s):
if isinstance(s, bool):
return s
elif s == 'True' or s == 'true' or s == '1' or (s == 1) or (s == True):
return True
elif s == 'False' or s == 'false' or s == '0' or (s == 0) or (s == False):
return False
return False
|
"""Version
==========
"""
__version__ = "0.4.0"
|
"""Version
==========
"""
__version__ = '0.4.0'
|
class Solution:
def compareVersion(self, version1: str, version2: str) -> int:
ver1 = version1.split('.')
ver2 = version2.split('.')
def removeLeadingZeros(s):
while len(s) > 1 and s[0] == '0':
s = s[1:]
return s
ver1 = [removeLeadingZeros(ver1[i]) for i in range(len(ver1))]
ver2 = [removeLeadingZeros(ver2[i]) for i in range(len(ver2))]
i = 0
while i < max(len(ver1), len(ver2)):
v1 = ver1[i] if i < len(ver1) else 0
v2 = ver2[i] if i < len(ver2) else 0
i += 1
if int(v1) > int(v2): return 1
if int(v1) < int(v2): return -1
return 0
|
class Solution:
def compare_version(self, version1: str, version2: str) -> int:
ver1 = version1.split('.')
ver2 = version2.split('.')
def remove_leading_zeros(s):
while len(s) > 1 and s[0] == '0':
s = s[1:]
return s
ver1 = [remove_leading_zeros(ver1[i]) for i in range(len(ver1))]
ver2 = [remove_leading_zeros(ver2[i]) for i in range(len(ver2))]
i = 0
while i < max(len(ver1), len(ver2)):
v1 = ver1[i] if i < len(ver1) else 0
v2 = ver2[i] if i < len(ver2) else 0
i += 1
if int(v1) > int(v2):
return 1
if int(v1) < int(v2):
return -1
return 0
|
GUIDs = {
"ASROCK_ACPIS4_DXE_GUID": [69196166, 45078, 18382, 175, 197, 34, 105, 237, 212, 173, 100],
"ASROCK_USBRT_GUID": [82487969, 10657, 4567, 136, 56, 0, 80, 4, 115, 212, 235],
"ASROCK_RAID_SETUP_GUID": [152494882, 14144, 12750, 173, 98, 189, 23, 44, 236, 202, 54],
"ASROCK_RAID_LOADER_GUID": [164506669, 19843, 17592, 151, 208, 16, 133, 235, 84, 144, 184],
"ASROCK_SIOSLPSMI_GUID": [204970154, 53806, 19926, 140, 180, 60, 156, 251, 29, 134, 211],
"ASROCK_PLEDDXE_GUID": [260599413, 12329, 20175, 182, 148, 34, 137, 77, 63, 33, 67],
"ASROCK_A_DEFAULT_DXE_GUID": [303480106, 49246, 19565, 145, 231, 235, 142, 55, 173, 59, 122],
"ASROCK_USER_DEF_SETUP_DXE_GUID": [321832763, 48422, 20415, 177, 147, 138, 203, 80, 239, 189, 137],
"ASROCK_WAKEUP_CTRL_SMM_GUID": [460234064, 4836, 19285, 129, 217, 26, 191, 236, 89, 212, 252],
"ASROCK_AMI_AGESA_DXE_GUID": [503020538, 49038, 19729, 151, 102, 47, 176, 208, 68, 35, 16],
"ASROCK_HDD_READY_SMI_GUID": [560462180, 29336, 19087, 154, 42, 191, 228, 152, 214, 0, 168],
"ASROCK_MOUSE_DRIVER_GUID": [719032155, 51156, 20094, 190, 42, 35, 99, 77, 246, 104, 161],
"ASROCK_IDESMM_GUID": [829100592, 1280, 17810, 140, 9, 234, 186, 15, 182, 176, 127],
"ASROCK_BFGSMI_GUID": [978522445, 22131, 19929, 181, 179, 203, 114, 195, 71, 102, 155],
"ASROCK_ASRLOGODXE_GUID": [1033880909, 6629, 19152, 185, 134, 2, 214, 135, 215, 96, 229],
"ASROCK_ASM104_X_DXE_GUID": [1080004582, 21011, 19333, 184, 33, 151, 183, 122, 255, 121, 91],
"ASROCK_HDAUDIO_SMI_GUID": [1254707048, 58961, 19256, 161, 216, 45, 93, 239, 250, 15, 96],
"ASROCK_SM_BUS_DXE_GUID": [1265110573, 3427, 20322, 185, 48, 122, 233, 149, 185, 179, 163],
"ASROCK_USBINT13_GUID": [1275096281, 6586, 17943, 132, 131, 96, 145, 148, 161, 172, 252],
"ASROCK_SLP_SUPPORT_GUID": [1279872597, 22601, 21314, 69, 84, 84, 69, 82, 33, 33, 33],
"ASROCK_PATA_CONTROLLER_GUID": [1334921163, 38702, 20316, 184, 105, 160, 33, 130, 201, 217, 60],
"ASROCK_SATA_CONTROLLER_GUID": [1359869601, 46785, 18760, 174, 231, 89, 242, 32, 248, 152, 189],
"ASROCK_ACPIS4_SMM_GUID": [1368992111, 10248, 19194, 148, 196, 153, 246, 176, 108, 135, 30],
"ASROCK_POST_REPORT_GUID": [1413923475, 13211, 18381, 183, 25, 88, 93, 227, 148, 8, 204],
"ASROCK_CLOCK_GEN_DXE_GUID": [1447053695, 25694, 17937, 185, 21, 230, 130, 200, 189, 71, 131],
"ASROCK_UHCD_GUID": [1477302528, 14429, 4567, 136, 58, 0, 80, 4, 115, 212, 235],
"ASROCK_LEGACY_REGION_GUID": [1495543256, 59343, 18809, 182, 14, 166, 6, 126, 42, 24, 95],
"ASROCK_SLEEP_SMI_GUID": [1654193688, 54767, 17079, 187, 12, 41, 83, 40, 63, 87, 4],
"ASROCK_CMOS_MANAGER_SMM_GUID": [1751762355, 44173, 18803, 139, 55, 227, 84, 219, 243, 74, 221],
"ASROCK_AMD_AGESA_DXE_DRIVER_GUID": [1766895615, 28387, 4573, 173, 139, 8, 0, 32, 12, 154, 102],
"ASROCK_RE_FLASH_GUID": [1893836824, 3041, 17481, 191, 212, 158, 246, 140, 127, 2, 168],
"ASROCK_LEGACY_INTERRUPT_GUID": [1911362257, 9483, 17147, 140, 23, 16, 220, 250, 119, 23, 1],
"ASROCK_SMM_CHILD_DISPATCHER_GUID": [1966485705, 64229, 18345, 187, 191, 136, 214, 33, 205, 114, 130],
"ASROCK_BFGDXE_GUID": [1988600983, 65358, 18687, 188, 170, 103, 219, 246, 92, 66, 209],
"ASROCK_IFLASHSETUP_GUID": [2011543064, 9746, 19496, 188, 223, 162, 177, 77, 138, 62, 254],
"ASROCK_S4_SLEEPDELAY_GUID": [2075935011, 23902, 19484, 149, 209, 48, 235, 164, 135, 1, 202],
"ASROCK_HDD_READY_DXE_GUID": [2179248970, 9868, 20428, 142, 57, 28, 29, 62, 111, 110, 105],
"ASROCK_RTLANDXE_GUID": [2332955475, 13708, 20015, 147, 69, 238, 191, 29, 171, 152, 155],
"ASROCK_AMD_SB900_DXE_GUID": [2333274783, 28981, 20139, 175, 218, 5, 18, 247, 75, 101, 234],
"ASROCK_SB900_SMBUS_LIGHT_GUID": [2551896525, 34437, 19115, 175, 218, 5, 18, 247, 75, 101, 234],
"ASROCK_AAFTBL_SMI_GUID": [2667102838, 46054, 19161, 143, 231, 199, 79, 113, 196, 114, 72],
"ASROCK_NVRAMID_GUID": [2708185858, 25876, 17031, 190, 227, 98, 35, 183, 222, 44, 33],
"ASROCK_IDE_SECURITY_GUID": [2847342799, 414, 19851, 163, 167, 136, 225, 234, 1, 105, 158],
"ASROCK_ASM1061_DXE_GUID": [2848876245, 27959, 17694, 169, 191, 245, 143, 122, 11, 60, 194],
"ASROCK_ASM104_X_SMI_GUID": [2904508538, 47702, 18652, 142, 170, 232, 251, 234, 116, 184, 242],
"ASROCK_RTLANSMI_GUID": [3005543067, 24215, 19449, 180, 224, 81, 37, 193, 246, 5, 213],
"ASROCK_GEC_UPDATE_SMI_GUID": [3092850716, 5882, 17832, 146, 1, 28, 56, 48, 169, 115, 189],
"ASROCK_APMOFF_GUID": [3146872289, 16021, 19326, 135, 80, 157, 106, 163, 78, 183, 246],
"ASROCK_SMIFLASH_GUID": [3157425597, 47490, 20309, 159, 121, 5, 106, 215, 233, 135, 197],
"ASROCK_RAID_X64_GUID": [3295196034, 17744, 18697, 173, 87, 36, 150, 20, 27, 63, 74],
"ASROCK_AMD_SB900_SMM_GUID": [3351810409, 6722, 20062, 179, 75, 230, 131, 6, 113, 201, 166],
"ASROCK_FIREWIRE_GUID": [3367390790, 38937, 17835, 135, 93, 9, 223, 218, 109, 139, 27],
"ASROCK_IDE_SMART_GUID": [3581707566, 32927, 17871, 163, 119, 215, 123, 192, 203, 120, 238],
"ASROCK_SB_INTERFACE_DXE_GUID": [3622218689, 38683, 17947, 181, 228, 60, 55, 102, 38, 122, 217],
"ASROCK_AMD_SB900_SMM_DISPATCHER_GUID": [3748899802, 31298, 20062, 179, 75, 230, 131, 6, 113, 201, 166],
"ASROCK_AMDCPU_DXE_GUID": [3786566962, 16719, 18139, 154, 238, 66, 0, 119, 243, 93, 190],
"ASROCK_SMBIOS_DMIEDIT_GUID": [3802613560, 35124, 18677, 132, 18, 153, 233, 72, 200, 220, 27],
"ASROCK_SECURITY_SELECT_DXE_GUID": [3832130086, 37480, 20144, 160, 135, 221, 76, 238, 55, 64, 75],
"ASROCK_FILE_EXPLORER_LITE_GUID": [3875982164, 33976, 16573, 131, 47, 127, 178, 213, 203, 135, 179],
"ASROCK_PLEDSMM_GUID": [3911953940, 15869, 19568, 159, 230, 56, 153, 243, 108, 120, 70],
"ASROCK_CPU_SMBIOS_DRIVER_GUID": [3930959592, 43089, 19103, 171, 244, 183, 159, 162, 82, 130, 145],
"ASROCK_AAFTBL_DXE_GUID": [4279363330, 35107, 18380, 173, 48, 217, 224, 226, 64, 221, 16],
}
|
gui_ds = {'ASROCK_ACPIS4_DXE_GUID': [69196166, 45078, 18382, 175, 197, 34, 105, 237, 212, 173, 100], 'ASROCK_USBRT_GUID': [82487969, 10657, 4567, 136, 56, 0, 80, 4, 115, 212, 235], 'ASROCK_RAID_SETUP_GUID': [152494882, 14144, 12750, 173, 98, 189, 23, 44, 236, 202, 54], 'ASROCK_RAID_LOADER_GUID': [164506669, 19843, 17592, 151, 208, 16, 133, 235, 84, 144, 184], 'ASROCK_SIOSLPSMI_GUID': [204970154, 53806, 19926, 140, 180, 60, 156, 251, 29, 134, 211], 'ASROCK_PLEDDXE_GUID': [260599413, 12329, 20175, 182, 148, 34, 137, 77, 63, 33, 67], 'ASROCK_A_DEFAULT_DXE_GUID': [303480106, 49246, 19565, 145, 231, 235, 142, 55, 173, 59, 122], 'ASROCK_USER_DEF_SETUP_DXE_GUID': [321832763, 48422, 20415, 177, 147, 138, 203, 80, 239, 189, 137], 'ASROCK_WAKEUP_CTRL_SMM_GUID': [460234064, 4836, 19285, 129, 217, 26, 191, 236, 89, 212, 252], 'ASROCK_AMI_AGESA_DXE_GUID': [503020538, 49038, 19729, 151, 102, 47, 176, 208, 68, 35, 16], 'ASROCK_HDD_READY_SMI_GUID': [560462180, 29336, 19087, 154, 42, 191, 228, 152, 214, 0, 168], 'ASROCK_MOUSE_DRIVER_GUID': [719032155, 51156, 20094, 190, 42, 35, 99, 77, 246, 104, 161], 'ASROCK_IDESMM_GUID': [829100592, 1280, 17810, 140, 9, 234, 186, 15, 182, 176, 127], 'ASROCK_BFGSMI_GUID': [978522445, 22131, 19929, 181, 179, 203, 114, 195, 71, 102, 155], 'ASROCK_ASRLOGODXE_GUID': [1033880909, 6629, 19152, 185, 134, 2, 214, 135, 215, 96, 229], 'ASROCK_ASM104_X_DXE_GUID': [1080004582, 21011, 19333, 184, 33, 151, 183, 122, 255, 121, 91], 'ASROCK_HDAUDIO_SMI_GUID': [1254707048, 58961, 19256, 161, 216, 45, 93, 239, 250, 15, 96], 'ASROCK_SM_BUS_DXE_GUID': [1265110573, 3427, 20322, 185, 48, 122, 233, 149, 185, 179, 163], 'ASROCK_USBINT13_GUID': [1275096281, 6586, 17943, 132, 131, 96, 145, 148, 161, 172, 252], 'ASROCK_SLP_SUPPORT_GUID': [1279872597, 22601, 21314, 69, 84, 84, 69, 82, 33, 33, 33], 'ASROCK_PATA_CONTROLLER_GUID': [1334921163, 38702, 20316, 184, 105, 160, 33, 130, 201, 217, 60], 'ASROCK_SATA_CONTROLLER_GUID': [1359869601, 46785, 18760, 174, 231, 89, 242, 32, 248, 152, 189], 'ASROCK_ACPIS4_SMM_GUID': [1368992111, 10248, 19194, 148, 196, 153, 246, 176, 108, 135, 30], 'ASROCK_POST_REPORT_GUID': [1413923475, 13211, 18381, 183, 25, 88, 93, 227, 148, 8, 204], 'ASROCK_CLOCK_GEN_DXE_GUID': [1447053695, 25694, 17937, 185, 21, 230, 130, 200, 189, 71, 131], 'ASROCK_UHCD_GUID': [1477302528, 14429, 4567, 136, 58, 0, 80, 4, 115, 212, 235], 'ASROCK_LEGACY_REGION_GUID': [1495543256, 59343, 18809, 182, 14, 166, 6, 126, 42, 24, 95], 'ASROCK_SLEEP_SMI_GUID': [1654193688, 54767, 17079, 187, 12, 41, 83, 40, 63, 87, 4], 'ASROCK_CMOS_MANAGER_SMM_GUID': [1751762355, 44173, 18803, 139, 55, 227, 84, 219, 243, 74, 221], 'ASROCK_AMD_AGESA_DXE_DRIVER_GUID': [1766895615, 28387, 4573, 173, 139, 8, 0, 32, 12, 154, 102], 'ASROCK_RE_FLASH_GUID': [1893836824, 3041, 17481, 191, 212, 158, 246, 140, 127, 2, 168], 'ASROCK_LEGACY_INTERRUPT_GUID': [1911362257, 9483, 17147, 140, 23, 16, 220, 250, 119, 23, 1], 'ASROCK_SMM_CHILD_DISPATCHER_GUID': [1966485705, 64229, 18345, 187, 191, 136, 214, 33, 205, 114, 130], 'ASROCK_BFGDXE_GUID': [1988600983, 65358, 18687, 188, 170, 103, 219, 246, 92, 66, 209], 'ASROCK_IFLASHSETUP_GUID': [2011543064, 9746, 19496, 188, 223, 162, 177, 77, 138, 62, 254], 'ASROCK_S4_SLEEPDELAY_GUID': [2075935011, 23902, 19484, 149, 209, 48, 235, 164, 135, 1, 202], 'ASROCK_HDD_READY_DXE_GUID': [2179248970, 9868, 20428, 142, 57, 28, 29, 62, 111, 110, 105], 'ASROCK_RTLANDXE_GUID': [2332955475, 13708, 20015, 147, 69, 238, 191, 29, 171, 152, 155], 'ASROCK_AMD_SB900_DXE_GUID': [2333274783, 28981, 20139, 175, 218, 5, 18, 247, 75, 101, 234], 'ASROCK_SB900_SMBUS_LIGHT_GUID': [2551896525, 34437, 19115, 175, 218, 5, 18, 247, 75, 101, 234], 'ASROCK_AAFTBL_SMI_GUID': [2667102838, 46054, 19161, 143, 231, 199, 79, 113, 196, 114, 72], 'ASROCK_NVRAMID_GUID': [2708185858, 25876, 17031, 190, 227, 98, 35, 183, 222, 44, 33], 'ASROCK_IDE_SECURITY_GUID': [2847342799, 414, 19851, 163, 167, 136, 225, 234, 1, 105, 158], 'ASROCK_ASM1061_DXE_GUID': [2848876245, 27959, 17694, 169, 191, 245, 143, 122, 11, 60, 194], 'ASROCK_ASM104_X_SMI_GUID': [2904508538, 47702, 18652, 142, 170, 232, 251, 234, 116, 184, 242], 'ASROCK_RTLANSMI_GUID': [3005543067, 24215, 19449, 180, 224, 81, 37, 193, 246, 5, 213], 'ASROCK_GEC_UPDATE_SMI_GUID': [3092850716, 5882, 17832, 146, 1, 28, 56, 48, 169, 115, 189], 'ASROCK_APMOFF_GUID': [3146872289, 16021, 19326, 135, 80, 157, 106, 163, 78, 183, 246], 'ASROCK_SMIFLASH_GUID': [3157425597, 47490, 20309, 159, 121, 5, 106, 215, 233, 135, 197], 'ASROCK_RAID_X64_GUID': [3295196034, 17744, 18697, 173, 87, 36, 150, 20, 27, 63, 74], 'ASROCK_AMD_SB900_SMM_GUID': [3351810409, 6722, 20062, 179, 75, 230, 131, 6, 113, 201, 166], 'ASROCK_FIREWIRE_GUID': [3367390790, 38937, 17835, 135, 93, 9, 223, 218, 109, 139, 27], 'ASROCK_IDE_SMART_GUID': [3581707566, 32927, 17871, 163, 119, 215, 123, 192, 203, 120, 238], 'ASROCK_SB_INTERFACE_DXE_GUID': [3622218689, 38683, 17947, 181, 228, 60, 55, 102, 38, 122, 217], 'ASROCK_AMD_SB900_SMM_DISPATCHER_GUID': [3748899802, 31298, 20062, 179, 75, 230, 131, 6, 113, 201, 166], 'ASROCK_AMDCPU_DXE_GUID': [3786566962, 16719, 18139, 154, 238, 66, 0, 119, 243, 93, 190], 'ASROCK_SMBIOS_DMIEDIT_GUID': [3802613560, 35124, 18677, 132, 18, 153, 233, 72, 200, 220, 27], 'ASROCK_SECURITY_SELECT_DXE_GUID': [3832130086, 37480, 20144, 160, 135, 221, 76, 238, 55, 64, 75], 'ASROCK_FILE_EXPLORER_LITE_GUID': [3875982164, 33976, 16573, 131, 47, 127, 178, 213, 203, 135, 179], 'ASROCK_PLEDSMM_GUID': [3911953940, 15869, 19568, 159, 230, 56, 153, 243, 108, 120, 70], 'ASROCK_CPU_SMBIOS_DRIVER_GUID': [3930959592, 43089, 19103, 171, 244, 183, 159, 162, 82, 130, 145], 'ASROCK_AAFTBL_DXE_GUID': [4279363330, 35107, 18380, 173, 48, 217, 224, 226, 64, 221, 16]}
|
"""
General unit tests
"""
class TestClass:
def test_base(self):
assert 42 == 42
|
"""
General unit tests
"""
class Testclass:
def test_base(self):
assert 42 == 42
|
'''
Python program to convert the distance (in feet) to inches,yards, and miles
'''
def distanceInInches (d_ft):
print("The distance in inches is %i inches." %(d_ft * 12))
def distanceInYard (d_ft):
print("The distance in yards is %.2f yards." %(d_ft / 3.0))
def distanceInMiles (d_ft):
print("The distance in miles is %.2f miles." %(d_ft / 5280.0) )
def main ():
d_ft = int(input("Input distance in feet: "))
distanceInInches (d_ft)
distanceInYard (d_ft)
distanceInMiles (d_ft)
main()
|
"""
Python program to convert the distance (in feet) to inches,yards, and miles
"""
def distance_in_inches(d_ft):
print('The distance in inches is %i inches.' % (d_ft * 12))
def distance_in_yard(d_ft):
print('The distance in yards is %.2f yards.' % (d_ft / 3.0))
def distance_in_miles(d_ft):
print('The distance in miles is %.2f miles.' % (d_ft / 5280.0))
def main():
d_ft = int(input('Input distance in feet: '))
distance_in_inches(d_ft)
distance_in_yard(d_ft)
distance_in_miles(d_ft)
main()
|
def somme(liste_nombres):
pass
def moyenne(liste_nombres):
pass
|
def somme(liste_nombres):
pass
def moyenne(liste_nombres):
pass
|
class Solution:
def solve(self, genes):
ans = 0
seen = set()
genes = set(genes)
for gene in genes:
if gene in seen:
continue
ans += 1
dfs = [gene]
seen.add(gene)
while dfs:
cur = dfs.pop()
cur_list = list(cur)
for i in range(len(cur)):
for char in ["A","C","G","T"]:
if char == cur[i]: continue
cur_list[i] = char
new_gene = "".join(cur_list)
if new_gene in genes and new_gene not in seen:
seen.add(new_gene)
dfs.append(new_gene)
cur_list[i] = cur[i]
return ans
|
class Solution:
def solve(self, genes):
ans = 0
seen = set()
genes = set(genes)
for gene in genes:
if gene in seen:
continue
ans += 1
dfs = [gene]
seen.add(gene)
while dfs:
cur = dfs.pop()
cur_list = list(cur)
for i in range(len(cur)):
for char in ['A', 'C', 'G', 'T']:
if char == cur[i]:
continue
cur_list[i] = char
new_gene = ''.join(cur_list)
if new_gene in genes and new_gene not in seen:
seen.add(new_gene)
dfs.append(new_gene)
cur_list[i] = cur[i]
return ans
|
def title1(content):
return "<h1 class='display-1'>{}</h1>".format(content)
def title2(content):
return "<h2 class='display-2'>{}</h2>".format(content)
def title3(content):
return "<h3 class='display-3'>{}</h3>".format(content)
def title4(content):
return "<h4 class='display-4'>{}</h4>".format(content)
def title5(content):
return "<h5 class='display-5'>{}</h5>".format(content)
def title6(content):
return "<h6 class='display-6'>{}</h6>".format(content)
def h1(content):
return "<h1>{}</h1>".format(content)
def h2(content):
return "<h2>{}</h2>".format(content)
def h3(content):
return "<h3>{}</h3>".format(content)
def h4(content):
return "<h4>{}</h4>".format(content)
def h5(content):
return "<h5>{}</h5>".format(content)
def h6(content):
return "<h6>{}</h6>".format(content)
def important(content):
return """<div class="lead">{}</div>""".format(content)
def small(content):
return "<small>{}</small>".format(content)
def p(content):
return "<p>{}</p>".format(content)
|
def title1(content):
return "<h1 class='display-1'>{}</h1>".format(content)
def title2(content):
return "<h2 class='display-2'>{}</h2>".format(content)
def title3(content):
return "<h3 class='display-3'>{}</h3>".format(content)
def title4(content):
return "<h4 class='display-4'>{}</h4>".format(content)
def title5(content):
return "<h5 class='display-5'>{}</h5>".format(content)
def title6(content):
return "<h6 class='display-6'>{}</h6>".format(content)
def h1(content):
return '<h1>{}</h1>'.format(content)
def h2(content):
return '<h2>{}</h2>'.format(content)
def h3(content):
return '<h3>{}</h3>'.format(content)
def h4(content):
return '<h4>{}</h4>'.format(content)
def h5(content):
return '<h5>{}</h5>'.format(content)
def h6(content):
return '<h6>{}</h6>'.format(content)
def important(content):
return '<div class="lead">{}</div>'.format(content)
def small(content):
return '<small>{}</small>'.format(content)
def p(content):
return '<p>{}</p>'.format(content)
|
class Constants:
# DATA TYPES
GENERATE_EPR_IF_NONE = 'generate_epr_if_none'
AWAIT_ACK = 'await_ack'
SEQUENCE_NUMBER = 'sequence_number'
PAYLOAD = 'payload'
PAYLOAD_TYPE = 'payload_type'
SENDER = 'sender'
RECEIVER = 'receiver'
PROTOCOL = 'protocol'
KEY = 'key'
# WAIT TIME
WAIT_TIME = 10
# QUBIT TYPES
EPR = 0
DATA = 1
GHZ = 2
# DATA KINDS
SIGNAL = 'signal'
CLASSICAL = 'classical'
QUANTUM = 'quantum'
# SIGNALS
ACK = 'qunetsim_ACK__'
NACK = 'qunetsim_NACK__'
# PROTOCOL IDs
REC_EPR = 'rec_epr'
SEND_EPR = 'send_epr'
REC_TELEPORT = 'rec_teleport'
SEND_TELEPORT = 'send_teleport'
REC_SUPERDENSE = 'rec_superdense'
SEND_SUPERDENSE = 'send_superdense'
REC_CLASSICAL = 'rec_classical'
SEND_CLASSICAL = 'send_classical'
SEND_BROADCAST = 'send_broadcast'
RELAY = 'relay'
SEND_QUBIT = 'send_qubit'
REC_QUBIT = 'rec_qubit'
SEND_KEY = 'send_key'
REC_KEY = 'rec_key'
SEND_GHZ = 'send_ghz'
REC_GHZ = 'rec_ghz'
# MISC
QUBITS = 'qubits'
HOSTS = 'hosts'
KEYSIZE = 'keysize'
|
class Constants:
generate_epr_if_none = 'generate_epr_if_none'
await_ack = 'await_ack'
sequence_number = 'sequence_number'
payload = 'payload'
payload_type = 'payload_type'
sender = 'sender'
receiver = 'receiver'
protocol = 'protocol'
key = 'key'
wait_time = 10
epr = 0
data = 1
ghz = 2
signal = 'signal'
classical = 'classical'
quantum = 'quantum'
ack = 'qunetsim_ACK__'
nack = 'qunetsim_NACK__'
rec_epr = 'rec_epr'
send_epr = 'send_epr'
rec_teleport = 'rec_teleport'
send_teleport = 'send_teleport'
rec_superdense = 'rec_superdense'
send_superdense = 'send_superdense'
rec_classical = 'rec_classical'
send_classical = 'send_classical'
send_broadcast = 'send_broadcast'
relay = 'relay'
send_qubit = 'send_qubit'
rec_qubit = 'rec_qubit'
send_key = 'send_key'
rec_key = 'rec_key'
send_ghz = 'send_ghz'
rec_ghz = 'rec_ghz'
qubits = 'qubits'
hosts = 'hosts'
keysize = 'keysize'
|
#--------------------------------------------------------------------#
# Help program.
# Created by: Jim - https://www.youtube.com/watch?v=XCgWYx-lGl8
# Changed by: Thiago Piovesan
#--------------------------------------------------------------------#
# When to use class methods and when to use static methods ?
#--------------------------------------------------------------------#
class Item:
@staticmethod
def is_integer():
'''
This should do something that has a relationship
with the class, but not something that must be unique
per instance!
'''
@classmethod
def instantiate_from_something(cls):
'''
This should also do something that has a relationship
with the class, but usually, those are used to
manipulate different structures of data to instantiate
objects, like we have done with CSV.
'''
# THE ONLY DIFFERENCE BETWEEN THOSE:
# Static methods are not passing the object reference as the first argument in the background!
#--------------------------------------------------------------------#
# NOTE: However, those could be also called from instances.
item1 = Item()
item1.is_integer()
item1.instantiate_from_something()
#--------------------------------------------------------------------#
|
class Item:
@staticmethod
def is_integer():
"""
This should do something that has a relationship
with the class, but not something that must be unique
per instance!
"""
@classmethod
def instantiate_from_something(cls):
"""
This should also do something that has a relationship
with the class, but usually, those are used to
manipulate different structures of data to instantiate
objects, like we have done with CSV.
"""
item1 = item()
item1.is_integer()
item1.instantiate_from_something()
|
FIPS_Reference = {
"AL":"01",
"AK":"02",
"AZ":"04",
"AR":"05",
"AS":"60",
"CA":"06",
"CO":"08",
"CT":"09",
"DE":"10",
"FL":"12",
"GA":"13",
"GU":"66",
"HI":"15",
"ID":"16",
"IL":"17",
"IN":"18",
"IA":"19",
"KS":"20",
"KY":"21",
"LA":"22",
"ME":"23",
"MD":"24",
"MA":"25",
"MI":"26",
"MN":"27",
"MS":"28",
"MO":"29",
"MT":"30",
"NE":"32",
"NV":"32",
"NH":"33",
"NJ":"34",
"NM":"35",
"NY":"36",
"NC":"37",
"ND":"38",
"OH":"39",
"OK":"40",
"OR":"41",
"PA":"42",
"RI":"44",
"PR":"72",
"SC":"45",
"SD":"46",
"TN":"47",
"TX":"48",
"UT":"49",
"VT":"50",
"VI":"78",
"VA":"51",
"WA":"53",
"WV":"54",
"WI":"55",
"WY":"56"
}
|
fips__reference = {'AL': '01', 'AK': '02', 'AZ': '04', 'AR': '05', 'AS': '60', 'CA': '06', 'CO': '08', 'CT': '09', 'DE': '10', 'FL': '12', 'GA': '13', 'GU': '66', 'HI': '15', 'ID': '16', 'IL': '17', 'IN': '18', 'IA': '19', 'KS': '20', 'KY': '21', 'LA': '22', 'ME': '23', 'MD': '24', 'MA': '25', 'MI': '26', 'MN': '27', 'MS': '28', 'MO': '29', 'MT': '30', 'NE': '32', 'NV': '32', 'NH': '33', 'NJ': '34', 'NM': '35', 'NY': '36', 'NC': '37', 'ND': '38', 'OH': '39', 'OK': '40', 'OR': '41', 'PA': '42', 'RI': '44', 'PR': '72', 'SC': '45', 'SD': '46', 'TN': '47', 'TX': '48', 'UT': '49', 'VT': '50', 'VI': '78', 'VA': '51', 'WA': '53', 'WV': '54', 'WI': '55', 'WY': '56'}
|
def check_full_text(fb_full_text, filter_full_text) -> bool:
if filter_full_text is None or fb_full_text == filter_full_text:
return True
return False
def check_contains(fb_contains, filter_contains) -> bool:
if filter_contains is None:
return True
intersection = list(fb_contains & filter_contains)
if len(intersection) == 0:
return False
return True
def check_payload(fb_payload, filter_payload) -> bool:
if filter_payload is None or fb_payload == filter_payload:
return True
return False
|
def check_full_text(fb_full_text, filter_full_text) -> bool:
if filter_full_text is None or fb_full_text == filter_full_text:
return True
return False
def check_contains(fb_contains, filter_contains) -> bool:
if filter_contains is None:
return True
intersection = list(fb_contains & filter_contains)
if len(intersection) == 0:
return False
return True
def check_payload(fb_payload, filter_payload) -> bool:
if filter_payload is None or fb_payload == filter_payload:
return True
return False
|
class _Manager(type):
""" Singletone for cProfile manager """
_inst = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._inst:
cls._inst[cls] = super(_Manager, cls).__call__(*args, **kwargs)
return cls._inst[cls]
class ProfileManager(metaclass=_Manager):
def __init__(self):
self._profiles = list()
def clear(self):
self._profiles.clear()
def add(self, profile):
self._profiles.append(profile)
def profiles(self):
return self._profiles
@property
def count(self):
return len(self._profiles)
|
class _Manager(type):
""" Singletone for cProfile manager """
_inst = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._inst:
cls._inst[cls] = super(_Manager, cls).__call__(*args, **kwargs)
return cls._inst[cls]
class Profilemanager(metaclass=_Manager):
def __init__(self):
self._profiles = list()
def clear(self):
self._profiles.clear()
def add(self, profile):
self._profiles.append(profile)
def profiles(self):
return self._profiles
@property
def count(self):
return len(self._profiles)
|
class Solution:
def maxRotateFunction(self, nums: List[int]) -> int:
sums = sum(nums)
index = 0
res = 0
for ele in nums:
res += index*ele
index += 1
ans = res
for i in range(1,len(nums)):
res = res + sums - (len(nums))*nums[len(nums) - i]
ans = max(res,ans)
return ans
|
class Solution:
def max_rotate_function(self, nums: List[int]) -> int:
sums = sum(nums)
index = 0
res = 0
for ele in nums:
res += index * ele
index += 1
ans = res
for i in range(1, len(nums)):
res = res + sums - len(nums) * nums[len(nums) - i]
ans = max(res, ans)
return ans
|
def is_even(n):
return n % 2 == 0
def is_odd(n):
return not is_even(n)
lost_numbers = (4, 8, 15, 16, 23, 42)
|
def is_even(n):
return n % 2 == 0
def is_odd(n):
return not is_even(n)
lost_numbers = (4, 8, 15, 16, 23, 42)
|
# You are given two non-empty linked lists representing two non-negative integers.
# The digits are stored in reverse order and each of their nodes contain a single digit.
# Add the two numbers and return it as a linked list.
# You may assume the two numbers do not contain any leading zero, except the number 0 itself.
# Example:
# Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
# Output: 7 -> 0 -> 8
# Explanation: 342 + 465 = 807.
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def addTwoNumbers(self,l1,l2):
dummy = ListNode(-1)
cur = dummy
t = 0
while l1 or l2 or t:
if l1:
t += l1.val
l1 = l1.next
if l2:
t += l2.val
l2 = l2.next
cur.next = ListNode(t % 10)
cur = cur.next
t //= 10
return dummy.next
|
class Listnode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def add_two_numbers(self, l1, l2):
dummy = list_node(-1)
cur = dummy
t = 0
while l1 or l2 or t:
if l1:
t += l1.val
l1 = l1.next
if l2:
t += l2.val
l2 = l2.next
cur.next = list_node(t % 10)
cur = cur.next
t //= 10
return dummy.next
|
# Given two strings s and t, determine if they are isomorphic.
# Two strings s and t are isomorphic if the characters in s can be replaced to
# get t.
# All occurrences of a character must be replaced with another character while
# preserving the order of characters. No two characters may map to the same
# character, but a character may map to itself.
# Example 1:
# Input: s = "egg", t = "add"
# Output: true
# Example 2:
# Input: s = "foo", t = "bar"
# Output: false
# Example 3:
# Input: s = "paper", t = "title"
# Output: true
# Constraints:
# 1 <= s.length <= 5 * 10^4
# t.length == s.length
# s and t consist of any valid ascii character.
class DictSetSolution:
def isIsomorphic(self, s: str, t: str) -> bool:
replacements = {}
mapped = set()
for s_let, t_let in zip(s, t):
if (replacement := replacements.get(s_let)):
if replacement != t_let:
return False
else:
if t_let in mapped:
return False
replacements[s_let] = t_let
mapped.add(t_let)
return True
class LengthComparisonSolution:
def isIsomorphic(self, s: str, t: str) -> bool:
return len(set(zip(s, t))) == len(set(s)) == len(set(t))
class ArraySolution:
def isIsomorphic(self, s: str, t: str) -> bool:
sa, ta = [0 for i in range(128)], [0 for i in range(128)]
for idx, letters in enumerate(zip(s, t)):
sl, tl = letters
if sa[ord(sl)] != ta[ord(tl)]:
return False
sa[ord(sl)] = idx + 1
ta[ord(tl)] = idx + 1
return True
|
class Dictsetsolution:
def is_isomorphic(self, s: str, t: str) -> bool:
replacements = {}
mapped = set()
for (s_let, t_let) in zip(s, t):
if (replacement := replacements.get(s_let)):
if replacement != t_let:
return False
else:
if t_let in mapped:
return False
replacements[s_let] = t_let
mapped.add(t_let)
return True
class Lengthcomparisonsolution:
def is_isomorphic(self, s: str, t: str) -> bool:
return len(set(zip(s, t))) == len(set(s)) == len(set(t))
class Arraysolution:
def is_isomorphic(self, s: str, t: str) -> bool:
(sa, ta) = ([0 for i in range(128)], [0 for i in range(128)])
for (idx, letters) in enumerate(zip(s, t)):
(sl, tl) = letters
if sa[ord(sl)] != ta[ord(tl)]:
return False
sa[ord(sl)] = idx + 1
ta[ord(tl)] = idx + 1
return True
|
def mergeSort(elements):
if len(elements) == 0 or len(elements) == 1:
# BASE CASE
return elements
middle = len(elements) // 2
left = mergeSort(elements[:middle])
right = mergeSort(elements[middle:])
if left == [] or right == []:
return left or right
result = []
i, j = 0, 0
while (len(result) < len(left) + len(right)):
if left[i] < right[j]:
result.append(left[i])
i+= 1
else:
result.append(right[j])
j+= 1
if i == len(left) or j == len(right):
result.extend(left[i:] or right[j:])
break
return result
print(mergeSort([3,4,5,1,2,8,3,7,6]))
|
def merge_sort(elements):
if len(elements) == 0 or len(elements) == 1:
return elements
middle = len(elements) // 2
left = merge_sort(elements[:middle])
right = merge_sort(elements[middle:])
if left == [] or right == []:
return left or right
result = []
(i, j) = (0, 0)
while len(result) < len(left) + len(right):
if left[i] < right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1
if i == len(left) or j == len(right):
result.extend(left[i:] or right[j:])
break
return result
print(merge_sort([3, 4, 5, 1, 2, 8, 3, 7, 6]))
|
__author__ = 'James Myatt'
__version__ = '0.0.2'
__all__ = [
'monitor', 'sensor', 'utils',
'time', 'w1therm'
]
|
__author__ = 'James Myatt'
__version__ = '0.0.2'
__all__ = ['monitor', 'sensor', 'utils', 'time', 'w1therm']
|
class SocketAPIError(Exception):
pass
class InvalidRequestError(SocketAPIError):
pass
class InvalidURIError(InvalidRequestError):
pass
class NotFoundError(InvalidRequestError):
pass
|
class Socketapierror(Exception):
pass
class Invalidrequesterror(SocketAPIError):
pass
class Invalidurierror(InvalidRequestError):
pass
class Notfounderror(InvalidRequestError):
pass
|
# Prints out a string
print("Mary had a little lamb.")
# Prints out a formatted string
print("Its fleece was white as {}.".format('snow'))
# Prints out another string
print("and everywhere that Mary went.")
# Prints a period for ten times
print("." * 10) # what'd that do?
# Assign a letter to string variable
end1 = "C"
end2 = "h"
end3 = "e"
end4 = "e"
end5 = "s"
end6 = "e"
end7 = "B"
end8 = "u"
end9 = "r"
end10 = "g"
end11 = "e"
end12 = "r"
# watch that comma at the end. try removing it to see what happens
# end part place a space insetad of a newline
print(end1 + end2 + end3 + end4 + end5 + end6, end=' ')
print(end7 + end8 + end9 + end10 + end11 + end12)
|
print('Mary had a little lamb.')
print('Its fleece was white as {}.'.format('snow'))
print('and everywhere that Mary went.')
print('.' * 10)
end1 = 'C'
end2 = 'h'
end3 = 'e'
end4 = 'e'
end5 = 's'
end6 = 'e'
end7 = 'B'
end8 = 'u'
end9 = 'r'
end10 = 'g'
end11 = 'e'
end12 = 'r'
print(end1 + end2 + end3 + end4 + end5 + end6, end=' ')
print(end7 + end8 + end9 + end10 + end11 + end12)
|
"""
Drones library and API version.
"""
DRONES_VERSION = "0.1.2"
|
"""
Drones library and API version.
"""
drones_version = '0.1.2'
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class HookitConnectionError(Exception):
pass
__all__ = ['HookitConnectionError']
|
class Hookitconnectionerror(Exception):
pass
__all__ = ['HookitConnectionError']
|
def get_gene_ne(global_variables,gene_dictionary):
values_list = []
# gets the ordered samples
sample_list = global_variables["sample_list"]
for sample in sample_list:
values_list.append(gene_dictionary[sample])
return values_list
|
def get_gene_ne(global_variables, gene_dictionary):
values_list = []
sample_list = global_variables['sample_list']
for sample in sample_list:
values_list.append(gene_dictionary[sample])
return values_list
|
def ceasear_encode( msg, key ):
code = ""
key = ord(key.upper())-ord("A")
for c in msg.upper():
if c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":
new_ord = ord(c)+key
if new_ord > ord("Z"):
new_ord -= 26
code += chr(new_ord)
else:
code += c
return code
def ceasear_decode( code, key ):
msg = ""
key = ord(key.upper())-ord("A")
for c in code.upper():
if c in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":
new_ord = ord(c)-key
if new_ord < ord("A"):
new_ord += 26
msg += chr(new_ord)
else:
msg += c
return msg
#print(ceasear_decode(ceasear_encode("HalloWelt", "F"), "F"))
msg = """
MRN BRLQNAQNRC NRWNA PNQNRVBLQAROC
MJAO WDA EXW MNA PNQNRVQJUCDWP
MNB BLQUDNBBNUB JKQJNWPNW, WRLQC
SNMXLQ EXW MNA PNQNRVQJUCDWP MNA
ENABLQUDNBBNUDWPBVNCQXMN.
"""
for key in "ABCDEFGHIJKLMNOPQRSTUVWXYZ":
#for key in "J":
print(key + ": " + ceasear_decode(msg, key)[:14])
|
def ceasear_encode(msg, key):
code = ''
key = ord(key.upper()) - ord('A')
for c in msg.upper():
if c in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':
new_ord = ord(c) + key
if new_ord > ord('Z'):
new_ord -= 26
code += chr(new_ord)
else:
code += c
return code
def ceasear_decode(code, key):
msg = ''
key = ord(key.upper()) - ord('A')
for c in code.upper():
if c in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':
new_ord = ord(c) - key
if new_ord < ord('A'):
new_ord += 26
msg += chr(new_ord)
else:
msg += c
return msg
msg = '\nMRN BRLQNAQNRC NRWNA PNQNRVBLQAROC\nMJAO WDA EXW MNA PNQNRVQJUCDWP\nMNB BLQUDNBBNUB JKQJNWPNW, WRLQC\nSNMXLQ EXW MNA PNQNRVQJUCDWP MNA\nENABLQUDNBBNUDWPBVNCQXMN.\n'
for key in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':
print(key + ': ' + ceasear_decode(msg, key)[:14])
|
def version():
"""Function takes no aruguments and returns a STR value of the current version of the library. This value should match
the value in the setup.py
:param None
:return str value of the current version of the library
:rtype str
>>> version()
1.0.33
"""
print ('1.0.34')
|
def version():
"""Function takes no aruguments and returns a STR value of the current version of the library. This value should match
the value in the setup.py
:param None
:return str value of the current version of the library
:rtype str
>>> version()
1.0.33
"""
print('1.0.34')
|
"""
The main module of DAFEST project.
ADAFEST is an abbreviation: 'A Data-Driven Approach to Estimating / Evaluating Software Testability'
The full version of source code will be available
as soon as the relevant paper(s) are published.
"""
class Main():
"""Welcome to project ADAFEST
This file contains the main script
"""
@classmethod
def print_welcome(cls, name) -> None:
"""
Print welcome message
:param name:
:return:
"""
print(f'Welcome to the project {name}.')
# Main driver
if __name__ == '__main__':
Main.print_welcome('ADAFEST')
|
"""
The main module of DAFEST project.
ADAFEST is an abbreviation: 'A Data-Driven Approach to Estimating / Evaluating Software Testability'
The full version of source code will be available
as soon as the relevant paper(s) are published.
"""
class Main:
"""Welcome to project ADAFEST
This file contains the main script
"""
@classmethod
def print_welcome(cls, name) -> None:
"""
Print welcome message
:param name:
:return:
"""
print(f'Welcome to the project {name}.')
if __name__ == '__main__':
Main.print_welcome('ADAFEST')
|
def sublime():
return [
('MacOS', 'https://download.sublimetext.com/Sublime%20Text%20Build%203126.dmg', 'sublime/sublime.dmg'),
('Windows (32-bit)', 'https://download.sublimetext.com/Sublime%20Text%20Build%203126%20Setup.exe', 'sublime/sublime-x86.exe'), # noqa
('Windows (64-bit)', 'https://download.sublimetext.com/Sublime%20Text%20Build%203126%20x64%20Setup.exe', 'sublime/sublime-amd64.exe'), # noqa
('Ubuntu (32-bit)', 'https://download.sublimetext.com/sublime-text_build-3126_i386.deb', 'sublime/sublime-x86.deb'), # noqa
('Ubuntu (64-bit)', 'https://download.sublimetext.com/sublime-text_build-3126_amd64.deb', 'sublime/sublime-amd64.deb'), # noqa
]
|
def sublime():
return [('MacOS', 'https://download.sublimetext.com/Sublime%20Text%20Build%203126.dmg', 'sublime/sublime.dmg'), ('Windows (32-bit)', 'https://download.sublimetext.com/Sublime%20Text%20Build%203126%20Setup.exe', 'sublime/sublime-x86.exe'), ('Windows (64-bit)', 'https://download.sublimetext.com/Sublime%20Text%20Build%203126%20x64%20Setup.exe', 'sublime/sublime-amd64.exe'), ('Ubuntu (32-bit)', 'https://download.sublimetext.com/sublime-text_build-3126_i386.deb', 'sublime/sublime-x86.deb'), ('Ubuntu (64-bit)', 'https://download.sublimetext.com/sublime-text_build-3126_amd64.deb', 'sublime/sublime-amd64.deb')]
|
class PyEVMError(Exception):
"""
Base class for all py-hvm errors.
"""
pass
class VMNotFound(PyEVMError):
"""
Raised when no VM is available for the provided block number.
"""
pass
class NoGenesisBlockPresent(PyEVMError):
"""
Raised when a block is imported but there is no genesis block.
"""
pass
class StateRootNotFound(PyEVMError):
"""
Raised when the requested state root is not present in our DB.
"""
pass
class HeaderNotFound(PyEVMError):
"""
Raised when a header with the given number/hash does not exist.
"""
class BlockNotFound(PyEVMError):
"""
Raised when the block with the given number/hash does not exist.
"""
pass
class BlockOnWrongChain(PyEVMError):
"""
Raised when a block interacts with a chain it doesnt belong to
"""
pass
class RewardProofSenderBlockMissing(PyEVMError):
"""
Raised when a reward block is imported with provided proof from peers, but we don't have an up to date peer chain yet
so we cannot verify the proof. Need to safe the block as unprocessed until we download the peer chain.
"""
pass
class NoLocalRootHashTimestamps(PyEVMError):
"""
Raised when there are no local root hash timestamps
"""
pass
class LocalRootHashNotInConsensus(PyEVMError):
"""
Raised when there are no local root hash timestamps
"""
pass
class LocalRootHashNotAsExpected(PyEVMError):
"""
Raised after importing blocks and our root hash doesnt match what it should be
"""
pass
class IncorrectBlockType(PyEVMError):
"""
Raised when the block is queueblock when it should be block or vice-versa
"""
pass
class IncorrectBlockHeaderType(PyEVMError):
"""
Raised when the block is queueblock when it should be block or vice-versa
"""
pass
class NotEnoughTimeBetweenBlocks(PyEVMError):
"""
Raised when there is not enough time between blocks. WHO WOULD HAVE GUESSED?
"""
pass
class CannotCalculateStake(PyEVMError):
"""
Raised when a function tries to calculate the stake for an address where we are missing information. for example, if we dont have their chain.
"""
pass
class ReceivableTransactionNotFound(PyEVMError):
"""
Raised when a A receive transaction tries to receive a transaction that wasnt sent
"""
pass
class HistoricalNetworkTPCMissing(PyEVMError):
"""
Raised when a historical network tpc is missing for a certain timestamp
"""
pass
class NotEnoughProofsOrStakeForRewardType2Proof(PyEVMError):
"""
Raised when all of the proof we have for a reward type 2 does not meet the minimum requirement
"""
pass
class RewardAmountRoundsToZero(PyEVMError):
"""
Raised when a node attempts to create a reward block that has amount = 0 for all kinds of rewards. This will occur if not enough time has passed since the last reward.
"""
pass
class NotEnoughDataForHistoricalMinGasPriceCalculation(PyEVMError):
"""
Raised when there is not enough historical TPC to perform a calculation. Can occur when the genesis node just starts
"""
pass
class HistoricalMinGasPriceError(PyEVMError):
"""
Raised when a historical network tpc is missing for a certain timestamp
"""
pass
class TransactionNotFound(PyEVMError):
"""
Raised when the transaction with the given hash or block index does not exist.
"""
pass
class InvalidHeadRootTimestamp(PyEVMError):
"""
Raised when a timestamp based head hash is loaded or saved with invalid timestamp
"""
pass
class NoChronologicalBlocks(PyEVMError):
"""
Raised When there are no new blocks within the chronological block windows
"""
pass
class ParentNotFound(HeaderNotFound):
"""
Raised when the parent of a given block does not exist.
"""
pass
class UnprocessedBlockNotAllowed(PyEVMError):
"""
Raised when an unprocessed block is imported when it is not allowed
"""
pass
class UnprocessedBlockChildIsProcessed(PyEVMError):
"""
Raised when a child of an unprocessed block has been processed for some reason
"""
pass
class ReplacingBlocksNotAllowed(PyEVMError):
"""
Raised when a block tries to replace another block when it is not allowed
"""
pass
class CanonicalHeadNotFound(PyEVMError):
"""
Raised when the chain has no canonical head.
"""
pass
class TriedImportingGenesisBlock(PyEVMError):
"""
Raised when the genesis block on the genesis chain is attempted to be overwritten
"""
pass
class TriedDeletingGenesisBlock(PyEVMError):
"""
Raised when the genesis block on the genesis chain is attempted to be deleted
"""
pass
class CollationHeaderNotFound(PyEVMError):
"""
Raised when the collation header for the given shard and period does not exist in the database.
"""
pass
class SyncerOutOfOrder(PyEVMError):
"""
Syncer process has hit a snag and is out of order. For example, regular chain syncer went before it should.
"""
pass
class CollationBodyNotFound(PyEVMError):
"""
Raised when the collation body for the given shard and period does not exist in the database.
"""
pass
class CanonicalCollationNotFound(PyEVMError):
"""
Raised when no collation for the given shard and period has been marked as canonical.
"""
pass
class AppendHistoricalRootHashTooOld(PyEVMError):
"""
Raised when you try to append a historical root hash that is older than the oldest one in our database. can only append newer historical root hashes
"""
pass
class ValidationError(PyEVMError):
"""
Raised when something does not pass a validation check.
"""
pass
class JournalDbNotActivated(PyEVMError):
"""
Raised when someone tries to discard, save, persist a db, when it is not actually a journaldb
"""
pass
class Halt(PyEVMError):
"""
Raised when an opcode function halts vm execution.
"""
pass
class VMError(PyEVMError):
"""
Base class for errors raised during VM execution.
"""
burns_gas = True
erases_return_data = True
class OutOfGas(VMError):
"""
Raised when a VM execution has run out of gas.
"""
pass
class InsufficientStack(VMError):
"""
Raised when the stack is empty.
"""
pass
class FullStack(VMError):
"""
Raised when the stack is full.
"""
pass
class InvalidJumpDestination(VMError):
"""
Raised when the jump destination for a JUMPDEST operation is invalid.
"""
pass
class InvalidInstruction(VMError):
"""
Raised when an opcode is invalid.
"""
pass
class InsufficientFunds(VMError):
"""
Raised when an account has insufficient funds to transfer the
requested value.
"""
pass
class ReceiveTransactionIncorrectSenderBlockHash(VMError):
"""
Raised when a receive transaction is found that has a sender block hash
that doesnt match the one in our database.
"""
pass
class ReceivingTransactionForWrongWallet(VMError):
"""
Raised when a someone tries to receive a transaction sent to someone else.
"""
pass
class StackDepthLimit(VMError):
"""
Raised when the call stack has exceeded it's maximum allowed depth.
"""
pass
class ContractCreationCollision(VMError):
"""
Raised when there was an address collision during contract creation.
"""
pass
class IncorrectContractCreationAddress(VMError):
"""
Raised when the address provided by transaction does not
match the calculated contract creation address.
"""
pass
class Revert(VMError):
"""
Raised when the REVERT opcode occured
"""
burns_gas = False
erases_return_data = False
class WriteProtection(VMError):
"""
Raised when an attempt to modify the state database is made while
operating inside of a STATICCALL context.
"""
pass
class OutOfBoundsRead(VMError):
"""
Raised when an attempt was made to read data beyond the
boundaries of the buffer (such as with RETURNDATACOPY)
"""
pass
class AttemptedToAccessExternalStorage(VMError):
"""
Raised when a contract calls another contract and attempts
to use the storage in the other contract. This is not allowed
on Helios. Use DelegateCall instead of Call.
"""
pass
class DepreciatedVMFunctionality(VMError):
"""
Raised when a contract calls another a depreciated global variable or function
"""
pass
|
class Pyevmerror(Exception):
"""
Base class for all py-hvm errors.
"""
pass
class Vmnotfound(PyEVMError):
"""
Raised when no VM is available for the provided block number.
"""
pass
class Nogenesisblockpresent(PyEVMError):
"""
Raised when a block is imported but there is no genesis block.
"""
pass
class Staterootnotfound(PyEVMError):
"""
Raised when the requested state root is not present in our DB.
"""
pass
class Headernotfound(PyEVMError):
"""
Raised when a header with the given number/hash does not exist.
"""
class Blocknotfound(PyEVMError):
"""
Raised when the block with the given number/hash does not exist.
"""
pass
class Blockonwrongchain(PyEVMError):
"""
Raised when a block interacts with a chain it doesnt belong to
"""
pass
class Rewardproofsenderblockmissing(PyEVMError):
"""
Raised when a reward block is imported with provided proof from peers, but we don't have an up to date peer chain yet
so we cannot verify the proof. Need to safe the block as unprocessed until we download the peer chain.
"""
pass
class Nolocalroothashtimestamps(PyEVMError):
"""
Raised when there are no local root hash timestamps
"""
pass
class Localroothashnotinconsensus(PyEVMError):
"""
Raised when there are no local root hash timestamps
"""
pass
class Localroothashnotasexpected(PyEVMError):
"""
Raised after importing blocks and our root hash doesnt match what it should be
"""
pass
class Incorrectblocktype(PyEVMError):
"""
Raised when the block is queueblock when it should be block or vice-versa
"""
pass
class Incorrectblockheadertype(PyEVMError):
"""
Raised when the block is queueblock when it should be block or vice-versa
"""
pass
class Notenoughtimebetweenblocks(PyEVMError):
"""
Raised when there is not enough time between blocks. WHO WOULD HAVE GUESSED?
"""
pass
class Cannotcalculatestake(PyEVMError):
"""
Raised when a function tries to calculate the stake for an address where we are missing information. for example, if we dont have their chain.
"""
pass
class Receivabletransactionnotfound(PyEVMError):
"""
Raised when a A receive transaction tries to receive a transaction that wasnt sent
"""
pass
class Historicalnetworktpcmissing(PyEVMError):
"""
Raised when a historical network tpc is missing for a certain timestamp
"""
pass
class Notenoughproofsorstakeforrewardtype2Proof(PyEVMError):
"""
Raised when all of the proof we have for a reward type 2 does not meet the minimum requirement
"""
pass
class Rewardamountroundstozero(PyEVMError):
"""
Raised when a node attempts to create a reward block that has amount = 0 for all kinds of rewards. This will occur if not enough time has passed since the last reward.
"""
pass
class Notenoughdataforhistoricalmingaspricecalculation(PyEVMError):
"""
Raised when there is not enough historical TPC to perform a calculation. Can occur when the genesis node just starts
"""
pass
class Historicalmingaspriceerror(PyEVMError):
"""
Raised when a historical network tpc is missing for a certain timestamp
"""
pass
class Transactionnotfound(PyEVMError):
"""
Raised when the transaction with the given hash or block index does not exist.
"""
pass
class Invalidheadroottimestamp(PyEVMError):
"""
Raised when a timestamp based head hash is loaded or saved with invalid timestamp
"""
pass
class Nochronologicalblocks(PyEVMError):
"""
Raised When there are no new blocks within the chronological block windows
"""
pass
class Parentnotfound(HeaderNotFound):
"""
Raised when the parent of a given block does not exist.
"""
pass
class Unprocessedblocknotallowed(PyEVMError):
"""
Raised when an unprocessed block is imported when it is not allowed
"""
pass
class Unprocessedblockchildisprocessed(PyEVMError):
"""
Raised when a child of an unprocessed block has been processed for some reason
"""
pass
class Replacingblocksnotallowed(PyEVMError):
"""
Raised when a block tries to replace another block when it is not allowed
"""
pass
class Canonicalheadnotfound(PyEVMError):
"""
Raised when the chain has no canonical head.
"""
pass
class Triedimportinggenesisblock(PyEVMError):
"""
Raised when the genesis block on the genesis chain is attempted to be overwritten
"""
pass
class Trieddeletinggenesisblock(PyEVMError):
"""
Raised when the genesis block on the genesis chain is attempted to be deleted
"""
pass
class Collationheadernotfound(PyEVMError):
"""
Raised when the collation header for the given shard and period does not exist in the database.
"""
pass
class Synceroutoforder(PyEVMError):
"""
Syncer process has hit a snag and is out of order. For example, regular chain syncer went before it should.
"""
pass
class Collationbodynotfound(PyEVMError):
"""
Raised when the collation body for the given shard and period does not exist in the database.
"""
pass
class Canonicalcollationnotfound(PyEVMError):
"""
Raised when no collation for the given shard and period has been marked as canonical.
"""
pass
class Appendhistoricalroothashtooold(PyEVMError):
"""
Raised when you try to append a historical root hash that is older than the oldest one in our database. can only append newer historical root hashes
"""
pass
class Validationerror(PyEVMError):
"""
Raised when something does not pass a validation check.
"""
pass
class Journaldbnotactivated(PyEVMError):
"""
Raised when someone tries to discard, save, persist a db, when it is not actually a journaldb
"""
pass
class Halt(PyEVMError):
"""
Raised when an opcode function halts vm execution.
"""
pass
class Vmerror(PyEVMError):
"""
Base class for errors raised during VM execution.
"""
burns_gas = True
erases_return_data = True
class Outofgas(VMError):
"""
Raised when a VM execution has run out of gas.
"""
pass
class Insufficientstack(VMError):
"""
Raised when the stack is empty.
"""
pass
class Fullstack(VMError):
"""
Raised when the stack is full.
"""
pass
class Invalidjumpdestination(VMError):
"""
Raised when the jump destination for a JUMPDEST operation is invalid.
"""
pass
class Invalidinstruction(VMError):
"""
Raised when an opcode is invalid.
"""
pass
class Insufficientfunds(VMError):
"""
Raised when an account has insufficient funds to transfer the
requested value.
"""
pass
class Receivetransactionincorrectsenderblockhash(VMError):
"""
Raised when a receive transaction is found that has a sender block hash
that doesnt match the one in our database.
"""
pass
class Receivingtransactionforwrongwallet(VMError):
"""
Raised when a someone tries to receive a transaction sent to someone else.
"""
pass
class Stackdepthlimit(VMError):
"""
Raised when the call stack has exceeded it's maximum allowed depth.
"""
pass
class Contractcreationcollision(VMError):
"""
Raised when there was an address collision during contract creation.
"""
pass
class Incorrectcontractcreationaddress(VMError):
"""
Raised when the address provided by transaction does not
match the calculated contract creation address.
"""
pass
class Revert(VMError):
"""
Raised when the REVERT opcode occured
"""
burns_gas = False
erases_return_data = False
class Writeprotection(VMError):
"""
Raised when an attempt to modify the state database is made while
operating inside of a STATICCALL context.
"""
pass
class Outofboundsread(VMError):
"""
Raised when an attempt was made to read data beyond the
boundaries of the buffer (such as with RETURNDATACOPY)
"""
pass
class Attemptedtoaccessexternalstorage(VMError):
"""
Raised when a contract calls another contract and attempts
to use the storage in the other contract. This is not allowed
on Helios. Use DelegateCall instead of Call.
"""
pass
class Depreciatedvmfunctionality(VMError):
"""
Raised when a contract calls another a depreciated global variable or function
"""
pass
|
example_data = """\
1721
979
366
299
675
1456\
"""
data = """\
1914
1931
1892
1584
1546
1988
1494
1709
1624
1755
1849
1430
1890
1675
1604
1580
1500
1277
1729
1456
2002
1075
1512
895
1843
1921
1904
1989
1407
1552
1714
757
1733
1459
1777
1440
1649
1409
1662
1968
1775
1998
1754
1938
1964
1415
1990
1997
1870
1664
1145
1782
1820
1625
1599
1530
1759
1575
1614
1869
1620
1818
1295
1667
1361
1520
1555
1485
1502
1983
1104
1973
1433
1906
1583
1562
1493
1945
1528
1600
1814
1712
1848
1454
1801
1710
1824
1426
1977
1511
1644
1302
1428
1513
1261
1761
1680
1731
1724
1970
907
600
1613
1091
1571
1418
1806
1542
1909
1445
1344
1937
1450
1865
1561
1962
1637
1803
1889
365
1810
1791
1591
1532
1863
1658
1808
1816
1837
1764
1443
1805
1616
1403
1656
1661
1734
1930
1120
1920
1227
1618
1640
1586
1982
1534
1278
1269
1572
1654
1472
1974
1748
1425
1553
1708
1394
1417
1746
1745
1834
1787
1298
1786
1966
1768
1932
1523
1356
1547
1634
1951
1922
222
1461
1628
1888
1639
473
1568
1783
572
1522
1934
1629
1283
1550
1859
2007
1996
1822
996
1911
1689
1537
1793
1762
1677
1266
1715\
"""
|
example_data = '1721\n979\n366\n299\n675\n1456'
data = '1914\n1931\n1892\n1584\n1546\n1988\n1494\n1709\n1624\n1755\n1849\n1430\n1890\n1675\n1604\n1580\n1500\n1277\n1729\n1456\n2002\n1075\n1512\n895\n1843\n1921\n1904\n1989\n1407\n1552\n1714\n757\n1733\n1459\n1777\n1440\n1649\n1409\n1662\n1968\n1775\n1998\n1754\n1938\n1964\n1415\n1990\n1997\n1870\n1664\n1145\n1782\n1820\n1625\n1599\n1530\n1759\n1575\n1614\n1869\n1620\n1818\n1295\n1667\n1361\n1520\n1555\n1485\n1502\n1983\n1104\n1973\n1433\n1906\n1583\n1562\n1493\n1945\n1528\n1600\n1814\n1712\n1848\n1454\n1801\n1710\n1824\n1426\n1977\n1511\n1644\n1302\n1428\n1513\n1261\n1761\n1680\n1731\n1724\n1970\n907\n600\n1613\n1091\n1571\n1418\n1806\n1542\n1909\n1445\n1344\n1937\n1450\n1865\n1561\n1962\n1637\n1803\n1889\n365\n1810\n1791\n1591\n1532\n1863\n1658\n1808\n1816\n1837\n1764\n1443\n1805\n1616\n1403\n1656\n1661\n1734\n1930\n1120\n1920\n1227\n1618\n1640\n1586\n1982\n1534\n1278\n1269\n1572\n1654\n1472\n1974\n1748\n1425\n1553\n1708\n1394\n1417\n1746\n1745\n1834\n1787\n1298\n1786\n1966\n1768\n1932\n1523\n1356\n1547\n1634\n1951\n1922\n222\n1461\n1628\n1888\n1639\n473\n1568\n1783\n572\n1522\n1934\n1629\n1283\n1550\n1859\n2007\n1996\n1822\n996\n1911\n1689\n1537\n1793\n1762\n1677\n1266\n1715'
|
#ID of the project
project_id = ""
#List of paths where the folders to check are
project_paths = []
#Destination of the sync, trailing slash
destination_path = ""
##################################
#Postgres database and rw user
##################################
db_host = ""
db_db = ""
db_user = ""
##################################
#How long to sleep between loops
sleep = 180
|
project_id = ''
project_paths = []
destination_path = ''
db_host = ''
db_db = ''
db_user = ''
sleep = 180
|
class Solution:
def summaryRanges(self, nums):
if not nums:
return nums
results = []
start = end = nums[0]
for i in nums:
if i != end:
rng = f"{start}->{end-1}" if start != (end - 1) else f"{start}"
results.append(rng)
start = end = i
end += 1
# we ended on a solo number.
if start == nums[-1]:
results.append(f'{start}')
# we ended on a range.
elif start != (end - 1):
results.append(f'{start}->{end-1}')
return results
|
class Solution:
def summary_ranges(self, nums):
if not nums:
return nums
results = []
start = end = nums[0]
for i in nums:
if i != end:
rng = f'{start}->{end - 1}' if start != end - 1 else f'{start}'
results.append(rng)
start = end = i
end += 1
if start == nums[-1]:
results.append(f'{start}')
elif start != end - 1:
results.append(f'{start}->{end - 1}')
return results
|
class Solution:
def totalNQueens(self, n: int) -> int:
def dfs(row):
if row == 0:
return 1
count = 0
for col in range(n):
if col not in col_blacklist and \
row - col not in major_blacklist and \
row + col not in minor_blacklist:
col_blacklist.add(col)
major_blacklist.add(row - col)
minor_blacklist.add(row + col)
count += dfs(row - 1)
col_blacklist.remove(col)
major_blacklist.remove(row - col)
minor_blacklist.remove(row + col)
return count
col_blacklist = set()
major_blacklist = set()
minor_blacklist = set()
return dfs(n)
|
class Solution:
def total_n_queens(self, n: int) -> int:
def dfs(row):
if row == 0:
return 1
count = 0
for col in range(n):
if col not in col_blacklist and row - col not in major_blacklist and (row + col not in minor_blacklist):
col_blacklist.add(col)
major_blacklist.add(row - col)
minor_blacklist.add(row + col)
count += dfs(row - 1)
col_blacklist.remove(col)
major_blacklist.remove(row - col)
minor_blacklist.remove(row + col)
return count
col_blacklist = set()
major_blacklist = set()
minor_blacklist = set()
return dfs(n)
|
N = int(input())
R = []
for i in range(0, N*2) :
if i%2 == 0 : R.append("*")
else : R.append(" ")
for l in range(0, N) :
P1 = P2 = ""
for i in range(0, N) :
P1 += R[i]
print(P1)
for i in range(N*2-1, N-1, -1) :
P2 += R[i]
print(P2)
|
n = int(input())
r = []
for i in range(0, N * 2):
if i % 2 == 0:
R.append('*')
else:
R.append(' ')
for l in range(0, N):
p1 = p2 = ''
for i in range(0, N):
p1 += R[i]
print(P1)
for i in range(N * 2 - 1, N - 1, -1):
p2 += R[i]
print(P2)
|
#
# PySNMP MIB module SYMMCOMMONPTP (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/neermitt/Dev/kusanagi/mibs.snmplabs.com/asn1/SYMMCOMMONPTP
# Produced by pysmi-0.3.4 at Tue Jul 30 11:34:16 2019
# On host NEERMITT-M-J0NV platform Darwin version 18.6.0 by user neermitt
# Using Python version 3.7.4 (default, Jul 9 2019, 18:13:23)
#
Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsUnion, ConstraintsIntersection, ValueSizeConstraint, ValueRangeConstraint, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "ConstraintsIntersection", "ValueSizeConstraint", "ValueRangeConstraint", "SingleValueConstraint")
entPhysicalIndex, = mibBuilder.importSymbols("ENTITY-MIB", "entPhysicalIndex")
ifIndex, ifNumber = mibBuilder.importSymbols("IF-MIB", "ifIndex", "ifNumber")
NotificationGroup, ModuleCompliance, ObjectGroup = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance", "ObjectGroup")
NotificationType, Counter64, MibScalar, MibTable, MibTableRow, MibTableColumn, Integer32, TimeTicks, Unsigned32, ObjectIdentity, ModuleIdentity, iso, Bits, MibIdentifier, Counter32, Gauge32, IpAddress = mibBuilder.importSymbols("SNMPv2-SMI", "NotificationType", "Counter64", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Integer32", "TimeTicks", "Unsigned32", "ObjectIdentity", "ModuleIdentity", "iso", "Bits", "MibIdentifier", "Counter32", "Gauge32", "IpAddress")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
EnableValue, symmPacketService = mibBuilder.importSymbols("SYMM-COMMON-SMI", "EnableValue", "symmPacketService")
symmPTPv2 = ModuleIdentity((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1))
symmPTPv2.setRevisions(('2018-07-31 06:20',))
if mibBuilder.loadTexts: symmPTPv2.setLastUpdated('201807310620Z')
if mibBuilder.loadTexts: symmPTPv2.setOrganization('Symmetricom')
class PTPPROFILEVALUE(Integer32):
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7))
namedValues = NamedValues(("profileTelecom2008", 1), ("profileDefault", 2), ("profileHybrid", 3), ("profileITU8265one", 4), ("profileEthernetDefault", 5), ("profileITU8275one", 6), ("profileITU8275two", 7))
class PTPTIMESCALETYPE(Integer32):
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3))
namedValues = NamedValues(("auto", 1), ("arb", 2), ("ptp", 3))
class PTPMGMTADDRTYPE(Integer32):
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(0, 1))
namedValues = NamedValues(("unicast", 0), ("multicast", 1))
class PTPTRANSPORTTYPE(Integer32):
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2))
namedValues = NamedValues(("ethernet", 1), ("ipv4", 2))
class PTPADDRMODETYPE(Integer32):
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(0, 1, 2))
namedValues = NamedValues(("unicast", 0), ("multicast", 1), ("multicasthybrid", 2))
class PORTSTATEVALUE(Integer32):
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2))
namedValues = NamedValues(("enable", 1), ("disable", 2))
class G82751McAddrValue(Integer32):
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2))
namedValues = NamedValues(("mac011b19000000", 1), ("mac0180c200000e", 2))
class VLANID(Integer32):
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1))
namedValues = NamedValues(("none", 1))
class DateAndTime(TextualConvention, OctetString):
status = 'current'
displayHint = '2d-1d-1d,1d:1d:1d.1d,1a1d:1d'
subtypeSpec = OctetString.subtypeSpec + ConstraintsUnion(ValueSizeConstraint(8, 8), ValueSizeConstraint(11, 11), )
class TLatAndLon(TextualConvention, OctetString):
status = 'current'
displayHint = '1a1d:1d:1d.1d'
subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(5, 5)
fixedLength = 5
class TAntHeight(TextualConvention, OctetString):
status = 'current'
displayHint = '1a2d.1d'
subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(4, 4)
fixedLength = 4
class TLocalTimeOffset(TextualConvention, OctetString):
status = 'current'
displayHint = '1a1d:1d'
subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(3, 3)
fixedLength = 3
class TSsm(TextualConvention, Integer32):
status = 'current'
displayHint = 'x'
subtypeSpec = Integer32.subtypeSpec + ValueRangeConstraint(0, 255)
ptpv2Status = MibIdentifier((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 1))
ptpv2StatusTable = MibTable((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 1, 1), )
if mibBuilder.loadTexts: ptpv2StatusTable.setStatus('current')
ptpv2StatusEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 1, 1, 1), ).setIndexNames((0, "IF-MIB", "ifIndex"), (0, "SYMMCOMMONPTP", "ptpv2StatusIndex"))
if mibBuilder.loadTexts: ptpv2StatusEntry.setStatus('current')
ptpv2StatusIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 1, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 1000)))
if mibBuilder.loadTexts: ptpv2StatusIndex.setStatus('current')
ptpv2StatusPortEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 1, 1, 1, 2), EnableValue()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ptpv2StatusPortEnable.setStatus('current')
ptpv2StatusClockID = MibTableColumn((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 1, 1, 1, 3), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ptpv2StatusClockID.setStatus('current')
ptpv2StatusProfile = MibTableColumn((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 1, 1, 1, 4), PTPPROFILEVALUE()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ptpv2StatusProfile.setStatus('current')
ptpv2StatusClockClass = MibTableColumn((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 1, 1, 1, 5), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ptpv2StatusClockClass.setStatus('current')
ptpv2StatusClockAccuracy = MibTableColumn((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 1, 1, 1, 6), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ptpv2StatusClockAccuracy.setStatus('current')
ptpv2StatusTimescale = MibTableColumn((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 1, 1, 1, 7), PTPTIMESCALETYPE()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ptpv2StatusTimescale.setStatus('current')
ptpv2StatusNumClient = MibTableColumn((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 1, 1, 1, 8), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 1000))).setMaxAccess("readonly")
if mibBuilder.loadTexts: ptpv2StatusNumClient.setStatus('current')
ptpv2StatusClientLoad = MibTableColumn((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 1, 1, 1, 9), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ptpv2StatusClientLoad.setStatus('current')
ptpv2ClientDataTable = MibTable((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 1, 2), )
if mibBuilder.loadTexts: ptpv2ClientDataTable.setStatus('current')
ptpv2ClientDataEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 1, 2, 1), ).setIndexNames((0, "SYMMCOMMONPTP", "ptpv2ClientDataIndex"))
if mibBuilder.loadTexts: ptpv2ClientDataEntry.setStatus('current')
ptpv2ClientDataIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 1, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 5000))).setMaxAccess("readonly")
if mibBuilder.loadTexts: ptpv2ClientDataIndex.setStatus('current')
ptpv2ClientData = MibTableColumn((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 1, 2, 1, 2), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ptpv2ClientData.setStatus('current')
ptpv2Config = MibIdentifier((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2))
ptpv2CommonTable = MibTable((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 1), )
if mibBuilder.loadTexts: ptpv2CommonTable.setStatus('current')
ptpv2CommonEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 1, 1), ).setIndexNames((0, "IF-MIB", "ifIndex"), (0, "SYMMCOMMONPTP", "ptpv2CommonIndex"))
if mibBuilder.loadTexts: ptpv2CommonEntry.setStatus('current')
ptpv2CommonIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 1000)))
if mibBuilder.loadTexts: ptpv2CommonIndex.setStatus('current')
ptpv2Profile = MibTableColumn((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 1, 1, 2), PTPPROFILEVALUE()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: ptpv2Profile.setStatus('current')
ptpv2ClockID = MibTableColumn((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 1, 1, 3), DisplayString()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: ptpv2ClockID.setStatus('current')
ptpv2Priority1 = MibTableColumn((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 1, 1, 4), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(0, 255))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: ptpv2Priority1.setStatus('current')
ptpv2Priority2 = MibTableColumn((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 1, 1, 5), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(0, 255))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: ptpv2Priority2.setStatus('current')
ptpv2Domain = MibTableColumn((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 1, 1, 6), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(0, 255))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: ptpv2Domain.setStatus('current')
ptpv2DSCPState = MibTableColumn((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 1, 1, 7), EnableValue()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: ptpv2DSCPState.setStatus('current')
ptpv2DSCPValue = MibTableColumn((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 1, 1, 8), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(0, 63))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: ptpv2DSCPValue.setStatus('current')
ptpv2State = MibTableColumn((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 1, 1, 9), EnableValue()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: ptpv2State.setStatus('current')
ptpv2MaxClient = MibTableColumn((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 1, 1, 10), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 1500)).clone(500)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: ptpv2MaxClient.setStatus('current')
ptpv2AnnounceLimit = MibTableColumn((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 1, 1, 11), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-4, 4)).clone(-3)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: ptpv2AnnounceLimit.setStatus('current')
ptpv2SyncLimit = MibTableColumn((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 1, 1, 12), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-7, 7)).clone(-7)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: ptpv2SyncLimit.setStatus('current')
ptpv2DelayLimit = MibTableColumn((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 1, 1, 13), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-7, 7)).clone(-7)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: ptpv2DelayLimit.setStatus('current')
ptpv2TwoStep = MibTableColumn((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 1, 1, 14), EnableValue()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: ptpv2TwoStep.setStatus('current')
ptpv2MgmtAddrMode = MibTableColumn((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 1, 1, 15), PTPMGMTADDRTYPE()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: ptpv2MgmtAddrMode.setStatus('current')
ptpv2TTL = MibTableColumn((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 1, 1, 16), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1, 255))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: ptpv2TTL.setStatus('current')
ptpv2AlternateGM = MibTableColumn((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 1, 1, 17), EnableValue()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: ptpv2AlternateGM.setStatus('current')
ptpv2TimeScale = MibTableColumn((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 1, 1, 18), PTPTIMESCALETYPE()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: ptpv2TimeScale.setStatus('current')
ptpv2Dither = MibTableColumn((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 1, 1, 19), EnableValue()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: ptpv2Dither.setStatus('current')
ptpv2ServiceLoadAlarmThreshold = MibTableColumn((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 1, 1, 20), Integer32().subtype(subtypeSpec=ValueRangeConstraint(10, 100))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: ptpv2ServiceLoadAlarmThreshold.setStatus('current')
ptpv2UnicastTable = MibTable((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 2), )
if mibBuilder.loadTexts: ptpv2UnicastTable.setStatus('current')
ptpv2UnicastEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 2, 1), ).setIndexNames((0, "IF-MIB", "ifIndex"), (0, "SYMMCOMMONPTP", "ptpv2UnicastIndex"))
if mibBuilder.loadTexts: ptpv2UnicastEntry.setStatus('current')
ptpv2UnicastIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 1000)))
if mibBuilder.loadTexts: ptpv2UnicastIndex.setStatus('current')
ptpv2UnicastNeg = MibTableColumn((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 2, 1, 2), EnableValue()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: ptpv2UnicastNeg.setStatus('current')
ptpv2UnicastLeaseDurLimit = MibTableColumn((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 2, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(10, 1000))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: ptpv2UnicastLeaseDurLimit.setStatus('current')
ptpv2UnicastInterfaceRateTLV = MibTableColumn((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 2, 1, 4), EnableValue()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: ptpv2UnicastInterfaceRateTLV.setStatus('current')
ptpv2UnicastLeaseExtension = MibTableColumn((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 2, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 1000))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: ptpv2UnicastLeaseExtension.setStatus('current')
ptpv2MulticastTable = MibTable((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 3), )
if mibBuilder.loadTexts: ptpv2MulticastTable.setStatus('current')
ptpv2MulticastEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 3, 1), ).setIndexNames((0, "IF-MIB", "ifIndex"), (0, "SYMMCOMMONPTP", "ptpv2MulticastIndex"))
if mibBuilder.loadTexts: ptpv2MulticastEntry.setStatus('current')
ptpv2MulticastIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 3, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 1000)))
if mibBuilder.loadTexts: ptpv2MulticastIndex.setStatus('current')
ptpv2MulticastAnnounceInt = MibTableColumn((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 3, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-4, 4))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: ptpv2MulticastAnnounceInt.setStatus('current')
ptpv2MulticastSyncInt = MibTableColumn((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 3, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-7, 7))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: ptpv2MulticastSyncInt.setStatus('current')
ptpv2MulticastDelayInt = MibTableColumn((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 3, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-7, 7))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: ptpv2MulticastDelayInt.setStatus('current')
ptpv2MulticastAnnoTimeout = MibTableColumn((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 3, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(2, 10)).clone(2)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: ptpv2MulticastAnnoTimeout.setStatus('current')
ptpv2MulticastVlanId = MibTableColumn((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 3, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 4094))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: ptpv2MulticastVlanId.setStatus('current')
ptpv2MulticastClientTimeout = MibTableColumn((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 3, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(10, 3600)).clone(360)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: ptpv2MulticastClientTimeout.setStatus('current')
ptpv2G82751Table = MibTable((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 4), )
if mibBuilder.loadTexts: ptpv2G82751Table.setStatus('current')
ptpv2G82751Entry = MibTableRow((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 4, 1), ).setIndexNames((0, "IF-MIB", "ifIndex"), (0, "SYMMCOMMONPTP", "ptpv2G82751Index"))
if mibBuilder.loadTexts: ptpv2G82751Entry.setStatus('current')
ptpv2G82751Index = MibTableColumn((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 4, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 1000)))
if mibBuilder.loadTexts: ptpv2G82751Index.setStatus('current')
ptpv2G82751MulticastAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 4, 1, 2), G82751McAddrValue()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: ptpv2G82751MulticastAddr.setStatus('current')
ptpv2G82751LocalPriority = MibTableColumn((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 4, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 255))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: ptpv2G82751LocalPriority.setStatus('current')
ptpv2ReflectorTable = MibTable((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 5), )
if mibBuilder.loadTexts: ptpv2ReflectorTable.setStatus('current')
ptpv2ReflectorEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 5, 1), ).setIndexNames((0, "IF-MIB", "ifIndex"), (0, "SYMMCOMMONPTP", "ptpv2ReflectorIndex"))
if mibBuilder.loadTexts: ptpv2ReflectorEntry.setStatus('current')
ptpv2ReflectorIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 5, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 1000)))
if mibBuilder.loadTexts: ptpv2ReflectorIndex.setStatus('current')
ptpv2ReflectorAnnounceIntv = MibTableColumn((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 5, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-3, 0))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: ptpv2ReflectorAnnounceIntv.setStatus('current')
ptpv2ReflectorSyncDelayIntv = MibTableColumn((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 5, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-7, -4))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: ptpv2ReflectorSyncDelayIntv.setStatus('current')
ptpv2ReflectorClientTimeout = MibTableColumn((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 5, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(60, 1000))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: ptpv2ReflectorClientTimeout.setStatus('current')
ptpv2ReflectorVlanID = MibTableColumn((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 5, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 4094))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: ptpv2ReflectorVlanID.setStatus('current')
ptpv2Conformance = ObjectIdentity((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 3))
if mibBuilder.loadTexts: ptpv2Conformance.setStatus('current')
ptpv2Compliances = MibIdentifier((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 3, 1))
ptpv2BasicCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 3, 1, 1)).setObjects(("SYMMCOMMONPTP", "ptpv2StatusGroup"), ("SYMMCOMMONPTP", "ptpv2ClientDataGroup"), ("SYMMCOMMONPTP", "ptpv2CommonGroup"), ("SYMMCOMMONPTP", "ptpv2UnicastGroup"), ("SYMMCOMMONPTP", "ptpv2MulticastGroup"), ("SYMMCOMMONPTP", "ptpv2G82751Group"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ptpv2BasicCompliance = ptpv2BasicCompliance.setStatus('current')
ptpv2UocGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 3, 2))
ptpv2StatusGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 3, 2, 1)).setObjects(("SYMMCOMMONPTP", "ptpv2StatusPortEnable"), ("SYMMCOMMONPTP", "ptpv2StatusClockID"), ("SYMMCOMMONPTP", "ptpv2StatusProfile"), ("SYMMCOMMONPTP", "ptpv2StatusClockClass"), ("SYMMCOMMONPTP", "ptpv2StatusClockAccuracy"), ("SYMMCOMMONPTP", "ptpv2StatusTimescale"), ("SYMMCOMMONPTP", "ptpv2StatusNumClient"), ("SYMMCOMMONPTP", "ptpv2StatusClientLoad"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ptpv2StatusGroup = ptpv2StatusGroup.setStatus('current')
ptpv2ClientDataGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 3, 2, 2)).setObjects(("SYMMCOMMONPTP", "ptpv2ClientDataIndex"), ("SYMMCOMMONPTP", "ptpv2ClientData"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ptpv2ClientDataGroup = ptpv2ClientDataGroup.setStatus('current')
ptpv2CommonGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 3, 2, 3)).setObjects(("SYMMCOMMONPTP", "ptpv2Profile"), ("SYMMCOMMONPTP", "ptpv2ClockID"), ("SYMMCOMMONPTP", "ptpv2Priority1"), ("SYMMCOMMONPTP", "ptpv2Priority2"), ("SYMMCOMMONPTP", "ptpv2Domain"), ("SYMMCOMMONPTP", "ptpv2DSCPState"), ("SYMMCOMMONPTP", "ptpv2DSCPValue"), ("SYMMCOMMONPTP", "ptpv2State"), ("SYMMCOMMONPTP", "ptpv2MaxClient"), ("SYMMCOMMONPTP", "ptpv2AnnounceLimit"), ("SYMMCOMMONPTP", "ptpv2SyncLimit"), ("SYMMCOMMONPTP", "ptpv2DelayLimit"), ("SYMMCOMMONPTP", "ptpv2TwoStep"), ("SYMMCOMMONPTP", "ptpv2MgmtAddrMode"), ("SYMMCOMMONPTP", "ptpv2TTL"), ("SYMMCOMMONPTP", "ptpv2AlternateGM"), ("SYMMCOMMONPTP", "ptpv2TimeScale"), ("SYMMCOMMONPTP", "ptpv2Dither"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ptpv2CommonGroup = ptpv2CommonGroup.setStatus('current')
ptpv2UnicastGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 3, 2, 4)).setObjects(("SYMMCOMMONPTP", "ptpv2UnicastNeg"), ("SYMMCOMMONPTP", "ptpv2UnicastLeaseDurLimit"), ("SYMMCOMMONPTP", "ptpv2UnicastInterfaceRateTLV"), ("SYMMCOMMONPTP", "ptpv2UnicastLeaseExtension"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ptpv2UnicastGroup = ptpv2UnicastGroup.setStatus('current')
ptpv2MulticastGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 3, 2, 5)).setObjects(("SYMMCOMMONPTP", "ptpv2MulticastAnnounceInt"), ("SYMMCOMMONPTP", "ptpv2MulticastSyncInt"), ("SYMMCOMMONPTP", "ptpv2MulticastDelayInt"), ("SYMMCOMMONPTP", "ptpv2MulticastAnnoTimeout"), ("SYMMCOMMONPTP", "ptpv2MulticastVlanId"), ("SYMMCOMMONPTP", "ptpv2MulticastClientTimeout"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ptpv2MulticastGroup = ptpv2MulticastGroup.setStatus('current')
ptpv2G82751Group = ObjectGroup((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 3, 2, 6)).setObjects(("SYMMCOMMONPTP", "ptpv2G82751MulticastAddr"), ("SYMMCOMMONPTP", "ptpv2G82751LocalPriority"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ptpv2G82751Group = ptpv2G82751Group.setStatus('current')
mibBuilder.exportSymbols("SYMMCOMMONPTP", ptpv2ReflectorAnnounceIntv=ptpv2ReflectorAnnounceIntv, PYSNMP_MODULE_ID=symmPTPv2, ptpv2Domain=ptpv2Domain, ptpv2StatusClockClass=ptpv2StatusClockClass, ptpv2StatusNumClient=ptpv2StatusNumClient, ptpv2ClientDataTable=ptpv2ClientDataTable, PTPADDRMODETYPE=PTPADDRMODETYPE, ptpv2ClientData=ptpv2ClientData, ptpv2UnicastTable=ptpv2UnicastTable, ptpv2ReflectorSyncDelayIntv=ptpv2ReflectorSyncDelayIntv, ptpv2TTL=ptpv2TTL, ptpv2Compliances=ptpv2Compliances, ptpv2G82751Index=ptpv2G82751Index, ptpv2MulticastClientTimeout=ptpv2MulticastClientTimeout, PTPMGMTADDRTYPE=PTPMGMTADDRTYPE, DateAndTime=DateAndTime, ptpv2StatusTimescale=ptpv2StatusTimescale, ptpv2Profile=ptpv2Profile, ptpv2G82751Entry=ptpv2G82751Entry, ptpv2StatusProfile=ptpv2StatusProfile, ptpv2MulticastSyncInt=ptpv2MulticastSyncInt, ptpv2State=ptpv2State, ptpv2CommonIndex=ptpv2CommonIndex, ptpv2MulticastGroup=ptpv2MulticastGroup, ptpv2StatusClockAccuracy=ptpv2StatusClockAccuracy, ptpv2TimeScale=ptpv2TimeScale, ptpv2UocGroups=ptpv2UocGroups, ptpv2ClockID=ptpv2ClockID, ptpv2UnicastInterfaceRateTLV=ptpv2UnicastInterfaceRateTLV, ptpv2G82751Group=ptpv2G82751Group, ptpv2StatusGroup=ptpv2StatusGroup, VLANID=VLANID, ptpv2MulticastIndex=ptpv2MulticastIndex, ptpv2MulticastTable=ptpv2MulticastTable, PTPTIMESCALETYPE=PTPTIMESCALETYPE, PTPTRANSPORTTYPE=PTPTRANSPORTTYPE, ptpv2StatusEntry=ptpv2StatusEntry, ptpv2ReflectorEntry=ptpv2ReflectorEntry, ptpv2MulticastVlanId=ptpv2MulticastVlanId, ptpv2UnicastEntry=ptpv2UnicastEntry, ptpv2Config=ptpv2Config, ptpv2TwoStep=ptpv2TwoStep, ptpv2CommonTable=ptpv2CommonTable, PTPPROFILEVALUE=PTPPROFILEVALUE, ptpv2DSCPState=ptpv2DSCPState, TLatAndLon=TLatAndLon, ptpv2CommonGroup=ptpv2CommonGroup, ptpv2UnicastIndex=ptpv2UnicastIndex, ptpv2G82751LocalPriority=ptpv2G82751LocalPriority, ptpv2MaxClient=ptpv2MaxClient, ptpv2G82751Table=ptpv2G82751Table, ptpv2ClientDataGroup=ptpv2ClientDataGroup, ptpv2MulticastAnnounceInt=ptpv2MulticastAnnounceInt, G82751McAddrValue=G82751McAddrValue, ptpv2AlternateGM=ptpv2AlternateGM, ptpv2Status=ptpv2Status, TSsm=TSsm, ptpv2UnicastNeg=ptpv2UnicastNeg, ptpv2StatusIndex=ptpv2StatusIndex, ptpv2ClientDataEntry=ptpv2ClientDataEntry, ptpv2BasicCompliance=ptpv2BasicCompliance, TLocalTimeOffset=TLocalTimeOffset, ptpv2ServiceLoadAlarmThreshold=ptpv2ServiceLoadAlarmThreshold, ptpv2StatusTable=ptpv2StatusTable, ptpv2MgmtAddrMode=ptpv2MgmtAddrMode, ptpv2AnnounceLimit=ptpv2AnnounceLimit, ptpv2DSCPValue=ptpv2DSCPValue, PORTSTATEVALUE=PORTSTATEVALUE, ptpv2ReflectorTable=ptpv2ReflectorTable, symmPTPv2=symmPTPv2, ptpv2ClientDataIndex=ptpv2ClientDataIndex, ptpv2UnicastGroup=ptpv2UnicastGroup, ptpv2StatusClockID=ptpv2StatusClockID, ptpv2MulticastEntry=ptpv2MulticastEntry, ptpv2ReflectorClientTimeout=ptpv2ReflectorClientTimeout, ptpv2StatusClientLoad=ptpv2StatusClientLoad, ptpv2SyncLimit=ptpv2SyncLimit, ptpv2Priority1=ptpv2Priority1, ptpv2ReflectorIndex=ptpv2ReflectorIndex, ptpv2G82751MulticastAddr=ptpv2G82751MulticastAddr, TAntHeight=TAntHeight, ptpv2DelayLimit=ptpv2DelayLimit, ptpv2ReflectorVlanID=ptpv2ReflectorVlanID, ptpv2StatusPortEnable=ptpv2StatusPortEnable, ptpv2UnicastLeaseDurLimit=ptpv2UnicastLeaseDurLimit, ptpv2MulticastDelayInt=ptpv2MulticastDelayInt, ptpv2Conformance=ptpv2Conformance, ptpv2Dither=ptpv2Dither, ptpv2Priority2=ptpv2Priority2, ptpv2UnicastLeaseExtension=ptpv2UnicastLeaseExtension, ptpv2MulticastAnnoTimeout=ptpv2MulticastAnnoTimeout, ptpv2CommonEntry=ptpv2CommonEntry)
|
(integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, constraints_intersection, value_size_constraint, value_range_constraint, single_value_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsUnion', 'ConstraintsIntersection', 'ValueSizeConstraint', 'ValueRangeConstraint', 'SingleValueConstraint')
(ent_physical_index,) = mibBuilder.importSymbols('ENTITY-MIB', 'entPhysicalIndex')
(if_index, if_number) = mibBuilder.importSymbols('IF-MIB', 'ifIndex', 'ifNumber')
(notification_group, module_compliance, object_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance', 'ObjectGroup')
(notification_type, counter64, mib_scalar, mib_table, mib_table_row, mib_table_column, integer32, time_ticks, unsigned32, object_identity, module_identity, iso, bits, mib_identifier, counter32, gauge32, ip_address) = mibBuilder.importSymbols('SNMPv2-SMI', 'NotificationType', 'Counter64', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'Integer32', 'TimeTicks', 'Unsigned32', 'ObjectIdentity', 'ModuleIdentity', 'iso', 'Bits', 'MibIdentifier', 'Counter32', 'Gauge32', 'IpAddress')
(display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention')
(enable_value, symm_packet_service) = mibBuilder.importSymbols('SYMM-COMMON-SMI', 'EnableValue', 'symmPacketService')
symm_pt_pv2 = module_identity((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1))
symmPTPv2.setRevisions(('2018-07-31 06:20',))
if mibBuilder.loadTexts:
symmPTPv2.setLastUpdated('201807310620Z')
if mibBuilder.loadTexts:
symmPTPv2.setOrganization('Symmetricom')
class Ptpprofilevalue(Integer32):
subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(1, 2, 3, 4, 5, 6, 7))
named_values = named_values(('profileTelecom2008', 1), ('profileDefault', 2), ('profileHybrid', 3), ('profileITU8265one', 4), ('profileEthernetDefault', 5), ('profileITU8275one', 6), ('profileITU8275two', 7))
class Ptptimescaletype(Integer32):
subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(1, 2, 3))
named_values = named_values(('auto', 1), ('arb', 2), ('ptp', 3))
class Ptpmgmtaddrtype(Integer32):
subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(0, 1))
named_values = named_values(('unicast', 0), ('multicast', 1))
class Ptptransporttype(Integer32):
subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(1, 2))
named_values = named_values(('ethernet', 1), ('ipv4', 2))
class Ptpaddrmodetype(Integer32):
subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(0, 1, 2))
named_values = named_values(('unicast', 0), ('multicast', 1), ('multicasthybrid', 2))
class Portstatevalue(Integer32):
subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(1, 2))
named_values = named_values(('enable', 1), ('disable', 2))
class G82751Mcaddrvalue(Integer32):
subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(1, 2))
named_values = named_values(('mac011b19000000', 1), ('mac0180c200000e', 2))
class Vlanid(Integer32):
subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(1))
named_values = named_values(('none', 1))
class Dateandtime(TextualConvention, OctetString):
status = 'current'
display_hint = '2d-1d-1d,1d:1d:1d.1d,1a1d:1d'
subtype_spec = OctetString.subtypeSpec + constraints_union(value_size_constraint(8, 8), value_size_constraint(11, 11))
class Tlatandlon(TextualConvention, OctetString):
status = 'current'
display_hint = '1a1d:1d:1d.1d'
subtype_spec = OctetString.subtypeSpec + value_size_constraint(5, 5)
fixed_length = 5
class Tantheight(TextualConvention, OctetString):
status = 'current'
display_hint = '1a2d.1d'
subtype_spec = OctetString.subtypeSpec + value_size_constraint(4, 4)
fixed_length = 4
class Tlocaltimeoffset(TextualConvention, OctetString):
status = 'current'
display_hint = '1a1d:1d'
subtype_spec = OctetString.subtypeSpec + value_size_constraint(3, 3)
fixed_length = 3
class Tssm(TextualConvention, Integer32):
status = 'current'
display_hint = 'x'
subtype_spec = Integer32.subtypeSpec + value_range_constraint(0, 255)
ptpv2_status = mib_identifier((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 1))
ptpv2_status_table = mib_table((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 1, 1))
if mibBuilder.loadTexts:
ptpv2StatusTable.setStatus('current')
ptpv2_status_entry = mib_table_row((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 1, 1, 1)).setIndexNames((0, 'IF-MIB', 'ifIndex'), (0, 'SYMMCOMMONPTP', 'ptpv2StatusIndex'))
if mibBuilder.loadTexts:
ptpv2StatusEntry.setStatus('current')
ptpv2_status_index = mib_table_column((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 1, 1, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(1, 1000)))
if mibBuilder.loadTexts:
ptpv2StatusIndex.setStatus('current')
ptpv2_status_port_enable = mib_table_column((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 1, 1, 1, 2), enable_value()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ptpv2StatusPortEnable.setStatus('current')
ptpv2_status_clock_id = mib_table_column((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 1, 1, 1, 3), display_string()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ptpv2StatusClockID.setStatus('current')
ptpv2_status_profile = mib_table_column((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 1, 1, 1, 4), ptpprofilevalue()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ptpv2StatusProfile.setStatus('current')
ptpv2_status_clock_class = mib_table_column((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 1, 1, 1, 5), display_string()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ptpv2StatusClockClass.setStatus('current')
ptpv2_status_clock_accuracy = mib_table_column((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 1, 1, 1, 6), display_string()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ptpv2StatusClockAccuracy.setStatus('current')
ptpv2_status_timescale = mib_table_column((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 1, 1, 1, 7), ptptimescaletype()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ptpv2StatusTimescale.setStatus('current')
ptpv2_status_num_client = mib_table_column((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 1, 1, 1, 8), integer32().subtype(subtypeSpec=value_range_constraint(0, 1000))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ptpv2StatusNumClient.setStatus('current')
ptpv2_status_client_load = mib_table_column((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 1, 1, 1, 9), display_string()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ptpv2StatusClientLoad.setStatus('current')
ptpv2_client_data_table = mib_table((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 1, 2))
if mibBuilder.loadTexts:
ptpv2ClientDataTable.setStatus('current')
ptpv2_client_data_entry = mib_table_row((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 1, 2, 1)).setIndexNames((0, 'SYMMCOMMONPTP', 'ptpv2ClientDataIndex'))
if mibBuilder.loadTexts:
ptpv2ClientDataEntry.setStatus('current')
ptpv2_client_data_index = mib_table_column((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 1, 2, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(1, 5000))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ptpv2ClientDataIndex.setStatus('current')
ptpv2_client_data = mib_table_column((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 1, 2, 1, 2), display_string()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ptpv2ClientData.setStatus('current')
ptpv2_config = mib_identifier((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2))
ptpv2_common_table = mib_table((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 1))
if mibBuilder.loadTexts:
ptpv2CommonTable.setStatus('current')
ptpv2_common_entry = mib_table_row((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 1, 1)).setIndexNames((0, 'IF-MIB', 'ifIndex'), (0, 'SYMMCOMMONPTP', 'ptpv2CommonIndex'))
if mibBuilder.loadTexts:
ptpv2CommonEntry.setStatus('current')
ptpv2_common_index = mib_table_column((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 1, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(1, 1000)))
if mibBuilder.loadTexts:
ptpv2CommonIndex.setStatus('current')
ptpv2_profile = mib_table_column((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 1, 1, 2), ptpprofilevalue()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
ptpv2Profile.setStatus('current')
ptpv2_clock_id = mib_table_column((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 1, 1, 3), display_string()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
ptpv2ClockID.setStatus('current')
ptpv2_priority1 = mib_table_column((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 1, 1, 4), unsigned32().subtype(subtypeSpec=value_range_constraint(0, 255))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
ptpv2Priority1.setStatus('current')
ptpv2_priority2 = mib_table_column((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 1, 1, 5), unsigned32().subtype(subtypeSpec=value_range_constraint(0, 255))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
ptpv2Priority2.setStatus('current')
ptpv2_domain = mib_table_column((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 1, 1, 6), unsigned32().subtype(subtypeSpec=value_range_constraint(0, 255))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
ptpv2Domain.setStatus('current')
ptpv2_dscp_state = mib_table_column((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 1, 1, 7), enable_value()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
ptpv2DSCPState.setStatus('current')
ptpv2_dscp_value = mib_table_column((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 1, 1, 8), unsigned32().subtype(subtypeSpec=value_range_constraint(0, 63))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
ptpv2DSCPValue.setStatus('current')
ptpv2_state = mib_table_column((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 1, 1, 9), enable_value()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
ptpv2State.setStatus('current')
ptpv2_max_client = mib_table_column((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 1, 1, 10), integer32().subtype(subtypeSpec=value_range_constraint(1, 1500)).clone(500)).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
ptpv2MaxClient.setStatus('current')
ptpv2_announce_limit = mib_table_column((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 1, 1, 11), integer32().subtype(subtypeSpec=value_range_constraint(-4, 4)).clone(-3)).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
ptpv2AnnounceLimit.setStatus('current')
ptpv2_sync_limit = mib_table_column((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 1, 1, 12), integer32().subtype(subtypeSpec=value_range_constraint(-7, 7)).clone(-7)).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
ptpv2SyncLimit.setStatus('current')
ptpv2_delay_limit = mib_table_column((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 1, 1, 13), integer32().subtype(subtypeSpec=value_range_constraint(-7, 7)).clone(-7)).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
ptpv2DelayLimit.setStatus('current')
ptpv2_two_step = mib_table_column((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 1, 1, 14), enable_value()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
ptpv2TwoStep.setStatus('current')
ptpv2_mgmt_addr_mode = mib_table_column((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 1, 1, 15), ptpmgmtaddrtype()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
ptpv2MgmtAddrMode.setStatus('current')
ptpv2_ttl = mib_table_column((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 1, 1, 16), unsigned32().subtype(subtypeSpec=value_range_constraint(1, 255))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
ptpv2TTL.setStatus('current')
ptpv2_alternate_gm = mib_table_column((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 1, 1, 17), enable_value()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
ptpv2AlternateGM.setStatus('current')
ptpv2_time_scale = mib_table_column((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 1, 1, 18), ptptimescaletype()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
ptpv2TimeScale.setStatus('current')
ptpv2_dither = mib_table_column((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 1, 1, 19), enable_value()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
ptpv2Dither.setStatus('current')
ptpv2_service_load_alarm_threshold = mib_table_column((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 1, 1, 20), integer32().subtype(subtypeSpec=value_range_constraint(10, 100))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
ptpv2ServiceLoadAlarmThreshold.setStatus('current')
ptpv2_unicast_table = mib_table((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 2))
if mibBuilder.loadTexts:
ptpv2UnicastTable.setStatus('current')
ptpv2_unicast_entry = mib_table_row((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 2, 1)).setIndexNames((0, 'IF-MIB', 'ifIndex'), (0, 'SYMMCOMMONPTP', 'ptpv2UnicastIndex'))
if mibBuilder.loadTexts:
ptpv2UnicastEntry.setStatus('current')
ptpv2_unicast_index = mib_table_column((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 2, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(1, 1000)))
if mibBuilder.loadTexts:
ptpv2UnicastIndex.setStatus('current')
ptpv2_unicast_neg = mib_table_column((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 2, 1, 2), enable_value()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
ptpv2UnicastNeg.setStatus('current')
ptpv2_unicast_lease_dur_limit = mib_table_column((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 2, 1, 3), integer32().subtype(subtypeSpec=value_range_constraint(10, 1000))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
ptpv2UnicastLeaseDurLimit.setStatus('current')
ptpv2_unicast_interface_rate_tlv = mib_table_column((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 2, 1, 4), enable_value()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
ptpv2UnicastInterfaceRateTLV.setStatus('current')
ptpv2_unicast_lease_extension = mib_table_column((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 2, 1, 5), integer32().subtype(subtypeSpec=value_range_constraint(0, 1000))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
ptpv2UnicastLeaseExtension.setStatus('current')
ptpv2_multicast_table = mib_table((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 3))
if mibBuilder.loadTexts:
ptpv2MulticastTable.setStatus('current')
ptpv2_multicast_entry = mib_table_row((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 3, 1)).setIndexNames((0, 'IF-MIB', 'ifIndex'), (0, 'SYMMCOMMONPTP', 'ptpv2MulticastIndex'))
if mibBuilder.loadTexts:
ptpv2MulticastEntry.setStatus('current')
ptpv2_multicast_index = mib_table_column((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 3, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(1, 1000)))
if mibBuilder.loadTexts:
ptpv2MulticastIndex.setStatus('current')
ptpv2_multicast_announce_int = mib_table_column((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 3, 1, 2), integer32().subtype(subtypeSpec=value_range_constraint(-4, 4))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
ptpv2MulticastAnnounceInt.setStatus('current')
ptpv2_multicast_sync_int = mib_table_column((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 3, 1, 3), integer32().subtype(subtypeSpec=value_range_constraint(-7, 7))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
ptpv2MulticastSyncInt.setStatus('current')
ptpv2_multicast_delay_int = mib_table_column((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 3, 1, 4), integer32().subtype(subtypeSpec=value_range_constraint(-7, 7))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
ptpv2MulticastDelayInt.setStatus('current')
ptpv2_multicast_anno_timeout = mib_table_column((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 3, 1, 5), integer32().subtype(subtypeSpec=value_range_constraint(2, 10)).clone(2)).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
ptpv2MulticastAnnoTimeout.setStatus('current')
ptpv2_multicast_vlan_id = mib_table_column((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 3, 1, 6), integer32().subtype(subtypeSpec=value_range_constraint(0, 4094))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
ptpv2MulticastVlanId.setStatus('current')
ptpv2_multicast_client_timeout = mib_table_column((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 3, 1, 7), integer32().subtype(subtypeSpec=value_range_constraint(10, 3600)).clone(360)).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
ptpv2MulticastClientTimeout.setStatus('current')
ptpv2_g82751_table = mib_table((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 4))
if mibBuilder.loadTexts:
ptpv2G82751Table.setStatus('current')
ptpv2_g82751_entry = mib_table_row((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 4, 1)).setIndexNames((0, 'IF-MIB', 'ifIndex'), (0, 'SYMMCOMMONPTP', 'ptpv2G82751Index'))
if mibBuilder.loadTexts:
ptpv2G82751Entry.setStatus('current')
ptpv2_g82751_index = mib_table_column((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 4, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(1, 1000)))
if mibBuilder.loadTexts:
ptpv2G82751Index.setStatus('current')
ptpv2_g82751_multicast_addr = mib_table_column((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 4, 1, 2), g82751_mc_addr_value()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
ptpv2G82751MulticastAddr.setStatus('current')
ptpv2_g82751_local_priority = mib_table_column((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 4, 1, 3), integer32().subtype(subtypeSpec=value_range_constraint(1, 255))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
ptpv2G82751LocalPriority.setStatus('current')
ptpv2_reflector_table = mib_table((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 5))
if mibBuilder.loadTexts:
ptpv2ReflectorTable.setStatus('current')
ptpv2_reflector_entry = mib_table_row((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 5, 1)).setIndexNames((0, 'IF-MIB', 'ifIndex'), (0, 'SYMMCOMMONPTP', 'ptpv2ReflectorIndex'))
if mibBuilder.loadTexts:
ptpv2ReflectorEntry.setStatus('current')
ptpv2_reflector_index = mib_table_column((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 5, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(1, 1000)))
if mibBuilder.loadTexts:
ptpv2ReflectorIndex.setStatus('current')
ptpv2_reflector_announce_intv = mib_table_column((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 5, 1, 2), integer32().subtype(subtypeSpec=value_range_constraint(-3, 0))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
ptpv2ReflectorAnnounceIntv.setStatus('current')
ptpv2_reflector_sync_delay_intv = mib_table_column((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 5, 1, 3), integer32().subtype(subtypeSpec=value_range_constraint(-7, -4))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
ptpv2ReflectorSyncDelayIntv.setStatus('current')
ptpv2_reflector_client_timeout = mib_table_column((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 5, 1, 4), integer32().subtype(subtypeSpec=value_range_constraint(60, 1000))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
ptpv2ReflectorClientTimeout.setStatus('current')
ptpv2_reflector_vlan_id = mib_table_column((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 2, 5, 1, 5), integer32().subtype(subtypeSpec=value_range_constraint(0, 4094))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
ptpv2ReflectorVlanID.setStatus('current')
ptpv2_conformance = object_identity((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 3))
if mibBuilder.loadTexts:
ptpv2Conformance.setStatus('current')
ptpv2_compliances = mib_identifier((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 3, 1))
ptpv2_basic_compliance = module_compliance((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 3, 1, 1)).setObjects(('SYMMCOMMONPTP', 'ptpv2StatusGroup'), ('SYMMCOMMONPTP', 'ptpv2ClientDataGroup'), ('SYMMCOMMONPTP', 'ptpv2CommonGroup'), ('SYMMCOMMONPTP', 'ptpv2UnicastGroup'), ('SYMMCOMMONPTP', 'ptpv2MulticastGroup'), ('SYMMCOMMONPTP', 'ptpv2G82751Group'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ptpv2_basic_compliance = ptpv2BasicCompliance.setStatus('current')
ptpv2_uoc_groups = mib_identifier((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 3, 2))
ptpv2_status_group = object_group((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 3, 2, 1)).setObjects(('SYMMCOMMONPTP', 'ptpv2StatusPortEnable'), ('SYMMCOMMONPTP', 'ptpv2StatusClockID'), ('SYMMCOMMONPTP', 'ptpv2StatusProfile'), ('SYMMCOMMONPTP', 'ptpv2StatusClockClass'), ('SYMMCOMMONPTP', 'ptpv2StatusClockAccuracy'), ('SYMMCOMMONPTP', 'ptpv2StatusTimescale'), ('SYMMCOMMONPTP', 'ptpv2StatusNumClient'), ('SYMMCOMMONPTP', 'ptpv2StatusClientLoad'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ptpv2_status_group = ptpv2StatusGroup.setStatus('current')
ptpv2_client_data_group = object_group((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 3, 2, 2)).setObjects(('SYMMCOMMONPTP', 'ptpv2ClientDataIndex'), ('SYMMCOMMONPTP', 'ptpv2ClientData'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ptpv2_client_data_group = ptpv2ClientDataGroup.setStatus('current')
ptpv2_common_group = object_group((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 3, 2, 3)).setObjects(('SYMMCOMMONPTP', 'ptpv2Profile'), ('SYMMCOMMONPTP', 'ptpv2ClockID'), ('SYMMCOMMONPTP', 'ptpv2Priority1'), ('SYMMCOMMONPTP', 'ptpv2Priority2'), ('SYMMCOMMONPTP', 'ptpv2Domain'), ('SYMMCOMMONPTP', 'ptpv2DSCPState'), ('SYMMCOMMONPTP', 'ptpv2DSCPValue'), ('SYMMCOMMONPTP', 'ptpv2State'), ('SYMMCOMMONPTP', 'ptpv2MaxClient'), ('SYMMCOMMONPTP', 'ptpv2AnnounceLimit'), ('SYMMCOMMONPTP', 'ptpv2SyncLimit'), ('SYMMCOMMONPTP', 'ptpv2DelayLimit'), ('SYMMCOMMONPTP', 'ptpv2TwoStep'), ('SYMMCOMMONPTP', 'ptpv2MgmtAddrMode'), ('SYMMCOMMONPTP', 'ptpv2TTL'), ('SYMMCOMMONPTP', 'ptpv2AlternateGM'), ('SYMMCOMMONPTP', 'ptpv2TimeScale'), ('SYMMCOMMONPTP', 'ptpv2Dither'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ptpv2_common_group = ptpv2CommonGroup.setStatus('current')
ptpv2_unicast_group = object_group((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 3, 2, 4)).setObjects(('SYMMCOMMONPTP', 'ptpv2UnicastNeg'), ('SYMMCOMMONPTP', 'ptpv2UnicastLeaseDurLimit'), ('SYMMCOMMONPTP', 'ptpv2UnicastInterfaceRateTLV'), ('SYMMCOMMONPTP', 'ptpv2UnicastLeaseExtension'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ptpv2_unicast_group = ptpv2UnicastGroup.setStatus('current')
ptpv2_multicast_group = object_group((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 3, 2, 5)).setObjects(('SYMMCOMMONPTP', 'ptpv2MulticastAnnounceInt'), ('SYMMCOMMONPTP', 'ptpv2MulticastSyncInt'), ('SYMMCOMMONPTP', 'ptpv2MulticastDelayInt'), ('SYMMCOMMONPTP', 'ptpv2MulticastAnnoTimeout'), ('SYMMCOMMONPTP', 'ptpv2MulticastVlanId'), ('SYMMCOMMONPTP', 'ptpv2MulticastClientTimeout'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ptpv2_multicast_group = ptpv2MulticastGroup.setStatus('current')
ptpv2_g82751_group = object_group((1, 3, 6, 1, 4, 1, 9070, 1, 2, 5, 1, 1, 3, 2, 6)).setObjects(('SYMMCOMMONPTP', 'ptpv2G82751MulticastAddr'), ('SYMMCOMMONPTP', 'ptpv2G82751LocalPriority'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ptpv2_g82751_group = ptpv2G82751Group.setStatus('current')
mibBuilder.exportSymbols('SYMMCOMMONPTP', ptpv2ReflectorAnnounceIntv=ptpv2ReflectorAnnounceIntv, PYSNMP_MODULE_ID=symmPTPv2, ptpv2Domain=ptpv2Domain, ptpv2StatusClockClass=ptpv2StatusClockClass, ptpv2StatusNumClient=ptpv2StatusNumClient, ptpv2ClientDataTable=ptpv2ClientDataTable, PTPADDRMODETYPE=PTPADDRMODETYPE, ptpv2ClientData=ptpv2ClientData, ptpv2UnicastTable=ptpv2UnicastTable, ptpv2ReflectorSyncDelayIntv=ptpv2ReflectorSyncDelayIntv, ptpv2TTL=ptpv2TTL, ptpv2Compliances=ptpv2Compliances, ptpv2G82751Index=ptpv2G82751Index, ptpv2MulticastClientTimeout=ptpv2MulticastClientTimeout, PTPMGMTADDRTYPE=PTPMGMTADDRTYPE, DateAndTime=DateAndTime, ptpv2StatusTimescale=ptpv2StatusTimescale, ptpv2Profile=ptpv2Profile, ptpv2G82751Entry=ptpv2G82751Entry, ptpv2StatusProfile=ptpv2StatusProfile, ptpv2MulticastSyncInt=ptpv2MulticastSyncInt, ptpv2State=ptpv2State, ptpv2CommonIndex=ptpv2CommonIndex, ptpv2MulticastGroup=ptpv2MulticastGroup, ptpv2StatusClockAccuracy=ptpv2StatusClockAccuracy, ptpv2TimeScale=ptpv2TimeScale, ptpv2UocGroups=ptpv2UocGroups, ptpv2ClockID=ptpv2ClockID, ptpv2UnicastInterfaceRateTLV=ptpv2UnicastInterfaceRateTLV, ptpv2G82751Group=ptpv2G82751Group, ptpv2StatusGroup=ptpv2StatusGroup, VLANID=VLANID, ptpv2MulticastIndex=ptpv2MulticastIndex, ptpv2MulticastTable=ptpv2MulticastTable, PTPTIMESCALETYPE=PTPTIMESCALETYPE, PTPTRANSPORTTYPE=PTPTRANSPORTTYPE, ptpv2StatusEntry=ptpv2StatusEntry, ptpv2ReflectorEntry=ptpv2ReflectorEntry, ptpv2MulticastVlanId=ptpv2MulticastVlanId, ptpv2UnicastEntry=ptpv2UnicastEntry, ptpv2Config=ptpv2Config, ptpv2TwoStep=ptpv2TwoStep, ptpv2CommonTable=ptpv2CommonTable, PTPPROFILEVALUE=PTPPROFILEVALUE, ptpv2DSCPState=ptpv2DSCPState, TLatAndLon=TLatAndLon, ptpv2CommonGroup=ptpv2CommonGroup, ptpv2UnicastIndex=ptpv2UnicastIndex, ptpv2G82751LocalPriority=ptpv2G82751LocalPriority, ptpv2MaxClient=ptpv2MaxClient, ptpv2G82751Table=ptpv2G82751Table, ptpv2ClientDataGroup=ptpv2ClientDataGroup, ptpv2MulticastAnnounceInt=ptpv2MulticastAnnounceInt, G82751McAddrValue=G82751McAddrValue, ptpv2AlternateGM=ptpv2AlternateGM, ptpv2Status=ptpv2Status, TSsm=TSsm, ptpv2UnicastNeg=ptpv2UnicastNeg, ptpv2StatusIndex=ptpv2StatusIndex, ptpv2ClientDataEntry=ptpv2ClientDataEntry, ptpv2BasicCompliance=ptpv2BasicCompliance, TLocalTimeOffset=TLocalTimeOffset, ptpv2ServiceLoadAlarmThreshold=ptpv2ServiceLoadAlarmThreshold, ptpv2StatusTable=ptpv2StatusTable, ptpv2MgmtAddrMode=ptpv2MgmtAddrMode, ptpv2AnnounceLimit=ptpv2AnnounceLimit, ptpv2DSCPValue=ptpv2DSCPValue, PORTSTATEVALUE=PORTSTATEVALUE, ptpv2ReflectorTable=ptpv2ReflectorTable, symmPTPv2=symmPTPv2, ptpv2ClientDataIndex=ptpv2ClientDataIndex, ptpv2UnicastGroup=ptpv2UnicastGroup, ptpv2StatusClockID=ptpv2StatusClockID, ptpv2MulticastEntry=ptpv2MulticastEntry, ptpv2ReflectorClientTimeout=ptpv2ReflectorClientTimeout, ptpv2StatusClientLoad=ptpv2StatusClientLoad, ptpv2SyncLimit=ptpv2SyncLimit, ptpv2Priority1=ptpv2Priority1, ptpv2ReflectorIndex=ptpv2ReflectorIndex, ptpv2G82751MulticastAddr=ptpv2G82751MulticastAddr, TAntHeight=TAntHeight, ptpv2DelayLimit=ptpv2DelayLimit, ptpv2ReflectorVlanID=ptpv2ReflectorVlanID, ptpv2StatusPortEnable=ptpv2StatusPortEnable, ptpv2UnicastLeaseDurLimit=ptpv2UnicastLeaseDurLimit, ptpv2MulticastDelayInt=ptpv2MulticastDelayInt, ptpv2Conformance=ptpv2Conformance, ptpv2Dither=ptpv2Dither, ptpv2Priority2=ptpv2Priority2, ptpv2UnicastLeaseExtension=ptpv2UnicastLeaseExtension, ptpv2MulticastAnnoTimeout=ptpv2MulticastAnnoTimeout, ptpv2CommonEntry=ptpv2CommonEntry)
|
class Solution:
def moveZeroes(self, nums: List[int]) -> None:
non_zeros = [i for i in range(len(nums)) if nums[i] != 0] # List comprehension to keep only numbers that are non -zero
nz = len(non_zeros)
nums[:nz] = [nums[i] for i in non_zeros] # edit the list to add non zero numbers to the list
nums[nz:] = [0] *(len(nums)-nz) #dd zeroes at the end
|
class Solution:
def move_zeroes(self, nums: List[int]) -> None:
non_zeros = [i for i in range(len(nums)) if nums[i] != 0]
nz = len(non_zeros)
nums[:nz] = [nums[i] for i in non_zeros]
nums[nz:] = [0] * (len(nums) - nz)
|
DEFAULT_OCR_AUTO_OCR = True
DEFAULT_OCR_BACKEND = 'mayan.apps.ocr.backends.tesseract.Tesseract'
DEFAULT_OCR_BACKEND_ARGUMENTS = {'environment': {'OMP_THREAD_LIMIT': '1'}}
TASK_DOCUMENT_VERSION_PAGE_OCR_RETRY_DELAY = 10
TASK_DOCUMENT_VERSION_PAGE_OCR_TIMEOUT = 10 * 60 # 10 Minutes per page
|
default_ocr_auto_ocr = True
default_ocr_backend = 'mayan.apps.ocr.backends.tesseract.Tesseract'
default_ocr_backend_arguments = {'environment': {'OMP_THREAD_LIMIT': '1'}}
task_document_version_page_ocr_retry_delay = 10
task_document_version_page_ocr_timeout = 10 * 60
|
input()
c = int(input())
a = sorted((map(int, input().split())))
a.sort(key= lambda x: x%c)
print(*a)
|
input()
c = int(input())
a = sorted(map(int, input().split()))
a.sort(key=lambda x: x % c)
print(*a)
|
def greet(name):
return "Hello {}".format(name)
print(greet("Alice"))
def greet2(name):
def greet_message():
return "Hello"
return "{} {}".format(greet_message(),name)
print(greet2("Alice"))
def change_name_greet(func):
name = "Alice"
return func(name)
print(change_name_greet(greet))
def upper(func):
def wrapper(name):
result = func(name)
return result.upper()
return wrapper
print(upper(greet)("Alice"))
|
def greet(name):
return 'Hello {}'.format(name)
print(greet('Alice'))
def greet2(name):
def greet_message():
return 'Hello'
return '{} {}'.format(greet_message(), name)
print(greet2('Alice'))
def change_name_greet(func):
name = 'Alice'
return func(name)
print(change_name_greet(greet))
def upper(func):
def wrapper(name):
result = func(name)
return result.upper()
return wrapper
print(upper(greet)('Alice'))
|
class Helpers(object):
"""
Adds additional helper functions that aren't part of the core or extended
API.
"""
def __init__(self, api):
self.api = api
def is_promotable(self, tail):
# type: (TransactionHash) -> bool
"""
Determines if a tail transaction is promotable.
:param tail:
Transaction hash. Must be a tail transaction.
"""
return self.api.check_consistency(tails=[tail])['state']
|
class Helpers(object):
"""
Adds additional helper functions that aren't part of the core or extended
API.
"""
def __init__(self, api):
self.api = api
def is_promotable(self, tail):
"""
Determines if a tail transaction is promotable.
:param tail:
Transaction hash. Must be a tail transaction.
"""
return self.api.check_consistency(tails=[tail])['state']
|
class FormClosedEventArgs(EventArgs):
"""
Provides data for the System.Windows.Forms.Form.FormClosed event.
FormClosedEventArgs(closeReason: CloseReason)
"""
@staticmethod
def __new__(self, closeReason):
""" __new__(cls: type,closeReason: CloseReason) """
pass
CloseReason = property(
lambda self: object(), lambda self, v: None, lambda self: None
)
"""Gets a value that indicates why the form was closed.
Get: CloseReason(self: FormClosedEventArgs) -> CloseReason
"""
|
class Formclosedeventargs(EventArgs):
"""
Provides data for the System.Windows.Forms.Form.FormClosed event.
FormClosedEventArgs(closeReason: CloseReason)
"""
@staticmethod
def __new__(self, closeReason):
""" __new__(cls: type,closeReason: CloseReason) """
pass
close_reason = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Gets a value that indicates why the form was closed.\n\n\n\nGet: CloseReason(self: FormClosedEventArgs) -> CloseReason\n\n\n\n'
|
s = b'abc'; print(s.islower(), s)
s = b'Abc'; print(s.islower(), s)
s = b'ABC'; print(s.islower(), s)
s = b'123'; print(s.islower(), s)
s = b'(_)'; print(s.islower(), s)
s = b'(abc)'; print(s.islower(), s)
s = b'(aBc)'; print(s.islower(), s)
s = bytearray(b'abc'); print(s.islower(), s)
s = bytearray(b'Abc'); print(s.islower(), s)
s = bytearray(b'ABC'); print(s.islower(), s)
s = bytearray(b'123'); print(s.islower(), s)
s = bytearray(b'(_)'); print(s.islower(), s)
s = bytearray(b'(abc)'); print(s.islower(), s)
s = bytearray(b'(aBc)'); print(s.islower(), s)
|
s = b'abc'
print(s.islower(), s)
s = b'Abc'
print(s.islower(), s)
s = b'ABC'
print(s.islower(), s)
s = b'123'
print(s.islower(), s)
s = b'(_)'
print(s.islower(), s)
s = b'(abc)'
print(s.islower(), s)
s = b'(aBc)'
print(s.islower(), s)
s = bytearray(b'abc')
print(s.islower(), s)
s = bytearray(b'Abc')
print(s.islower(), s)
s = bytearray(b'ABC')
print(s.islower(), s)
s = bytearray(b'123')
print(s.islower(), s)
s = bytearray(b'(_)')
print(s.islower(), s)
s = bytearray(b'(abc)')
print(s.islower(), s)
s = bytearray(b'(aBc)')
print(s.islower(), s)
|
class Solution:
def maxArea(self, height: List[int]) -> int:
i = 0
j = len(height)-1
res = 0
area = 0
while i < j:
area = min(height[i],height[j])*(j-i)
#print(area)
res = max(res,area)
if height[i]<height[j]:
i+=1
else:
j-=1
return res
|
class Solution:
def max_area(self, height: List[int]) -> int:
i = 0
j = len(height) - 1
res = 0
area = 0
while i < j:
area = min(height[i], height[j]) * (j - i)
res = max(res, area)
if height[i] < height[j]:
i += 1
else:
j -= 1
return res
|
explanations = {
'gamma': '''
Proportion of tree modifications that should use mutrel-informed choice for
node to move, rather than uniform choice
''',
'zeta': '''
Proportion of tree modifications that should use mutrel-informed choice for
destination to move node to, rather than uniform choice
''',
'iota': '''
Probability of initializing with mutrel-informed tree rather than fully
branching tree when beginning chain
'''
}
defaults = {
'gamma': 0.7,
'zeta': 0.7,
'iota': 0.7,
}
assert set(explanations.keys()) == set(defaults.keys())
|
explanations = {'gamma': '\n Proportion of tree modifications that should use mutrel-informed choice for\n node to move, rather than uniform choice\n ', 'zeta': '\n Proportion of tree modifications that should use mutrel-informed choice for\n destination to move node to, rather than uniform choice\n ', 'iota': '\n Probability of initializing with mutrel-informed tree rather than fully\n branching tree when beginning chain\n '}
defaults = {'gamma': 0.7, 'zeta': 0.7, 'iota': 0.7}
assert set(explanations.keys()) == set(defaults.keys())
|
def _impl(_ctx):
pass
bad_attrs = rule(implementation = _impl, attrs = {"1234isntvalid": attr.int()})
|
def _impl(_ctx):
pass
bad_attrs = rule(implementation=_impl, attrs={'1234isntvalid': attr.int()})
|
# Copyright (c) 2017 Hristo Iliev <github@hiliev.eu>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
# list of conditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# * Neither the name of the copyright holder nor the names of its
# contributors may be used to endorse or promote products derived from
# this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
DMU_TYPE_DESC = [
"unallocated", # 0
"object directory", # 1
"object array", # 2
"packed nvlist", # 3
"packed nvlist size", # 4
"bpobj", # 5
"bpobj header", # 6
"SPA space map header", # 7
"SPA space map", # 8
"ZIL intent log", # 9
"DMU dnode", # 10
"DMU objset", # 11
"DSL directory", # 12
"DSL directory child map", # 13
"DSL dataset snap map", # 14
"DSL props", # 15
"DSL dataset", # 16
"ZFS znode", # 17
"ZFS V0 ACL", # 18
"ZFS plain file", # 19
"ZFS directory", # 20
"ZFS master node", # 21
"ZFS delete queue", # 22
"zvol object", # 23
"zvol prop", # 24
"other uint8[]", # 25
"other uint64[]", # 26
"other ZAP", # 27
"persistent error log", # 28
"SPA history", # 29
"SPA history offsets", # 30
"Pool properties", # 31
"DSL permissions", # 32
"ZFS ACL", # 33
"ZFS SYSACL", # 34
"FUID table", # 35
"FUID table size", # 36
"DSL dataset next clones", # 37
"scan work queue", # 38
"ZFS user/group used", # 39
"ZFS user/group quota", # 40
"snapshot refcount tags", # 41
"DDT ZAP algorithm", # 42
"DDT statistics", # 43
"System attributes", # 44
"SA master node", # 45
"SA attr registration", # 46
"SA attr layouts", # 47
"scan translations", # 48
"deduplicated block", # 49
"DSL deadlist map", # 50
"DSL deadlist map hdr", # 51
"DSL dir clones", # 52
"bpobj subobj" # 53
]
COMP_DESC = [
"invalid",
"lzjb",
"off",
"lzjb",
"empty",
"gzip1",
"gzip2",
"gzip3",
"gzip4",
"gzip5",
"gzip6",
"gzip7",
"gzip8",
"gzip9",
"zle",
"lz4"
]
CHKSUM_DESC = ["invalid", "fletcher2", "none", "SHA-256", "SHA-256", "fletcher2", "fletcher2", "fletcher4", "SHA-256"]
ENDIAN_DESC = ["BE", "LE"]
|
dmu_type_desc = ['unallocated', 'object directory', 'object array', 'packed nvlist', 'packed nvlist size', 'bpobj', 'bpobj header', 'SPA space map header', 'SPA space map', 'ZIL intent log', 'DMU dnode', 'DMU objset', 'DSL directory', 'DSL directory child map', 'DSL dataset snap map', 'DSL props', 'DSL dataset', 'ZFS znode', 'ZFS V0 ACL', 'ZFS plain file', 'ZFS directory', 'ZFS master node', 'ZFS delete queue', 'zvol object', 'zvol prop', 'other uint8[]', 'other uint64[]', 'other ZAP', 'persistent error log', 'SPA history', 'SPA history offsets', 'Pool properties', 'DSL permissions', 'ZFS ACL', 'ZFS SYSACL', 'FUID table', 'FUID table size', 'DSL dataset next clones', 'scan work queue', 'ZFS user/group used', 'ZFS user/group quota', 'snapshot refcount tags', 'DDT ZAP algorithm', 'DDT statistics', 'System attributes', 'SA master node', 'SA attr registration', 'SA attr layouts', 'scan translations', 'deduplicated block', 'DSL deadlist map', 'DSL deadlist map hdr', 'DSL dir clones', 'bpobj subobj']
comp_desc = ['invalid', 'lzjb', 'off', 'lzjb', 'empty', 'gzip1', 'gzip2', 'gzip3', 'gzip4', 'gzip5', 'gzip6', 'gzip7', 'gzip8', 'gzip9', 'zle', 'lz4']
chksum_desc = ['invalid', 'fletcher2', 'none', 'SHA-256', 'SHA-256', 'fletcher2', 'fletcher2', 'fletcher4', 'SHA-256']
endian_desc = ['BE', 'LE']
|
def caesar_encode(phrase, shift):
res=[]
for i,j in enumerate(phrase.split()):
res.append("".join(chr(ord("a")+(ord(k)-ord("a")+shift+i)%26) for k in j))
return " ".join(res)
|
def caesar_encode(phrase, shift):
res = []
for (i, j) in enumerate(phrase.split()):
res.append(''.join((chr(ord('a') + (ord(k) - ord('a') + shift + i) % 26) for k in j)))
return ' '.join(res)
|
expected_output = {
'ints': {
'Ethernet 1/1/1': {
'ip_address': 'unassigned',
'ok': True,
'method': 'unset',
'status': 'up',
'protocol': 'up'
},
'Ethernet 1/1/2': {
'ip_address': 'unassigned',
'ok': True,
'method': 'unset',
'status': 'up',
'protocol': 'up'
},
'Ethernet 1/1/3': {
'ip_address': 'unassigned',
'ok': True,
'method': 'unset',
'status': 'up',
'protocol': 'up'
},
'Ethernet 1/1/4': {
'ip_address': 'unassigned',
'ok': True,
'method': 'unset',
'status': 'up',
'protocol': 'up'
},
'Ethernet 1/1/5': {
'ip_address': 'unassigned',
'ok': False,
'method': 'unset',
'status': 'up',
'protocol': 'down'
},
'Ethernet 1/1/6': {
'ip_address': 'unassigned',
'ok': False,
'method': 'unset',
'status': 'up',
'protocol': 'down'
},
'Ethernet 1/1/7': {
'ip_address': 'unassigned',
'ok': False,
'method': 'unset',
'status': 'up',
'protocol': 'down'
},
'Ethernet 1/1/8': {
'ip_address': 'unassigned',
'ok': False,
'method': 'unset',
'status': 'up',
'protocol': 'down'
},
'Ethernet 1/1/9': {
'ip_address': 'unassigned',
'ok': False,
'method': 'unset',
'status': 'up',
'protocol': 'down'
},
'Ethernet 1/1/10': {
'ip_address': 'unassigned',
'ok': False,
'method': 'unset',
'status': 'up',
'protocol': 'down'
},
'Ethernet 1/1/11': {
'ip_address': 'unassigned',
'ok': False,
'method': 'unset',
'status': 'up',
'protocol': 'down'
},
'Ethernet 1/1/12': {
'ip_address': 'unassigned',
'ok': False,
'method': 'unset',
'status': 'up',
'protocol': 'down'
},
'Ethernet 1/1/13': {
'ip_address': 'unassigned',
'ok': False,
'method': 'unset',
'status': 'up',
'protocol': 'down'
},
'Ethernet 1/1/14': {
'ip_address': 'unassigned',
'ok': False,
'method': 'unset',
'status': 'up',
'protocol': 'down'
},
'Ethernet 1/1/15': {
'ip_address': 'unassigned',
'ok': False,
'method': 'unset',
'status': 'up',
'protocol': 'down'
},
'Ethernet 1/1/16': {
'ip_address': 'unassigned',
'ok': False,
'method': 'unset',
'status': 'up',
'protocol': 'down'
},
'Ethernet 1/1/17': {
'ip_address': 'unassigned',
'ok': False,
'method': 'unset',
'status': 'up',
'protocol': 'down'
},
'Ethernet 1/1/18': {
'ip_address': 'unassigned',
'ok': False,
'method': 'unset',
'status': 'up',
'protocol': 'down'
},
'Ethernet 1/1/19': {
'ip_address': 'unassigned',
'ok': False,
'method': 'unset',
'status': 'up',
'protocol': 'down'
},
'Ethernet 1/1/20': {
'ip_address': 'unassigned',
'ok': False,
'method': 'unset',
'status': 'up',
'protocol': 'down'
},
'Ethernet 1/1/21': {
'ip_address': 'unassigned',
'ok': False,
'method': 'unset',
'status': 'up',
'protocol': 'down'
},
'Ethernet 1/1/22': {
'ip_address': 'unassigned',
'ok': False,
'method': 'unset',
'status': 'up',
'protocol': 'down'
},
'Ethernet 1/1/23': {
'ip_address': 'unassigned',
'ok': False,
'method': 'unset',
'status': 'up',
'protocol': 'down'
},
'Ethernet 1/1/24': {
'ip_address': 'unassigned',
'ok': False,
'method': 'unset',
'status': 'up',
'protocol': 'down'
},
'Ethernet 1/1/25': {
'ip_address': 'unassigned',
'ok': False,
'method': 'unset',
'status': 'up',
'protocol': 'down'
},
'Ethernet 1/1/26': {
'ip_address': 'unassigned',
'ok': False,
'method': 'unset',
'status': 'up',
'protocol': 'down'
},
'Ethernet 1/1/27': {
'ip_address': 'unassigned',
'ok': False,
'method': 'unset',
'status': 'up',
'protocol': 'down'
},
'Ethernet 1/1/28': {
'ip_address': 'unassigned',
'ok': False,
'method': 'unset',
'status': 'up',
'protocol': 'down'
},
'Ethernet 1/1/29': {
'ip_address': 'unassigned',
'ok': False,
'method': 'unset',
'status': 'up',
'protocol': 'down'
},
'Ethernet 1/1/30': {
'ip_address': 'unassigned',
'ok': False,
'method': 'unset',
'status': 'up',
'protocol': 'down'
},
'Ethernet 1/1/31': {
'ip_address': 'unassigned',
'ok': False,
'method': 'unset',
'status': 'up',
'protocol': 'down'
},
'Ethernet 1/1/32': {
'ip_address': 'unassigned',
'ok': False,
'method': 'unset',
'status': 'up',
'protocol': 'down'
},
'Management 1/1/1': {
'ip_address': '10.10.21.16/24',
'ok': True,
'method': 'manual',
'status': 'up',
'protocol': 'up'
},
'Vlan 1': {
'ip_address': 'unassigned',
'ok': True,
'method': 'unset',
'status': 'up',
'protocol': 'up'
}
}
}
|
expected_output = {'ints': {'Ethernet 1/1/1': {'ip_address': 'unassigned', 'ok': True, 'method': 'unset', 'status': 'up', 'protocol': 'up'}, 'Ethernet 1/1/2': {'ip_address': 'unassigned', 'ok': True, 'method': 'unset', 'status': 'up', 'protocol': 'up'}, 'Ethernet 1/1/3': {'ip_address': 'unassigned', 'ok': True, 'method': 'unset', 'status': 'up', 'protocol': 'up'}, 'Ethernet 1/1/4': {'ip_address': 'unassigned', 'ok': True, 'method': 'unset', 'status': 'up', 'protocol': 'up'}, 'Ethernet 1/1/5': {'ip_address': 'unassigned', 'ok': False, 'method': 'unset', 'status': 'up', 'protocol': 'down'}, 'Ethernet 1/1/6': {'ip_address': 'unassigned', 'ok': False, 'method': 'unset', 'status': 'up', 'protocol': 'down'}, 'Ethernet 1/1/7': {'ip_address': 'unassigned', 'ok': False, 'method': 'unset', 'status': 'up', 'protocol': 'down'}, 'Ethernet 1/1/8': {'ip_address': 'unassigned', 'ok': False, 'method': 'unset', 'status': 'up', 'protocol': 'down'}, 'Ethernet 1/1/9': {'ip_address': 'unassigned', 'ok': False, 'method': 'unset', 'status': 'up', 'protocol': 'down'}, 'Ethernet 1/1/10': {'ip_address': 'unassigned', 'ok': False, 'method': 'unset', 'status': 'up', 'protocol': 'down'}, 'Ethernet 1/1/11': {'ip_address': 'unassigned', 'ok': False, 'method': 'unset', 'status': 'up', 'protocol': 'down'}, 'Ethernet 1/1/12': {'ip_address': 'unassigned', 'ok': False, 'method': 'unset', 'status': 'up', 'protocol': 'down'}, 'Ethernet 1/1/13': {'ip_address': 'unassigned', 'ok': False, 'method': 'unset', 'status': 'up', 'protocol': 'down'}, 'Ethernet 1/1/14': {'ip_address': 'unassigned', 'ok': False, 'method': 'unset', 'status': 'up', 'protocol': 'down'}, 'Ethernet 1/1/15': {'ip_address': 'unassigned', 'ok': False, 'method': 'unset', 'status': 'up', 'protocol': 'down'}, 'Ethernet 1/1/16': {'ip_address': 'unassigned', 'ok': False, 'method': 'unset', 'status': 'up', 'protocol': 'down'}, 'Ethernet 1/1/17': {'ip_address': 'unassigned', 'ok': False, 'method': 'unset', 'status': 'up', 'protocol': 'down'}, 'Ethernet 1/1/18': {'ip_address': 'unassigned', 'ok': False, 'method': 'unset', 'status': 'up', 'protocol': 'down'}, 'Ethernet 1/1/19': {'ip_address': 'unassigned', 'ok': False, 'method': 'unset', 'status': 'up', 'protocol': 'down'}, 'Ethernet 1/1/20': {'ip_address': 'unassigned', 'ok': False, 'method': 'unset', 'status': 'up', 'protocol': 'down'}, 'Ethernet 1/1/21': {'ip_address': 'unassigned', 'ok': False, 'method': 'unset', 'status': 'up', 'protocol': 'down'}, 'Ethernet 1/1/22': {'ip_address': 'unassigned', 'ok': False, 'method': 'unset', 'status': 'up', 'protocol': 'down'}, 'Ethernet 1/1/23': {'ip_address': 'unassigned', 'ok': False, 'method': 'unset', 'status': 'up', 'protocol': 'down'}, 'Ethernet 1/1/24': {'ip_address': 'unassigned', 'ok': False, 'method': 'unset', 'status': 'up', 'protocol': 'down'}, 'Ethernet 1/1/25': {'ip_address': 'unassigned', 'ok': False, 'method': 'unset', 'status': 'up', 'protocol': 'down'}, 'Ethernet 1/1/26': {'ip_address': 'unassigned', 'ok': False, 'method': 'unset', 'status': 'up', 'protocol': 'down'}, 'Ethernet 1/1/27': {'ip_address': 'unassigned', 'ok': False, 'method': 'unset', 'status': 'up', 'protocol': 'down'}, 'Ethernet 1/1/28': {'ip_address': 'unassigned', 'ok': False, 'method': 'unset', 'status': 'up', 'protocol': 'down'}, 'Ethernet 1/1/29': {'ip_address': 'unassigned', 'ok': False, 'method': 'unset', 'status': 'up', 'protocol': 'down'}, 'Ethernet 1/1/30': {'ip_address': 'unassigned', 'ok': False, 'method': 'unset', 'status': 'up', 'protocol': 'down'}, 'Ethernet 1/1/31': {'ip_address': 'unassigned', 'ok': False, 'method': 'unset', 'status': 'up', 'protocol': 'down'}, 'Ethernet 1/1/32': {'ip_address': 'unassigned', 'ok': False, 'method': 'unset', 'status': 'up', 'protocol': 'down'}, 'Management 1/1/1': {'ip_address': '10.10.21.16/24', 'ok': True, 'method': 'manual', 'status': 'up', 'protocol': 'up'}, 'Vlan 1': {'ip_address': 'unassigned', 'ok': True, 'method': 'unset', 'status': 'up', 'protocol': 'up'}}}
|
class UnshortenerOld():
"""
Todo option selenium ?
"""
def __init__(self,
logger=None,
verbose=True,
maxItemCount=100000000,
maxDataSizeMo=10000,
dataDir=None,
seleniumBrowserCount=20,
resetBrowsersRate=0.1,
useSelenium=False,
seleniumBrowsersIsNice=True,
storeAll=False,
readOnly=False,
shortenersDomainsFilePath=None):
self.readOnly = readOnly
self.seleniumBrowsersIsNice = seleniumBrowsersIsNice
self.resetBrowsersRate = resetBrowsersRate
self.seleniumBrowserCount = seleniumBrowserCount
self.shortenersDomainsFilePath = shortenersDomainsFilePath
if self.shortenersDomainsFilePath is None:
self.shortenersDomainsFilePath = getDataDir() + "/Misc/crawling/shorteners.txt"
self.useSelenium = useSelenium
self.storeAll = storeAll
self.maxDataSizeMo = maxDataSizeMo
self.maxItemCount = maxItemCount
self.dataDir = dataDir
if self.dataDir is None:
self.dataDir = getDataDir() + "/Misc/crawling/"
self.fileName = "unshortener-database"
self.urlParser = URLParser()
self.requestCounter = 0
self.verbose = verbose
self.logger = logger
self.data = SerializableDict \
(
self.dataDir, self.fileName,
cleanMaxSizeMoReadModifiedOlder=self.maxDataSizeMo,
limit=self.maxItemCount,
serializeEachNAction=20,
verbose=True
)
self.shortenersDomains = None
self.initShortenersDomains()
self.browsers = None
def initShortenersDomains(self):
if self.shortenersDomains is None:
shorteners = fileToStrList(self.shortenersDomainsFilePath, removeDuplicates=True)
newShorteners = []
for current in shorteners:
current = current.lower()
newShorteners.append(current)
shorteners = newShorteners
self.shortenersDomains = set()
for current in shorteners:
newCurrent = self.urlParser.getDomain(current)
self.shortenersDomains.add(newCurrent)
self.shortenersDomains = list(self.shortenersDomains)
# We filter all by presence of a point:
newShortenersDomains= []
for current in self.shortenersDomains:
if "." in current:
newShortenersDomains.append(current)
self.shortenersDomains = newShortenersDomains
def getUnshortenersDomains(self):
return self.shortenersDomains
def close(self):
self.data.close()
def isShortener(self, url):
smartDomain = self.urlParser.getDomain(url)
return smartDomain in self.shortenersDomains
def isStatusCodeOk(self, statusCode):
if isinstance(statusCode, dict) and dictContains(dict, "statusCode"):
statusCode = statusCode["statusCode"]
return statusCode == 200
def generateSeleniumBrowsers(self):
# We have to reset browsers sometimes because it can take a lot of RAM:
if self.browsers is None or getRandomFloat() < self.resetBrowsersRate:
if self.browsers is not None:
for browser in self.browsers:
browser.quit()
self.browsers = []
def generateRandomBrowser(proxy):
self.browsers.append(Browser(driverType=DRIVER_TYPE.phantomjs, proxy=proxy))
allThreads = []
for i in range(self.seleniumBrowserCount):
theThread = Thread(target=generateRandomBrowser, args=(getRandomProxy(),))
theThread.start()
allThreads.append(theThread)
for theThread in allThreads:
theThread.join()
def getRandomSeleniumBrowser(self):
return random.choice(self.browsers)
def unshort(self, url, force=False, useProxy=True, timeout=20, retryIf407=True):
"""
force as False will check if the given url have to match with a known shorter service
force as True will give the last url for the request...
"""
url = self.urlParser.normalize(url)
smartDomain = self.urlParser.getDomain(url)
if not force and smartDomain not in self.shortenersDomains:
result = \
{
"force": force,
"url": url,
"message": "The domain is not a shortener service!",
"status": -1,
}
return result
if self.data.hasKey(url):
log(url + " was in the Unshortener database!", self)
return self.data.get(url)
elif self.readOnly:
result = \
{
"force": force,
"url": url,
"message": "The url is not in the database and the unshortener was set as read only.",
"status": -2,
}
return result
else:
log("Trying to unshort " + url, self)
proxy = None
if useProxy:
proxy = getRandomProxy()
seleniumFailed = False
if self.useSelenium:
self.generateSeleniumBrowsers()
browser = self.getRandomSeleniumBrowser()
result = browser.html(url)
if result["status"] == REQUEST_STATUS.refused or \
result["status"] == REQUEST_STATUS.timeout:
seleniumFailed = True
logError("Selenium failed to get " + url + "\nTrying with a HTTPBrowser...", self)
else:
result = convertBrowserResponse(result, browser, nice=self.seleniumBrowsersIsNice)
if not self.useSelenium or seleniumFailed:
httpBrowser = HTTPBrowser(proxy=proxy, logger=self.logger, verbose=self.verbose)
result = httpBrowser.get(url)
result["force"] = force
if self.storeAll or result["status"] == 200 or result["status"] == 404:
self.data.add(url, result)
del result["html"]
log("Unshort of " + result["url"] + " : " + str(result["status"]), self)
return result
|
class Unshortenerold:
"""
Todo option selenium ?
"""
def __init__(self, logger=None, verbose=True, maxItemCount=100000000, maxDataSizeMo=10000, dataDir=None, seleniumBrowserCount=20, resetBrowsersRate=0.1, useSelenium=False, seleniumBrowsersIsNice=True, storeAll=False, readOnly=False, shortenersDomainsFilePath=None):
self.readOnly = readOnly
self.seleniumBrowsersIsNice = seleniumBrowsersIsNice
self.resetBrowsersRate = resetBrowsersRate
self.seleniumBrowserCount = seleniumBrowserCount
self.shortenersDomainsFilePath = shortenersDomainsFilePath
if self.shortenersDomainsFilePath is None:
self.shortenersDomainsFilePath = get_data_dir() + '/Misc/crawling/shorteners.txt'
self.useSelenium = useSelenium
self.storeAll = storeAll
self.maxDataSizeMo = maxDataSizeMo
self.maxItemCount = maxItemCount
self.dataDir = dataDir
if self.dataDir is None:
self.dataDir = get_data_dir() + '/Misc/crawling/'
self.fileName = 'unshortener-database'
self.urlParser = url_parser()
self.requestCounter = 0
self.verbose = verbose
self.logger = logger
self.data = serializable_dict(self.dataDir, self.fileName, cleanMaxSizeMoReadModifiedOlder=self.maxDataSizeMo, limit=self.maxItemCount, serializeEachNAction=20, verbose=True)
self.shortenersDomains = None
self.initShortenersDomains()
self.browsers = None
def init_shorteners_domains(self):
if self.shortenersDomains is None:
shorteners = file_to_str_list(self.shortenersDomainsFilePath, removeDuplicates=True)
new_shorteners = []
for current in shorteners:
current = current.lower()
newShorteners.append(current)
shorteners = newShorteners
self.shortenersDomains = set()
for current in shorteners:
new_current = self.urlParser.getDomain(current)
self.shortenersDomains.add(newCurrent)
self.shortenersDomains = list(self.shortenersDomains)
new_shorteners_domains = []
for current in self.shortenersDomains:
if '.' in current:
newShortenersDomains.append(current)
self.shortenersDomains = newShortenersDomains
def get_unshorteners_domains(self):
return self.shortenersDomains
def close(self):
self.data.close()
def is_shortener(self, url):
smart_domain = self.urlParser.getDomain(url)
return smartDomain in self.shortenersDomains
def is_status_code_ok(self, statusCode):
if isinstance(statusCode, dict) and dict_contains(dict, 'statusCode'):
status_code = statusCode['statusCode']
return statusCode == 200
def generate_selenium_browsers(self):
if self.browsers is None or get_random_float() < self.resetBrowsersRate:
if self.browsers is not None:
for browser in self.browsers:
browser.quit()
self.browsers = []
def generate_random_browser(proxy):
self.browsers.append(browser(driverType=DRIVER_TYPE.phantomjs, proxy=proxy))
all_threads = []
for i in range(self.seleniumBrowserCount):
the_thread = thread(target=generateRandomBrowser, args=(get_random_proxy(),))
theThread.start()
allThreads.append(theThread)
for the_thread in allThreads:
theThread.join()
def get_random_selenium_browser(self):
return random.choice(self.browsers)
def unshort(self, url, force=False, useProxy=True, timeout=20, retryIf407=True):
"""
force as False will check if the given url have to match with a known shorter service
force as True will give the last url for the request...
"""
url = self.urlParser.normalize(url)
smart_domain = self.urlParser.getDomain(url)
if not force and smartDomain not in self.shortenersDomains:
result = {'force': force, 'url': url, 'message': 'The domain is not a shortener service!', 'status': -1}
return result
if self.data.hasKey(url):
log(url + ' was in the Unshortener database!', self)
return self.data.get(url)
elif self.readOnly:
result = {'force': force, 'url': url, 'message': 'The url is not in the database and the unshortener was set as read only.', 'status': -2}
return result
else:
log('Trying to unshort ' + url, self)
proxy = None
if useProxy:
proxy = get_random_proxy()
selenium_failed = False
if self.useSelenium:
self.generateSeleniumBrowsers()
browser = self.getRandomSeleniumBrowser()
result = browser.html(url)
if result['status'] == REQUEST_STATUS.refused or result['status'] == REQUEST_STATUS.timeout:
selenium_failed = True
log_error('Selenium failed to get ' + url + '\nTrying with a HTTPBrowser...', self)
else:
result = convert_browser_response(result, browser, nice=self.seleniumBrowsersIsNice)
if not self.useSelenium or seleniumFailed:
http_browser = http_browser(proxy=proxy, logger=self.logger, verbose=self.verbose)
result = httpBrowser.get(url)
result['force'] = force
if self.storeAll or result['status'] == 200 or result['status'] == 404:
self.data.add(url, result)
del result['html']
log('Unshort of ' + result['url'] + ' : ' + str(result['status']), self)
return result
|
class Solution:
def removeElement(self, nums, val):
count = 0
for i in range(len(nums)):
if nums[i] != val:
nums[count] = nums[i]
count += 1
print(count)
return(count)
obj = Solution()
obj.removeElement([3,2,2,3], 3)
obj.removeElement([0,1,2,2,3,0,4,2], 2)
|
class Solution:
def remove_element(self, nums, val):
count = 0
for i in range(len(nums)):
if nums[i] != val:
nums[count] = nums[i]
count += 1
print(count)
return count
obj = solution()
obj.removeElement([3, 2, 2, 3], 3)
obj.removeElement([0, 1, 2, 2, 3, 0, 4, 2], 2)
|
#!/usr/bin/env python3
class Solution:
def buddStrings(self, A, B):
la, lb = len(A), len(B)
if la != lb:
return False
diff = [i for i in range(la) if A[i] != B[i]]
if len(diff) > 2 or len(diff) == 1:
return False
elif len(diff) == 0 and len(set(A)) == la:
return False
else:
i, j = diff
if A[i] != B[j] or A[j] != B[i]:
return False
return True
|
class Solution:
def budd_strings(self, A, B):
(la, lb) = (len(A), len(B))
if la != lb:
return False
diff = [i for i in range(la) if A[i] != B[i]]
if len(diff) > 2 or len(diff) == 1:
return False
elif len(diff) == 0 and len(set(A)) == la:
return False
else:
(i, j) = diff
if A[i] != B[j] or A[j] != B[i]:
return False
return True
|
print('this is the first line of second.py')
for x in range(20):
print(x)
print('this is the chunk of code added to the fourth branch')
print('Im editing this file in GitHub to see if fetch finds it')
print('adding this code to push to the main on the remote repository')
|
print('this is the first line of second.py')
for x in range(20):
print(x)
print('this is the chunk of code added to the fourth branch')
print('Im editing this file in GitHub to see if fetch finds it')
print('adding this code to push to the main on the remote repository')
|
def count_substring(string, sub_string):
k = len(sub_string)
ans = 0
for i in range(len(string)):
if i+k > len(string):
break
if sub_string == string[i:i+k]:
ans += 1
return ans
if __name__ == '__main__':
string = input().strip()
sub_string = input().strip()
count = count_substring(string, sub_string)
print(count)
|
def count_substring(string, sub_string):
k = len(sub_string)
ans = 0
for i in range(len(string)):
if i + k > len(string):
break
if sub_string == string[i:i + k]:
ans += 1
return ans
if __name__ == '__main__':
string = input().strip()
sub_string = input().strip()
count = count_substring(string, sub_string)
print(count)
|
print("Hello World")
my_name = input("Whats your name? ")
print("Hello " + my_name)
print('Did you know that your name is ' + str(len(my_name)) + ' letters long!')
|
print('Hello World')
my_name = input('Whats your name? ')
print('Hello ' + my_name)
print('Did you know that your name is ' + str(len(my_name)) + ' letters long!')
|
"""
37. How to get the nrows, ncolumns, datatype, summary stats of each column of a dataframe? Also get the array and list equivalent.
"""
"""
Difficulty Level: L2
"""
"""
Get the number of rows, columns, datatype and summary statistics of each column of the Cars93 dataset. Also get the numpy array and list equivalent of the dataframe.
"""
"""
"""
|
"""
37. How to get the nrows, ncolumns, datatype, summary stats of each column of a dataframe? Also get the array and list equivalent.
"""
'\nDifficulty Level: L2\n'
'\nGet the number of rows, columns, datatype and summary statistics of each column of the Cars93 dataset. Also get the numpy array and list equivalent of the dataframe.\n'
'\n \n'
|
#py_screener.py
def screener(user_inp=None):
"""A function to square only floating points.
Returns custom exceptions if an int or complex is encountered."""
#make sure something was input
if not user_inp:
print("Ummm...did you type in ANYTHING?")
return
#If it *might* be a float (has a ".") try to type-cast it and return
if "." in user_inp:
try:
inp_as_float=float(user_inp)
if isinstance(inp_as_float, float):
square = inp_as_float**2
print( "You gave me {}. Its square is: {}".format(user_inp, square))
except:
return
try: #see if we need to return the ComplexException
if "(" in user_inp: #it might be complex if it has a (
inp_as_complex=complex(user_inp)
if isinstance(inp_as_complex, complex):
raise ComplexException(inp_as_complex)
except: #it's not complex
pass
try:
#we already tried to type-cast to float, let's try casting to int
inp_as_integer=int(user_inp)
if isinstance(inp_as_integer, int):
raise IntException(inp_as_integer)
except:
pass
#if we're here, the function hasn't returned anything or raised an exception
print("Done processing {} ".format(user_inp))
|
def screener(user_inp=None):
"""A function to square only floating points.
Returns custom exceptions if an int or complex is encountered."""
if not user_inp:
print('Ummm...did you type in ANYTHING?')
return
if '.' in user_inp:
try:
inp_as_float = float(user_inp)
if isinstance(inp_as_float, float):
square = inp_as_float ** 2
print('You gave me {}. Its square is: {}'.format(user_inp, square))
except:
return
try:
if '(' in user_inp:
inp_as_complex = complex(user_inp)
if isinstance(inp_as_complex, complex):
raise complex_exception(inp_as_complex)
except:
pass
try:
inp_as_integer = int(user_inp)
if isinstance(inp_as_integer, int):
raise int_exception(inp_as_integer)
except:
pass
print('Done processing {} '.format(user_inp))
|
default_mapping = {
'Recipient Name': 'recipient_name',
'Recipient DUNS Number': 'recipient_unique_id',
'Awarding Agency': 'awarding_toptier_agency_name',
'Awarding Agency Code': 'awarding_toptier_agency_code',
'Awarding Sub Agency': 'awarding_subtier_agency_name',
'Awarding Sub Agency Code': 'awarding_subtier_agency_code',
'Funding Agency': 'funding_toptier_agency_name', # Leave in for possible future use
'Funding Agency Code': 'funding_toptier_agency_code', # Leave in for possible future use
'Funding Sub Agency': 'funding_subtier_agency_name', # Leave in for possible future use
'Funding Sub Agency Code': 'funding_subtier_agency_code', # Leave in for possible future use
'Place of Performance City Code': 'pop_city_code',
'Place of Performance State Code': 'pop_state_code',
'Place of Performance Country Code': 'pop_country_code',
'Place of Performance Zip5': 'pop_zip5',
'Period of Performance Start Date': 'period_of_performance_start_date',
'Period of Performance Current End Date': 'period_of_performance_current_end_date',
'Description': 'description',
'Last Modified Date': 'last_modified_date',
'Base Obligation Date': 'date_signed',
}
award_contracts_mapping = default_mapping.copy()
grant_award_mapping = default_mapping.copy()
loan_award_mapping = default_mapping.copy()
direct_payment_award_mapping = default_mapping.copy()
other_award_mapping = default_mapping.copy()
award_contracts_mapping.update({
'Award ID': 'piid',
'Start Date': 'period_of_performance_start_date',
'End Date': 'period_of_performance_current_end_date',
'Award Amount': 'total_obligation',
'Contract Award Type': 'type_description',
})
grant_award_mapping.update({
'Award ID': 'fain',
'Start Date': 'period_of_performance_start_date',
'End Date': 'period_of_performance_current_end_date',
'Award Amount': 'total_obligation',
'Award Type': 'type_description',
'SAI Number': 'sai_number',
'CFDA Number': 'cfda_number'
})
loan_award_mapping.update({
'Award ID': 'fain',
'Issued Date': 'action_date',
'Loan Value': 'total_loan_value',
'Subsidy Cost': 'total_subsidy_cost',
'SAI Number': 'sai_number',
'CFDA Number': 'cfda_number'
})
direct_payment_award_mapping.update({
'Award ID': 'fain',
'Start Date': 'period_of_performance_start_date',
'End Date': 'period_of_performance_current_end_date',
'Award Amount': 'total_obligation',
'Award Type': 'type_description',
'SAI Number': 'sai_number',
'CFDA Number': 'cfda_number'
})
other_award_mapping.update({
'Award ID': 'fain',
'Start Date': 'period_of_performance_start_date',
'End Date': 'period_of_performance_current_end_date',
'Award Amount': 'total_obligation',
'Award Type': 'type_description',
'SAI Number': 'sai_number',
'CFDA Number': 'cfda_number'
})
award_assistance_mapping = {**grant_award_mapping, **loan_award_mapping, **direct_payment_award_mapping,
**other_award_mapping}
non_loan_assistance_award_mapping = assistance_award_mapping = {**grant_award_mapping, **direct_payment_award_mapping,
**other_award_mapping}
|
default_mapping = {'Recipient Name': 'recipient_name', 'Recipient DUNS Number': 'recipient_unique_id', 'Awarding Agency': 'awarding_toptier_agency_name', 'Awarding Agency Code': 'awarding_toptier_agency_code', 'Awarding Sub Agency': 'awarding_subtier_agency_name', 'Awarding Sub Agency Code': 'awarding_subtier_agency_code', 'Funding Agency': 'funding_toptier_agency_name', 'Funding Agency Code': 'funding_toptier_agency_code', 'Funding Sub Agency': 'funding_subtier_agency_name', 'Funding Sub Agency Code': 'funding_subtier_agency_code', 'Place of Performance City Code': 'pop_city_code', 'Place of Performance State Code': 'pop_state_code', 'Place of Performance Country Code': 'pop_country_code', 'Place of Performance Zip5': 'pop_zip5', 'Period of Performance Start Date': 'period_of_performance_start_date', 'Period of Performance Current End Date': 'period_of_performance_current_end_date', 'Description': 'description', 'Last Modified Date': 'last_modified_date', 'Base Obligation Date': 'date_signed'}
award_contracts_mapping = default_mapping.copy()
grant_award_mapping = default_mapping.copy()
loan_award_mapping = default_mapping.copy()
direct_payment_award_mapping = default_mapping.copy()
other_award_mapping = default_mapping.copy()
award_contracts_mapping.update({'Award ID': 'piid', 'Start Date': 'period_of_performance_start_date', 'End Date': 'period_of_performance_current_end_date', 'Award Amount': 'total_obligation', 'Contract Award Type': 'type_description'})
grant_award_mapping.update({'Award ID': 'fain', 'Start Date': 'period_of_performance_start_date', 'End Date': 'period_of_performance_current_end_date', 'Award Amount': 'total_obligation', 'Award Type': 'type_description', 'SAI Number': 'sai_number', 'CFDA Number': 'cfda_number'})
loan_award_mapping.update({'Award ID': 'fain', 'Issued Date': 'action_date', 'Loan Value': 'total_loan_value', 'Subsidy Cost': 'total_subsidy_cost', 'SAI Number': 'sai_number', 'CFDA Number': 'cfda_number'})
direct_payment_award_mapping.update({'Award ID': 'fain', 'Start Date': 'period_of_performance_start_date', 'End Date': 'period_of_performance_current_end_date', 'Award Amount': 'total_obligation', 'Award Type': 'type_description', 'SAI Number': 'sai_number', 'CFDA Number': 'cfda_number'})
other_award_mapping.update({'Award ID': 'fain', 'Start Date': 'period_of_performance_start_date', 'End Date': 'period_of_performance_current_end_date', 'Award Amount': 'total_obligation', 'Award Type': 'type_description', 'SAI Number': 'sai_number', 'CFDA Number': 'cfda_number'})
award_assistance_mapping = {**grant_award_mapping, **loan_award_mapping, **direct_payment_award_mapping, **other_award_mapping}
non_loan_assistance_award_mapping = assistance_award_mapping = {**grant_award_mapping, **direct_payment_award_mapping, **other_award_mapping}
|
class Reporting(object):
def __init__(self, verbose=False, debug=False):
self.verbose_flag = verbose
self.debug_flag = debug
def error(self, msg):
pass
def debug(self, msg):
pass
def verbose(self, msg):
pass
|
class Reporting(object):
def __init__(self, verbose=False, debug=False):
self.verbose_flag = verbose
self.debug_flag = debug
def error(self, msg):
pass
def debug(self, msg):
pass
def verbose(self, msg):
pass
|
def iloc(records, rows=':', cols=':') -> list:
"""A Pandas .iloc-like function.
Args:
records (list): A 2-D list.
rows (str or int): The indices of rows. Default is ':'.
cols (str or int): The indices of columns. Default is ':'.
Returns:
list: The sliced records.
Examples:
>>> l = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> iloc(l)
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> iloc(l, rows=0)
[[1, 2, 3]]
>>> iloc(l, rows=0, cols=0)
[1]
>>> iloc(l, rows='0:1')
[[1, 2, 3]]
>>> iloc(l, rows='1:')
[[4, 5, 6], [7, 8, 9]]
>>> iloc(l, rows=':2')
[[1, 2, 3], [4, 5, 6]]
>>> iloc(l, rows=':', cols='1:')
[[2, 3], [5, 6], [8, 9]]
>>> iloc(l, rows=':', cols=0)
[1, 4, 7]
>>> iloc(l, rows=':', cols='0:1')
[1, 4, 7]
>>> iloc(l, rows=':', cols='0:2')
[[1, 2], [4, 5], [7, 8]]
"""
assert isinstance(records[0], list), 'records must be a 2-D list!'
def _parseColon(ind: str) -> int:
"""Parse colon in rows or cols.
Args:
ind (str): rows or cols
Returns:
int: Then start or/and end of the rows or cols.
Examples:
# ':'.split(':') ---- ['', '']
>>> _parseColon(':')
(0, None)
# '0'.split(':') ---- ['0]
>>> _parseColon(0)
(0, 1)
# '1:'.split(':') ---- ['1', '']
>>> _parseColon('1:')
(1, None)
# ':2'.split(':') ---- ['', '2']
>>> _parseColon(':2')
(0, 2)
# '1:2'.split(':') ---- ['1', '2']
>>> _parseColon('1:2')
(1, 2)
"""
ind = str(ind)
ind = ind.split(':', maxsplit=1)
start = ind[0]
start = int(start) if start != '' else 0
# if no ind[0], end = start+1
end = ind[1] if len(ind) == 2 else start+1
end = int(end) if end != '' else None
return start, end
# Get row_start, row_end
row_start, row_end = _parseColon(rows)
# Get col_start, col_end
col_start, col_end = _parseColon(cols)
# Slice rows
records = records[row_start:row_end]
# Slice columns
if col_end is None:
records = [record[col_start:col_end] for record in records]
elif col_end - col_start != 1:
records = [record[col_start:col_end] for record in records]
else:
records = [record[col_start] for record in records]
return records
|
def iloc(records, rows=':', cols=':') -> list:
"""A Pandas .iloc-like function.
Args:
records (list): A 2-D list.
rows (str or int): The indices of rows. Default is ':'.
cols (str or int): The indices of columns. Default is ':'.
Returns:
list: The sliced records.
Examples:
>>> l = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> iloc(l)
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> iloc(l, rows=0)
[[1, 2, 3]]
>>> iloc(l, rows=0, cols=0)
[1]
>>> iloc(l, rows='0:1')
[[1, 2, 3]]
>>> iloc(l, rows='1:')
[[4, 5, 6], [7, 8, 9]]
>>> iloc(l, rows=':2')
[[1, 2, 3], [4, 5, 6]]
>>> iloc(l, rows=':', cols='1:')
[[2, 3], [5, 6], [8, 9]]
>>> iloc(l, rows=':', cols=0)
[1, 4, 7]
>>> iloc(l, rows=':', cols='0:1')
[1, 4, 7]
>>> iloc(l, rows=':', cols='0:2')
[[1, 2], [4, 5], [7, 8]]
"""
assert isinstance(records[0], list), 'records must be a 2-D list!'
def _parse_colon(ind: str) -> int:
"""Parse colon in rows or cols.
Args:
ind (str): rows or cols
Returns:
int: Then start or/and end of the rows or cols.
Examples:
# ':'.split(':') ---- ['', '']
>>> _parseColon(':')
(0, None)
# '0'.split(':') ---- ['0]
>>> _parseColon(0)
(0, 1)
# '1:'.split(':') ---- ['1', '']
>>> _parseColon('1:')
(1, None)
# ':2'.split(':') ---- ['', '2']
>>> _parseColon(':2')
(0, 2)
# '1:2'.split(':') ---- ['1', '2']
>>> _parseColon('1:2')
(1, 2)
"""
ind = str(ind)
ind = ind.split(':', maxsplit=1)
start = ind[0]
start = int(start) if start != '' else 0
end = ind[1] if len(ind) == 2 else start + 1
end = int(end) if end != '' else None
return (start, end)
(row_start, row_end) = _parse_colon(rows)
(col_start, col_end) = _parse_colon(cols)
records = records[row_start:row_end]
if col_end is None:
records = [record[col_start:col_end] for record in records]
elif col_end - col_start != 1:
records = [record[col_start:col_end] for record in records]
else:
records = [record[col_start] for record in records]
return records
|
class Solution:
def isValid(self, s: str) -> bool:
if not s: return True
if len(s) % 2: return False
if s[0] in ']})': return False
maps = {'(':')', '{':'}', '[':']'}
stack = []
for char in s:
if char in '({[':
stack.append(char)
else:
if not stack: return False
else:
temp = stack.pop()
if maps[temp] != char:
return False
return len(stack) == 0
|
class Solution:
def is_valid(self, s: str) -> bool:
if not s:
return True
if len(s) % 2:
return False
if s[0] in ']})':
return False
maps = {'(': ')', '{': '}', '[': ']'}
stack = []
for char in s:
if char in '({[':
stack.append(char)
elif not stack:
return False
else:
temp = stack.pop()
if maps[temp] != char:
return False
return len(stack) == 0
|
#!/usr/bin/python3
# https://practice.geeksforgeeks.org/problems/next-sparse-binary-number/0
def sol(num):
"""
By definition of sparse number two 1s cannot be adjacent but zeroes can be
If two 1s are adjacent and we want to make a bigger number we cannot
make the either of the bits 0, so only option left is we make the third
bit 1 if it is 0 or we add an extra bit
"""
b = list(bin(num)[2:])
b.insert(0, "0")
# We might have to add an extra bit lets add it.
# Adding a zero does not change the number
#print(b)
n = len(b)
i=n-2
while i >= 1:
# Search for the sequence where two adjacents bits are set and the
# third bit to the left is not set and unset all the bits to its right
# including both the set bits
if b[i] == b[i+1] == "1" and b[i-1] == "0":
for j in range(i, n):
b[j] = '0'
b[i-1] = "1"
# Set the third bit
i-=1
num = 0
n = len(b)
#print(b)
for i in range(n):
p = n-1-i
num += int(b[i])*(2**p)
return num
print(sol(3))
print(sol(5))
print(sol(19169))
print(sol(18467))
print(sol(6334))
|
def sol(num):
"""
By definition of sparse number two 1s cannot be adjacent but zeroes can be
If two 1s are adjacent and we want to make a bigger number we cannot
make the either of the bits 0, so only option left is we make the third
bit 1 if it is 0 or we add an extra bit
"""
b = list(bin(num)[2:])
b.insert(0, '0')
n = len(b)
i = n - 2
while i >= 1:
if b[i] == b[i + 1] == '1' and b[i - 1] == '0':
for j in range(i, n):
b[j] = '0'
b[i - 1] = '1'
i -= 1
num = 0
n = len(b)
for i in range(n):
p = n - 1 - i
num += int(b[i]) * 2 ** p
return num
print(sol(3))
print(sol(5))
print(sol(19169))
print(sol(18467))
print(sol(6334))
|
command = input()
kids = 0
adults = 0
while command != "Christmas":
peoples_age = int(command)
if peoples_age <= 16:
kids += 1
elif peoples_age > 16:
adults += 1
command = input()
if command == "Christmas":
total_toys_price = kids * 5
total_sweater_price = adults * 15
print(f"Number of adults: {adults}")
print(f"Number of kids: {kids}")
print(f"Money for toys: {total_toys_price}")
print(f"Money for sweaters: {total_sweater_price}")
|
command = input()
kids = 0
adults = 0
while command != 'Christmas':
peoples_age = int(command)
if peoples_age <= 16:
kids += 1
elif peoples_age > 16:
adults += 1
command = input()
if command == 'Christmas':
total_toys_price = kids * 5
total_sweater_price = adults * 15
print(f'Number of adults: {adults}')
print(f'Number of kids: {kids}')
print(f'Money for toys: {total_toys_price}')
print(f'Money for sweaters: {total_sweater_price}')
|
class Solution(object):
def findBestValue(self, arr, target):
arr.sort(reverse = True)
while arr and target >= arr[-1]*len(arr):
temp = arr[-1]
target -= arr.pop()
if not arr:
return temp
res = target / float(len(arr))
if res % 1 > 0.5:
return int(res) + 1
else:
return int(res)
arr = [2,2,2]
target = 10
res = Solution().findBestValue(arr, target)
print(res)
|
class Solution(object):
def find_best_value(self, arr, target):
arr.sort(reverse=True)
while arr and target >= arr[-1] * len(arr):
temp = arr[-1]
target -= arr.pop()
if not arr:
return temp
res = target / float(len(arr))
if res % 1 > 0.5:
return int(res) + 1
else:
return int(res)
arr = [2, 2, 2]
target = 10
res = solution().findBestValue(arr, target)
print(res)
|
# Converts RGB to GRB which is needed by the lightstrip
def Color(red, green, blue, white = 0):
"""Convert the provided red, green, blue color to a 24-bit color value.
Each color component should be a value 0-255 where 0 is the lowest intensity
and 255 is the highest intensity.
"""
return (white << 24) | (green << 16)| (red << 8) | blue
def getRGB(color):
r = 0b11111111 & (color >> 8)
g = 0b11111111 & (color >> 16)
b = 0b11111111 & color
return r, g, b
def calcGradient(color1, color2, progress = 0.5):
r1, g1, b1 = getRGB(color1)
r2, g2, b2 = getRGB(color2)
dr = (r2 - r1)
dg = (g2 - g1)
db = (b2 - b1)
return Color(r1 + int(round(dr * progress)), g1 + int(round(dg * progress)), b1 + int(round(db * progress)))
def red(n):
return Color(255, 0, 0)
def green(n):
return Color(0, 255, 0)
def blue(n):
return Color(0, 0, 255)
def clear(n):
return Color(0, 0, 0)
def color(r, g, b):
def colorFunc(n):
return Color(r, g, b)
return colorFunc
def gradient(r1, g1, b1, r2, g2, b2):
dr = (r2 - r1) / 128.0
dg = (g2 - g1) / 128.0
db = (b2 - b1) / 128.0
def gradientFunc(n):
n += 128
n = n & 255
n = abs(128 - n)
return Color(r1 + int(round(dr * n)), g1 + int(round(dg * n)), b1 + int(round(db * n)))
return gradientFunc
def gradient_cycle(r1, g1, b1, r2, g2, b2, length):
default_gradient = gradient(r1, g1, b1, r2, g2, b2)
def gradCycleFunc(n):
return default_gradient(n * 256 // length)
return gradCycleFunc
def rainbow(n):
n = n & 255
n = 255 - n
if n < 85:
return Color(255 - n * 3, 0, n * 3)
elif n < 170:
n -= 85
return Color(0, n * 3, 255 - n * 3)
else:
n -= 170
return Color(n * 3, 255 - n * 3, 0)
def rainbow_cycle(length):
def rainbowCycleFunc(n):
return rainbow(n * 256 // length)
return rainbowCycleFunc
def online_background(connection):
def onlineSetColor(n):
color = connection.getBackgroundColor()
return Color(color['red'], color['green'], color['blue'])
return onlineSetColor
def online_foreground(connection):
def onlineSetColor(n):
color = connection.getForegroundColor()
return Color(color['red'], color['green'], color['blue'])
return onlineSetColor
|
def color(red, green, blue, white=0):
"""Convert the provided red, green, blue color to a 24-bit color value.
Each color component should be a value 0-255 where 0 is the lowest intensity
and 255 is the highest intensity.
"""
return white << 24 | green << 16 | red << 8 | blue
def get_rgb(color):
r = 255 & color >> 8
g = 255 & color >> 16
b = 255 & color
return (r, g, b)
def calc_gradient(color1, color2, progress=0.5):
(r1, g1, b1) = get_rgb(color1)
(r2, g2, b2) = get_rgb(color2)
dr = r2 - r1
dg = g2 - g1
db = b2 - b1
return color(r1 + int(round(dr * progress)), g1 + int(round(dg * progress)), b1 + int(round(db * progress)))
def red(n):
return color(255, 0, 0)
def green(n):
return color(0, 255, 0)
def blue(n):
return color(0, 0, 255)
def clear(n):
return color(0, 0, 0)
def color(r, g, b):
def color_func(n):
return color(r, g, b)
return colorFunc
def gradient(r1, g1, b1, r2, g2, b2):
dr = (r2 - r1) / 128.0
dg = (g2 - g1) / 128.0
db = (b2 - b1) / 128.0
def gradient_func(n):
n += 128
n = n & 255
n = abs(128 - n)
return color(r1 + int(round(dr * n)), g1 + int(round(dg * n)), b1 + int(round(db * n)))
return gradientFunc
def gradient_cycle(r1, g1, b1, r2, g2, b2, length):
default_gradient = gradient(r1, g1, b1, r2, g2, b2)
def grad_cycle_func(n):
return default_gradient(n * 256 // length)
return gradCycleFunc
def rainbow(n):
n = n & 255
n = 255 - n
if n < 85:
return color(255 - n * 3, 0, n * 3)
elif n < 170:
n -= 85
return color(0, n * 3, 255 - n * 3)
else:
n -= 170
return color(n * 3, 255 - n * 3, 0)
def rainbow_cycle(length):
def rainbow_cycle_func(n):
return rainbow(n * 256 // length)
return rainbowCycleFunc
def online_background(connection):
def online_set_color(n):
color = connection.getBackgroundColor()
return color(color['red'], color['green'], color['blue'])
return onlineSetColor
def online_foreground(connection):
def online_set_color(n):
color = connection.getForegroundColor()
return color(color['red'], color['green'], color['blue'])
return onlineSetColor
|
class MockRequests:
def __init__(self, ok=True, json_data=None):
self.ok = ok
self.json_data = json_data
self.get_method_called = False
def __call__(self, *args, **kwargs):
self.get_method_called = True
self.response = MockResponse(json_data=self.json_data)
return self.response
class MockResponse:
def __init__(self, ok=True, json_data=None):
self.ok = ok
self.json_method_called = False
self.json_data = json_data
def json(self):
self.json_method_called = True
return self.json_data
class MockRedis:
def __init__(self, get_data=None):
self.get_data = get_data
self.get_method_called = False
self.set_method_called = False
def get(self, *args, **kwargs):
self.get_method_called = True
return self.get_data
def set(self, *args, **kwargs):
self.set_method_called = True
def __call__(self, *args, **kwargs):
return self
|
class Mockrequests:
def __init__(self, ok=True, json_data=None):
self.ok = ok
self.json_data = json_data
self.get_method_called = False
def __call__(self, *args, **kwargs):
self.get_method_called = True
self.response = mock_response(json_data=self.json_data)
return self.response
class Mockresponse:
def __init__(self, ok=True, json_data=None):
self.ok = ok
self.json_method_called = False
self.json_data = json_data
def json(self):
self.json_method_called = True
return self.json_data
class Mockredis:
def __init__(self, get_data=None):
self.get_data = get_data
self.get_method_called = False
self.set_method_called = False
def get(self, *args, **kwargs):
self.get_method_called = True
return self.get_data
def set(self, *args, **kwargs):
self.set_method_called = True
def __call__(self, *args, **kwargs):
return self
|
# -*- coding: utf-8 -*-
class Solution:
def minCostToMoveChips(self, chips):
count_even, count_odd = 0, 0
for chip in chips:
if chip % 2 == 0:
count_even += 1
else:
count_odd += 1
return min(count_even, count_odd)
if __name__ == '__main__':
solution = Solution()
assert 1 == solution.minCostToMoveChips([1, 2, 3])
assert 2 == solution.minCostToMoveChips([2, 2, 2, 3, 3])
|
class Solution:
def min_cost_to_move_chips(self, chips):
(count_even, count_odd) = (0, 0)
for chip in chips:
if chip % 2 == 0:
count_even += 1
else:
count_odd += 1
return min(count_even, count_odd)
if __name__ == '__main__':
solution = solution()
assert 1 == solution.minCostToMoveChips([1, 2, 3])
assert 2 == solution.minCostToMoveChips([2, 2, 2, 3, 3])
|
"""Module for user service exceptions"""
__all__ = [
'UserNotFoundException',
'UserIsExistsException',
]
class UserNotFoundException(Exception):
"""Indicates that user not found
Args:
message: Detailed message
"""
def __init__(self, message: str) -> None:
self.message = message
class UserIsExistsException(Exception):
"""Indicates that user is already exists in database
Args:
message: Detailed message
"""
def __init__(self, message: str) -> None:
self.message = message
|
"""Module for user service exceptions"""
__all__ = ['UserNotFoundException', 'UserIsExistsException']
class Usernotfoundexception(Exception):
"""Indicates that user not found
Args:
message: Detailed message
"""
def __init__(self, message: str) -> None:
self.message = message
class Userisexistsexception(Exception):
"""Indicates that user is already exists in database
Args:
message: Detailed message
"""
def __init__(self, message: str) -> None:
self.message = message
|
def _copy_cmd(ctx, file_list, target_dir):
dest_list = []
if file_list == None or len(file_list) == 0:
return dest_list
shell_content = ""
batch_file_name = "%s-copy-files.bat" % (ctx.label.name)
bat = ctx.actions.declare_file(batch_file_name)
src_file_list = []
for (src_file, relative_dest_file) in file_list:
src_file_list.append(src_file)
dest_file = ctx.actions.declare_file("{}/{}".format(target_dir, relative_dest_file))
dest_list.append(dest_file)
shell_content += "@copy /Y \"%s\" \"%s\" >NUL\n" % (
src_file.path.replace("/", "\\"),
dest_file.path.replace("/", "\\"),
)
ctx.actions.write(
output = bat,
content = shell_content,
is_executable = True,
)
ctx.actions.run(
inputs = src_file_list,
tools = [bat],
outputs = dest_list,
executable = "cmd.exe",
arguments = ["/C", bat.path.replace("/", "\\")],
mnemonic = "CopyFile",
progress_message = "Copying files",
use_default_shell_env = True,
)
return dest_list
def _copy_bash(ctx, src_list, target_dir):
dest_list = []
for (src_file, relative_dest_file) in src_list:
dest_file = ctx.actions.declare_file("{}/{}".format(target_dir, relative_dest_file))
dest_list.append(dest_file)
ctx.actions.run_shell(
tools = [src_file],
outputs = [dest_file],
command = "cp -f \"$1\" \"$2\"",
arguments = [src_file.path, dest_file.path],
mnemonic = "CopyFile",
progress_message = "Copying files",
use_default_shell_env = True,
)
return dest_list
def copy_files(ctx, file_list, base_dest_directory, is_windows):
dest_list = []
if is_windows:
dest_list = _copy_cmd(ctx, file_list, base_dest_directory)
else:
dest_list = _copy_bash(ctx, file_list, base_dest_directory)
return dest_list
|
def _copy_cmd(ctx, file_list, target_dir):
dest_list = []
if file_list == None or len(file_list) == 0:
return dest_list
shell_content = ''
batch_file_name = '%s-copy-files.bat' % ctx.label.name
bat = ctx.actions.declare_file(batch_file_name)
src_file_list = []
for (src_file, relative_dest_file) in file_list:
src_file_list.append(src_file)
dest_file = ctx.actions.declare_file('{}/{}'.format(target_dir, relative_dest_file))
dest_list.append(dest_file)
shell_content += '@copy /Y "%s" "%s" >NUL\n' % (src_file.path.replace('/', '\\'), dest_file.path.replace('/', '\\'))
ctx.actions.write(output=bat, content=shell_content, is_executable=True)
ctx.actions.run(inputs=src_file_list, tools=[bat], outputs=dest_list, executable='cmd.exe', arguments=['/C', bat.path.replace('/', '\\')], mnemonic='CopyFile', progress_message='Copying files', use_default_shell_env=True)
return dest_list
def _copy_bash(ctx, src_list, target_dir):
dest_list = []
for (src_file, relative_dest_file) in src_list:
dest_file = ctx.actions.declare_file('{}/{}'.format(target_dir, relative_dest_file))
dest_list.append(dest_file)
ctx.actions.run_shell(tools=[src_file], outputs=[dest_file], command='cp -f "$1" "$2"', arguments=[src_file.path, dest_file.path], mnemonic='CopyFile', progress_message='Copying files', use_default_shell_env=True)
return dest_list
def copy_files(ctx, file_list, base_dest_directory, is_windows):
dest_list = []
if is_windows:
dest_list = _copy_cmd(ctx, file_list, base_dest_directory)
else:
dest_list = _copy_bash(ctx, file_list, base_dest_directory)
return dest_list
|
class Enum(object):
@classmethod
def parse(cls, value):
options = cls.options()
result = []
for k, v in options.items():
if type(v) is not int or v == 0:
continue
if value == 0 or (value & v) == v:
result.append(v)
return result
@classmethod
def options(cls):
result = {}
for key in dir(cls):
if key.startswith('_'):
continue
result[key] = getattr(cls, key)
return result
class Media(Enum):
All = 0
Movies = 1
Shows = 2
Seasons = 4
Episodes = 8
Lists = 16
__map__ = None
@classmethod
def get(cls, key):
if cls.__map__ is None:
cls.__map__ = {
Media.Movies: 'movies',
Media.Shows: 'shows',
Media.Seasons: 'seasons',
Media.Episodes: 'episodes',
Media.Lists: 'lists'
}
return cls.__map__.get(key)
class Data(Enum):
All = 0
Collection = 1
Playback = 2
Ratings = 4
Watched = 8
Watchlist = 16
# Lists
Liked = 32
Personal = 64
__attributes__ = None
__map__ = None
@classmethod
def initialize(cls):
if cls.__attributes__:
return
cls.__attributes__ = {
Data.Collection: {
'interface': 'sync/collection',
'timestamp': 'collected_at'
},
Data.Playback: {
'interface': 'sync/playback',
'timestamp': 'paused_at'
},
Data.Ratings: {
'interface': 'sync/ratings',
'timestamp': 'rated_at'
},
Data.Watched: {
'interface': 'sync/watched',
'timestamp': 'watched_at'
},
Data.Watchlist: {
'interface': 'sync/watchlist',
'timestamp': 'watchlisted_at'
},
# Lists
Data.Liked: {
'interface': 'users/likes',
'timestamp': 'updated_at'
},
Data.Personal: {
'interface': 'users/*/lists',
'timestamp': 'updated_at'
}
}
@classmethod
def get(cls, key):
if cls.__map__ is None:
cls.__map__ = {
Data.Collection: 'collection',
Data.Playback: 'playback',
Data.Ratings: 'ratings',
Data.Watched: 'watched',
Data.Watchlist: 'watchlist',
# Lists
Data.Liked: 'liked',
Data.Personal: 'personal'
}
return cls.__map__.get(key)
@classmethod
def get_interface(cls, key):
return cls.get_attribute(key, 'interface')
@classmethod
def get_timestamp_key(cls, key):
return cls.get_attribute(key, 'timestamp')
@classmethod
def get_attribute(cls, key, attribute):
cls.initialize()
attributes = cls.__attributes__.get(key)
if not attributes:
return None
return attributes.get(attribute)
|
class Enum(object):
@classmethod
def parse(cls, value):
options = cls.options()
result = []
for (k, v) in options.items():
if type(v) is not int or v == 0:
continue
if value == 0 or value & v == v:
result.append(v)
return result
@classmethod
def options(cls):
result = {}
for key in dir(cls):
if key.startswith('_'):
continue
result[key] = getattr(cls, key)
return result
class Media(Enum):
all = 0
movies = 1
shows = 2
seasons = 4
episodes = 8
lists = 16
__map__ = None
@classmethod
def get(cls, key):
if cls.__map__ is None:
cls.__map__ = {Media.Movies: 'movies', Media.Shows: 'shows', Media.Seasons: 'seasons', Media.Episodes: 'episodes', Media.Lists: 'lists'}
return cls.__map__.get(key)
class Data(Enum):
all = 0
collection = 1
playback = 2
ratings = 4
watched = 8
watchlist = 16
liked = 32
personal = 64
__attributes__ = None
__map__ = None
@classmethod
def initialize(cls):
if cls.__attributes__:
return
cls.__attributes__ = {Data.Collection: {'interface': 'sync/collection', 'timestamp': 'collected_at'}, Data.Playback: {'interface': 'sync/playback', 'timestamp': 'paused_at'}, Data.Ratings: {'interface': 'sync/ratings', 'timestamp': 'rated_at'}, Data.Watched: {'interface': 'sync/watched', 'timestamp': 'watched_at'}, Data.Watchlist: {'interface': 'sync/watchlist', 'timestamp': 'watchlisted_at'}, Data.Liked: {'interface': 'users/likes', 'timestamp': 'updated_at'}, Data.Personal: {'interface': 'users/*/lists', 'timestamp': 'updated_at'}}
@classmethod
def get(cls, key):
if cls.__map__ is None:
cls.__map__ = {Data.Collection: 'collection', Data.Playback: 'playback', Data.Ratings: 'ratings', Data.Watched: 'watched', Data.Watchlist: 'watchlist', Data.Liked: 'liked', Data.Personal: 'personal'}
return cls.__map__.get(key)
@classmethod
def get_interface(cls, key):
return cls.get_attribute(key, 'interface')
@classmethod
def get_timestamp_key(cls, key):
return cls.get_attribute(key, 'timestamp')
@classmethod
def get_attribute(cls, key, attribute):
cls.initialize()
attributes = cls.__attributes__.get(key)
if not attributes:
return None
return attributes.get(attribute)
|
class Model:
def __init__(self):
pass
class Optimizer:
def __init__(self):
pass
|
class Model:
def __init__(self):
pass
class Optimizer:
def __init__(self):
pass
|
currency = {
'GDP' : 1.3,
'EUR' : 1.08,
'USD' : 1.0,
'AUD' : 0.66,
'JPY' : 0.0090
}
while True:
intialcur = str(input('Please Enter the currency you want to convert from\n: ')).upper()
while True:
if intialcur in currency:
break
else:
intialcur = str(input('Not in list. Please Enter the currency you want to convert from\n: ')).upper()
intialvalue = input('Please enter the amount of that currency\n: ')
while True:
try:
float(intialvalue)
break
except ValueError:
intialvalue = input('Not a number. Please enter the amount of that currency\n: ')
finalcur = str(input('Enter the currency you want to convert this to\n: ')).upper()
while True:
if finalcur in currency:
break
else:
finalcur = str(input('Not in list. Please Enter the currency you want to convert from\n: ')).upper()
finalvalue = (float(currency.get(str(intialcur))) * float(intialvalue)) / float(currency.get(str(finalcur)))
print(finalvalue)
decision = input('Would you like to convert more values?').lower()
if decision == 'no':
print('Goodbye')
exit()
elif decision != 'no' and decision != 'yes':
decision = input('Would you like to convert more values? Please enter yes or no\n: ').lower()
|
currency = {'GDP': 1.3, 'EUR': 1.08, 'USD': 1.0, 'AUD': 0.66, 'JPY': 0.009}
while True:
intialcur = str(input('Please Enter the currency you want to convert from\n: ')).upper()
while True:
if intialcur in currency:
break
else:
intialcur = str(input('Not in list. Please Enter the currency you want to convert from\n: ')).upper()
intialvalue = input('Please enter the amount of that currency\n: ')
while True:
try:
float(intialvalue)
break
except ValueError:
intialvalue = input('Not a number. Please enter the amount of that currency\n: ')
finalcur = str(input('Enter the currency you want to convert this to\n: ')).upper()
while True:
if finalcur in currency:
break
else:
finalcur = str(input('Not in list. Please Enter the currency you want to convert from\n: ')).upper()
finalvalue = float(currency.get(str(intialcur))) * float(intialvalue) / float(currency.get(str(finalcur)))
print(finalvalue)
decision = input('Would you like to convert more values?').lower()
if decision == 'no':
print('Goodbye')
exit()
elif decision != 'no' and decision != 'yes':
decision = input('Would you like to convert more values? Please enter yes or no\n: ').lower()
|
"""
Implementation of a specific learning rate scheduler for GANs.
"""
class DRS_LRScheduler:
"""
Learning rate scheduler for training GANs. Supports GAN specific LR scheduling
policies, such as the linear decay policy using in SN-GAN paper as based on the
original chainer implementation. However, one could safely ignore this class
and instead use the official PyTorch scheduler wrappers around a optimizer
for other scheduling policies.
Attributes:
lr_decay (str): The learning rate decay policy to use.
optD (Optimizer): Torch optimizer object for discriminator.
optG (Optimizer): Torch optimizer object for generator.
num_steps (int): The number of training iterations.
lr_D (float): The initial learning rate of optD.
lr_G (float): The initial learning rate of optG.
"""
def __init__(self,
lr_decay,
optimizers,
num_steps,
start_step=0,
**kwargs):
if lr_decay not in [None, 'None', 'linear']:
raise NotImplementedError(
"lr_decay {} is not currently supported.")
self.lr_decay = lr_decay
self.optimizers = optimizers
self.num_steps = num_steps
self.start_step = start_step
# Cache the initial learning rate for uses later
self.lrs = [opt.param_groups[0]['lr'] for opt in optimizers]
def linear_decay(self, optimizer, global_step, lr_value_range,
lr_step_range):
"""
Performs linear decay of the optimizer learning rate based on the number of global
steps taken. Follows SNGAN's chainer implementation of linear decay, as seen in the
chainer references:
https://docs.chainer.org/en/stable/reference/generated/chainer.training.extensions.LinearShift.html
https://github.com/chainer/chainer/blob/v6.2.0/chainer/training/extensions/linear_shift.py#L66
Note: assumes that the optimizer has only one parameter group to update!
Args:
optimizer (Optimizer): Torch optimizer object to update learning rate.
global_step (int): The current global step of the training.
lr_value_range (tuple): A tuple of floats (x,y) to decrease from x to y.
lr_step_range (tuple): A tuple of ints (i, j) to start decreasing
when global_step > i, and until j.
Returns:
float: Float representing the new updated learning rate.
"""
# Compute the new learning rate
v1, v2 = lr_value_range
s1, s2 = lr_step_range
if global_step <= s1:
updated_lr = v1
elif global_step >= s2:
updated_lr = v2
else:
scale_factor = (global_step - s1) / (s2 - s1)
updated_lr = v1 + scale_factor * (v2 - v1)
# Update the learning rate
optimizer.param_groups[0]['lr'] = updated_lr
return updated_lr
def step(self, log_data, global_step):
"""
Takes a step for updating learning rate and updates the input log_data
with the current status.
Args:
log_data (MetricLog): Object for logging the updated learning rate metric.
global_step (int): The current global step of the training.
Returns:
MetricLog: MetricLog object containing the updated learning rate at the current global step.
"""
for idx, (opt, init_lr) in enumerate(zip(self.optimizers, self.lrs)):
if self.lr_decay == "linear":
lr = self.linear_decay(
optimizer=opt,
global_step=global_step,
lr_value_range=(init_lr, 0.0),
lr_step_range=(self.start_step,
self.num_steps))
elif self.lr_decay in [None, "None"]:
lr = init_lr
# Update metrics log
log_data.add_metric(f'lr_{idx}', lr, group='lr', precision=6)
return log_data
|
"""
Implementation of a specific learning rate scheduler for GANs.
"""
class Drs_Lrscheduler:
"""
Learning rate scheduler for training GANs. Supports GAN specific LR scheduling
policies, such as the linear decay policy using in SN-GAN paper as based on the
original chainer implementation. However, one could safely ignore this class
and instead use the official PyTorch scheduler wrappers around a optimizer
for other scheduling policies.
Attributes:
lr_decay (str): The learning rate decay policy to use.
optD (Optimizer): Torch optimizer object for discriminator.
optG (Optimizer): Torch optimizer object for generator.
num_steps (int): The number of training iterations.
lr_D (float): The initial learning rate of optD.
lr_G (float): The initial learning rate of optG.
"""
def __init__(self, lr_decay, optimizers, num_steps, start_step=0, **kwargs):
if lr_decay not in [None, 'None', 'linear']:
raise not_implemented_error('lr_decay {} is not currently supported.')
self.lr_decay = lr_decay
self.optimizers = optimizers
self.num_steps = num_steps
self.start_step = start_step
self.lrs = [opt.param_groups[0]['lr'] for opt in optimizers]
def linear_decay(self, optimizer, global_step, lr_value_range, lr_step_range):
"""
Performs linear decay of the optimizer learning rate based on the number of global
steps taken. Follows SNGAN's chainer implementation of linear decay, as seen in the
chainer references:
https://docs.chainer.org/en/stable/reference/generated/chainer.training.extensions.LinearShift.html
https://github.com/chainer/chainer/blob/v6.2.0/chainer/training/extensions/linear_shift.py#L66
Note: assumes that the optimizer has only one parameter group to update!
Args:
optimizer (Optimizer): Torch optimizer object to update learning rate.
global_step (int): The current global step of the training.
lr_value_range (tuple): A tuple of floats (x,y) to decrease from x to y.
lr_step_range (tuple): A tuple of ints (i, j) to start decreasing
when global_step > i, and until j.
Returns:
float: Float representing the new updated learning rate.
"""
(v1, v2) = lr_value_range
(s1, s2) = lr_step_range
if global_step <= s1:
updated_lr = v1
elif global_step >= s2:
updated_lr = v2
else:
scale_factor = (global_step - s1) / (s2 - s1)
updated_lr = v1 + scale_factor * (v2 - v1)
optimizer.param_groups[0]['lr'] = updated_lr
return updated_lr
def step(self, log_data, global_step):
"""
Takes a step for updating learning rate and updates the input log_data
with the current status.
Args:
log_data (MetricLog): Object for logging the updated learning rate metric.
global_step (int): The current global step of the training.
Returns:
MetricLog: MetricLog object containing the updated learning rate at the current global step.
"""
for (idx, (opt, init_lr)) in enumerate(zip(self.optimizers, self.lrs)):
if self.lr_decay == 'linear':
lr = self.linear_decay(optimizer=opt, global_step=global_step, lr_value_range=(init_lr, 0.0), lr_step_range=(self.start_step, self.num_steps))
elif self.lr_decay in [None, 'None']:
lr = init_lr
log_data.add_metric(f'lr_{idx}', lr, group='lr', precision=6)
return log_data
|
n, a, b = map(int, input().split())
ans = 0
for i in range(1, n+1):
str_i = str(i)
sum = 0
for j in range(len(str_i)):
sum += int(str_i[j])
if a <= sum <= b:
ans +=i
print(ans)
|
(n, a, b) = map(int, input().split())
ans = 0
for i in range(1, n + 1):
str_i = str(i)
sum = 0
for j in range(len(str_i)):
sum += int(str_i[j])
if a <= sum <= b:
ans += i
print(ans)
|
VERSION = "0.0.2"
VERSION_GUI = "0.0.2"
VERSION_CUI = "0.0.0"
VERSION_AUDIOCABLE = "0.0.2"
VERSION_ROUTE = "0.0.2"
VERSION_SETINGS = "0.0.1"
CALLBACK_AUDIOCABLE_SELECTED = None
CALLBACK_ROUTE_SELECTED = None
SETTINGS = None
CONFIGURATION = None
PATH_ROOT = ""
PATH_SETTINGS = ""
|
version = '0.0.2'
version_gui = '0.0.2'
version_cui = '0.0.0'
version_audiocable = '0.0.2'
version_route = '0.0.2'
version_setings = '0.0.1'
callback_audiocable_selected = None
callback_route_selected = None
settings = None
configuration = None
path_root = ''
path_settings = ''
|
def xor_reverse(iterable):
lenght = len(iterable)
i = 0
while i < lenght // 2:
iterable[i] ^= iterable[lenght - i - 1]
iterable[lenght - i - 1] ^= iterable[i]
iterable[i] ^= iterable[lenght - i - 1]
i += 1
return iterable
|
def xor_reverse(iterable):
lenght = len(iterable)
i = 0
while i < lenght // 2:
iterable[i] ^= iterable[lenght - i - 1]
iterable[lenght - i - 1] ^= iterable[i]
iterable[i] ^= iterable[lenght - i - 1]
i += 1
return iterable
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
# pylint: disable=line-too-long
def load_arguments(commands_loader, _):
with commands_loader.argument_context('apim api policy') as c:
c.argument('api_id', options_list=['--api-id', '-a'], help='API revision identifier. Must be unique in the current API Management service instance.')
c.argument('xml', options_list=['--xml-value', '-v'], help='The XML document value inline as a non-XML encoded string.')
c.argument('xml_path', options_list=['--xml-file', '-f'], help='The path to the policy XML document.')
c.argument('xml_uri', options_list=['--xml-uri', '-u'], help='The URI of the policy XML document from an HTTP endpoint accessible from the API Management service.')
|
def load_arguments(commands_loader, _):
with commands_loader.argument_context('apim api policy') as c:
c.argument('api_id', options_list=['--api-id', '-a'], help='API revision identifier. Must be unique in the current API Management service instance.')
c.argument('xml', options_list=['--xml-value', '-v'], help='The XML document value inline as a non-XML encoded string.')
c.argument('xml_path', options_list=['--xml-file', '-f'], help='The path to the policy XML document.')
c.argument('xml_uri', options_list=['--xml-uri', '-u'], help='The URI of the policy XML document from an HTTP endpoint accessible from the API Management service.')
|
# Variables that contain the user credentials to access Twitter API.
ACCESS_TOKEN = "570634225-AnsM63tVCpI4yeFwpj6QfSJTwm3pUx6onf30fI2Z"
ACCESS_TOKEN_SECRET = "ykA5CW0lWpl3VDiIRqJ5rhJjsQc6fyt0pps22tLAywXUJ"
CONSUMER_KEY = "iRwp1I7vH0cBoWNIO5w0uxURN"
CONSUMER_SECRET = "5rA8XDisNbzwTueiCiZG7JXEZe5T4HRiwLbFjWMTWlyNoU35r4"
|
access_token = '570634225-AnsM63tVCpI4yeFwpj6QfSJTwm3pUx6onf30fI2Z'
access_token_secret = 'ykA5CW0lWpl3VDiIRqJ5rhJjsQc6fyt0pps22tLAywXUJ'
consumer_key = 'iRwp1I7vH0cBoWNIO5w0uxURN'
consumer_secret = '5rA8XDisNbzwTueiCiZG7JXEZe5T4HRiwLbFjWMTWlyNoU35r4'
|
def split_data(input, output, validation_percentage=0.1):
num_sets = output.shape[0]
num_validation = int(num_sets * validation_percentage)
return (input[:-num_validation], output[:-num_validation]), (input[-num_validation:], output[-num_validation:])
|
def split_data(input, output, validation_percentage=0.1):
num_sets = output.shape[0]
num_validation = int(num_sets * validation_percentage)
return ((input[:-num_validation], output[:-num_validation]), (input[-num_validation:], output[-num_validation:]))
|
class Solution:
def maxProfit(self, prices: List[int]) -> int:
# 1st solution
# O(n) time | O(1) space
profit = 0
start = prices[0]
end = start
for i, price in enumerate(prices):
if price >= end and i < len(prices) - 1:
end = price
else:
if price >= end:
profit += price - start
elif end > start:
profit += end - start
start = price
end = start
return profit
# 2nd Solution
# O(n) time | O(1) space
total = 0
for i in range(len(prices) - 1):
curProfit = prices[i + 1] - prices[i]
if curProfit > 0:
total += curProfit
return total
|
class Solution:
def max_profit(self, prices: List[int]) -> int:
profit = 0
start = prices[0]
end = start
for (i, price) in enumerate(prices):
if price >= end and i < len(prices) - 1:
end = price
else:
if price >= end:
profit += price - start
elif end > start:
profit += end - start
start = price
end = start
return profit
total = 0
for i in range(len(prices) - 1):
cur_profit = prices[i + 1] - prices[i]
if curProfit > 0:
total += curProfit
return total
|
class Stat:
def __init__(self):
self.sum = {}
self.sum_square = {}
self.count = {}
def add(self, key, value):
self.count[key] = self.count.get(key, 0) + 1
self.sum[key] = self.sum.get(key, 0.0) + value
self.sum_square[key] = self.sum_square.get(key, 0.0) + value ** 2
def add_dict(self, dict):
for key in dict:
self.add(key, dict[key])
def print_stat(self):
for key in self.count:
name = key
count = self.count[key]
sum = self.sum[key]
square = self.sum_square[key]
avg = sum / count
std = (square / count - (avg) ** 2) ** 0.5
print("%s - count %d avg %.2g std %.2g" % (name, count, avg, std))
def get_count(self, keys):
return {key: self.count.get(key, 0) for key in keys}
def get_avg(self, keys):
return {key: self.sum.get(key, 0) / self.count.get(key, 0) for key in keys if self.count.get(key, 0) != 0}
def get_std(self, keys):
return {key: (self.square.get(key, 0) / self.sum.get(key, 0) - (
self.sum.get(key, 0) / self.count.get(key, 0)) ** 2) ** 0.5 for key in keys if key in self.count}
|
class Stat:
def __init__(self):
self.sum = {}
self.sum_square = {}
self.count = {}
def add(self, key, value):
self.count[key] = self.count.get(key, 0) + 1
self.sum[key] = self.sum.get(key, 0.0) + value
self.sum_square[key] = self.sum_square.get(key, 0.0) + value ** 2
def add_dict(self, dict):
for key in dict:
self.add(key, dict[key])
def print_stat(self):
for key in self.count:
name = key
count = self.count[key]
sum = self.sum[key]
square = self.sum_square[key]
avg = sum / count
std = (square / count - avg ** 2) ** 0.5
print('%s - count %d avg %.2g std %.2g' % (name, count, avg, std))
def get_count(self, keys):
return {key: self.count.get(key, 0) for key in keys}
def get_avg(self, keys):
return {key: self.sum.get(key, 0) / self.count.get(key, 0) for key in keys if self.count.get(key, 0) != 0}
def get_std(self, keys):
return {key: (self.square.get(key, 0) / self.sum.get(key, 0) - (self.sum.get(key, 0) / self.count.get(key, 0)) ** 2) ** 0.5 for key in keys if key in self.count}
|
BUY = 1
SALE = 2
OrderType = [
(BUY, 'BUY'),
(SALE, 'SALE')
]
|
buy = 1
sale = 2
order_type = [(BUY, 'BUY'), (SALE, 'SALE')]
|
# A function with Behavior That varies Over Time
# A function compound value have a body and a parent frame
# The parent frame contains the balance, the local state of the withdraw function
# Non-Local Assignment & Persistent Local State
# Work for python 3
def make_withdraw(balance):
""" Return a withdraw function with a starting balance."""
def withdraw(amount):
nonlocal balance # Declare the name "balance" nonlocal at the top of the body
# of the function which it is re-assigned
if amount > balance:
return 'Insufficient funds'
balance = balance - amount #Re-bind balance in the first non-local frame in which
#it was bound previously
return balance
def deposit(amount):
nonlocal balance
balance = balance + amount
return balance
return withdraw, deposit
# nonlocal <name>
# Effect: future assignments to that name change its pre-existing binding in the first non-local frame of the current environment
# Alternative 2.7
def make_withdraw(balance):
""" Return a withdraw function with a starting balance."""
balance = [balance]
def withdraw(amount):
if amount > balance[0]:
return 'Insufficient funds'
balance[0] = balance[0] - amount
return balance[0]
def deposit(amount):
balance[0] = balance[0] + amount
return balance[0]
return withdraw, deposit
|
def make_withdraw(balance):
""" Return a withdraw function with a starting balance."""
def withdraw(amount):
nonlocal balance
if amount > balance:
return 'Insufficient funds'
balance = balance - amount
return balance
def deposit(amount):
nonlocal balance
balance = balance + amount
return balance
return (withdraw, deposit)
def make_withdraw(balance):
""" Return a withdraw function with a starting balance."""
balance = [balance]
def withdraw(amount):
if amount > balance[0]:
return 'Insufficient funds'
balance[0] = balance[0] - amount
return balance[0]
def deposit(amount):
balance[0] = balance[0] + amount
return balance[0]
return (withdraw, deposit)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.