content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
#Calculator app
# read input
# figure out order of operations
# consider edge cases
#divide by zero
#formula : string => "1 + 2 + 3"
def Calculator(formula):
"""Calculator handler executes calculation and returns float result"""
ans = 0
#read input into a list
tokens = formula.split()
print(tokens)
#execute multiplication and division first
oopList = oopFirstPass(tokens)
print(oopList)
#addition and subtraction second
if (oopList is not None):
tokens2 = oopList.split()
print(tokens2)
ans = oopSecondPass(tokens2)
return ans
def oopFirstPass(tokens):
"""checks for add/sub operations to add to new string and executes mult/div operations"""
oopList = ""
num1 = None
num2 = None
operation = None
for val in tokens:
if (num1 is None):
num1 = float(val)
continue
if (val == "+" or val == "-"):
#add to oopList
oopList += str(num1) + " " + val + " "
num1 = None
continue
if (operation is None):
operation = val
continue
if (num2 is None):
num2 = float(val)
# do multiply/division
if (operation == "*"):
num1 = multiply(num1, num2)
elif (operation == "/"):
num1 = divide(num1, num2)
else:
return "Incorrect Input Formula"
num2 = None
operation = None
oopList += str(num1)
return oopList
def oopSecondPass(tokens):
"""executes add/sub operations and returns final result"""
num1 = None
num2 = None
operation = None
for val in tokens:
if (num1 is None):
num1 = float(val)
continue
if (operation is None):
operation = val
continue
if (num2 is None):
num2 = float(val)
#do add/subtract
if (operation == "+"):
num1 = add(num1, num2)
elif (operation == "-"):
num1 = subtract(num1, num2)
else:
return "Incorrect Input Formula"
num2 = None
operation = None
return num1
def multiply(x, y):
return x * y
def divide(x, y):
return x / y
def add(x, y):
return x + y
def subtract(x, y):
return x - y
answer = Calculator("1 * 2 * 2 / 3")
print(answer) | def calculator(formula):
"""Calculator handler executes calculation and returns float result"""
ans = 0
tokens = formula.split()
print(tokens)
oop_list = oop_first_pass(tokens)
print(oopList)
if oopList is not None:
tokens2 = oopList.split()
print(tokens2)
ans = oop_second_pass(tokens2)
return ans
def oop_first_pass(tokens):
"""checks for add/sub operations to add to new string and executes mult/div operations"""
oop_list = ''
num1 = None
num2 = None
operation = None
for val in tokens:
if num1 is None:
num1 = float(val)
continue
if val == '+' or val == '-':
oop_list += str(num1) + ' ' + val + ' '
num1 = None
continue
if operation is None:
operation = val
continue
if num2 is None:
num2 = float(val)
if operation == '*':
num1 = multiply(num1, num2)
elif operation == '/':
num1 = divide(num1, num2)
else:
return 'Incorrect Input Formula'
num2 = None
operation = None
oop_list += str(num1)
return oopList
def oop_second_pass(tokens):
"""executes add/sub operations and returns final result"""
num1 = None
num2 = None
operation = None
for val in tokens:
if num1 is None:
num1 = float(val)
continue
if operation is None:
operation = val
continue
if num2 is None:
num2 = float(val)
if operation == '+':
num1 = add(num1, num2)
elif operation == '-':
num1 = subtract(num1, num2)
else:
return 'Incorrect Input Formula'
num2 = None
operation = None
return num1
def multiply(x, y):
return x * y
def divide(x, y):
return x / y
def add(x, y):
return x + y
def subtract(x, y):
return x - y
answer = calculator('1 * 2 * 2 / 3')
print(answer) |
class Form:
company: str
user: str
days: int
def __init__(self, company, user, days):
self.company = company
self.user = user
self.days = days
| class Form:
company: str
user: str
days: int
def __init__(self, company, user, days):
self.company = company
self.user = user
self.days = days |
def large(arr):
if (len(arr)) < 0:
return 0
max_sum = current = arr[0]
for num in arr[1:]:
current = max(current + num, num)
max_sum = max(current, max_sum)
return max_sum
if __name__ == "__main__":
print(large([1, -1, 3, -4, 5, -3, 6, -3, 2, -1])) | def large(arr):
if len(arr) < 0:
return 0
max_sum = current = arr[0]
for num in arr[1:]:
current = max(current + num, num)
max_sum = max(current, max_sum)
return max_sum
if __name__ == '__main__':
print(large([1, -1, 3, -4, 5, -3, 6, -3, 2, -1])) |
for i in range(int(input())):
n, k, s = list(map(int, input().split()))
total = k * s
count = 0
val = False
m = 0
for j in range(1, s + 1):
if (j % 7) != 0:
count += n
m += 1
else:
continue
if count >= total:
val = True
break
if val:
print(m)
else:
print(-1) | for i in range(int(input())):
(n, k, s) = list(map(int, input().split()))
total = k * s
count = 0
val = False
m = 0
for j in range(1, s + 1):
if j % 7 != 0:
count += n
m += 1
else:
continue
if count >= total:
val = True
break
if val:
print(m)
else:
print(-1) |
# Python program to display astrological sign
# or Zodiac sign for given date of birth
def zodiac_sign(day, month):
# checks month and date within the valid range
# of a specified zodiac
if month == 'december':
astro_sign = 'Sagittarius' if (day < 22) else 'capricorn'
elif month == 'january':
astro_sign = 'Capricorn' if (day < 20) else 'aquarius'
elif month == 'february':
astro_sign = 'Aquarius' if (day < 19) else 'pisces'
elif month == 'march':
astro_sign = 'Pisces' if (day < 21) else 'aries'
elif month == 'april':
astro_sign = 'Aries' if (day < 20) else 'taurus'
elif month == 'may':
astro_sign = 'Taurus' if (day < 21) else 'gemini'
elif month == 'june':
astro_sign = 'Gemini' if (day < 21) else 'cancer'
elif month == 'july':
astro_sign = 'Cancer' if (day < 23) else 'leo'
elif month == 'august':
astro_sign = 'Leo' if (day < 23) else 'virgo'
elif month == 'september':
astro_sign = 'Virgo' if (day < 23) else 'libra'
elif month == 'october':
astro_sign = 'Libra' if (day < 23) else 'scorpio'
elif month == 'november':
astro_sign = 'scorpio' if (day < 22) else 'sagittarius'
print(astro_sign)
# Driver code
if __name__ == '__main__':
day = 21
month = "april"
zodiac_sign(day, month)
| def zodiac_sign(day, month):
if month == 'december':
astro_sign = 'Sagittarius' if day < 22 else 'capricorn'
elif month == 'january':
astro_sign = 'Capricorn' if day < 20 else 'aquarius'
elif month == 'february':
astro_sign = 'Aquarius' if day < 19 else 'pisces'
elif month == 'march':
astro_sign = 'Pisces' if day < 21 else 'aries'
elif month == 'april':
astro_sign = 'Aries' if day < 20 else 'taurus'
elif month == 'may':
astro_sign = 'Taurus' if day < 21 else 'gemini'
elif month == 'june':
astro_sign = 'Gemini' if day < 21 else 'cancer'
elif month == 'july':
astro_sign = 'Cancer' if day < 23 else 'leo'
elif month == 'august':
astro_sign = 'Leo' if day < 23 else 'virgo'
elif month == 'september':
astro_sign = 'Virgo' if day < 23 else 'libra'
elif month == 'october':
astro_sign = 'Libra' if day < 23 else 'scorpio'
elif month == 'november':
astro_sign = 'scorpio' if day < 22 else 'sagittarius'
print(astro_sign)
if __name__ == '__main__':
day = 21
month = 'april'
zodiac_sign(day, month) |
class Redirect(Exception):
def __init__(self, *args, **kwargs):
self.args = args
self.kwargs = kwargs
| class Redirect(Exception):
def __init__(self, *args, **kwargs):
self.args = args
self.kwargs = kwargs |
audio = [
"aif",
"cda",
"mid",
"midi",
"mp3",
"mpa",
"ogg",
"wav",
"wma",
"wpl"
]
compressed = [
"arj",
"deb",
"gz",
"pkg",
"rar",
"rpm",
"tar",
"z",
"zip"
]
image = [
"ai",
"bmp",
"gif",
"ico",
"jpeg",
"jpg",
"png",
"ps",
"psd",
"svg",
"tif",
"tiff",
"webp"
]
spreadsheet = [
"ods",
"xlr",
"xls",
"xlsx"
]
text = [
"doc",
"docx",
"odt",
"pdf",
"rtf",
"tex",
"txt",
"wks",
"wpd",
"wps"
]
video = [
"avi",
"mp4"
]
| audio = ['aif', 'cda', 'mid', 'midi', 'mp3', 'mpa', 'ogg', 'wav', 'wma', 'wpl']
compressed = ['arj', 'deb', 'gz', 'pkg', 'rar', 'rpm', 'tar', 'z', 'zip']
image = ['ai', 'bmp', 'gif', 'ico', 'jpeg', 'jpg', 'png', 'ps', 'psd', 'svg', 'tif', 'tiff', 'webp']
spreadsheet = ['ods', 'xlr', 'xls', 'xlsx']
text = ['doc', 'docx', 'odt', 'pdf', 'rtf', 'tex', 'txt', 'wks', 'wpd', 'wps']
video = ['avi', 'mp4'] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class UnknownSizeError(Exception):
def __init__(self, cls):
self.cls = cls
def __str__(self):
return f'The size of `{self.cls}` is unkown, the object could not be generated.'
class UnavalibleAttributeError(Exception):
def __init__(self, cls, attr_name):
self.cls = cls
self.attr_name = attr_name
def __str__(self):
return f'Did not defined attribute `{self.attr_name}` for `{self.cls}`.' | class Unknownsizeerror(Exception):
def __init__(self, cls):
self.cls = cls
def __str__(self):
return f'The size of `{self.cls}` is unkown, the object could not be generated.'
class Unavalibleattributeerror(Exception):
def __init__(self, cls, attr_name):
self.cls = cls
self.attr_name = attr_name
def __str__(self):
return f'Did not defined attribute `{self.attr_name}` for `{self.cls}`.' |
# ------------------------------
# 166. Fraction to Recurring Decimal
#
# Description:
# Given two integers representing the numerator and denominator of a fraction, return the fraction in string format.
# If the fractional part is repeating, enclose the repeating part in parentheses.
# Example 1:
# Input: numerator = 1, denominator = 2
# Output: "0.5"
#
# Example 2:
# Input: numerator = 2, denominator = 1
# Output: "2"
#
# Example 3:
# Input: numerator = 2, denominator = 3
# Output: "0.(6)"
#
# Version: 1.0
# 08/26/18 by Jianfa
# ------------------------------
class Solution(object):
def fractionToDecimal(self, numerator, denominator):
"""
:type numerator: int
:type denominator: int
:rtype: str
"""
if numerator == 0:
return "0"
res = []
res.append('-' if (numerator > 0) ^ (denominator > 0) else "")
num = abs(numerator)
denom = abs(denominator)
# Integral part
res.append(str(num / denom))
num %= denom
if num == 0:
return ''.join(res)
res.append('.')
dic = dict()
dic[num] = len(res)
# Fractional part
while num:
num *= 10
res.append(str(num / denom))
num %= denom
if num in dic: # fractional part is start to repeat
res.insert(dic[num], '(')
res.insert(len(res), ')')
break
else:
dic[num] = len(res)
return ''.join(res)
# Used for testing
if __name__ == "__main__":
test = Solution()
# ------------------------------
# Summary:
# Get solution from https://leetcode.com/problems/fraction-to-recurring-decimal/discuss/51106/My-clean-Java-solution
# The point is to seperate building the result to integral part and fractional part.
# Maintain a list, add digits to the list one by one. | class Solution(object):
def fraction_to_decimal(self, numerator, denominator):
"""
:type numerator: int
:type denominator: int
:rtype: str
"""
if numerator == 0:
return '0'
res = []
res.append('-' if (numerator > 0) ^ (denominator > 0) else '')
num = abs(numerator)
denom = abs(denominator)
res.append(str(num / denom))
num %= denom
if num == 0:
return ''.join(res)
res.append('.')
dic = dict()
dic[num] = len(res)
while num:
num *= 10
res.append(str(num / denom))
num %= denom
if num in dic:
res.insert(dic[num], '(')
res.insert(len(res), ')')
break
else:
dic[num] = len(res)
return ''.join(res)
if __name__ == '__main__':
test = solution() |
# test short circuit expressions outside if conditionals
print(() or 1)
print((1,) or 1)
print(() and 1)
print((1,) and 1)
print("PASS") | print(() or 1)
print((1,) or 1)
print(() and 1)
print((1,) and 1)
print('PASS') |
TRAINING_DATA = [
(
"i went to amsterdem last year and the canals were beautiful",
{"entities": [(10, 19, "TOURIST_DESTINATION")]},
),
(
"You should visit Paris once in your life, but the Eiffel Tower is kinda boring",
{"entities": [(17, 22, "TOURIST_DESTINATION")]},
),
("There's also a Paris in Arkansas, lol", {"entities": []}),
(
"Berlin is perfect for summer holiday: lots of parks, great nightlife, cheap beer!",
{"entities": [(0, 6, "TOURIST_DESTINATION")]},
),
]
| training_data = [('i went to amsterdem last year and the canals were beautiful', {'entities': [(10, 19, 'TOURIST_DESTINATION')]}), ('You should visit Paris once in your life, but the Eiffel Tower is kinda boring', {'entities': [(17, 22, 'TOURIST_DESTINATION')]}), ("There's also a Paris in Arkansas, lol", {'entities': []}), ('Berlin is perfect for summer holiday: lots of parks, great nightlife, cheap beer!', {'entities': [(0, 6, 'TOURIST_DESTINATION')]})] |
class LoraCommands:
## Returns the firmware version and release date in format: "RN2903 X.Y.Z MMM DD YYYY HH:MM:SS"
GET_VERSION = 'sys get ver'
## Resets LoRa stack
RESET_STACK = 'mac reset'
## Sets the LoRA functionality to radio (needs to be done before anything else)
START_RADIO_OP = 'mac pause'
## Sets the radio pwr to the given value in dB (range from 2dB to 20dB)
SET_RADIO_POWER = 'radio set pwr {}'
## Gets current operating mode (LoRa or FSK)
GET_RADIO_MODE = 'radio get mod'
## Gets radio frequency
GET_RADIO_FREQUENCY = 'radio get freq'
## Gets radio spreading factor (values can be sf7, sf8, sf9, sf10, sf11, sf12)
GET_RADIO_SPREADING_FACTOR = 'radio get sf'
## Sets the radio functionality to receive continuously
SET_CONTINUOUS_RADIO_RECEPTION = 'radio rx 0'
## Exits the radio functionality to receive continuously
EXIT_CONTINUOUS_RADIO_RECEPTION = 'radio rxstop'
## Disables the watchdog timer timeout for continuous reception
DISABLE_TIMEOUT = 'radio set wdt 0'
## Turns the LoRa stick LED on
TURN_OFF_RED_LED = 'sys set pindig GPIO11 0'
## Turns the LoRa stick LED off
TURN_ON_RED_LED = 'sys set pindig GPIO11 1'
## Turns the LoRa stick LED on
TURN_OFF_BLUE_LED = 'sys set pindig GPIO10 0'
## Turns the LoRa stick LED off
TURN_ON_BLUE_LED = 'sys set pindig GPIO10 1'
## Data was successfully received
RADIO_DATA_OK = 'ok'
## An error occured during radio operations
RADIO_DATA_ERROR = 'radio_err'
## The radio line was busy
RADIO_LINE_BUSY = 'busy'
## Input of radio command was invalid
RADIO_INVALID_PARAM = 'invalid_param'
## Data received over radio
RADIO_RADIO_DATA_RECEIVED = 'radio_rx'
## Radio data transmission was successful
RADIO_TRANSFER_OK = 'radio_tx_ok'
## Radio transfer over radio
RADIO_DATA_TRANSFER = 'radio tx {}'
| class Loracommands:
get_version = 'sys get ver'
reset_stack = 'mac reset'
start_radio_op = 'mac pause'
set_radio_power = 'radio set pwr {}'
get_radio_mode = 'radio get mod'
get_radio_frequency = 'radio get freq'
get_radio_spreading_factor = 'radio get sf'
set_continuous_radio_reception = 'radio rx 0'
exit_continuous_radio_reception = 'radio rxstop'
disable_timeout = 'radio set wdt 0'
turn_off_red_led = 'sys set pindig GPIO11 0'
turn_on_red_led = 'sys set pindig GPIO11 1'
turn_off_blue_led = 'sys set pindig GPIO10 0'
turn_on_blue_led = 'sys set pindig GPIO10 1'
radio_data_ok = 'ok'
radio_data_error = 'radio_err'
radio_line_busy = 'busy'
radio_invalid_param = 'invalid_param'
radio_radio_data_received = 'radio_rx'
radio_transfer_ok = 'radio_tx_ok'
radio_data_transfer = 'radio tx {}' |
"""
Integers in Python can be as big as the bytes in your machine's memory. There is no limit in size as there is: (c++ int) or
(C++ long long int).
As we know, the result of
grows really fast with increasing
.
Let's do some calculations on very large integers.
Task
Read four numbers,
, , , and , and print the result of
.
Input Format
Integers
, , , and
are given on four separate lines, respectively.
Constraints
Output Format
Print the result of
on one line.
Sample Input
9
29
7
27
Sample Output
4710194409608608369201743232
Note: This result is bigger than
. Hence, it won't fit in the long long int of C++ or a 64-bit integer.
"""
# SOLUTION 1
a = int(input())
b = int(input())
c = int(input())
d = int(input())
result = (a**b) + (c**d)
print(result)
# SOLUTION 2
a, b, c, d = (int(input()) for _ in range(4))
print(pow(a, b)+pow(c, d))
| """
Integers in Python can be as big as the bytes in your machine's memory. There is no limit in size as there is: (c++ int) or
(C++ long long int).
As we know, the result of
grows really fast with increasing
.
Let's do some calculations on very large integers.
Task
Read four numbers,
, , , and , and print the result of
.
Input Format
Integers
, , , and
are given on four separate lines, respectively.
Constraints
Output Format
Print the result of
on one line.
Sample Input
9
29
7
27
Sample Output
4710194409608608369201743232
Note: This result is bigger than
. Hence, it won't fit in the long long int of C++ or a 64-bit integer.
"""
a = int(input())
b = int(input())
c = int(input())
d = int(input())
result = a ** b + c ** d
print(result)
(a, b, c, d) = (int(input()) for _ in range(4))
print(pow(a, b) + pow(c, d)) |
# DataBase Credentials
database="da665kfg2oc9og"
user = "aourrzrdjlrpjo"
password = "12359d0fa8d70aeea4d2ef3acd96eb794f178dee42887f7c350ad49a4d78e323"
host = "ec2-18-207-95-219.compute-1.amazonaws.com"
port = "5432" | database = 'da665kfg2oc9og'
user = 'aourrzrdjlrpjo'
password = '12359d0fa8d70aeea4d2ef3acd96eb794f178dee42887f7c350ad49a4d78e323'
host = 'ec2-18-207-95-219.compute-1.amazonaws.com'
port = '5432' |
# http://codeforces.com/contest/268/problem/C
n, m = map(int, input().split())
d = min(n, m)
print(d + 1)
for i in range(d + 1): print("{} {}".format(d-i, i)) | (n, m) = map(int, input().split())
d = min(n, m)
print(d + 1)
for i in range(d + 1):
print('{} {}'.format(d - i, i)) |
infile = "input_file.txt"
outfile = "output_file.txt"
delete_list = [
# Your words you want to fill to filter.
"Dog","Bird","Pig"
]
with open(infile) as fin, open(outfile, "w+") as fout:
for line in fin:
for word in delete_list:
line = line.replace(word, "")
fout.write(line)
| infile = 'input_file.txt'
outfile = 'output_file.txt'
delete_list = ['Dog', 'Bird', 'Pig']
with open(infile) as fin, open(outfile, 'w+') as fout:
for line in fin:
for word in delete_list:
line = line.replace(word, '')
fout.write(line) |
answers =[
"Apple",
"Apricot",
"Avocado",
"Banana",
"Bilberry",
"Blackberry",
"Blackcurrant",
"Blueberry",
"Cherry",
"Coconut",
"Cranberry",
"Date",
"Dragonfruit",
"Durian",
"Grape",
"Grapefruit",
"Guava",
"Jackfruit",
"Jujube",
"Kiwifruit",
"Kumquat",
"Lemon",
"Lime",
"Longan",
"Lychee",
"Mango",
"Mangosteen",
"Melon",
"Cantaloupe",
"Honeydew",
"Watermelon",
"Orange",
"Mandarine",
"Tangerine",
"Papaya",
"Passionfruit",
"Peach",
"Pear",
"Plum",
"Prune",
"Pineapple",
"Pomegranate",
"Pomelo",
"Raspberry",
"Rambutan",
"Salak",
"Strawberry",
"Tamarind",
"Tomato"
] | answers = ['Apple', 'Apricot', 'Avocado', 'Banana', 'Bilberry', 'Blackberry', 'Blackcurrant', 'Blueberry', 'Cherry', 'Coconut', 'Cranberry', 'Date', 'Dragonfruit', 'Durian', 'Grape', 'Grapefruit', 'Guava', 'Jackfruit', 'Jujube', 'Kiwifruit', 'Kumquat', 'Lemon', 'Lime', 'Longan', 'Lychee', 'Mango', 'Mangosteen', 'Melon', 'Cantaloupe', 'Honeydew', 'Watermelon', 'Orange', 'Mandarine', 'Tangerine', 'Papaya', 'Passionfruit', 'Peach', 'Pear', 'Plum', 'Prune', 'Pineapple', 'Pomegranate', 'Pomelo', 'Raspberry', 'Rambutan', 'Salak', 'Strawberry', 'Tamarind', 'Tomato'] |
puzzle_input_list = []
with open("input.txt", "r") as puzzle_input:
for line in puzzle_input:
line = line.strip()
puzzle_input_list.append(line)
open_brackets = {"{", "(", "[", "<"}
bracket_mapping = {"}": "{", ")": "(", "]": "[", ">": "<",
"{": "}", "(": ")", "[": "]", "<": ">"
}
bracket_to_points = {")": 1, "]": 2, "}": 3, ">": 4}
incomplete_lines = []
for puzzle_line in puzzle_input_list:
brackets = []
valid_line = True
for bracket in puzzle_line:
if bracket in open_brackets:
brackets.append(bracket)
else:
if brackets[-1] == bracket_mapping[bracket]:
del brackets[-1]
else:
valid_line = False
if valid_line is True:
incomplete_lines.append(brackets)
scores = []
for incomplete_line in incomplete_lines:
score = 0
for character in incomplete_line[::-1]:
score *= 5
score += bracket_to_points[bracket_mapping[character]]
scores.append(score)
scores.sort()
print(scores)
print(scores[len(scores)//2])
| puzzle_input_list = []
with open('input.txt', 'r') as puzzle_input:
for line in puzzle_input:
line = line.strip()
puzzle_input_list.append(line)
open_brackets = {'{', '(', '[', '<'}
bracket_mapping = {'}': '{', ')': '(', ']': '[', '>': '<', '{': '}', '(': ')', '[': ']', '<': '>'}
bracket_to_points = {')': 1, ']': 2, '}': 3, '>': 4}
incomplete_lines = []
for puzzle_line in puzzle_input_list:
brackets = []
valid_line = True
for bracket in puzzle_line:
if bracket in open_brackets:
brackets.append(bracket)
elif brackets[-1] == bracket_mapping[bracket]:
del brackets[-1]
else:
valid_line = False
if valid_line is True:
incomplete_lines.append(brackets)
scores = []
for incomplete_line in incomplete_lines:
score = 0
for character in incomplete_line[::-1]:
score *= 5
score += bracket_to_points[bracket_mapping[character]]
scores.append(score)
scores.sort()
print(scores)
print(scores[len(scores) // 2]) |
#Kunal Gautam
#Codewars : @Kunalpod
#Problem name: Average Scores
#Problem level: 7 kyu
def average(array):
return round(sum(array)/len(array))
| def average(array):
return round(sum(array) / len(array)) |
# -*- coding: utf-8 -*-
{
'name': "Online Event Ticketing",
'category': 'Website/Website',
'summary': "Sell event tickets online",
'description': """
Sell event tickets through eCommerce app.
""",
'depends': ['website_event', 'event_sale', 'website_sale'],
'data': [
'data/event_data.xml',
'views/event_templates.xml',
'views/event_views.xml',
'security/ir.model.access.csv',
'security/website_event_sale_security.xml',
],
'auto_install': True
}
| {'name': 'Online Event Ticketing', 'category': 'Website/Website', 'summary': 'Sell event tickets online', 'description': '\nSell event tickets through eCommerce app.\n ', 'depends': ['website_event', 'event_sale', 'website_sale'], 'data': ['data/event_data.xml', 'views/event_templates.xml', 'views/event_views.xml', 'security/ir.model.access.csv', 'security/website_event_sale_security.xml'], 'auto_install': True} |
class Allergies(object):
items = {
'eggs': 1,
'peanuts': 2,
'shellfish': 4,
'strawberries': 8,
'tomatoes': 16,
'chocolate': 32,
'pollen': 64,
'cats': 128,
}
def __init__(self, score):
self._score = score
def is_allergic_to(self, item):
return bool(Allergies.items.get(item, 0) & self._score)
@property
def lst(self):
return [k for k, v in Allergies.items.items() if v & self._score]
| class Allergies(object):
items = {'eggs': 1, 'peanuts': 2, 'shellfish': 4, 'strawberries': 8, 'tomatoes': 16, 'chocolate': 32, 'pollen': 64, 'cats': 128}
def __init__(self, score):
self._score = score
def is_allergic_to(self, item):
return bool(Allergies.items.get(item, 0) & self._score)
@property
def lst(self):
return [k for (k, v) in Allergies.items.items() if v & self._score] |
def main():
# Let's create a dictionary with student keys and GPA values
student_gpa = {"john": 3.5,
"jane": 4.0,
"bob": 2.8,
"mary": 3.2}
# There are four student records in this dictionary
assert len(student_gpa) == 4
# Each student has a name key and a GPA value
assert len(student_gpa.keys()) == len(student_gpa.values())
# We can get the names in isolation
for student in student_gpa.keys():
assert len(student) > 2
# We can get the GPAs in isolation
for gpa in student_gpa.values():
assert gpa > 2.0
# We can get the GPA for a specific student
assert student_gpa["john"] == 3.5
# We can access the student and GPA simultaneously
for student, gpa in student_gpa.items():
print(f"Student {student} has a {gpa} GPA")
if __name__ == "__main__":
main()
| def main():
student_gpa = {'john': 3.5, 'jane': 4.0, 'bob': 2.8, 'mary': 3.2}
assert len(student_gpa) == 4
assert len(student_gpa.keys()) == len(student_gpa.values())
for student in student_gpa.keys():
assert len(student) > 2
for gpa in student_gpa.values():
assert gpa > 2.0
assert student_gpa['john'] == 3.5
for (student, gpa) in student_gpa.items():
print(f'Student {student} has a {gpa} GPA')
if __name__ == '__main__':
main() |
# DNA -> RNA Transcription
def transcribe(seq: str) -> str:
"""
transcribes DNA to RNA by generating
the complement sequence with T -> U replacement
"""
# rna dict
rna_dict = {'A': 'U', 'T': 'A',
'C': 'G', 'G': 'C'}
# seq to list
seq_list = list(seq)
# for each el in list get key
for i, s in enumerate(seq_list):
seq_list[i] = rna_dict[s]
# list to string
rna_seq = ''.join(seq_list)
return rna_seq
def reverse_transcribe(seq: str) -> str:
"""
transcribes DNA to RNA then reverses
the strand
"""
# Change T to U first
transc = transcribe(seq)
# return the reverse order
return transc[::-1]
| def transcribe(seq: str) -> str:
"""
transcribes DNA to RNA by generating
the complement sequence with T -> U replacement
"""
rna_dict = {'A': 'U', 'T': 'A', 'C': 'G', 'G': 'C'}
seq_list = list(seq)
for (i, s) in enumerate(seq_list):
seq_list[i] = rna_dict[s]
rna_seq = ''.join(seq_list)
return rna_seq
def reverse_transcribe(seq: str) -> str:
"""
transcribes DNA to RNA then reverses
the strand
"""
transc = transcribe(seq)
return transc[::-1] |
class VserverPeerState(basestring):
"""
peered|pending|initializing|initiated|rejected|suspended|deleted
Possible values:
<ul>
<li> "peered" - Vserver peer relationship is
established and the respective applications can use peer
relationship,
<li> "pending" - Vserver peer relationship is initiated
in the peer Cluster and local cluster needs to accept the
request,
<li> "initializing" - Communicating to the peer cluster for
initializing the peering relationship,
<li> "initiated" - Relationship initiated in local
Cluster,
<li> "rejected" - Relationship initiated and peer Cluster
rejected the same,
<li> "suspended" - Relationship got suspended, should not
initiate any data transfers ,
<li> "deleted" - Relationship got deleted on peer
Cluster
</ul>
"""
@staticmethod
def get_api_name():
return "vserver-peer-state"
| class Vserverpeerstate(basestring):
"""
peered|pending|initializing|initiated|rejected|suspended|deleted
Possible values:
<ul>
<li> "peered" - Vserver peer relationship is
established and the respective applications can use peer
relationship,
<li> "pending" - Vserver peer relationship is initiated
in the peer Cluster and local cluster needs to accept the
request,
<li> "initializing" - Communicating to the peer cluster for
initializing the peering relationship,
<li> "initiated" - Relationship initiated in local
Cluster,
<li> "rejected" - Relationship initiated and peer Cluster
rejected the same,
<li> "suspended" - Relationship got suspended, should not
initiate any data transfers ,
<li> "deleted" - Relationship got deleted on peer
Cluster
</ul>
"""
@staticmethod
def get_api_name():
return 'vserver-peer-state' |
# The MIT License (MIT)
#
# Copyright (c) 2017-2018 Niklas Rosenstein
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
def truncate(message, from_start, from_end=None):
"""
Truncate the string *message* until at max *from_start* characters and
insert an ellipsis (`...`) in place of the additional content. If *from_end*
is specified, the same will be applied to the end of the string.
"""
if len(message) <= (from_start + (from_end or 0) + 3):
return message
part1, part2 = message[:from_start], ''
if from_end and len(message) > from_end:
if len(message) - from_start < from_end:
from_end -= len(message) - from_start
part2 = message[-from_end:]
return part1 + '...' + part2
| def truncate(message, from_start, from_end=None):
"""
Truncate the string *message* until at max *from_start* characters and
insert an ellipsis (`...`) in place of the additional content. If *from_end*
is specified, the same will be applied to the end of the string.
"""
if len(message) <= from_start + (from_end or 0) + 3:
return message
(part1, part2) = (message[:from_start], '')
if from_end and len(message) > from_end:
if len(message) - from_start < from_end:
from_end -= len(message) - from_start
part2 = message[-from_end:]
return part1 + '...' + part2 |
# pylint: disable=missing-docstring
"""
# Stub file type annotations examples
## Links
[Stub files](https://mypy.readthedocs.io/en/latest/stubs.html)
"""
class MyValue:
pass
def func(_list, _my_value_cls=MyValue, **_kwargs):
pass
def func_any(_list, _my_value_cls=MyValue, **_kwargs):
pass
| """
# Stub file type annotations examples
## Links
[Stub files](https://mypy.readthedocs.io/en/latest/stubs.html)
"""
class Myvalue:
pass
def func(_list, _my_value_cls=MyValue, **_kwargs):
pass
def func_any(_list, _my_value_cls=MyValue, **_kwargs):
pass |
class Heap:
def __init__(self,comp):
self.hp = []
self.size = 0
self.comp = comp
def push(self,value):
self.hp.append(value)
self.size += 1
self._heapifyForInsertion()
def pop(self):
if self.size == 0:
return None
value = self.hp[0]
self.hp[0] = self.hp[self.size - 1]
self.hp.pop()
self.size -= 1
self._heapifyForDeletion()
return value
def _heapifyForInsertion(self):
if self.size <= 1:
return
index = self.size - 1
parent = (index - 1) // 2
while self.comp(self.hp[index],self.hp[parent]):
self.hp[index], self.hp[parent] = self.hp[parent], self.hp[index]
if parent == 0:
break
index = parent
parent = (index - 1) // 2
def _heapifyForDeletion(self):
if self.size <= 1:
return
index = 0
lChild = 2 * index + 1
rChild = 2 * index + 2
minPos = 0
if lChild > (self.size - 1):
minPos = rChild
elif rChild > (self.size - 1):
minPos = lChild
else:
minPos = lChild if self.comp(self.hp[lChild],self.hp[rChild]) else rChild
while self.comp(self.hp[minPos],self.hp[index]):
self.hp[index], self.hp[minPos] = self.hp[minPos], self.hp[index]
index = minPos
lChild = 2 * index + 1
rChild = 2 * index + 2
if lChild > (self.size - 1) and rChild > (self.size - 1):
break
elif lChild > (self.size - 1):
minPos = rChild
elif rChild > (self.size - 1):
minPos = lChild
else:
minPos = lChild if self.comp(self.hp[lChild],self.hp[rChild]) else rChild
def getHeap(self):
return self.hp
def Size(self):
return self.size
| class Heap:
def __init__(self, comp):
self.hp = []
self.size = 0
self.comp = comp
def push(self, value):
self.hp.append(value)
self.size += 1
self._heapifyForInsertion()
def pop(self):
if self.size == 0:
return None
value = self.hp[0]
self.hp[0] = self.hp[self.size - 1]
self.hp.pop()
self.size -= 1
self._heapifyForDeletion()
return value
def _heapify_for_insertion(self):
if self.size <= 1:
return
index = self.size - 1
parent = (index - 1) // 2
while self.comp(self.hp[index], self.hp[parent]):
(self.hp[index], self.hp[parent]) = (self.hp[parent], self.hp[index])
if parent == 0:
break
index = parent
parent = (index - 1) // 2
def _heapify_for_deletion(self):
if self.size <= 1:
return
index = 0
l_child = 2 * index + 1
r_child = 2 * index + 2
min_pos = 0
if lChild > self.size - 1:
min_pos = rChild
elif rChild > self.size - 1:
min_pos = lChild
else:
min_pos = lChild if self.comp(self.hp[lChild], self.hp[rChild]) else rChild
while self.comp(self.hp[minPos], self.hp[index]):
(self.hp[index], self.hp[minPos]) = (self.hp[minPos], self.hp[index])
index = minPos
l_child = 2 * index + 1
r_child = 2 * index + 2
if lChild > self.size - 1 and rChild > self.size - 1:
break
elif lChild > self.size - 1:
min_pos = rChild
elif rChild > self.size - 1:
min_pos = lChild
else:
min_pos = lChild if self.comp(self.hp[lChild], self.hp[rChild]) else rChild
def get_heap(self):
return self.hp
def size(self):
return self.size |
names = []
for i in range(10):
X =str(input(''))
names.append(X)
print(names[2])
print(names[6])
print(names[8]) | names = []
for i in range(10):
x = str(input(''))
names.append(X)
print(names[2])
print(names[6])
print(names[8]) |
def addBinary(a: str, b: str) -> str:
n_a = len(a)
n_b = len(b)
max_n = max(n_a, n_b)
a = a.rjust(max_n, "0")
b = b.rjust(max_n, "0")
jin_bit = 0
result = ""
for i in range(max_n - 1, -1, -1):
tmp_a = int(a[i])
tmp_b = int(b[i])
tmp = tmp_a + tmp_b + jin_bit
result = "{}{}".format(tmp % 2, result)
jin_bit = tmp // 2
if jin_bit != 0:
result = "{}{}".format(1, result)
return result
if __name__ == "__main__" :
a = "11"
b = "11"
c = "11".rjust(2,"0")
result = addBinary(a,b)
print(result) | def add_binary(a: str, b: str) -> str:
n_a = len(a)
n_b = len(b)
max_n = max(n_a, n_b)
a = a.rjust(max_n, '0')
b = b.rjust(max_n, '0')
jin_bit = 0
result = ''
for i in range(max_n - 1, -1, -1):
tmp_a = int(a[i])
tmp_b = int(b[i])
tmp = tmp_a + tmp_b + jin_bit
result = '{}{}'.format(tmp % 2, result)
jin_bit = tmp // 2
if jin_bit != 0:
result = '{}{}'.format(1, result)
return result
if __name__ == '__main__':
a = '11'
b = '11'
c = '11'.rjust(2, '0')
result = add_binary(a, b)
print(result) |
# Performance note: I benchmarked this code using a set instead of
# a list for the stopwords and was surprised to find that the list
# performed /better/ than the set - maybe because it's only a small
# list.
stopwords = '''
i
a
an
are
as
at
be
by
for
from
how
in
is
it
of
on
or
that
the
this
to
was
what
when
where
'''.split()
def strip_stopwords(sentence):
"Removes stopwords - also normalizes whitespace"
words = sentence.split()
sentence = []
for word in words:
if word.lower() not in stopwords:
sentence.append(word)
return u' '.join(sentence)
| stopwords = '\ni\na\nan\nare\nas\nat\nbe\nby\nfor\nfrom\nhow\nin\nis\nit\nof\non\nor\nthat\nthe\nthis\nto\nwas\nwhat\nwhen\nwhere\n'.split()
def strip_stopwords(sentence):
"""Removes stopwords - also normalizes whitespace"""
words = sentence.split()
sentence = []
for word in words:
if word.lower() not in stopwords:
sentence.append(word)
return u' '.join(sentence) |
class Credentials(object):
def __init__(self, username, password):
"""
Credentials.
:param username: Username
:param password: Password
"""
self.username = username #: Username
self.password = password #: Password
| class Credentials(object):
def __init__(self, username, password):
"""
Credentials.
:param username: Username
:param password: Password
"""
self.username = username
self.password = password |
# st2common
__all__ = ["MASKED_ATTRIBUTES_BLACKLIST", "MASKED_ATTRIBUTE_VALUE"]
# A blacklist of attributes which should be masked in the log messages by default.
# Note: If an attribute is an object or a dict, we try to recursively process it and mask the
# values.
MASKED_ATTRIBUTES_BLACKLIST = [
"password",
"auth_token",
"token",
"secret",
"credentials",
"st2_auth_token",
]
# Value with which the masked attribute values are replaced
MASKED_ATTRIBUTE_VALUE = "********"
| __all__ = ['MASKED_ATTRIBUTES_BLACKLIST', 'MASKED_ATTRIBUTE_VALUE']
masked_attributes_blacklist = ['password', 'auth_token', 'token', 'secret', 'credentials', 'st2_auth_token']
masked_attribute_value = '********' |
combination = [(True,True,True),(True,True,False),(True,False,True),(True,False,False),(False,True,True),(False,True,False),(False,False,True),(False,False,False)]
variable = {'p':0,'q':1,'r':2}
kb = ''
q = ''
priority = {'~':3,'v':1,'^':2}
def input_rules():
global kb,q
kb = (input("Enter rule : "))
q = (input("enter query : "))
def _eval(i,val1,val2):
if i=='^':
return val2 and val1
return val2 or val1
def evaluatePostfix(exp,comb):
stack = []
for i in exp:
if isOperand(i):
stack.append(comb[variable[i]])
elif i == '~':
val1 = stack.pop()
stack.append(not val1)
else:
val1 = stack.pop()
val2 = stack.pop()
stack.append(_eval(i,val1,val2))
return stack.pop()
def toPostfix(infix):
stack=[]
postfix = ''
for c in infix:
if isOperand(c):
postfix += c
else:
if isLeftParanthesis(c):
stack.append(c)
elif isRightParanthesis(c):
operator = stack.pop()
while not isLeftParanthesis(operator):
postfix += operator
operator = stack.pop()
else:
while (not isEmpty(stack)) and hasLessOrEqualPriority(c,peek(stack)):
postfix += stack.pop()
stack.append(c)
while (not isEmpty(stack)):
postfix += stack.pop()
return postfix
def entailment():
global kb,q
print('*'*10 + "Truth Table Reference" + '*'*10)
print('kb','alpha')
print('*'*10)
for comb in combination:
s = evaluatePostfix(toPostfix(kb),comb)
f = evaluatePostfix(toPostfix(q),comb)
print(s,f)
print('-'*10)
if s and not f:
return False
return True
def isOperand(c):
return c.isalpha() and c!= 'v'
def isLeftParanthesis(c):
return c=='('
def isRightParanthesis(c):
return c==')'
def isEmpty(stack):
return len(stack)==0
def peek(stack):
return stack[-1]
def hasLessOrEqualPriority(c1,c2):
try: return priority[c1]<=priority[c2]
except KeyError: return False
input_rules()
ans = entailment()
if ans:
print("Knowledge base entails query")
else:
print("Knowledge base does not entail query")
#test
#(~qv~pvr)^(~q^p)^q
# (pvq)^(~rvp)
| combination = [(True, True, True), (True, True, False), (True, False, True), (True, False, False), (False, True, True), (False, True, False), (False, False, True), (False, False, False)]
variable = {'p': 0, 'q': 1, 'r': 2}
kb = ''
q = ''
priority = {'~': 3, 'v': 1, '^': 2}
def input_rules():
global kb, q
kb = input('Enter rule : ')
q = input('enter query : ')
def _eval(i, val1, val2):
if i == '^':
return val2 and val1
return val2 or val1
def evaluate_postfix(exp, comb):
stack = []
for i in exp:
if is_operand(i):
stack.append(comb[variable[i]])
elif i == '~':
val1 = stack.pop()
stack.append(not val1)
else:
val1 = stack.pop()
val2 = stack.pop()
stack.append(_eval(i, val1, val2))
return stack.pop()
def to_postfix(infix):
stack = []
postfix = ''
for c in infix:
if is_operand(c):
postfix += c
elif is_left_paranthesis(c):
stack.append(c)
elif is_right_paranthesis(c):
operator = stack.pop()
while not is_left_paranthesis(operator):
postfix += operator
operator = stack.pop()
else:
while not is_empty(stack) and has_less_or_equal_priority(c, peek(stack)):
postfix += stack.pop()
stack.append(c)
while not is_empty(stack):
postfix += stack.pop()
return postfix
def entailment():
global kb, q
print('*' * 10 + 'Truth Table Reference' + '*' * 10)
print('kb', 'alpha')
print('*' * 10)
for comb in combination:
s = evaluate_postfix(to_postfix(kb), comb)
f = evaluate_postfix(to_postfix(q), comb)
print(s, f)
print('-' * 10)
if s and (not f):
return False
return True
def is_operand(c):
return c.isalpha() and c != 'v'
def is_left_paranthesis(c):
return c == '('
def is_right_paranthesis(c):
return c == ')'
def is_empty(stack):
return len(stack) == 0
def peek(stack):
return stack[-1]
def has_less_or_equal_priority(c1, c2):
try:
return priority[c1] <= priority[c2]
except KeyError:
return False
input_rules()
ans = entailment()
if ans:
print('Knowledge base entails query')
else:
print('Knowledge base does not entail query') |
# Numeric Pattern 7
"""
2 4 6 8 10
12 14 16 18 20
22 24 26 28 30
32 34 36 38 40
42 44 46 48 50
"""
i = 0
nums = list(range(2, 52, 2))
for _ in range(5):
j = i + 5
row = " ".join(map(str, nums[i:j]))
print(row)
i = j
| """
2 4 6 8 10
12 14 16 18 20
22 24 26 28 30
32 34 36 38 40
42 44 46 48 50
"""
i = 0
nums = list(range(2, 52, 2))
for _ in range(5):
j = i + 5
row = ' '.join(map(str, nums[i:j]))
print(row)
i = j |
{
'includes': [
'common.gypi',
],
'targets': [
{
'target_name': 'svg',
'type': 'static_library',
'include_dirs': [
'../include/config',
'../include/core',
'../include/xml',
'../include/utils',
'../include/svg',
],
'sources': [
'../include/svg/SkSVGAttribute.h',
'../include/svg/SkSVGBase.h',
'../include/svg/SkSVGPaintState.h',
'../include/svg/SkSVGParser.h',
'../include/svg/SkSVGTypes.h',
'../src/svg/SkSVGCircle.cpp',
'../src/svg/SkSVGCircle.h',
'../src/svg/SkSVGClipPath.cpp',
'../src/svg/SkSVGClipPath.h',
'../src/svg/SkSVGDefs.cpp',
'../src/svg/SkSVGDefs.h',
'../src/svg/SkSVGElements.cpp',
'../src/svg/SkSVGElements.h',
'../src/svg/SkSVGEllipse.cpp',
'../src/svg/SkSVGEllipse.h',
'../src/svg/SkSVGFeColorMatrix.cpp',
'../src/svg/SkSVGFeColorMatrix.h',
'../src/svg/SkSVGFilter.cpp',
'../src/svg/SkSVGFilter.h',
'../src/svg/SkSVGG.cpp',
'../src/svg/SkSVGG.h',
'../src/svg/SkSVGGradient.cpp',
'../src/svg/SkSVGGradient.h',
'../src/svg/SkSVGGroup.cpp',
'../src/svg/SkSVGGroup.h',
'../src/svg/SkSVGImage.cpp',
'../src/svg/SkSVGImage.h',
'../src/svg/SkSVGLine.cpp',
'../src/svg/SkSVGLine.h',
'../src/svg/SkSVGLinearGradient.cpp',
'../src/svg/SkSVGLinearGradient.h',
'../src/svg/SkSVGMask.cpp',
'../src/svg/SkSVGMask.h',
'../src/svg/SkSVGMetadata.cpp',
'../src/svg/SkSVGMetadata.h',
'../src/svg/SkSVGPaintState.cpp',
'../src/svg/SkSVGParser.cpp',
'../src/svg/SkSVGPath.cpp',
'../src/svg/SkSVGPath.h',
'../src/svg/SkSVGPolygon.cpp',
'../src/svg/SkSVGPolygon.h',
'../src/svg/SkSVGPolyline.cpp',
'../src/svg/SkSVGPolyline.h',
'../src/svg/SkSVGRadialGradient.cpp',
'../src/svg/SkSVGRadialGradient.h',
'../src/svg/SkSVGRect.cpp',
'../src/svg/SkSVGRect.h',
'../src/svg/SkSVGStop.cpp',
'../src/svg/SkSVGStop.h',
'../src/svg/SkSVGSVG.cpp',
'../src/svg/SkSVGSVG.h',
'../src/svg/SkSVGSymbol.cpp',
'../src/svg/SkSVGSymbol.h',
'../src/svg/SkSVGText.cpp',
'../src/svg/SkSVGText.h',
'../src/svg/SkSVGUse.cpp',
],
'sources!' : [
'../src/svg/SkSVG.cpp', # doesn't compile, maybe this is test code?
],
'direct_dependent_settings': {
'include_dirs': [
'../include/svg',
],
},
},
],
}
# Local Variables:
# tab-width:2
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=2 shiftwidth=2:
| {'includes': ['common.gypi'], 'targets': [{'target_name': 'svg', 'type': 'static_library', 'include_dirs': ['../include/config', '../include/core', '../include/xml', '../include/utils', '../include/svg'], 'sources': ['../include/svg/SkSVGAttribute.h', '../include/svg/SkSVGBase.h', '../include/svg/SkSVGPaintState.h', '../include/svg/SkSVGParser.h', '../include/svg/SkSVGTypes.h', '../src/svg/SkSVGCircle.cpp', '../src/svg/SkSVGCircle.h', '../src/svg/SkSVGClipPath.cpp', '../src/svg/SkSVGClipPath.h', '../src/svg/SkSVGDefs.cpp', '../src/svg/SkSVGDefs.h', '../src/svg/SkSVGElements.cpp', '../src/svg/SkSVGElements.h', '../src/svg/SkSVGEllipse.cpp', '../src/svg/SkSVGEllipse.h', '../src/svg/SkSVGFeColorMatrix.cpp', '../src/svg/SkSVGFeColorMatrix.h', '../src/svg/SkSVGFilter.cpp', '../src/svg/SkSVGFilter.h', '../src/svg/SkSVGG.cpp', '../src/svg/SkSVGG.h', '../src/svg/SkSVGGradient.cpp', '../src/svg/SkSVGGradient.h', '../src/svg/SkSVGGroup.cpp', '../src/svg/SkSVGGroup.h', '../src/svg/SkSVGImage.cpp', '../src/svg/SkSVGImage.h', '../src/svg/SkSVGLine.cpp', '../src/svg/SkSVGLine.h', '../src/svg/SkSVGLinearGradient.cpp', '../src/svg/SkSVGLinearGradient.h', '../src/svg/SkSVGMask.cpp', '../src/svg/SkSVGMask.h', '../src/svg/SkSVGMetadata.cpp', '../src/svg/SkSVGMetadata.h', '../src/svg/SkSVGPaintState.cpp', '../src/svg/SkSVGParser.cpp', '../src/svg/SkSVGPath.cpp', '../src/svg/SkSVGPath.h', '../src/svg/SkSVGPolygon.cpp', '../src/svg/SkSVGPolygon.h', '../src/svg/SkSVGPolyline.cpp', '../src/svg/SkSVGPolyline.h', '../src/svg/SkSVGRadialGradient.cpp', '../src/svg/SkSVGRadialGradient.h', '../src/svg/SkSVGRect.cpp', '../src/svg/SkSVGRect.h', '../src/svg/SkSVGStop.cpp', '../src/svg/SkSVGStop.h', '../src/svg/SkSVGSVG.cpp', '../src/svg/SkSVGSVG.h', '../src/svg/SkSVGSymbol.cpp', '../src/svg/SkSVGSymbol.h', '../src/svg/SkSVGText.cpp', '../src/svg/SkSVGText.h', '../src/svg/SkSVGUse.cpp'], 'sources!': ['../src/svg/SkSVG.cpp'], 'direct_dependent_settings': {'include_dirs': ['../include/svg']}}]} |
def SetUpGame():
global WreckContainer, ShipContainer, PlanetContainer, ArchiveContainer, playerShip, gameData, SystemContainer
GameData = gameData()
GameData.tutorial = False
PlanetContainer = [Planet(0, -1050, 1000)]
GameData.homePlanet = PlanetContainer[0]
GameData.tasks = []
PlanetContainer[0].baseAt = 0
ShipContainer = []
ShipContainer.append(enemyShip(200, 200, 0, 0, 2, (0, -1050, 1500)))
WreckContainer = []
SystemContainer = [(0, 0, "Home System")]
for newPlanetX in range(-1, 2):
for newPlanetY in range(-1, 2):
if newPlanetX == 0 and newPlanetY == 0:
continue
PlanetContainer.append(
Planet(
newPlanetX * 20000 + random.randint(-8000, 8000),
newPlanetY * 18000 + random.randint(-6000, 6000),
random.randint(250, 1500),
)
)
PlanetContainer[-1].enemyAt = random.choice(
(None, random.randint(0, 360)))
PlanetContainer[0].playerLanded = "base"
ArchiveContainer = []
playerShip.X = 0
playerShip.Y = 25
playerShip.angle = 0
playerShip.faceAngle = 180
playerShip.speed = 0
playerShip.hull = 592
playerShip.toX = 0
playerShip.toY = 0
playerView.X = 0
playerView.Y = 0
playerView.angle = 0
playerView.zoomfactor = 1
gameData.basesBuilt = 0
playerShip.oil = 1000
star.params = (
random.random(),
random.random(),
random.random(),
random.random(),
random.random(),
)
checkProgress("game started")
| def set_up_game():
global WreckContainer, ShipContainer, PlanetContainer, ArchiveContainer, playerShip, gameData, SystemContainer
game_data = game_data()
GameData.tutorial = False
planet_container = [planet(0, -1050, 1000)]
GameData.homePlanet = PlanetContainer[0]
GameData.tasks = []
PlanetContainer[0].baseAt = 0
ship_container = []
ShipContainer.append(enemy_ship(200, 200, 0, 0, 2, (0, -1050, 1500)))
wreck_container = []
system_container = [(0, 0, 'Home System')]
for new_planet_x in range(-1, 2):
for new_planet_y in range(-1, 2):
if newPlanetX == 0 and newPlanetY == 0:
continue
PlanetContainer.append(planet(newPlanetX * 20000 + random.randint(-8000, 8000), newPlanetY * 18000 + random.randint(-6000, 6000), random.randint(250, 1500)))
PlanetContainer[-1].enemyAt = random.choice((None, random.randint(0, 360)))
PlanetContainer[0].playerLanded = 'base'
archive_container = []
playerShip.X = 0
playerShip.Y = 25
playerShip.angle = 0
playerShip.faceAngle = 180
playerShip.speed = 0
playerShip.hull = 592
playerShip.toX = 0
playerShip.toY = 0
playerView.X = 0
playerView.Y = 0
playerView.angle = 0
playerView.zoomfactor = 1
gameData.basesBuilt = 0
playerShip.oil = 1000
star.params = (random.random(), random.random(), random.random(), random.random(), random.random())
check_progress('game started') |
class SearchGoogleNewsError(Exception):
pass
class SearchGoogleNewsDataSourceNotFound(Exception):
pass
class SearchGoogleNewsParseError(Exception):
pass
| class Searchgooglenewserror(Exception):
pass
class Searchgooglenewsdatasourcenotfound(Exception):
pass
class Searchgooglenewsparseerror(Exception):
pass |
#!/usr/bin/env python3
# Character Picture Grid
grid = [
[".", ".", ".", ".", ".", "."],
[".", "O", "O", ".", ".", "."],
["O", "O", "O", "O", ".", "."],
["O", "O", "O", "O", "O", "."],
[".", "O", "O", "O", "O", "O"],
["O", "O", "O", "O", "O", "."],
["O", "O", "O", "O", ".", "."],
[".", "O", "O", ".", ".", "."],
[".", ".", ".", ".", ".", "."],
]
rows = len(grid)
columns = len(grid[0])
for x in range(columns):
for y in range(rows):
print(grid[y][x], end="")
print()
| grid = [['.', '.', '.', '.', '.', '.'], ['.', 'O', 'O', '.', '.', '.'], ['O', 'O', 'O', 'O', '.', '.'], ['O', 'O', 'O', 'O', 'O', '.'], ['.', 'O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O', '.'], ['O', 'O', 'O', 'O', '.', '.'], ['.', 'O', 'O', '.', '.', '.'], ['.', '.', '.', '.', '.', '.']]
rows = len(grid)
columns = len(grid[0])
for x in range(columns):
for y in range(rows):
print(grid[y][x], end='')
print() |
#
# PySNMP MIB module HH3C-VM-MAN-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HH3C-VM-MAN-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:30:16 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "OctetString", "Integer")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
SingleValueConstraint, ValueRangeConstraint, ConstraintsIntersection, ConstraintsUnion, ValueSizeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ValueRangeConstraint", "ConstraintsIntersection", "ConstraintsUnion", "ValueSizeConstraint")
entPhysicalAssetID, = mibBuilder.importSymbols("ENTITY-MIB", "entPhysicalAssetID")
hh3cSurveillanceMIB, = mibBuilder.importSymbols("HH3C-OID-MIB", "hh3cSurveillanceMIB")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
MibScalar, MibTable, MibTableRow, MibTableColumn, Counter64, TimeTicks, ModuleIdentity, NotificationType, ObjectIdentity, IpAddress, MibIdentifier, Integer32, iso, Bits, Gauge32, Counter32, Unsigned32 = mibBuilder.importSymbols("SNMPv2-SMI", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Counter64", "TimeTicks", "ModuleIdentity", "NotificationType", "ObjectIdentity", "IpAddress", "MibIdentifier", "Integer32", "iso", "Bits", "Gauge32", "Counter32", "Unsigned32")
DateAndTime, TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "DateAndTime", "TextualConvention", "DisplayString")
hh3cVMMan = ModuleIdentity((1, 3, 6, 1, 4, 1, 25506, 9, 1))
if mibBuilder.loadTexts: hh3cVMMan.setLastUpdated('200704130000Z')
if mibBuilder.loadTexts: hh3cVMMan.setOrganization('Hangzhou H3C Tech. Co., Ltd.')
if mibBuilder.loadTexts: hh3cVMMan.setContactInfo('Platform Team Hangzhou H3C Tech. Co., Ltd. Hai-Dian District Beijing P.R. China http://www.h3c.com Zip:100085 ')
if mibBuilder.loadTexts: hh3cVMMan.setDescription('VM is one of surveillance features, implementing user authentication, configuration management, network management and control signalling forwarding. This MIB contains objects to manage the VM feature.')
hh3cVMManMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 25506, 9, 1, 1))
hh3cVMCapabilitySet = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 1, 1), Bits().clone(namedValues=NamedValues(("cms", 0), ("css", 1), ("dm", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cVMCapabilitySet.setStatus('current')
if mibBuilder.loadTexts: hh3cVMCapabilitySet.setDescription('Components included in the VM feature represented by bit fields. VM feature includes three componets: CMS(Central Management Server), CSS(Control Signalling Server) and DM(Data Managment). A bit set to 1 indicates the corresponding component of this bit is included otherwise indicates the corresponding component of this bit is not included. VM can include one or more components at one time. ')
hh3cVMStat = MibIdentifier((1, 3, 6, 1, 4, 1, 25506, 9, 1, 1, 2))
hh3cVMStatTotalConnEstablishRequests = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 1, 2, 1), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cVMStatTotalConnEstablishRequests.setStatus('current')
if mibBuilder.loadTexts: hh3cVMStatTotalConnEstablishRequests.setDescription('The total number of establishment requests for video connection.')
hh3cVMStatSuccConnEstablishRequests = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 1, 2, 2), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cVMStatSuccConnEstablishRequests.setStatus('current')
if mibBuilder.loadTexts: hh3cVMStatSuccConnEstablishRequests.setDescription('The total number of successful establishment requests for video connection.')
hh3cVMStatFailConnEstablishRequests = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 1, 2, 3), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cVMStatFailConnEstablishRequests.setStatus('current')
if mibBuilder.loadTexts: hh3cVMStatFailConnEstablishRequests.setDescription('The total number of unsuccessful establishment requests for video connection.')
hh3cVMStatTotalConnReleaseRequests = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 1, 2, 4), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cVMStatTotalConnReleaseRequests.setStatus('current')
if mibBuilder.loadTexts: hh3cVMStatTotalConnReleaseRequests.setDescription('The total number of release requests for video connection.')
hh3cVMStatSuccConnReleaseRequests = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 1, 2, 5), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cVMStatSuccConnReleaseRequests.setStatus('current')
if mibBuilder.loadTexts: hh3cVMStatSuccConnReleaseRequests.setDescription('The total number of successful release requests for video connection.')
hh3cVMStatFailConnReleaseRequests = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 1, 2, 6), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cVMStatFailConnReleaseRequests.setStatus('current')
if mibBuilder.loadTexts: hh3cVMStatFailConnReleaseRequests.setDescription('The total number of unsuccessful release requests for video connection.')
hh3cVMStatExceptionTerminationConn = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 1, 2, 7), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cVMStatExceptionTerminationConn.setStatus('current')
if mibBuilder.loadTexts: hh3cVMStatExceptionTerminationConn.setDescription('The total number of exceptional termination for video connection.')
hh3cVMManMIBTrap = MibIdentifier((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2))
hh3cVMManTrapPrex = MibIdentifier((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0))
hh3cVMManDeviceOnlineTrap = NotificationType((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0, 1)).setObjects(("ENTITY-MIB", "entPhysicalAssetID"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevIP"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevName"))
if mibBuilder.loadTexts: hh3cVMManDeviceOnlineTrap.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManDeviceOnlineTrap.setDescription('Send a trap about the device having been registered to VM.')
hh3cVMManDeviceOfflineTrap = NotificationType((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0, 2)).setObjects(("ENTITY-MIB", "entPhysicalAssetID"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevIP"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevName"))
if mibBuilder.loadTexts: hh3cVMManDeviceOfflineTrap.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManDeviceOfflineTrap.setDescription('Send a trap about the device having been unregistered to VM.')
hh3cVMManForwardDeviceExternalSemaphoreTrap = NotificationType((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0, 3)).setObjects(("ENTITY-MIB", "entPhysicalAssetID"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevIP"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevName"), ("HH3C-VM-MAN-MIB", "hh3cVMManPUExternalInputAlarmChannelID"))
if mibBuilder.loadTexts: hh3cVMManForwardDeviceExternalSemaphoreTrap.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManForwardDeviceExternalSemaphoreTrap.setDescription('Forward a trap about external semaphore alarm, which is created by the third party device.')
hh3cVMManForwardDeviceVideoLossTrap = NotificationType((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0, 4)).setObjects(("ENTITY-MIB", "entPhysicalAssetID"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevIP"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevName"), ("HH3C-VM-MAN-MIB", "hh3cVMManPUECVideoChannelName"))
if mibBuilder.loadTexts: hh3cVMManForwardDeviceVideoLossTrap.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManForwardDeviceVideoLossTrap.setDescription('Forward a trap about video loss, which is created by the third party device.')
hh3cVMManForwardDeviceVideoRecoverTrap = NotificationType((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0, 5)).setObjects(("ENTITY-MIB", "entPhysicalAssetID"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevIP"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevName"), ("HH3C-VM-MAN-MIB", "hh3cVMManPUECVideoChannelName"))
if mibBuilder.loadTexts: hh3cVMManForwardDeviceVideoRecoverTrap.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManForwardDeviceVideoRecoverTrap.setDescription('Forward a trap about video recovery after loss, which is created by the third party device.')
hh3cVMManForwardDeviceMotionDetectTrap = NotificationType((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0, 6)).setObjects(("ENTITY-MIB", "entPhysicalAssetID"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevIP"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevName"), ("HH3C-VM-MAN-MIB", "hh3cVMManPUECVideoChannelName"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegionCoordinateX1"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegionCoordinateY1"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegionCoordinateX2"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegionCoordinateY2"))
if mibBuilder.loadTexts: hh3cVMManForwardDeviceMotionDetectTrap.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManForwardDeviceMotionDetectTrap.setDescription('Forward a trap about motion detection, which is created by the third party device.')
hh3cVMManForwardDeviceCoverTrap = NotificationType((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0, 7)).setObjects(("ENTITY-MIB", "entPhysicalAssetID"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevIP"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevName"), ("HH3C-VM-MAN-MIB", "hh3cVMManPUECVideoChannelName"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegionCoordinateX1"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegionCoordinateY1"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegionCoordinateX2"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegionCoordinateY2"))
if mibBuilder.loadTexts: hh3cVMManForwardDeviceCoverTrap.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManForwardDeviceCoverTrap.setDescription('Forward a trap about video cover, which is created by the third party device.')
hh3cVMManForwardDeviceCpuUsageThresholdTrap = NotificationType((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0, 8)).setObjects(("ENTITY-MIB", "entPhysicalAssetID"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevIP"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevName"), ("HH3C-VM-MAN-MIB", "hh3cVMManCpuUsage"), ("HH3C-VM-MAN-MIB", "hh3cVMManCpuUsageThreshold"))
if mibBuilder.loadTexts: hh3cVMManForwardDeviceCpuUsageThresholdTrap.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManForwardDeviceCpuUsageThresholdTrap.setDescription('Forward a trap about cpu usage exceeding its threshold, which is created by the third party device.')
hh3cVMManForwardDeviceMemUsageThresholdTrap = NotificationType((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0, 9)).setObjects(("ENTITY-MIB", "entPhysicalAssetID"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevIP"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevName"), ("HH3C-VM-MAN-MIB", "hh3cVMManMemUsage"), ("HH3C-VM-MAN-MIB", "hh3cVMManMemUsageThreshold"))
if mibBuilder.loadTexts: hh3cVMManForwardDeviceMemUsageThresholdTrap.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManForwardDeviceMemUsageThresholdTrap.setDescription('Forward a trap about memory usage exceeding its threshold, which is created by the third party device.')
hh3cVMManForwardDeviceHardDiskUsageThresholdTrap = NotificationType((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0, 10)).setObjects(("ENTITY-MIB", "entPhysicalAssetID"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevIP"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevName"), ("HH3C-VM-MAN-MIB", "hh3cVMManHardDiskUsage"), ("HH3C-VM-MAN-MIB", "hh3cVMManHardDiskUsageThreshold"))
if mibBuilder.loadTexts: hh3cVMManForwardDeviceHardDiskUsageThresholdTrap.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManForwardDeviceHardDiskUsageThresholdTrap.setDescription('Forward a trap about harddisk usage exceeding its threshold, which is created by the third party device.')
hh3cVMManForwardDeviceTemperatureThresholdTrap = NotificationType((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0, 11)).setObjects(("ENTITY-MIB", "entPhysicalAssetID"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevIP"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevName"), ("HH3C-VM-MAN-MIB", "hh3cVMManTemperature"), ("HH3C-VM-MAN-MIB", "hh3cVMManTemperatureThreshold"))
if mibBuilder.loadTexts: hh3cVMManForwardDeviceTemperatureThresholdTrap.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManForwardDeviceTemperatureThresholdTrap.setDescription('Forward a trap about temperature exceeding its threshold, which is created by the third party device.')
hh3cVMManForwardDeviceStartKinescopeTrap = NotificationType((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0, 12)).setObjects(("ENTITY-MIB", "entPhysicalAssetID"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevIP"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevName"), ("HH3C-VM-MAN-MIB", "hh3cVMManPUECVideoChannelName"))
if mibBuilder.loadTexts: hh3cVMManForwardDeviceStartKinescopeTrap.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManForwardDeviceStartKinescopeTrap.setDescription('Forward a trap about starting kinescope, which is created by the third party device.')
hh3cVMManForwardDeviceStopKinescopeTrap = NotificationType((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0, 13)).setObjects(("ENTITY-MIB", "entPhysicalAssetID"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevIP"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevName"), ("HH3C-VM-MAN-MIB", "hh3cVMManPUECVideoChannelName"))
if mibBuilder.loadTexts: hh3cVMManForwardDeviceStopKinescopeTrap.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManForwardDeviceStopKinescopeTrap.setDescription('Forward a trap about stopping kinescope, which is created by the third party device.')
hh3cVMManClientReportTrap = NotificationType((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0, 14)).setObjects(("ENTITY-MIB", "entPhysicalAssetID"), ("HH3C-VM-MAN-MIB", "hh3cVMManClientIP"), ("HH3C-VM-MAN-MIB", "hh3cVMManUserName"), ("HH3C-VM-MAN-MIB", "hh3cVMManReportContent"))
if mibBuilder.loadTexts: hh3cVMManClientReportTrap.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManClientReportTrap.setDescription('Send a trap about the fault which is reported by clients.')
hh3cVMManClientRealtimeSurveillanceNoVideoTrap = NotificationType((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0, 15)).setObjects(("ENTITY-MIB", "entPhysicalAssetID"), ("HH3C-VM-MAN-MIB", "hh3cVMManClientIP"), ("HH3C-VM-MAN-MIB", "hh3cVMManUserName"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevIP"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevName"), ("HH3C-VM-MAN-MIB", "hh3cVMManPUECVideoChannelName"))
if mibBuilder.loadTexts: hh3cVMManClientRealtimeSurveillanceNoVideoTrap.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManClientRealtimeSurveillanceNoVideoTrap.setDescription("Send a trap about no realtime surveillance video stream which is reported by clients. hh3cVMManRegDevIP, entPhysicalAssetID, hh3cVMManRegDevName and hh3cVMManPUECVideoChannelName describe an EC's relative information. ")
hh3cVMManClientVODNoVideoTrap = NotificationType((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0, 16)).setObjects(("ENTITY-MIB", "entPhysicalAssetID"), ("HH3C-VM-MAN-MIB", "hh3cVMManClientIP"), ("HH3C-VM-MAN-MIB", "hh3cVMManUserName"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevIP"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevName"), ("HH3C-VM-MAN-MIB", "hh3cVMManPUECVideoChannelName"), ("HH3C-VM-MAN-MIB", "hh3cVMManClientVODStart"), ("HH3C-VM-MAN-MIB", "hh3cVMManClientVODEnd"), ("HH3C-VM-MAN-MIB", "hh3cVMManIPSANDevIP"))
if mibBuilder.loadTexts: hh3cVMManClientVODNoVideoTrap.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManClientVODNoVideoTrap.setDescription("Send a trap about no VOD video stream which is reported by clients. hh3cVMManRegDevIP, entPhysicalAssetID, hh3cVMManRegDevName and hh3cVMManPUECVideoChannelName describe an EC's relative information.")
hh3cVMManClientRealtimeSurveillanceVideoStreamDiscontinuityTrap = NotificationType((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0, 17)).setObjects(("ENTITY-MIB", "entPhysicalAssetID"), ("HH3C-VM-MAN-MIB", "hh3cVMManClientIP"), ("HH3C-VM-MAN-MIB", "hh3cVMManUserName"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevIP"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevName"), ("HH3C-VM-MAN-MIB", "hh3cVMManPUECVideoChannelName"), ("HH3C-VM-MAN-MIB", "hh3cVMManClientVideoStreamDiscontinuityInterval"), ("HH3C-VM-MAN-MIB", "hh3cVMManClientVideoStreamDiscontinuityIntervalThreshold"), ("HH3C-VM-MAN-MIB", "hh3cVMManClientStatPeriod"))
if mibBuilder.loadTexts: hh3cVMManClientRealtimeSurveillanceVideoStreamDiscontinuityTrap.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManClientRealtimeSurveillanceVideoStreamDiscontinuityTrap.setDescription("Send a trap about the realtime surveillance video stream discontinuity which is reported by clients. entPhysicalAssetID, hh3cVMManRegDevIP, hh3cVMManRegDevName and hh3cVMManPUECVideoChannelName describe an EC's relative information.")
hh3cVMManClientVODVideoStreamDiscontinuityTrap = NotificationType((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0, 18)).setObjects(("ENTITY-MIB", "entPhysicalAssetID"), ("HH3C-VM-MAN-MIB", "hh3cVMManClientIP"), ("HH3C-VM-MAN-MIB", "hh3cVMManUserName"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevIP"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevName"), ("HH3C-VM-MAN-MIB", "hh3cVMManPUECVideoChannelName"), ("HH3C-VM-MAN-MIB", "hh3cVMManClientVODStart"), ("HH3C-VM-MAN-MIB", "hh3cVMManClientVODEnd"), ("HH3C-VM-MAN-MIB", "hh3cVMManIPSANDevIP"), ("HH3C-VM-MAN-MIB", "hh3cVMManClientVideoStreamDiscontinuityInterval"), ("HH3C-VM-MAN-MIB", "hh3cVMManClientVideoStreamDiscontinuityIntervalThreshold"), ("HH3C-VM-MAN-MIB", "hh3cVMManClientStatPeriod"))
if mibBuilder.loadTexts: hh3cVMManClientVODVideoStreamDiscontinuityTrap.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManClientVODVideoStreamDiscontinuityTrap.setDescription("Send a trap about the VOD video stream discontinuity which is reported by clients. hh3cVMManRegDevIP, entPhysicalAssetID, hh3cVMManRegDevName and hh3cVMManPUECVideoChannelName describe an EC's relative information.")
hh3cVMManClientCtlConnExceptionTerminationTrap = NotificationType((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0, 19)).setObjects(("ENTITY-MIB", "entPhysicalAssetID"), ("HH3C-VM-MAN-MIB", "hh3cVMManClientIP"), ("HH3C-VM-MAN-MIB", "hh3cVMManUserName"))
if mibBuilder.loadTexts: hh3cVMManClientCtlConnExceptionTerminationTrap.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManClientCtlConnExceptionTerminationTrap.setDescription('Send a trap about the exceptional termination for control connection. ')
hh3cVMManClientFrequencyLoginFailTrap = NotificationType((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0, 20)).setObjects(("ENTITY-MIB", "entPhysicalAssetID"), ("HH3C-VM-MAN-MIB", "hh3cVMManClientIP"), ("HH3C-VM-MAN-MIB", "hh3cVMManUserName"), ("HH3C-VM-MAN-MIB", "hh3cVMManClientLoginFailNum"), ("HH3C-VM-MAN-MIB", "hh3cVMManClientLoginFailNumThreshold"), ("HH3C-VM-MAN-MIB", "hh3cVMManClientStatPeriod"))
if mibBuilder.loadTexts: hh3cVMManClientFrequencyLoginFailTrap.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManClientFrequencyLoginFailTrap.setDescription('Send a trap about the frequency of client login failure.')
hh3cVMManClientFrequencyVODFailTrap = NotificationType((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0, 21)).setObjects(("ENTITY-MIB", "entPhysicalAssetID"), ("HH3C-VM-MAN-MIB", "hh3cVMManClientIP"), ("HH3C-VM-MAN-MIB", "hh3cVMManUserName"), ("HH3C-VM-MAN-MIB", "hh3cVMManClientVODFailNum"), ("HH3C-VM-MAN-MIB", "hh3cVMManClientVODFailNumThreshold"), ("HH3C-VM-MAN-MIB", "hh3cVMManClientStatPeriod"))
if mibBuilder.loadTexts: hh3cVMManClientFrequencyVODFailTrap.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManClientFrequencyVODFailTrap.setDescription('Send a trap about the frequency of client VOD failure.')
hh3cVMManDMECDisobeyStorageScheduleTrap = NotificationType((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0, 22)).setObjects(("ENTITY-MIB", "entPhysicalAssetID"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevIP"), ("HH3C-VM-MAN-MIB", "hh3cVMManPUECVideoChannelName"))
if mibBuilder.loadTexts: hh3cVMManDMECDisobeyStorageScheduleTrap.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManDMECDisobeyStorageScheduleTrap.setDescription('Send a trap about EC disobeying storage schedule created by DM.')
hh3cVMManDMECDisobeyStorageScheduleRecoverTrap = NotificationType((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0, 23)).setObjects(("ENTITY-MIB", "entPhysicalAssetID"), ("HH3C-VM-MAN-MIB", "hh3cVMManRegDevIP"), ("HH3C-VM-MAN-MIB", "hh3cVMManPUECVideoChannelName"))
if mibBuilder.loadTexts: hh3cVMManDMECDisobeyStorageScheduleRecoverTrap.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManDMECDisobeyStorageScheduleRecoverTrap.setDescription('Send a trap about recovery after EC disobeying storage schedule created by DM.')
hh3cVMManTrapObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1))
hh3cVMManIPSANDevIP = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 1), IpAddress()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cVMManIPSANDevIP.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManIPSANDevIP.setDescription('IP address of IPSAN Device which can store video data.')
hh3cVMManRegDevIP = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 2), IpAddress()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cVMManRegDevIP.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManRegDevIP.setDescription('IP address of devices which can registered or unregistered to VM.')
hh3cVMManRegDevName = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 64))).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cVMManRegDevName.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManRegDevName.setDescription('Name of devices which can registered or unregistered to VM.')
hh3cVMManRegionCoordinateX1 = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 4), Unsigned32()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cVMManRegionCoordinateX1.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManRegionCoordinateX1.setDescription('The horizontal coordinate of top left point of the motion detection region.')
hh3cVMManRegionCoordinateY1 = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 5), Unsigned32()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cVMManRegionCoordinateY1.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManRegionCoordinateY1.setDescription('The vertical coordinate of top left point of the motion detection region.')
hh3cVMManRegionCoordinateX2 = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 6), Unsigned32()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cVMManRegionCoordinateX2.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManRegionCoordinateX2.setDescription('The horizontal coordinate of botton right point of the motion detection region.')
hh3cVMManRegionCoordinateY2 = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 7), Unsigned32()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cVMManRegionCoordinateY2.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManRegionCoordinateY2.setDescription('The horizontal coordinate of botton right point of the motion detection region.')
hh3cVMManCpuUsage = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 8), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(0, 100))).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cVMManCpuUsage.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManCpuUsage.setDescription('The CPU usage for this entity. Generally, the CPU usage will caculate the overall CPU usage on the entity, and it is not sensible with the number of CPU on the entity. ')
hh3cVMManCpuUsageThreshold = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 9), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(0, 100))).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cVMManCpuUsageThreshold.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManCpuUsageThreshold.setDescription('The threshold for the CPU usage. When the CPU usage exceeds the threshold, a notification will be sent.')
hh3cVMManMemUsage = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 10), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(0, 100))).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cVMManMemUsage.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManMemUsage.setDescription('The memory usage for the entity. This object indicates what percent of memory are used. ')
hh3cVMManMemUsageThreshold = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 11), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(0, 100))).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cVMManMemUsageThreshold.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManMemUsageThreshold.setDescription('The threshold for the Memory usage. When the memory usage exceeds the threshold, a notification will be sent. ')
hh3cVMManHardDiskUsage = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 12), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(0, 100))).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cVMManHardDiskUsage.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManHardDiskUsage.setDescription('The hard disk usage for the entity. This object indicates what percent of hard disk are used. ')
hh3cVMManHardDiskUsageThreshold = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 13), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(0, 100))).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cVMManHardDiskUsageThreshold.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManHardDiskUsageThreshold.setDescription('The threshold for the hard disk usage. When the hard disk usage exceeds the threshold, a notification will be sent. ')
hh3cVMManTemperature = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 14), Integer32()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cVMManTemperature.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManTemperature.setDescription('The temperature for the entity. ')
hh3cVMManTemperatureThreshold = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 15), Integer32()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cVMManTemperatureThreshold.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManTemperatureThreshold.setDescription('The threshold for the temperature. When the temperature exceeds the threshold, a notification will be sent. ')
hh3cVMManClientIP = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 16), IpAddress()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cVMManClientIP.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManClientIP.setDescription('The client device IP address.')
hh3cVMManUserName = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 17), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 32))).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cVMManUserName.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManUserName.setDescription('The client user name.')
hh3cVMManReportContent = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 18), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cVMManReportContent.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManReportContent.setDescription('The details of the fault which reported by clients')
hh3cVMManClientVideoStreamDiscontinuityInterval = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 19), Unsigned32()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cVMManClientVideoStreamDiscontinuityInterval.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManClientVideoStreamDiscontinuityInterval.setDescription('Video stream discontinuity interval. ')
hh3cVMManClientVideoStreamDiscontinuityIntervalThreshold = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 20), Unsigned32()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cVMManClientVideoStreamDiscontinuityIntervalThreshold.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManClientVideoStreamDiscontinuityIntervalThreshold.setDescription('The threshold for the video stream discontinuity interval. When the discontinuity interval exceeds the threshold, a notification will be sent. ')
hh3cVMManClientStatPeriod = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 21), Unsigned32()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cVMManClientStatPeriod.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManClientStatPeriod.setDescription('The client statistic period. ')
hh3cVMManClientLoginFailNum = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 22), Unsigned32()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cVMManClientLoginFailNum.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManClientLoginFailNum.setDescription('The total number of client login failure in last statistic period which is defined by hh3cVMManClientStatPeriod entity.')
hh3cVMManClientLoginFailNumThreshold = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 23), Unsigned32()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cVMManClientLoginFailNumThreshold.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManClientLoginFailNumThreshold.setDescription('The threshold for the total number of client login failure in last statistic period. When the number exceeds the threshold, a notification will be sent. ')
hh3cVMManClientVODFailNum = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 24), Unsigned32()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cVMManClientVODFailNum.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManClientVODFailNum.setDescription('The total number of client VOD failure in last statistic period which is defined by hh3cVMManClientStatPeriod entity.')
hh3cVMManClientVODFailNumThreshold = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 25), Unsigned32()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cVMManClientVODFailNumThreshold.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManClientVODFailNumThreshold.setDescription('The threshold for the total number of client VOD failure in last statistic period. When the number exceeds the threshold, a notification will be sent. ')
hh3cVMManClientVODStart = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 26), DateAndTime()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cVMManClientVODStart.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManClientVODStart.setDescription('The start time for VOD.')
hh3cVMManClientVODEnd = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 27), DateAndTime()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cVMManClientVODEnd.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManClientVODEnd.setDescription('The end time for VOD.')
hh3cVMManPUExternalInputAlarmChannelID = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 28), Unsigned32()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cVMManPUExternalInputAlarmChannelID.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManPUExternalInputAlarmChannelID.setDescription('The ID of the external input alarm channel.')
hh3cVMManPUECVideoChannelName = MibScalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 29), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 32))).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: hh3cVMManPUECVideoChannelName.setStatus('current')
if mibBuilder.loadTexts: hh3cVMManPUECVideoChannelName.setDescription('The name of the video channel. It is suggested that the name includes the channel ID information.')
mibBuilder.exportSymbols("HH3C-VM-MAN-MIB", hh3cVMManPUExternalInputAlarmChannelID=hh3cVMManPUExternalInputAlarmChannelID, hh3cVMManClientVODEnd=hh3cVMManClientVODEnd, hh3cVMManDMECDisobeyStorageScheduleRecoverTrap=hh3cVMManDMECDisobeyStorageScheduleRecoverTrap, hh3cVMManDeviceOfflineTrap=hh3cVMManDeviceOfflineTrap, hh3cVMManIPSANDevIP=hh3cVMManIPSANDevIP, hh3cVMManTemperatureThreshold=hh3cVMManTemperatureThreshold, hh3cVMManClientStatPeriod=hh3cVMManClientStatPeriod, hh3cVMManForwardDeviceCpuUsageThresholdTrap=hh3cVMManForwardDeviceCpuUsageThresholdTrap, hh3cVMManClientRealtimeSurveillanceNoVideoTrap=hh3cVMManClientRealtimeSurveillanceNoVideoTrap, hh3cVMManClientVODFailNumThreshold=hh3cVMManClientVODFailNumThreshold, hh3cVMMan=hh3cVMMan, hh3cVMStatFailConnEstablishRequests=hh3cVMStatFailConnEstablishRequests, hh3cVMStatTotalConnEstablishRequests=hh3cVMStatTotalConnEstablishRequests, hh3cVMStat=hh3cVMStat, hh3cVMStatSuccConnEstablishRequests=hh3cVMStatSuccConnEstablishRequests, hh3cVMStatExceptionTerminationConn=hh3cVMStatExceptionTerminationConn, hh3cVMManForwardDeviceExternalSemaphoreTrap=hh3cVMManForwardDeviceExternalSemaphoreTrap, hh3cVMManForwardDeviceStopKinescopeTrap=hh3cVMManForwardDeviceStopKinescopeTrap, hh3cVMManClientRealtimeSurveillanceVideoStreamDiscontinuityTrap=hh3cVMManClientRealtimeSurveillanceVideoStreamDiscontinuityTrap, hh3cVMManCpuUsageThreshold=hh3cVMManCpuUsageThreshold, hh3cVMManUserName=hh3cVMManUserName, hh3cVMManClientFrequencyLoginFailTrap=hh3cVMManClientFrequencyLoginFailTrap, hh3cVMManReportContent=hh3cVMManReportContent, hh3cVMManPUECVideoChannelName=hh3cVMManPUECVideoChannelName, hh3cVMStatFailConnReleaseRequests=hh3cVMStatFailConnReleaseRequests, hh3cVMManForwardDeviceMotionDetectTrap=hh3cVMManForwardDeviceMotionDetectTrap, hh3cVMManForwardDeviceHardDiskUsageThresholdTrap=hh3cVMManForwardDeviceHardDiskUsageThresholdTrap, hh3cVMManTrapPrex=hh3cVMManTrapPrex, hh3cVMStatTotalConnReleaseRequests=hh3cVMStatTotalConnReleaseRequests, hh3cVMManForwardDeviceStartKinescopeTrap=hh3cVMManForwardDeviceStartKinescopeTrap, hh3cVMManClientVODNoVideoTrap=hh3cVMManClientVODNoVideoTrap, hh3cVMManRegionCoordinateY2=hh3cVMManRegionCoordinateY2, hh3cVMManCpuUsage=hh3cVMManCpuUsage, hh3cVMManClientVideoStreamDiscontinuityIntervalThreshold=hh3cVMManClientVideoStreamDiscontinuityIntervalThreshold, hh3cVMManClientVODStart=hh3cVMManClientVODStart, hh3cVMManMIBTrap=hh3cVMManMIBTrap, hh3cVMCapabilitySet=hh3cVMCapabilitySet, hh3cVMManRegionCoordinateY1=hh3cVMManRegionCoordinateY1, hh3cVMManMIBObjects=hh3cVMManMIBObjects, hh3cVMManForwardDeviceTemperatureThresholdTrap=hh3cVMManForwardDeviceTemperatureThresholdTrap, hh3cVMManClientCtlConnExceptionTerminationTrap=hh3cVMManClientCtlConnExceptionTerminationTrap, hh3cVMManForwardDeviceMemUsageThresholdTrap=hh3cVMManForwardDeviceMemUsageThresholdTrap, hh3cVMManClientFrequencyVODFailTrap=hh3cVMManClientFrequencyVODFailTrap, hh3cVMManDMECDisobeyStorageScheduleTrap=hh3cVMManDMECDisobeyStorageScheduleTrap, hh3cVMManRegDevIP=hh3cVMManRegDevIP, hh3cVMManMemUsage=hh3cVMManMemUsage, hh3cVMManTemperature=hh3cVMManTemperature, hh3cVMManClientLoginFailNumThreshold=hh3cVMManClientLoginFailNumThreshold, hh3cVMManClientVODFailNum=hh3cVMManClientVODFailNum, hh3cVMManClientReportTrap=hh3cVMManClientReportTrap, hh3cVMManHardDiskUsage=hh3cVMManHardDiskUsage, hh3cVMManDeviceOnlineTrap=hh3cVMManDeviceOnlineTrap, hh3cVMManForwardDeviceVideoLossTrap=hh3cVMManForwardDeviceVideoLossTrap, hh3cVMManClientLoginFailNum=hh3cVMManClientLoginFailNum, hh3cVMManRegionCoordinateX1=hh3cVMManRegionCoordinateX1, hh3cVMManRegDevName=hh3cVMManRegDevName, hh3cVMManClientIP=hh3cVMManClientIP, PYSNMP_MODULE_ID=hh3cVMMan, hh3cVMManClientVODVideoStreamDiscontinuityTrap=hh3cVMManClientVODVideoStreamDiscontinuityTrap, hh3cVMManTrapObjects=hh3cVMManTrapObjects, hh3cVMManClientVideoStreamDiscontinuityInterval=hh3cVMManClientVideoStreamDiscontinuityInterval, hh3cVMManForwardDeviceCoverTrap=hh3cVMManForwardDeviceCoverTrap, hh3cVMManRegionCoordinateX2=hh3cVMManRegionCoordinateX2, hh3cVMStatSuccConnReleaseRequests=hh3cVMStatSuccConnReleaseRequests, hh3cVMManMemUsageThreshold=hh3cVMManMemUsageThreshold, hh3cVMManHardDiskUsageThreshold=hh3cVMManHardDiskUsageThreshold, hh3cVMManForwardDeviceVideoRecoverTrap=hh3cVMManForwardDeviceVideoRecoverTrap)
| (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, value_range_constraint, constraints_intersection, constraints_union, value_size_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'SingleValueConstraint', 'ValueRangeConstraint', 'ConstraintsIntersection', 'ConstraintsUnion', 'ValueSizeConstraint')
(ent_physical_asset_id,) = mibBuilder.importSymbols('ENTITY-MIB', 'entPhysicalAssetID')
(hh3c_surveillance_mib,) = mibBuilder.importSymbols('HH3C-OID-MIB', 'hh3cSurveillanceMIB')
(notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance')
(mib_scalar, mib_table, mib_table_row, mib_table_column, counter64, time_ticks, module_identity, notification_type, object_identity, ip_address, mib_identifier, integer32, iso, bits, gauge32, counter32, unsigned32) = mibBuilder.importSymbols('SNMPv2-SMI', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'Counter64', 'TimeTicks', 'ModuleIdentity', 'NotificationType', 'ObjectIdentity', 'IpAddress', 'MibIdentifier', 'Integer32', 'iso', 'Bits', 'Gauge32', 'Counter32', 'Unsigned32')
(date_and_time, textual_convention, display_string) = mibBuilder.importSymbols('SNMPv2-TC', 'DateAndTime', 'TextualConvention', 'DisplayString')
hh3c_vm_man = module_identity((1, 3, 6, 1, 4, 1, 25506, 9, 1))
if mibBuilder.loadTexts:
hh3cVMMan.setLastUpdated('200704130000Z')
if mibBuilder.loadTexts:
hh3cVMMan.setOrganization('Hangzhou H3C Tech. Co., Ltd.')
if mibBuilder.loadTexts:
hh3cVMMan.setContactInfo('Platform Team Hangzhou H3C Tech. Co., Ltd. Hai-Dian District Beijing P.R. China http://www.h3c.com Zip:100085 ')
if mibBuilder.loadTexts:
hh3cVMMan.setDescription('VM is one of surveillance features, implementing user authentication, configuration management, network management and control signalling forwarding. This MIB contains objects to manage the VM feature.')
hh3c_vm_man_mib_objects = mib_identifier((1, 3, 6, 1, 4, 1, 25506, 9, 1, 1))
hh3c_vm_capability_set = mib_scalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 1, 1), bits().clone(namedValues=named_values(('cms', 0), ('css', 1), ('dm', 2)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
hh3cVMCapabilitySet.setStatus('current')
if mibBuilder.loadTexts:
hh3cVMCapabilitySet.setDescription('Components included in the VM feature represented by bit fields. VM feature includes three componets: CMS(Central Management Server), CSS(Control Signalling Server) and DM(Data Managment). A bit set to 1 indicates the corresponding component of this bit is included otherwise indicates the corresponding component of this bit is not included. VM can include one or more components at one time. ')
hh3c_vm_stat = mib_identifier((1, 3, 6, 1, 4, 1, 25506, 9, 1, 1, 2))
hh3c_vm_stat_total_conn_establish_requests = mib_scalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 1, 2, 1), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
hh3cVMStatTotalConnEstablishRequests.setStatus('current')
if mibBuilder.loadTexts:
hh3cVMStatTotalConnEstablishRequests.setDescription('The total number of establishment requests for video connection.')
hh3c_vm_stat_succ_conn_establish_requests = mib_scalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 1, 2, 2), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
hh3cVMStatSuccConnEstablishRequests.setStatus('current')
if mibBuilder.loadTexts:
hh3cVMStatSuccConnEstablishRequests.setDescription('The total number of successful establishment requests for video connection.')
hh3c_vm_stat_fail_conn_establish_requests = mib_scalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 1, 2, 3), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
hh3cVMStatFailConnEstablishRequests.setStatus('current')
if mibBuilder.loadTexts:
hh3cVMStatFailConnEstablishRequests.setDescription('The total number of unsuccessful establishment requests for video connection.')
hh3c_vm_stat_total_conn_release_requests = mib_scalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 1, 2, 4), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
hh3cVMStatTotalConnReleaseRequests.setStatus('current')
if mibBuilder.loadTexts:
hh3cVMStatTotalConnReleaseRequests.setDescription('The total number of release requests for video connection.')
hh3c_vm_stat_succ_conn_release_requests = mib_scalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 1, 2, 5), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
hh3cVMStatSuccConnReleaseRequests.setStatus('current')
if mibBuilder.loadTexts:
hh3cVMStatSuccConnReleaseRequests.setDescription('The total number of successful release requests for video connection.')
hh3c_vm_stat_fail_conn_release_requests = mib_scalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 1, 2, 6), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
hh3cVMStatFailConnReleaseRequests.setStatus('current')
if mibBuilder.loadTexts:
hh3cVMStatFailConnReleaseRequests.setDescription('The total number of unsuccessful release requests for video connection.')
hh3c_vm_stat_exception_termination_conn = mib_scalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 1, 2, 7), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
hh3cVMStatExceptionTerminationConn.setStatus('current')
if mibBuilder.loadTexts:
hh3cVMStatExceptionTerminationConn.setDescription('The total number of exceptional termination for video connection.')
hh3c_vm_man_mib_trap = mib_identifier((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2))
hh3c_vm_man_trap_prex = mib_identifier((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0))
hh3c_vm_man_device_online_trap = notification_type((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0, 1)).setObjects(('ENTITY-MIB', 'entPhysicalAssetID'), ('HH3C-VM-MAN-MIB', 'hh3cVMManRegDevIP'), ('HH3C-VM-MAN-MIB', 'hh3cVMManRegDevName'))
if mibBuilder.loadTexts:
hh3cVMManDeviceOnlineTrap.setStatus('current')
if mibBuilder.loadTexts:
hh3cVMManDeviceOnlineTrap.setDescription('Send a trap about the device having been registered to VM.')
hh3c_vm_man_device_offline_trap = notification_type((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0, 2)).setObjects(('ENTITY-MIB', 'entPhysicalAssetID'), ('HH3C-VM-MAN-MIB', 'hh3cVMManRegDevIP'), ('HH3C-VM-MAN-MIB', 'hh3cVMManRegDevName'))
if mibBuilder.loadTexts:
hh3cVMManDeviceOfflineTrap.setStatus('current')
if mibBuilder.loadTexts:
hh3cVMManDeviceOfflineTrap.setDescription('Send a trap about the device having been unregistered to VM.')
hh3c_vm_man_forward_device_external_semaphore_trap = notification_type((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0, 3)).setObjects(('ENTITY-MIB', 'entPhysicalAssetID'), ('HH3C-VM-MAN-MIB', 'hh3cVMManRegDevIP'), ('HH3C-VM-MAN-MIB', 'hh3cVMManRegDevName'), ('HH3C-VM-MAN-MIB', 'hh3cVMManPUExternalInputAlarmChannelID'))
if mibBuilder.loadTexts:
hh3cVMManForwardDeviceExternalSemaphoreTrap.setStatus('current')
if mibBuilder.loadTexts:
hh3cVMManForwardDeviceExternalSemaphoreTrap.setDescription('Forward a trap about external semaphore alarm, which is created by the third party device.')
hh3c_vm_man_forward_device_video_loss_trap = notification_type((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0, 4)).setObjects(('ENTITY-MIB', 'entPhysicalAssetID'), ('HH3C-VM-MAN-MIB', 'hh3cVMManRegDevIP'), ('HH3C-VM-MAN-MIB', 'hh3cVMManRegDevName'), ('HH3C-VM-MAN-MIB', 'hh3cVMManPUECVideoChannelName'))
if mibBuilder.loadTexts:
hh3cVMManForwardDeviceVideoLossTrap.setStatus('current')
if mibBuilder.loadTexts:
hh3cVMManForwardDeviceVideoLossTrap.setDescription('Forward a trap about video loss, which is created by the third party device.')
hh3c_vm_man_forward_device_video_recover_trap = notification_type((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0, 5)).setObjects(('ENTITY-MIB', 'entPhysicalAssetID'), ('HH3C-VM-MAN-MIB', 'hh3cVMManRegDevIP'), ('HH3C-VM-MAN-MIB', 'hh3cVMManRegDevName'), ('HH3C-VM-MAN-MIB', 'hh3cVMManPUECVideoChannelName'))
if mibBuilder.loadTexts:
hh3cVMManForwardDeviceVideoRecoverTrap.setStatus('current')
if mibBuilder.loadTexts:
hh3cVMManForwardDeviceVideoRecoverTrap.setDescription('Forward a trap about video recovery after loss, which is created by the third party device.')
hh3c_vm_man_forward_device_motion_detect_trap = notification_type((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0, 6)).setObjects(('ENTITY-MIB', 'entPhysicalAssetID'), ('HH3C-VM-MAN-MIB', 'hh3cVMManRegDevIP'), ('HH3C-VM-MAN-MIB', 'hh3cVMManRegDevName'), ('HH3C-VM-MAN-MIB', 'hh3cVMManPUECVideoChannelName'), ('HH3C-VM-MAN-MIB', 'hh3cVMManRegionCoordinateX1'), ('HH3C-VM-MAN-MIB', 'hh3cVMManRegionCoordinateY1'), ('HH3C-VM-MAN-MIB', 'hh3cVMManRegionCoordinateX2'), ('HH3C-VM-MAN-MIB', 'hh3cVMManRegionCoordinateY2'))
if mibBuilder.loadTexts:
hh3cVMManForwardDeviceMotionDetectTrap.setStatus('current')
if mibBuilder.loadTexts:
hh3cVMManForwardDeviceMotionDetectTrap.setDescription('Forward a trap about motion detection, which is created by the third party device.')
hh3c_vm_man_forward_device_cover_trap = notification_type((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0, 7)).setObjects(('ENTITY-MIB', 'entPhysicalAssetID'), ('HH3C-VM-MAN-MIB', 'hh3cVMManRegDevIP'), ('HH3C-VM-MAN-MIB', 'hh3cVMManRegDevName'), ('HH3C-VM-MAN-MIB', 'hh3cVMManPUECVideoChannelName'), ('HH3C-VM-MAN-MIB', 'hh3cVMManRegionCoordinateX1'), ('HH3C-VM-MAN-MIB', 'hh3cVMManRegionCoordinateY1'), ('HH3C-VM-MAN-MIB', 'hh3cVMManRegionCoordinateX2'), ('HH3C-VM-MAN-MIB', 'hh3cVMManRegionCoordinateY2'))
if mibBuilder.loadTexts:
hh3cVMManForwardDeviceCoverTrap.setStatus('current')
if mibBuilder.loadTexts:
hh3cVMManForwardDeviceCoverTrap.setDescription('Forward a trap about video cover, which is created by the third party device.')
hh3c_vm_man_forward_device_cpu_usage_threshold_trap = notification_type((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0, 8)).setObjects(('ENTITY-MIB', 'entPhysicalAssetID'), ('HH3C-VM-MAN-MIB', 'hh3cVMManRegDevIP'), ('HH3C-VM-MAN-MIB', 'hh3cVMManRegDevName'), ('HH3C-VM-MAN-MIB', 'hh3cVMManCpuUsage'), ('HH3C-VM-MAN-MIB', 'hh3cVMManCpuUsageThreshold'))
if mibBuilder.loadTexts:
hh3cVMManForwardDeviceCpuUsageThresholdTrap.setStatus('current')
if mibBuilder.loadTexts:
hh3cVMManForwardDeviceCpuUsageThresholdTrap.setDescription('Forward a trap about cpu usage exceeding its threshold, which is created by the third party device.')
hh3c_vm_man_forward_device_mem_usage_threshold_trap = notification_type((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0, 9)).setObjects(('ENTITY-MIB', 'entPhysicalAssetID'), ('HH3C-VM-MAN-MIB', 'hh3cVMManRegDevIP'), ('HH3C-VM-MAN-MIB', 'hh3cVMManRegDevName'), ('HH3C-VM-MAN-MIB', 'hh3cVMManMemUsage'), ('HH3C-VM-MAN-MIB', 'hh3cVMManMemUsageThreshold'))
if mibBuilder.loadTexts:
hh3cVMManForwardDeviceMemUsageThresholdTrap.setStatus('current')
if mibBuilder.loadTexts:
hh3cVMManForwardDeviceMemUsageThresholdTrap.setDescription('Forward a trap about memory usage exceeding its threshold, which is created by the third party device.')
hh3c_vm_man_forward_device_hard_disk_usage_threshold_trap = notification_type((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0, 10)).setObjects(('ENTITY-MIB', 'entPhysicalAssetID'), ('HH3C-VM-MAN-MIB', 'hh3cVMManRegDevIP'), ('HH3C-VM-MAN-MIB', 'hh3cVMManRegDevName'), ('HH3C-VM-MAN-MIB', 'hh3cVMManHardDiskUsage'), ('HH3C-VM-MAN-MIB', 'hh3cVMManHardDiskUsageThreshold'))
if mibBuilder.loadTexts:
hh3cVMManForwardDeviceHardDiskUsageThresholdTrap.setStatus('current')
if mibBuilder.loadTexts:
hh3cVMManForwardDeviceHardDiskUsageThresholdTrap.setDescription('Forward a trap about harddisk usage exceeding its threshold, which is created by the third party device.')
hh3c_vm_man_forward_device_temperature_threshold_trap = notification_type((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0, 11)).setObjects(('ENTITY-MIB', 'entPhysicalAssetID'), ('HH3C-VM-MAN-MIB', 'hh3cVMManRegDevIP'), ('HH3C-VM-MAN-MIB', 'hh3cVMManRegDevName'), ('HH3C-VM-MAN-MIB', 'hh3cVMManTemperature'), ('HH3C-VM-MAN-MIB', 'hh3cVMManTemperatureThreshold'))
if mibBuilder.loadTexts:
hh3cVMManForwardDeviceTemperatureThresholdTrap.setStatus('current')
if mibBuilder.loadTexts:
hh3cVMManForwardDeviceTemperatureThresholdTrap.setDescription('Forward a trap about temperature exceeding its threshold, which is created by the third party device.')
hh3c_vm_man_forward_device_start_kinescope_trap = notification_type((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0, 12)).setObjects(('ENTITY-MIB', 'entPhysicalAssetID'), ('HH3C-VM-MAN-MIB', 'hh3cVMManRegDevIP'), ('HH3C-VM-MAN-MIB', 'hh3cVMManRegDevName'), ('HH3C-VM-MAN-MIB', 'hh3cVMManPUECVideoChannelName'))
if mibBuilder.loadTexts:
hh3cVMManForwardDeviceStartKinescopeTrap.setStatus('current')
if mibBuilder.loadTexts:
hh3cVMManForwardDeviceStartKinescopeTrap.setDescription('Forward a trap about starting kinescope, which is created by the third party device.')
hh3c_vm_man_forward_device_stop_kinescope_trap = notification_type((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0, 13)).setObjects(('ENTITY-MIB', 'entPhysicalAssetID'), ('HH3C-VM-MAN-MIB', 'hh3cVMManRegDevIP'), ('HH3C-VM-MAN-MIB', 'hh3cVMManRegDevName'), ('HH3C-VM-MAN-MIB', 'hh3cVMManPUECVideoChannelName'))
if mibBuilder.loadTexts:
hh3cVMManForwardDeviceStopKinescopeTrap.setStatus('current')
if mibBuilder.loadTexts:
hh3cVMManForwardDeviceStopKinescopeTrap.setDescription('Forward a trap about stopping kinescope, which is created by the third party device.')
hh3c_vm_man_client_report_trap = notification_type((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0, 14)).setObjects(('ENTITY-MIB', 'entPhysicalAssetID'), ('HH3C-VM-MAN-MIB', 'hh3cVMManClientIP'), ('HH3C-VM-MAN-MIB', 'hh3cVMManUserName'), ('HH3C-VM-MAN-MIB', 'hh3cVMManReportContent'))
if mibBuilder.loadTexts:
hh3cVMManClientReportTrap.setStatus('current')
if mibBuilder.loadTexts:
hh3cVMManClientReportTrap.setDescription('Send a trap about the fault which is reported by clients.')
hh3c_vm_man_client_realtime_surveillance_no_video_trap = notification_type((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0, 15)).setObjects(('ENTITY-MIB', 'entPhysicalAssetID'), ('HH3C-VM-MAN-MIB', 'hh3cVMManClientIP'), ('HH3C-VM-MAN-MIB', 'hh3cVMManUserName'), ('HH3C-VM-MAN-MIB', 'hh3cVMManRegDevIP'), ('HH3C-VM-MAN-MIB', 'hh3cVMManRegDevName'), ('HH3C-VM-MAN-MIB', 'hh3cVMManPUECVideoChannelName'))
if mibBuilder.loadTexts:
hh3cVMManClientRealtimeSurveillanceNoVideoTrap.setStatus('current')
if mibBuilder.loadTexts:
hh3cVMManClientRealtimeSurveillanceNoVideoTrap.setDescription("Send a trap about no realtime surveillance video stream which is reported by clients. hh3cVMManRegDevIP, entPhysicalAssetID, hh3cVMManRegDevName and hh3cVMManPUECVideoChannelName describe an EC's relative information. ")
hh3c_vm_man_client_vod_no_video_trap = notification_type((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0, 16)).setObjects(('ENTITY-MIB', 'entPhysicalAssetID'), ('HH3C-VM-MAN-MIB', 'hh3cVMManClientIP'), ('HH3C-VM-MAN-MIB', 'hh3cVMManUserName'), ('HH3C-VM-MAN-MIB', 'hh3cVMManRegDevIP'), ('HH3C-VM-MAN-MIB', 'hh3cVMManRegDevName'), ('HH3C-VM-MAN-MIB', 'hh3cVMManPUECVideoChannelName'), ('HH3C-VM-MAN-MIB', 'hh3cVMManClientVODStart'), ('HH3C-VM-MAN-MIB', 'hh3cVMManClientVODEnd'), ('HH3C-VM-MAN-MIB', 'hh3cVMManIPSANDevIP'))
if mibBuilder.loadTexts:
hh3cVMManClientVODNoVideoTrap.setStatus('current')
if mibBuilder.loadTexts:
hh3cVMManClientVODNoVideoTrap.setDescription("Send a trap about no VOD video stream which is reported by clients. hh3cVMManRegDevIP, entPhysicalAssetID, hh3cVMManRegDevName and hh3cVMManPUECVideoChannelName describe an EC's relative information.")
hh3c_vm_man_client_realtime_surveillance_video_stream_discontinuity_trap = notification_type((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0, 17)).setObjects(('ENTITY-MIB', 'entPhysicalAssetID'), ('HH3C-VM-MAN-MIB', 'hh3cVMManClientIP'), ('HH3C-VM-MAN-MIB', 'hh3cVMManUserName'), ('HH3C-VM-MAN-MIB', 'hh3cVMManRegDevIP'), ('HH3C-VM-MAN-MIB', 'hh3cVMManRegDevName'), ('HH3C-VM-MAN-MIB', 'hh3cVMManPUECVideoChannelName'), ('HH3C-VM-MAN-MIB', 'hh3cVMManClientVideoStreamDiscontinuityInterval'), ('HH3C-VM-MAN-MIB', 'hh3cVMManClientVideoStreamDiscontinuityIntervalThreshold'), ('HH3C-VM-MAN-MIB', 'hh3cVMManClientStatPeriod'))
if mibBuilder.loadTexts:
hh3cVMManClientRealtimeSurveillanceVideoStreamDiscontinuityTrap.setStatus('current')
if mibBuilder.loadTexts:
hh3cVMManClientRealtimeSurveillanceVideoStreamDiscontinuityTrap.setDescription("Send a trap about the realtime surveillance video stream discontinuity which is reported by clients. entPhysicalAssetID, hh3cVMManRegDevIP, hh3cVMManRegDevName and hh3cVMManPUECVideoChannelName describe an EC's relative information.")
hh3c_vm_man_client_vod_video_stream_discontinuity_trap = notification_type((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0, 18)).setObjects(('ENTITY-MIB', 'entPhysicalAssetID'), ('HH3C-VM-MAN-MIB', 'hh3cVMManClientIP'), ('HH3C-VM-MAN-MIB', 'hh3cVMManUserName'), ('HH3C-VM-MAN-MIB', 'hh3cVMManRegDevIP'), ('HH3C-VM-MAN-MIB', 'hh3cVMManRegDevName'), ('HH3C-VM-MAN-MIB', 'hh3cVMManPUECVideoChannelName'), ('HH3C-VM-MAN-MIB', 'hh3cVMManClientVODStart'), ('HH3C-VM-MAN-MIB', 'hh3cVMManClientVODEnd'), ('HH3C-VM-MAN-MIB', 'hh3cVMManIPSANDevIP'), ('HH3C-VM-MAN-MIB', 'hh3cVMManClientVideoStreamDiscontinuityInterval'), ('HH3C-VM-MAN-MIB', 'hh3cVMManClientVideoStreamDiscontinuityIntervalThreshold'), ('HH3C-VM-MAN-MIB', 'hh3cVMManClientStatPeriod'))
if mibBuilder.loadTexts:
hh3cVMManClientVODVideoStreamDiscontinuityTrap.setStatus('current')
if mibBuilder.loadTexts:
hh3cVMManClientVODVideoStreamDiscontinuityTrap.setDescription("Send a trap about the VOD video stream discontinuity which is reported by clients. hh3cVMManRegDevIP, entPhysicalAssetID, hh3cVMManRegDevName and hh3cVMManPUECVideoChannelName describe an EC's relative information.")
hh3c_vm_man_client_ctl_conn_exception_termination_trap = notification_type((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0, 19)).setObjects(('ENTITY-MIB', 'entPhysicalAssetID'), ('HH3C-VM-MAN-MIB', 'hh3cVMManClientIP'), ('HH3C-VM-MAN-MIB', 'hh3cVMManUserName'))
if mibBuilder.loadTexts:
hh3cVMManClientCtlConnExceptionTerminationTrap.setStatus('current')
if mibBuilder.loadTexts:
hh3cVMManClientCtlConnExceptionTerminationTrap.setDescription('Send a trap about the exceptional termination for control connection. ')
hh3c_vm_man_client_frequency_login_fail_trap = notification_type((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0, 20)).setObjects(('ENTITY-MIB', 'entPhysicalAssetID'), ('HH3C-VM-MAN-MIB', 'hh3cVMManClientIP'), ('HH3C-VM-MAN-MIB', 'hh3cVMManUserName'), ('HH3C-VM-MAN-MIB', 'hh3cVMManClientLoginFailNum'), ('HH3C-VM-MAN-MIB', 'hh3cVMManClientLoginFailNumThreshold'), ('HH3C-VM-MAN-MIB', 'hh3cVMManClientStatPeriod'))
if mibBuilder.loadTexts:
hh3cVMManClientFrequencyLoginFailTrap.setStatus('current')
if mibBuilder.loadTexts:
hh3cVMManClientFrequencyLoginFailTrap.setDescription('Send a trap about the frequency of client login failure.')
hh3c_vm_man_client_frequency_vod_fail_trap = notification_type((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0, 21)).setObjects(('ENTITY-MIB', 'entPhysicalAssetID'), ('HH3C-VM-MAN-MIB', 'hh3cVMManClientIP'), ('HH3C-VM-MAN-MIB', 'hh3cVMManUserName'), ('HH3C-VM-MAN-MIB', 'hh3cVMManClientVODFailNum'), ('HH3C-VM-MAN-MIB', 'hh3cVMManClientVODFailNumThreshold'), ('HH3C-VM-MAN-MIB', 'hh3cVMManClientStatPeriod'))
if mibBuilder.loadTexts:
hh3cVMManClientFrequencyVODFailTrap.setStatus('current')
if mibBuilder.loadTexts:
hh3cVMManClientFrequencyVODFailTrap.setDescription('Send a trap about the frequency of client VOD failure.')
hh3c_vm_man_dmec_disobey_storage_schedule_trap = notification_type((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0, 22)).setObjects(('ENTITY-MIB', 'entPhysicalAssetID'), ('HH3C-VM-MAN-MIB', 'hh3cVMManRegDevIP'), ('HH3C-VM-MAN-MIB', 'hh3cVMManPUECVideoChannelName'))
if mibBuilder.loadTexts:
hh3cVMManDMECDisobeyStorageScheduleTrap.setStatus('current')
if mibBuilder.loadTexts:
hh3cVMManDMECDisobeyStorageScheduleTrap.setDescription('Send a trap about EC disobeying storage schedule created by DM.')
hh3c_vm_man_dmec_disobey_storage_schedule_recover_trap = notification_type((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 0, 23)).setObjects(('ENTITY-MIB', 'entPhysicalAssetID'), ('HH3C-VM-MAN-MIB', 'hh3cVMManRegDevIP'), ('HH3C-VM-MAN-MIB', 'hh3cVMManPUECVideoChannelName'))
if mibBuilder.loadTexts:
hh3cVMManDMECDisobeyStorageScheduleRecoverTrap.setStatus('current')
if mibBuilder.loadTexts:
hh3cVMManDMECDisobeyStorageScheduleRecoverTrap.setDescription('Send a trap about recovery after EC disobeying storage schedule created by DM.')
hh3c_vm_man_trap_objects = mib_identifier((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1))
hh3c_vm_man_ipsan_dev_ip = mib_scalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 1), ip_address()).setMaxAccess('accessiblefornotify')
if mibBuilder.loadTexts:
hh3cVMManIPSANDevIP.setStatus('current')
if mibBuilder.loadTexts:
hh3cVMManIPSANDevIP.setDescription('IP address of IPSAN Device which can store video data.')
hh3c_vm_man_reg_dev_ip = mib_scalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 2), ip_address()).setMaxAccess('accessiblefornotify')
if mibBuilder.loadTexts:
hh3cVMManRegDevIP.setStatus('current')
if mibBuilder.loadTexts:
hh3cVMManRegDevIP.setDescription('IP address of devices which can registered or unregistered to VM.')
hh3c_vm_man_reg_dev_name = mib_scalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 3), display_string().subtype(subtypeSpec=value_size_constraint(0, 64))).setMaxAccess('accessiblefornotify')
if mibBuilder.loadTexts:
hh3cVMManRegDevName.setStatus('current')
if mibBuilder.loadTexts:
hh3cVMManRegDevName.setDescription('Name of devices which can registered or unregistered to VM.')
hh3c_vm_man_region_coordinate_x1 = mib_scalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 4), unsigned32()).setMaxAccess('accessiblefornotify')
if mibBuilder.loadTexts:
hh3cVMManRegionCoordinateX1.setStatus('current')
if mibBuilder.loadTexts:
hh3cVMManRegionCoordinateX1.setDescription('The horizontal coordinate of top left point of the motion detection region.')
hh3c_vm_man_region_coordinate_y1 = mib_scalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 5), unsigned32()).setMaxAccess('accessiblefornotify')
if mibBuilder.loadTexts:
hh3cVMManRegionCoordinateY1.setStatus('current')
if mibBuilder.loadTexts:
hh3cVMManRegionCoordinateY1.setDescription('The vertical coordinate of top left point of the motion detection region.')
hh3c_vm_man_region_coordinate_x2 = mib_scalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 6), unsigned32()).setMaxAccess('accessiblefornotify')
if mibBuilder.loadTexts:
hh3cVMManRegionCoordinateX2.setStatus('current')
if mibBuilder.loadTexts:
hh3cVMManRegionCoordinateX2.setDescription('The horizontal coordinate of botton right point of the motion detection region.')
hh3c_vm_man_region_coordinate_y2 = mib_scalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 7), unsigned32()).setMaxAccess('accessiblefornotify')
if mibBuilder.loadTexts:
hh3cVMManRegionCoordinateY2.setStatus('current')
if mibBuilder.loadTexts:
hh3cVMManRegionCoordinateY2.setDescription('The horizontal coordinate of botton right point of the motion detection region.')
hh3c_vm_man_cpu_usage = mib_scalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 8), unsigned32().subtype(subtypeSpec=value_range_constraint(0, 100))).setMaxAccess('accessiblefornotify')
if mibBuilder.loadTexts:
hh3cVMManCpuUsage.setStatus('current')
if mibBuilder.loadTexts:
hh3cVMManCpuUsage.setDescription('The CPU usage for this entity. Generally, the CPU usage will caculate the overall CPU usage on the entity, and it is not sensible with the number of CPU on the entity. ')
hh3c_vm_man_cpu_usage_threshold = mib_scalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 9), unsigned32().subtype(subtypeSpec=value_range_constraint(0, 100))).setMaxAccess('accessiblefornotify')
if mibBuilder.loadTexts:
hh3cVMManCpuUsageThreshold.setStatus('current')
if mibBuilder.loadTexts:
hh3cVMManCpuUsageThreshold.setDescription('The threshold for the CPU usage. When the CPU usage exceeds the threshold, a notification will be sent.')
hh3c_vm_man_mem_usage = mib_scalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 10), unsigned32().subtype(subtypeSpec=value_range_constraint(0, 100))).setMaxAccess('accessiblefornotify')
if mibBuilder.loadTexts:
hh3cVMManMemUsage.setStatus('current')
if mibBuilder.loadTexts:
hh3cVMManMemUsage.setDescription('The memory usage for the entity. This object indicates what percent of memory are used. ')
hh3c_vm_man_mem_usage_threshold = mib_scalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 11), unsigned32().subtype(subtypeSpec=value_range_constraint(0, 100))).setMaxAccess('accessiblefornotify')
if mibBuilder.loadTexts:
hh3cVMManMemUsageThreshold.setStatus('current')
if mibBuilder.loadTexts:
hh3cVMManMemUsageThreshold.setDescription('The threshold for the Memory usage. When the memory usage exceeds the threshold, a notification will be sent. ')
hh3c_vm_man_hard_disk_usage = mib_scalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 12), unsigned32().subtype(subtypeSpec=value_range_constraint(0, 100))).setMaxAccess('accessiblefornotify')
if mibBuilder.loadTexts:
hh3cVMManHardDiskUsage.setStatus('current')
if mibBuilder.loadTexts:
hh3cVMManHardDiskUsage.setDescription('The hard disk usage for the entity. This object indicates what percent of hard disk are used. ')
hh3c_vm_man_hard_disk_usage_threshold = mib_scalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 13), unsigned32().subtype(subtypeSpec=value_range_constraint(0, 100))).setMaxAccess('accessiblefornotify')
if mibBuilder.loadTexts:
hh3cVMManHardDiskUsageThreshold.setStatus('current')
if mibBuilder.loadTexts:
hh3cVMManHardDiskUsageThreshold.setDescription('The threshold for the hard disk usage. When the hard disk usage exceeds the threshold, a notification will be sent. ')
hh3c_vm_man_temperature = mib_scalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 14), integer32()).setMaxAccess('accessiblefornotify')
if mibBuilder.loadTexts:
hh3cVMManTemperature.setStatus('current')
if mibBuilder.loadTexts:
hh3cVMManTemperature.setDescription('The temperature for the entity. ')
hh3c_vm_man_temperature_threshold = mib_scalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 15), integer32()).setMaxAccess('accessiblefornotify')
if mibBuilder.loadTexts:
hh3cVMManTemperatureThreshold.setStatus('current')
if mibBuilder.loadTexts:
hh3cVMManTemperatureThreshold.setDescription('The threshold for the temperature. When the temperature exceeds the threshold, a notification will be sent. ')
hh3c_vm_man_client_ip = mib_scalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 16), ip_address()).setMaxAccess('accessiblefornotify')
if mibBuilder.loadTexts:
hh3cVMManClientIP.setStatus('current')
if mibBuilder.loadTexts:
hh3cVMManClientIP.setDescription('The client device IP address.')
hh3c_vm_man_user_name = mib_scalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 17), display_string().subtype(subtypeSpec=value_size_constraint(0, 32))).setMaxAccess('accessiblefornotify')
if mibBuilder.loadTexts:
hh3cVMManUserName.setStatus('current')
if mibBuilder.loadTexts:
hh3cVMManUserName.setDescription('The client user name.')
hh3c_vm_man_report_content = mib_scalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 18), display_string().subtype(subtypeSpec=value_size_constraint(0, 128))).setMaxAccess('accessiblefornotify')
if mibBuilder.loadTexts:
hh3cVMManReportContent.setStatus('current')
if mibBuilder.loadTexts:
hh3cVMManReportContent.setDescription('The details of the fault which reported by clients')
hh3c_vm_man_client_video_stream_discontinuity_interval = mib_scalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 19), unsigned32()).setMaxAccess('accessiblefornotify')
if mibBuilder.loadTexts:
hh3cVMManClientVideoStreamDiscontinuityInterval.setStatus('current')
if mibBuilder.loadTexts:
hh3cVMManClientVideoStreamDiscontinuityInterval.setDescription('Video stream discontinuity interval. ')
hh3c_vm_man_client_video_stream_discontinuity_interval_threshold = mib_scalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 20), unsigned32()).setMaxAccess('accessiblefornotify')
if mibBuilder.loadTexts:
hh3cVMManClientVideoStreamDiscontinuityIntervalThreshold.setStatus('current')
if mibBuilder.loadTexts:
hh3cVMManClientVideoStreamDiscontinuityIntervalThreshold.setDescription('The threshold for the video stream discontinuity interval. When the discontinuity interval exceeds the threshold, a notification will be sent. ')
hh3c_vm_man_client_stat_period = mib_scalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 21), unsigned32()).setMaxAccess('accessiblefornotify')
if mibBuilder.loadTexts:
hh3cVMManClientStatPeriod.setStatus('current')
if mibBuilder.loadTexts:
hh3cVMManClientStatPeriod.setDescription('The client statistic period. ')
hh3c_vm_man_client_login_fail_num = mib_scalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 22), unsigned32()).setMaxAccess('accessiblefornotify')
if mibBuilder.loadTexts:
hh3cVMManClientLoginFailNum.setStatus('current')
if mibBuilder.loadTexts:
hh3cVMManClientLoginFailNum.setDescription('The total number of client login failure in last statistic period which is defined by hh3cVMManClientStatPeriod entity.')
hh3c_vm_man_client_login_fail_num_threshold = mib_scalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 23), unsigned32()).setMaxAccess('accessiblefornotify')
if mibBuilder.loadTexts:
hh3cVMManClientLoginFailNumThreshold.setStatus('current')
if mibBuilder.loadTexts:
hh3cVMManClientLoginFailNumThreshold.setDescription('The threshold for the total number of client login failure in last statistic period. When the number exceeds the threshold, a notification will be sent. ')
hh3c_vm_man_client_vod_fail_num = mib_scalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 24), unsigned32()).setMaxAccess('accessiblefornotify')
if mibBuilder.loadTexts:
hh3cVMManClientVODFailNum.setStatus('current')
if mibBuilder.loadTexts:
hh3cVMManClientVODFailNum.setDescription('The total number of client VOD failure in last statistic period which is defined by hh3cVMManClientStatPeriod entity.')
hh3c_vm_man_client_vod_fail_num_threshold = mib_scalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 25), unsigned32()).setMaxAccess('accessiblefornotify')
if mibBuilder.loadTexts:
hh3cVMManClientVODFailNumThreshold.setStatus('current')
if mibBuilder.loadTexts:
hh3cVMManClientVODFailNumThreshold.setDescription('The threshold for the total number of client VOD failure in last statistic period. When the number exceeds the threshold, a notification will be sent. ')
hh3c_vm_man_client_vod_start = mib_scalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 26), date_and_time()).setMaxAccess('accessiblefornotify')
if mibBuilder.loadTexts:
hh3cVMManClientVODStart.setStatus('current')
if mibBuilder.loadTexts:
hh3cVMManClientVODStart.setDescription('The start time for VOD.')
hh3c_vm_man_client_vod_end = mib_scalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 27), date_and_time()).setMaxAccess('accessiblefornotify')
if mibBuilder.loadTexts:
hh3cVMManClientVODEnd.setStatus('current')
if mibBuilder.loadTexts:
hh3cVMManClientVODEnd.setDescription('The end time for VOD.')
hh3c_vm_man_pu_external_input_alarm_channel_id = mib_scalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 28), unsigned32()).setMaxAccess('accessiblefornotify')
if mibBuilder.loadTexts:
hh3cVMManPUExternalInputAlarmChannelID.setStatus('current')
if mibBuilder.loadTexts:
hh3cVMManPUExternalInputAlarmChannelID.setDescription('The ID of the external input alarm channel.')
hh3c_vm_man_puec_video_channel_name = mib_scalar((1, 3, 6, 1, 4, 1, 25506, 9, 1, 2, 1, 29), display_string().subtype(subtypeSpec=value_size_constraint(0, 32))).setMaxAccess('accessiblefornotify')
if mibBuilder.loadTexts:
hh3cVMManPUECVideoChannelName.setStatus('current')
if mibBuilder.loadTexts:
hh3cVMManPUECVideoChannelName.setDescription('The name of the video channel. It is suggested that the name includes the channel ID information.')
mibBuilder.exportSymbols('HH3C-VM-MAN-MIB', hh3cVMManPUExternalInputAlarmChannelID=hh3cVMManPUExternalInputAlarmChannelID, hh3cVMManClientVODEnd=hh3cVMManClientVODEnd, hh3cVMManDMECDisobeyStorageScheduleRecoverTrap=hh3cVMManDMECDisobeyStorageScheduleRecoverTrap, hh3cVMManDeviceOfflineTrap=hh3cVMManDeviceOfflineTrap, hh3cVMManIPSANDevIP=hh3cVMManIPSANDevIP, hh3cVMManTemperatureThreshold=hh3cVMManTemperatureThreshold, hh3cVMManClientStatPeriod=hh3cVMManClientStatPeriod, hh3cVMManForwardDeviceCpuUsageThresholdTrap=hh3cVMManForwardDeviceCpuUsageThresholdTrap, hh3cVMManClientRealtimeSurveillanceNoVideoTrap=hh3cVMManClientRealtimeSurveillanceNoVideoTrap, hh3cVMManClientVODFailNumThreshold=hh3cVMManClientVODFailNumThreshold, hh3cVMMan=hh3cVMMan, hh3cVMStatFailConnEstablishRequests=hh3cVMStatFailConnEstablishRequests, hh3cVMStatTotalConnEstablishRequests=hh3cVMStatTotalConnEstablishRequests, hh3cVMStat=hh3cVMStat, hh3cVMStatSuccConnEstablishRequests=hh3cVMStatSuccConnEstablishRequests, hh3cVMStatExceptionTerminationConn=hh3cVMStatExceptionTerminationConn, hh3cVMManForwardDeviceExternalSemaphoreTrap=hh3cVMManForwardDeviceExternalSemaphoreTrap, hh3cVMManForwardDeviceStopKinescopeTrap=hh3cVMManForwardDeviceStopKinescopeTrap, hh3cVMManClientRealtimeSurveillanceVideoStreamDiscontinuityTrap=hh3cVMManClientRealtimeSurveillanceVideoStreamDiscontinuityTrap, hh3cVMManCpuUsageThreshold=hh3cVMManCpuUsageThreshold, hh3cVMManUserName=hh3cVMManUserName, hh3cVMManClientFrequencyLoginFailTrap=hh3cVMManClientFrequencyLoginFailTrap, hh3cVMManReportContent=hh3cVMManReportContent, hh3cVMManPUECVideoChannelName=hh3cVMManPUECVideoChannelName, hh3cVMStatFailConnReleaseRequests=hh3cVMStatFailConnReleaseRequests, hh3cVMManForwardDeviceMotionDetectTrap=hh3cVMManForwardDeviceMotionDetectTrap, hh3cVMManForwardDeviceHardDiskUsageThresholdTrap=hh3cVMManForwardDeviceHardDiskUsageThresholdTrap, hh3cVMManTrapPrex=hh3cVMManTrapPrex, hh3cVMStatTotalConnReleaseRequests=hh3cVMStatTotalConnReleaseRequests, hh3cVMManForwardDeviceStartKinescopeTrap=hh3cVMManForwardDeviceStartKinescopeTrap, hh3cVMManClientVODNoVideoTrap=hh3cVMManClientVODNoVideoTrap, hh3cVMManRegionCoordinateY2=hh3cVMManRegionCoordinateY2, hh3cVMManCpuUsage=hh3cVMManCpuUsage, hh3cVMManClientVideoStreamDiscontinuityIntervalThreshold=hh3cVMManClientVideoStreamDiscontinuityIntervalThreshold, hh3cVMManClientVODStart=hh3cVMManClientVODStart, hh3cVMManMIBTrap=hh3cVMManMIBTrap, hh3cVMCapabilitySet=hh3cVMCapabilitySet, hh3cVMManRegionCoordinateY1=hh3cVMManRegionCoordinateY1, hh3cVMManMIBObjects=hh3cVMManMIBObjects, hh3cVMManForwardDeviceTemperatureThresholdTrap=hh3cVMManForwardDeviceTemperatureThresholdTrap, hh3cVMManClientCtlConnExceptionTerminationTrap=hh3cVMManClientCtlConnExceptionTerminationTrap, hh3cVMManForwardDeviceMemUsageThresholdTrap=hh3cVMManForwardDeviceMemUsageThresholdTrap, hh3cVMManClientFrequencyVODFailTrap=hh3cVMManClientFrequencyVODFailTrap, hh3cVMManDMECDisobeyStorageScheduleTrap=hh3cVMManDMECDisobeyStorageScheduleTrap, hh3cVMManRegDevIP=hh3cVMManRegDevIP, hh3cVMManMemUsage=hh3cVMManMemUsage, hh3cVMManTemperature=hh3cVMManTemperature, hh3cVMManClientLoginFailNumThreshold=hh3cVMManClientLoginFailNumThreshold, hh3cVMManClientVODFailNum=hh3cVMManClientVODFailNum, hh3cVMManClientReportTrap=hh3cVMManClientReportTrap, hh3cVMManHardDiskUsage=hh3cVMManHardDiskUsage, hh3cVMManDeviceOnlineTrap=hh3cVMManDeviceOnlineTrap, hh3cVMManForwardDeviceVideoLossTrap=hh3cVMManForwardDeviceVideoLossTrap, hh3cVMManClientLoginFailNum=hh3cVMManClientLoginFailNum, hh3cVMManRegionCoordinateX1=hh3cVMManRegionCoordinateX1, hh3cVMManRegDevName=hh3cVMManRegDevName, hh3cVMManClientIP=hh3cVMManClientIP, PYSNMP_MODULE_ID=hh3cVMMan, hh3cVMManClientVODVideoStreamDiscontinuityTrap=hh3cVMManClientVODVideoStreamDiscontinuityTrap, hh3cVMManTrapObjects=hh3cVMManTrapObjects, hh3cVMManClientVideoStreamDiscontinuityInterval=hh3cVMManClientVideoStreamDiscontinuityInterval, hh3cVMManForwardDeviceCoverTrap=hh3cVMManForwardDeviceCoverTrap, hh3cVMManRegionCoordinateX2=hh3cVMManRegionCoordinateX2, hh3cVMStatSuccConnReleaseRequests=hh3cVMStatSuccConnReleaseRequests, hh3cVMManMemUsageThreshold=hh3cVMManMemUsageThreshold, hh3cVMManHardDiskUsageThreshold=hh3cVMManHardDiskUsageThreshold, hh3cVMManForwardDeviceVideoRecoverTrap=hh3cVMManForwardDeviceVideoRecoverTrap) |
# Copyright 2017 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Helper methods for implementing the test bundles."""
load(
"@build_bazel_rules_apple//apple/bundling:binary_support.bzl",
"binary_support",
)
load(
"@build_bazel_rules_apple//apple/bundling:bundler.bzl",
"bundler",
)
load(
"@build_bazel_rules_apple//apple:providers.bzl",
"AppleBundleInfo",
)
# Default test bundle ID for tests that don't have a test host or were not given
# a bundle ID.
_DEFAULT_TEST_BUNDLE_ID = "com.bazelbuild.rulesapple.Tests"
def _computed_test_bundle_id(test_host_bundle_id):
"""Compute a test bundle ID from the test host, or a default if not given."""
if test_host_bundle_id:
bundle_id = test_host_bundle_id + "Tests"
else:
bundle_id = _DEFAULT_TEST_BUNDLE_ID
return bundle_id
def _test_host_bundle_id(test_host):
"""Return the bundle ID for the given test host, or None if none was given."""
if not test_host:
return None
test_host_bundle_info = test_host[AppleBundleInfo]
return test_host_bundle_info.bundle_id
def _apple_test_bundle_impl(ctx,
mnemonic,
progress_description,
extra_providers):
"""Implementation for the test bundle rules."""
test_host_bundle_id = _test_host_bundle_id(ctx.attr.test_host)
if ctx.attr.bundle_id:
bundle_id = ctx.attr.bundle_id
else:
bundle_id = _computed_test_bundle_id(test_host_bundle_id)
if bundle_id == test_host_bundle_id:
fail("The test bundle's identifier of '" + bundle_id + "' can't be the " +
"same as the test host's bundle identifier. Please change one of " +
"them.")
binary_artifact = binary_support.get_binary_provider(
ctx.attr.deps, apple_common.AppleLoadableBundleBinary).binary
deps_objc_provider = binary_support.get_binary_provider(
ctx.attr.deps, apple_common.AppleLoadableBundleBinary).objc
bundler_providers, legacy_providers, additional_outputs = bundler.run(
ctx,
mnemonic,
progress_description,
bundle_id,
binary_artifact=binary_artifact,
deps_objc_providers=[deps_objc_provider],
version_keys_required=False,
)
return struct(
files=additional_outputs,
instrumented_files=struct(dependency_attributes=["binary", "test_host"]),
providers=extra_providers + bundler_providers,
**legacy_providers
)
# Define the loadable module that lists the exported symbols in this file.
apple_test_bundle_support = struct(
apple_test_bundle_impl=_apple_test_bundle_impl,
)
| """Helper methods for implementing the test bundles."""
load('@build_bazel_rules_apple//apple/bundling:binary_support.bzl', 'binary_support')
load('@build_bazel_rules_apple//apple/bundling:bundler.bzl', 'bundler')
load('@build_bazel_rules_apple//apple:providers.bzl', 'AppleBundleInfo')
_default_test_bundle_id = 'com.bazelbuild.rulesapple.Tests'
def _computed_test_bundle_id(test_host_bundle_id):
"""Compute a test bundle ID from the test host, or a default if not given."""
if test_host_bundle_id:
bundle_id = test_host_bundle_id + 'Tests'
else:
bundle_id = _DEFAULT_TEST_BUNDLE_ID
return bundle_id
def _test_host_bundle_id(test_host):
"""Return the bundle ID for the given test host, or None if none was given."""
if not test_host:
return None
test_host_bundle_info = test_host[AppleBundleInfo]
return test_host_bundle_info.bundle_id
def _apple_test_bundle_impl(ctx, mnemonic, progress_description, extra_providers):
"""Implementation for the test bundle rules."""
test_host_bundle_id = _test_host_bundle_id(ctx.attr.test_host)
if ctx.attr.bundle_id:
bundle_id = ctx.attr.bundle_id
else:
bundle_id = _computed_test_bundle_id(test_host_bundle_id)
if bundle_id == test_host_bundle_id:
fail("The test bundle's identifier of '" + bundle_id + "' can't be the " + "same as the test host's bundle identifier. Please change one of " + 'them.')
binary_artifact = binary_support.get_binary_provider(ctx.attr.deps, apple_common.AppleLoadableBundleBinary).binary
deps_objc_provider = binary_support.get_binary_provider(ctx.attr.deps, apple_common.AppleLoadableBundleBinary).objc
(bundler_providers, legacy_providers, additional_outputs) = bundler.run(ctx, mnemonic, progress_description, bundle_id, binary_artifact=binary_artifact, deps_objc_providers=[deps_objc_provider], version_keys_required=False)
return struct(files=additional_outputs, instrumented_files=struct(dependency_attributes=['binary', 'test_host']), providers=extra_providers + bundler_providers, **legacy_providers)
apple_test_bundle_support = struct(apple_test_bundle_impl=_apple_test_bundle_impl) |
class Solution:
def canVisitAllRooms(self, rooms):
"""
:type rooms: List[List[int]]
:rtype: bool
"""
if len(rooms) == 1:
return True
if len(rooms[0]) == 0:
return False
curent = set()
visited = [0]
for key in rooms[0]:
curent.add(key)
while len(curent) > 0:
temp = curent.pop()
if temp in visited:
print("I benn here before")
else:
for item in rooms[temp]:
curent.add(item)
visited.append(temp)
if len(visited) == len(rooms):
return True
return False
| class Solution:
def can_visit_all_rooms(self, rooms):
"""
:type rooms: List[List[int]]
:rtype: bool
"""
if len(rooms) == 1:
return True
if len(rooms[0]) == 0:
return False
curent = set()
visited = [0]
for key in rooms[0]:
curent.add(key)
while len(curent) > 0:
temp = curent.pop()
if temp in visited:
print('I benn here before')
else:
for item in rooms[temp]:
curent.add(item)
visited.append(temp)
if len(visited) == len(rooms):
return True
return False |
"""2. Fine-tuning SOTA video models on your own dataset
=======================================================
Fine-tuning is an important way to obtain good video models on your own data when you don't have large annotated dataset or don't have the
computing resources to train a model from scratch for your use case.
In this tutorial, we provide a simple unified solution.
The only thing you need to prepare is a text file containing the information of your videos (e.g., the path to your videos),
we will take care of the rest.
You can start fine-tuning from many popular pre-trained models (e.g., I3D, R2+1D, SlowFast and TPN) using a single command line.
"""
######################################################################
# Custom DataLoader
# ------------------
#
# The first and only thing you need to prepare is the data annotation files ``train.txt`` and ``val.txt``.
# We provide a general dataloader for you to use on your own dataset.
# Your data can be stored in any hierarchy, and the ``train.txt`` should look like:
#
# ::
#
# video_001.mp4 200 0
# video_001.mp4 200 0
# video_002.mp4 300 0
# video_003.mp4 100 1
# video_004.mp4 400 2
# ......
# video_100.mp4 200 10
#
# As you can see, there are three items in each line, separated by spaces.
# The first item is the path to your training videos, e.g., video_001.mp4.
# The second item is the number of frames in each video. But you can put any number here
# because our video loader will compute the number of frames again automatically during training.
# The third item is the label of that video, e.g., 0.
# ``val.txt`` looks the same as ``train.txt`` in terms of format.
#
#
# Once you prepare the ``train.txt`` and ``val.txt``, you are good to go.
# In this tutorial, we will use I3D model and Something-something-v2 dataset as an example.
# Suppose you have Something-something-v2 dataset and you don't want to train an I3D model from scratch.
# First, prepare the data anotation files as mentioned above.
# Second, follow this configuration file `i3d_resnet50_v1_custom.yaml <https://raw.githubusercontent.com/dmlc/gluon-cv/master/scripts/action-recognition/configuration/i3d_resnet50_v1_custom.yaml>`_.
# Specifically, you just need to change the data paths and number of classes in that yaml file.
#
# ::
#
# TRAIN_ANNO_PATH: '/home/ubuntu/data/sthsthv2/sthsthv2_train.txt'
# VAL_ANNO_PATH: '/home/ubuntu/data/sthsthv2/sthsthv2_val.txt'
# TRAIN_DATA_PATH: '/home/ubuntu/data/sthsthv2/20bn-something-something-v2/'
# VAL_DATA_PATH: '/home/ubuntu/data/sthsthv2/20bn-something-something-v2/'
# NUM_CLASSES: 174
#
# If you want to tune other parameters, it is also easy to do.
# Change the learning rate, batch size, clip lenght according to your use cases. Usually a small learning rate is preferred since the model initialization is decent.
######################################################################
# We also support finetuning on other models, e.g.,
# `resnet50_v1b_custom.yaml <https://raw.githubusercontent.com/dmlc/gluon-cv/master/scripts/action-recognition/configuration/resnet50_v1b_custom.yaml>`_,
# `slowfast_4x16_resnet50_custom.yaml <https://raw.githubusercontent.com/dmlc/gluon-cv/master/scripts/action-recognition/configuration/slowfast_4x16_resnet50_custom.yaml>`_,
# `tpn_resnet50_f32s2_custom.yaml <https://raw.githubusercontent.com/dmlc/gluon-cv/master/scripts/action-recognition/configuration/tpn_resnet50_f32s2_custom.yaml>`_,
# `r2plus1d_v1_resnet50_custom.yaml <https://raw.githubusercontent.com/dmlc/gluon-cv/master/scripts/action-recognition/configuration/r2plus1d_v1_resnet50_custom.yaml>`_,
# `i3d_slow_resnet50_f32s2_custom.yaml <https://raw.githubusercontent.com/dmlc/gluon-cv/master/scripts/action-recognition/configuration/i3d_slow_resnet50_f32s2_custom.yaml>`_.
# Try fine-tuning these SOTA video models on your own dataset and see how it goes.
#
# If you would like to extract good video features on your datasets,
# feel free to read the next `tutorial on feature extraction <extract_feat.html>`__.
| """2. Fine-tuning SOTA video models on your own dataset
=======================================================
Fine-tuning is an important way to obtain good video models on your own data when you don't have large annotated dataset or don't have the
computing resources to train a model from scratch for your use case.
In this tutorial, we provide a simple unified solution.
The only thing you need to prepare is a text file containing the information of your videos (e.g., the path to your videos),
we will take care of the rest.
You can start fine-tuning from many popular pre-trained models (e.g., I3D, R2+1D, SlowFast and TPN) using a single command line.
""" |
class Solution:
"""
@param height: A list of integer
@return: The area of largest rectangle in the histogram
"""
def largestRectangleArea(self, height):
len_histogram = len(height)
ans = 0
height_list = sorter(height, reverse=True)
for now_height in height_list:
max_area = 0
now_area = 0
for i in range(len_histogram):
if height[i] >= now_height:
now_area += height[i] * now_height
else:
max_area = max(max_area, now_area)
ans = max(max_area, ans)
return ans
| class Solution:
"""
@param height: A list of integer
@return: The area of largest rectangle in the histogram
"""
def largest_rectangle_area(self, height):
len_histogram = len(height)
ans = 0
height_list = sorter(height, reverse=True)
for now_height in height_list:
max_area = 0
now_area = 0
for i in range(len_histogram):
if height[i] >= now_height:
now_area += height[i] * now_height
else:
max_area = max(max_area, now_area)
ans = max(max_area, ans)
return ans |
# 17. Take 10 integers from keyboard using loop and print their average value on the screen. (use array to store inputs).
numbers = list(map(int, input("Enter 10 numbers:").split()))
if len(numbers) >= 10:
numbers = numbers[0:10]
print("10 Numbers are", numbers)
print("Average=", sum(numbers)/len(numbers))
| numbers = list(map(int, input('Enter 10 numbers:').split()))
if len(numbers) >= 10:
numbers = numbers[0:10]
print('10 Numbers are', numbers)
print('Average=', sum(numbers) / len(numbers)) |
def parse_parts(line):
space_separated_parts = line.split()
bounds = space_separated_parts[0].split('-')
char = space_separated_parts[1].split(':')[0]
password = space_separated_parts[2]
return int(bounds[0]), int(bounds[1]), char, password
def is_valid_first(min_req, max_req, letter, password):
letter_count = password.count(letter)
return letter_count >= min_req and letter_count <= max_req
# exactly one of the positions must equal the letter
# => logical 'xor' of the two comparisions, 'xor' is equivalent to '!='
def is_valid_second(pos1, pos2, letter, password):
return (password[pos1-1] == letter) != (password[pos2-1] == letter)
def main():
input_filename = 'input.txt'
star_number = 2
num_valid_pws = 0
with open(input_filename, 'r') as input:
for line in input:
num1, num2, letter, password = parse_parts(line)
if star_number == 1:
if is_valid_first(num1, num2, letter, password):
num_valid_pws += 1
elif star_number == 2:
if is_valid_second(num1, num2, letter, password):
num_valid_pws += 1
print('Number of valid passwords: {}'.format(num_valid_pws))
if __name__ == "__main__":
main() | def parse_parts(line):
space_separated_parts = line.split()
bounds = space_separated_parts[0].split('-')
char = space_separated_parts[1].split(':')[0]
password = space_separated_parts[2]
return (int(bounds[0]), int(bounds[1]), char, password)
def is_valid_first(min_req, max_req, letter, password):
letter_count = password.count(letter)
return letter_count >= min_req and letter_count <= max_req
def is_valid_second(pos1, pos2, letter, password):
return (password[pos1 - 1] == letter) != (password[pos2 - 1] == letter)
def main():
input_filename = 'input.txt'
star_number = 2
num_valid_pws = 0
with open(input_filename, 'r') as input:
for line in input:
(num1, num2, letter, password) = parse_parts(line)
if star_number == 1:
if is_valid_first(num1, num2, letter, password):
num_valid_pws += 1
elif star_number == 2:
if is_valid_second(num1, num2, letter, password):
num_valid_pws += 1
print('Number of valid passwords: {}'.format(num_valid_pws))
if __name__ == '__main__':
main() |
# Given a collection of numbers, return all possible permutations.
# For example,
# [1,2,3] have the following permutations:
# [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], and [3,2,1].
# [1,2] have the following permutations:
# [1,2], [2,1]
class Solution:
# @param {integer[]} nums
# @return {integer[][]}
def permute(self, nums):
# stack version(1):
ans = []
stack = [([], nums)]
while stack:
ret, nums = stack.pop(0)
if nums:
for i in range(len(nums)):
stack.append((ret + [nums[i]], nums[:i] + nums[i+1:]))
else:
ans.append(ret)
return ans
# stack version(2):
# if not nums:
# return nums
# res = [[nums[0]]]
# for i in range(1, len(nums)):
# for j in range(len(res)):
# tmp = res.pop(0)
# for k in range(len(tmp)+ 1):
# res.append(tmp[:k] + [nums[i]] + tmp[k:])
# return res
# recursion version:
# if len(nums) <= 1:
# return [nums]
# permutations = []
# for i in range(len(nums)):
# permutations.extend([ [nums[i]] + p for p in self.permute(nums[:i] + nums[i+1:]) ])
# return permutations
| class Solution:
def permute(self, nums):
ans = []
stack = [([], nums)]
while stack:
(ret, nums) = stack.pop(0)
if nums:
for i in range(len(nums)):
stack.append((ret + [nums[i]], nums[:i] + nums[i + 1:]))
else:
ans.append(ret)
return ans |
# import pytest
class TestDatabase:
def test___call__(self): # synced
assert True
def test_default_schema(self): # synced
assert True
def test_schema_names(self): # synced
assert True
def test_table_names(self): # synced
assert True
def test_view_names(self): # synced
assert True
def test_create_table(self): # synced
assert True
def test_drop_table(self): # synced
assert True
def test_refresh_table(self): # synced
assert True
def test_exists_table(self): # synced
assert True
def test_reset(self): # synced
assert True
def test__get_metadata(self): # synced
assert True
def test__cache_metadata(self): # synced
assert True
def test__post_reshape_soon(self): # synced
assert True
def test__sync_with_db(self): # synced
assert True
def test__reflect_database(self): # synced
assert True
def test__reflect_schema(self): # synced
assert True
def test__reflect_object(self): # synced
assert True
def test__autoload_models(self): # synced
assert True
def test_cls_instrument(self): # synced
assert True
def test__remove_expired_metadata_objects(self): # synced
assert True
def test__remove_object_if_exists(self): # synced
assert True
def test__name_from_object(self): # synced
assert True
def test__normalize_table(self): # synced
assert True
def test__table_name(self): # synced
assert True
def test_table_name(self): # synced
assert True
def test__scalar_name(self): # synced
assert True
def test_scalar_name(self): # synced
assert True
def test__collection_name(self): # synced
assert True
def test_collection_name(self): # synced
assert True
| class Testdatabase:
def test___call__(self):
assert True
def test_default_schema(self):
assert True
def test_schema_names(self):
assert True
def test_table_names(self):
assert True
def test_view_names(self):
assert True
def test_create_table(self):
assert True
def test_drop_table(self):
assert True
def test_refresh_table(self):
assert True
def test_exists_table(self):
assert True
def test_reset(self):
assert True
def test__get_metadata(self):
assert True
def test__cache_metadata(self):
assert True
def test__post_reshape_soon(self):
assert True
def test__sync_with_db(self):
assert True
def test__reflect_database(self):
assert True
def test__reflect_schema(self):
assert True
def test__reflect_object(self):
assert True
def test__autoload_models(self):
assert True
def test_cls_instrument(self):
assert True
def test__remove_expired_metadata_objects(self):
assert True
def test__remove_object_if_exists(self):
assert True
def test__name_from_object(self):
assert True
def test__normalize_table(self):
assert True
def test__table_name(self):
assert True
def test_table_name(self):
assert True
def test__scalar_name(self):
assert True
def test_scalar_name(self):
assert True
def test__collection_name(self):
assert True
def test_collection_name(self):
assert True |
class Vetor:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __repr__(self):
return 'Vetor (%r,%r)' % (self.x, self.y)
def __mul__(self, escalar):
x = self.x * escalar
y = self.y * escalar
return Vetor(x, y)
def __add__(self, outro):
x = self.x + outro.x
y = self.y + outro.y
return Vetor(x, y)
def __bool__(self):
return bool(self.x or self.y)
def __float__(self):
return float(self.x) + float(self.y)
v = Vetor(3, 5)
print(v*3)
v1 = Vetor(0, 0)
v2 = Vetor(8, 2)
print(v1+v2)
print(float(v2))
print(bool(v1))
print(bool(v2)) | class Vetor:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __repr__(self):
return 'Vetor (%r,%r)' % (self.x, self.y)
def __mul__(self, escalar):
x = self.x * escalar
y = self.y * escalar
return vetor(x, y)
def __add__(self, outro):
x = self.x + outro.x
y = self.y + outro.y
return vetor(x, y)
def __bool__(self):
return bool(self.x or self.y)
def __float__(self):
return float(self.x) + float(self.y)
v = vetor(3, 5)
print(v * 3)
v1 = vetor(0, 0)
v2 = vetor(8, 2)
print(v1 + v2)
print(float(v2))
print(bool(v1))
print(bool(v2)) |
# Databricks notebook source
# MAGIC %md # CCU002_03-D04-custom_tables
# MAGIC
# MAGIC **Description** This notebook creates custom tables, such as long format HES.
# MAGIC
# MAGIC **Author(s)** Venexia Walker
# COMMAND ----------
# MAGIC %md ## Define functions
# COMMAND ----------
# Define create table function by Sam Hollings
# Source: Workspaces/dars_nic_391419_j3w9t_collab/DATA_CURATION_wrang000_functions
def create_table(table_name:str, database_name:str='dars_nic_391419_j3w9t_collab', select_sql_script:str=None) -> None:
"""Will save to table from a global_temp view of the same name as the supplied table name (if no SQL script is supplied)
Otherwise, can supply a SQL script and this will be used to make the table with the specificed name, in the specifcied database."""
spark.conf.set("spark.sql.legacy.allowCreatingManagedTableUsingNonemptyLocation","true")
if select_sql_script is None:
select_sql_script = f"SELECT * FROM global_temp.{table_name}"
spark.sql(f"""CREATE TABLE {database_name}.{table_name} AS
{select_sql_script}
""")
spark.sql(f"ALTER TABLE {database_name}.{table_name} OWNER TO {database_name}")
def drop_table(table_name:str, database_name:str='dars_nic_391419_j3w9t_collab', if_exists=True):
if if_exists:
IF_EXISTS = 'IF EXISTS'
else:
IF_EXISTS = ''
spark.sql(f"DROP TABLE {IF_EXISTS} {database_name}.{table_name}")
# COMMAND ----------
# MAGIC %md ## Long format HES APC
# COMMAND ----------
# MAGIC %sql
# MAGIC CREATE OR REPLACE GLOBAL TEMP VIEW ccu002_03_hes_apc_longformat AS
# MAGIC SELECT *
# MAGIC FROM (SELECT PERSON_ID_DEID AS NHS_NUMBER_DEID,
# MAGIC ADMIDATE,
# MAGIC DISDATE,
# MAGIC EPISTART,
# MAGIC EPIEND,
# MAGIC EPIKEY,
# MAGIC STACK(40,
# MAGIC DIAG_3_01, 'DIAG_3_01',
# MAGIC DIAG_3_02, 'DIAG_3_02',
# MAGIC DIAG_3_03, 'DIAG_3_03',
# MAGIC DIAG_3_04, 'DIAG_3_04',
# MAGIC DIAG_3_05, 'DIAG_3_05',
# MAGIC DIAG_3_06, 'DIAG_3_06',
# MAGIC DIAG_3_07, 'DIAG_3_07',
# MAGIC DIAG_3_08, 'DIAG_3_08',
# MAGIC DIAG_3_09, 'DIAG_3_09',
# MAGIC DIAG_3_10, 'DIAG_3_10',
# MAGIC DIAG_3_11, 'DIAG_3_11',
# MAGIC DIAG_3_12, 'DIAG_3_12',
# MAGIC DIAG_3_13, 'DIAG_3_13',
# MAGIC DIAG_3_14, 'DIAG_3_14',
# MAGIC DIAG_3_15, 'DIAG_3_15',
# MAGIC DIAG_3_16, 'DIAG_3_16',
# MAGIC DIAG_3_17, 'DIAG_3_17',
# MAGIC DIAG_3_18, 'DIAG_3_18',
# MAGIC DIAG_3_19, 'DIAG_3_19',
# MAGIC DIAG_3_20, 'DIAG_3_20',
# MAGIC DIAG_4_01, 'DIAG_4_01',
# MAGIC DIAG_4_02, 'DIAG_4_02',
# MAGIC DIAG_4_03, 'DIAG_4_03',
# MAGIC DIAG_4_04, 'DIAG_4_04',
# MAGIC DIAG_4_05, 'DIAG_4_05',
# MAGIC DIAG_4_06, 'DIAG_4_06',
# MAGIC DIAG_4_07, 'DIAG_4_07',
# MAGIC DIAG_4_08, 'DIAG_4_08',
# MAGIC DIAG_4_09, 'DIAG_4_09',
# MAGIC DIAG_4_10, 'DIAG_4_10',
# MAGIC DIAG_4_11, 'DIAG_4_11',
# MAGIC DIAG_4_12, 'DIAG_4_12',
# MAGIC DIAG_4_13, 'DIAG_4_13',
# MAGIC DIAG_4_14, 'DIAG_4_14',
# MAGIC DIAG_4_15, 'DIAG_4_15',
# MAGIC DIAG_4_16, 'DIAG_4_16',
# MAGIC DIAG_4_17, 'DIAG_4_17',
# MAGIC DIAG_4_18, 'DIAG_4_18',
# MAGIC DIAG_4_19, 'DIAG_4_19',
# MAGIC DIAG_4_20, 'DIAG_4_20') AS (CODE, SOURCE)
# MAGIC FROM dars_nic_391419_j3w9t_collab.ccu002_03_hes_apc_all_years)
# MAGIC WHERE NHS_NUMBER_DEID IS NOT NULL AND CODE IS NOT NULL
# COMMAND ----------
drop_table('ccu002_03_hes_apc_longformat')
create_table('ccu002_03_hes_apc_longformat')
# COMMAND ----------
# MAGIC %md ## Long format HES APC surgery
# COMMAND ----------
# MAGIC %sql
# MAGIC CREATE OR REPLACE GLOBAL TEMP VIEW ccu002_03_hes_apc_opertn_longformat_tmp AS
# MAGIC SELECT *
# MAGIC FROM (SELECT PERSON_ID_DEID AS NHS_NUMBER_DEID,
# MAGIC ADMIDATE,
# MAGIC DISDATE,
# MAGIC EPISTART,
# MAGIC EPIEND,
# MAGIC EPIKEY,
# MAGIC STACK(48,
# MAGIC OPERTN_3_01, 'OPERTN_3_01',
# MAGIC OPERTN_3_02, 'OPERTN_3_02',
# MAGIC OPERTN_3_03, 'OPERTN_3_03',
# MAGIC OPERTN_3_04, 'OPERTN_3_04',
# MAGIC OPERTN_3_05, 'OPERTN_3_05',
# MAGIC OPERTN_3_06, 'OPERTN_3_06',
# MAGIC OPERTN_3_07, 'OPERTN_3_07',
# MAGIC OPERTN_3_08, 'OPERTN_3_08',
# MAGIC OPERTN_3_09, 'OPERTN_3_09',
# MAGIC OPERTN_3_10, 'OPERTN_3_10',
# MAGIC OPERTN_3_11, 'OPERTN_3_11',
# MAGIC OPERTN_3_12, 'OPERTN_3_12',
# MAGIC OPERTN_3_13, 'OPERTN_3_13',
# MAGIC OPERTN_3_14, 'OPERTN_3_14',
# MAGIC OPERTN_3_15, 'OPERTN_3_15',
# MAGIC OPERTN_3_16, 'OPERTN_3_16',
# MAGIC OPERTN_3_17, 'OPERTN_3_17',
# MAGIC OPERTN_3_18, 'OPERTN_3_18',
# MAGIC OPERTN_3_19, 'OPERTN_3_19',
# MAGIC OPERTN_3_20, 'OPERTN_3_20',
# MAGIC OPERTN_3_21, 'OPERTN_3_21',
# MAGIC OPERTN_3_22, 'OPERTN_3_22',
# MAGIC OPERTN_3_23, 'OPERTN_3_23',
# MAGIC OPERTN_3_24, 'OPERTN_3_24',
# MAGIC OPERTN_4_01, 'OPERTN_4_01',
# MAGIC OPERTN_4_02, 'OPERTN_4_02',
# MAGIC OPERTN_4_03, 'OPERTN_4_03',
# MAGIC OPERTN_4_04, 'OPERTN_4_04',
# MAGIC OPERTN_4_05, 'OPERTN_4_05',
# MAGIC OPERTN_4_06, 'OPERTN_4_06',
# MAGIC OPERTN_4_07, 'OPERTN_4_07',
# MAGIC OPERTN_4_08, 'OPERTN_4_08',
# MAGIC OPERTN_4_09, 'OPERTN_4_09',
# MAGIC OPERTN_4_10, 'OPERTN_4_10',
# MAGIC OPERTN_4_11, 'OPERTN_4_11',
# MAGIC OPERTN_4_12, 'OPERTN_4_12',
# MAGIC OPERTN_4_13, 'OPERTN_4_13',
# MAGIC OPERTN_4_14, 'OPERTN_4_14',
# MAGIC OPERTN_4_15, 'OPERTN_4_15',
# MAGIC OPERTN_4_16, 'OPERTN_4_16',
# MAGIC OPERTN_4_17, 'OPERTN_4_17',
# MAGIC OPERTN_4_18, 'OPERTN_4_18',
# MAGIC OPERTN_4_19, 'OPERTN_4_19',
# MAGIC OPERTN_4_20, 'OPERTN_4_20',
# MAGIC OPERTN_4_21, 'OPERTN_4_21',
# MAGIC OPERTN_4_22, 'OPERTN_4_22',
# MAGIC OPERTN_4_23, 'OPERTN_4_23',
# MAGIC OPERTN_4_24, 'OPERTN_4_24') AS (CODE, SOURCE)
# MAGIC FROM dars_nic_391419_j3w9t_collab.ccu002_03_hes_apc_all_years)
# MAGIC WHERE NHS_NUMBER_DEID IS NOT NULL
# COMMAND ----------
drop_table('ccu002_03_hes_apc_opertn_longformat')
create_table('ccu002_03_hes_apc_opertn_longformat')
# COMMAND ----------
# MAGIC %md ## Long format deaths
# COMMAND ----------
# MAGIC %sql
# MAGIC CREATE OR REPLACE GLOBAL TEMP VIEW ccu002_03_deaths_longformat AS
# MAGIC SELECT *
# MAGIC FROM (SELECT DEC_CONF_NHS_NUMBER_CLEAN_DEID AS NHS_NUMBER_DEID,
# MAGIC to_date(cast(REG_DATE_OF_DEATH as string), 'yyyyMMdd') AS DATE,
# MAGIC STACK(16,
# MAGIC S_UNDERLYING_COD_ICD10,'S_UNDERLYING_COD_ICD10',
# MAGIC S_COD_CODE_1, 'S_COD_CODE_1',
# MAGIC S_COD_CODE_2, 'S_COD_CODE_2',
# MAGIC S_COD_CODE_3, 'S_COD_CODE_3',
# MAGIC S_COD_CODE_4, 'S_COD_CODE_4',
# MAGIC S_COD_CODE_5, 'S_COD_CODE_5',
# MAGIC S_COD_CODE_6, 'S_COD_CODE_6',
# MAGIC S_COD_CODE_7, 'S_COD_CODE_7',
# MAGIC S_COD_CODE_8, 'S_COD_CODE_8',
# MAGIC S_COD_CODE_9, 'S_COD_CODE_9',
# MAGIC S_COD_CODE_10, 'S_COD_CODE_10',
# MAGIC S_COD_CODE_11, 'S_COD_CODE_11',
# MAGIC S_COD_CODE_12, 'S_COD_CODE_12',
# MAGIC S_COD_CODE_13, 'S_COD_CODE_13',
# MAGIC S_COD_CODE_14, 'S_COD_CODE_14',
# MAGIC S_COD_CODE_15, 'S_COD_CODE_15') AS (CODE, SOURCE)
# MAGIC FROM dars_nic_391419_j3w9t_collab.ccu002_03_deaths_dars_nic_391419_j3w9t)
# MAGIC WHERE NHS_NUMBER_DEID IS NOT NULL AND DATE IS NOT NULL AND CODE IS NOT NULL
# COMMAND ----------
drop_table('ccu002_03_deaths_longformat')
create_table('ccu002_03_deaths_longformat')
# COMMAND ----------
# MAGIC %md ## Long format SUS
# COMMAND ----------
# MAGIC %sql
# MAGIC CREATE OR REPLACE GLOBAL TEMP VIEW ccu002_03_sus_longformat AS
# MAGIC SELECT NHS_NUMBER_DEID,
# MAGIC START_DATE_HOSPITAL_PROVIDER_SPELL,
# MAGIC END_DATE_HOSPITAL_PROVIDER_SPELL,
# MAGIC EPISODE_START_DATE,
# MAGIC EPISODE_END_DATE,
# MAGIC EPISODE_DURATION,
# MAGIC EPISODE_NUMBER,
# MAGIC STACK(25,
# MAGIC LEFT(REGEXP_REPLACE(PRIMARY_DIAGNOSIS_CODE,'[-]|[\.]|[X\+]*$|[ ]|[\*]|[X\]|[X\-]*$|[X][A-Z]$|[A-Za-z\-]*$',''), 4), 'PRIMARY_DIAGNOSIS_CODE',
# MAGIC LEFT(REGEXP_REPLACE(SECONDARY_DIAGNOSIS_CODE_1,'[-]|[\.]|[X\+]*$|[ ]|[\*]|[X\]|[X\-]*$|[X][A-Z]$|[A-Za-z\-]*$',''), 4), 'SECONDARY_DIAGNOSIS_CODE_1',
# MAGIC LEFT(REGEXP_REPLACE(SECONDARY_DIAGNOSIS_CODE_2,'[-]|[\.]|[X\+]*$|[ ]|[\*]|[X\]|[X\-]*$|[X][A-Z]$|[A-Za-z\-]*$',''), 4), 'SECONDARY_DIAGNOSIS_CODE_2',
# MAGIC LEFT(REGEXP_REPLACE(SECONDARY_DIAGNOSIS_CODE_3,'[-]|[\.]|[X\+]*$|[ ]|[\*]|[X\]|[X\-]*$|[X][A-Z]$|[A-Za-z\-]*$',''), 4), 'SECONDARY_DIAGNOSIS_CODE_3',
# MAGIC LEFT(REGEXP_REPLACE(SECONDARY_DIAGNOSIS_CODE_4,'[-]|[\.]|[X\+]*$|[ ]|[\*]|[X\]|[X\-]*$|[X][A-Z]$|[A-Za-z\-]*$',''), 4), 'SECONDARY_DIAGNOSIS_CODE_4',
# MAGIC LEFT(REGEXP_REPLACE(SECONDARY_DIAGNOSIS_CODE_5,'[-]|[\.]|[X\+]*$|[ ]|[\*]|[X\]|[X\-]*$|[X][A-Z]$|[A-Za-z\-]*$',''), 4), 'SECONDARY_DIAGNOSIS_CODE_5',
# MAGIC LEFT(REGEXP_REPLACE(SECONDARY_DIAGNOSIS_CODE_6,'[-]|[\.]|[X\+]*$|[ ]|[\*]|[X\]|[X\-]*$|[X][A-Z]$|[A-Za-z\-]*$',''), 4), 'SECONDARY_DIAGNOSIS_CODE_6',
# MAGIC LEFT(REGEXP_REPLACE(SECONDARY_DIAGNOSIS_CODE_7,'[-]|[\.]|[X\+]*$|[ ]|[\*]|[X\]|[X\-]*$|[X][A-Z]$|[A-Za-z\-]*$',''), 4), 'SECONDARY_DIAGNOSIS_CODE_7',
# MAGIC LEFT(REGEXP_REPLACE(SECONDARY_DIAGNOSIS_CODE_8,'[-]|[\.]|[X\+]*$|[ ]|[\*]|[X\]|[X\-]*$|[X][A-Z]$|[A-Za-z\-]*$',''), 4), 'SECONDARY_DIAGNOSIS_CODE_8',
# MAGIC LEFT(REGEXP_REPLACE(SECONDARY_DIAGNOSIS_CODE_9,'[-]|[\.]|[X\+]*$|[ ]|[\*]|[X\]|[X\-]*$|[X][A-Z]$|[A-Za-z\-]*$',''), 4), 'SECONDARY_DIAGNOSIS_CODE_9',
# MAGIC LEFT(REGEXP_REPLACE(SECONDARY_DIAGNOSIS_CODE_10,'[-]|[\.]|[X\+]*$|[ ]|[\*]|[X\]|[X\-]*$|[X][A-Z]$|[A-Za-z\-]*$',''), 4), 'SECONDARY_DIAGNOSIS_CODE_10',
# MAGIC LEFT(REGEXP_REPLACE(SECONDARY_DIAGNOSIS_CODE_11,'[-]|[\.]|[X\+]*$|[ ]|[\*]|[X\]|[X\-]*$|[X][A-Z]$|[A-Za-z\-]*$',''), 4), 'SECONDARY_DIAGNOSIS_CODE_11',
# MAGIC LEFT(REGEXP_REPLACE(SECONDARY_DIAGNOSIS_CODE_12,'[-]|[\.]|[X\+]*$|[ ]|[\*]|[X\]|[X\-]*$|[X][A-Z]$|[A-Za-z\-]*$',''), 4), 'SECONDARY_DIAGNOSIS_CODE_12',
# MAGIC LEFT(REGEXP_REPLACE(SECONDARY_DIAGNOSIS_CODE_13,'[-]|[\.]|[X\+]*$|[ ]|[\*]|[X\]|[X\-]*$|[X][A-Z]$|[A-Za-z\-]*$',''), 4), 'SECONDARY_DIAGNOSIS_CODE_13',
# MAGIC LEFT(REGEXP_REPLACE(SECONDARY_DIAGNOSIS_CODE_14,'[-]|[\.]|[X\+]*$|[ ]|[\*]|[X\]|[X\-]*$|[X][A-Z]$|[A-Za-z\-]*$',''), 4), 'SECONDARY_DIAGNOSIS_CODE_14',
# MAGIC LEFT(REGEXP_REPLACE(SECONDARY_DIAGNOSIS_CODE_15,'[-]|[\.]|[X\+]*$|[ ]|[\*]|[X\]|[X\-]*$|[X][A-Z]$|[A-Za-z\-]*$',''), 4), 'SECONDARY_DIAGNOSIS_CODE_15',
# MAGIC LEFT(REGEXP_REPLACE(SECONDARY_DIAGNOSIS_CODE_16,'[-]|[\.]|[X\+]*$|[ ]|[\*]|[X\]|[X\-]*$|[X][A-Z]$|[A-Za-z\-]*$',''), 4), 'SECONDARY_DIAGNOSIS_CODE_16',
# MAGIC LEFT(REGEXP_REPLACE(SECONDARY_DIAGNOSIS_CODE_17,'[-]|[\.]|[X\+]*$|[ ]|[\*]|[X\]|[X\-]*$|[X][A-Z]$|[A-Za-z\-]*$',''), 4), 'SECONDARY_DIAGNOSIS_CODE_17',
# MAGIC LEFT(REGEXP_REPLACE(SECONDARY_DIAGNOSIS_CODE_18,'[-]|[\.]|[X\+]*$|[ ]|[\*]|[X\]|[X\-]*$|[X][A-Z]$|[A-Za-z\-]*$',''), 4), 'SECONDARY_DIAGNOSIS_CODE_18',
# MAGIC LEFT(REGEXP_REPLACE(SECONDARY_DIAGNOSIS_CODE_19,'[-]|[\.]|[X\+]*$|[ ]|[\*]|[X\]|[X\-]*$|[X][A-Z]$|[A-Za-z\-]*$',''), 4), 'SECONDARY_DIAGNOSIS_CODE_19',
# MAGIC LEFT(REGEXP_REPLACE(SECONDARY_DIAGNOSIS_CODE_20,'[-]|[\.]|[X\+]*$|[ ]|[\*]|[X\]|[X\-]*$|[X][A-Z]$|[A-Za-z\-]*$',''), 4), 'SECONDARY_DIAGNOSIS_CODE_20',
# MAGIC LEFT(REGEXP_REPLACE(SECONDARY_DIAGNOSIS_CODE_21,'[-]|[\.]|[X\+]*$|[ ]|[\*]|[X\]|[X\-]*$|[X][A-Z]$|[A-Za-z\-]*$',''), 4), 'SECONDARY_DIAGNOSIS_CODE_21',
# MAGIC LEFT(REGEXP_REPLACE(SECONDARY_DIAGNOSIS_CODE_22,'[-]|[\.]|[X\+]*$|[ ]|[\*]|[X\]|[X\-]*$|[X][A-Z]$|[A-Za-z\-]*$',''), 4), 'SECONDARY_DIAGNOSIS_CODE_22',
# MAGIC LEFT(REGEXP_REPLACE(SECONDARY_DIAGNOSIS_CODE_23,'[-]|[\.]|[X\+]*$|[ ]|[\*]|[X\]|[X\-]*$|[X][A-Z]$|[A-Za-z\-]*$',''), 4), 'SECONDARY_DIAGNOSIS_CODE_23',
# MAGIC LEFT(REGEXP_REPLACE(SECONDARY_DIAGNOSIS_CODE_24,'[-]|[\.]|[X\+]*$|[ ]|[\*]|[X\]|[X\-]*$|[X][A-Z]$|[A-Za-z\-]*$',''), 4), 'SECONDARY_DIAGNOSIS_CODE_24') AS (CODE,SOURCE)
# MAGIC FROM dars_nic_391419_j3w9t_collab.ccu002_03_sus_dars_nic_391419_j3w9t
# COMMAND ----------
drop_table('ccu002_03_sus_longformat')
create_table('ccu002_03_sus_longformat')
# COMMAND ----------
# MAGIC %md ##LSOA region lookup
# COMMAND ----------
# MAGIC %sql
# MAGIC -- Code developed by Sam Hollings and Spencer Keene
# MAGIC CREATE OR REPLACE GLOBAL TEMP VIEW ccu002_03_lsoa_region_lookup AS
# MAGIC with
# MAGIC curren_chd_geo_listings as (SELECT * FROM dss_corporate.ons_chd_geo_listings WHERE IS_CURRENT = 1),
# MAGIC lsoa_auth as (
# MAGIC SELECT e01.geography_code as lsoa_code, e01.geography_name lsoa_name,
# MAGIC e02.geography_code as msoa_code, e02.geography_name as msoa_name,
# MAGIC e0789.geography_code as authority_code, e0789.geography_name as authority_name,
# MAGIC e0789.parent_geography_code as authority_parent_geography
# MAGIC FROM curren_chd_geo_listings e01
# MAGIC LEFT JOIN curren_chd_geo_listings e02 on e02.geography_code = e01.parent_geography_code
# MAGIC LEFT JOIN curren_chd_geo_listings e0789 on e0789.geography_code = e02.parent_geography_code
# MAGIC WHERE e01.geography_code like 'E01%' and e02.geography_code like 'E02%'
# MAGIC ),
# MAGIC auth_county as (
# MAGIC SELECT lsoa_code, lsoa_name,
# MAGIC msoa_code, msoa_name,
# MAGIC authority_code, authority_name,
# MAGIC e10.geography_code as county_code, e10.geography_name as county_name,
# MAGIC e10.parent_geography_code as parent_geography
# MAGIC FROM
# MAGIC lsoa_auth
# MAGIC LEFT JOIN dss_corporate.ons_chd_geo_listings e10 on e10.geography_code = lsoa_auth.authority_parent_geography
# MAGIC
# MAGIC WHERE LEFT(authority_parent_geography,3) = 'E10'
# MAGIC ),
# MAGIC auth_met_county as (
# MAGIC SELECT lsoa_code, lsoa_name,
# MAGIC msoa_code, msoa_name,
# MAGIC authority_code, authority_name,
# MAGIC NULL as county_code, NULL as county_name,
# MAGIC lsoa_auth.authority_parent_geography as region_code
# MAGIC FROM lsoa_auth
# MAGIC WHERE LEFT(authority_parent_geography,3) = 'E12'
# MAGIC ),
# MAGIC lsoa_region_code as (
# MAGIC SELECT lsoa_code, lsoa_name,
# MAGIC msoa_code, msoa_name,
# MAGIC authority_code, authority_name,
# MAGIC county_code, county_name, auth_county.parent_geography as region_code
# MAGIC FROM auth_county
# MAGIC UNION ALL
# MAGIC SELECT lsoa_code, lsoa_name,
# MAGIC msoa_code, msoa_name,
# MAGIC authority_code, authority_name,
# MAGIC county_code, county_name, region_code
# MAGIC FROM auth_met_county
# MAGIC ),
# MAGIC lsoa_region as (
# MAGIC SELECT lsoa_code, lsoa_name,
# MAGIC msoa_code, msoa_name,
# MAGIC authority_code, authority_name,
# MAGIC county_code, county_name, region_code, e12.geography_name as region_name FROM lsoa_region_code
# MAGIC LEFT JOIN dss_corporate.ons_chd_geo_listings e12 on lsoa_region_code.region_code = e12.geography_code
# MAGIC )
# MAGIC SELECT * FROM lsoa_region
# COMMAND ----------
drop_table('ccu002_03_lsoa_region_lookup')
create_table('ccu002_03_lsoa_region_lookup')
# COMMAND ----------
# MAGIC %md ## COVID19 tractory table (run on 3 August 2021)
# COMMAND ----------
# MAGIC %sql
# MAGIC CREATE OR REPLACE GLOBAL TEMP VIEW ccu002_03_ccu013_covid_trajectory AS
# MAGIC SELECT * FROM dars_nic_391419_j3w9t_collab.ccu013_covid_trajectory
# COMMAND ----------
drop_table('ccu002_03_ccu013_covid_trajectory')
create_table('ccu002_03_ccu013_covid_trajectory')
| def create_table(table_name: str, database_name: str='dars_nic_391419_j3w9t_collab', select_sql_script: str=None) -> None:
"""Will save to table from a global_temp view of the same name as the supplied table name (if no SQL script is supplied)
Otherwise, can supply a SQL script and this will be used to make the table with the specificed name, in the specifcied database."""
spark.conf.set('spark.sql.legacy.allowCreatingManagedTableUsingNonemptyLocation', 'true')
if select_sql_script is None:
select_sql_script = f'SELECT * FROM global_temp.{table_name}'
spark.sql(f'CREATE TABLE {database_name}.{table_name} AS\n {select_sql_script}\n ')
spark.sql(f'ALTER TABLE {database_name}.{table_name} OWNER TO {database_name}')
def drop_table(table_name: str, database_name: str='dars_nic_391419_j3w9t_collab', if_exists=True):
if if_exists:
if_exists = 'IF EXISTS'
else:
if_exists = ''
spark.sql(f'DROP TABLE {IF_EXISTS} {database_name}.{table_name}')
drop_table('ccu002_03_hes_apc_longformat')
create_table('ccu002_03_hes_apc_longformat')
drop_table('ccu002_03_hes_apc_opertn_longformat')
create_table('ccu002_03_hes_apc_opertn_longformat')
drop_table('ccu002_03_deaths_longformat')
create_table('ccu002_03_deaths_longformat')
drop_table('ccu002_03_sus_longformat')
create_table('ccu002_03_sus_longformat')
drop_table('ccu002_03_lsoa_region_lookup')
create_table('ccu002_03_lsoa_region_lookup')
drop_table('ccu002_03_ccu013_covid_trajectory')
create_table('ccu002_03_ccu013_covid_trajectory') |
SUBJ_REPORT = "Problem Report: ExCEED Labs"
ERROR_NO_EMAIL_TO_GET_AHOLD = "We need to know how to get ahold of you!"
ERROR_NO_REPORT = "Don't forget to add your problem report or request!"
ERROR_NOT_SUBMITTED = "There was a problem with your submission. Please try again!"
SUCCESS_REPORT_SUBMITTED = "Success! Your problem report or request has been submitted to the ExCEED Labs directors."
| subj_report = 'Problem Report: ExCEED Labs'
error_no_email_to_get_ahold = 'We need to know how to get ahold of you!'
error_no_report = "Don't forget to add your problem report or request!"
error_not_submitted = 'There was a problem with your submission. Please try again!'
success_report_submitted = 'Success! Your problem report or request has been submitted to the ExCEED Labs directors.' |
"""
URL: https://codeforces.com/problemset/problem/144/A
Author: Safiul Kabir [safiulanik at gmail.com]
"""
n = int(input())
mil = list(map(int, input().split()))
count = 0
maxx_index = mil.index(max(mil))
while maxx_index - 1 >= 0:
mil[maxx_index - 1], mil[maxx_index] = mil[maxx_index], mil[maxx_index - 1]
count += 1
maxx_index -= 1
mil = mil[::-1]
minn_index = mil.index(min(mil))
while minn_index - 1 >= 0:
mil[minn_index - 1], mil[minn_index] = mil[minn_index], mil[minn_index - 1]
count += 1
minn_index -= 1
print(count)
| """
URL: https://codeforces.com/problemset/problem/144/A
Author: Safiul Kabir [safiulanik at gmail.com]
"""
n = int(input())
mil = list(map(int, input().split()))
count = 0
maxx_index = mil.index(max(mil))
while maxx_index - 1 >= 0:
(mil[maxx_index - 1], mil[maxx_index]) = (mil[maxx_index], mil[maxx_index - 1])
count += 1
maxx_index -= 1
mil = mil[::-1]
minn_index = mil.index(min(mil))
while minn_index - 1 >= 0:
(mil[minn_index - 1], mil[minn_index]) = (mil[minn_index], mil[minn_index - 1])
count += 1
minn_index -= 1
print(count) |
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
#
# FreeType high-level python API - Copyright 2011-2015 Nicolas P. Rougier
# Distributed under the terms of the new BSD license.
#
# -----------------------------------------------------------------------------
"""
A list of valid values for the 'platform_id' identifier code in FT_CharMapRec
and FT_SfntName structures.
TT_PLATFORM_APPLE_UNICODE
Used by Apple to indicate a Unicode character map and/or name entry. See
TT_APPLE_ID_XXX for corresponding 'encoding_id' values. Note that name
entries in this format are coded as big-endian UCS-2 character codes only.
TT_PLATFORM_MACINTOSH
Used by Apple to indicate a MacOS-specific charmap and/or name entry. See
TT_MAC_ID_XXX for corresponding 'encoding_id' values. Note that most TrueType
fonts contain an Apple roman charmap to be usable on MacOS systems (even if
they contain a Microsoft charmap as well).
TT_PLATFORM_ISO
This value was used to specify ISO/IEC 10646 charmaps. It is however now
deprecated. See TT_ISO_ID_XXX for a list of corresponding 'encoding_id'
values.
TT_PLATFORM_MICROSOFT
Used by Microsoft to indicate Windows-specific charmaps. See TT_MS_ID_XXX for
a list of corresponding 'encoding_id' values. Note that most fonts contain a
Unicode charmap using (TT_PLATFORM_MICROSOFT, TT_MS_ID_UNICODE_CS).
TT_PLATFORM_CUSTOM
Used to indicate application-specific charmaps.
TT_PLATFORM_ADOBE
This value isn't part of any font format specification, but is used by
FreeType to report Adobe-specific charmaps in an FT_CharMapRec structure. See
TT_ADOBE_ID_XXX.
"""
TT_PLATFORMS = {
'TT_PLATFORM_APPLE_UNICODE' : 0,
'TT_PLATFORM_MACINTOSH' : 1,
'TT_PLATFORM_ISO' : 2, # deprecated
'TT_PLATFORM_MICROSOFT' : 3,
'TT_PLATFORM_CUSTOM' : 4,
'TT_PLATFORM_ADOBE' : 7} # artificial
globals().update(TT_PLATFORMS)
| """
A list of valid values for the 'platform_id' identifier code in FT_CharMapRec
and FT_SfntName structures.
TT_PLATFORM_APPLE_UNICODE
Used by Apple to indicate a Unicode character map and/or name entry. See
TT_APPLE_ID_XXX for corresponding 'encoding_id' values. Note that name
entries in this format are coded as big-endian UCS-2 character codes only.
TT_PLATFORM_MACINTOSH
Used by Apple to indicate a MacOS-specific charmap and/or name entry. See
TT_MAC_ID_XXX for corresponding 'encoding_id' values. Note that most TrueType
fonts contain an Apple roman charmap to be usable on MacOS systems (even if
they contain a Microsoft charmap as well).
TT_PLATFORM_ISO
This value was used to specify ISO/IEC 10646 charmaps. It is however now
deprecated. See TT_ISO_ID_XXX for a list of corresponding 'encoding_id'
values.
TT_PLATFORM_MICROSOFT
Used by Microsoft to indicate Windows-specific charmaps. See TT_MS_ID_XXX for
a list of corresponding 'encoding_id' values. Note that most fonts contain a
Unicode charmap using (TT_PLATFORM_MICROSOFT, TT_MS_ID_UNICODE_CS).
TT_PLATFORM_CUSTOM
Used to indicate application-specific charmaps.
TT_PLATFORM_ADOBE
This value isn't part of any font format specification, but is used by
FreeType to report Adobe-specific charmaps in an FT_CharMapRec structure. See
TT_ADOBE_ID_XXX.
"""
tt_platforms = {'TT_PLATFORM_APPLE_UNICODE': 0, 'TT_PLATFORM_MACINTOSH': 1, 'TT_PLATFORM_ISO': 2, 'TT_PLATFORM_MICROSOFT': 3, 'TT_PLATFORM_CUSTOM': 4, 'TT_PLATFORM_ADOBE': 7}
globals().update(TT_PLATFORMS) |
# Sum square difference
# https://projecteuler.net/problem=6
def solve(n):
sn = (n*(n+1)//2) * (n*(n+1)//2)
sn2 = n*(n+1)*(2*n+1)//6 # sum of first n squared natural numbers
return abs(sn - sn2)
print(solve(100)) | def solve(n):
sn = n * (n + 1) // 2 * (n * (n + 1) // 2)
sn2 = n * (n + 1) * (2 * n + 1) // 6
return abs(sn - sn2)
print(solve(100)) |
_base_ = [
'../_base_/models/paa_distil_fpn.py',
'../_base_/datasets/coco_detection.py',
'../_base_/schedules/schedule_1x.py',
'../_base_/default_runtime.py'
]
model = dict(
type='LAD',
# student
pretrained='torchvision://resnet50',
backbone=dict(depth=50),
bbox_head=dict(type='PAA_LAD_Head'),
# teacher
teacher_pretrained="http://download.openmmlab.com/mmdetection/v2.0/paa/paa_r101_fpn_1x_coco/paa_r101_fpn_1x_coco_20200821-0a1825a4.pth",
teacher_backbone=dict(depth=101),
teacher_bbox_head=dict(type='PAA_LAD_Head'))
# optimizer
optimizer = dict(lr=0.01)
data = dict(samples_per_gpu=4, workers_per_gpu=4)
optimizer_config = dict(
_delete_=True, grad_clip=dict(max_norm=35, norm_type=2))
| _base_ = ['../_base_/models/paa_distil_fpn.py', '../_base_/datasets/coco_detection.py', '../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py']
model = dict(type='LAD', pretrained='torchvision://resnet50', backbone=dict(depth=50), bbox_head=dict(type='PAA_LAD_Head'), teacher_pretrained='http://download.openmmlab.com/mmdetection/v2.0/paa/paa_r101_fpn_1x_coco/paa_r101_fpn_1x_coco_20200821-0a1825a4.pth', teacher_backbone=dict(depth=101), teacher_bbox_head=dict(type='PAA_LAD_Head'))
optimizer = dict(lr=0.01)
data = dict(samples_per_gpu=4, workers_per_gpu=4)
optimizer_config = dict(_delete_=True, grad_clip=dict(max_norm=35, norm_type=2)) |
class Solution(object):
def solveNQueens(self, n):
def dfs(queens, xy_sub, xy_plus):
row = len(queens)
if row == n:
result.append(queens)
return None
for col in range(n):
if col not in queens and col + row not in xy_plus and row - col not in xy_sub:
dfs(queens + [col], xy_sub + [row - col], xy_plus + [row + col])
result = []
dfs([], [], [])
return [["."* i + "Q" + "."* (n -i-1) for i in s] for s in result] | class Solution(object):
def solve_n_queens(self, n):
def dfs(queens, xy_sub, xy_plus):
row = len(queens)
if row == n:
result.append(queens)
return None
for col in range(n):
if col not in queens and col + row not in xy_plus and (row - col not in xy_sub):
dfs(queens + [col], xy_sub + [row - col], xy_plus + [row + col])
result = []
dfs([], [], [])
return [['.' * i + 'Q' + '.' * (n - i - 1) for i in s] for s in result] |
def merge_sort_time(job_list):
'''
sorts the list by timestamp
:return:
array
'''
if len(job_list) > 1:
mid = len(job_list) // 2
lefthalf = job_list[:mid]
righthalf = job_list[mid:]
merge_sort_time(lefthalf)
merge_sort_time(righthalf)
i = 0
j = 0
k = 0
while i < len(lefthalf) and j < len(righthalf):
if lefthalf[i]['time'] > righthalf[j]['time']:
job_list[k] = lefthalf[i]
i = i + 1
else:
job_list[k] = righthalf[j]
j = j + 1
k = k + 1
while i < len(lefthalf):
job_list[k] = lefthalf[i]
i = i + 1
k = k + 1
while j < len(righthalf):
job_list[k] = righthalf[j]
j = j + 1
k = k + 1 | def merge_sort_time(job_list):
"""
sorts the list by timestamp
:return:
array
"""
if len(job_list) > 1:
mid = len(job_list) // 2
lefthalf = job_list[:mid]
righthalf = job_list[mid:]
merge_sort_time(lefthalf)
merge_sort_time(righthalf)
i = 0
j = 0
k = 0
while i < len(lefthalf) and j < len(righthalf):
if lefthalf[i]['time'] > righthalf[j]['time']:
job_list[k] = lefthalf[i]
i = i + 1
else:
job_list[k] = righthalf[j]
j = j + 1
k = k + 1
while i < len(lefthalf):
job_list[k] = lefthalf[i]
i = i + 1
k = k + 1
while j < len(righthalf):
job_list[k] = righthalf[j]
j = j + 1
k = k + 1 |
#
# PySNMP MIB module CHARACTER-MIB (http://pysnmp.sf.net)
# ASN.1 source http://mibs.snmplabs.com:80/asn1/CHARACTER-MIB
# Produced by pysmi-0.0.7 at Sun Feb 14 00:06:47 2016
# On host bldfarm platform Linux version 4.1.13-100.fc21.x86_64 by user goose
# Using Python version 3.5.0 (default, Jan 5 2016, 17:11:52)
#
( ObjectIdentifier, OctetString, Integer, ) = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "OctetString", "Integer")
( NamedValues, ) = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
( ConstraintsIntersection, ValueRangeConstraint, ConstraintsUnion, ValueSizeConstraint, SingleValueConstraint, ) = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ValueRangeConstraint", "ConstraintsUnion", "ValueSizeConstraint", "SingleValueConstraint")
( InterfaceIndex, ) = mibBuilder.importSymbols("IF-MIB", "InterfaceIndex")
( ObjectGroup, NotificationGroup, ModuleCompliance, ) = mibBuilder.importSymbols("SNMPv2-CONF", "ObjectGroup", "NotificationGroup", "ModuleCompliance")
( MibIdentifier, transmission, Bits, Integer32, IpAddress, Gauge32, mib_2, Counter32, Counter64, MibScalar, MibTable, MibTableRow, MibTableColumn, iso, Unsigned32, ObjectIdentity, TimeTicks, ModuleIdentity, NotificationType, ) = mibBuilder.importSymbols("SNMPv2-SMI", "MibIdentifier", "transmission", "Bits", "Integer32", "IpAddress", "Gauge32", "mib-2", "Counter32", "Counter64", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "iso", "Unsigned32", "ObjectIdentity", "TimeTicks", "ModuleIdentity", "NotificationType")
( TextualConvention, DisplayString, AutonomousType, InstancePointer, ) = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString", "AutonomousType", "InstancePointer")
char = ModuleIdentity((1, 3, 6, 1, 2, 1, 19))
if mibBuilder.loadTexts: char.setLastUpdated('9405261700Z')
if mibBuilder.loadTexts: char.setOrganization('IETF Character MIB Working Group')
if mibBuilder.loadTexts: char.setContactInfo(' Bob Stewart\n Postal: Xyplex, Inc.\n 295 Foster Street\n Littleton, MA 01460\n\n Tel: 508-952-4816\n Fax: 508-952-4887\n\n E-mail: rlstewart@eng.xyplex.com')
if mibBuilder.loadTexts: char.setDescription('The MIB module for character stream devices.')
class PortIndex(Integer32, TextualConvention):
displayHint = 'd'
charNumber = MibScalar((1, 3, 6, 1, 2, 1, 19, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: charNumber.setDescription('The number of entries in charPortTable, regardless\n of their current state.')
charPortTable = MibTable((1, 3, 6, 1, 2, 1, 19, 2), )
if mibBuilder.loadTexts: charPortTable.setDescription('A list of port entries. The number of entries is\n given by the value of charNumber.')
charPortEntry = MibTableRow((1, 3, 6, 1, 2, 1, 19, 2, 1), ).setIndexNames((0, "CHARACTER-MIB", "charPortIndex"))
if mibBuilder.loadTexts: charPortEntry.setDescription('Status and parameter values for a character port.')
charPortIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 19, 2, 1, 1), PortIndex()).setMaxAccess("readonly")
if mibBuilder.loadTexts: charPortIndex.setDescription('A unique value for each character port, perhaps\n corresponding to the same value of ifIndex when the\n character port is associated with a hardware port\n represented by an ifIndex.')
charPortName = MibTableColumn((1, 3, 6, 1, 2, 1, 19, 2, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0,32))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: charPortName.setDescription('An administratively assigned name for the port,\n typically with some local significance.')
charPortType = MibTableColumn((1, 3, 6, 1, 2, 1, 19, 2, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2,))).clone(namedValues=NamedValues(("physical", 1), ("virtual", 2),))).setMaxAccess("readonly")
if mibBuilder.loadTexts: charPortType.setDescription("The port's type, 'physical' if the port represents\n an external hardware connector, 'virtual' if it does\n not.")
charPortHardware = MibTableColumn((1, 3, 6, 1, 2, 1, 19, 2, 1, 4), AutonomousType()).setMaxAccess("readonly")
if mibBuilder.loadTexts: charPortHardware.setDescription("A reference to hardware MIB definitions specific to\n a physical port's external connector. For example,\n if the connector is RS-232, then the value of this\n object refers to a MIB sub-tree defining objects\n specific to RS-232. If an agent is not configured\n to have such values, the agent returns the object\n identifier:\n\n nullHardware OBJECT IDENTIFIER ::= { 0 0 }\n ")
charPortReset = MibTableColumn((1, 3, 6, 1, 2, 1, 19, 2, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2,))).clone(namedValues=NamedValues(("ready", 1), ("execute", 2),))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: charPortReset.setDescription("A control to force the port into a clean, initial\n state, both hardware and software, disconnecting all\n the port's existing sessions. In response to a\n get-request or get-next-request, the agent always\n returns 'ready' as the value. Setting the value to\n 'execute' causes a reset.")
charPortAdminStatus = MibTableColumn((1, 3, 6, 1, 2, 1, 19, 2, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4,))).clone(namedValues=NamedValues(("enabled", 1), ("disabled", 2), ("off", 3), ("maintenance", 4),))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: charPortAdminStatus.setDescription("The port's desired state, independent of flow\n control. 'enabled' indicates that the port is\n allowed to pass characters and form new sessions.\n 'disabled' indicates that the port is allowed to\n pass characters but not form new sessions. 'off'\n indicates that the port is not allowed to pass\n characters or have any sessions. 'maintenance'\n indicates a maintenance mode, exclusive of normal\n operation, such as running a test.\n\n 'enabled' corresponds to ifAdminStatus 'up'.\n 'disabled' and 'off' correspond to ifAdminStatus\n 'down'. 'maintenance' corresponds to ifAdminStatus\n 'test'.")
charPortOperStatus = MibTableColumn((1, 3, 6, 1, 2, 1, 19, 2, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5,))).clone(namedValues=NamedValues(("up", 1), ("down", 2), ("maintenance", 3), ("absent", 4), ("active", 5),))).setMaxAccess("readonly")
if mibBuilder.loadTexts: charPortOperStatus.setDescription("The port's actual, operational state, independent\n of flow control. 'up' indicates able to function\n normally. 'down' indicates inability to function\n for administrative or operational reasons.\n 'maintenance' indicates a maintenance mode,\n exclusive of normal operation, such as running a\n test. 'absent' indicates that port hardware is not\n present. 'active' indicates up with a user present\n (e.g. logged in).\n\n 'up' and 'active' correspond to ifOperStatus 'up'.\n 'down' and 'absent' correspond to ifOperStatus\n 'down'. 'maintenance' corresponds to ifOperStatus\n 'test'.")
charPortLastChange = MibTableColumn((1, 3, 6, 1, 2, 1, 19, 2, 1, 8), TimeTicks()).setMaxAccess("readonly")
if mibBuilder.loadTexts: charPortLastChange.setDescription('The value of sysUpTime at the time the port entered\n its current operational state. If the current state\n was entered prior to the last reinitialization of\n the local network management subsystem, then this\n object contains a zero value.')
charPortInFlowType = MibTableColumn((1, 3, 6, 1, 2, 1, 19, 2, 1, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5,))).clone(namedValues=NamedValues(("none", 1), ("xonXoff", 2), ("hardware", 3), ("ctsRts", 4), ("dsrDtr", 5),))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: charPortInFlowType.setDescription("The port's type of input flow control. 'none'\n indicates no flow control at this level or below.\n 'xonXoff' indicates software flow control by\n recognizing XON and XOFF characters. 'hardware'\n indicates flow control delegated to the lower level,\n for example a parallel port.\n\n 'ctsRts' and 'dsrDtr' are specific to RS-232-like\n ports. Although not architecturally pure, they are\n included here for simplicity's sake.")
charPortOutFlowType = MibTableColumn((1, 3, 6, 1, 2, 1, 19, 2, 1, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5,))).clone(namedValues=NamedValues(("none", 1), ("xonXoff", 2), ("hardware", 3), ("ctsRts", 4), ("dsrDtr", 5),))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: charPortOutFlowType.setDescription("The port's type of output flow control. 'none'\n indicates no flow control at this level or below.\n 'xonXoff' indicates software flow control by\n recognizing XON and XOFF characters. 'hardware'\n indicates flow control delegated to the lower level,\n for example a parallel port.\n\n 'ctsRts' and 'dsrDtr' are specific to RS-232-like\n ports. Although not architecturally pure, they are\n included here for simplicy's sake.")
charPortInFlowState = MibTableColumn((1, 3, 6, 1, 2, 1, 19, 2, 1, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4,))).clone(namedValues=NamedValues(("none", 1), ("unknown", 2), ("stop", 3), ("go", 4),))).setMaxAccess("readonly")
if mibBuilder.loadTexts: charPortInFlowState.setDescription("The current operational state of input flow control\n on the port. 'none' indicates not applicable.\n 'unknown' indicates this level does not know.\n 'stop' indicates flow not allowed. 'go' indicates\n flow allowed.")
charPortOutFlowState = MibTableColumn((1, 3, 6, 1, 2, 1, 19, 2, 1, 12), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4,))).clone(namedValues=NamedValues(("none", 1), ("unknown", 2), ("stop", 3), ("go", 4),))).setMaxAccess("readonly")
if mibBuilder.loadTexts: charPortOutFlowState.setDescription("The current operational state of output flow\n control on the port. 'none' indicates not\n applicable. 'unknown' indicates this level does not\n know. 'stop' indicates flow not allowed. 'go'\n indicates flow allowed.")
charPortInCharacters = MibTableColumn((1, 3, 6, 1, 2, 1, 19, 2, 1, 13), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: charPortInCharacters.setDescription("Total number of characters detected as input from\n the port since system re-initialization and while\n the port operational state was 'up', 'active', or\n 'maintenance', including, for example, framing, flow\n control (i.e. XON and XOFF), each occurrence of a\n BREAK condition, locally-processed input, and input\n sent to all sessions.")
charPortOutCharacters = MibTableColumn((1, 3, 6, 1, 2, 1, 19, 2, 1, 14), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: charPortOutCharacters.setDescription("Total number of characters detected as output to\n the port since system re-initialization and while\n the port operational state was 'up', 'active', or\n 'maintenance', including, for example, framing, flow\n control (i.e. XON and XOFF), each occurrence of a\n BREAK condition, locally-created output, and output\n received from all sessions.")
charPortAdminOrigin = MibTableColumn((1, 3, 6, 1, 2, 1, 19, 2, 1, 15), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4,))).clone(namedValues=NamedValues(("dynamic", 1), ("network", 2), ("local", 3), ("none", 4),))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: charPortAdminOrigin.setDescription("The administratively allowed origin for\n establishing session on the port. 'dynamic' allows\n 'network' or 'local' session establishment. 'none'\n disallows session establishment.")
charPortSessionMaximum = MibTableColumn((1, 3, 6, 1, 2, 1, 19, 2, 1, 16), Integer32().subtype(subtypeSpec=ValueRangeConstraint(-1,2147483647))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: charPortSessionMaximum.setDescription('The maximum number of concurrent sessions allowed\n on the port. A value of -1 indicates no maximum.\n Setting the maximum to less than the current number\n of sessions has unspecified results.')
charPortSessionNumber = MibTableColumn((1, 3, 6, 1, 2, 1, 19, 2, 1, 17), Gauge32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: charPortSessionNumber.setDescription('The number of open sessions on the port that are in\n the connecting, connected, or disconnecting state.')
charPortSessionIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 19, 2, 1, 18), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0,2147483647))).setMaxAccess("readonly")
if mibBuilder.loadTexts: charPortSessionIndex.setDescription("The value of charSessIndex for the port's first or\n only active session. If the port has no active\n session, the agent returns the value zero.")
charPortInFlowTypes = MibTableColumn((1, 3, 6, 1, 2, 1, 19, 2, 1, 19), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1,1)).setFixedLength(1)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: charPortInFlowTypes.setDescription("The port's types of input flow control at the\n software level. Hardware-level flow control is\n independently controlled by the appropriate\n hardware-level MIB.\n\n A value of zero indicates no flow control.\n Depending on the specific implementation, any or\n all combinations of flow control may be chosen by\n adding the values:\n\n 128 xonXoff, recognizing XON and XOFF characters\n 64 enqHost, ENQ/ACK to allow input to host\n 32 enqTerm, ACK to allow output to port\n ")
charPortOutFlowTypes = MibTableColumn((1, 3, 6, 1, 2, 1, 19, 2, 1, 20), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1,1)).setFixedLength(1)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: charPortOutFlowTypes.setDescription("The port's types of output flow control at the\n software level. Hardware-level flow control is\n independently controlled by the appropriate\n hardware-level MIB.\n\n A value of zero indicates no flow control.\n Depending on the specific implementation, any or\n all combinations of flow control may be chosen by\n adding the values:\n\n 128 xonXoff, recognizing XON and XOFF characters\n 64 enqHost, ENQ/ACK to allow input to host\n 32 enqTerm, ACK to allow output to port\n ")
charPortLowerIfIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 19, 2, 1, 21), InterfaceIndex()).setMaxAccess("readonly")
if mibBuilder.loadTexts: charPortLowerIfIndex.setDescription('The ifIndex value of the lower level hardware supporting\n this character port, zero if none.')
charSessTable = MibTable((1, 3, 6, 1, 2, 1, 19, 3), )
if mibBuilder.loadTexts: charSessTable.setDescription('A list of port session entries.')
charSessEntry = MibTableRow((1, 3, 6, 1, 2, 1, 19, 3, 1), ).setIndexNames((0, "CHARACTER-MIB", "charSessPortIndex"), (0, "CHARACTER-MIB", "charSessIndex"))
if mibBuilder.loadTexts: charSessEntry.setDescription('Status and parameter values for a character port\n session.')
charSessPortIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 19, 3, 1, 1), PortIndex()).setMaxAccess("readonly")
if mibBuilder.loadTexts: charSessPortIndex.setDescription('The value of charPortIndex for the port to which\n this session belongs.')
charSessIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 19, 3, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1,2147483647))).setMaxAccess("readonly")
if mibBuilder.loadTexts: charSessIndex.setDescription('The session index in the context of the port, a\n non-zero positive integer. Session indexes within a\n port need not be sequential. Session indexes may be\n reused for different ports. For example, port 1 and\n port 3 may both have a session 2 at the same time.\n Session indexes may have any valid integer value,\n with any meaning convenient to the agent\n implementation.')
charSessKill = MibTableColumn((1, 3, 6, 1, 2, 1, 19, 3, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2,))).clone(namedValues=NamedValues(("ready", 1), ("execute", 2),))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: charSessKill.setDescription("A control to terminate the session. In response to\n a get-request or get-next-request, the agent always\n returns 'ready' as the value. Setting the value to\n 'execute' causes termination.")
charSessState = MibTableColumn((1, 3, 6, 1, 2, 1, 19, 3, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3,))).clone(namedValues=NamedValues(("connecting", 1), ("connected", 2), ("disconnecting", 3),))).setMaxAccess("readonly")
if mibBuilder.loadTexts: charSessState.setDescription("The current operational state of the session,\n disregarding flow control. 'connected' indicates\n that character data could flow on the network side\n of session. 'connecting' indicates moving from\n nonexistent toward 'connected'. 'disconnecting'\n indicates moving from 'connected' or 'connecting' to\n nonexistent.")
charSessProtocol = MibTableColumn((1, 3, 6, 1, 2, 1, 19, 3, 1, 5), AutonomousType()).setMaxAccess("readonly")
if mibBuilder.loadTexts: charSessProtocol.setDescription('The network protocol over which the session is\n running. Other OBJECT IDENTIFIER values may be\n defined elsewhere, in association with specific\n protocols. However, this document assigns those of\n known interest as of this writing.')
wellKnownProtocols = MibIdentifier((1, 3, 6, 1, 2, 1, 19, 4))
protocolOther = MibIdentifier((1, 3, 6, 1, 2, 1, 19, 4, 1))
protocolTelnet = MibIdentifier((1, 3, 6, 1, 2, 1, 19, 4, 2))
protocolRlogin = MibIdentifier((1, 3, 6, 1, 2, 1, 19, 4, 3))
protocolLat = MibIdentifier((1, 3, 6, 1, 2, 1, 19, 4, 4))
protocolX29 = MibIdentifier((1, 3, 6, 1, 2, 1, 19, 4, 5))
protocolVtp = MibIdentifier((1, 3, 6, 1, 2, 1, 19, 4, 6))
charSessOperOrigin = MibTableColumn((1, 3, 6, 1, 2, 1, 19, 3, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3,))).clone(namedValues=NamedValues(("unknown", 1), ("network", 2), ("local", 3),))).setMaxAccess("readonly")
if mibBuilder.loadTexts: charSessOperOrigin.setDescription("The session's source of establishment.")
charSessInCharacters = MibTableColumn((1, 3, 6, 1, 2, 1, 19, 3, 1, 7), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: charSessInCharacters.setDescription("This session's subset of charPortInCharacters.")
charSessOutCharacters = MibTableColumn((1, 3, 6, 1, 2, 1, 19, 3, 1, 8), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: charSessOutCharacters.setDescription("This session's subset of charPortOutCharacters.")
charSessConnectionId = MibTableColumn((1, 3, 6, 1, 2, 1, 19, 3, 1, 9), InstancePointer()).setMaxAccess("readonly")
if mibBuilder.loadTexts: charSessConnectionId.setDescription('A reference to additional local MIB information.\n This should be the highest available related MIB,\n corresponding to charSessProtocol, such as Telnet.\n For example, the value for a TCP connection (in the\n absence of a Telnet MIB) is the object identifier of\n tcpConnState. If an agent is not configured to have\n such values, the agent returns the object\n identifier:\n\n nullConnectionId OBJECT IDENTIFIER ::= { 0 0 }\n ')
charSessStartTime = MibTableColumn((1, 3, 6, 1, 2, 1, 19, 3, 1, 10), TimeTicks()).setMaxAccess("readonly")
if mibBuilder.loadTexts: charSessStartTime.setDescription('The value of sysUpTime in MIB-2 when the session\n entered connecting state.')
charConformance = MibIdentifier((1, 3, 6, 1, 2, 1, 19, 5))
charGroups = MibIdentifier((1, 3, 6, 1, 2, 1, 19, 5, 1))
charCompliances = MibIdentifier((1, 3, 6, 1, 2, 1, 19, 5, 2))
charCompliance = ModuleCompliance((1, 3, 6, 1, 2, 1, 19, 5, 2, 1)).setObjects(*(("CHARACTER-MIB", "charGroup"),))
if mibBuilder.loadTexts: charCompliance.setDescription('The compliance statement for SNMPv2 entities\n which have Character hardware interfaces.')
charGroup = ObjectGroup((1, 3, 6, 1, 2, 1, 19, 5, 1, 1)).setObjects(*(("CHARACTER-MIB", "charNumber"), ("CHARACTER-MIB", "charPortIndex"), ("CHARACTER-MIB", "charPortName"), ("CHARACTER-MIB", "charPortType"), ("CHARACTER-MIB", "charPortHardware"), ("CHARACTER-MIB", "charPortReset"), ("CHARACTER-MIB", "charPortAdminStatus"), ("CHARACTER-MIB", "charPortOperStatus"), ("CHARACTER-MIB", "charPortLastChange"), ("CHARACTER-MIB", "charPortInFlowState"), ("CHARACTER-MIB", "charPortOutFlowState"), ("CHARACTER-MIB", "charPortAdminOrigin"), ("CHARACTER-MIB", "charPortSessionMaximum"), ("CHARACTER-MIB", "charPortInFlowTypes"), ("CHARACTER-MIB", "charPortOutFlowTypes"), ("CHARACTER-MIB", "charPortInCharacters"), ("CHARACTER-MIB", "charPortOutCharacters"), ("CHARACTER-MIB", "charPortSessionNumber"), ("CHARACTER-MIB", "charPortSessionIndex"), ("CHARACTER-MIB", "charPortLowerIfIndex"), ("CHARACTER-MIB", "charSessPortIndex"), ("CHARACTER-MIB", "charSessIndex"), ("CHARACTER-MIB", "charSessKill"), ("CHARACTER-MIB", "charSessState"), ("CHARACTER-MIB", "charSessProtocol"), ("CHARACTER-MIB", "charSessOperOrigin"), ("CHARACTER-MIB", "charSessInCharacters"), ("CHARACTER-MIB", "charSessOutCharacters"), ("CHARACTER-MIB", "charSessConnectionId"), ("CHARACTER-MIB", "charSessStartTime"),))
if mibBuilder.loadTexts: charGroup.setDescription('A collection of objects providing information\n applicable to all Character interfaces.')
mibBuilder.exportSymbols("CHARACTER-MIB", protocolOther=protocolOther, charPortAdminOrigin=charPortAdminOrigin, charPortSessionMaximum=charPortSessionMaximum, charSessIndex=charSessIndex, charSessInCharacters=charSessInCharacters, charPortAdminStatus=charPortAdminStatus, charSessEntry=charSessEntry, charNumber=charNumber, charPortType=charPortType, charSessKill=charSessKill, protocolRlogin=protocolRlogin, charCompliance=charCompliance, charPortInCharacters=charPortInCharacters, charPortLowerIfIndex=charPortLowerIfIndex, charPortOutFlowState=charPortOutFlowState, charConformance=charConformance, charSessConnectionId=charSessConnectionId, charPortOutCharacters=charPortOutCharacters, charSessStartTime=charSessStartTime, charSessOutCharacters=charSessOutCharacters, wellKnownProtocols=wellKnownProtocols, charPortIndex=charPortIndex, charPortReset=charPortReset, charPortInFlowType=charPortInFlowType, charPortHardware=charPortHardware, protocolLat=protocolLat, charPortLastChange=charPortLastChange, charPortSessionIndex=charPortSessionIndex, protocolVtp=protocolVtp, charSessTable=charSessTable, charSessProtocol=charSessProtocol, charSessOperOrigin=charSessOperOrigin, charPortOutFlowTypes=charPortOutFlowTypes, protocolTelnet=protocolTelnet, charPortOutFlowType=charPortOutFlowType, charPortTable=charPortTable, charPortInFlowState=charPortInFlowState, charSessPortIndex=charSessPortIndex, PortIndex=PortIndex, charPortSessionNumber=charPortSessionNumber, charCompliances=charCompliances, PYSNMP_MODULE_ID=char, charGroups=charGroups, charPortEntry=charPortEntry, charPortInFlowTypes=charPortInFlowTypes, charPortOperStatus=charPortOperStatus, charGroup=charGroup, charPortName=charPortName, charSessState=charSessState, char=char, protocolX29=protocolX29)
| (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, value_range_constraint, constraints_union, value_size_constraint, single_value_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsIntersection', 'ValueRangeConstraint', 'ConstraintsUnion', 'ValueSizeConstraint', 'SingleValueConstraint')
(interface_index,) = mibBuilder.importSymbols('IF-MIB', 'InterfaceIndex')
(object_group, notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'ObjectGroup', 'NotificationGroup', 'ModuleCompliance')
(mib_identifier, transmission, bits, integer32, ip_address, gauge32, mib_2, counter32, counter64, mib_scalar, mib_table, mib_table_row, mib_table_column, iso, unsigned32, object_identity, time_ticks, module_identity, notification_type) = mibBuilder.importSymbols('SNMPv2-SMI', 'MibIdentifier', 'transmission', 'Bits', 'Integer32', 'IpAddress', 'Gauge32', 'mib-2', 'Counter32', 'Counter64', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'iso', 'Unsigned32', 'ObjectIdentity', 'TimeTicks', 'ModuleIdentity', 'NotificationType')
(textual_convention, display_string, autonomous_type, instance_pointer) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'DisplayString', 'AutonomousType', 'InstancePointer')
char = module_identity((1, 3, 6, 1, 2, 1, 19))
if mibBuilder.loadTexts:
char.setLastUpdated('9405261700Z')
if mibBuilder.loadTexts:
char.setOrganization('IETF Character MIB Working Group')
if mibBuilder.loadTexts:
char.setContactInfo(' Bob Stewart\n Postal: Xyplex, Inc.\n 295 Foster Street\n Littleton, MA 01460\n\n Tel: 508-952-4816\n Fax: 508-952-4887\n\n E-mail: rlstewart@eng.xyplex.com')
if mibBuilder.loadTexts:
char.setDescription('The MIB module for character stream devices.')
class Portindex(Integer32, TextualConvention):
display_hint = 'd'
char_number = mib_scalar((1, 3, 6, 1, 2, 1, 19, 1), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
charNumber.setDescription('The number of entries in charPortTable, regardless\n of their current state.')
char_port_table = mib_table((1, 3, 6, 1, 2, 1, 19, 2))
if mibBuilder.loadTexts:
charPortTable.setDescription('A list of port entries. The number of entries is\n given by the value of charNumber.')
char_port_entry = mib_table_row((1, 3, 6, 1, 2, 1, 19, 2, 1)).setIndexNames((0, 'CHARACTER-MIB', 'charPortIndex'))
if mibBuilder.loadTexts:
charPortEntry.setDescription('Status and parameter values for a character port.')
char_port_index = mib_table_column((1, 3, 6, 1, 2, 1, 19, 2, 1, 1), port_index()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
charPortIndex.setDescription('A unique value for each character port, perhaps\n corresponding to the same value of ifIndex when the\n character port is associated with a hardware port\n represented by an ifIndex.')
char_port_name = mib_table_column((1, 3, 6, 1, 2, 1, 19, 2, 1, 2), display_string().subtype(subtypeSpec=value_size_constraint(0, 32))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
charPortName.setDescription('An administratively assigned name for the port,\n typically with some local significance.')
char_port_type = mib_table_column((1, 3, 6, 1, 2, 1, 19, 2, 1, 3), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('physical', 1), ('virtual', 2)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
charPortType.setDescription("The port's type, 'physical' if the port represents\n an external hardware connector, 'virtual' if it does\n not.")
char_port_hardware = mib_table_column((1, 3, 6, 1, 2, 1, 19, 2, 1, 4), autonomous_type()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
charPortHardware.setDescription("A reference to hardware MIB definitions specific to\n a physical port's external connector. For example,\n if the connector is RS-232, then the value of this\n object refers to a MIB sub-tree defining objects\n specific to RS-232. If an agent is not configured\n to have such values, the agent returns the object\n identifier:\n\n nullHardware OBJECT IDENTIFIER ::= { 0 0 }\n ")
char_port_reset = mib_table_column((1, 3, 6, 1, 2, 1, 19, 2, 1, 5), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('ready', 1), ('execute', 2)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
charPortReset.setDescription("A control to force the port into a clean, initial\n state, both hardware and software, disconnecting all\n the port's existing sessions. In response to a\n get-request or get-next-request, the agent always\n returns 'ready' as the value. Setting the value to\n 'execute' causes a reset.")
char_port_admin_status = mib_table_column((1, 3, 6, 1, 2, 1, 19, 2, 1, 6), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4))).clone(namedValues=named_values(('enabled', 1), ('disabled', 2), ('off', 3), ('maintenance', 4)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
charPortAdminStatus.setDescription("The port's desired state, independent of flow\n control. 'enabled' indicates that the port is\n allowed to pass characters and form new sessions.\n 'disabled' indicates that the port is allowed to\n pass characters but not form new sessions. 'off'\n indicates that the port is not allowed to pass\n characters or have any sessions. 'maintenance'\n indicates a maintenance mode, exclusive of normal\n operation, such as running a test.\n\n 'enabled' corresponds to ifAdminStatus 'up'.\n 'disabled' and 'off' correspond to ifAdminStatus\n 'down'. 'maintenance' corresponds to ifAdminStatus\n 'test'.")
char_port_oper_status = mib_table_column((1, 3, 6, 1, 2, 1, 19, 2, 1, 7), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4, 5))).clone(namedValues=named_values(('up', 1), ('down', 2), ('maintenance', 3), ('absent', 4), ('active', 5)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
charPortOperStatus.setDescription("The port's actual, operational state, independent\n of flow control. 'up' indicates able to function\n normally. 'down' indicates inability to function\n for administrative or operational reasons.\n 'maintenance' indicates a maintenance mode,\n exclusive of normal operation, such as running a\n test. 'absent' indicates that port hardware is not\n present. 'active' indicates up with a user present\n (e.g. logged in).\n\n 'up' and 'active' correspond to ifOperStatus 'up'.\n 'down' and 'absent' correspond to ifOperStatus\n 'down'. 'maintenance' corresponds to ifOperStatus\n 'test'.")
char_port_last_change = mib_table_column((1, 3, 6, 1, 2, 1, 19, 2, 1, 8), time_ticks()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
charPortLastChange.setDescription('The value of sysUpTime at the time the port entered\n its current operational state. If the current state\n was entered prior to the last reinitialization of\n the local network management subsystem, then this\n object contains a zero value.')
char_port_in_flow_type = mib_table_column((1, 3, 6, 1, 2, 1, 19, 2, 1, 9), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4, 5))).clone(namedValues=named_values(('none', 1), ('xonXoff', 2), ('hardware', 3), ('ctsRts', 4), ('dsrDtr', 5)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
charPortInFlowType.setDescription("The port's type of input flow control. 'none'\n indicates no flow control at this level or below.\n 'xonXoff' indicates software flow control by\n recognizing XON and XOFF characters. 'hardware'\n indicates flow control delegated to the lower level,\n for example a parallel port.\n\n 'ctsRts' and 'dsrDtr' are specific to RS-232-like\n ports. Although not architecturally pure, they are\n included here for simplicity's sake.")
char_port_out_flow_type = mib_table_column((1, 3, 6, 1, 2, 1, 19, 2, 1, 10), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4, 5))).clone(namedValues=named_values(('none', 1), ('xonXoff', 2), ('hardware', 3), ('ctsRts', 4), ('dsrDtr', 5)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
charPortOutFlowType.setDescription("The port's type of output flow control. 'none'\n indicates no flow control at this level or below.\n 'xonXoff' indicates software flow control by\n recognizing XON and XOFF characters. 'hardware'\n indicates flow control delegated to the lower level,\n for example a parallel port.\n\n 'ctsRts' and 'dsrDtr' are specific to RS-232-like\n ports. Although not architecturally pure, they are\n included here for simplicy's sake.")
char_port_in_flow_state = mib_table_column((1, 3, 6, 1, 2, 1, 19, 2, 1, 11), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4))).clone(namedValues=named_values(('none', 1), ('unknown', 2), ('stop', 3), ('go', 4)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
charPortInFlowState.setDescription("The current operational state of input flow control\n on the port. 'none' indicates not applicable.\n 'unknown' indicates this level does not know.\n 'stop' indicates flow not allowed. 'go' indicates\n flow allowed.")
char_port_out_flow_state = mib_table_column((1, 3, 6, 1, 2, 1, 19, 2, 1, 12), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4))).clone(namedValues=named_values(('none', 1), ('unknown', 2), ('stop', 3), ('go', 4)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
charPortOutFlowState.setDescription("The current operational state of output flow\n control on the port. 'none' indicates not\n applicable. 'unknown' indicates this level does not\n know. 'stop' indicates flow not allowed. 'go'\n indicates flow allowed.")
char_port_in_characters = mib_table_column((1, 3, 6, 1, 2, 1, 19, 2, 1, 13), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
charPortInCharacters.setDescription("Total number of characters detected as input from\n the port since system re-initialization and while\n the port operational state was 'up', 'active', or\n 'maintenance', including, for example, framing, flow\n control (i.e. XON and XOFF), each occurrence of a\n BREAK condition, locally-processed input, and input\n sent to all sessions.")
char_port_out_characters = mib_table_column((1, 3, 6, 1, 2, 1, 19, 2, 1, 14), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
charPortOutCharacters.setDescription("Total number of characters detected as output to\n the port since system re-initialization and while\n the port operational state was 'up', 'active', or\n 'maintenance', including, for example, framing, flow\n control (i.e. XON and XOFF), each occurrence of a\n BREAK condition, locally-created output, and output\n received from all sessions.")
char_port_admin_origin = mib_table_column((1, 3, 6, 1, 2, 1, 19, 2, 1, 15), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4))).clone(namedValues=named_values(('dynamic', 1), ('network', 2), ('local', 3), ('none', 4)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
charPortAdminOrigin.setDescription("The administratively allowed origin for\n establishing session on the port. 'dynamic' allows\n 'network' or 'local' session establishment. 'none'\n disallows session establishment.")
char_port_session_maximum = mib_table_column((1, 3, 6, 1, 2, 1, 19, 2, 1, 16), integer32().subtype(subtypeSpec=value_range_constraint(-1, 2147483647))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
charPortSessionMaximum.setDescription('The maximum number of concurrent sessions allowed\n on the port. A value of -1 indicates no maximum.\n Setting the maximum to less than the current number\n of sessions has unspecified results.')
char_port_session_number = mib_table_column((1, 3, 6, 1, 2, 1, 19, 2, 1, 17), gauge32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
charPortSessionNumber.setDescription('The number of open sessions on the port that are in\n the connecting, connected, or disconnecting state.')
char_port_session_index = mib_table_column((1, 3, 6, 1, 2, 1, 19, 2, 1, 18), integer32().subtype(subtypeSpec=value_range_constraint(0, 2147483647))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
charPortSessionIndex.setDescription("The value of charSessIndex for the port's first or\n only active session. If the port has no active\n session, the agent returns the value zero.")
char_port_in_flow_types = mib_table_column((1, 3, 6, 1, 2, 1, 19, 2, 1, 19), octet_string().subtype(subtypeSpec=value_size_constraint(1, 1)).setFixedLength(1)).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
charPortInFlowTypes.setDescription("The port's types of input flow control at the\n software level. Hardware-level flow control is\n independently controlled by the appropriate\n hardware-level MIB.\n\n A value of zero indicates no flow control.\n Depending on the specific implementation, any or\n all combinations of flow control may be chosen by\n adding the values:\n\n 128 xonXoff, recognizing XON and XOFF characters\n 64 enqHost, ENQ/ACK to allow input to host\n 32 enqTerm, ACK to allow output to port\n ")
char_port_out_flow_types = mib_table_column((1, 3, 6, 1, 2, 1, 19, 2, 1, 20), octet_string().subtype(subtypeSpec=value_size_constraint(1, 1)).setFixedLength(1)).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
charPortOutFlowTypes.setDescription("The port's types of output flow control at the\n software level. Hardware-level flow control is\n independently controlled by the appropriate\n hardware-level MIB.\n\n A value of zero indicates no flow control.\n Depending on the specific implementation, any or\n all combinations of flow control may be chosen by\n adding the values:\n\n 128 xonXoff, recognizing XON and XOFF characters\n 64 enqHost, ENQ/ACK to allow input to host\n 32 enqTerm, ACK to allow output to port\n ")
char_port_lower_if_index = mib_table_column((1, 3, 6, 1, 2, 1, 19, 2, 1, 21), interface_index()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
charPortLowerIfIndex.setDescription('The ifIndex value of the lower level hardware supporting\n this character port, zero if none.')
char_sess_table = mib_table((1, 3, 6, 1, 2, 1, 19, 3))
if mibBuilder.loadTexts:
charSessTable.setDescription('A list of port session entries.')
char_sess_entry = mib_table_row((1, 3, 6, 1, 2, 1, 19, 3, 1)).setIndexNames((0, 'CHARACTER-MIB', 'charSessPortIndex'), (0, 'CHARACTER-MIB', 'charSessIndex'))
if mibBuilder.loadTexts:
charSessEntry.setDescription('Status and parameter values for a character port\n session.')
char_sess_port_index = mib_table_column((1, 3, 6, 1, 2, 1, 19, 3, 1, 1), port_index()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
charSessPortIndex.setDescription('The value of charPortIndex for the port to which\n this session belongs.')
char_sess_index = mib_table_column((1, 3, 6, 1, 2, 1, 19, 3, 1, 2), integer32().subtype(subtypeSpec=value_range_constraint(1, 2147483647))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
charSessIndex.setDescription('The session index in the context of the port, a\n non-zero positive integer. Session indexes within a\n port need not be sequential. Session indexes may be\n reused for different ports. For example, port 1 and\n port 3 may both have a session 2 at the same time.\n Session indexes may have any valid integer value,\n with any meaning convenient to the agent\n implementation.')
char_sess_kill = mib_table_column((1, 3, 6, 1, 2, 1, 19, 3, 1, 3), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('ready', 1), ('execute', 2)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
charSessKill.setDescription("A control to terminate the session. In response to\n a get-request or get-next-request, the agent always\n returns 'ready' as the value. Setting the value to\n 'execute' causes termination.")
char_sess_state = mib_table_column((1, 3, 6, 1, 2, 1, 19, 3, 1, 4), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('connecting', 1), ('connected', 2), ('disconnecting', 3)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
charSessState.setDescription("The current operational state of the session,\n disregarding flow control. 'connected' indicates\n that character data could flow on the network side\n of session. 'connecting' indicates moving from\n nonexistent toward 'connected'. 'disconnecting'\n indicates moving from 'connected' or 'connecting' to\n nonexistent.")
char_sess_protocol = mib_table_column((1, 3, 6, 1, 2, 1, 19, 3, 1, 5), autonomous_type()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
charSessProtocol.setDescription('The network protocol over which the session is\n running. Other OBJECT IDENTIFIER values may be\n defined elsewhere, in association with specific\n protocols. However, this document assigns those of\n known interest as of this writing.')
well_known_protocols = mib_identifier((1, 3, 6, 1, 2, 1, 19, 4))
protocol_other = mib_identifier((1, 3, 6, 1, 2, 1, 19, 4, 1))
protocol_telnet = mib_identifier((1, 3, 6, 1, 2, 1, 19, 4, 2))
protocol_rlogin = mib_identifier((1, 3, 6, 1, 2, 1, 19, 4, 3))
protocol_lat = mib_identifier((1, 3, 6, 1, 2, 1, 19, 4, 4))
protocol_x29 = mib_identifier((1, 3, 6, 1, 2, 1, 19, 4, 5))
protocol_vtp = mib_identifier((1, 3, 6, 1, 2, 1, 19, 4, 6))
char_sess_oper_origin = mib_table_column((1, 3, 6, 1, 2, 1, 19, 3, 1, 6), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('unknown', 1), ('network', 2), ('local', 3)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
charSessOperOrigin.setDescription("The session's source of establishment.")
char_sess_in_characters = mib_table_column((1, 3, 6, 1, 2, 1, 19, 3, 1, 7), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
charSessInCharacters.setDescription("This session's subset of charPortInCharacters.")
char_sess_out_characters = mib_table_column((1, 3, 6, 1, 2, 1, 19, 3, 1, 8), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
charSessOutCharacters.setDescription("This session's subset of charPortOutCharacters.")
char_sess_connection_id = mib_table_column((1, 3, 6, 1, 2, 1, 19, 3, 1, 9), instance_pointer()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
charSessConnectionId.setDescription('A reference to additional local MIB information.\n This should be the highest available related MIB,\n corresponding to charSessProtocol, such as Telnet.\n For example, the value for a TCP connection (in the\n absence of a Telnet MIB) is the object identifier of\n tcpConnState. If an agent is not configured to have\n such values, the agent returns the object\n identifier:\n\n nullConnectionId OBJECT IDENTIFIER ::= { 0 0 }\n ')
char_sess_start_time = mib_table_column((1, 3, 6, 1, 2, 1, 19, 3, 1, 10), time_ticks()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
charSessStartTime.setDescription('The value of sysUpTime in MIB-2 when the session\n entered connecting state.')
char_conformance = mib_identifier((1, 3, 6, 1, 2, 1, 19, 5))
char_groups = mib_identifier((1, 3, 6, 1, 2, 1, 19, 5, 1))
char_compliances = mib_identifier((1, 3, 6, 1, 2, 1, 19, 5, 2))
char_compliance = module_compliance((1, 3, 6, 1, 2, 1, 19, 5, 2, 1)).setObjects(*(('CHARACTER-MIB', 'charGroup'),))
if mibBuilder.loadTexts:
charCompliance.setDescription('The compliance statement for SNMPv2 entities\n which have Character hardware interfaces.')
char_group = object_group((1, 3, 6, 1, 2, 1, 19, 5, 1, 1)).setObjects(*(('CHARACTER-MIB', 'charNumber'), ('CHARACTER-MIB', 'charPortIndex'), ('CHARACTER-MIB', 'charPortName'), ('CHARACTER-MIB', 'charPortType'), ('CHARACTER-MIB', 'charPortHardware'), ('CHARACTER-MIB', 'charPortReset'), ('CHARACTER-MIB', 'charPortAdminStatus'), ('CHARACTER-MIB', 'charPortOperStatus'), ('CHARACTER-MIB', 'charPortLastChange'), ('CHARACTER-MIB', 'charPortInFlowState'), ('CHARACTER-MIB', 'charPortOutFlowState'), ('CHARACTER-MIB', 'charPortAdminOrigin'), ('CHARACTER-MIB', 'charPortSessionMaximum'), ('CHARACTER-MIB', 'charPortInFlowTypes'), ('CHARACTER-MIB', 'charPortOutFlowTypes'), ('CHARACTER-MIB', 'charPortInCharacters'), ('CHARACTER-MIB', 'charPortOutCharacters'), ('CHARACTER-MIB', 'charPortSessionNumber'), ('CHARACTER-MIB', 'charPortSessionIndex'), ('CHARACTER-MIB', 'charPortLowerIfIndex'), ('CHARACTER-MIB', 'charSessPortIndex'), ('CHARACTER-MIB', 'charSessIndex'), ('CHARACTER-MIB', 'charSessKill'), ('CHARACTER-MIB', 'charSessState'), ('CHARACTER-MIB', 'charSessProtocol'), ('CHARACTER-MIB', 'charSessOperOrigin'), ('CHARACTER-MIB', 'charSessInCharacters'), ('CHARACTER-MIB', 'charSessOutCharacters'), ('CHARACTER-MIB', 'charSessConnectionId'), ('CHARACTER-MIB', 'charSessStartTime')))
if mibBuilder.loadTexts:
charGroup.setDescription('A collection of objects providing information\n applicable to all Character interfaces.')
mibBuilder.exportSymbols('CHARACTER-MIB', protocolOther=protocolOther, charPortAdminOrigin=charPortAdminOrigin, charPortSessionMaximum=charPortSessionMaximum, charSessIndex=charSessIndex, charSessInCharacters=charSessInCharacters, charPortAdminStatus=charPortAdminStatus, charSessEntry=charSessEntry, charNumber=charNumber, charPortType=charPortType, charSessKill=charSessKill, protocolRlogin=protocolRlogin, charCompliance=charCompliance, charPortInCharacters=charPortInCharacters, charPortLowerIfIndex=charPortLowerIfIndex, charPortOutFlowState=charPortOutFlowState, charConformance=charConformance, charSessConnectionId=charSessConnectionId, charPortOutCharacters=charPortOutCharacters, charSessStartTime=charSessStartTime, charSessOutCharacters=charSessOutCharacters, wellKnownProtocols=wellKnownProtocols, charPortIndex=charPortIndex, charPortReset=charPortReset, charPortInFlowType=charPortInFlowType, charPortHardware=charPortHardware, protocolLat=protocolLat, charPortLastChange=charPortLastChange, charPortSessionIndex=charPortSessionIndex, protocolVtp=protocolVtp, charSessTable=charSessTable, charSessProtocol=charSessProtocol, charSessOperOrigin=charSessOperOrigin, charPortOutFlowTypes=charPortOutFlowTypes, protocolTelnet=protocolTelnet, charPortOutFlowType=charPortOutFlowType, charPortTable=charPortTable, charPortInFlowState=charPortInFlowState, charSessPortIndex=charSessPortIndex, PortIndex=PortIndex, charPortSessionNumber=charPortSessionNumber, charCompliances=charCompliances, PYSNMP_MODULE_ID=char, charGroups=charGroups, charPortEntry=charPortEntry, charPortInFlowTypes=charPortInFlowTypes, charPortOperStatus=charPortOperStatus, charGroup=charGroup, charPortName=charPortName, charSessState=charSessState, char=char, protocolX29=protocolX29) |
class Regularcombo():
"""docstring for ."""
def __init__(self, burger = ["big_mac"], snack = ["fries"], drink = ["coca"]):
try:
assert type(burger) == list
except AssertionError:
print('Please enter initial burger as list then custom')
else:
self.burger = burger
try:
assert type(snack) == list
except AssertionError:
print('Please enter initial snack as list then custom')
else:
self.snack = snack
try:
assert type(drink) == list
except AssertionError:
print('Please enter initial drink as list then custom')
else:
self.drink = drink
self.total = 0
def burger_custom(self, extra):
self.burger.append(extra)
def snack_custom(self, extra):
self.snack.append(extra)
def drink_custom(self, extra):
try:
assert type(extra) == str
except:
return "Your custom value is not valid"
try:
if len(self.drink) > 3:
raise DrinkcustomError()
except DrinkcustomError:
return "Your drink is too complex, please re-custom"
else:
self.drink.append(extra)
def display(self):
#print("burger:{},snack:{},drink:{}".format(self.burger, self.snack, self.drink))
return '{} {} {}'.format(self.burger, self.snack, self.drink)
def total_price(self):
self.total = (len(self.burger)*4.99 + len(self.snack)*2.99 + 1.99)*1.15
#print("total price is:{} CAD(Tax included)".format(self.total))
return round(self.total,2)
class DrinkcustomError(Exception):
pass
| class Regularcombo:
"""docstring for ."""
def __init__(self, burger=['big_mac'], snack=['fries'], drink=['coca']):
try:
assert type(burger) == list
except AssertionError:
print('Please enter initial burger as list then custom')
else:
self.burger = burger
try:
assert type(snack) == list
except AssertionError:
print('Please enter initial snack as list then custom')
else:
self.snack = snack
try:
assert type(drink) == list
except AssertionError:
print('Please enter initial drink as list then custom')
else:
self.drink = drink
self.total = 0
def burger_custom(self, extra):
self.burger.append(extra)
def snack_custom(self, extra):
self.snack.append(extra)
def drink_custom(self, extra):
try:
assert type(extra) == str
except:
return 'Your custom value is not valid'
try:
if len(self.drink) > 3:
raise drinkcustom_error()
except DrinkcustomError:
return 'Your drink is too complex, please re-custom'
else:
self.drink.append(extra)
def display(self):
return '{} {} {}'.format(self.burger, self.snack, self.drink)
def total_price(self):
self.total = (len(self.burger) * 4.99 + len(self.snack) * 2.99 + 1.99) * 1.15
return round(self.total, 2)
class Drinkcustomerror(Exception):
pass |
def write_results(results, save_path):
output = []
for k, v in results.items():
output.append("{}: {}".format(k, v))
output.append("\n")
output.append("If you need to access these results for the future "
"they are stored in: {}".format(save_path))
with open(save_path, 'w') as fp:
fp.write("\n".join(output))
return "\n".join(output)
| def write_results(results, save_path):
output = []
for (k, v) in results.items():
output.append('{}: {}'.format(k, v))
output.append('\n')
output.append('If you need to access these results for the future they are stored in: {}'.format(save_path))
with open(save_path, 'w') as fp:
fp.write('\n'.join(output))
return '\n'.join(output) |
houses = {"Harry": "Gryffindor", "Draco": "Slytherin"}
houses["Hermione"] = "Gryffindor"
print(houses["Harry"])
| houses = {'Harry': 'Gryffindor', 'Draco': 'Slytherin'}
houses['Hermione'] = 'Gryffindor'
print(houses['Harry']) |
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def oddEvenList(self, head):
if not head:
return None
i = 0
tmp = head
first = True
prev = None
tmp_even_head = None
tail = None
while tmp:
if i % 2 != 0:
if first:
second_list = ListNode(tmp.val)
tmp_even_head = second_list
second_list.next = None
first = False
else:
second_list.next = ListNode(tmp.val)
second_list = second_list.next
second_list.next = None
if tmp and tmp.next:
prev.next = tmp.next
else:
tail = tmp
prev = tmp
tmp = tmp.next
i += 1
if tmp_even_head:
tail.next = tmp_even_head
return head
| class Solution:
def odd_even_list(self, head):
if not head:
return None
i = 0
tmp = head
first = True
prev = None
tmp_even_head = None
tail = None
while tmp:
if i % 2 != 0:
if first:
second_list = list_node(tmp.val)
tmp_even_head = second_list
second_list.next = None
first = False
else:
second_list.next = list_node(tmp.val)
second_list = second_list.next
second_list.next = None
if tmp and tmp.next:
prev.next = tmp.next
else:
tail = tmp
prev = tmp
tmp = tmp.next
i += 1
if tmp_even_head:
tail.next = tmp_even_head
return head |
def lineup_students(string):
return sorted(string.split(), key=lambda x: (len(x), x), reverse=True)
# lineup_students = lambda s: sorted(s.split(), key=lambda x: (len(x), x), reverse=True)
| def lineup_students(string):
return sorted(string.split(), key=lambda x: (len(x), x), reverse=True) |
# Accept a positive integer and print the reverse of it.
n = int(input("Enter a positive integer: ")) # | n = 123
print()
rev = 0 # | rev = 0
while n > 0: # | 123 > 0 = True | 12 > 0 = True | 1 > 0 = True |
digit = n % 10 # extract the last digit # | digit = 123 % 10 = 3 | digit = 12 % 10 = 2 | digit = 1 % 10 = 1 |
rev = rev * 10 + digit # ?? # | rev = 0 * 10 + 3 = 3 | rev = 3 * 10 + 2 = 32 | rev = 32 * 10 + 1 = 321 |
n = n // 10 # remove the last digit # | n = 123 // 10 = 12 | n = 12 // 10 = 1 | n = 1 // 10 = 0 |
print("The reverse of the number is:", rev)
| n = int(input('Enter a positive integer: '))
print()
rev = 0
while n > 0:
digit = n % 10
rev = rev * 10 + digit
n = n // 10
print('The reverse of the number is:', rev) |
def parse_plotter_args(parser):
parser.add_option(
"--name_of_3dmodel",
type="string",
default="airplane/airplane_0630.ply",
help="name of 3D model to plot using the 'plot_subclouds' script",
)
parser.add_option(
"--save_plot_frames",
action="store_true",
default=False,
help="whether to record the 3D model shown in 'plot_subclouds' script",
)
parser.add_option(
"--plotted_image_folder",
type="string",
default="./gif_images",
help="folder to store the images created if save_plot_frames=True",
)
return parser
| def parse_plotter_args(parser):
parser.add_option('--name_of_3dmodel', type='string', default='airplane/airplane_0630.ply', help="name of 3D model to plot using the 'plot_subclouds' script")
parser.add_option('--save_plot_frames', action='store_true', default=False, help="whether to record the 3D model shown in 'plot_subclouds' script")
parser.add_option('--plotted_image_folder', type='string', default='./gif_images', help='folder to store the images created if save_plot_frames=True')
return parser |
PART_NAMES = [
"nose", "leftEye", "rightEye", "leftEar", "rightEar", "leftShoulder",
"rightShoulder", "leftElbow", "rightElbow", "leftWrist", "rightWrist",
"leftHip", "rightHip", "leftKnee", "rightKnee", "leftAnkle", "rightAnkle"
]
NUM_KEYPOINTS = len(PART_NAMES)
PART_IDS = {pn: pid for pid, pn in enumerate(PART_NAMES)}
CONNECTED_PART_NAMES = [
("leftHip", "leftShoulder"), ("leftElbow", "leftShoulder"),
("leftElbow", "leftWrist"), ("leftHip", "leftKnee"),
("leftKnee", "leftAnkle"), ("rightHip", "rightShoulder"),
("rightElbow", "rightShoulder"), ("rightElbow", "rightWrist"),
("rightHip", "rightKnee"), ("rightKnee", "rightAnkle"),
("leftShoulder", "rightShoulder"), ("leftHip", "rightHip")
]
CONNECTED_PART_INDICES = [(PART_IDS[a], PART_IDS[b]) for a, b in CONNECTED_PART_NAMES]
LOCAL_MAXIMUM_RADIUS = 1
POSE_CHAIN = [
("nose", "leftEye"), ("leftEye", "leftEar"), ("nose", "rightEye"),
("rightEye", "rightEar"), ("nose", "leftShoulder"),
("leftShoulder", "leftElbow"), ("leftElbow", "leftWrist"),
("leftShoulder", "leftHip"), ("leftHip", "leftKnee"),
("leftKnee", "leftAnkle"), ("nose", "rightShoulder"),
("rightShoulder", "rightElbow"), ("rightElbow", "rightWrist"),
("rightShoulder", "rightHip"), ("rightHip", "rightKnee"),
("rightKnee", "rightAnkle")
]
MOVABLE_PART = [
[("rightShoulder", "rightElbow"), ("rightElbow", "rightWrist")],
[("leftShoulder", "leftElbow"), ("leftElbow", "leftWrist")],
[("rightElbow", "rightShoulder"), ("rightShoulder", "rightHip")],
[("leftElbow", "leftShoulder"), ("leftShoulder", "leftHip")],
[("leftHip", "leftKnee"), ("leftKnee", "leftAnkle")],
[("rightHip", "rightKnee"), ("rightKnee", "rightAnkle")]
]
PIVOT_POINT = [
"rightElbow", "leftElbow", "rightShoulder", "leftShoulder", "leftKnee", "rightKnee"
]
PARENT_CHILD_TUPLES = [(PART_IDS[parent], PART_IDS[child]) for parent, child in POSE_CHAIN]
PART_CHANNELS = [
'left_face',
'right_face',
'right_upper_leg_front',
'right_lower_leg_back',
'right_upper_leg_back',
'left_lower_leg_front',
'left_upper_leg_front',
'left_upper_leg_back',
'left_lower_leg_back',
'right_feet',
'right_lower_leg_front',
'left_feet',
'torso_front',
'torso_back',
'right_upper_arm_front',
'right_upper_arm_back',
'right_lower_arm_back',
'left_lower_arm_front',
'left_upper_arm_front',
'left_upper_arm_back',
'left_lower_arm_back',
'right_hand',
'right_lower_arm_front',
'left_hand'
] | part_names = ['nose', 'leftEye', 'rightEye', 'leftEar', 'rightEar', 'leftShoulder', 'rightShoulder', 'leftElbow', 'rightElbow', 'leftWrist', 'rightWrist', 'leftHip', 'rightHip', 'leftKnee', 'rightKnee', 'leftAnkle', 'rightAnkle']
num_keypoints = len(PART_NAMES)
part_ids = {pn: pid for (pid, pn) in enumerate(PART_NAMES)}
connected_part_names = [('leftHip', 'leftShoulder'), ('leftElbow', 'leftShoulder'), ('leftElbow', 'leftWrist'), ('leftHip', 'leftKnee'), ('leftKnee', 'leftAnkle'), ('rightHip', 'rightShoulder'), ('rightElbow', 'rightShoulder'), ('rightElbow', 'rightWrist'), ('rightHip', 'rightKnee'), ('rightKnee', 'rightAnkle'), ('leftShoulder', 'rightShoulder'), ('leftHip', 'rightHip')]
connected_part_indices = [(PART_IDS[a], PART_IDS[b]) for (a, b) in CONNECTED_PART_NAMES]
local_maximum_radius = 1
pose_chain = [('nose', 'leftEye'), ('leftEye', 'leftEar'), ('nose', 'rightEye'), ('rightEye', 'rightEar'), ('nose', 'leftShoulder'), ('leftShoulder', 'leftElbow'), ('leftElbow', 'leftWrist'), ('leftShoulder', 'leftHip'), ('leftHip', 'leftKnee'), ('leftKnee', 'leftAnkle'), ('nose', 'rightShoulder'), ('rightShoulder', 'rightElbow'), ('rightElbow', 'rightWrist'), ('rightShoulder', 'rightHip'), ('rightHip', 'rightKnee'), ('rightKnee', 'rightAnkle')]
movable_part = [[('rightShoulder', 'rightElbow'), ('rightElbow', 'rightWrist')], [('leftShoulder', 'leftElbow'), ('leftElbow', 'leftWrist')], [('rightElbow', 'rightShoulder'), ('rightShoulder', 'rightHip')], [('leftElbow', 'leftShoulder'), ('leftShoulder', 'leftHip')], [('leftHip', 'leftKnee'), ('leftKnee', 'leftAnkle')], [('rightHip', 'rightKnee'), ('rightKnee', 'rightAnkle')]]
pivot_point = ['rightElbow', 'leftElbow', 'rightShoulder', 'leftShoulder', 'leftKnee', 'rightKnee']
parent_child_tuples = [(PART_IDS[parent], PART_IDS[child]) for (parent, child) in POSE_CHAIN]
part_channels = ['left_face', 'right_face', 'right_upper_leg_front', 'right_lower_leg_back', 'right_upper_leg_back', 'left_lower_leg_front', 'left_upper_leg_front', 'left_upper_leg_back', 'left_lower_leg_back', 'right_feet', 'right_lower_leg_front', 'left_feet', 'torso_front', 'torso_back', 'right_upper_arm_front', 'right_upper_arm_back', 'right_lower_arm_back', 'left_lower_arm_front', 'left_upper_arm_front', 'left_upper_arm_back', 'left_lower_arm_back', 'right_hand', 'right_lower_arm_front', 'left_hand'] |
to_remove = input()
word = input()
while to_remove in word:
word = word.replace(to_remove, '')
print(word)
| to_remove = input()
word = input()
while to_remove in word:
word = word.replace(to_remove, '')
print(word) |
BASE_URL = 'https://www.instagram.com/'
LOGIN_URL = BASE_URL + 'accounts/login/ajax/'
LOGOUT_URL = BASE_URL + 'accounts/logout/'
MEDIA_URL = BASE_URL + '{0}/media'
CHROME_WIN_UA = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36'
STORIES_URL = 'https://i.instagram.com/api/v1/feed/user/{0}/reel_media/'
STORIES_UA = 'Instagram 9.5.2 (iPhone7,2; iPhone OS 9_3_3; en_US; en-US; scale=2.00; 750x1334) AppleWebKit/420+'
STORIES_COOKIE = 'ds_user_id={0}; sessionid={1};'
TAGS_URL = BASE_URL + 'explore/tags/{0}/?__a=1'
LOCATIONS_URL = BASE_URL + 'explore/locations/{0}/?__a=1'
VIEW_MEDIA_URL = BASE_URL + 'p/{0}/?__a=1'
SEARCH_URL = BASE_URL + 'web/search/topsearch/?context=blended&query={0}'
QUERY_COMMENTS = BASE_URL + 'graphql/query/?query_id=17852405266163336&shortcode={0}&first=100&after={1}'
QUERY_HASHTAG = BASE_URL + 'graphql/query/?query_id=17882293912014529&tag_name={0}&first=100&after={1}'
QUERY_LOCATION = BASE_URL + 'graphql/query/?query_id=17881432870018455&id={0}&first=100&after={1}'
| base_url = 'https://www.instagram.com/'
login_url = BASE_URL + 'accounts/login/ajax/'
logout_url = BASE_URL + 'accounts/logout/'
media_url = BASE_URL + '{0}/media'
chrome_win_ua = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/59.0.3071.115 Safari/537.36'
stories_url = 'https://i.instagram.com/api/v1/feed/user/{0}/reel_media/'
stories_ua = 'Instagram 9.5.2 (iPhone7,2; iPhone OS 9_3_3; en_US; en-US; scale=2.00; 750x1334) AppleWebKit/420+'
stories_cookie = 'ds_user_id={0}; sessionid={1};'
tags_url = BASE_URL + 'explore/tags/{0}/?__a=1'
locations_url = BASE_URL + 'explore/locations/{0}/?__a=1'
view_media_url = BASE_URL + 'p/{0}/?__a=1'
search_url = BASE_URL + 'web/search/topsearch/?context=blended&query={0}'
query_comments = BASE_URL + 'graphql/query/?query_id=17852405266163336&shortcode={0}&first=100&after={1}'
query_hashtag = BASE_URL + 'graphql/query/?query_id=17882293912014529&tag_name={0}&first=100&after={1}'
query_location = BASE_URL + 'graphql/query/?query_id=17881432870018455&id={0}&first=100&after={1}' |
if __name__ == '__main__':
name = ' aleX'
print(name.strip())
# name = name.strip()
if name.startswith('al'):
print('yes')
if name.endswith('X'):
print('yes')
print(name.replace('l', 'p'))
# name = name.replace('l', 'p')
print(name.split('l'))
print(type(name.split('e')))
print(name.upper())
print(name.lower())
print(name[2])
print(name[:3])
print(name[3:])
print(name.index('e'))
print(name[:len(name) - 1])
| if __name__ == '__main__':
name = ' aleX'
print(name.strip())
if name.startswith('al'):
print('yes')
if name.endswith('X'):
print('yes')
print(name.replace('l', 'p'))
print(name.split('l'))
print(type(name.split('e')))
print(name.upper())
print(name.lower())
print(name[2])
print(name[:3])
print(name[3:])
print(name.index('e'))
print(name[:len(name) - 1]) |
'''
Created on 16.1.2017
@author: jm
'''
class GedcomLine(object):
'''
Gedcom line container, which can also carry the lower level gedcom lines.
Example
- level 2
- tag 'GIVN'
- value 'Johan' ...}
'''
# Current path elemements
# See https://docs.python.org/3/faq/programming.html#how-do-i-create-static-class-data-and-static-class-methods
path_elem = []
def __init__(self, line, linenum=0):
'''
Constructor: Parses and stores a gedcom line
Different constructors:
GedcomLine("1 GIVN Ville")
GedcomLine("1 GIVN Ville", 20)
GedcomLine((1, "GIVN", "Ville"))
GedcomLine((1, "GIVN", "Ville"), 20)
'''
self.path = ""
self.attributes = {}
self.linenum = linenum
if type(line) == str:
# Parse line
tkns = line.split(None,2)
self.line = line
else:
tkns = tuple(line)
self.level = int(tkns[0])
self.tag = tkns[1]
if len(tkns) > 2:
self.value = tkns[2]
else:
self.value = ""
self.line = str(self)
self.set_path(self.level, self.tag)
def __str__(self):
''' Get the original line '''
try:
ret = "{} {} {}".format(self.level, self.tag, self.value).rstrip()
except:
ret = "* Not complete *"
return ret
def set_path(self, level, tag):
''' Update self.path with given tag and level '''
if level > len(GedcomLine.path_elem):
raise RuntimeError("{} Invalid level {}: {}".format(self.path, level, self.line))
if level == len(GedcomLine.path_elem):
GedcomLine.path_elem.append(tag)
else:
GedcomLine.path_elem[level] = tag
GedcomLine.path_elem = GedcomLine.path_elem[:self.level+1]
self.path = ".".join(GedcomLine.path_elem)
return self.path
def set_attr(self, key, value):
''' Optional attributes like name TYPE as a tuple {'TYPE':'marriage'} '''
self.attributes[key] = value
def get_attr(self, key):
''' Get optional attribute value '''
if key in self.attributes:
return self.attributes[key]
return None
def get_year(self):
'''If value has a four digit last part, the numeric value of it is returned
'''
p = self.value.split()
try:
if len(p) > 0 and len(p[-1]) == 4:
return int(p[-1])
except:
return None
def emit(self, f):
# Print out current line to file f
f.emit(str(self))
| """
Created on 16.1.2017
@author: jm
"""
class Gedcomline(object):
"""
Gedcom line container, which can also carry the lower level gedcom lines.
Example
- level 2
- tag 'GIVN'
- value 'Johan' ...}
"""
path_elem = []
def __init__(self, line, linenum=0):
"""
Constructor: Parses and stores a gedcom line
Different constructors:
GedcomLine("1 GIVN Ville")
GedcomLine("1 GIVN Ville", 20)
GedcomLine((1, "GIVN", "Ville"))
GedcomLine((1, "GIVN", "Ville"), 20)
"""
self.path = ''
self.attributes = {}
self.linenum = linenum
if type(line) == str:
tkns = line.split(None, 2)
self.line = line
else:
tkns = tuple(line)
self.level = int(tkns[0])
self.tag = tkns[1]
if len(tkns) > 2:
self.value = tkns[2]
else:
self.value = ''
self.line = str(self)
self.set_path(self.level, self.tag)
def __str__(self):
""" Get the original line """
try:
ret = '{} {} {}'.format(self.level, self.tag, self.value).rstrip()
except:
ret = '* Not complete *'
return ret
def set_path(self, level, tag):
""" Update self.path with given tag and level """
if level > len(GedcomLine.path_elem):
raise runtime_error('{} Invalid level {}: {}'.format(self.path, level, self.line))
if level == len(GedcomLine.path_elem):
GedcomLine.path_elem.append(tag)
else:
GedcomLine.path_elem[level] = tag
GedcomLine.path_elem = GedcomLine.path_elem[:self.level + 1]
self.path = '.'.join(GedcomLine.path_elem)
return self.path
def set_attr(self, key, value):
""" Optional attributes like name TYPE as a tuple {'TYPE':'marriage'} """
self.attributes[key] = value
def get_attr(self, key):
""" Get optional attribute value """
if key in self.attributes:
return self.attributes[key]
return None
def get_year(self):
"""If value has a four digit last part, the numeric value of it is returned
"""
p = self.value.split()
try:
if len(p) > 0 and len(p[-1]) == 4:
return int(p[-1])
except:
return None
def emit(self, f):
f.emit(str(self)) |
'''input
1
1 1 0 1 0 0 0 1 0 1
3 4 5 6 7 8 9 -2 -3 4 -2
8
3
1 1 1 1 1 1 0 0 1 1
0 1 0 1 1 1 1 0 1 0
1 0 1 1 0 1 0 1 0 1
-8 6 -2 -8 -8 4 8 7 -6 2 2
-9 2 0 1 7 -5 0 -2 -6 5 5
6 -6 7 -9 6 -5 8 0 -9 -7 -7
23
2
1 1 1 1 1 0 0 0 0 0
0 0 0 0 0 1 1 1 1 1
3 -2 -2 -2 -2 -2 -1 -1 -1 -1 -1
0 -2 -2 -2 -2 -2 -1 -1 -1 -1 -1
1
2
1 1 1 1 1 0 0 0 0 0
0 0 0 0 0 1 1 1 1 1
0 -2 -2 -2 -2 -2 -1 -1 -1 -1 -1
3 -2 -2 -2 -2 -2 -1 -1 -1 -1 -1
1
2
1 1 1 1 1 0 0 0 0 0
0 0 0 0 0 1 1 1 1 1
0 -2 -2 -2 -2 -2 -1 -1 -1 -1 -1
0 -2 -2 -2 -2 -2 -1 -1 -1 -1 -1
-2
'''
# -*- coding: utf-8 -*-
# AtCoder Beginner Contest
# Problem C
# FIXME: More smarter.
def calc_benefit(my_schedule, others_schedule, benefit_table, answer):
score = 0
if sum(my_schedule) == 0:
return benefit_total
for index, other_schedule in enumerate(others_schedule):
count = 0
for mine, other in zip(my_schedule, other_schedule):
if mine == other == 1:
count += 1
score += benefit_table[index][count]
return max(score, benefit_total)
# FIXME: More smarter.
def dfs(my_schedule, others_schedule, benefit_table, benefit_total, pos):
if pos == 10:
return calc_benefit(my_schedule, others_schedule, benefit_table, benefit_total)
my_schedule[pos] = 0
foo = dfs(my_schedule, others_schedule, benefit_table, benefit_total, pos + 1)
my_schedule[pos] = 1
bar = dfs(my_schedule, others_schedule, benefit_table, benefit_total, pos + 1)
return max(foo, bar)
if __name__ == '__main__':
shop_count = int(input())
others_schedule = [list(map(int, input().split())) for _ in range(shop_count)]
benefit_table = [list(map(int, input().split())) for _ in range(shop_count)]
benefit_total = -1000000000
my_schedule = [None] * (10)
# See: https://www.youtube.com/watch?v=GWhYUxeDe70
benefit_total = dfs(my_schedule, others_schedule, benefit_table, benefit_total, 0)
print(benefit_total)
| """input
1
1 1 0 1 0 0 0 1 0 1
3 4 5 6 7 8 9 -2 -3 4 -2
8
3
1 1 1 1 1 1 0 0 1 1
0 1 0 1 1 1 1 0 1 0
1 0 1 1 0 1 0 1 0 1
-8 6 -2 -8 -8 4 8 7 -6 2 2
-9 2 0 1 7 -5 0 -2 -6 5 5
6 -6 7 -9 6 -5 8 0 -9 -7 -7
23
2
1 1 1 1 1 0 0 0 0 0
0 0 0 0 0 1 1 1 1 1
3 -2 -2 -2 -2 -2 -1 -1 -1 -1 -1
0 -2 -2 -2 -2 -2 -1 -1 -1 -1 -1
1
2
1 1 1 1 1 0 0 0 0 0
0 0 0 0 0 1 1 1 1 1
0 -2 -2 -2 -2 -2 -1 -1 -1 -1 -1
3 -2 -2 -2 -2 -2 -1 -1 -1 -1 -1
1
2
1 1 1 1 1 0 0 0 0 0
0 0 0 0 0 1 1 1 1 1
0 -2 -2 -2 -2 -2 -1 -1 -1 -1 -1
0 -2 -2 -2 -2 -2 -1 -1 -1 -1 -1
-2
"""
def calc_benefit(my_schedule, others_schedule, benefit_table, answer):
score = 0
if sum(my_schedule) == 0:
return benefit_total
for (index, other_schedule) in enumerate(others_schedule):
count = 0
for (mine, other) in zip(my_schedule, other_schedule):
if mine == other == 1:
count += 1
score += benefit_table[index][count]
return max(score, benefit_total)
def dfs(my_schedule, others_schedule, benefit_table, benefit_total, pos):
if pos == 10:
return calc_benefit(my_schedule, others_schedule, benefit_table, benefit_total)
my_schedule[pos] = 0
foo = dfs(my_schedule, others_schedule, benefit_table, benefit_total, pos + 1)
my_schedule[pos] = 1
bar = dfs(my_schedule, others_schedule, benefit_table, benefit_total, pos + 1)
return max(foo, bar)
if __name__ == '__main__':
shop_count = int(input())
others_schedule = [list(map(int, input().split())) for _ in range(shop_count)]
benefit_table = [list(map(int, input().split())) for _ in range(shop_count)]
benefit_total = -1000000000
my_schedule = [None] * 10
benefit_total = dfs(my_schedule, others_schedule, benefit_table, benefit_total, 0)
print(benefit_total) |
filename = 'programming_poll.txt'
responses = []
while True:
response = input("\nWhy do you like programming? ")
responses.append(response)
continue_poll = input("Would you like to let someone else respond? (y/n) ")
if continue_poll != 'y':
break
with open(filename, 'a') as f:
for response in responses:
f.write(response + "\n") | filename = 'programming_poll.txt'
responses = []
while True:
response = input('\nWhy do you like programming? ')
responses.append(response)
continue_poll = input('Would you like to let someone else respond? (y/n) ')
if continue_poll != 'y':
break
with open(filename, 'a') as f:
for response in responses:
f.write(response + '\n') |
'''
Created on Oct 13, 2017
@author: LSX1KOR
'''
"""
In the multiple inheritance scenario, any specified attribute is searched first in the current class.
If not found, the search continues into parent classes in depth-first,
left-right fashion without searching same class twice.
"""
class Base1(object):
def foo(self):
print("BASE1")
class Base2(object):
def foo(self):
print('BASE2')
class Derived(Base2,Base1):
pass
d=Derived()
d.foo()
#__mro__=Method Resolution Orde
#It will tell you how the search order will be
print(Derived.__mro__)
#o/p=(<class '__main__.Derived'>, <class '__main__.Base2'>, <class '__main__.Base1'>, <class 'object'>)
#so it will look first into current class then left i.e, Base2 then Base1 then object class
| """
Created on Oct 13, 2017
@author: LSX1KOR
"""
'\nIn the multiple inheritance scenario, any specified attribute is searched first in the current class.\nIf not found, the search continues into parent classes in depth-first,\nleft-right fashion without searching same class twice.\n'
class Base1(object):
def foo(self):
print('BASE1')
class Base2(object):
def foo(self):
print('BASE2')
class Derived(Base2, Base1):
pass
d = derived()
d.foo()
print(Derived.__mro__) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = "Louis Richard"
__email__ = "louisr@irfu.se"
__copyright__ = "Copyright 2020-2021"
__license__ = "MIT"
__version__ = "2.3.7"
__status__ = "Prototype"
def iso86012datetime64(time):
r"""Convert ISO8601 time format to datetime64 in ns units.
Parameters
----------
time : ndarray
Time in ISO 8601 format
Returns
-------
time_datetime64 : ndarray
Time in datetime64 in ns units.
See Also
--------
pyrfu.pyrf.datetime642iso8601
"""
time_datetime64 = time.astype("<M8[ns]")
return time_datetime64
| __author__ = 'Louis Richard'
__email__ = 'louisr@irfu.se'
__copyright__ = 'Copyright 2020-2021'
__license__ = 'MIT'
__version__ = '2.3.7'
__status__ = 'Prototype'
def iso86012datetime64(time):
"""Convert ISO8601 time format to datetime64 in ns units.
Parameters
----------
time : ndarray
Time in ISO 8601 format
Returns
-------
time_datetime64 : ndarray
Time in datetime64 in ns units.
See Also
--------
pyrfu.pyrf.datetime642iso8601
"""
time_datetime64 = time.astype('<M8[ns]')
return time_datetime64 |
#
# @lc app=leetcode id=1806 lang=python3
#
# [1806] Minimum Number of Operations to Reinitialize a Permutation
#
# @lc code=start
class Solution:
def reinitializePermutation(self, n: int) -> int:
i, cnt = 1, 0
while not cnt or i > 1: # i != 1 doesn't work
i = i * 2 % (n - 1)
cnt += 1
return cnt
# @lc code=end
| class Solution:
def reinitialize_permutation(self, n: int) -> int:
(i, cnt) = (1, 0)
while not cnt or i > 1:
i = i * 2 % (n - 1)
cnt += 1
return cnt |
class TestFunctionalTest(object):
counter = 0
@classmethod
def setup_class(cls):
cls.counter += 1
@classmethod
def teardown_class(cls):
cls.counter -= 1
def _run(self):
assert self.counter==1
def test1(self):
self._run()
def test2(self):
self._run()
| class Testfunctionaltest(object):
counter = 0
@classmethod
def setup_class(cls):
cls.counter += 1
@classmethod
def teardown_class(cls):
cls.counter -= 1
def _run(self):
assert self.counter == 1
def test1(self):
self._run()
def test2(self):
self._run() |
class Parameter:
'''
Defines a sampled (or "free") parameter by spin, parity, channel,
rank, and whether it's an energy or width (kind).
kind : "energy" or "width"
"width" can be the partial width or ANC (depending on how it was
set up in AZURE2)
channel : channel pair (defined in AZURE2; consistent with AZURE2,
these are one-based)
rank : Which spin^{parity} level is this? (There are frequently
more than one. Consistent with AZURE2, these are
one-based.)
'''
def __init__(self, spin, parity, kind, channel, rank=1, is_anc=False):
self.spin = spin
self.parity = parity
self.kind = kind
self.channel = int(channel)
self.rank = rank
jpi_label = '+' if self.parity == 1 else '-'
subscript = f'{rank:d},{channel:d}'
superscript = f'({jpi_label:s}{spin:.1f})'
if self.kind == 'energy':
self.label = r'$E_{%s}^{%s}$' % (subscript, superscript)
elif self.kind == 'width':
if is_anc:
self.label = r'$C_{%s}^{%s}$' % (subscript, superscript)
else:
self.label = r'$\Gamma_{%s}^{%s}$' % (subscript, superscript)
else:
print('"kind" attribute must be either "energy" or "width"')
def string(self):
parity = '+' if self.parity == 1 else '-'
return f'{self.spin}{parity} {self.kind} (number {self.rank}) in \
particle pair {self.channel}, {self.label}'
def print(self):
print(self.string())
class NormFactor:
'''
Defines a sampled normalization factor (n_i in the AZURE2 manual).
'''
def __init__(self, dataset_index):
self.index = dataset_index
self.label = r'$n_{%d}$' % (self.index)
| class Parameter:
"""
Defines a sampled (or "free") parameter by spin, parity, channel,
rank, and whether it's an energy or width (kind).
kind : "energy" or "width"
"width" can be the partial width or ANC (depending on how it was
set up in AZURE2)
channel : channel pair (defined in AZURE2; consistent with AZURE2,
these are one-based)
rank : Which spin^{parity} level is this? (There are frequently
more than one. Consistent with AZURE2, these are
one-based.)
"""
def __init__(self, spin, parity, kind, channel, rank=1, is_anc=False):
self.spin = spin
self.parity = parity
self.kind = kind
self.channel = int(channel)
self.rank = rank
jpi_label = '+' if self.parity == 1 else '-'
subscript = f'{rank:d},{channel:d}'
superscript = f'({jpi_label:s}{spin:.1f})'
if self.kind == 'energy':
self.label = '$E_{%s}^{%s}$' % (subscript, superscript)
elif self.kind == 'width':
if is_anc:
self.label = '$C_{%s}^{%s}$' % (subscript, superscript)
else:
self.label = '$\\Gamma_{%s}^{%s}$' % (subscript, superscript)
else:
print('"kind" attribute must be either "energy" or "width"')
def string(self):
parity = '+' if self.parity == 1 else '-'
return f'{self.spin}{parity} {self.kind} (number {self.rank}) in particle pair {self.channel}, {self.label}'
def print(self):
print(self.string())
class Normfactor:
"""
Defines a sampled normalization factor (n_i in the AZURE2 manual).
"""
def __init__(self, dataset_index):
self.index = dataset_index
self.label = '$n_{%d}$' % self.index |
top_avg = """SELECT *
FROM rm_episodes
INNER JOIN ratings
ON rm_episodes.tconst = ratings.tconst
ORDER BY averageRating
DESC
LIMIT 5
"""
worst_avg = """SELECT *
FROM rm_episodes
INNER JOIN ratings
ON rm_episodes.tconst = ratings.tconst
ORDER BY averageRating
ASC
LIMIT 5
"""
top_vote = """SELECT *
FROM rm_episodes
INNER JOIN ratings
ON rm_episodes.tconst = ratings.tconst
ORDER BY numVotes
DESC
LIMIT 5
"""
worst_vote = """SELECT *
FROM rm_episodes
INNER JOIN ratings
ON rm_episodes.tconst = ratings.tconst
ORDER BY numVotes
ASC
LIMIT 5
"""
seven_b = """SELECT *
FROM name_basics
WHERE birthYear > 2000
AND primaryProfession
LIKE '%music_department%'
AND primaryProfession
LIKE '%actress%' """
seven_c = """select count(*) from four_actress """
| top_avg = 'SELECT *\nFROM rm_episodes\nINNER JOIN ratings\nON rm_episodes.tconst = ratings.tconst\nORDER BY averageRating\nDESC\nLIMIT 5\n'
worst_avg = 'SELECT *\nFROM rm_episodes\nINNER JOIN ratings\nON rm_episodes.tconst = ratings.tconst\nORDER BY averageRating\nASC\nLIMIT 5\n'
top_vote = 'SELECT *\nFROM rm_episodes\nINNER JOIN ratings\nON rm_episodes.tconst = ratings.tconst\nORDER BY numVotes\nDESC\nLIMIT 5\n'
worst_vote = 'SELECT *\nFROM rm_episodes\nINNER JOIN ratings\nON rm_episodes.tconst = ratings.tconst\nORDER BY numVotes\nASC\nLIMIT 5\n'
seven_b = "SELECT * \nFROM name_basics \nWHERE birthYear > 2000 \nAND primaryProfession \nLIKE '%music_department%' \nAND primaryProfession \nLIKE '%actress%' "
seven_c = 'select count(*) from four_actress ' |
config = {
# these values are related to the user's environment
'env': {
'databases': {
'postgres_host': '127.0.0.1',
'postgres_name': 'jesse_db',
'postgres_port': 5432,
'postgres_username': 'jesse_user',
'postgres_password': 'password',
},
'caching': {
'driver': 'pickle'
},
'logging': {
'order_submission': True,
'order_cancellation': True,
'order_execution': True,
'position_opened': True,
'position_increased': True,
'position_reduced': True,
'position_closed': True,
'shorter_period_candles': False,
'trading_candles': True,
'balance_update': True,
},
'exchanges': {
'Sandbox': {
'fee': 0,
'type': 'spot',
# used only in futures trading
'settlement_currency': 'USDT',
# accepted values are: 'cross' and 'isolated'
'futures_leverage_mode': 'cross',
# 1x, 2x, 10x, 50x, etc. Enter as integers
'futures_leverage': 1,
'assets': [
{'asset': 'USDT', 'balance': 10_000},
{'asset': 'BTC', 'balance': 0},
],
},
# https://www.bitfinex.com
'Bitfinex': {
'fee': 0.002,
# backtest mode only: accepted are 'spot' and 'futures'
'type': 'futures',
# futures mode only
'settlement_currency': 'USD',
# accepted values are: 'cross' and 'isolated'
'futures_leverage_mode': 'cross',
# 1x, 2x, 10x, 50x, etc. Enter as integers
'futures_leverage': 1,
# used for spot exchange only
'assets': [
{'asset': 'USDT', 'balance': 10_000},
{'asset': 'USD', 'balance': 10_000},
{'asset': 'BTC', 'balance': 0},
],
},
# https://www.binance.com
'Binance': {
'fee': 0.001,
# backtest mode only: accepted are 'spot' and 'futures'
'type': 'futures',
# futures mode only
'settlement_currency': 'USDT',
# accepted values are: 'cross' and 'isolated'
'futures_leverage_mode': 'cross',
# 1x, 2x, 10x, 50x, etc. Enter as integers
'futures_leverage': 1,
# used for spot exchange only
'assets': [
{'asset': 'USDT', 'balance': 10_000},
{'asset': 'BTC', 'balance': 0},
],
},
# https://www.binance.com
'Binance Futures': {
'fee': 0.0004,
# backtest mode only: accepted are 'spot' and 'futures'
'type': 'futures',
# futures mode only
'settlement_currency': 'USDT',
# accepted values are: 'cross' and 'isolated'
'futures_leverage_mode': 'cross',
# 1x, 2x, 10x, 50x, etc. Enter as integers
'futures_leverage': 1,
# used for spot exchange only
'assets': [
{'asset': 'USDT', 'balance': 10_000},
],
},
# https://testnet.binancefuture.com
'Testnet Binance Futures': {
'fee': 0.0004,
# backtest mode only: accepted are 'spot' and 'futures'
'type': 'futures',
# futures mode only
'settlement_currency': 'USDT',
# accepted values are: 'cross' and 'isolated'
'futures_leverage_mode': 'cross',
# 1x, 2x, 10x, 50x, etc. Enter as integers
'futures_leverage': 1,
# used for spot mode
'assets': [
{'asset': 'USDT', 'balance': 10_000},
],
},
# https://pro.coinbase.com
'Coinbase': {
'fee': 0.005,
# backtest mode only: accepted are 'spot' and 'futures'
'type': 'futures',
# futures mode only
'settlement_currency': 'USD',
# accepted values are: 'cross' and 'isolated'
'futures_leverage_mode': 'cross',
# 1x, 2x, 10x, 50x, etc. Enter as integers
'futures_leverage': 1,
# used for spot exchange only
'assets': [
{'asset': 'USDT', 'balance': 10_000},
{'asset': 'USD', 'balance': 10_000},
{'asset': 'BTC', 'balance': 0},
],
},
},
# changes the metrics output of the backtest
'metrics': {
'sharpe_ratio': True,
'calmar_ratio': False,
'sortino_ratio': False,
'omega_ratio': False,
'winning_streak': False,
'losing_streak': False,
'largest_losing_trade': False,
'largest_winning_trade': False,
'total_winning_trades': False,
'total_losing_trades': False,
},
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Optimize mode
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#
# Below configurations are related to the optimize mode
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
'optimization': {
# sharpe, calmar, sortino, omega
'ratio': 'sharpe',
},
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# Data
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#
# Below configurations are related to the data
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
'data': {
# The minimum number of warmup candles that is loaded before each session.
'warmup_candles_num': 210,
}
},
# These values are just placeholders used by Jesse at runtime
'app': {
# list of currencies to consider
'considering_symbols': [],
# The symbol to trade.
'trading_symbols': [],
# list of time frames to consider
'considering_timeframes': [],
# Which candle type do you intend trade on
'trading_timeframes': [],
# list of exchanges to consider
'considering_exchanges': [],
# list of exchanges to consider
'trading_exchanges': [],
'considering_candles': [],
# dict of registered live trade drivers
'live_drivers': {},
# Accepted values are: 'backtest', 'livetrade', 'fitness'.
'trading_mode': '',
# variable used for test-driving the livetrade mode
'is_test_driving': False,
# this would enable many console.log()s in the code, which are helpful for debugging.
'debug_mode': False,
},
}
backup_config = config.copy()
def set_config(c) -> None:
global config
config['env'] = c
# add sandbox because it isn't in the local config file
config['env']['exchanges']['Sandbox'] = {
'type': 'spot',
# used only in futures trading
'settlement_currency': 'USDT',
'fee': 0,
'futures_leverage_mode': 'cross',
'futures_leverage': 1,
'assets': [
{'asset': 'USDT', 'balance': 10_000},
{'asset': 'BTC', 'balance': 0},
],
}
def reset_config() -> None:
global config
config = backup_config.copy()
| config = {'env': {'databases': {'postgres_host': '127.0.0.1', 'postgres_name': 'jesse_db', 'postgres_port': 5432, 'postgres_username': 'jesse_user', 'postgres_password': 'password'}, 'caching': {'driver': 'pickle'}, 'logging': {'order_submission': True, 'order_cancellation': True, 'order_execution': True, 'position_opened': True, 'position_increased': True, 'position_reduced': True, 'position_closed': True, 'shorter_period_candles': False, 'trading_candles': True, 'balance_update': True}, 'exchanges': {'Sandbox': {'fee': 0, 'type': 'spot', 'settlement_currency': 'USDT', 'futures_leverage_mode': 'cross', 'futures_leverage': 1, 'assets': [{'asset': 'USDT', 'balance': 10000}, {'asset': 'BTC', 'balance': 0}]}, 'Bitfinex': {'fee': 0.002, 'type': 'futures', 'settlement_currency': 'USD', 'futures_leverage_mode': 'cross', 'futures_leverage': 1, 'assets': [{'asset': 'USDT', 'balance': 10000}, {'asset': 'USD', 'balance': 10000}, {'asset': 'BTC', 'balance': 0}]}, 'Binance': {'fee': 0.001, 'type': 'futures', 'settlement_currency': 'USDT', 'futures_leverage_mode': 'cross', 'futures_leverage': 1, 'assets': [{'asset': 'USDT', 'balance': 10000}, {'asset': 'BTC', 'balance': 0}]}, 'Binance Futures': {'fee': 0.0004, 'type': 'futures', 'settlement_currency': 'USDT', 'futures_leverage_mode': 'cross', 'futures_leverage': 1, 'assets': [{'asset': 'USDT', 'balance': 10000}]}, 'Testnet Binance Futures': {'fee': 0.0004, 'type': 'futures', 'settlement_currency': 'USDT', 'futures_leverage_mode': 'cross', 'futures_leverage': 1, 'assets': [{'asset': 'USDT', 'balance': 10000}]}, 'Coinbase': {'fee': 0.005, 'type': 'futures', 'settlement_currency': 'USD', 'futures_leverage_mode': 'cross', 'futures_leverage': 1, 'assets': [{'asset': 'USDT', 'balance': 10000}, {'asset': 'USD', 'balance': 10000}, {'asset': 'BTC', 'balance': 0}]}}, 'metrics': {'sharpe_ratio': True, 'calmar_ratio': False, 'sortino_ratio': False, 'omega_ratio': False, 'winning_streak': False, 'losing_streak': False, 'largest_losing_trade': False, 'largest_winning_trade': False, 'total_winning_trades': False, 'total_losing_trades': False}, 'optimization': {'ratio': 'sharpe'}, 'data': {'warmup_candles_num': 210}}, 'app': {'considering_symbols': [], 'trading_symbols': [], 'considering_timeframes': [], 'trading_timeframes': [], 'considering_exchanges': [], 'trading_exchanges': [], 'considering_candles': [], 'live_drivers': {}, 'trading_mode': '', 'is_test_driving': False, 'debug_mode': False}}
backup_config = config.copy()
def set_config(c) -> None:
global config
config['env'] = c
config['env']['exchanges']['Sandbox'] = {'type': 'spot', 'settlement_currency': 'USDT', 'fee': 0, 'futures_leverage_mode': 'cross', 'futures_leverage': 1, 'assets': [{'asset': 'USDT', 'balance': 10000}, {'asset': 'BTC', 'balance': 0}]}
def reset_config() -> None:
global config
config = backup_config.copy() |
class CopyAsValuesParam(object):
def __init__(self, **kargs):
self.nodeId = kargs["nodeId"] if "nodeId" in kargs else None
self.asNewNode = kargs["asNewNode"] if "asNewNode" in kargs else False
| class Copyasvaluesparam(object):
def __init__(self, **kargs):
self.nodeId = kargs['nodeId'] if 'nodeId' in kargs else None
self.asNewNode = kargs['asNewNode'] if 'asNewNode' in kargs else False |
# a queue is a data structure in which the data element entered first is removed first
# basically you insert elements from one end and remove them from another end
# a very simple, and cliche example would be that of a plain old queue at McDonald's
# The person who joined the queue first will order first, and the one who joined last will order last
# (unless you're a prick)
# queues have two important operations:
# queue
# dequeue
# queuing is basically entereing a new element to the end of the queue
# dequeing is removing an element from the front of the queue
# let us try to build a queue using an array
# we will have a few functions
# one to queue new elements
# one to dequeue elements
# one to print the queue
# one to get the front of the queue
# one to get the end of the queue
# one to check if the queue is empty
class OurQueue:
def __init__(self):
self.front = -1
self.end = -1
self.elements = []
def queue(self, value):
self.front = self.front + 1
self.elements.insert(self.top, value)
def pop(self):
if (self.top >= 0):
self.top = self.top - 1
else:
print("Cannot pop because the stack is empty.")
def peek(self):
print(self.elements[self.top])
def isEmpty(self):
if(self.top == -1):
return True
else:
return False
def length(self):
return self.top + 1
def display(self):
if(self.top == -1):
print("Stack is empty!")
else:
for i in range(self.top, -1, -1):
print(self.elements[i], end=' ')
# also try out stack with linked lists, and when you do please contrivute to this project right here lol | class Ourqueue:
def __init__(self):
self.front = -1
self.end = -1
self.elements = []
def queue(self, value):
self.front = self.front + 1
self.elements.insert(self.top, value)
def pop(self):
if self.top >= 0:
self.top = self.top - 1
else:
print('Cannot pop because the stack is empty.')
def peek(self):
print(self.elements[self.top])
def is_empty(self):
if self.top == -1:
return True
else:
return False
def length(self):
return self.top + 1
def display(self):
if self.top == -1:
print('Stack is empty!')
else:
for i in range(self.top, -1, -1):
print(self.elements[i], end=' ') |
#!/usr/bin/env python3
def coverage_test_helper():
one = 10 + 3 - 12
print('This function should be called {one} time to achieve 100% coverage')
return one
| def coverage_test_helper():
one = 10 + 3 - 12
print('This function should be called {one} time to achieve 100% coverage')
return one |
class Checksum:
@staticmethod
def calc(data: str):
chksum = Checksum.__str_list2bin(data)
chksum = Checksum.__sum_bytes(chksum)
map(lambda x: bytearray(x + 1)[0], chksum)
return chksum
@staticmethod
def __str_list2bin(data: str) -> list:
map(lambda x: bytearray(x, "utf-8"), data)
return data
@staticmethod
def __sum_bytes(arr: list) -> bytearray:
actual_sum = arr[0]
[actual_sum := Checksum.__overflow(actual_sum, x) + bytearray(actual_sum + x) for x in arr[1:]]
return actual_sum
@staticmethod
def __overflow(actsum, arr) -> bytearray:
if bytearray(actsum, arr)[16] == 1:
return bytearray(b"000000000000001")
else:
return bytearray(b"000000000000000")
| class Checksum:
@staticmethod
def calc(data: str):
chksum = Checksum.__str_list2bin(data)
chksum = Checksum.__sum_bytes(chksum)
map(lambda x: bytearray(x + 1)[0], chksum)
return chksum
@staticmethod
def __str_list2bin(data: str) -> list:
map(lambda x: bytearray(x, 'utf-8'), data)
return data
@staticmethod
def __sum_bytes(arr: list) -> bytearray:
actual_sum = arr[0]
[(actual_sum := (Checksum.__overflow(actual_sum, x) + bytearray(actual_sum + x))) for x in arr[1:]]
return actual_sum
@staticmethod
def __overflow(actsum, arr) -> bytearray:
if bytearray(actsum, arr)[16] == 1:
return bytearray(b'000000000000001')
else:
return bytearray(b'000000000000000') |
async def m001_initial(db):
await db.execute(
"""
CREATE TABLE subdomains.domain (
id TEXT PRIMARY KEY,
wallet TEXT NOT NULL,
domain TEXT NOT NULL,
webhook TEXT,
cf_token TEXT NOT NULL,
cf_zone_id TEXT NOT NULL,
description TEXT NOT NULL,
cost INTEGER NOT NULL,
amountmade INTEGER NOT NULL,
allowed_record_types TEXT NOT NULL,
time TIMESTAMP NOT NULL DEFAULT """
+ db.timestamp_now
+ """
);
"""
)
await db.execute(
"""
CREATE TABLE subdomains.subdomain (
id TEXT PRIMARY KEY,
domain TEXT NOT NULL,
email TEXT NOT NULL,
subdomain TEXT NOT NULL,
ip TEXT NOT NULL,
wallet TEXT NOT NULL,
sats INTEGER NOT NULL,
duration INTEGER NOT NULL,
paid BOOLEAN NOT NULL,
record_type TEXT NOT NULL,
time TIMESTAMP NOT NULL DEFAULT """
+ db.timestamp_now
+ """
);
"""
)
| async def m001_initial(db):
await db.execute('\n CREATE TABLE subdomains.domain (\n id TEXT PRIMARY KEY,\n wallet TEXT NOT NULL,\n domain TEXT NOT NULL,\n webhook TEXT,\n cf_token TEXT NOT NULL,\n cf_zone_id TEXT NOT NULL,\n description TEXT NOT NULL,\n cost INTEGER NOT NULL,\n amountmade INTEGER NOT NULL,\n allowed_record_types TEXT NOT NULL,\n time TIMESTAMP NOT NULL DEFAULT ' + db.timestamp_now + '\n );\n ')
await db.execute('\n CREATE TABLE subdomains.subdomain (\n id TEXT PRIMARY KEY,\n domain TEXT NOT NULL,\n email TEXT NOT NULL,\n subdomain TEXT NOT NULL,\n ip TEXT NOT NULL,\n wallet TEXT NOT NULL,\n sats INTEGER NOT NULL,\n duration INTEGER NOT NULL,\n paid BOOLEAN NOT NULL,\n record_type TEXT NOT NULL,\n time TIMESTAMP NOT NULL DEFAULT ' + db.timestamp_now + '\n );\n ') |
# --------------
##File path for the file
file_path
#Code starts here
#Function to read file
def read_file(path):
#Opening of the file located in the path in 'read' mode
file = open(path, 'r')
#Reading of the first line of the file and storing it in a variable
sentence=file.readline()
#Closing of the file
file.close()
#Returning the first line of the file
return sentence
#Calling the function to read file
sample_message=read_file(file_path)
#Printing the line of the file
print(sample_message)
#Code ends here
# --------------
#Code starts here
#Opening files:
file_1 = open(file_path_1)
file_2 = open(file_path_2)
#Reading & Printing messages:
message_1 = read_file(file_path_1)
print(message_1)
message_2 = read_file(file_path_2)
print(message_2)
#Declaring a function fuse_msg():
def fuse_msg(message_a, message_b):
int_message_a = int(message_a)
int_message_b = int(message_b)
quotient = (int_message_b//int_message_a)
return str(quotient)
#Calling the function fuse_msg():
secret_msg_1 = fuse_msg(message_1,message_2)
print(secret_msg_1)
# --------------
#Code starts here
#Opening file:
file_3 = open(file_path_3)
#Reading file:
message_3 = read_file(file_path_3)
print(message_3)
#Defining a function substitute_msg():
def substitute_msg(message_c):
sub = ''
if str(message_c) == 'Red':
sub = 'Army General'
elif str(message_c) == 'Green':
sub = 'Data Scientist'
elif str(message_c) == 'Blue':
sub = 'Marine Biologist'
return str(sub)
#Calling function substitute_msg():
secret_msg_2 = substitute_msg(message_3)
# --------------
# Opening files:
file_4 = open(file_path_4)
file_5 = open(file_path_5)
# Reading files:
message_4 = read_file(file_path_4)
message_5 = read_file(file_path_5)
print(message_4)
print(message_5)
# Declaring function compare_msg():
def compare_msg(message_d, message_e):
a_list = message_d.split(' ')
b_list = message_e.split(' ')
c_list = [i for i in a_list + b_list if i not in b_list]
final_msg = ' '.join(c_list)
return final_msg
# Calling function compare_msg():
secret_msg_3 = compare_msg(message_4, message_5)
#Code starts here
# --------------
#Code starts here
#Opening file:
file_6 = open(file_path_6)
#Reading file:
message_6 = read_file(file_path_6)
print(message_6)
#Declaring function extract_msg():
def extract_msg(message_f):
a_list = message_f.split(' ')
even_word = lambda x : (len(x)%2 == 0)
b_list = filter(even_word, a_list)
final_msg = ' '.join(b_list)
return str(final_msg)
#Calling function extract_msg():
secret_msg_4 = extract_msg(message_6)
print(secret_msg_4)
# --------------
#Secret message parts in the correct order
message_parts=[secret_msg_3, secret_msg_1, secret_msg_4, secret_msg_2]
final_path= user_data_dir + '/secret_message.txt'
#Code starts here
secret_msg = ' '.join(message_parts)
print(secret_msg)
#Declaraing function write_file():
def write_file(secret_msg, path):
file_final = open(path, mode='a+')
file_final.write(' '.join(secret_msg))
file_final.close()
#Calling function write_file():
ans = write_file(secret_msg, final_path)
print(ans)
| file_path
def read_file(path):
file = open(path, 'r')
sentence = file.readline()
file.close()
return sentence
sample_message = read_file(file_path)
print(sample_message)
file_1 = open(file_path_1)
file_2 = open(file_path_2)
message_1 = read_file(file_path_1)
print(message_1)
message_2 = read_file(file_path_2)
print(message_2)
def fuse_msg(message_a, message_b):
int_message_a = int(message_a)
int_message_b = int(message_b)
quotient = int_message_b // int_message_a
return str(quotient)
secret_msg_1 = fuse_msg(message_1, message_2)
print(secret_msg_1)
file_3 = open(file_path_3)
message_3 = read_file(file_path_3)
print(message_3)
def substitute_msg(message_c):
sub = ''
if str(message_c) == 'Red':
sub = 'Army General'
elif str(message_c) == 'Green':
sub = 'Data Scientist'
elif str(message_c) == 'Blue':
sub = 'Marine Biologist'
return str(sub)
secret_msg_2 = substitute_msg(message_3)
file_4 = open(file_path_4)
file_5 = open(file_path_5)
message_4 = read_file(file_path_4)
message_5 = read_file(file_path_5)
print(message_4)
print(message_5)
def compare_msg(message_d, message_e):
a_list = message_d.split(' ')
b_list = message_e.split(' ')
c_list = [i for i in a_list + b_list if i not in b_list]
final_msg = ' '.join(c_list)
return final_msg
secret_msg_3 = compare_msg(message_4, message_5)
file_6 = open(file_path_6)
message_6 = read_file(file_path_6)
print(message_6)
def extract_msg(message_f):
a_list = message_f.split(' ')
even_word = lambda x: len(x) % 2 == 0
b_list = filter(even_word, a_list)
final_msg = ' '.join(b_list)
return str(final_msg)
secret_msg_4 = extract_msg(message_6)
print(secret_msg_4)
message_parts = [secret_msg_3, secret_msg_1, secret_msg_4, secret_msg_2]
final_path = user_data_dir + '/secret_message.txt'
secret_msg = ' '.join(message_parts)
print(secret_msg)
def write_file(secret_msg, path):
file_final = open(path, mode='a+')
file_final.write(' '.join(secret_msg))
file_final.close()
ans = write_file(secret_msg, final_path)
print(ans) |
# Adapted from: https://stackoverflow.com/questions/37935920/quantile-normalization-on-pandas-dataframe
# Citing: https://en.wikipedia.org/wiki/Quantile_normalization
class QNorm:
def __init__(self):
return
def fit(self,df):
return _QNormFit(self,df.stack().groupby(df.rank(method='first').stack().astype(int)).mean())
def fit_transform(self,df):
return self.fit(df).transform(df)
class _QNormFit:
def __init__(self,parent,df):
self.qnorm = parent
self.rank_mean = df
return
def transform(self,df):
return df.rank(method='min').stack().astype(int).map(self.rank_mean).unstack()
| class Qnorm:
def __init__(self):
return
def fit(self, df):
return _q_norm_fit(self, df.stack().groupby(df.rank(method='first').stack().astype(int)).mean())
def fit_transform(self, df):
return self.fit(df).transform(df)
class _Qnormfit:
def __init__(self, parent, df):
self.qnorm = parent
self.rank_mean = df
return
def transform(self, df):
return df.rank(method='min').stack().astype(int).map(self.rank_mean).unstack() |
class PluginError(Exception):
pass
class OneLoginClientError(PluginError):
pass
class UserNotFound(PluginError):
pass
class FactorNotFound(PluginError):
pass
class TimeOutError(PluginError):
pass
class APIResponseError(PluginError):
pass | class Pluginerror(Exception):
pass
class Oneloginclienterror(PluginError):
pass
class Usernotfound(PluginError):
pass
class Factornotfound(PluginError):
pass
class Timeouterror(PluginError):
pass
class Apiresponseerror(PluginError):
pass |
YES = "LuckyChef"
NO = "UnluckyChef"
def solve():
for _ in range(int(input())):
x, y, k, n = map(int, input().split())
arr = []
for __ in range(n):
arr.append(list(map(int, input().split())))
remaining_pages = x - y
if remaining_pages <= 0:
print(YES)
continue
for pages, price in arr:
if pages >= remaining_pages and price <= k:
print(YES)
break
else:
print(NO)
solve()
| yes = 'LuckyChef'
no = 'UnluckyChef'
def solve():
for _ in range(int(input())):
(x, y, k, n) = map(int, input().split())
arr = []
for __ in range(n):
arr.append(list(map(int, input().split())))
remaining_pages = x - y
if remaining_pages <= 0:
print(YES)
continue
for (pages, price) in arr:
if pages >= remaining_pages and price <= k:
print(YES)
break
else:
print(NO)
solve() |
class Board:
def __init__(self, lines):
self.data = []
self.has_won = False
for i, l in enumerate(lines):
self.data.append([int(x) for x in l.split()])
def __str__(self):
return str(self.data)
def __repr__(self):
return str(self)
def final_score(self, called_numbers, just_called):
uncalled = self.uncalled_numbers(called_numbers)
print(f"Board score: {sum(uncalled) * int(just_called)}")
def uncalled_numbers(self, called):
nums = []
for row in self.data:
nums.extend(row)
not_called = list(set(nums) - set(called))
return not_called
def won(self, called):
called = set(called)
# horzontally
for row in self.data:
if set(row).issubset(called):
return True
# vertically
for x in range(5):
s = set()
for y in range(5):
s.add(self.data[y][x])
if s.issubset(called):
return True
return False
if __name__ == "__main__":
lines = open('../input.txt', 'r').readlines()
called = lines[0]
boards = []
accum = []
for l in lines[1:]:
if not l.strip() and accum:
boards.append(Board(accum))
accum = []
else:
accum.append(l.strip())
called_numbers = []
won = False
last_board = None
boards = boards[1:]
for call in called.split(','):
called_numbers.append(int(call))
for b in boards:
if b.won(called_numbers):
b.has_won = True
non_winning_boards = [x for x in boards if x.has_won == False]
if len(non_winning_boards) == 1:
last_board = non_winning_boards[0]
if last_board and last_board.has_won:
print(last_board.final_score(called_numbers, just_called=call))
break
hide = """
data = "20 87 16 25 9
15 70 19 72 56
71 37 69 2 62
76 97 41 8 92
40 65 86 0 32"
data = data.split('\n')
b = Board(data)
print(b.data)
print(b.won([15,70,19,72,56]))
print(b.won([20,15,71,76,40]))
print(b.won([16,22,7,19,2,69,80,41,82]))
""" | class Board:
def __init__(self, lines):
self.data = []
self.has_won = False
for (i, l) in enumerate(lines):
self.data.append([int(x) for x in l.split()])
def __str__(self):
return str(self.data)
def __repr__(self):
return str(self)
def final_score(self, called_numbers, just_called):
uncalled = self.uncalled_numbers(called_numbers)
print(f'Board score: {sum(uncalled) * int(just_called)}')
def uncalled_numbers(self, called):
nums = []
for row in self.data:
nums.extend(row)
not_called = list(set(nums) - set(called))
return not_called
def won(self, called):
called = set(called)
for row in self.data:
if set(row).issubset(called):
return True
for x in range(5):
s = set()
for y in range(5):
s.add(self.data[y][x])
if s.issubset(called):
return True
return False
if __name__ == '__main__':
lines = open('../input.txt', 'r').readlines()
called = lines[0]
boards = []
accum = []
for l in lines[1:]:
if not l.strip() and accum:
boards.append(board(accum))
accum = []
else:
accum.append(l.strip())
called_numbers = []
won = False
last_board = None
boards = boards[1:]
for call in called.split(','):
called_numbers.append(int(call))
for b in boards:
if b.won(called_numbers):
b.has_won = True
non_winning_boards = [x for x in boards if x.has_won == False]
if len(non_winning_boards) == 1:
last_board = non_winning_boards[0]
if last_board and last_board.has_won:
print(last_board.final_score(called_numbers, just_called=call))
break
hide = '\n data = "20 87 16 25 9\n15 70 19 72 56\n71 37 69 2 62\n76 97 41 8 92\n40 65 86 0 32"\n data = data.split(\'\n\')\n b = Board(data)\n print(b.data)\n print(b.won([15,70,19,72,56]))\n print(b.won([20,15,71,76,40]))\n print(b.won([16,22,7,19,2,69,80,41,82]))\n' |
#!/usr/bin/env python3
NUMBER_OF_DIVS = 25
INCL_SPACES = True
divString = """
<div class="item{}">
<img class="rounded-img carousel-img" id="carousel-img-{}" src="images/sample.png" alt="Pic{}">
</div>
"""
if(INCL_SPACES):
divString = """
<div class="item{}">
<img class="rounded-img carousel-img" id="carousel-img-{}" src="images/sample.png" alt="Pic{}">
</div>
"""
else:
divString = """
<div class="item{}">
<img class="rounded-img carousel-img" id="carousel-img-{}" src="images/sample.png" alt="Pic{}">
</div>
"""
activeString = " active"
for divNum in range(NUMBER_OF_DIVS):
if(divNum == 0):
print(divString.format(activeString, divNum, divNum), end='')
continue
print(divString.format('', divNum, divNum), end='')
| number_of_divs = 25
incl_spaces = True
div_string = '\n<div class="item{}">\n <img class="rounded-img carousel-img" id="carousel-img-{}" src="images/sample.png" alt="Pic{}">\n</div>\n'
if INCL_SPACES:
div_string = '\n <div class="item{}">\n <img class="rounded-img carousel-img" id="carousel-img-{}" src="images/sample.png" alt="Pic{}">\n </div>\n\t'
else:
div_string = '\n<div class="item{}">\n <img class="rounded-img carousel-img" id="carousel-img-{}" src="images/sample.png" alt="Pic{}">\n</div>\n'
active_string = ' active'
for div_num in range(NUMBER_OF_DIVS):
if divNum == 0:
print(divString.format(activeString, divNum, divNum), end='')
continue
print(divString.format('', divNum, divNum), end='') |
nome = input('Digite seu nome completo: ')
nomem = nome.upper()
nomemin = nome.lower()
fat = nome.split()
juntin = '-'.join(fat)
nomefatiado = nome.replace(" ", "")
print(len(nomefatiado))
print(nomemin)
print(nomem)
print(len(fat[0]))
print(fat)
print(juntin) | nome = input('Digite seu nome completo: ')
nomem = nome.upper()
nomemin = nome.lower()
fat = nome.split()
juntin = '-'.join(fat)
nomefatiado = nome.replace(' ', '')
print(len(nomefatiado))
print(nomemin)
print(nomem)
print(len(fat[0]))
print(fat)
print(juntin) |
def write_tsv(headerfields, features, outfn):
"""Writes header and generator of lines to tab separated file.
headerfields - list of field names in header in correct order
features - generates 1 list per line that belong to header
outfn - filename to output to. Overwritten if exists
"""
with open(outfn, 'w') as fp:
write_tsv_line_from_list(headerfields, fp)
for line in features:
write_tsv_line_from_list([str(line[field]) for field
in headerfields], fp)
def write_tsv_line_from_list(linelist, outfp):
"""Utility method to convert list to tsv line with carriage return"""
line = '\t'.join(linelist)
outfp.write(line)
outfp.write('\n')
def parse_NA(feature, header):
for field in header:
try:
feature[field] = str(feature[field])
except KeyError:
feature[field] = 'NA'
return feature
| def write_tsv(headerfields, features, outfn):
"""Writes header and generator of lines to tab separated file.
headerfields - list of field names in header in correct order
features - generates 1 list per line that belong to header
outfn - filename to output to. Overwritten if exists
"""
with open(outfn, 'w') as fp:
write_tsv_line_from_list(headerfields, fp)
for line in features:
write_tsv_line_from_list([str(line[field]) for field in headerfields], fp)
def write_tsv_line_from_list(linelist, outfp):
"""Utility method to convert list to tsv line with carriage return"""
line = '\t'.join(linelist)
outfp.write(line)
outfp.write('\n')
def parse_na(feature, header):
for field in header:
try:
feature[field] = str(feature[field])
except KeyError:
feature[field] = 'NA'
return feature |
if __name__ == '__main__':
n = int(input())
arr = map(int, input().split())
# Copy original array
new_arr = set(arr)
# Remove max values
new_arr.remove(max(new_arr))
# Print new max (2nd max)
print(max(new_arr))
| if __name__ == '__main__':
n = int(input())
arr = map(int, input().split())
new_arr = set(arr)
new_arr.remove(max(new_arr))
print(max(new_arr)) |
a, b, c = map(int, input().split())
if b - a == c - b:
print("YES")
else:
print("NO") | (a, b, c) = map(int, input().split())
if b - a == c - b:
print('YES')
else:
print('NO') |
# https://leetcode.com/problems/longest-valid-parentheses/
# Given a string containing just the characters '(' and ')', find the length of
# the longest valid (well-formed) parentheses substring.
################################################################################
# dp[i] = longest valid of s[i:n] starting with s[i] -> travel backwards
# s[i], [valid of len = dp[i+1]], s[j], [valid of len = dp[j+1]], ...
class Solution:
def longestValidParentheses(self, s: str) -> int:
if len(s) <= 1: return 0
n = len(s)
ans = 0
dp = [0] * n
for i in range(n - 2, -1, -1):
if s[i] == "(":
# loop for ")" at j: s[i], [valid of len = dp[i+1]], s[j]
j = i + dp[i + 1] + 1
if j < n and s[j] == ")":
dp[i] = dp[i + 1] + 2
if j + 1 < n: # cumlative valid length starting with s[j+1]
dp[i] += dp[j + 1]
return max(dp)
| class Solution:
def longest_valid_parentheses(self, s: str) -> int:
if len(s) <= 1:
return 0
n = len(s)
ans = 0
dp = [0] * n
for i in range(n - 2, -1, -1):
if s[i] == '(':
j = i + dp[i + 1] + 1
if j < n and s[j] == ')':
dp[i] = dp[i + 1] + 2
if j + 1 < n:
dp[i] += dp[j + 1]
return max(dp) |
def fizz_buzz(n):
for fizz_buzz in range(n+1):
if fizz_buzz % 3 == 0 and fizz_buzz % 5 == 0:
print("fizzbuzz")
continue
elif fizz_buzz % 3 == 0:
print("fizz")
continue
elif fizz_buzz % 5 == 0:
print("buzz")
print(fizz_buzz)
fizz_buzz(26)
if __name__ == "__main__":
fizz_buzz(100) | def fizz_buzz(n):
for fizz_buzz in range(n + 1):
if fizz_buzz % 3 == 0 and fizz_buzz % 5 == 0:
print('fizzbuzz')
continue
elif fizz_buzz % 3 == 0:
print('fizz')
continue
elif fizz_buzz % 5 == 0:
print('buzz')
print(fizz_buzz)
fizz_buzz(26)
if __name__ == '__main__':
fizz_buzz(100) |
"""Unix shell commands toolchain support.
Defines a toolchain capturing common Unix shell commands as defined by IEEE
1003.1-2008 (POSIX), see `sh_posix_toolchain`, and `sh_posix_configure` to scan
the local environment for shell commands. The list of known commands is
available in `posix.commands`.
"""
load("@bazel_skylib//lib:paths.bzl", "paths")
load("@bazel_tools//tools/cpp:lib_cc_configure.bzl", "get_cpu_value")
# List of Unix commands as specified by IEEE Std 1003.1-2008.
# Extracted from https://en.wikipedia.org/wiki/List_of_Unix_commands.
_commands = [
"admin",
"alias",
"ar",
"asa",
"at",
"awk",
"basename",
"batch",
"bc",
"bg",
"cc",
"c99",
"cal",
"cat",
"cd",
"cflow",
"chgrp",
"chmod",
"chown",
"cksum",
"cmp",
"comm",
"command",
"compress",
"cp",
"crontab",
"csplit",
"ctags",
"cut",
"cxref",
"date",
"dd",
"delta",
"df",
"diff",
"dirname",
"du",
"echo",
"ed",
"env",
"ex",
"expand",
"expr",
"false",
"fc",
"fg",
"file",
"find",
"fold",
"fort77",
"fuser",
"gencat",
"get",
"getconf",
"getopts",
"grep",
"hash",
"head",
"iconv",
"id",
"ipcrm",
"ipcs",
"jobs",
"join",
"kill",
"lex",
"link",
"ln",
"locale",
"localedef",
"logger",
"logname",
"lp",
"ls",
"m4",
"mailx",
"make",
"man",
"mesg",
"mkdir",
"mkfifo",
"more",
"mv",
"newgrp",
"nice",
"nl",
"nm",
"nohup",
"od",
"paste",
"patch",
"pathchk",
"pax",
"pr",
"printf",
"prs",
"ps",
"pwd",
"qalter",
"qdel",
"qhold",
"qmove",
"qmsg",
"qrerun",
"qrls",
"qselect",
"qsig",
"qstat",
"qsub",
"read",
"renice",
"rm",
"rmdel",
"rmdir",
"sact",
"sccs",
"sed",
"sh",
"sleep",
"sort",
"split",
"strings",
"strip",
"stty",
"tabs",
"tail",
"talk",
"tee",
"test",
"time",
"touch",
"tput",
"tr",
"true",
"tsort",
"tty",
"type",
"ulimit",
"umask",
"unalias",
"uname",
"uncompress",
"unexpand",
"unget",
"uniq",
"unlink",
"uucp",
"uudecode",
"uuencode",
"uustat",
"uux",
"val",
"vi",
"wait",
"wc",
"what",
"who",
"write",
"xargs",
"yacc",
"zcat",
]
TOOLCHAIN_TYPE = "@rules_sh//sh/posix:toolchain_type"
MAKE_VARIABLES = "@rules_sh//sh/posix:make_variables"
def _sh_posix_toolchain_impl(ctx):
commands = {}
cmds = ctx.attr.cmds
for cmd in _commands:
cmd_path = cmds.get(cmd, None)
if not cmd_path:
cmd_path = None
commands[cmd] = cmd_path
unrecognizeds = [cmd for cmd in cmds.keys() if cmd not in _commands]
if unrecognizeds:
fail("Unrecognized commands in keys of sh_posix_toolchain's \"cmds\" attributes: {}. See posix.commands in @rules_sh//sh:posix.bzl for the list of recognized commands.".format(", ".join(unrecognizeds)))
cmd_paths = {
paths.dirname(cmd_path): None
for cmd_path in commands.values()
if cmd_path
}.keys()
return [platform_common.ToolchainInfo(
commands = commands,
paths = cmd_paths,
)]
sh_posix_toolchain = rule(
attrs = {
"cmds": attr.string_dict(
doc = "dict where keys are command names and values are paths",
mandatory = True,
)
},
doc = """
A toolchain capturing standard Unix shell commands.
Provides:
commands: Dict of String, an item per command holding the path to the executable or None.
paths: List of String, deduplicated bindir paths. Suitable for generating `$PATH`.
Use `sh_posix_configure` to create an instance of this toolchain.
See `sh_posix_make_variables` on how to use this toolchain in genrules.
""",
implementation = _sh_posix_toolchain_impl,
)
def _sh_posix_make_variables_impl(ctx):
toolchain = ctx.toolchains[TOOLCHAIN_TYPE]
cmd_vars = {
"POSIX_%s" % cmd.upper(): cmd_path
for cmd in _commands
for cmd_path in [toolchain.commands[cmd]]
if cmd_path
}
return [platform_common.TemplateVariableInfo(cmd_vars)]
sh_posix_make_variables = rule(
doc = """
Provides POSIX toolchain commands as custom make variables.
Make variables:
Provides a make variable of the form `POSIX_<COMMAND>` for each available
command, where `<COMMAND>` is the name of the command in upper case.
Use `posix.MAKE_VARIABLES` instead of instantiating this rule yourself.
Example:
>>> genrule(
name = "use-grep",
srcs = [":some-file"],
outs = ["grep-out"],
cmd = "$(POSIX_GREP) search $(execpath :some-file) > $(OUTS)",
toolchains = [posix.MAKE_VARIABLES],
)
""",
implementation = _sh_posix_make_variables_impl,
toolchains = [TOOLCHAIN_TYPE],
)
def _windows_detect_sh_dir(repository_ctx):
# Taken and adapted from @bazel_tools//tools/sh/sh_configure.bzl.
sh_path = repository_ctx.os.environ.get("BAZEL_SH")
if not sh_path:
sh_path = repository_ctx.which("bash.exe")
if sh_path:
# repository_ctx.which returns a path object, convert that to
# string so we can call string.startswith on it.
sh_path = str(sh_path)
# When the Windows Subsystem for Linux is installed there's a
# bash.exe under %WINDIR%\system32\bash.exe that launches Ubuntu
# Bash which cannot run native Windows programs so it's not what
# we want.
windir = repository_ctx.os.environ.get("WINDIR")
if windir and sh_path.startswith(windir):
sh_path = None
if sh_path != None:
sh_dir = str(repository_ctx.path(sh_path).dirname)
return sh_dir
def _sh_posix_config_impl(repository_ctx):
cpu = get_cpu_value(repository_ctx)
env = repository_ctx.os.environ
windows_sh_dir = None
if cpu == "x64_windows":
windows_sh_dir = _windows_detect_sh_dir(repository_ctx)
commands = {}
for cmd in _commands:
cmd_path = env.get("POSIX_%s" % cmd.upper(), None)
if cmd_path == None and cpu != "x64_windows":
cmd_path = repository_ctx.which(cmd)
elif cmd_path == None and cpu == "x64_windows":
# Autodetection using `repository_ctx.which` is not safe on
# Windows, as it may turn up false friends. E.g. Windows has a
# `find.exe` which is unrelated to POSIX `find`. Instead we use
# tools next to `bash.exe`.
cmd_path = repository_ctx.path(windows_sh_dir + "/" + cmd + ".exe")
if not cmd_path.exists:
cmd_path = None
commands[cmd] = cmd_path
repository_ctx.file("BUILD.bazel", executable = False, content = """
load("@rules_sh//sh:posix.bzl", "sh_posix_toolchain")
sh_posix_toolchain(
name = "local_posix",
visibility = ["//visibility:public"],
cmds = {{
{commands}
}}
)
toolchain(
name = "local_posix_toolchain",
toolchain = ":local_posix",
toolchain_type = "{toolchain_type}",
exec_compatible_with = [
"@platforms//cpu:x86_64",
"@platforms//os:{os}",
],
)
""".format(
commands = ",\n ".join([
'"{cmd}": "{path}"'.format(cmd = cmd, path = cmd_path)
for (cmd, cmd_path) in commands.items()
if cmd_path
]),
os = {
"darwin": "osx",
"x64_windows": "windows",
}.get(cpu, "linux"),
toolchain_type = TOOLCHAIN_TYPE,
))
_sh_posix_config = repository_rule(
configure = True,
environ = ["PATH"] + [
"POSIX_%s" % cmd.upper()
for cmd in _commands
],
local = True,
implementation = _sh_posix_config_impl,
)
def sh_posix_configure(name = "local_posix_config"):
"""Autodetect local Unix commands.
Scans the environment (`$PATH`) for standard shell commands, generates a
corresponding POSIX toolchain and registers the toolchain.
You can override the autodetection for individual commands by setting
environment variables of the form `POSIX_<COMMAND>`. E.g.
`POSIX_MAKE=/usr/bin/gmake` will override the make command.
"""
_sh_posix_config(name = name)
native.register_toolchains("@{}//:local_posix_toolchain".format(name))
posix = struct(
commands = _commands,
TOOLCHAIN_TYPE = TOOLCHAIN_TYPE,
MAKE_VARIABLES = MAKE_VARIABLES,
)
| """Unix shell commands toolchain support.
Defines a toolchain capturing common Unix shell commands as defined by IEEE
1003.1-2008 (POSIX), see `sh_posix_toolchain`, and `sh_posix_configure` to scan
the local environment for shell commands. The list of known commands is
available in `posix.commands`.
"""
load('@bazel_skylib//lib:paths.bzl', 'paths')
load('@bazel_tools//tools/cpp:lib_cc_configure.bzl', 'get_cpu_value')
_commands = ['admin', 'alias', 'ar', 'asa', 'at', 'awk', 'basename', 'batch', 'bc', 'bg', 'cc', 'c99', 'cal', 'cat', 'cd', 'cflow', 'chgrp', 'chmod', 'chown', 'cksum', 'cmp', 'comm', 'command', 'compress', 'cp', 'crontab', 'csplit', 'ctags', 'cut', 'cxref', 'date', 'dd', 'delta', 'df', 'diff', 'dirname', 'du', 'echo', 'ed', 'env', 'ex', 'expand', 'expr', 'false', 'fc', 'fg', 'file', 'find', 'fold', 'fort77', 'fuser', 'gencat', 'get', 'getconf', 'getopts', 'grep', 'hash', 'head', 'iconv', 'id', 'ipcrm', 'ipcs', 'jobs', 'join', 'kill', 'lex', 'link', 'ln', 'locale', 'localedef', 'logger', 'logname', 'lp', 'ls', 'm4', 'mailx', 'make', 'man', 'mesg', 'mkdir', 'mkfifo', 'more', 'mv', 'newgrp', 'nice', 'nl', 'nm', 'nohup', 'od', 'paste', 'patch', 'pathchk', 'pax', 'pr', 'printf', 'prs', 'ps', 'pwd', 'qalter', 'qdel', 'qhold', 'qmove', 'qmsg', 'qrerun', 'qrls', 'qselect', 'qsig', 'qstat', 'qsub', 'read', 'renice', 'rm', 'rmdel', 'rmdir', 'sact', 'sccs', 'sed', 'sh', 'sleep', 'sort', 'split', 'strings', 'strip', 'stty', 'tabs', 'tail', 'talk', 'tee', 'test', 'time', 'touch', 'tput', 'tr', 'true', 'tsort', 'tty', 'type', 'ulimit', 'umask', 'unalias', 'uname', 'uncompress', 'unexpand', 'unget', 'uniq', 'unlink', 'uucp', 'uudecode', 'uuencode', 'uustat', 'uux', 'val', 'vi', 'wait', 'wc', 'what', 'who', 'write', 'xargs', 'yacc', 'zcat']
toolchain_type = '@rules_sh//sh/posix:toolchain_type'
make_variables = '@rules_sh//sh/posix:make_variables'
def _sh_posix_toolchain_impl(ctx):
commands = {}
cmds = ctx.attr.cmds
for cmd in _commands:
cmd_path = cmds.get(cmd, None)
if not cmd_path:
cmd_path = None
commands[cmd] = cmd_path
unrecognizeds = [cmd for cmd in cmds.keys() if cmd not in _commands]
if unrecognizeds:
fail('Unrecognized commands in keys of sh_posix_toolchain\'s "cmds" attributes: {}. See posix.commands in @rules_sh//sh:posix.bzl for the list of recognized commands.'.format(', '.join(unrecognizeds)))
cmd_paths = {paths.dirname(cmd_path): None for cmd_path in commands.values() if cmd_path}.keys()
return [platform_common.ToolchainInfo(commands=commands, paths=cmd_paths)]
sh_posix_toolchain = rule(attrs={'cmds': attr.string_dict(doc='dict where keys are command names and values are paths', mandatory=True)}, doc='\nA toolchain capturing standard Unix shell commands.\n\nProvides:\n commands: Dict of String, an item per command holding the path to the executable or None.\n paths: List of String, deduplicated bindir paths. Suitable for generating `$PATH`.\n\nUse `sh_posix_configure` to create an instance of this toolchain.\nSee `sh_posix_make_variables` on how to use this toolchain in genrules.\n', implementation=_sh_posix_toolchain_impl)
def _sh_posix_make_variables_impl(ctx):
toolchain = ctx.toolchains[TOOLCHAIN_TYPE]
cmd_vars = {'POSIX_%s' % cmd.upper(): cmd_path for cmd in _commands for cmd_path in [toolchain.commands[cmd]] if cmd_path}
return [platform_common.TemplateVariableInfo(cmd_vars)]
sh_posix_make_variables = rule(doc='\nProvides POSIX toolchain commands as custom make variables.\n\nMake variables:\n Provides a make variable of the form `POSIX_<COMMAND>` for each available\n command, where `<COMMAND>` is the name of the command in upper case.\n\nUse `posix.MAKE_VARIABLES` instead of instantiating this rule yourself.\n\nExample:\n >>> genrule(\n name = "use-grep",\n srcs = [":some-file"],\n outs = ["grep-out"],\n cmd = "$(POSIX_GREP) search $(execpath :some-file) > $(OUTS)",\n toolchains = [posix.MAKE_VARIABLES],\n )\n', implementation=_sh_posix_make_variables_impl, toolchains=[TOOLCHAIN_TYPE])
def _windows_detect_sh_dir(repository_ctx):
sh_path = repository_ctx.os.environ.get('BAZEL_SH')
if not sh_path:
sh_path = repository_ctx.which('bash.exe')
if sh_path:
sh_path = str(sh_path)
windir = repository_ctx.os.environ.get('WINDIR')
if windir and sh_path.startswith(windir):
sh_path = None
if sh_path != None:
sh_dir = str(repository_ctx.path(sh_path).dirname)
return sh_dir
def _sh_posix_config_impl(repository_ctx):
cpu = get_cpu_value(repository_ctx)
env = repository_ctx.os.environ
windows_sh_dir = None
if cpu == 'x64_windows':
windows_sh_dir = _windows_detect_sh_dir(repository_ctx)
commands = {}
for cmd in _commands:
cmd_path = env.get('POSIX_%s' % cmd.upper(), None)
if cmd_path == None and cpu != 'x64_windows':
cmd_path = repository_ctx.which(cmd)
elif cmd_path == None and cpu == 'x64_windows':
cmd_path = repository_ctx.path(windows_sh_dir + '/' + cmd + '.exe')
if not cmd_path.exists:
cmd_path = None
commands[cmd] = cmd_path
repository_ctx.file('BUILD.bazel', executable=False, content='\nload("@rules_sh//sh:posix.bzl", "sh_posix_toolchain")\nsh_posix_toolchain(\n name = "local_posix",\n visibility = ["//visibility:public"],\n cmds = {{\n {commands}\n }}\n)\ntoolchain(\n name = "local_posix_toolchain",\n toolchain = ":local_posix",\n toolchain_type = "{toolchain_type}",\n exec_compatible_with = [\n "@platforms//cpu:x86_64",\n "@platforms//os:{os}",\n ],\n)\n'.format(commands=',\n '.join(['"{cmd}": "{path}"'.format(cmd=cmd, path=cmd_path) for (cmd, cmd_path) in commands.items() if cmd_path]), os={'darwin': 'osx', 'x64_windows': 'windows'}.get(cpu, 'linux'), toolchain_type=TOOLCHAIN_TYPE))
_sh_posix_config = repository_rule(configure=True, environ=['PATH'] + ['POSIX_%s' % cmd.upper() for cmd in _commands], local=True, implementation=_sh_posix_config_impl)
def sh_posix_configure(name='local_posix_config'):
"""Autodetect local Unix commands.
Scans the environment (`$PATH`) for standard shell commands, generates a
corresponding POSIX toolchain and registers the toolchain.
You can override the autodetection for individual commands by setting
environment variables of the form `POSIX_<COMMAND>`. E.g.
`POSIX_MAKE=/usr/bin/gmake` will override the make command.
"""
_sh_posix_config(name=name)
native.register_toolchains('@{}//:local_posix_toolchain'.format(name))
posix = struct(commands=_commands, TOOLCHAIN_TYPE=TOOLCHAIN_TYPE, MAKE_VARIABLES=MAKE_VARIABLES) |
#import GreenMindLib
msg_menu = '''
Use: sudo ./green -u http://businesscorp.com.br -o teste.txt \n\n
Green Recon
=============
Command Description
------- -----------
greenrecon Start recon OSINT
recon Suite recon OSINT
google_search Recon google search
shodan_search Recon shodan search
hostname Recon IP using URL
whois Search whois
traceroute Recon traceroute
check_robots Check Robots.txt
archive_search Search archive history
check_cms Check CMS
sharingmyip Check using http://sharingmyip.com
Use:
greenrecon http://businesscorp.com.br teste.txt
recon google_search https://greenmindlabs.com
recon shodan_search 37.59.174.225
recon hostname http://businesscorp.com.br
recon whois 37.59.174.225
recon traceroute http://businesscorp.com.br
recon check_robots http://businesscorp.com.br
recon archive_search http://businesscorp.com.br
recon check_cms https://greenmindlabs.com
recon sharingmyip https://greenmindlabs.com
Core Commands
=============
Command Description
------- -----------
? Help menu
exit Exit the console
help Help menu
version Show the version numbers
Green Cripto
=============
Command Description
------- -----------
cripto
reverse Reverse string
encrypt_base64 Encrypt Base64
decrypt_base64 Decrypt Base64
encrypt_md5 Encrypt MD5
encrypt_sha1 Encrypt SHA1
encrypt_sha256 Encrypt SHA256
encrypt_sha512 Encrypt SHA512
Use:
cripto reverse "54321"
cripto encrypt_base64 teste
cripto decrypt_base64 dGVzdGU=
cripto encrypt_md5 teste
cripto encrypt_sha1 teste
cripto encrypt_sha256 teste
cripto encrypt_sha512 teste
System Backend Commands
============================
Command Description
------- -----------
help Menu help
exit Green exit program
'''
msg_menu2 = '''
Green Basic Commands
=============
Command Description
------- -----------
greenrecon Start recon
Core Commands
=============
Command Description
------- -----------
? Help menu
exit Exit the console
help Help menu
version Show the version numbers
Brute Force Commands
========================
Command Description
------- -----------
bruteforce_linux Brute force attack on a Linux password
bruteforce_windows_nt Brute force attack on Windows NT
bruteforce_windows_lm Brute force attack on Windows LM
Green Cripto
=============
Command Description
------- -----------
cripto
reverse Reverse string
encrypt_base64 Encrypt Base64
decrypt_base64 Decrypt Base64
encrypt_md5 Encrypt MD5
encrypt_sha1 Encrypt SHA1
encrypt_sha256 Encrypt SHA256
encrypt_sha512 Encrypt SHA512
Use:
cripto reverse "54321"
System Backend Commands
============================
Command Description
------- -----------
reverse_shell Reverse shell using netcat
pwd Current directory
ls List dir
help Menu help
exit Green exit program
'''
msg_cripto='''
Green Cripto
=============
Command Description
------- -----------
cripto
reverse Reverse string
encrypt_base64 Encrypt Base64
decrypt_base64 Decrypt Base64
encrypt_md5 Encrypt MD5
encrypt_sha1 Encrypt SHA1
encrypt_sha256 Encrypt SHA256
encrypt_sha512 Encrypt SHA512
Use:
cripto reverse "54321"
'''
msg_set='''
Green Set
=============
Command Description
------- -----------
set
payload Insert payload
Use: set payload "web"
'''
| msg_menu = '\n\n Use: sudo ./green -u http://businesscorp.com.br -o teste.txt \n\n\nGreen Recon\n=============\n\n Command Description\n ------- -----------\n greenrecon Start recon OSINT\n recon Suite recon OSINT\n google_search Recon google search\n shodan_search Recon shodan search\n hostname Recon IP using URL\n whois Search whois\n traceroute Recon traceroute\n check_robots Check Robots.txt\n archive_search Search archive history\n check_cms Check CMS\n sharingmyip Check using http://sharingmyip.com\n Use:\n greenrecon http://businesscorp.com.br teste.txt\n recon google_search https://greenmindlabs.com\n recon shodan_search 37.59.174.225\n recon hostname http://businesscorp.com.br\n recon whois 37.59.174.225\n recon traceroute http://businesscorp.com.br\n recon check_robots http://businesscorp.com.br\n recon archive_search http://businesscorp.com.br\n recon check_cms https://greenmindlabs.com\n recon sharingmyip https://greenmindlabs.com\n\nCore Commands\n=============\n\n Command Description\n ------- -----------\n ? Help menu\n exit Exit the console\n help Help menu\n version Show the version numbers\n\nGreen Cripto\n=============\n\n Command Description\n ------- -----------\n cripto\n reverse Reverse string\n encrypt_base64 Encrypt Base64\n decrypt_base64 Decrypt Base64\n encrypt_md5 Encrypt MD5\n encrypt_sha1 Encrypt SHA1\n encrypt_sha256 Encrypt SHA256\n encrypt_sha512 Encrypt SHA512\n Use:\n cripto reverse "54321"\n cripto encrypt_base64 teste\n cripto decrypt_base64 dGVzdGU=\n cripto encrypt_md5 teste\n cripto encrypt_sha1 teste\n cripto encrypt_sha256 teste\n cripto encrypt_sha512 teste\n\nSystem Backend Commands\n============================\n\n Command Description\n ------- -----------\n help Menu help\n exit Green exit program\n'
msg_menu2 = '\n\nGreen Basic Commands\n=============\n\n Command Description\n ------- -----------\n greenrecon Start recon\n\nCore Commands\n=============\n\n Command Description\n ------- -----------\n ? Help menu\n exit Exit the console\n help Help menu\n version Show the version numbers\n\n\nBrute Force Commands\n========================\n\n Command Description\n ------- -----------\n bruteforce_linux Brute force attack on a Linux password\n bruteforce_windows_nt Brute force attack on Windows NT\n bruteforce_windows_lm Brute force attack on Windows LM\n\nGreen Cripto\n=============\n\n Command Description\n ------- -----------\n cripto\n reverse Reverse string\n encrypt_base64 Encrypt Base64\n decrypt_base64 Decrypt Base64\n encrypt_md5 Encrypt MD5\n encrypt_sha1 Encrypt SHA1\n encrypt_sha256 Encrypt SHA256\n encrypt_sha512 Encrypt SHA512\n Use:\n cripto reverse "54321"\n\nSystem Backend Commands\n============================\n\n Command Description\n ------- -----------\n reverse_shell Reverse shell using netcat\n pwd Current directory\n ls List dir\n help Menu help\n exit Green exit program\n'
msg_cripto = '\nGreen Cripto\n=============\n\n Command Description\n ------- -----------\n cripto\n reverse Reverse string\n encrypt_base64 Encrypt Base64\n decrypt_base64 Decrypt Base64\n encrypt_md5 Encrypt MD5\n encrypt_sha1 Encrypt SHA1\n encrypt_sha256 Encrypt SHA256\n encrypt_sha512 Encrypt SHA512\n Use:\n cripto reverse "54321"\n\n'
msg_set = '\nGreen Set\n=============\n\n Command Description\n ------- -----------\n set\n payload Insert payload\n\n Use: set payload "web"\n' |
"""yolk.
Author: Rob Cakebread <cakebread at gmail>
License : BSD
"""
__version__ = '0.9.5'
| """yolk.
Author: Rob Cakebread <cakebread at gmail>
License : BSD
"""
__version__ = '0.9.5' |
_base_ = [
'../../_base_/default_runtime.py',
'../../_base_/schedules/schedule_sgd_1200e.py',
'../../_base_/det_models/dbnet_r18_fpnc.py',
'../../_base_/det_datasets/icdar2015.py',
'../../_base_/det_pipelines/dbnet_pipeline.py'
]
train_list = {{_base_.train_list}}
test_list = {{_base_.test_list}}
train_pipeline_r18 = {{_base_.train_pipeline_r18}}
test_pipeline_1333_736 = {{_base_.test_pipeline_1333_736}}
data = dict(
samples_per_gpu=16,
workers_per_gpu=8,
val_dataloader=dict(samples_per_gpu=1),
test_dataloader=dict(samples_per_gpu=1),
train=dict(
type='UniformConcatDataset',
datasets=train_list,
pipeline=train_pipeline_r18),
val=dict(
type='UniformConcatDataset',
datasets=test_list,
pipeline=test_pipeline_1333_736),
test=dict(
type='UniformConcatDataset',
datasets=test_list,
pipeline=test_pipeline_1333_736))
evaluation = dict(interval=100, metric='hmean-iou')
| _base_ = ['../../_base_/default_runtime.py', '../../_base_/schedules/schedule_sgd_1200e.py', '../../_base_/det_models/dbnet_r18_fpnc.py', '../../_base_/det_datasets/icdar2015.py', '../../_base_/det_pipelines/dbnet_pipeline.py']
train_list = {{_base_.train_list}}
test_list = {{_base_.test_list}}
train_pipeline_r18 = {{_base_.train_pipeline_r18}}
test_pipeline_1333_736 = {{_base_.test_pipeline_1333_736}}
data = dict(samples_per_gpu=16, workers_per_gpu=8, val_dataloader=dict(samples_per_gpu=1), test_dataloader=dict(samples_per_gpu=1), train=dict(type='UniformConcatDataset', datasets=train_list, pipeline=train_pipeline_r18), val=dict(type='UniformConcatDataset', datasets=test_list, pipeline=test_pipeline_1333_736), test=dict(type='UniformConcatDataset', datasets=test_list, pipeline=test_pipeline_1333_736))
evaluation = dict(interval=100, metric='hmean-iou') |
class MoveNotFound(Exception):
pass
class CharacterNotFound(Exception):
pass
class OptionError(Exception):
pass
class LimitError(Exception):
pass
class CharacterMainError(Exception):
pass
class CharacterSubError(Exception):
pass
class CommandNotFound(Exception):
pass
class CommandAlreadyExisting(Exception):
pass
class ChannelAlreadyAdded(Exception):
pass
class ChannelNonExistent(Exception):
pass
class GuildNotSetError(Exception):
pass
class PrefixError(Exception):
pass
class LinkNotFound(Exception):
pass
class DatabaseInitError(Exception):
pass
class TableNameError(Exception):
pass
class ColumnNameError(Exception):
pass
class MoveNameError(Exception):
pass
class CharacterNameError(Exception):
pass
class NotInitializedError(Exception):
pass
class ChannelNotSetError(Exception):
pass
| class Movenotfound(Exception):
pass
class Characternotfound(Exception):
pass
class Optionerror(Exception):
pass
class Limiterror(Exception):
pass
class Charactermainerror(Exception):
pass
class Charactersuberror(Exception):
pass
class Commandnotfound(Exception):
pass
class Commandalreadyexisting(Exception):
pass
class Channelalreadyadded(Exception):
pass
class Channelnonexistent(Exception):
pass
class Guildnotseterror(Exception):
pass
class Prefixerror(Exception):
pass
class Linknotfound(Exception):
pass
class Databaseiniterror(Exception):
pass
class Tablenameerror(Exception):
pass
class Columnnameerror(Exception):
pass
class Movenameerror(Exception):
pass
class Characternameerror(Exception):
pass
class Notinitializederror(Exception):
pass
class Channelnotseterror(Exception):
pass |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.