content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
WARNING_HEADER = '[\033[1m\033[93mWARNING\033[0m]'
def warning_message(message_text):
print('{header} {text}'.format(header=WARNING_HEADER, text=message_text))
| warning_header = '[\x1b[1m\x1b[93mWARNING\x1b[0m]'
def warning_message(message_text):
print('{header} {text}'.format(header=WARNING_HEADER, text=message_text)) |
class WebsocketError(Exception):
pass
class NoTokenError(WebsocketError):
pass
| class Websocketerror(Exception):
pass
class Notokenerror(WebsocketError):
pass |
a,b=0,1
while b<10:
print(b)
a,b=b,a+b
| (a, b) = (0, 1)
while b < 10:
print(b)
(a, b) = (b, a + b) |
def thank_you(donation):
if donation >= 1000:
print("Thank you for your donation! You have achieved platinum donation status!")
elif donation >= 500:
print("Thank you for your donation! You have achieved gold donation status!")
elif donation >= 100:
print("Thank you for your donation! You have achieved silver donation status!")
else:
print("Thank you for your donation! You have achieved bronze donation status!")
thank_you(500)
def grade_converter(gpa):
grade = "F"
if gpa >= 4.0:
grade = "A"
elif gpa >= 3.0:
grade = "B"
elif gpa >= 2.0:
grade = "C"
elif gpa >= 1.0:
grade = "D"
return grade
print(grade_converter(2.0)) | def thank_you(donation):
if donation >= 1000:
print('Thank you for your donation! You have achieved platinum donation status!')
elif donation >= 500:
print('Thank you for your donation! You have achieved gold donation status!')
elif donation >= 100:
print('Thank you for your donation! You have achieved silver donation status!')
else:
print('Thank you for your donation! You have achieved bronze donation status!')
thank_you(500)
def grade_converter(gpa):
grade = 'F'
if gpa >= 4.0:
grade = 'A'
elif gpa >= 3.0:
grade = 'B'
elif gpa >= 2.0:
grade = 'C'
elif gpa >= 1.0:
grade = 'D'
return grade
print(grade_converter(2.0)) |
'''
This file holds all the constants that are required for programming the LIS3DH
including register addresses and their values
'''
'''
The LIS3DH I2C address
'''
LIS3DH_I2C_ADDR = 0x18
'''
The LIS3DH Register Map
'''
#0x00 - 0x06 - reserved
STATUS_REG_AUX = 0x07
OUT_ADC1_L = 0x08
OUT_ADC1_H = 0x09
OUT_ADC2_L = 0x0A
OUT_ADC2_H = 0x0B
OUT_ADC3_L = 0x0C
OUT_ADC3_H = 0x0D
INT_COUNTER_REG = 0x0E
WHO_AM_I = 0x0F
# 0x10 0x1E - reserved
TEMP_CFG_REG = 0x1F
CTRL_REG1 = 0x20
CTRL_REG2 = 0x21
CTRL_REG3 = 0x22
CTRL_REG4 = 0x23
CTRL_REG5 = 0x24
CTRL_REG6 = 0x25
REFERENCE = 0x26
STATUS_REG2 = 0x27
OUT_X_L = 0x28
OUT_X_H = 0x29
OUT_Y_L = 0x2A
OUT_Y_H = 0x2B
OUT_Z_L = 0x2C
OUT_Z_H = 0x2D
FIFO_CTRL_REG = 0x2E
FIFO_SRC_REG = 0x2F
INT1_CFG = 0x30
INT1_SOURCE = 0x31
INT1_THS = 0x32
INT1_DURATION = 0x33
#0x34 - 0x37 - reserved
CLICK_CFG = 0x38
CLICK_SRC = 0x39
CLICK_THS = 0x3A
TIME_LIMIT = 0x3B
TIME_LATENCY = 0x3C
TIME_WINDOW = 0x3D
'''
Values to select range of the accelerometer
'''
RANGE_2G = 0b00
RANGE_4G = 0b01
RANGE_8G = 0b10
RANGE_16G = 0b11
'''
Values to select data refresh rate of the accelerometer
'''
RATE_400HZ = 0b0111
RATE_200HZ = 0b0110
RATE_100HZ = 0b0101
RATE_50HZ = 0b0100
RATE_25HZ = 0b0011
RATE_10HZ = 0b0010
RATE_1HZ = 0b0001
RATE_POWERDOWN = 0
RATE_LOWPOWER_1K6HZ = 0b1000
RATE_LOWPOWER_5KHZ = 0b1001
'''
The WHO_AM_I reply
'''
WHO_AM_I_ID = 0x33
| """
This file holds all the constants that are required for programming the LIS3DH
including register addresses and their values
"""
'\nThe LIS3DH I2C address\n'
lis3_dh_i2_c_addr = 24
'\nThe LIS3DH Register Map\n'
status_reg_aux = 7
out_adc1_l = 8
out_adc1_h = 9
out_adc2_l = 10
out_adc2_h = 11
out_adc3_l = 12
out_adc3_h = 13
int_counter_reg = 14
who_am_i = 15
temp_cfg_reg = 31
ctrl_reg1 = 32
ctrl_reg2 = 33
ctrl_reg3 = 34
ctrl_reg4 = 35
ctrl_reg5 = 36
ctrl_reg6 = 37
reference = 38
status_reg2 = 39
out_x_l = 40
out_x_h = 41
out_y_l = 42
out_y_h = 43
out_z_l = 44
out_z_h = 45
fifo_ctrl_reg = 46
fifo_src_reg = 47
int1_cfg = 48
int1_source = 49
int1_ths = 50
int1_duration = 51
click_cfg = 56
click_src = 57
click_ths = 58
time_limit = 59
time_latency = 60
time_window = 61
'\nValues to select range of the accelerometer\n'
range_2_g = 0
range_4_g = 1
range_8_g = 2
range_16_g = 3
'\nValues to select data refresh rate of the accelerometer\n'
rate_400_hz = 7
rate_200_hz = 6
rate_100_hz = 5
rate_50_hz = 4
rate_25_hz = 3
rate_10_hz = 2
rate_1_hz = 1
rate_powerdown = 0
rate_lowpower_1_k6_hz = 8
rate_lowpower_5_khz = 9
'\nThe WHO_AM_I reply\n'
who_am_i_id = 51 |
def moveDictionary():
electro_shock = {"Name" : "Electro Shock", \
"Kind" : "atk",\
"Pwr" : 25, \
"Acc" : 95, \
"Crit" : 80, \
"Txt" : "releases one thousand volts of static"}
#special
heal = {"Name" : "Heal", \
"Kind" : "heal",\
"Pwr" : 28, \
"Acc" : 36, \
"Crit" : 5, \
"Txt" : "attempts to put itself back together"}
robot_punch = {"Name" : "Robot Punch", \
"Kind" : "atk",\
"Pwr" : 40, \
"Acc" : 70, \
"Crit" : 20, \
"Txt" : "reels back and slugs hard"}
robot_slap = {"Name" : "Robot Slap", \
"Kind" : "atk",\
"Pwr" : 32, \
"Acc" : 90, \
"Crit" : 20, \
"Txt" : "slaps a hoe"}
robot_headbutt = {"Name" : "Robot Headbutt", \
"Kind" : "atk",\
"Pwr" : 45, \
"Acc" : 20, \
"Crit" : 80, \
"Txt" : "attempts a powerful attack"}
#special
moveDic = {"electro_shock" : electro_shock,\
"heal" : heal, \
"robot_punch" : robot_punch,\
"robot_slap" : robot_slap,\
"robot_headbutt" : robot_headbutt}
return moveDic
##dictionary = moveDictionary() #module testing
##print(type(dictionary)) #module print test
| def move_dictionary():
electro_shock = {'Name': 'Electro Shock', 'Kind': 'atk', 'Pwr': 25, 'Acc': 95, 'Crit': 80, 'Txt': 'releases one thousand volts of static'}
heal = {'Name': 'Heal', 'Kind': 'heal', 'Pwr': 28, 'Acc': 36, 'Crit': 5, 'Txt': 'attempts to put itself back together'}
robot_punch = {'Name': 'Robot Punch', 'Kind': 'atk', 'Pwr': 40, 'Acc': 70, 'Crit': 20, 'Txt': 'reels back and slugs hard'}
robot_slap = {'Name': 'Robot Slap', 'Kind': 'atk', 'Pwr': 32, 'Acc': 90, 'Crit': 20, 'Txt': 'slaps a hoe'}
robot_headbutt = {'Name': 'Robot Headbutt', 'Kind': 'atk', 'Pwr': 45, 'Acc': 20, 'Crit': 80, 'Txt': 'attempts a powerful attack'}
move_dic = {'electro_shock': electro_shock, 'heal': heal, 'robot_punch': robot_punch, 'robot_slap': robot_slap, 'robot_headbutt': robot_headbutt}
return moveDic |
class Solution:
def rob(self, nums):
robbed, notRobbed = 0, 0
for i in nums:
robbed, notRobbed = notRobbed + i, max(robbed, notRobbed)
return max(robbed, notRobbed)
| class Solution:
def rob(self, nums):
(robbed, not_robbed) = (0, 0)
for i in nums:
(robbed, not_robbed) = (notRobbed + i, max(robbed, notRobbed))
return max(robbed, notRobbed) |
# Common package prefixes, in the order we want to check for them
_PREFIXES = (".com.", ".org.", ".net.", ".io.")
# By default bazel computes the name of test classes based on the
# standard Maven directory structure, which we may not always use,
# so try to compute the correct package name.
def get_package_name():
pkg = native.package_name().replace("/", ".")
for prefix in _PREFIXES:
idx = pkg.find(prefix)
if idx != -1:
return pkg[idx + 1:] + "."
return ""
# Converts a file name into what is hopefully a valid class name.
def get_class_name(src):
# Strip the suffix from the source
idx = src.rindex(".")
name = src[:idx].replace("/", ".")
for prefix in _PREFIXES:
idx = name.find(prefix)
if idx != -1:
return name[idx + 1:]
pkg = get_package_name()
if pkg:
return pkg + name
return name
| _prefixes = ('.com.', '.org.', '.net.', '.io.')
def get_package_name():
pkg = native.package_name().replace('/', '.')
for prefix in _PREFIXES:
idx = pkg.find(prefix)
if idx != -1:
return pkg[idx + 1:] + '.'
return ''
def get_class_name(src):
idx = src.rindex('.')
name = src[:idx].replace('/', '.')
for prefix in _PREFIXES:
idx = name.find(prefix)
if idx != -1:
return name[idx + 1:]
pkg = get_package_name()
if pkg:
return pkg + name
return name |
numbers = [int(i) for i in input().split(" ")]
opposite_numbers = []
for current_num in numbers:
if current_num >= 0:
opposite_numbers.append(-current_num)
elif current_num < 0:
opposite_numbers.append(abs(current_num))
print(opposite_numbers) | numbers = [int(i) for i in input().split(' ')]
opposite_numbers = []
for current_num in numbers:
if current_num >= 0:
opposite_numbers.append(-current_num)
elif current_num < 0:
opposite_numbers.append(abs(current_num))
print(opposite_numbers) |
def finder(data, x):
if x == 0:
return data[x]
v1 = data[x]
v2 = finder(data, x-1)
if v1 > v2:
return v1
else:
return v2
print(finder([0, -247, 341, 1001, 741, 22])) | def finder(data, x):
if x == 0:
return data[x]
v1 = data[x]
v2 = finder(data, x - 1)
if v1 > v2:
return v1
else:
return v2
print(finder([0, -247, 341, 1001, 741, 22])) |
def extractStrictlybromanceCom(item):
'''
Parser for 'strictlybromance.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('grave robbers\' chronicles', 'grave robbers\' chronicles', 'translated'),
('haunted houses\' chronicles', 'haunted houses\' chronicles', 'translated'),
('the trial game of life', 'the trial game of life', 'translated'),
('the invasion day', 'The Invasion Day', 'translated'),
('saving unpermitted', 'saving unpermitted', 'translated'),
('PRC', 'PRC', 'translated'),
('Loiterous', 'Loiterous', 'oel'),
]
for tagname, name, tl_type in tagmap:
if tagname in item['tags']:
return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
return False | def extract_strictlybromance_com(item):
"""
Parser for 'strictlybromance.com'
"""
(vol, chp, frag, postfix) = extract_vol_chapter_fragment_postfix(item['title'])
if not (chp or vol) or 'preview' in item['title'].lower():
return None
tagmap = [("grave robbers' chronicles", "grave robbers' chronicles", 'translated'), ("haunted houses' chronicles", "haunted houses' chronicles", 'translated'), ('the trial game of life', 'the trial game of life', 'translated'), ('the invasion day', 'The Invasion Day', 'translated'), ('saving unpermitted', 'saving unpermitted', 'translated'), ('PRC', 'PRC', 'translated'), ('Loiterous', 'Loiterous', 'oel')]
for (tagname, name, tl_type) in tagmap:
if tagname in item['tags']:
return build_release_message_with_type(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
return False |
class Solution:
def largestTimeFromDigits(self, nums: List[int]) -> str:
res=[]
def per(depth):
if depth==len(nums)-1:
res.append(nums[:])
for i in range(depth,len(nums)):
nums[i],nums[depth]=nums[depth],nums[i]
per(depth+1)
nums[i],nums[depth]=nums[depth],nums[i]
per(0)
re=""
for i in res:
if i[0]*10 +i[1]<24 and i[2]*10+i[3]<60:
re=max(re,str(i[0])+str(i[1])+':'+str(i[2])+str(i[3]))
return re
| class Solution:
def largest_time_from_digits(self, nums: List[int]) -> str:
res = []
def per(depth):
if depth == len(nums) - 1:
res.append(nums[:])
for i in range(depth, len(nums)):
(nums[i], nums[depth]) = (nums[depth], nums[i])
per(depth + 1)
(nums[i], nums[depth]) = (nums[depth], nums[i])
per(0)
re = ''
for i in res:
if i[0] * 10 + i[1] < 24 and i[2] * 10 + i[3] < 60:
re = max(re, str(i[0]) + str(i[1]) + ':' + str(i[2]) + str(i[3]))
return re |
EPS = 1.0e-16
PI = 3.141592653589793
| eps = 1e-16
pi = 3.141592653589793 |
#all binary
allSensors = ['D021', 'D022', 'D023', 'D024',
'D025', 'D026', 'D027', 'D028', 'D029', 'D030', 'D031', 'D032', 'M001',
'M002', 'M003', 'M004', 'M005', 'M006', 'M007', 'M008', 'M009', 'M010',
'M011', 'M012', 'M013', 'M014', 'M015', 'M016', 'M017', 'M018', 'M019',
'M020']
doorSensors = ['D021', 'D022', 'D023', 'D024',
'D025', 'D026', 'D027', 'D028', 'D029', 'D030', 'D031', 'D032']
motionSensors = ['M001', 'M002', 'M003', 'M004', 'M005', 'M006', 'M007', 'M008', 'M009', 'M010',
'M011', 'M012', 'M013', 'M014', 'M015', 'M016', 'M017', 'M018', 'M019',
'M020']
doorFalse = "CLOSE"
doorTrue = "OPEN"
motionFalse = "OFF"
motionTrue = "ON"
allActivities = ['Bathing', 'Bed_Toilet_Transition', 'Eating', 'Enter_Home', 'Housekeeping', 'Leave_Home',
'Meal_Preparation', 'Other_Activity', 'Personal_Hygiene', 'Relax', 'Sleeping_Not_in_Bed',
'Sleeping_in_Bed', 'Take_Medicine', 'Work']
sensColToOrd = { val : i for i, val in enumerate(allSensors)}
week = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
timeMidn = "TimeFromMid"
class rawLabels:
time = "Time"
sensor = "Sensor"
signal = "Signal"
activity = "Activity"
correctOrder = [time, sensor, signal, activity]
rl = rawLabels
features = [rl.time, rl.signal] + allSensors + allActivities
conditionals = [timeMidn] + week
conditionalSize = len(conditionals)
colOrdConditional = {day : i+1 for i, day in enumerate(week)}
colOrdConditional[timeMidn] = 0
allBinaryColumns = [rl.signal] + allSensors + allActivities + week
correctOrder = features + conditionals
class start_stop:
def __init__(self, start, length):
self.start = start
self.stop = start + length
class pivots:
time = start_stop(0,1)
signal = start_stop(time.stop, 1)
sensors = start_stop(signal.stop, len(allSensors))
activities = start_stop(sensors.stop, len(allActivities))
features = start_stop(0, activities.stop)
timeLabels = start_stop(activities.stop, len(conditionals))
weekdays = start_stop(timeLabels.start, 1)
colOrder = [rl.time, rl.signal] + allSensors + allActivities + conditionals
ordinalColDict = {i:c for i, c in enumerate(colOrder)}
colOrdinalDict = {c:i for i, c in enumerate(colOrder)}
class home_names:
allHomes = "All Real Home"
synthetic = "Fake Home"
home1 = "H1"
home2 = "H2"
home3 = "H3" | all_sensors = ['D021', 'D022', 'D023', 'D024', 'D025', 'D026', 'D027', 'D028', 'D029', 'D030', 'D031', 'D032', 'M001', 'M002', 'M003', 'M004', 'M005', 'M006', 'M007', 'M008', 'M009', 'M010', 'M011', 'M012', 'M013', 'M014', 'M015', 'M016', 'M017', 'M018', 'M019', 'M020']
door_sensors = ['D021', 'D022', 'D023', 'D024', 'D025', 'D026', 'D027', 'D028', 'D029', 'D030', 'D031', 'D032']
motion_sensors = ['M001', 'M002', 'M003', 'M004', 'M005', 'M006', 'M007', 'M008', 'M009', 'M010', 'M011', 'M012', 'M013', 'M014', 'M015', 'M016', 'M017', 'M018', 'M019', 'M020']
door_false = 'CLOSE'
door_true = 'OPEN'
motion_false = 'OFF'
motion_true = 'ON'
all_activities = ['Bathing', 'Bed_Toilet_Transition', 'Eating', 'Enter_Home', 'Housekeeping', 'Leave_Home', 'Meal_Preparation', 'Other_Activity', 'Personal_Hygiene', 'Relax', 'Sleeping_Not_in_Bed', 'Sleeping_in_Bed', 'Take_Medicine', 'Work']
sens_col_to_ord = {val: i for (i, val) in enumerate(allSensors)}
week = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
time_midn = 'TimeFromMid'
class Rawlabels:
time = 'Time'
sensor = 'Sensor'
signal = 'Signal'
activity = 'Activity'
correct_order = [time, sensor, signal, activity]
rl = rawLabels
features = [rl.time, rl.signal] + allSensors + allActivities
conditionals = [timeMidn] + week
conditional_size = len(conditionals)
col_ord_conditional = {day: i + 1 for (i, day) in enumerate(week)}
colOrdConditional[timeMidn] = 0
all_binary_columns = [rl.signal] + allSensors + allActivities + week
correct_order = features + conditionals
class Start_Stop:
def __init__(self, start, length):
self.start = start
self.stop = start + length
class Pivots:
time = start_stop(0, 1)
signal = start_stop(time.stop, 1)
sensors = start_stop(signal.stop, len(allSensors))
activities = start_stop(sensors.stop, len(allActivities))
features = start_stop(0, activities.stop)
time_labels = start_stop(activities.stop, len(conditionals))
weekdays = start_stop(timeLabels.start, 1)
col_order = [rl.time, rl.signal] + allSensors + allActivities + conditionals
ordinal_col_dict = {i: c for (i, c) in enumerate(colOrder)}
col_ordinal_dict = {c: i for (i, c) in enumerate(colOrder)}
class Home_Names:
all_homes = 'All Real Home'
synthetic = 'Fake Home'
home1 = 'H1'
home2 = 'H2'
home3 = 'H3' |
f = [1, 1, 2, 6, 4]
for _ in range(int(input())):
n = int(input())
if n <= 4:
print(f[n])
else:
print(0)
| f = [1, 1, 2, 6, 4]
for _ in range(int(input())):
n = int(input())
if n <= 4:
print(f[n])
else:
print(0) |
# 6. Zigzag Conversion
# Runtime: 103 ms, faster than 20.89% of Python3 online submissions for Zigzag Conversion.
# Memory Usage: 14.7 MB, less than 13.84% of Python3 online submissions for Zigzag Conversion.
class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows == 1:
return s
rows = [[] for _ in range(numRows)]
# In the first and last rows, the interval between two adjacent elements is the larget.
largest_interval = (numRows * 2) - 2
for r in range(numRows):
i = r
# In other rows, The sum of the intervals of every three elements is equal to the larget interval.
curr_interval = largest_interval - 2 * r
if curr_interval == 0:
curr_interval = largest_interval
while i < len(s):
rows[r].append(s[i])
i += curr_interval
if curr_interval != largest_interval:
curr_interval = largest_interval - curr_interval
ans = []
for row in rows:
ans.extend(row)
return "".join(ans) | class Solution:
def convert(self, s: str, numRows: int) -> str:
if numRows == 1:
return s
rows = [[] for _ in range(numRows)]
largest_interval = numRows * 2 - 2
for r in range(numRows):
i = r
curr_interval = largest_interval - 2 * r
if curr_interval == 0:
curr_interval = largest_interval
while i < len(s):
rows[r].append(s[i])
i += curr_interval
if curr_interval != largest_interval:
curr_interval = largest_interval - curr_interval
ans = []
for row in rows:
ans.extend(row)
return ''.join(ans) |
#
# PySNMP MIB module AGENTX-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/AGENTX-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:15:42 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
Integer, ObjectIdentifier, OctetString = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueRangeConstraint, ValueSizeConstraint, SingleValueConstraint, ConstraintsIntersection, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ValueSizeConstraint", "SingleValueConstraint", "ConstraintsIntersection", "ConstraintsUnion")
SnmpAdminString, = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString")
ModuleCompliance, NotificationGroup, ObjectGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup", "ObjectGroup")
Counter64, mib_2, NotificationType, Bits, iso, Unsigned32, MibIdentifier, TimeTicks, ObjectIdentity, Integer32, ModuleIdentity, Gauge32, IpAddress, Counter32, MibScalar, MibTable, MibTableRow, MibTableColumn = mibBuilder.importSymbols("SNMPv2-SMI", "Counter64", "mib-2", "NotificationType", "Bits", "iso", "Unsigned32", "MibIdentifier", "TimeTicks", "ObjectIdentity", "Integer32", "ModuleIdentity", "Gauge32", "IpAddress", "Counter32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn")
TimeStamp, DisplayString, TextualConvention, TDomain, TruthValue = mibBuilder.importSymbols("SNMPv2-TC", "TimeStamp", "DisplayString", "TextualConvention", "TDomain", "TruthValue")
agentxMIB = ModuleIdentity((1, 3, 6, 1, 2, 1, 74))
agentxMIB.setRevisions(('2000-01-10 00:00',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: agentxMIB.setRevisionsDescriptions(('Initial version published as RFC 2742.',))
if mibBuilder.loadTexts: agentxMIB.setLastUpdated('200001100000Z')
if mibBuilder.loadTexts: agentxMIB.setOrganization('AgentX Working Group')
if mibBuilder.loadTexts: agentxMIB.setContactInfo('WG-email: agentx@dorothy.bmc.com Subscribe: agentx-request@dorothy.bmc.com WG-email Archive: ftp://ftp.peer.com/pub/agentx/archives FTP repository: ftp://ftp.peer.com/pub/agentx http://www.ietf.org/html.charters/agentx-charter.html Chair: Bob Natale ACE*COMM Corporation Email: bnatale@acecomm.com WG editor: Mark Ellison Ellison Software Consulting, Inc. Email: ellison@world.std.com Co-author: Lauren Heintz Cisco Systems, EMail: lheintz@cisco.com Co-author: Smitha Gudur Independent Consultant Email: sgudur@hotmail.com ')
if mibBuilder.loadTexts: agentxMIB.setDescription('This is the MIB module for the SNMP Agent Extensibility Protocol (AgentX). This MIB module will be implemented by the master agent. ')
class AgentxTAddress(TextualConvention, OctetString):
description = 'Denotes a transport service address. This is identical to the TAddress textual convention (SNMPv2-SMI) except that zero-length values are permitted. '
status = 'current'
subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(0, 255)
agentxObjects = MibIdentifier((1, 3, 6, 1, 2, 1, 74, 1))
agentxGeneral = MibIdentifier((1, 3, 6, 1, 2, 1, 74, 1, 1))
agentxConnection = MibIdentifier((1, 3, 6, 1, 2, 1, 74, 1, 2))
agentxSession = MibIdentifier((1, 3, 6, 1, 2, 1, 74, 1, 3))
agentxRegistration = MibIdentifier((1, 3, 6, 1, 2, 1, 74, 1, 4))
agentxDefaultTimeout = MibScalar((1, 3, 6, 1, 2, 1, 74, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 255)).clone(5)).setUnits('seconds').setMaxAccess("readonly")
if mibBuilder.loadTexts: agentxDefaultTimeout.setStatus('current')
if mibBuilder.loadTexts: agentxDefaultTimeout.setDescription('The default length of time, in seconds, that the master agent should allow to elapse after dispatching a message to a session before it regards the subagent as not responding. This is a system-wide value that may override the timeout value associated with a particular session (agentxSessionTimeout) or a particular registered MIB region (agentxRegTimeout). If the associated value of agentxSessionTimeout and agentxRegTimeout are zero, or impractical in accordance with implementation-specific procedure of the master agent, the value represented by this object will be the effective timeout value for the master agent to await a response to a dispatch from a given subagent. ')
agentxMasterAgentXVer = MibScalar((1, 3, 6, 1, 2, 1, 74, 1, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: agentxMasterAgentXVer.setStatus('current')
if mibBuilder.loadTexts: agentxMasterAgentXVer.setDescription('The AgentX protocol version supported by this master agent. The current protocol version is 1. Note that the master agent must also allow interaction with earlier version subagents. ')
agentxConnTableLastChange = MibScalar((1, 3, 6, 1, 2, 1, 74, 1, 2, 1), TimeStamp()).setMaxAccess("readonly")
if mibBuilder.loadTexts: agentxConnTableLastChange.setStatus('current')
if mibBuilder.loadTexts: agentxConnTableLastChange.setDescription('The value of sysUpTime when the last row creation or deletion occurred in the agentxConnectionTable. ')
agentxConnectionTable = MibTable((1, 3, 6, 1, 2, 1, 74, 1, 2, 2), )
if mibBuilder.loadTexts: agentxConnectionTable.setStatus('current')
if mibBuilder.loadTexts: agentxConnectionTable.setDescription('The agentxConnectionTable tracks all current AgentX transport connections. There may be zero, one, or more AgentX sessions carried on a given AgentX connection. ')
agentxConnectionEntry = MibTableRow((1, 3, 6, 1, 2, 1, 74, 1, 2, 2, 1), ).setIndexNames((0, "AGENTX-MIB", "agentxConnIndex"))
if mibBuilder.loadTexts: agentxConnectionEntry.setStatus('current')
if mibBuilder.loadTexts: agentxConnectionEntry.setDescription('An agentxConnectionEntry contains information describing a single AgentX transport connection. A connection may be used to support zero or more AgentX sessions. An entry is created when a new transport connection is established, and is destroyed when the transport connection is terminated. ')
agentxConnIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 74, 1, 2, 2, 1, 1), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1, 4294967295)))
if mibBuilder.loadTexts: agentxConnIndex.setStatus('current')
if mibBuilder.loadTexts: agentxConnIndex.setDescription('agentxConnIndex contains the value that uniquely identifies an open transport connection used by this master agent to provide AgentX service. Values of this index should not be re-used. The value assigned to a given transport connection is constant for the lifetime of that connection. ')
agentxConnOpenTime = MibTableColumn((1, 3, 6, 1, 2, 1, 74, 1, 2, 2, 1, 2), TimeStamp()).setMaxAccess("readonly")
if mibBuilder.loadTexts: agentxConnOpenTime.setStatus('current')
if mibBuilder.loadTexts: agentxConnOpenTime.setDescription('The value of sysUpTime when this connection was established and, therefore, its value when this entry was added to the table. ')
agentxConnTransportDomain = MibTableColumn((1, 3, 6, 1, 2, 1, 74, 1, 2, 2, 1, 3), TDomain()).setMaxAccess("readonly")
if mibBuilder.loadTexts: agentxConnTransportDomain.setStatus('current')
if mibBuilder.loadTexts: agentxConnTransportDomain.setDescription('The transport protocol in use for this connection to the subagent. ')
agentxConnTransportAddress = MibTableColumn((1, 3, 6, 1, 2, 1, 74, 1, 2, 2, 1, 4), AgentxTAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: agentxConnTransportAddress.setStatus('current')
if mibBuilder.loadTexts: agentxConnTransportAddress.setDescription('The transport address of the remote (subagent) end of this connection to the master agent. This object may be zero-length for unix-domain sockets (and possibly other types of transport addresses) since the subagent need not bind a filename to its local socket. ')
agentxSessionTableLastChange = MibScalar((1, 3, 6, 1, 2, 1, 74, 1, 3, 1), TimeStamp()).setMaxAccess("readonly")
if mibBuilder.loadTexts: agentxSessionTableLastChange.setStatus('current')
if mibBuilder.loadTexts: agentxSessionTableLastChange.setDescription('The value of sysUpTime when the last row creation or deletion occurred in the agentxSessionTable. ')
agentxSessionTable = MibTable((1, 3, 6, 1, 2, 1, 74, 1, 3, 2), )
if mibBuilder.loadTexts: agentxSessionTable.setStatus('current')
if mibBuilder.loadTexts: agentxSessionTable.setDescription('A table of AgentX subagent sessions currently in effect. ')
agentxSessionEntry = MibTableRow((1, 3, 6, 1, 2, 1, 74, 1, 3, 2, 1), ).setIndexNames((0, "AGENTX-MIB", "agentxConnIndex"), (0, "AGENTX-MIB", "agentxSessionIndex"))
if mibBuilder.loadTexts: agentxSessionEntry.setStatus('current')
if mibBuilder.loadTexts: agentxSessionEntry.setDescription('Information about a single open session between the AgentX master agent and a subagent is contained in this entry. An entry is created when a new session is successfully established and is destroyed either when the subagent transport connection has terminated or when the subagent session is closed. ')
agentxSessionIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 74, 1, 3, 2, 1, 1), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(0, 4294967295)))
if mibBuilder.loadTexts: agentxSessionIndex.setStatus('current')
if mibBuilder.loadTexts: agentxSessionIndex.setDescription("A unique index for the subagent session. It is the same as h.sessionID defined in the agentx header. Note that if a subagent's session with the master agent is closed for any reason its index should not be re-used. A value of zero(0) is specifically allowed in order to be compatible with the definition of h.sessionId. ")
agentxSessionObjectID = MibTableColumn((1, 3, 6, 1, 2, 1, 74, 1, 3, 2, 1, 2), ObjectIdentifier()).setMaxAccess("readonly")
if mibBuilder.loadTexts: agentxSessionObjectID.setStatus('current')
if mibBuilder.loadTexts: agentxSessionObjectID.setDescription("This is taken from the o.id field of the agentx-Open-PDU. This attribute will report a value of '0.0' for subagents not supporting the notion of an AgentX session object identifier. ")
agentxSessionDescr = MibTableColumn((1, 3, 6, 1, 2, 1, 74, 1, 3, 2, 1, 3), SnmpAdminString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: agentxSessionDescr.setStatus('current')
if mibBuilder.loadTexts: agentxSessionDescr.setDescription('A textual description of the session. This is analogous to sysDescr defined in the SNMPv2-MIB in RFC 1907 [19] and is taken from the o.descr field of the agentx-Open-PDU. This attribute will report a zero-length string value for subagents not supporting the notion of a session description. ')
agentxSessionAdminStatus = MibTableColumn((1, 3, 6, 1, 2, 1, 74, 1, 3, 2, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("up", 1), ("down", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: agentxSessionAdminStatus.setStatus('current')
if mibBuilder.loadTexts: agentxSessionAdminStatus.setDescription("The administrative (desired) status of the session. Setting the value to 'down(2)' closes the subagent session (with c.reason set to 'reasonByManager'). ")
agentxSessionOpenTime = MibTableColumn((1, 3, 6, 1, 2, 1, 74, 1, 3, 2, 1, 5), TimeStamp()).setMaxAccess("readonly")
if mibBuilder.loadTexts: agentxSessionOpenTime.setStatus('current')
if mibBuilder.loadTexts: agentxSessionOpenTime.setDescription('The value of sysUpTime when this session was opened and, therefore, its value when this entry was added to the table. ')
agentxSessionAgentXVer = MibTableColumn((1, 3, 6, 1, 2, 1, 74, 1, 3, 2, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: agentxSessionAgentXVer.setStatus('current')
if mibBuilder.loadTexts: agentxSessionAgentXVer.setDescription('The version of the AgentX protocol supported by the session. This must be less than or equal to the value of agentxMasterAgentXVer. ')
agentxSessionTimeout = MibTableColumn((1, 3, 6, 1, 2, 1, 74, 1, 3, 2, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 255))).setUnits('seconds').setMaxAccess("readonly")
if mibBuilder.loadTexts: agentxSessionTimeout.setStatus('current')
if mibBuilder.loadTexts: agentxSessionTimeout.setDescription("The length of time, in seconds, that a master agent should allow to elapse after dispatching a message to this session before it regards the subagent as not responding. This value is taken from the o.timeout field of the agentx-Open-PDU. This is a session-specific value that may be overridden by values associated with the specific registered MIB regions (see agentxRegTimeout). A value of zero(0) indicates that the master agent's default timeout value should be used (see agentxDefaultTimeout). ")
agentxRegistrationTableLastChange = MibScalar((1, 3, 6, 1, 2, 1, 74, 1, 4, 1), TimeStamp()).setMaxAccess("readonly")
if mibBuilder.loadTexts: agentxRegistrationTableLastChange.setStatus('current')
if mibBuilder.loadTexts: agentxRegistrationTableLastChange.setDescription('The value of sysUpTime when the last row creation or deletion occurred in the agentxRegistrationTable. ')
agentxRegistrationTable = MibTable((1, 3, 6, 1, 2, 1, 74, 1, 4, 2), )
if mibBuilder.loadTexts: agentxRegistrationTable.setStatus('current')
if mibBuilder.loadTexts: agentxRegistrationTable.setDescription('A table of registered regions. ')
agentxRegistrationEntry = MibTableRow((1, 3, 6, 1, 2, 1, 74, 1, 4, 2, 1), ).setIndexNames((0, "AGENTX-MIB", "agentxConnIndex"), (0, "AGENTX-MIB", "agentxSessionIndex"), (0, "AGENTX-MIB", "agentxRegIndex"))
if mibBuilder.loadTexts: agentxRegistrationEntry.setStatus('current')
if mibBuilder.loadTexts: agentxRegistrationEntry.setDescription('Contains information for a single registered region. An entry is created when a session successfully registers a region and is destroyed for any of three reasons: this region is unregistered by the session, the session is closed, or the subagent connection is closed. ')
agentxRegIndex = MibTableColumn((1, 3, 6, 1, 2, 1, 74, 1, 4, 2, 1, 1), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1, 4294967295)))
if mibBuilder.loadTexts: agentxRegIndex.setStatus('current')
if mibBuilder.loadTexts: agentxRegIndex.setDescription('agentxRegIndex uniquely identifies a registration entry. This value is constant for the lifetime of an entry. ')
agentxRegContext = MibTableColumn((1, 3, 6, 1, 2, 1, 74, 1, 4, 2, 1, 2), OctetString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: agentxRegContext.setStatus('current')
if mibBuilder.loadTexts: agentxRegContext.setDescription('The context in which the session supports the objects in this region. A zero-length context indicates the default context. ')
agentxRegStart = MibTableColumn((1, 3, 6, 1, 2, 1, 74, 1, 4, 2, 1, 3), ObjectIdentifier()).setMaxAccess("readonly")
if mibBuilder.loadTexts: agentxRegStart.setStatus('current')
if mibBuilder.loadTexts: agentxRegStart.setDescription('The starting OBJECT IDENTIFIER of this registration entry. The session identified by agentxSessionIndex implements objects starting at this value (inclusive). Note that this value could identify an object type, an object instance, or a partial object instance. ')
agentxRegRangeSubId = MibTableColumn((1, 3, 6, 1, 2, 1, 74, 1, 4, 2, 1, 4), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: agentxRegRangeSubId.setStatus('current')
if mibBuilder.loadTexts: agentxRegRangeSubId.setDescription("agentxRegRangeSubId is used to specify the range. This is taken from r.region_subid in the registration PDU. If the value of this object is zero, no range is specified. If it is non-zero, it identifies the `nth' sub-identifier in r.region for which this entry's agentxRegUpperBound value is substituted in the OID for purposes of defining the region's upper bound. ")
agentxRegUpperBound = MibTableColumn((1, 3, 6, 1, 2, 1, 74, 1, 4, 2, 1, 5), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: agentxRegUpperBound.setStatus('current')
if mibBuilder.loadTexts: agentxRegUpperBound.setDescription('agentxRegUpperBound represents the upper-bound sub-identifier in a registration. This is taken from the r.upper_bound in the registration PDU. If agentxRegRangeSubid (r.region_subid) is zero, this value is also zero and is not used to define an upper bound for this registration. ')
agentxRegPriority = MibTableColumn((1, 3, 6, 1, 2, 1, 74, 1, 4, 2, 1, 6), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: agentxRegPriority.setStatus('current')
if mibBuilder.loadTexts: agentxRegPriority.setDescription('The registration priority. Lower values have higher priority. This value is taken from r.priority in the register PDU. Sessions should use the value of 127 for r.priority if a default value is desired. ')
agentxRegTimeout = MibTableColumn((1, 3, 6, 1, 2, 1, 74, 1, 4, 2, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 255))).setUnits('seconds').setMaxAccess("readonly")
if mibBuilder.loadTexts: agentxRegTimeout.setStatus('current')
if mibBuilder.loadTexts: agentxRegTimeout.setDescription('The timeout value, in seconds, for responses to requests associated with this registered MIB region. A value of zero(0) indicates the default value (indicated by by agentxSessionTimeout or agentxDefaultTimeout) is to be used. This value is taken from the r.timeout field of the agentx-Register-PDU. ')
agentxRegInstance = MibTableColumn((1, 3, 6, 1, 2, 1, 74, 1, 4, 2, 1, 8), TruthValue()).setMaxAccess("readonly")
if mibBuilder.loadTexts: agentxRegInstance.setStatus('current')
if mibBuilder.loadTexts: agentxRegInstance.setDescription("The value of agentxRegInstance is `true' for registrations for which the INSTANCE_REGISTRATION was set, and is `false' for all other registrations. ")
agentxConformance = MibIdentifier((1, 3, 6, 1, 2, 1, 74, 2))
agentxMIBGroups = MibIdentifier((1, 3, 6, 1, 2, 1, 74, 2, 1))
agentxMIBCompliances = MibIdentifier((1, 3, 6, 1, 2, 1, 74, 2, 2))
agentxMIBCompliance = ModuleCompliance((1, 3, 6, 1, 2, 1, 74, 2, 2, 1)).setObjects(("AGENTX-MIB", "agentxMIBGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
agentxMIBCompliance = agentxMIBCompliance.setStatus('current')
if mibBuilder.loadTexts: agentxMIBCompliance.setDescription('The compliance statement for SNMP entities that implement the AgentX protocol. Note that a compliant agent can implement all objects in this MIB module as read-only. ')
agentxMIBGroup = ObjectGroup((1, 3, 6, 1, 2, 1, 74, 2, 1, 1)).setObjects(("AGENTX-MIB", "agentxDefaultTimeout"), ("AGENTX-MIB", "agentxMasterAgentXVer"), ("AGENTX-MIB", "agentxConnTableLastChange"), ("AGENTX-MIB", "agentxConnOpenTime"), ("AGENTX-MIB", "agentxConnTransportDomain"), ("AGENTX-MIB", "agentxConnTransportAddress"), ("AGENTX-MIB", "agentxSessionTableLastChange"), ("AGENTX-MIB", "agentxSessionTimeout"), ("AGENTX-MIB", "agentxSessionObjectID"), ("AGENTX-MIB", "agentxSessionDescr"), ("AGENTX-MIB", "agentxSessionAdminStatus"), ("AGENTX-MIB", "agentxSessionOpenTime"), ("AGENTX-MIB", "agentxSessionAgentXVer"), ("AGENTX-MIB", "agentxRegistrationTableLastChange"), ("AGENTX-MIB", "agentxRegContext"), ("AGENTX-MIB", "agentxRegStart"), ("AGENTX-MIB", "agentxRegRangeSubId"), ("AGENTX-MIB", "agentxRegUpperBound"), ("AGENTX-MIB", "agentxRegPriority"), ("AGENTX-MIB", "agentxRegTimeout"), ("AGENTX-MIB", "agentxRegInstance"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
agentxMIBGroup = agentxMIBGroup.setStatus('current')
if mibBuilder.loadTexts: agentxMIBGroup.setDescription('All accessible objects in the AgentX MIB. ')
mibBuilder.exportSymbols("AGENTX-MIB", agentxConnTransportAddress=agentxConnTransportAddress, agentxRegistrationTable=agentxRegistrationTable, agentxMIBGroups=agentxMIBGroups, agentxSession=agentxSession, agentxDefaultTimeout=agentxDefaultTimeout, agentxConformance=agentxConformance, agentxGeneral=agentxGeneral, PYSNMP_MODULE_ID=agentxMIB, agentxConnTransportDomain=agentxConnTransportDomain, agentxSessionTableLastChange=agentxSessionTableLastChange, AgentxTAddress=AgentxTAddress, agentxRegInstance=agentxRegInstance, agentxMIBCompliances=agentxMIBCompliances, agentxRegistration=agentxRegistration, agentxConnIndex=agentxConnIndex, agentxConnOpenTime=agentxConnOpenTime, agentxRegIndex=agentxRegIndex, agentxMIB=agentxMIB, agentxSessionIndex=agentxSessionIndex, agentxRegistrationTableLastChange=agentxRegistrationTableLastChange, agentxSessionEntry=agentxSessionEntry, agentxRegRangeSubId=agentxRegRangeSubId, agentxConnTableLastChange=agentxConnTableLastChange, agentxSessionAgentXVer=agentxSessionAgentXVer, agentxSessionOpenTime=agentxSessionOpenTime, agentxRegTimeout=agentxRegTimeout, agentxMIBGroup=agentxMIBGroup, agentxSessionTable=agentxSessionTable, agentxSessionObjectID=agentxSessionObjectID, agentxRegStart=agentxRegStart, agentxSessionTimeout=agentxSessionTimeout, agentxConnectionTable=agentxConnectionTable, agentxConnectionEntry=agentxConnectionEntry, agentxRegPriority=agentxRegPriority, agentxMIBCompliance=agentxMIBCompliance, agentxRegistrationEntry=agentxRegistrationEntry, agentxRegUpperBound=agentxRegUpperBound, agentxConnection=agentxConnection, agentxObjects=agentxObjects, agentxSessionAdminStatus=agentxSessionAdminStatus, agentxMasterAgentXVer=agentxMasterAgentXVer, agentxRegContext=agentxRegContext, agentxSessionDescr=agentxSessionDescr)
| (integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, value_size_constraint, single_value_constraint, constraints_intersection, constraints_union) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueRangeConstraint', 'ValueSizeConstraint', 'SingleValueConstraint', 'ConstraintsIntersection', 'ConstraintsUnion')
(snmp_admin_string,) = mibBuilder.importSymbols('SNMP-FRAMEWORK-MIB', 'SnmpAdminString')
(module_compliance, notification_group, object_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup', 'ObjectGroup')
(counter64, mib_2, notification_type, bits, iso, unsigned32, mib_identifier, time_ticks, object_identity, integer32, module_identity, gauge32, ip_address, counter32, mib_scalar, mib_table, mib_table_row, mib_table_column) = mibBuilder.importSymbols('SNMPv2-SMI', 'Counter64', 'mib-2', 'NotificationType', 'Bits', 'iso', 'Unsigned32', 'MibIdentifier', 'TimeTicks', 'ObjectIdentity', 'Integer32', 'ModuleIdentity', 'Gauge32', 'IpAddress', 'Counter32', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn')
(time_stamp, display_string, textual_convention, t_domain, truth_value) = mibBuilder.importSymbols('SNMPv2-TC', 'TimeStamp', 'DisplayString', 'TextualConvention', 'TDomain', 'TruthValue')
agentx_mib = module_identity((1, 3, 6, 1, 2, 1, 74))
agentxMIB.setRevisions(('2000-01-10 00:00',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts:
agentxMIB.setRevisionsDescriptions(('Initial version published as RFC 2742.',))
if mibBuilder.loadTexts:
agentxMIB.setLastUpdated('200001100000Z')
if mibBuilder.loadTexts:
agentxMIB.setOrganization('AgentX Working Group')
if mibBuilder.loadTexts:
agentxMIB.setContactInfo('WG-email: agentx@dorothy.bmc.com Subscribe: agentx-request@dorothy.bmc.com WG-email Archive: ftp://ftp.peer.com/pub/agentx/archives FTP repository: ftp://ftp.peer.com/pub/agentx http://www.ietf.org/html.charters/agentx-charter.html Chair: Bob Natale ACE*COMM Corporation Email: bnatale@acecomm.com WG editor: Mark Ellison Ellison Software Consulting, Inc. Email: ellison@world.std.com Co-author: Lauren Heintz Cisco Systems, EMail: lheintz@cisco.com Co-author: Smitha Gudur Independent Consultant Email: sgudur@hotmail.com ')
if mibBuilder.loadTexts:
agentxMIB.setDescription('This is the MIB module for the SNMP Agent Extensibility Protocol (AgentX). This MIB module will be implemented by the master agent. ')
class Agentxtaddress(TextualConvention, OctetString):
description = 'Denotes a transport service address. This is identical to the TAddress textual convention (SNMPv2-SMI) except that zero-length values are permitted. '
status = 'current'
subtype_spec = OctetString.subtypeSpec + value_size_constraint(0, 255)
agentx_objects = mib_identifier((1, 3, 6, 1, 2, 1, 74, 1))
agentx_general = mib_identifier((1, 3, 6, 1, 2, 1, 74, 1, 1))
agentx_connection = mib_identifier((1, 3, 6, 1, 2, 1, 74, 1, 2))
agentx_session = mib_identifier((1, 3, 6, 1, 2, 1, 74, 1, 3))
agentx_registration = mib_identifier((1, 3, 6, 1, 2, 1, 74, 1, 4))
agentx_default_timeout = mib_scalar((1, 3, 6, 1, 2, 1, 74, 1, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(0, 255)).clone(5)).setUnits('seconds').setMaxAccess('readonly')
if mibBuilder.loadTexts:
agentxDefaultTimeout.setStatus('current')
if mibBuilder.loadTexts:
agentxDefaultTimeout.setDescription('The default length of time, in seconds, that the master agent should allow to elapse after dispatching a message to a session before it regards the subagent as not responding. This is a system-wide value that may override the timeout value associated with a particular session (agentxSessionTimeout) or a particular registered MIB region (agentxRegTimeout). If the associated value of agentxSessionTimeout and agentxRegTimeout are zero, or impractical in accordance with implementation-specific procedure of the master agent, the value represented by this object will be the effective timeout value for the master agent to await a response to a dispatch from a given subagent. ')
agentx_master_agent_x_ver = mib_scalar((1, 3, 6, 1, 2, 1, 74, 1, 1, 2), integer32().subtype(subtypeSpec=value_range_constraint(1, 255))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
agentxMasterAgentXVer.setStatus('current')
if mibBuilder.loadTexts:
agentxMasterAgentXVer.setDescription('The AgentX protocol version supported by this master agent. The current protocol version is 1. Note that the master agent must also allow interaction with earlier version subagents. ')
agentx_conn_table_last_change = mib_scalar((1, 3, 6, 1, 2, 1, 74, 1, 2, 1), time_stamp()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
agentxConnTableLastChange.setStatus('current')
if mibBuilder.loadTexts:
agentxConnTableLastChange.setDescription('The value of sysUpTime when the last row creation or deletion occurred in the agentxConnectionTable. ')
agentx_connection_table = mib_table((1, 3, 6, 1, 2, 1, 74, 1, 2, 2))
if mibBuilder.loadTexts:
agentxConnectionTable.setStatus('current')
if mibBuilder.loadTexts:
agentxConnectionTable.setDescription('The agentxConnectionTable tracks all current AgentX transport connections. There may be zero, one, or more AgentX sessions carried on a given AgentX connection. ')
agentx_connection_entry = mib_table_row((1, 3, 6, 1, 2, 1, 74, 1, 2, 2, 1)).setIndexNames((0, 'AGENTX-MIB', 'agentxConnIndex'))
if mibBuilder.loadTexts:
agentxConnectionEntry.setStatus('current')
if mibBuilder.loadTexts:
agentxConnectionEntry.setDescription('An agentxConnectionEntry contains information describing a single AgentX transport connection. A connection may be used to support zero or more AgentX sessions. An entry is created when a new transport connection is established, and is destroyed when the transport connection is terminated. ')
agentx_conn_index = mib_table_column((1, 3, 6, 1, 2, 1, 74, 1, 2, 2, 1, 1), unsigned32().subtype(subtypeSpec=value_range_constraint(1, 4294967295)))
if mibBuilder.loadTexts:
agentxConnIndex.setStatus('current')
if mibBuilder.loadTexts:
agentxConnIndex.setDescription('agentxConnIndex contains the value that uniquely identifies an open transport connection used by this master agent to provide AgentX service. Values of this index should not be re-used. The value assigned to a given transport connection is constant for the lifetime of that connection. ')
agentx_conn_open_time = mib_table_column((1, 3, 6, 1, 2, 1, 74, 1, 2, 2, 1, 2), time_stamp()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
agentxConnOpenTime.setStatus('current')
if mibBuilder.loadTexts:
agentxConnOpenTime.setDescription('The value of sysUpTime when this connection was established and, therefore, its value when this entry was added to the table. ')
agentx_conn_transport_domain = mib_table_column((1, 3, 6, 1, 2, 1, 74, 1, 2, 2, 1, 3), t_domain()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
agentxConnTransportDomain.setStatus('current')
if mibBuilder.loadTexts:
agentxConnTransportDomain.setDescription('The transport protocol in use for this connection to the subagent. ')
agentx_conn_transport_address = mib_table_column((1, 3, 6, 1, 2, 1, 74, 1, 2, 2, 1, 4), agentx_t_address()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
agentxConnTransportAddress.setStatus('current')
if mibBuilder.loadTexts:
agentxConnTransportAddress.setDescription('The transport address of the remote (subagent) end of this connection to the master agent. This object may be zero-length for unix-domain sockets (and possibly other types of transport addresses) since the subagent need not bind a filename to its local socket. ')
agentx_session_table_last_change = mib_scalar((1, 3, 6, 1, 2, 1, 74, 1, 3, 1), time_stamp()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
agentxSessionTableLastChange.setStatus('current')
if mibBuilder.loadTexts:
agentxSessionTableLastChange.setDescription('The value of sysUpTime when the last row creation or deletion occurred in the agentxSessionTable. ')
agentx_session_table = mib_table((1, 3, 6, 1, 2, 1, 74, 1, 3, 2))
if mibBuilder.loadTexts:
agentxSessionTable.setStatus('current')
if mibBuilder.loadTexts:
agentxSessionTable.setDescription('A table of AgentX subagent sessions currently in effect. ')
agentx_session_entry = mib_table_row((1, 3, 6, 1, 2, 1, 74, 1, 3, 2, 1)).setIndexNames((0, 'AGENTX-MIB', 'agentxConnIndex'), (0, 'AGENTX-MIB', 'agentxSessionIndex'))
if mibBuilder.loadTexts:
agentxSessionEntry.setStatus('current')
if mibBuilder.loadTexts:
agentxSessionEntry.setDescription('Information about a single open session between the AgentX master agent and a subagent is contained in this entry. An entry is created when a new session is successfully established and is destroyed either when the subagent transport connection has terminated or when the subagent session is closed. ')
agentx_session_index = mib_table_column((1, 3, 6, 1, 2, 1, 74, 1, 3, 2, 1, 1), unsigned32().subtype(subtypeSpec=value_range_constraint(0, 4294967295)))
if mibBuilder.loadTexts:
agentxSessionIndex.setStatus('current')
if mibBuilder.loadTexts:
agentxSessionIndex.setDescription("A unique index for the subagent session. It is the same as h.sessionID defined in the agentx header. Note that if a subagent's session with the master agent is closed for any reason its index should not be re-used. A value of zero(0) is specifically allowed in order to be compatible with the definition of h.sessionId. ")
agentx_session_object_id = mib_table_column((1, 3, 6, 1, 2, 1, 74, 1, 3, 2, 1, 2), object_identifier()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
agentxSessionObjectID.setStatus('current')
if mibBuilder.loadTexts:
agentxSessionObjectID.setDescription("This is taken from the o.id field of the agentx-Open-PDU. This attribute will report a value of '0.0' for subagents not supporting the notion of an AgentX session object identifier. ")
agentx_session_descr = mib_table_column((1, 3, 6, 1, 2, 1, 74, 1, 3, 2, 1, 3), snmp_admin_string()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
agentxSessionDescr.setStatus('current')
if mibBuilder.loadTexts:
agentxSessionDescr.setDescription('A textual description of the session. This is analogous to sysDescr defined in the SNMPv2-MIB in RFC 1907 [19] and is taken from the o.descr field of the agentx-Open-PDU. This attribute will report a zero-length string value for subagents not supporting the notion of a session description. ')
agentx_session_admin_status = mib_table_column((1, 3, 6, 1, 2, 1, 74, 1, 3, 2, 1, 4), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('up', 1), ('down', 2)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
agentxSessionAdminStatus.setStatus('current')
if mibBuilder.loadTexts:
agentxSessionAdminStatus.setDescription("The administrative (desired) status of the session. Setting the value to 'down(2)' closes the subagent session (with c.reason set to 'reasonByManager'). ")
agentx_session_open_time = mib_table_column((1, 3, 6, 1, 2, 1, 74, 1, 3, 2, 1, 5), time_stamp()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
agentxSessionOpenTime.setStatus('current')
if mibBuilder.loadTexts:
agentxSessionOpenTime.setDescription('The value of sysUpTime when this session was opened and, therefore, its value when this entry was added to the table. ')
agentx_session_agent_x_ver = mib_table_column((1, 3, 6, 1, 2, 1, 74, 1, 3, 2, 1, 6), integer32().subtype(subtypeSpec=value_range_constraint(1, 255))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
agentxSessionAgentXVer.setStatus('current')
if mibBuilder.loadTexts:
agentxSessionAgentXVer.setDescription('The version of the AgentX protocol supported by the session. This must be less than or equal to the value of agentxMasterAgentXVer. ')
agentx_session_timeout = mib_table_column((1, 3, 6, 1, 2, 1, 74, 1, 3, 2, 1, 7), integer32().subtype(subtypeSpec=value_range_constraint(0, 255))).setUnits('seconds').setMaxAccess('readonly')
if mibBuilder.loadTexts:
agentxSessionTimeout.setStatus('current')
if mibBuilder.loadTexts:
agentxSessionTimeout.setDescription("The length of time, in seconds, that a master agent should allow to elapse after dispatching a message to this session before it regards the subagent as not responding. This value is taken from the o.timeout field of the agentx-Open-PDU. This is a session-specific value that may be overridden by values associated with the specific registered MIB regions (see agentxRegTimeout). A value of zero(0) indicates that the master agent's default timeout value should be used (see agentxDefaultTimeout). ")
agentx_registration_table_last_change = mib_scalar((1, 3, 6, 1, 2, 1, 74, 1, 4, 1), time_stamp()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
agentxRegistrationTableLastChange.setStatus('current')
if mibBuilder.loadTexts:
agentxRegistrationTableLastChange.setDescription('The value of sysUpTime when the last row creation or deletion occurred in the agentxRegistrationTable. ')
agentx_registration_table = mib_table((1, 3, 6, 1, 2, 1, 74, 1, 4, 2))
if mibBuilder.loadTexts:
agentxRegistrationTable.setStatus('current')
if mibBuilder.loadTexts:
agentxRegistrationTable.setDescription('A table of registered regions. ')
agentx_registration_entry = mib_table_row((1, 3, 6, 1, 2, 1, 74, 1, 4, 2, 1)).setIndexNames((0, 'AGENTX-MIB', 'agentxConnIndex'), (0, 'AGENTX-MIB', 'agentxSessionIndex'), (0, 'AGENTX-MIB', 'agentxRegIndex'))
if mibBuilder.loadTexts:
agentxRegistrationEntry.setStatus('current')
if mibBuilder.loadTexts:
agentxRegistrationEntry.setDescription('Contains information for a single registered region. An entry is created when a session successfully registers a region and is destroyed for any of three reasons: this region is unregistered by the session, the session is closed, or the subagent connection is closed. ')
agentx_reg_index = mib_table_column((1, 3, 6, 1, 2, 1, 74, 1, 4, 2, 1, 1), unsigned32().subtype(subtypeSpec=value_range_constraint(1, 4294967295)))
if mibBuilder.loadTexts:
agentxRegIndex.setStatus('current')
if mibBuilder.loadTexts:
agentxRegIndex.setDescription('agentxRegIndex uniquely identifies a registration entry. This value is constant for the lifetime of an entry. ')
agentx_reg_context = mib_table_column((1, 3, 6, 1, 2, 1, 74, 1, 4, 2, 1, 2), octet_string()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
agentxRegContext.setStatus('current')
if mibBuilder.loadTexts:
agentxRegContext.setDescription('The context in which the session supports the objects in this region. A zero-length context indicates the default context. ')
agentx_reg_start = mib_table_column((1, 3, 6, 1, 2, 1, 74, 1, 4, 2, 1, 3), object_identifier()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
agentxRegStart.setStatus('current')
if mibBuilder.loadTexts:
agentxRegStart.setDescription('The starting OBJECT IDENTIFIER of this registration entry. The session identified by agentxSessionIndex implements objects starting at this value (inclusive). Note that this value could identify an object type, an object instance, or a partial object instance. ')
agentx_reg_range_sub_id = mib_table_column((1, 3, 6, 1, 2, 1, 74, 1, 4, 2, 1, 4), unsigned32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
agentxRegRangeSubId.setStatus('current')
if mibBuilder.loadTexts:
agentxRegRangeSubId.setDescription("agentxRegRangeSubId is used to specify the range. This is taken from r.region_subid in the registration PDU. If the value of this object is zero, no range is specified. If it is non-zero, it identifies the `nth' sub-identifier in r.region for which this entry's agentxRegUpperBound value is substituted in the OID for purposes of defining the region's upper bound. ")
agentx_reg_upper_bound = mib_table_column((1, 3, 6, 1, 2, 1, 74, 1, 4, 2, 1, 5), unsigned32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
agentxRegUpperBound.setStatus('current')
if mibBuilder.loadTexts:
agentxRegUpperBound.setDescription('agentxRegUpperBound represents the upper-bound sub-identifier in a registration. This is taken from the r.upper_bound in the registration PDU. If agentxRegRangeSubid (r.region_subid) is zero, this value is also zero and is not used to define an upper bound for this registration. ')
agentx_reg_priority = mib_table_column((1, 3, 6, 1, 2, 1, 74, 1, 4, 2, 1, 6), unsigned32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
agentxRegPriority.setStatus('current')
if mibBuilder.loadTexts:
agentxRegPriority.setDescription('The registration priority. Lower values have higher priority. This value is taken from r.priority in the register PDU. Sessions should use the value of 127 for r.priority if a default value is desired. ')
agentx_reg_timeout = mib_table_column((1, 3, 6, 1, 2, 1, 74, 1, 4, 2, 1, 7), integer32().subtype(subtypeSpec=value_range_constraint(0, 255))).setUnits('seconds').setMaxAccess('readonly')
if mibBuilder.loadTexts:
agentxRegTimeout.setStatus('current')
if mibBuilder.loadTexts:
agentxRegTimeout.setDescription('The timeout value, in seconds, for responses to requests associated with this registered MIB region. A value of zero(0) indicates the default value (indicated by by agentxSessionTimeout or agentxDefaultTimeout) is to be used. This value is taken from the r.timeout field of the agentx-Register-PDU. ')
agentx_reg_instance = mib_table_column((1, 3, 6, 1, 2, 1, 74, 1, 4, 2, 1, 8), truth_value()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
agentxRegInstance.setStatus('current')
if mibBuilder.loadTexts:
agentxRegInstance.setDescription("The value of agentxRegInstance is `true' for registrations for which the INSTANCE_REGISTRATION was set, and is `false' for all other registrations. ")
agentx_conformance = mib_identifier((1, 3, 6, 1, 2, 1, 74, 2))
agentx_mib_groups = mib_identifier((1, 3, 6, 1, 2, 1, 74, 2, 1))
agentx_mib_compliances = mib_identifier((1, 3, 6, 1, 2, 1, 74, 2, 2))
agentx_mib_compliance = module_compliance((1, 3, 6, 1, 2, 1, 74, 2, 2, 1)).setObjects(('AGENTX-MIB', 'agentxMIBGroup'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
agentx_mib_compliance = agentxMIBCompliance.setStatus('current')
if mibBuilder.loadTexts:
agentxMIBCompliance.setDescription('The compliance statement for SNMP entities that implement the AgentX protocol. Note that a compliant agent can implement all objects in this MIB module as read-only. ')
agentx_mib_group = object_group((1, 3, 6, 1, 2, 1, 74, 2, 1, 1)).setObjects(('AGENTX-MIB', 'agentxDefaultTimeout'), ('AGENTX-MIB', 'agentxMasterAgentXVer'), ('AGENTX-MIB', 'agentxConnTableLastChange'), ('AGENTX-MIB', 'agentxConnOpenTime'), ('AGENTX-MIB', 'agentxConnTransportDomain'), ('AGENTX-MIB', 'agentxConnTransportAddress'), ('AGENTX-MIB', 'agentxSessionTableLastChange'), ('AGENTX-MIB', 'agentxSessionTimeout'), ('AGENTX-MIB', 'agentxSessionObjectID'), ('AGENTX-MIB', 'agentxSessionDescr'), ('AGENTX-MIB', 'agentxSessionAdminStatus'), ('AGENTX-MIB', 'agentxSessionOpenTime'), ('AGENTX-MIB', 'agentxSessionAgentXVer'), ('AGENTX-MIB', 'agentxRegistrationTableLastChange'), ('AGENTX-MIB', 'agentxRegContext'), ('AGENTX-MIB', 'agentxRegStart'), ('AGENTX-MIB', 'agentxRegRangeSubId'), ('AGENTX-MIB', 'agentxRegUpperBound'), ('AGENTX-MIB', 'agentxRegPriority'), ('AGENTX-MIB', 'agentxRegTimeout'), ('AGENTX-MIB', 'agentxRegInstance'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
agentx_mib_group = agentxMIBGroup.setStatus('current')
if mibBuilder.loadTexts:
agentxMIBGroup.setDescription('All accessible objects in the AgentX MIB. ')
mibBuilder.exportSymbols('AGENTX-MIB', agentxConnTransportAddress=agentxConnTransportAddress, agentxRegistrationTable=agentxRegistrationTable, agentxMIBGroups=agentxMIBGroups, agentxSession=agentxSession, agentxDefaultTimeout=agentxDefaultTimeout, agentxConformance=agentxConformance, agentxGeneral=agentxGeneral, PYSNMP_MODULE_ID=agentxMIB, agentxConnTransportDomain=agentxConnTransportDomain, agentxSessionTableLastChange=agentxSessionTableLastChange, AgentxTAddress=AgentxTAddress, agentxRegInstance=agentxRegInstance, agentxMIBCompliances=agentxMIBCompliances, agentxRegistration=agentxRegistration, agentxConnIndex=agentxConnIndex, agentxConnOpenTime=agentxConnOpenTime, agentxRegIndex=agentxRegIndex, agentxMIB=agentxMIB, agentxSessionIndex=agentxSessionIndex, agentxRegistrationTableLastChange=agentxRegistrationTableLastChange, agentxSessionEntry=agentxSessionEntry, agentxRegRangeSubId=agentxRegRangeSubId, agentxConnTableLastChange=agentxConnTableLastChange, agentxSessionAgentXVer=agentxSessionAgentXVer, agentxSessionOpenTime=agentxSessionOpenTime, agentxRegTimeout=agentxRegTimeout, agentxMIBGroup=agentxMIBGroup, agentxSessionTable=agentxSessionTable, agentxSessionObjectID=agentxSessionObjectID, agentxRegStart=agentxRegStart, agentxSessionTimeout=agentxSessionTimeout, agentxConnectionTable=agentxConnectionTable, agentxConnectionEntry=agentxConnectionEntry, agentxRegPriority=agentxRegPriority, agentxMIBCompliance=agentxMIBCompliance, agentxRegistrationEntry=agentxRegistrationEntry, agentxRegUpperBound=agentxRegUpperBound, agentxConnection=agentxConnection, agentxObjects=agentxObjects, agentxSessionAdminStatus=agentxSessionAdminStatus, agentxMasterAgentXVer=agentxMasterAgentXVer, agentxRegContext=agentxRegContext, agentxSessionDescr=agentxSessionDescr) |
class Layer:
def __init(self):
self.input=None
self.output=None
def forward(self,input):
#to return the output layer
pass
def backward(self,output_gradient,learning_rate):
#change para and return input derivative
pass
| class Layer:
def __init(self):
self.input = None
self.output = None
def forward(self, input):
pass
def backward(self, output_gradient, learning_rate):
pass |
class Capture:
def capture(self):
pass
| class Capture:
def capture(self):
pass |
def f(n):
if n == 0: return 0
elif n == 1: return 1
else: return f(n-1)+f(n-2)
n=int(input())
values = [str(f(x)) for x in range(0, n+1)]
print(",".join(values)) | def f(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return f(n - 1) + f(n - 2)
n = int(input())
values = [str(f(x)) for x in range(0, n + 1)]
print(','.join(values)) |
#TODO Create Functions for PMTA
## TORISPHERICAL TOP HEAD 2:1 - Min thickness allowed and PMTA
class TorisphericalCalcs:
def __init__(self):
self.L_top_head = None
self.r_top_head = None
self.ratio_L_r_top = None
self.M_factor_top_head = None
self.t_min_top_head = None
self.t_nom_top_head_plate =None
self.t_top_head_nom_after_conf = None
self.top_head_pmta = None
self.L_bottom_head = None
self.r_bottom_head = None
self.ratio_L_r_bottom = None
self.M_factor_bottom_head = None
self.t_min_bottom_head = None
self.t_nom_bottom_head_plate = None
self.t_bottom_head_nom_after_conf = None
self.bottom_head_pmta = None
def tor_top_min_thick_allowed(self,Rcor, P, Shot_top_head, E, conf_loss, C):
self.L_top_head = 0.904 * (2 * Rcor)
self.r_top_head = 0.173 * (2 * Rcor)
self.ratio_L_r_top = self.L_top_head/self.r_top_head
self.M_factor_top_head = (1/4) * (3 + (self.ratio_L_r_top)**(1/2))
self.t_min_top_head = (P * self.L_top_head * self.M_factor_top_head) / ((2 * Shot_top_head * E) - 0.2 * P)
self.t_nom_top_head_plate = self.t_min_top_head + conf_loss + C
self.t_top_head_nom_after_conf = self.t_min_top_head + C
print(f"\n\nTorispherical Top Head Min thickness allowed: \n\nTop Head radius (L) is {self.L_top_head} mm \nTop Head Toroidal radius (r) is {self.r_top_head} mm \nTop Head M factor (M) is {self.M_factor_top_head}")
print(f"Top Head minimun thickness due circuferencial stress is {self.t_min_top_head} mm.")
print(f"Top Head plate Thickness w/ Corrosion allowance and conf. loss is {self.t_nom_top_head_plate} mm. Ps.: Choose equal or higher comercial plate")
print(f"Top Head Nominal Thicknes after conformation is {self.t_top_head_nom_after_conf} mm")
return self.L_top_head, self.r_top_head, self.ratio_L_r_top , self.M_factor_top_head, self.t_nom_top_head_plate, self.t_top_head_nom_after_conf, self.t_min_top_head
def tor_top_head_pmta (self,Rcor, Shot_top_head, E):
self.L_top_head = 0.904 * (2 * Rcor)
self.r_top_head = 0.173 * (2 * Rcor)
self.ratio_L_r_top = self.L_top_head/self.r_top_head
self.M_factor_top_head = (1/4) * (3 + (self.ratio_L_r_top)**(1/2))
self.top_head_pmta = (2*self.t_min_top_head*Shot_top_head*E)/(self.L_top_head*self.M_factor_top_head + 0.2*self.t_min_top_head)
print(f"Top Head MAWP is: {self.top_head_pmta} kPa")
return self.top_head_pmta
def tor_top_head_stress_calc(self, P, E):
self.top_head_stress = P * (self.L_top_head * self.M_factor_top_head + 0.2 * self.t_min_top_head) / (2 * self.t_min_top_head * E)
print(f"Top head stress is {self.top_head_stress} kPa")
return self.top_head_stress
## TORISPHERICAL BOTTOM HEAD 2:1 - Min thickness allowed and PMTA
def tor_bottom_min_thick_allowed(self,Rcor,Pwater_col, P, Shot_bottom_head, E, conf_loss, C ):
self.L_bottom_head = 0.904 * (2 * Rcor)
self.r_bottom_head = 0.173 * (2 * Rcor)
self.ratio_L_r_bottom = self.L_bottom_head/self.r_bottom_head
self.M_factor_bottom_head = (1/4) * (3 + (self.ratio_L_r_bottom)**(1/2))
self.t_min_bottom_head = ((P+Pwater_col) * self.L_bottom_head * self.M_factor_bottom_head) / ((2 * Shot_bottom_head * E) - 0.2 * P)
self.t_nom_bottom_head_plate = self.t_min_bottom_head + conf_loss + C
self.t_bottom_head_nom_after_conf = self.t_min_bottom_head + C
print(f"\n\nTorispherical Bottom Head Min thickness allowed: \n\nBottom Head radius (L) is {self.L_bottom_head} mm \nBottom Head Toroidal radius (r) is {self.r_bottom_head} mm \nBottom Head M factor (M) is {self.M_factor_bottom_head}")
print(f"Bottom Head minimun thickness due circuferencial stress is {self.t_min_bottom_head} mm.")
print(f"Bottom Head plate Thickness w/ Corrosion allowance and conf. loss is {self.t_nom_bottom_head_plate} mm. Ps.: Choose equal or higher comercial plate")
print(f"Bottom Head Nominal Thicknes after conformation is {self.t_bottom_head_nom_after_conf} mm")
return self.L_bottom_head, self.r_bottom_head, self.ratio_L_r_bottom, self.M_factor_bottom_head, self.t_min_bottom_head, self.t_nom_bottom_head_plate, self.t_bottom_head_nom_after_conf
def tor_bottom_head_pmta (self,Rcor, E, Shot_bottom_head):
self.L_bottom_head = 0.904 * (2 * Rcor)
self.r_bottom_head = 0.173 * (2 * Rcor)
self.ratio_L_r_bottom = self.L_bottom_head/self.r_bottom_head
self.M_factor_bottom_head = (1/4) * (3 + (self.ratio_L_r_bottom)**(1/2))
self.bottom_head_pmta = (2*self.t_min_bottom_head*Shot_bottom_head*E)/(self.L_bottom_head*self.M_factor_bottom_head + 0.2*self.t_min_bottom_head)
print(f"Bottom Head MAWP is: {self.bottom_head_pmta} kPa")
return self.bottom_head_pmta
def tor_bottom_head_stress_calc(self,Pwater_col, P, E):
self.bottom_head_stress = (P+Pwater_col) * (self.L_bottom_head * self.M_factor_bottom_head + 0.2 * self.t_min_bottom_head) / (2 * self.t_min_bottom_head * E)
print(f"Bottom head stress is {self.bottom_head_stress} kPa")
return self.bottom_head_stress | class Torisphericalcalcs:
def __init__(self):
self.L_top_head = None
self.r_top_head = None
self.ratio_L_r_top = None
self.M_factor_top_head = None
self.t_min_top_head = None
self.t_nom_top_head_plate = None
self.t_top_head_nom_after_conf = None
self.top_head_pmta = None
self.L_bottom_head = None
self.r_bottom_head = None
self.ratio_L_r_bottom = None
self.M_factor_bottom_head = None
self.t_min_bottom_head = None
self.t_nom_bottom_head_plate = None
self.t_bottom_head_nom_after_conf = None
self.bottom_head_pmta = None
def tor_top_min_thick_allowed(self, Rcor, P, Shot_top_head, E, conf_loss, C):
self.L_top_head = 0.904 * (2 * Rcor)
self.r_top_head = 0.173 * (2 * Rcor)
self.ratio_L_r_top = self.L_top_head / self.r_top_head
self.M_factor_top_head = 1 / 4 * (3 + self.ratio_L_r_top ** (1 / 2))
self.t_min_top_head = P * self.L_top_head * self.M_factor_top_head / (2 * Shot_top_head * E - 0.2 * P)
self.t_nom_top_head_plate = self.t_min_top_head + conf_loss + C
self.t_top_head_nom_after_conf = self.t_min_top_head + C
print(f'\n\nTorispherical Top Head Min thickness allowed: \n\nTop Head radius (L) is {self.L_top_head} mm \nTop Head Toroidal radius (r) is {self.r_top_head} mm \nTop Head M factor (M) is {self.M_factor_top_head}')
print(f'Top Head minimun thickness due circuferencial stress is {self.t_min_top_head} mm.')
print(f'Top Head plate Thickness w/ Corrosion allowance and conf. loss is {self.t_nom_top_head_plate} mm. Ps.: Choose equal or higher comercial plate')
print(f'Top Head Nominal Thicknes after conformation is {self.t_top_head_nom_after_conf} mm')
return (self.L_top_head, self.r_top_head, self.ratio_L_r_top, self.M_factor_top_head, self.t_nom_top_head_plate, self.t_top_head_nom_after_conf, self.t_min_top_head)
def tor_top_head_pmta(self, Rcor, Shot_top_head, E):
self.L_top_head = 0.904 * (2 * Rcor)
self.r_top_head = 0.173 * (2 * Rcor)
self.ratio_L_r_top = self.L_top_head / self.r_top_head
self.M_factor_top_head = 1 / 4 * (3 + self.ratio_L_r_top ** (1 / 2))
self.top_head_pmta = 2 * self.t_min_top_head * Shot_top_head * E / (self.L_top_head * self.M_factor_top_head + 0.2 * self.t_min_top_head)
print(f'Top Head MAWP is: {self.top_head_pmta} kPa')
return self.top_head_pmta
def tor_top_head_stress_calc(self, P, E):
self.top_head_stress = P * (self.L_top_head * self.M_factor_top_head + 0.2 * self.t_min_top_head) / (2 * self.t_min_top_head * E)
print(f'Top head stress is {self.top_head_stress} kPa')
return self.top_head_stress
def tor_bottom_min_thick_allowed(self, Rcor, Pwater_col, P, Shot_bottom_head, E, conf_loss, C):
self.L_bottom_head = 0.904 * (2 * Rcor)
self.r_bottom_head = 0.173 * (2 * Rcor)
self.ratio_L_r_bottom = self.L_bottom_head / self.r_bottom_head
self.M_factor_bottom_head = 1 / 4 * (3 + self.ratio_L_r_bottom ** (1 / 2))
self.t_min_bottom_head = (P + Pwater_col) * self.L_bottom_head * self.M_factor_bottom_head / (2 * Shot_bottom_head * E - 0.2 * P)
self.t_nom_bottom_head_plate = self.t_min_bottom_head + conf_loss + C
self.t_bottom_head_nom_after_conf = self.t_min_bottom_head + C
print(f'\n\nTorispherical Bottom Head Min thickness allowed: \n\nBottom Head radius (L) is {self.L_bottom_head} mm \nBottom Head Toroidal radius (r) is {self.r_bottom_head} mm \nBottom Head M factor (M) is {self.M_factor_bottom_head}')
print(f'Bottom Head minimun thickness due circuferencial stress is {self.t_min_bottom_head} mm.')
print(f'Bottom Head plate Thickness w/ Corrosion allowance and conf. loss is {self.t_nom_bottom_head_plate} mm. Ps.: Choose equal or higher comercial plate')
print(f'Bottom Head Nominal Thicknes after conformation is {self.t_bottom_head_nom_after_conf} mm')
return (self.L_bottom_head, self.r_bottom_head, self.ratio_L_r_bottom, self.M_factor_bottom_head, self.t_min_bottom_head, self.t_nom_bottom_head_plate, self.t_bottom_head_nom_after_conf)
def tor_bottom_head_pmta(self, Rcor, E, Shot_bottom_head):
self.L_bottom_head = 0.904 * (2 * Rcor)
self.r_bottom_head = 0.173 * (2 * Rcor)
self.ratio_L_r_bottom = self.L_bottom_head / self.r_bottom_head
self.M_factor_bottom_head = 1 / 4 * (3 + self.ratio_L_r_bottom ** (1 / 2))
self.bottom_head_pmta = 2 * self.t_min_bottom_head * Shot_bottom_head * E / (self.L_bottom_head * self.M_factor_bottom_head + 0.2 * self.t_min_bottom_head)
print(f'Bottom Head MAWP is: {self.bottom_head_pmta} kPa')
return self.bottom_head_pmta
def tor_bottom_head_stress_calc(self, Pwater_col, P, E):
self.bottom_head_stress = (P + Pwater_col) * (self.L_bottom_head * self.M_factor_bottom_head + 0.2 * self.t_min_bottom_head) / (2 * self.t_min_bottom_head * E)
print(f'Bottom head stress is {self.bottom_head_stress} kPa')
return self.bottom_head_stress |
# Collaborators (including web sites where you got help: (enter none if you didn't need help)
# claryse adams
def avg_temp(user_list):
total = 0
for x in range(1, len(user_list)):
total += user_list[x]
average = total/(len(user_list)-1)
average = round(average, 2)
return average
if __name__ == '__main__':
with open("temps.txt") as file_object:
contents = file_object.readlines()
int()
list_length = len(contents)
for i in range(1, list_length):
contents[i] = contents[i].rstrip()
contents[i] = int(contents[i])
print(contents)
print(avg_temp(contents)) | def avg_temp(user_list):
total = 0
for x in range(1, len(user_list)):
total += user_list[x]
average = total / (len(user_list) - 1)
average = round(average, 2)
return average
if __name__ == '__main__':
with open('temps.txt') as file_object:
contents = file_object.readlines()
int()
list_length = len(contents)
for i in range(1, list_length):
contents[i] = contents[i].rstrip()
contents[i] = int(contents[i])
print(contents)
print(avg_temp(contents)) |
def fry():
print('The eggs have been fried')
| def fry():
print('The eggs have been fried') |
class Data:
def __init__(self, dia, mes, ano):
self.dia = dia
self.mes = mes
self.ano = ano
print(self)
@classmethod
def de_string(cls, data_string):
dia, mes, ano = map(int, data_string.split("-"))
data = cls(dia, mes, ano)
return data
@staticmethod
def is_date_valid(data_string):
dia, mes, ano = map(int, data_string.split("-"))
return dia <= 31 and mes <= 12 and ano <= 2030
data = Data(10, 10, 10)
data1 = data.de_string("10-10-2020")
print(data1)
vdd = data1.is_date_valid("10-10-2020")
print(vdd)
| class Data:
def __init__(self, dia, mes, ano):
self.dia = dia
self.mes = mes
self.ano = ano
print(self)
@classmethod
def de_string(cls, data_string):
(dia, mes, ano) = map(int, data_string.split('-'))
data = cls(dia, mes, ano)
return data
@staticmethod
def is_date_valid(data_string):
(dia, mes, ano) = map(int, data_string.split('-'))
return dia <= 31 and mes <= 12 and (ano <= 2030)
data = data(10, 10, 10)
data1 = data.de_string('10-10-2020')
print(data1)
vdd = data1.is_date_valid('10-10-2020')
print(vdd) |
class DummyContext:
context = {}
dummy_context = DummyContext()
| class Dummycontext:
context = {}
dummy_context = dummy_context() |
# Copyright 2020 BBC Research & Development
#
# 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.
# ==============================================================================
experiment_name = "exp1_bn" # experiment name
experiment_path = "experiment/path" # experiment base path
output_path = experiment_path + experiment_name
# Model parameters
core_model = "bn_model" # [bn_model, in_model, bn_sn_model, in_sn_model, ibn_model]
d_scales = 1 # number of multi discriminator scales
# Data parameters
data_path = "data/path" # data path for train and test
input_shape = (256, 256) # input shape
input_color_mode = 'rgb' # input colour space (same as data path content)
output_color_mode = 'lab' # output colour space
interpolation = 'nearest' # interpolation for reshaping operations
chunk_size = 10000 # reading chunk size
samples_rate = 1. # percentage of output samples within data path
shuffle = True # shuffle during training
seed = 42 # seed for shuffle operation
# Training parameters
epochs = 200 # training epochs
batch_size = 16 # batch size for train and validation. batch_size = 1 for test
l1_lambda = 100 # l1 weight into global loss function
lr_d = 0.0002 # learning rate for discriminator
lr_g = 0.0002 # learning rate for generator
beta = 0.5 # learning beta
display_step = 10 # step size for updating tensorboard log file
plots_per_epoch = 20 # prediction logs per epoch
weights_per_epoch = 20 # weight checkpoints per epoch
multi_gpu = False # enable multi gpu model
gpus = 2 # number of available gpus
workers = 10 # number of worker threads
max_queue_size = 10 # queue size for worker threads
use_multiprocessing = False # use multiprocessing
| experiment_name = 'exp1_bn'
experiment_path = 'experiment/path'
output_path = experiment_path + experiment_name
core_model = 'bn_model'
d_scales = 1
data_path = 'data/path'
input_shape = (256, 256)
input_color_mode = 'rgb'
output_color_mode = 'lab'
interpolation = 'nearest'
chunk_size = 10000
samples_rate = 1.0
shuffle = True
seed = 42
epochs = 200
batch_size = 16
l1_lambda = 100
lr_d = 0.0002
lr_g = 0.0002
beta = 0.5
display_step = 10
plots_per_epoch = 20
weights_per_epoch = 20
multi_gpu = False
gpus = 2
workers = 10
max_queue_size = 10
use_multiprocessing = False |
# -*- coding: utf-8 -*-
__author__ = 'Wael Ben Zid El Guebsi'
__email__ = 'benzid.wael@hotmail.fr'
__version__ = '0.0.0' | __author__ = 'Wael Ben Zid El Guebsi'
__email__ = 'benzid.wael@hotmail.fr'
__version__ = '0.0.0' |
# coding: utf-8
n = int(input())
li = [int(i) for i in input().split()]
print(sum(li)/n)
| n = int(input())
li = [int(i) for i in input().split()]
print(sum(li) / n) |
class Question:
def __init__(self, text, answer):
self.text = text
self.answer = answer
new_q = Question("lkajsdkf", "False")
| class Question:
def __init__(self, text, answer):
self.text = text
self.answer = answer
new_q = question('lkajsdkf', 'False') |
def find_three_values_that_sum(lines, sum=2020):
for idx1, line1 in enumerate(lines):
for idx2, line2 in enumerate(lines[idx1:]):
for idx3, line3 in enumerate(lines[idx1+idx2:]):
num1 = int(line1)
num2 = int(line2)
num3 = int(line3)
if (num1 + num2 + num3 == sum):
print(f'Found the matching values (idx):value: ({idx1}): {num1}, ({idx2}): {num2}, ({idx3}): {num3}')
return num1, num2, num3
def find_two_values_that_sum(lines, sum=2020):
for idx1, line1 in enumerate(lines):
for idx2, line2 in enumerate(lines[idx1:]):
num1 = int(line1)
num2 = int(line2)
if (num1 + num2 == sum):
print(f'Found the matching values (idx):value: ({idx1}): {num1}, ({idx2}): {num2}')
return num1, num2
def main():
filename = 'input-p1.txt'
with open(filename, 'r') as f:
lines = f.readlines()
print(f'Read in file: {filename} Number of lines: {len(lines)}')
num1, num2 = find_two_values_that_sum(lines, sum=2020)
print(f'Multiply two values together: {num1 * num2}')
num1, num2, num3 = find_three_values_that_sum(lines, sum=2020)
print(f'Multiply three values together: {num1 * num2 * num3}')
if __name__ == '__main__':
main()
| def find_three_values_that_sum(lines, sum=2020):
for (idx1, line1) in enumerate(lines):
for (idx2, line2) in enumerate(lines[idx1:]):
for (idx3, line3) in enumerate(lines[idx1 + idx2:]):
num1 = int(line1)
num2 = int(line2)
num3 = int(line3)
if num1 + num2 + num3 == sum:
print(f'Found the matching values (idx):value: ({idx1}): {num1}, ({idx2}): {num2}, ({idx3}): {num3}')
return (num1, num2, num3)
def find_two_values_that_sum(lines, sum=2020):
for (idx1, line1) in enumerate(lines):
for (idx2, line2) in enumerate(lines[idx1:]):
num1 = int(line1)
num2 = int(line2)
if num1 + num2 == sum:
print(f'Found the matching values (idx):value: ({idx1}): {num1}, ({idx2}): {num2}')
return (num1, num2)
def main():
filename = 'input-p1.txt'
with open(filename, 'r') as f:
lines = f.readlines()
print(f'Read in file: {filename} Number of lines: {len(lines)}')
(num1, num2) = find_two_values_that_sum(lines, sum=2020)
print(f'Multiply two values together: {num1 * num2}')
(num1, num2, num3) = find_three_values_that_sum(lines, sum=2020)
print(f'Multiply three values together: {num1 * num2 * num3}')
if __name__ == '__main__':
main() |
"Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k"
class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
if not nums or len(nums) == 1:
return False
pairs = dict()
for idx, num in enumerate(nums):
if num in pairs:
if abs(pairs[num] - idx) <= k:
return True
pairs[num] = idx
return False
| """Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k"""
class Solution:
def contains_nearby_duplicate(self, nums: List[int], k: int) -> bool:
if not nums or len(nums) == 1:
return False
pairs = dict()
for (idx, num) in enumerate(nums):
if num in pairs:
if abs(pairs[num] - idx) <= k:
return True
pairs[num] = idx
return False |
class Solution:
def generate(self, numRows: int):
result = []
if not numRows:
return result
for i in range(1, numRows + 1):
temp = [1] * i
lo = 1
hi = i - 2
while lo <= hi:
temp[lo] = temp[hi] = result[i - 2][lo] + result[i - 2][lo - 1]
lo += 1
hi -= 1
result.append(temp)
return result | class Solution:
def generate(self, numRows: int):
result = []
if not numRows:
return result
for i in range(1, numRows + 1):
temp = [1] * i
lo = 1
hi = i - 2
while lo <= hi:
temp[lo] = temp[hi] = result[i - 2][lo] + result[i - 2][lo - 1]
lo += 1
hi -= 1
result.append(temp)
return result |
# 1921. Eliminate Maximum Number of Monsters
# You are playing a video game where you are defending your city from a group of n monsters.
# You are given a 0-indexed integer array dist of size n, where dist[i] is the initial
# distance in meters of the ith monster from the city.
# The monsters walk toward the city at a constant speed. The speed of each monster is
# given to you in an integer array speed of size n, where speed[i] is the speed of the
# ith monster in meters per minute.
# The monsters start moving at minute 0. You have a weapon that you can choose to use
# at the start of every minute, including minute 0. You cannot use the weapon in the
# middle of a minute. The weapon can eliminate any monster that is still alive.
# You lose when any monster reaches your city. If a monster reaches the city exactly
# at the start of a minute, it counts as a loss, and the game ends before you can use
# your weapon in that minute.
# Return the maximum number of monsters that you can eliminate before you lose, or n
# if you can eliminate all the monsters before they reach the city.
# Example 1:
# Input: dist = [1,3,4], speed = [1,1,1]
# Output: 3
# Explanation:
# At the start of minute 0, the distances of the monsters are [1,3,4], you eliminate the first monster.
# At the start of minute 1, the distances of the monsters are [X,2,3], you don't do anything.
# At the start of minute 2, the distances of the monsters are [X,1,2], you eliminate the second monster.
# At the start of minute 3, the distances of the monsters are [X,X,1], you eliminate the third monster.
# All 3 monsters can be eliminated.
# Example 2:
# Input: dist = [1,1,2,3], speed = [1,1,1,1]
# Output: 1
# Explanation:
# At the start of minute 0, the distances of the monsters are [1,1,2,3], you eliminate the first monster.
# At the start of minute 1, the distances of the monsters are [X,0,1,2], so you lose.
# You can only eliminate 1 monster.
# Example 3:
# Input: dist = [3,2,4], speed = [5,3,2]
# Output: 1
# Explanation:
# At the start of minute 0, the distances of the monsters are [3,2,4], you eliminate the first monster.
# At the start of minute 1, the distances of the monsters are [X,0,2], so you lose.
# You can only eliminate 1 monster.
# Constraints:
# n == dist.length == speed.length
# 1 <= n <= 105
# 1 <= dist[i], speed[i] <= 105
# Solution
# Sort the monsters by arrival times
# If the moster arrives earlier than we can shoot, then we lost
class Solution:
def eliminateMaximum(self, dist: List[int], speed: List[int]) -> int:
if not dist or not speed or len(dist) == 0 or len(speed) == 0 or len(dist) != len(speed):
return 0
l = len(speed)
orders = []
for i in range(l):
orders.append([dist[i], speed[i]])
orders.sort(key=lambda x: math.ceil(x[0] / x[1]))
for i in range(l):
if orders[i][0] <= i * orders[i][1]:
# arrive earlier than we can shoot
return i
return l
| class Solution:
def eliminate_maximum(self, dist: List[int], speed: List[int]) -> int:
if not dist or not speed or len(dist) == 0 or (len(speed) == 0) or (len(dist) != len(speed)):
return 0
l = len(speed)
orders = []
for i in range(l):
orders.append([dist[i], speed[i]])
orders.sort(key=lambda x: math.ceil(x[0] / x[1]))
for i in range(l):
if orders[i][0] <= i * orders[i][1]:
return i
return l |
__author__ = 'Chetan'
class Wizard():
def __init__(self, src, rootdir):
self.choices = []
self.rootdir = rootdir
self.src = src
def preferences(self, command):
self.choices.append(command)
def execute(self):
for choice in self.choices:
if list(choice.values())[0]:
print("Copying binaries --", self.src, " to ", self.rootdir)
else:
print("No Operation")
def rollback(self):
print("Deleting the unwanted..", self.rootdir)
if __name__ == '__main__':
## Client code
wizard = Wizard('python3.5.gzip', '/usr/bin/')
## Steps for installation. ## Users chooses to install Python only
wizard.preferences({'python':True})
wizard.preferences({'java':False})
wizard.execute()
| __author__ = 'Chetan'
class Wizard:
def __init__(self, src, rootdir):
self.choices = []
self.rootdir = rootdir
self.src = src
def preferences(self, command):
self.choices.append(command)
def execute(self):
for choice in self.choices:
if list(choice.values())[0]:
print('Copying binaries --', self.src, ' to ', self.rootdir)
else:
print('No Operation')
def rollback(self):
print('Deleting the unwanted..', self.rootdir)
if __name__ == '__main__':
wizard = wizard('python3.5.gzip', '/usr/bin/')
wizard.preferences({'python': True})
wizard.preferences({'java': False})
wizard.execute() |
#######################################################
#
# ManageRacacatPinController.py
# Python implementation of the Class ManageRacacatPinController
# Generated by Enterprise Architect
# Created on: 15-Apr-2020 4:57:23 PM
# Original author: Giu Platania
#
#######################################################
class ManageRacacatPinController:
# default constructor def __init__(self):
pass | class Manageracacatpincontroller:
pass |
N = int(input())
ans = 0
if N < 10 ** 3:
print(0)
elif 10 ** 3 <= N < 10 ** 6:
print(N - 10 ** 3 + 1)
elif 10 ** 6 <= N < 10 ** 9:
print(10 ** 6 - 10 ** 3 + (N - 10 ** 6 + 1)*2)
elif 10 ** 9 <= N < 10 ** 12:
print(10 ** 6 - 10 ** 3 + (10 ** 9 - 10 ** 6)*2 + (N - 10 ** 9 + 1)*3)
elif 10 ** 12 <= N < 10 ** 15:
print(10 ** 6 - 10 ** 3 + (10 ** 9 - 10 ** 6)*2 + (10 ** 12 - 10 ** 9)*3 + (N - 10 ** 12 + 1)*4)
else:
print(10 ** 6 - 10 ** 3 + (10 ** 9 - 10 ** 6)*2 + (10 ** 12 - 10 ** 9)*3 + (10 ** 15 - 10 ** 12)*4 + 5) | n = int(input())
ans = 0
if N < 10 ** 3:
print(0)
elif 10 ** 3 <= N < 10 ** 6:
print(N - 10 ** 3 + 1)
elif 10 ** 6 <= N < 10 ** 9:
print(10 ** 6 - 10 ** 3 + (N - 10 ** 6 + 1) * 2)
elif 10 ** 9 <= N < 10 ** 12:
print(10 ** 6 - 10 ** 3 + (10 ** 9 - 10 ** 6) * 2 + (N - 10 ** 9 + 1) * 3)
elif 10 ** 12 <= N < 10 ** 15:
print(10 ** 6 - 10 ** 3 + (10 ** 9 - 10 ** 6) * 2 + (10 ** 12 - 10 ** 9) * 3 + (N - 10 ** 12 + 1) * 4)
else:
print(10 ** 6 - 10 ** 3 + (10 ** 9 - 10 ** 6) * 2 + (10 ** 12 - 10 ** 9) * 3 + (10 ** 15 - 10 ** 12) * 4 + 5) |
valor = 12
def teste_git(testes):
result = testes ** 33
return result
print(teste_git(valor))
| valor = 12
def teste_git(testes):
result = testes ** 33
return result
print(teste_git(valor)) |
def show_first(word):
print(word[0])
show_first("abc")
| def show_first(word):
print(word[0])
show_first('abc') |
def count_positives_sum_negatives(arr):
if not arr:
return []
positive_array_count = 0
negative_array_count = 0
neither_array = 0
for i in arr:
if i > 0:
positive_array_count = positive_array_count + 1
elif i == 0:
neither_array = neither_array + i
else:
negative_array_count = negative_array_count + i
return [positive_array_count, negative_array_count] | def count_positives_sum_negatives(arr):
if not arr:
return []
positive_array_count = 0
negative_array_count = 0
neither_array = 0
for i in arr:
if i > 0:
positive_array_count = positive_array_count + 1
elif i == 0:
neither_array = neither_array + i
else:
negative_array_count = negative_array_count + i
return [positive_array_count, negative_array_count] |
input_shape = 56, 56, 3
num_class = 80
total_epoches = 50
batch_size = 64
train_num = 11650
val_num = 1254
iterations_per_epoch = train_num // batch_size + 1
test_iterations = val_num // batch_size + 1
weight_decay = 1e-3
label_smoothing = 0.1
'''
numeric characteristics
'''
mean = [154.64720717, 163.98750114, 175.11027269]
std = [88.22176357, 82.46385599, 78.50590683]
# eigval = [18793.85624672, 1592.25590705, 360.43236465]
eigval = [137.09068621, 39.90308142, 18.98505635]
eigvec = [[-0.61372719, -0.62390345, 0.48382169],
[-0.59095847, -0.0433538, -0.80553618],
[-0.52355231, 0.78029798, 0.34209362]]
| input_shape = (56, 56, 3)
num_class = 80
total_epoches = 50
batch_size = 64
train_num = 11650
val_num = 1254
iterations_per_epoch = train_num // batch_size + 1
test_iterations = val_num // batch_size + 1
weight_decay = 0.001
label_smoothing = 0.1
'\nnumeric characteristics\n'
mean = [154.64720717, 163.98750114, 175.11027269]
std = [88.22176357, 82.46385599, 78.50590683]
eigval = [137.09068621, 39.90308142, 18.98505635]
eigvec = [[-0.61372719, -0.62390345, 0.48382169], [-0.59095847, -0.0433538, -0.80553618], [-0.52355231, 0.78029798, 0.34209362]] |
def sort3(a, b, c):
i = []
i.append(a), i.append(b), i.append(c)
i = sorted(i)
return i
a, b, c = input(), input(), input()
print(*sort3(a, b, c))
| def sort3(a, b, c):
i = []
(i.append(a), i.append(b), i.append(c))
i = sorted(i)
return i
(a, b, c) = (input(), input(), input())
print(*sort3(a, b, c)) |
'''
occurrences_dict
loop values:
occurrences_dict[value] += 1
'''
# numbers_string = '-2.5 4 3 -2.5 -5.54 4 3 3 -2.5 3'
# numbers_string = '2 4 4 5 5 2 3 3 4 4 3 3 4 3 5 3 2 5 4 3'
numbers_string = input()
occurrence_counts = {}
# No such thing as tuple comprehension, this is generator
numbers = [float(x) for x in numbers_string.split(' ')]
for number in numbers:
# Not the best solution
# if number in occurrence_counts:
# occurrence_counts[number] += 1
# else:
# occurrence_counts[number] = 1
if number not in occurrence_counts:
occurrence_counts[number] = 0
occurrence_counts[number] += 1
for number, count in occurrence_counts.items():
print(f'{number:.1f} - {count} times')
| """
occurrences_dict
loop values:
occurrences_dict[value] += 1
"""
numbers_string = input()
occurrence_counts = {}
numbers = [float(x) for x in numbers_string.split(' ')]
for number in numbers:
if number not in occurrence_counts:
occurrence_counts[number] = 0
occurrence_counts[number] += 1
for (number, count) in occurrence_counts.items():
print(f'{number:.1f} - {count} times') |
count = 0
total = 0
while True:
Enter = input('Enter a number:\n')
try:
if Enter == "Done":
break
else:
inp = int(Enter)
total = total + inp
count = count + 1
average = total / count
except:
print('Invalid input')
print('Total:', total, 'Count:', count, 'Average:', average)
| count = 0
total = 0
while True:
enter = input('Enter a number:\n')
try:
if Enter == 'Done':
break
else:
inp = int(Enter)
total = total + inp
count = count + 1
average = total / count
except:
print('Invalid input')
print('Total:', total, 'Count:', count, 'Average:', average) |
#
# PySNMP MIB module BEGEMOT-IP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/BEGEMOT-IP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:37:03 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
ObjectIdentifier, Integer, OctetString = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "Integer", "OctetString")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsIntersection, ValueSizeConstraint, ValueRangeConstraint, SingleValueConstraint, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ValueSizeConstraint", "ValueRangeConstraint", "SingleValueConstraint", "ConstraintsUnion")
begemot, = mibBuilder.importSymbols("BEGEMOT-MIB", "begemot")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
iso, Gauge32, ModuleIdentity, Counter64, Integer32, Bits, MibScalar, MibTable, MibTableRow, MibTableColumn, IpAddress, MibIdentifier, ObjectIdentity, Unsigned32, Counter32, NotificationType, TimeTicks = mibBuilder.importSymbols("SNMPv2-SMI", "iso", "Gauge32", "ModuleIdentity", "Counter64", "Integer32", "Bits", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "IpAddress", "MibIdentifier", "ObjectIdentity", "Unsigned32", "Counter32", "NotificationType", "TimeTicks")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
begemotIp = ModuleIdentity((1, 3, 6, 1, 4, 1, 12325, 1, 3))
if mibBuilder.loadTexts: begemotIp.setLastUpdated('200602130000Z')
if mibBuilder.loadTexts: begemotIp.setOrganization('German Aerospace Center')
if mibBuilder.loadTexts: begemotIp.setContactInfo(' Hartmut Brandt Postal: German Aerospace Center Oberpfaffenhofen 82234 Wessling Germany Fax: +49 8153 28 2843 E-mail: harti@freebsd.org')
if mibBuilder.loadTexts: begemotIp.setDescription('The MIB for IP stuff that is not in the official IP MIBs.')
begemotIpObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 12325, 1, 3, 1))
mibBuilder.exportSymbols("BEGEMOT-IP-MIB", begemotIp=begemotIp, PYSNMP_MODULE_ID=begemotIp, begemotIpObjects=begemotIpObjects)
| (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, value_size_constraint, value_range_constraint, single_value_constraint, constraints_union) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsIntersection', 'ValueSizeConstraint', 'ValueRangeConstraint', 'SingleValueConstraint', 'ConstraintsUnion')
(begemot,) = mibBuilder.importSymbols('BEGEMOT-MIB', 'begemot')
(module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup')
(iso, gauge32, module_identity, counter64, integer32, bits, mib_scalar, mib_table, mib_table_row, mib_table_column, ip_address, mib_identifier, object_identity, unsigned32, counter32, notification_type, time_ticks) = mibBuilder.importSymbols('SNMPv2-SMI', 'iso', 'Gauge32', 'ModuleIdentity', 'Counter64', 'Integer32', 'Bits', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'IpAddress', 'MibIdentifier', 'ObjectIdentity', 'Unsigned32', 'Counter32', 'NotificationType', 'TimeTicks')
(display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention')
begemot_ip = module_identity((1, 3, 6, 1, 4, 1, 12325, 1, 3))
if mibBuilder.loadTexts:
begemotIp.setLastUpdated('200602130000Z')
if mibBuilder.loadTexts:
begemotIp.setOrganization('German Aerospace Center')
if mibBuilder.loadTexts:
begemotIp.setContactInfo(' Hartmut Brandt Postal: German Aerospace Center Oberpfaffenhofen 82234 Wessling Germany Fax: +49 8153 28 2843 E-mail: harti@freebsd.org')
if mibBuilder.loadTexts:
begemotIp.setDescription('The MIB for IP stuff that is not in the official IP MIBs.')
begemot_ip_objects = mib_identifier((1, 3, 6, 1, 4, 1, 12325, 1, 3, 1))
mibBuilder.exportSymbols('BEGEMOT-IP-MIB', begemotIp=begemotIp, PYSNMP_MODULE_ID=begemotIp, begemotIpObjects=begemotIpObjects) |
SECRET_KEY = 'fake-key-here'
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'rest_framework',
'rest_framework.authtoken',
'data_ingest',
]
MIDDLEWARE = [
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
]
ROOT_URLCONF = 'data_ingest.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'OPTIONS': {
'context_processors': [
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'test_data_ingest',
'USER': 'postgres',
'PASSWORD': 'test_data_password',
'HOST': 'localhost',
'PORT': '5432',
}
}
# Rest Framework
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework.authentication.TokenAuthentication',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions.IsAuthenticated', )
}
# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
| secret_key = 'fake-key-here'
installed_apps = ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'rest_framework.authtoken', 'data_ingest']
middleware = ['django.contrib.sessions.middleware.SessionMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware']
root_urlconf = 'data_ingest.urls'
templates = [{'BACKEND': 'django.template.backends.django.DjangoTemplates', 'OPTIONS': {'context_processors': ['django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages']}}]
databases = {'default': {'ENGINE': 'django.db.backends.postgresql', 'NAME': 'test_data_ingest', 'USER': 'postgres', 'PASSWORD': 'test_data_password', 'HOST': 'localhost', 'PORT': '5432'}}
rest_framework = {'DEFAULT_AUTHENTICATION_CLASSES': ('rest_framework.authentication.TokenAuthentication',), 'DEFAULT_PERMISSION_CLASSES': ('rest_framework.permissions.IsAuthenticated',)}
language_code = 'en-us'
time_zone = 'UTC'
use_i18_n = True
use_l10_n = True
use_tz = True |
# RUN: test-parser.sh %s
# RUN: test-output.sh %s
x = 1 # PARSER-LABEL:x = 1i
y = 2 # PARSER-NEXT:y = 2i
print("Start") # PARSER-NEXT:print("Start")
# OUTPUT-LABEL: Start
if x == 1: # PARSER-NEXT:if (x == 1i):
if y == 3: # PARSER-NEXT: if (y == 3i):
print("A") # PARSER-NEXT: print("A")
else: # PARSER-NEXT:else:
print("C") # PARSER-NEXT: print("C")
print("D") # PARSER-NEXT:print("D")
# OUTPUT-NEXT: D
if x == 1: # PARSER-NEXT:if (x == 1i):
if y == 3: # PARSER-NEXT: if (y == 3i):
print("A") # PARSER-NEXT: print("A")
else: # PARSER-NEXT: else:
print("B") # PARSER-NEXT: print("B")
else: # PARSER-NEXT:else:
print("C") # PARSER-NEXT: print("C")
print("D") # PARSER-NEXT:print("D")
# OUTPUT-NEXT: B
# OUTPUT-NEXT: D
if x == 1: # PARSER-NEXT:if (x == 1i):
if y == 3: # PARSER-NEXT: if (y == 3i):
print("A") # PARSER-NEXT: print("A")
else: # PARSER-NEXT: else:
print("B") # PARSER-NEXT: print("B")
print("D") # PARSER-NEXT:print("D")
# OUTPUT-NEXT: B
# OUTPUT-NEXT: D
if x == 1: # PARSER-NEXT:if (x == 1i):
if y == 3: # PARSER-NEXT: if (y == 3i):
print("A") # PARSER-NEXT: print("A")
else: # PARSER-NEXT: else:
print("X") # PARSER-NEXT: print("X")
if y == 2: # PARSER-NEXT: if (y == 2i):
print("B") # PARSER-NEXT: print("B")
else: # PARSER-NEXT: else:
print("E") # PARSER-NEXT: print("E")
else: # PARSER-NEXT:else:
print("C") # PARSER-NEXT: print("C")
print("D") # PARSER-NEXT:print("D")
# OUTPUT-NEXT: X
# OUTPUT-NEXT: B
# OUTPUT-NEXT: D
| x = 1
y = 2
print('Start')
if x == 1:
if y == 3:
print('A')
else:
print('C')
print('D')
if x == 1:
if y == 3:
print('A')
else:
print('B')
else:
print('C')
print('D')
if x == 1:
if y == 3:
print('A')
else:
print('B')
print('D')
if x == 1:
if y == 3:
print('A')
else:
print('X')
if y == 2:
print('B')
else:
print('E')
else:
print('C')
print('D') |
class CameraNotConnected(Exception):
pass
class WiredControlAlreadyEstablished(Exception):
pass
| class Cameranotconnected(Exception):
pass
class Wiredcontrolalreadyestablished(Exception):
pass |
# https://codeforces.com/problemset/problem/116/A
n = int(input())
stops = [list(map(int, input().split())) for _ in range(n)]
p, peak_p = 0, 0
for stop in stops:
p -= stop[0]
p += stop[1]
peak_p = max(p, peak_p)
print(peak_p) | n = int(input())
stops = [list(map(int, input().split())) for _ in range(n)]
(p, peak_p) = (0, 0)
for stop in stops:
p -= stop[0]
p += stop[1]
peak_p = max(p, peak_p)
print(peak_p) |
def int_to_char(word):
arr = list(word)
num_str = ""
while True:
if not arr[0].isdigit():
break
num_str += arr[0]
arr.pop(0)
num = int(num_str)
arr.insert(0, chr(num))
return "".join(arr)
def switch_letters(word):
list_chars = list(word)
list_chars[1], list_chars[-1] = list_chars[-1], list_chars[1]
return "".join(list_chars)
def decrypt_word(word):
word = int_to_char(word)
word = switch_letters(word)
return word
words = input().split()
words = [decrypt_word(word) for word in words]
print(" ".join(words))
| def int_to_char(word):
arr = list(word)
num_str = ''
while True:
if not arr[0].isdigit():
break
num_str += arr[0]
arr.pop(0)
num = int(num_str)
arr.insert(0, chr(num))
return ''.join(arr)
def switch_letters(word):
list_chars = list(word)
(list_chars[1], list_chars[-1]) = (list_chars[-1], list_chars[1])
return ''.join(list_chars)
def decrypt_word(word):
word = int_to_char(word)
word = switch_letters(word)
return word
words = input().split()
words = [decrypt_word(word) for word in words]
print(' '.join(words)) |
PROJECT_ID = 'dmp-y-tests'
DATASET_NAME = 'test_gpl'
BUCKET_NAME = 'bucket_gpl'
LOCAL_DIR_PATH = '/tmp/gpl_directory'
| project_id = 'dmp-y-tests'
dataset_name = 'test_gpl'
bucket_name = 'bucket_gpl'
local_dir_path = '/tmp/gpl_directory' |
def commonDiv(num, den, divs = None) :
if not divs : divs = divisors(den)
for i in divs[1:] :
if not num % i : return True
return False
def validNums(den, minNum, maxNum) :
divs = divisors(den)
return [i for i in range(minNum,maxNum+1) if not commonDiv(i, den, divs)]
def countBetween(lowNum, lowDen, highNum, highDen, maxDen) :
total = 0
for i in range(2,maxDen+1) :
minNum = i*lowNum/lowDen+1
maxNum = (i*highNum-1)/highDen
nums = validNums(i, minNum, maxNum)
total += len(nums)
#print "%d -> %d to %d (%s) %d" % (i, minNum, maxNum, ','.join([str(i) for i in nums]), total)
return total
countBetween(1, 3, 1, 2, 12000)
| def common_div(num, den, divs=None):
if not divs:
divs = divisors(den)
for i in divs[1:]:
if not num % i:
return True
return False
def valid_nums(den, minNum, maxNum):
divs = divisors(den)
return [i for i in range(minNum, maxNum + 1) if not common_div(i, den, divs)]
def count_between(lowNum, lowDen, highNum, highDen, maxDen):
total = 0
for i in range(2, maxDen + 1):
min_num = i * lowNum / lowDen + 1
max_num = (i * highNum - 1) / highDen
nums = valid_nums(i, minNum, maxNum)
total += len(nums)
return total
count_between(1, 3, 1, 2, 12000) |
# Exception Handling function
def exception_handling(number1, number2, operator):
# Only digit exception
try:
int(number1)
except:
return "Error: Numbers must only contain digits."
try:
int(number2)
except:
return "Error: Numbers must only contain digits."
# More than 4 digit no. exception
try:
if len(number1) > 4 or len(number2) > 4:
raise BaseException
except:
return "Error: Numbers cannot be more than four digits."
# Operator must be + | - exception.
try:
if operator != '+' and operator != '-':
raise BaseException
except:
return "Error: Operator must be '+' or '-'."
return ""
def arithmetic_arranger(problems, displayMode=False):
start = True
side_space = " "
line1 = line2 = line3 = line4 = ""
# Too many Problem exception
try:
if len(problems) > 5:
raise BaseException
except:
return "Error: Too many problems."
for prob in problems:
# Splitting the Problem into separate strings
separated_problem = prob.split()
# storing number 1
number1 = separated_problem[0]
# Storing the operator sign
operator = separated_problem[1]
# storing number 2
number2 = separated_problem[2]
exp = exception_handling(number1, number2, operator)
if exp != "":
return exp
no1 = int(number1)
no2 = int(number2)
# space contains the max no. os spaces required.
space = max(len(number1), len(number2))
# For first arithmetic arragement
if start == True:
line1 += number1.rjust(space + 2)
line2 += operator + ' ' + number2.rjust(space)
line3 += '-' * (space + 2)
if displayMode == True:
if operator == '+':
line4 += str(no1 + no2).rjust(space + 2)
else:
line4 += str(no1 - no2).rjust(space + 2)
start = False
# Other than first arithmetic arragement
else:
line1 += number1.rjust(space + 6)
line2 += operator.rjust(5) + ' ' + number2.rjust(space)
line3 += side_space + '-' * (space + 2)
if displayMode == True:
if operator == '+':
line4 += side_space + str(no1 + no2).rjust(space + 2)
else:
line4 += side_space + str(no1 - no2).rjust(space + 2)
# displayMode is Ture then append line4
if displayMode == True:
return line1 + '\n' + line2 + '\n' + line3 + '\n' + line4
return line1 + '\n' + line2 + '\n' + line3
| def exception_handling(number1, number2, operator):
try:
int(number1)
except:
return 'Error: Numbers must only contain digits.'
try:
int(number2)
except:
return 'Error: Numbers must only contain digits.'
try:
if len(number1) > 4 or len(number2) > 4:
raise BaseException
except:
return 'Error: Numbers cannot be more than four digits.'
try:
if operator != '+' and operator != '-':
raise BaseException
except:
return "Error: Operator must be '+' or '-'."
return ''
def arithmetic_arranger(problems, displayMode=False):
start = True
side_space = ' '
line1 = line2 = line3 = line4 = ''
try:
if len(problems) > 5:
raise BaseException
except:
return 'Error: Too many problems.'
for prob in problems:
separated_problem = prob.split()
number1 = separated_problem[0]
operator = separated_problem[1]
number2 = separated_problem[2]
exp = exception_handling(number1, number2, operator)
if exp != '':
return exp
no1 = int(number1)
no2 = int(number2)
space = max(len(number1), len(number2))
if start == True:
line1 += number1.rjust(space + 2)
line2 += operator + ' ' + number2.rjust(space)
line3 += '-' * (space + 2)
if displayMode == True:
if operator == '+':
line4 += str(no1 + no2).rjust(space + 2)
else:
line4 += str(no1 - no2).rjust(space + 2)
start = False
else:
line1 += number1.rjust(space + 6)
line2 += operator.rjust(5) + ' ' + number2.rjust(space)
line3 += side_space + '-' * (space + 2)
if displayMode == True:
if operator == '+':
line4 += side_space + str(no1 + no2).rjust(space + 2)
else:
line4 += side_space + str(no1 - no2).rjust(space + 2)
if displayMode == True:
return line1 + '\n' + line2 + '\n' + line3 + '\n' + line4
return line1 + '\n' + line2 + '\n' + line3 |
TWITTER_TAGS = [
"agdq2021",
"gamesdonequick.com",
"agdq",
"sgdq",
"gamesdonequick",
"awesome games done quick",
"games done quick",
"summer games done quick",
"gdq",
]
TWITCH_CHANNEL = "gamesdonequick"
TWITCH_HOST = "irc.twitch.tv"
TWITCH_PORT = 6667
# Update this value to change the current event:
EVENT_SHORTHAND = "AGDQ2021"
# The following should stay pretty stable between events
DONATION_URL = (
"https://gamesdonequick.com/tracker/event/{}".format(EVENT_SHORTHAND)
)
SCHEDULE_URL = "https://gamesdonequick.com/schedule"
DONATION_INDEX_URL = (
"https://gamesdonequick.com/tracker/donations/{}".format(EVENT_SHORTHAND)
)
DONATION_DETAIL_URL = "https://gamesdonequick.com/tracker/donation"
DONOR_URL = "https://gamesdonequick.com/tracker/donor"
| twitter_tags = ['agdq2021', 'gamesdonequick.com', 'agdq', 'sgdq', 'gamesdonequick', 'awesome games done quick', 'games done quick', 'summer games done quick', 'gdq']
twitch_channel = 'gamesdonequick'
twitch_host = 'irc.twitch.tv'
twitch_port = 6667
event_shorthand = 'AGDQ2021'
donation_url = 'https://gamesdonequick.com/tracker/event/{}'.format(EVENT_SHORTHAND)
schedule_url = 'https://gamesdonequick.com/schedule'
donation_index_url = 'https://gamesdonequick.com/tracker/donations/{}'.format(EVENT_SHORTHAND)
donation_detail_url = 'https://gamesdonequick.com/tracker/donation'
donor_url = 'https://gamesdonequick.com/tracker/donor' |
'''
Problem : Find out duplicate number between 1 to N numbers.
- Find array sum
- Subtract sum of First (n-1) natural numbers from it to find the result.
Author : Alok Tripathi
'''
# Method to find duplicate in array
def findDuplicate(arr, n):
return sum(arr) - (((n - 1) * n) // 2) #it will return int not float
# Driver method
if __name__ == "__main__":
arr = [1, 2, 3, 3, 4]
n = len(arr)
print(findDuplicate(arr, n))
| """
Problem : Find out duplicate number between 1 to N numbers.
- Find array sum
- Subtract sum of First (n-1) natural numbers from it to find the result.
Author : Alok Tripathi
"""
def find_duplicate(arr, n):
return sum(arr) - (n - 1) * n // 2
if __name__ == '__main__':
arr = [1, 2, 3, 3, 4]
n = len(arr)
print(find_duplicate(arr, n)) |
def get_score(player_deck):
score_sum=0
for i in player_deck:
try:
score_sum+=int(i[1])
except:
if i[1] in ['K', 'Q', 'J']:
score_sum+=10
if i[1]=='Ace':
if (score_sum+11)<=21:
score_sum+=11
else:
score_sum+=1
return score_sum | def get_score(player_deck):
score_sum = 0
for i in player_deck:
try:
score_sum += int(i[1])
except:
if i[1] in ['K', 'Q', 'J']:
score_sum += 10
if i[1] == 'Ace':
if score_sum + 11 <= 21:
score_sum += 11
else:
score_sum += 1
return score_sum |
# coding: utf-8
n = int(input())
a = [int(i) for i in input().split()]
for i in range(n):
if i < n-1 and a[i+1]<a[i]:
break
if i==n-1:
ans = 0
else:
ans = n-1-i
a = a[i+1:]+a[:i+1]
for i in range(n-1):
if a[i] > a[i+1]:
print(-1)
break
else:
print(ans)
| n = int(input())
a = [int(i) for i in input().split()]
for i in range(n):
if i < n - 1 and a[i + 1] < a[i]:
break
if i == n - 1:
ans = 0
else:
ans = n - 1 - i
a = a[i + 1:] + a[:i + 1]
for i in range(n - 1):
if a[i] > a[i + 1]:
print(-1)
break
else:
print(ans) |
# Scrapy settings for dirbot project
SPIDER_MODULES = ['dirbot.spiders']
NEWSPIDER_MODULE = 'dirbot.spiders'
DEFAULT_ITEM_CLASS = 'dirbot.items.Website'
ITEM_PIPELINES = {
'dirbot.pipelines.RequiredFieldsPipeline': 1,
'dirbot.pipelines.FilterWordsPipeline': 2,
'dirbot.pipelines.DbPipeline': 3,
}
# Database settings
DB_API_NAME = 'MySQLdb'
DB_ARGS = {
'host': 'localhost',
'db': 'dirbot',
'user': 'root',
'passwd': '123',
'charset': 'utf8',
'use_unicode': True,
}
| spider_modules = ['dirbot.spiders']
newspider_module = 'dirbot.spiders'
default_item_class = 'dirbot.items.Website'
item_pipelines = {'dirbot.pipelines.RequiredFieldsPipeline': 1, 'dirbot.pipelines.FilterWordsPipeline': 2, 'dirbot.pipelines.DbPipeline': 3}
db_api_name = 'MySQLdb'
db_args = {'host': 'localhost', 'db': 'dirbot', 'user': 'root', 'passwd': '123', 'charset': 'utf8', 'use_unicode': True} |
class Solution:
def getHeight(self, root):
if root is None:
return 0
lh = self.getHeight(root.left) + 1
rh = self.getHeight(root.right) + 1
return max(lh, rh)
def isBalanced(self, root):
if root is None:
return True
leftHeight = self.getHeight(root.left)
rightHeight = self.getHeight(root.right)
return abs(leftHeight - rightHeight) <= 1 and self.isBalanced(root.left) and self.isBalanced(root.right)
'''
Given a sorted array with unique ints, write algo to
create binary search tree with min height
[1,2,3,4,5,6,7], len 7, middle 3
4
2 6
1 3 5 7
[1,2], len 1, middle 0
1
2
[1,2,3], len 2, middle 1
1
2 3
[1,2,3,4], len 3, middle 1
1
2 3
4
'''
# print(arrToBst([]))
# print(arrToBst([1]))
# print(arrToBst([1, 2]))
# print(arrToBst([1, 2, 3]))
# print(arrToBst([1, 2, 3, 4]))
# print(arrToBst([1, 2, 3, 4, 5]))
print("******* In order 1 *******")
# postOrder(root, [])
# preOrder(root, [])
# inOrder(root, [])
| class Solution:
def get_height(self, root):
if root is None:
return 0
lh = self.getHeight(root.left) + 1
rh = self.getHeight(root.right) + 1
return max(lh, rh)
def is_balanced(self, root):
if root is None:
return True
left_height = self.getHeight(root.left)
right_height = self.getHeight(root.right)
return abs(leftHeight - rightHeight) <= 1 and self.isBalanced(root.left) and self.isBalanced(root.right)
'\nGiven a sorted array with unique ints, write algo to\ncreate binary search tree with min height\n\n[1,2,3,4,5,6,7], len 7, middle 3\n 4\n 2 6\n 1 3 5 7\n\n[1,2], len 1, middle 0\n 1\n 2\n\n[1,2,3], len 2, middle 1\n 1\n 2 3\n\n[1,2,3,4], len 3, middle 1\n 1\n 2 3\n 4\n'
print('******* In order 1 *******') |
def get_products_of_all_ints_except_at_index(int_list):
if len(int_list) < 2:
raise IndexError('Getting the product of numbers at other '
'indices requires at least 2 numbers')
# We make a list with the length of the input list to
# hold our products
products_of_all_ints_except_at_index = [None] * len(int_list)
# For each integer, we find the product of all the integers
# before it, storing the total product so far each time
product_so_far = 1
for i in range(len(int_list)):
products_of_all_ints_except_at_index[i] = product_so_far
product_so_far *= int_list[i]
# For each integer, we find the product of all the integers
# after it. since each index in products already has the
# product of all the integers before it, now we're storing
# the total product of all other integers
product_so_far = 1
for i in range(len(int_list) - 1, -1, -1):
products_of_all_ints_except_at_index[i] *= product_so_far
product_so_far *= int_list[i]
return products_of_all_ints_except_at_index
| def get_products_of_all_ints_except_at_index(int_list):
if len(int_list) < 2:
raise index_error('Getting the product of numbers at other indices requires at least 2 numbers')
products_of_all_ints_except_at_index = [None] * len(int_list)
product_so_far = 1
for i in range(len(int_list)):
products_of_all_ints_except_at_index[i] = product_so_far
product_so_far *= int_list[i]
product_so_far = 1
for i in range(len(int_list) - 1, -1, -1):
products_of_all_ints_except_at_index[i] *= product_so_far
product_so_far *= int_list[i]
return products_of_all_ints_except_at_index |
count = 0 # A global count variable
def remember():
global count
count += 1 # Count this invocation
print(str(count))
remember()
remember()
remember()
remember()
remember()
| count = 0
def remember():
global count
count += 1
print(str(count))
remember()
remember()
remember()
remember()
remember() |
def find_rc(rc):
rc = rc[:: -1]
replacements = {"A": "T",
"T": "A",
"G": "C",
"C": "G"}
rc = "".join([replacements.get(c, c) for c in rc])
return rc
print(find_rc('ATTA'))
| def find_rc(rc):
rc = rc[::-1]
replacements = {'A': 'T', 'T': 'A', 'G': 'C', 'C': 'G'}
rc = ''.join([replacements.get(c, c) for c in rc])
return rc
print(find_rc('ATTA')) |
first_name = input("Please enter your first name: ")
print(f"Your first name is: {first_name}")
print("a regular string: " + first_name)
print('a regular string' + first_name)
# string literal with the r prefix
print(r'a regular string')
| first_name = input('Please enter your first name: ')
print(f'Your first name is: {first_name}')
print('a regular string: ' + first_name)
print('a regular string' + first_name)
print('a regular string') |
# A variable lets you save some information to use later
# You can save numbers!
my_var = 1
print(my_var)
# Or strings!
my_var = "MARIO"
print(my_var)
# Or anything else you need! | my_var = 1
print(my_var)
my_var = 'MARIO'
print(my_var) |
def code_to_color(code):
assert len(code) in (4, 5, 7, 9), f'Bad format color code: {code}'
if len(code) == 4 or len(code) == 5: # "#RGB" or "#RGBA"
return tuple(map(lambda x: int(x, 16) * 17, code[1:]))
elif len(code) == 7 or len(code) == 9: # "#RRGGBB" or "#RRGGBBAA"
return tuple(map(lambda x, y: int(x + y, 16), code[::1], code[1::1]))
def color_to_code(color):
code = '#'
for c in color:
code += str(hex(c))
return code
colormap = {
'k': (0, 0, 0),
'black': (0, 0, 0),
'r': (255, 0, 0),
'red': (255, 0, 0),
'g': (0, 255, 0),
'green': (0, 255, 0),
'b': (0, 0, 255),
'blue': (0, 0, 255),
'w': (255, 255, 255),
'white': (255, 255, 255),
}
def lookup_colormap(color):
return colormap[color]
class Color:
def __init__(self, rgb):
assert isinstance(rgb, (str, list, tuple))
if isinstance(rgb, str):
if rgb[0] == '#':
self.rgb = code_to_color(rgb)
else:
self.rgb = lookup_colormap(rgb)
elif isinstance(rgb, (list, tuple)):
self.rgb = tuple(rgb)
@property
def code(self):
return color_to_code(self.rgb)
@property
def gray(self):
return int(
0.2126 * self.rgb[0] +
0.7152 * self.rgb[1] +
0.0722 * self.rgb[2])
| def code_to_color(code):
assert len(code) in (4, 5, 7, 9), f'Bad format color code: {code}'
if len(code) == 4 or len(code) == 5:
return tuple(map(lambda x: int(x, 16) * 17, code[1:]))
elif len(code) == 7 or len(code) == 9:
return tuple(map(lambda x, y: int(x + y, 16), code[::1], code[1::1]))
def color_to_code(color):
code = '#'
for c in color:
code += str(hex(c))
return code
colormap = {'k': (0, 0, 0), 'black': (0, 0, 0), 'r': (255, 0, 0), 'red': (255, 0, 0), 'g': (0, 255, 0), 'green': (0, 255, 0), 'b': (0, 0, 255), 'blue': (0, 0, 255), 'w': (255, 255, 255), 'white': (255, 255, 255)}
def lookup_colormap(color):
return colormap[color]
class Color:
def __init__(self, rgb):
assert isinstance(rgb, (str, list, tuple))
if isinstance(rgb, str):
if rgb[0] == '#':
self.rgb = code_to_color(rgb)
else:
self.rgb = lookup_colormap(rgb)
elif isinstance(rgb, (list, tuple)):
self.rgb = tuple(rgb)
@property
def code(self):
return color_to_code(self.rgb)
@property
def gray(self):
return int(0.2126 * self.rgb[0] + 0.7152 * self.rgb[1] + 0.0722 * self.rgb[2]) |
class Payload:
@staticmethod
def login_payload(username, password):
return {'UserName': username, 'Password': password, 'ValidateUser': '1', 'dbKeyAuth': 'JusticePA',
'SignOn': 'Sign+On'}
@staticmethod
def payload(param_parser, last_name, first_name, middle_name, birth_date):
payload = {
'__EVENTTARGET': '',
'__EVENTARGUMENT': '',
'__VIEWSTATE': param_parser.view_state,
'__VIEWSTATEGENERATOR': param_parser.view_state_generator,
'__EVENTVALIDATION': param_parser.event_validation,
'NodeID': param_parser.node_id,
'NodeDesc': 'All+Locations',
'SearchBy': '1',
'ExactName': 'on',
'CaseSearchMode': 'CaseNumber',
'CaseSearchValue': '',
'CitationSearchValue': '',
'CourtCaseSearchValue': '',
'PartySearchMode': 'Name',
'AttorneySearchMode': 'Name',
'LastName': last_name,
'FirstName': first_name,
'cboState': 'AA',
'MiddleName': middle_name,
'DateOfBirth': birth_date,
'DriverLicNum': '',
'CaseStatusType': '0',
'DateFiledOnAfter': '',
'DateFiledOnBefore': '',
'chkCriminal': 'on',
'chkFamily': 'on',
'chkCivil': 'on',
'chkProbate': 'on',
'chkDtRangeCriminal': 'on',
'chkDtRangeFamily': 'on',
'chkDtRangeCivil': 'on',
'chkDtRangeProbate': 'on',
'chkCriminalMagist': 'on',
'chkFamilyMagist': 'on',
'chkCivilMagist': 'on',
'chkProbateMagist': 'on',
'DateSettingOnAfter': '',
'DateSettingOnBefore': '',
'SortBy': 'fileddate',
'SearchSubmit': 'Search',
'SearchType': 'PARTY',
'SearchMode': 'NAME',
'NameTypeKy': 'ALIAS',
'BaseConnKy': 'DF',
'StatusType': 'true',
'ShowInactive': '',
'AllStatusTypes': 'true',
'CaseCategories': '',
'RequireFirstName': 'True',
'CaseTypeIDs': '',
'HearingTypeIDs': '',
'SearchParams': "SearchBy~~Search+By:~~Defendant~~Defendant||chkExactName~~Exact+Name:~~on~~on||PartyNameOption~~Party+Search+Mode:~~Name~~Name||LastName~~Last+Name:~~" + last_name + "~~" + last_name + "||FirstName~~First+Name:~~" + first_name + "~~" + first_name + "||MiddleName~~Middle+Name:~~" + middle_name + "~~" + middle_name+ "||DateOfBirth~~Date+of+Birth:~~" + birth_date + "~~" + birth_date + "||AllOption~~All~~0~~All||selectSortBy~~Sort+By:~~Filed+Date~~Filed+Date"
}
return payload
class URL:
@staticmethod
def login_url():
return 'https://publicaccess.courts.oregon.gov/PublicAccessLogin/login.aspx'
| class Payload:
@staticmethod
def login_payload(username, password):
return {'UserName': username, 'Password': password, 'ValidateUser': '1', 'dbKeyAuth': 'JusticePA', 'SignOn': 'Sign+On'}
@staticmethod
def payload(param_parser, last_name, first_name, middle_name, birth_date):
payload = {'__EVENTTARGET': '', '__EVENTARGUMENT': '', '__VIEWSTATE': param_parser.view_state, '__VIEWSTATEGENERATOR': param_parser.view_state_generator, '__EVENTVALIDATION': param_parser.event_validation, 'NodeID': param_parser.node_id, 'NodeDesc': 'All+Locations', 'SearchBy': '1', 'ExactName': 'on', 'CaseSearchMode': 'CaseNumber', 'CaseSearchValue': '', 'CitationSearchValue': '', 'CourtCaseSearchValue': '', 'PartySearchMode': 'Name', 'AttorneySearchMode': 'Name', 'LastName': last_name, 'FirstName': first_name, 'cboState': 'AA', 'MiddleName': middle_name, 'DateOfBirth': birth_date, 'DriverLicNum': '', 'CaseStatusType': '0', 'DateFiledOnAfter': '', 'DateFiledOnBefore': '', 'chkCriminal': 'on', 'chkFamily': 'on', 'chkCivil': 'on', 'chkProbate': 'on', 'chkDtRangeCriminal': 'on', 'chkDtRangeFamily': 'on', 'chkDtRangeCivil': 'on', 'chkDtRangeProbate': 'on', 'chkCriminalMagist': 'on', 'chkFamilyMagist': 'on', 'chkCivilMagist': 'on', 'chkProbateMagist': 'on', 'DateSettingOnAfter': '', 'DateSettingOnBefore': '', 'SortBy': 'fileddate', 'SearchSubmit': 'Search', 'SearchType': 'PARTY', 'SearchMode': 'NAME', 'NameTypeKy': 'ALIAS', 'BaseConnKy': 'DF', 'StatusType': 'true', 'ShowInactive': '', 'AllStatusTypes': 'true', 'CaseCategories': '', 'RequireFirstName': 'True', 'CaseTypeIDs': '', 'HearingTypeIDs': '', 'SearchParams': 'SearchBy~~Search+By:~~Defendant~~Defendant||chkExactName~~Exact+Name:~~on~~on||PartyNameOption~~Party+Search+Mode:~~Name~~Name||LastName~~Last+Name:~~' + last_name + '~~' + last_name + '||FirstName~~First+Name:~~' + first_name + '~~' + first_name + '||MiddleName~~Middle+Name:~~' + middle_name + '~~' + middle_name + '||DateOfBirth~~Date+of+Birth:~~' + birth_date + '~~' + birth_date + '||AllOption~~All~~0~~All||selectSortBy~~Sort+By:~~Filed+Date~~Filed+Date'}
return payload
class Url:
@staticmethod
def login_url():
return 'https://publicaccess.courts.oregon.gov/PublicAccessLogin/login.aspx' |
class Solution:
def addBinary(self, a: str, b: str) -> str:
max_len = max(len(a), len(b))
a = a.zfill(max_len)
b = b.zfill(max_len)
result = ''
# initialize the carry
carry = 0
# Traverse the string
for i in range(max_len - 1, -1, -1):
r = carry
r += 1 if a[i] == '1' else 0
r += 1 if b[i] == '1' else 0
result = ('1' if r % 2 == 1 else '0') + result
carry = 0 if r < 2 else 1 # Compute the carry.
if carry !=0 : result = '1' + result
return result.zfill(max_len) | class Solution:
def add_binary(self, a: str, b: str) -> str:
max_len = max(len(a), len(b))
a = a.zfill(max_len)
b = b.zfill(max_len)
result = ''
carry = 0
for i in range(max_len - 1, -1, -1):
r = carry
r += 1 if a[i] == '1' else 0
r += 1 if b[i] == '1' else 0
result = ('1' if r % 2 == 1 else '0') + result
carry = 0 if r < 2 else 1
if carry != 0:
result = '1' + result
return result.zfill(max_len) |
'''
Locating suspicious data
You will now inspect the suspect record by locating the offending row.
You will see that, according to the data, Joyce Chepchumba was a man that won a medal in a women's event. That is a data error as you can confirm with a web search.
INSTRUCTIONS
70XP
Create a Boolean Series with a condition that captures the only row that has medals.Event_gender == 'W' and medals.Gender == 'Men'. Be sure to use the & operator.
Use the Boolean Series to create a DataFrame called suspect with the suspicious row.
Print suspect. This has been done for you, so hit 'Submit Answer' to see the result.
'''
# Create the Boolean Series: sus
sus = (medals.Event_gender == 'W') & (medals.Gender == 'Men')
# Create a DataFrame with the suspicious row: suspect
suspect = medals[(medals.Event_gender == 'W') & (medals.Gender == 'Men')]
# Print suspect
print(suspect)
| """
Locating suspicious data
You will now inspect the suspect record by locating the offending row.
You will see that, according to the data, Joyce Chepchumba was a man that won a medal in a women's event. That is a data error as you can confirm with a web search.
INSTRUCTIONS
70XP
Create a Boolean Series with a condition that captures the only row that has medals.Event_gender == 'W' and medals.Gender == 'Men'. Be sure to use the & operator.
Use the Boolean Series to create a DataFrame called suspect with the suspicious row.
Print suspect. This has been done for you, so hit 'Submit Answer' to see the result.
"""
sus = (medals.Event_gender == 'W') & (medals.Gender == 'Men')
suspect = medals[(medals.Event_gender == 'W') & (medals.Gender == 'Men')]
print(suspect) |
class InvalidSymbolException(Exception):
pass
class InvalidMoveException(Exception):
pass
class InvalidCoordinateInputException(Exception):
pass
| class Invalidsymbolexception(Exception):
pass
class Invalidmoveexception(Exception):
pass
class Invalidcoordinateinputexception(Exception):
pass |
def odd_nums(number: int) -> int:
for num in range(1, number + 1, 2):
yield num
pass
n = 15
generator = odd_nums(n)
for _ in range(1, n + 1, 2):
print(next(generator))
next(generator)
| def odd_nums(number: int) -> int:
for num in range(1, number + 1, 2):
yield num
pass
n = 15
generator = odd_nums(n)
for _ in range(1, n + 1, 2):
print(next(generator))
next(generator) |
def find_nemo(array):
for item in array:
if item == 'nemo':
print('found NEMO')
nemo = ['nemo']
find_nemo(nemo) | def find_nemo(array):
for item in array:
if item == 'nemo':
print('found NEMO')
nemo = ['nemo']
find_nemo(nemo) |
def loss_function(X_values, X_media, X_org):
# X_media = {
# "labels": ["facebook", "tiktok"],
# "coefs": [6.454, 1.545],
# "drs": [0.6, 0.7]
# }
# X_org = {
# "labels": ["const"],
# "coefs": [-27.5],
# "values": [1]
# }
y = 0
for i in range(len(X_values)):
transform = X_values[i] ** X_media["drs"][i]
contrib = X_media["coefs"][i] * transform
y += contrib
for i in range(len(X_org)):
contrib = X_org["coefs"][i] * X_org["values"][i]
y += contrib
return -y | def loss_function(X_values, X_media, X_org):
y = 0
for i in range(len(X_values)):
transform = X_values[i] ** X_media['drs'][i]
contrib = X_media['coefs'][i] * transform
y += contrib
for i in range(len(X_org)):
contrib = X_org['coefs'][i] * X_org['values'][i]
y += contrib
return -y |
def getcommonletters(strlist):
return ''.join([x[0] for x in zip(*strlist) \
if reduce(lambda a,b:(a == b) and a or None,x)])
def findcommonstart(strlist):
strlist = strlist[:]
prev = None
while True:
common = getcommonletters(strlist)
if common == prev:
break
strlist.append(common)
prev = common
return getcommonletters(strlist)
| def getcommonletters(strlist):
return ''.join([x[0] for x in zip(*strlist) if reduce(lambda a, b: a == b and a or None, x)])
def findcommonstart(strlist):
strlist = strlist[:]
prev = None
while True:
common = getcommonletters(strlist)
if common == prev:
break
strlist.append(common)
prev = common
return getcommonletters(strlist) |
# DO NOT comment out
# (REQ) REQUIRED
# *****************************************************************************
# DATA DISCOVERY ENGINE - MAIN (REQ)
# *****************************************************************************
# name also used on metadata
SITE_NAME = "NIAID Data Portal"
SITE_DESC = 'An aggregator of open datasets, with a particular focus on allergy and infectious diseases'
API_URL = "https://crawler.biothings.io/api/"
SITE_URL = "https://discovery.biothings.io/niaid/"
# SITE_URL = "http://localhost:8000/"
CONTACT_REPO = "https://github.com/SuLab/niaid-data-portal"
CONTACT_EMAIL = "cd2h-metadata@googlegroups.com"
# *****************************************************************************
# DATA DISCOVERY ENGINE - METADATA (REQ)
# *****************************************************************************
METADATA_CONTENT_URL = "http://discovery.biothings.io/"
METADATA_DESC = 'An aggregator of open datasets, with a particular focus on allergy and infectious diseases'
METADATA_FEATURED_IMAGE = "https://i.postimg.cc/vZYnpSML/featured.jpg"
METADATA_MAIN_COLOR = "#1C5D5D"
# *****************************************************************************
# DATA DISCOVERY ENGINE - COLORS (REQ)
# *****************************************************************************
MAIN_COLOR = "#113B56"
SEC_COLOR = "#0F627C"
# *****************************************************************************
# DATA DISCOVERY ENGINE - IMAGES (REQ)
# *****************************************************************************
# create a folder with <name> and put all icons there
STATIC_IMAGE_FOLDER = 'niaid'
# *****************************************************************************
# REPOSITORY NAMES
# *****************************************************************************
# List of all possible repositories.
# NOTE: Everything should be automated; if you want to change the sort order in the heatmap in /schema, though, you need to alter schema.vue:repoOrder
REPOSITORIES = [{
"name": "Omics DI",
"id": "omicsdi",
"synonyms": ["omicsdi", "indexed_omicsdi"],
"img_src": "static/img/repositories/omicsdi.png",
"url": "https://www.omicsdi.org/",
"description": ""
},
{
"name": "NCBI GEO",
"id": "ncbi_geo",
"synonyms": ["indexed_ncbi_geo", "ncbi_geo", "ncbi geo"],
"img_src": "static/img/repositories/geo.gif",
"url": "https://www.ncbi.nlm.nih.gov/geo/",
"description": ""
},
{
"name": "Zenodo",
"id": "zenodo",
"synonyms": ["indexed_zenodo", "zenodo"],
"img_src": "static/img/repositories/zenodo.svg",
"url": "https://zenodo.org/",
"description": ""
},
{
"name": "Harvard Dataverse",
"id": "harvard_dataverse",
"synonyms": ["indexed_harvard_dataverse", "harvard_dataverse", "harvard dataverse"],
"img_src": "static/img/repositories/dataverse_small.png",
"url": "https://dataverse.harvard.edu/",
"description": ""
},
{
"name": "NYU Data Catalog",
"id": "nyu",
"synonyms": ["indexed_nyu", "nyu"],
"img_src": "static/img/repositories/nyu.png",
"url": "https://datacatalog.med.nyu.edu/",
"description": ""
},
{
"name": "ImmPort",
"id": "immport",
"synonyms": ["indexed_immport", "immport"],
"img_src": "static/img/repositories/immport.png",
"url": "https://www.immport.org/home",
"description": ""
},
{
"name": "Data Discovery Engine",
"id": "discovery",
"synonyms": ["indexed_discovery", "discovery"],
"img_src": "static/img/repositories/dde.png",
"url": "https://discovery.biothings.io/dataset",
"description": ""
}
]
| site_name = 'NIAID Data Portal'
site_desc = 'An aggregator of open datasets, with a particular focus on allergy and infectious diseases'
api_url = 'https://crawler.biothings.io/api/'
site_url = 'https://discovery.biothings.io/niaid/'
contact_repo = 'https://github.com/SuLab/niaid-data-portal'
contact_email = 'cd2h-metadata@googlegroups.com'
metadata_content_url = 'http://discovery.biothings.io/'
metadata_desc = 'An aggregator of open datasets, with a particular focus on allergy and infectious diseases'
metadata_featured_image = 'https://i.postimg.cc/vZYnpSML/featured.jpg'
metadata_main_color = '#1C5D5D'
main_color = '#113B56'
sec_color = '#0F627C'
static_image_folder = 'niaid'
repositories = [{'name': 'Omics DI', 'id': 'omicsdi', 'synonyms': ['omicsdi', 'indexed_omicsdi'], 'img_src': 'static/img/repositories/omicsdi.png', 'url': 'https://www.omicsdi.org/', 'description': ''}, {'name': 'NCBI GEO', 'id': 'ncbi_geo', 'synonyms': ['indexed_ncbi_geo', 'ncbi_geo', 'ncbi geo'], 'img_src': 'static/img/repositories/geo.gif', 'url': 'https://www.ncbi.nlm.nih.gov/geo/', 'description': ''}, {'name': 'Zenodo', 'id': 'zenodo', 'synonyms': ['indexed_zenodo', 'zenodo'], 'img_src': 'static/img/repositories/zenodo.svg', 'url': 'https://zenodo.org/', 'description': ''}, {'name': 'Harvard Dataverse', 'id': 'harvard_dataverse', 'synonyms': ['indexed_harvard_dataverse', 'harvard_dataverse', 'harvard dataverse'], 'img_src': 'static/img/repositories/dataverse_small.png', 'url': 'https://dataverse.harvard.edu/', 'description': ''}, {'name': 'NYU Data Catalog', 'id': 'nyu', 'synonyms': ['indexed_nyu', 'nyu'], 'img_src': 'static/img/repositories/nyu.png', 'url': 'https://datacatalog.med.nyu.edu/', 'description': ''}, {'name': 'ImmPort', 'id': 'immport', 'synonyms': ['indexed_immport', 'immport'], 'img_src': 'static/img/repositories/immport.png', 'url': 'https://www.immport.org/home', 'description': ''}, {'name': 'Data Discovery Engine', 'id': 'discovery', 'synonyms': ['indexed_discovery', 'discovery'], 'img_src': 'static/img/repositories/dde.png', 'url': 'https://discovery.biothings.io/dataset', 'description': ''}] |
# pylint: skip-file
POKEAPI_POKEMON_LIST_EXAMPLE = {
"count": 949,
"previous": None,
"results": [
{
"url": "https://pokeapi.co/api/v2/pokemon/21/",
"name": "spearow"
},
{
"url": "https://pokeapi.co/api/v2/pokemon/22/",
"name": "fearow"
}
]
}
POKEAPI_POKEMON_DATA_EXAMPLE_FIRST = {
"forms": [
{
"url": "https://pokeapi.co/api/v2/pokemon-form/21/",
"name": "spearow"
}
],
"stats": [
{
"stat": {
"url": "https://pokeapi.co/api/v2/stat/6/",
"name": "speed"
},
"effort": 1,
"base_stat": 70
},
{
"stat": {
"url": "https://pokeapi.co/api/v2/stat/5/",
"name": "special-defense"
},
"effort": 0,
"base_stat": 31
},
{
"stat": {
"url": "https://pokeapi.co/api/v2/stat/4/",
"name": "special-attack"
},
"effort": 0,
"base_stat": 31
},
{
"stat": {
"url": "https://pokeapi.co/api/v2/stat/3/",
"name": "defense"
},
"effort": 0,
"base_stat": 30
},
{
"stat": {
"url": "https://pokeapi.co/api/v2/stat/2/",
"name": "attack"
},
"effort": 0,
"base_stat": 60
},
{
"stat": {
"url": "https://pokeapi.co/api/v2/stat/1/",
"name": "hp"
},
"effort": 0,
"base_stat": 40
}
],
"name": "spearow",
"weight": 20,
"sprites": {
"back_female": None,
"back_shiny_female": None,
"back_default": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/back/21.png",
"front_female": None,
"front_shiny_female": None,
"back_shiny": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/back/shiny/21.png",
"front_default": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/21.png",
"front_shiny": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/shiny/21.png"
},
"id": 21,
"order": 30,
"base_experience": 52
}
POKEAPI_POKEMON_DATA_EXAMPLE_SECOND = {
"forms": [
{
"url": "https://pokeapi.co/api/v2/pokemon-form/22/",
"name": "fearow"
}
],
"stats": [
{
"stat": {
"url": "https://pokeapi.co/api/v2/stat/6/",
"name": "speed"
},
"effort": 2,
"base_stat": 100
},
{
"stat": {
"url": "https://pokeapi.co/api/v2/stat/5/",
"name": "special-defense"
},
"effort": 0,
"base_stat": 31
},
{
"stat": {
"url": "https://pokeapi.co/api/v2/stat/4/",
"name": "special-attack"
},
"effort": 0,
"base_stat": 31
},
{
"stat": {
"url": "https://pokeapi.co/api/v2/stat/3/",
"name": "defense"
},
"effort": 0,
"base_stat": 65
},
{
"stat": {
"url": "https://pokeapi.co/api/v2/stat/2/",
"name": "attack"
},
"effort": 0,
"base_stat": 90
},
{
"stat": {
"url": "https://pokeapi.co/api/v2/stat/1/",
"name": "hp"
},
"effort": 0,
"base_stat": 40
}
],
"name": "fearow",
"weight": 100,
"sprites": {
"back_female": None,
"back_shiny_female": None,
"back_default": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/back/22.png",
"front_female": None,
"front_shiny_female": None,
"back_shiny": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/back/shiny/22.png",
"front_default": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/22.png",
"front_shiny": "https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/shiny/22.png"
},
"id": 22,
"order": 30,
"base_experience": 52
}
| pokeapi_pokemon_list_example = {'count': 949, 'previous': None, 'results': [{'url': 'https://pokeapi.co/api/v2/pokemon/21/', 'name': 'spearow'}, {'url': 'https://pokeapi.co/api/v2/pokemon/22/', 'name': 'fearow'}]}
pokeapi_pokemon_data_example_first = {'forms': [{'url': 'https://pokeapi.co/api/v2/pokemon-form/21/', 'name': 'spearow'}], 'stats': [{'stat': {'url': 'https://pokeapi.co/api/v2/stat/6/', 'name': 'speed'}, 'effort': 1, 'base_stat': 70}, {'stat': {'url': 'https://pokeapi.co/api/v2/stat/5/', 'name': 'special-defense'}, 'effort': 0, 'base_stat': 31}, {'stat': {'url': 'https://pokeapi.co/api/v2/stat/4/', 'name': 'special-attack'}, 'effort': 0, 'base_stat': 31}, {'stat': {'url': 'https://pokeapi.co/api/v2/stat/3/', 'name': 'defense'}, 'effort': 0, 'base_stat': 30}, {'stat': {'url': 'https://pokeapi.co/api/v2/stat/2/', 'name': 'attack'}, 'effort': 0, 'base_stat': 60}, {'stat': {'url': 'https://pokeapi.co/api/v2/stat/1/', 'name': 'hp'}, 'effort': 0, 'base_stat': 40}], 'name': 'spearow', 'weight': 20, 'sprites': {'back_female': None, 'back_shiny_female': None, 'back_default': 'https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/back/21.png', 'front_female': None, 'front_shiny_female': None, 'back_shiny': 'https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/back/shiny/21.png', 'front_default': 'https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/21.png', 'front_shiny': 'https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/shiny/21.png'}, 'id': 21, 'order': 30, 'base_experience': 52}
pokeapi_pokemon_data_example_second = {'forms': [{'url': 'https://pokeapi.co/api/v2/pokemon-form/22/', 'name': 'fearow'}], 'stats': [{'stat': {'url': 'https://pokeapi.co/api/v2/stat/6/', 'name': 'speed'}, 'effort': 2, 'base_stat': 100}, {'stat': {'url': 'https://pokeapi.co/api/v2/stat/5/', 'name': 'special-defense'}, 'effort': 0, 'base_stat': 31}, {'stat': {'url': 'https://pokeapi.co/api/v2/stat/4/', 'name': 'special-attack'}, 'effort': 0, 'base_stat': 31}, {'stat': {'url': 'https://pokeapi.co/api/v2/stat/3/', 'name': 'defense'}, 'effort': 0, 'base_stat': 65}, {'stat': {'url': 'https://pokeapi.co/api/v2/stat/2/', 'name': 'attack'}, 'effort': 0, 'base_stat': 90}, {'stat': {'url': 'https://pokeapi.co/api/v2/stat/1/', 'name': 'hp'}, 'effort': 0, 'base_stat': 40}], 'name': 'fearow', 'weight': 100, 'sprites': {'back_female': None, 'back_shiny_female': None, 'back_default': 'https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/back/22.png', 'front_female': None, 'front_shiny_female': None, 'back_shiny': 'https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/back/shiny/22.png', 'front_default': 'https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/22.png', 'front_shiny': 'https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/shiny/22.png'}, 'id': 22, 'order': 30, 'base_experience': 52} |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
class Mapping:
def __init__(self, iterable):
self.items_list = []
self.__update(iterable)
def __update(self, iterable):
for item in iterable:
self.items_list.append(item)
def test_parent(self):
print(self.__update)
class MappingSubclass(Mapping):
def __update(self, keys, values):
# provides new signature for update()
# but does not break __init__()
for item in zip(keys, values):
self.items_list.append(item)
def test_child(self):
print(self.__update)
# print(Mapping.__update) # Results in error
print(Mapping._Mapping__update)
print(MappingSubclass._Mapping__update)
print(MappingSubclass._MappingSubclass__update)
parent = Mapping([])
child = MappingSubclass([])
parent.test_parent()
child.test_parent()
child.test_child()
| class Mapping:
def __init__(self, iterable):
self.items_list = []
self.__update(iterable)
def __update(self, iterable):
for item in iterable:
self.items_list.append(item)
def test_parent(self):
print(self.__update)
class Mappingsubclass(Mapping):
def __update(self, keys, values):
for item in zip(keys, values):
self.items_list.append(item)
def test_child(self):
print(self.__update)
print(Mapping._Mapping__update)
print(MappingSubclass._Mapping__update)
print(MappingSubclass._MappingSubclass__update)
parent = mapping([])
child = mapping_subclass([])
parent.test_parent()
child.test_parent()
child.test_child() |
class Solution:
def removeElement(self, nums: List[int], val: int) -> int:
i = 0
length = len(nums)
while i < length:
if nums[i] == val:
nums[i:] = nums[i + 1:]
length -= 1
else:
i += 1
return length
| class Solution:
def remove_element(self, nums: List[int], val: int) -> int:
i = 0
length = len(nums)
while i < length:
if nums[i] == val:
nums[i:] = nums[i + 1:]
length -= 1
else:
i += 1
return length |
# 7x^1 - 2x^2 + 1x^3 + 2x^4 = 3
# 2x^1 + 8x^2 + 3x^3 + 1x^4 = -2
# -1x^1 + 0x^2 + 5x^3 + 2x^4 = 5
# 0x^1 + 2x^2 - 1x^3 + 4x^4 = 4
def getX1(x2,x3,x4):
return (3+2*x2-x3-2*x4)/7
def getX2(x1,x3,x4):
return (-2-2*x1-3*x3-x4)/8
def getX3(x1,x2,x4):
return (5+x1-2*x4)/5
def getX4(x1,x2,x3):
return (4-2*x2+x3)/4
x1=0
x2=0
x3=0
x4=0
#error=0.00001
x1a = 0.00001
x2a = 0.00001
x3a = 0.00001
x4a = 0.00001
for i in range(5):
x1 = getX1(x2,x3, x4)
x2 = getX2(x1,x3, x4)
x3 = getX3(x1,x2, x4)
x4 = getX4(x1,x2, x3)
#print("VALUES {0}{1}{2}{3}".format(x1,x2,x3,x4))
ex1 = abs((x1a-x1)/x1a)
ex2 = abs((x2a-x2)/x2a)
ex3 = abs((x3a-x3)/x3a)
ex4 = abs((x4a-x4)/x4a)
#if ex1 < error and ex2 < error and ex3 < error:
#break
x1a = x1
x2a = x2
x3a = x3
x4a = x4
print("FINAL: {0}\t{1}\t{2}\t{3}".format(x1,x2,x3,x4))
print("Errores: {0}\t{1}\t{2}\t{3}".format(ex1,ex2,ex3,ex4))
| def get_x1(x2, x3, x4):
return (3 + 2 * x2 - x3 - 2 * x4) / 7
def get_x2(x1, x3, x4):
return (-2 - 2 * x1 - 3 * x3 - x4) / 8
def get_x3(x1, x2, x4):
return (5 + x1 - 2 * x4) / 5
def get_x4(x1, x2, x3):
return (4 - 2 * x2 + x3) / 4
x1 = 0
x2 = 0
x3 = 0
x4 = 0
x1a = 1e-05
x2a = 1e-05
x3a = 1e-05
x4a = 1e-05
for i in range(5):
x1 = get_x1(x2, x3, x4)
x2 = get_x2(x1, x3, x4)
x3 = get_x3(x1, x2, x4)
x4 = get_x4(x1, x2, x3)
ex1 = abs((x1a - x1) / x1a)
ex2 = abs((x2a - x2) / x2a)
ex3 = abs((x3a - x3) / x3a)
ex4 = abs((x4a - x4) / x4a)
x1a = x1
x2a = x2
x3a = x3
x4a = x4
print('FINAL: {0}\t{1}\t{2}\t{3}'.format(x1, x2, x3, x4))
print('Errores: {0}\t{1}\t{2}\t{3}'.format(ex1, ex2, ex3, ex4)) |
def calc_fact(num):
total = 0
final_tot = 1
for x in range(num):
total = final_tot * (x+1)
final_tot = total
print(total)
calc_fact(10) # excepted output: 3628800 | def calc_fact(num):
total = 0
final_tot = 1
for x in range(num):
total = final_tot * (x + 1)
final_tot = total
print(total)
calc_fact(10) |
z = int(input())
y = int(input())
x = int(input())
space = x * y * z
box = int(0)
box_space = int(0)
while box != "Done":
box = input()
if box != "Done":
box = float(box)
box = int(box)
box_space += box
if box_space > space:
print(f"No more free space! You need {box_space - space} Cubic meters more.")
break
if box == "Done":
if space - box_space >= 0:
print(f"{space - box_space} Cubic meters left.")
if box_space - space >= 0:
print(f"No more free space! You need {box_space - space} Cubic meters more.")
| z = int(input())
y = int(input())
x = int(input())
space = x * y * z
box = int(0)
box_space = int(0)
while box != 'Done':
box = input()
if box != 'Done':
box = float(box)
box = int(box)
box_space += box
if box_space > space:
print(f'No more free space! You need {box_space - space} Cubic meters more.')
break
if box == 'Done':
if space - box_space >= 0:
print(f'{space - box_space} Cubic meters left.')
if box_space - space >= 0:
print(f'No more free space! You need {box_space - space} Cubic meters more.') |
DEBUG_MODE = False
#DIR_BASE = '/tmp/sms'
DIR_BASE = '/var/spool/sms'
DIR_INCOMING = 'incoming'
DIR_OUTGOING = 'outgoing'
DIR_CHECKED = 'checked'
DIR_FAILED = 'failed'
DIR_SENT = 'sent'
# Default international phone code
DEFAULT_CODE = '62'
# Unformatted messages will forward to
FORWARD_TO = ('62813123123', '62813123124')
| debug_mode = False
dir_base = '/var/spool/sms'
dir_incoming = 'incoming'
dir_outgoing = 'outgoing'
dir_checked = 'checked'
dir_failed = 'failed'
dir_sent = 'sent'
default_code = '62'
forward_to = ('62813123123', '62813123124') |
#===============================================================
# DMXIS Macro (c) 2010 db audioware limited
#===============================================================
sel = GetAllSelCh(False)
if len(sel)>0:
for ch in sel:
RemoveFixture(ch) | sel = get_all_sel_ch(False)
if len(sel) > 0:
for ch in sel:
remove_fixture(ch) |
#!/usr/bin/python3
def echo(input):
return input
def count_valid(data, anagrams=True):
valid = 0
if anagrams:
sort = echo
else:
sort = sorted
for line in data:
words = []
for word in line.split():
if sort(word) not in words:
words.append(sort(word))
else:
break
else:
valid += 1
return valid
if __name__ == "__main__":
with open("4") as dfile:
data = dfile.readlines()
print("Solution 1:", count_valid(data))
print("Solution 2:", count_valid(data, False))
| def echo(input):
return input
def count_valid(data, anagrams=True):
valid = 0
if anagrams:
sort = echo
else:
sort = sorted
for line in data:
words = []
for word in line.split():
if sort(word) not in words:
words.append(sort(word))
else:
break
else:
valid += 1
return valid
if __name__ == '__main__':
with open('4') as dfile:
data = dfile.readlines()
print('Solution 1:', count_valid(data))
print('Solution 2:', count_valid(data, False)) |
def initialize():
global detected, undetected, unsupported, total, report_id
detected = {}
undetected = {}
unsupported = {}
total = {}
report_id = {}
def initialize_colours():
global HEADER, OKBLUE, OKCYAN, OKGREEN, WARNING, FAIL, ENDC, BOLD, UNDERLINE, ALERT, GRAY, WHITE, END
global C
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKCYAN = '\033[96m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
RED = '\033[91m\033[1m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
ALERT = '\033[91m\033[4m\033[1m'
GRAY = '\033[90m'
WHITE = '\033[1m\033[97m'
END = '\033[0m'
C = '\033[1m'
def initialize_flask():
global mal_df, mal_file_dict, ctime, djvu_files
mal_df = None
mal_file_dict = {}
ctime = ''
djvu_files = []
| def initialize():
global detected, undetected, unsupported, total, report_id
detected = {}
undetected = {}
unsupported = {}
total = {}
report_id = {}
def initialize_colours():
global HEADER, OKBLUE, OKCYAN, OKGREEN, WARNING, FAIL, ENDC, BOLD, UNDERLINE, ALERT, GRAY, WHITE, END
global C
header = '\x1b[95m'
okblue = '\x1b[94m'
okcyan = '\x1b[96m'
okgreen = '\x1b[92m'
warning = '\x1b[93m'
fail = '\x1b[91m'
red = '\x1b[91m\x1b[1m'
endc = '\x1b[0m'
bold = '\x1b[1m'
underline = '\x1b[4m'
alert = '\x1b[91m\x1b[4m\x1b[1m'
gray = '\x1b[90m'
white = '\x1b[1m\x1b[97m'
end = '\x1b[0m'
c = '\x1b[1m'
def initialize_flask():
global mal_df, mal_file_dict, ctime, djvu_files
mal_df = None
mal_file_dict = {}
ctime = ''
djvu_files = [] |
##Afficher les communs diverseurs du nombre naturel N
n = int(input())
for a in range (1, n + 1) :
if n % a == 0 :
print(a)
else :
print(' ') | n = int(input())
for a in range(1, n + 1):
if n % a == 0:
print(a)
else:
print(' ') |
MAIL_USERNAME = 'buildasaasappwithflask@gmail.com'
MAIL_PASSWORD = 'helicopterpantswalrusfoot'
STRIPE_SECRET_KEY = 'sk_test_nycOOQdO9C16zxubr2WWtbug'
STRIPE_PUBLISHABLE_KEY = 'pk_test_ClU5mzNj1YxRRnrdZB5jEO29'
| mail_username = 'buildasaasappwithflask@gmail.com'
mail_password = 'helicopterpantswalrusfoot'
stripe_secret_key = 'sk_test_nycOOQdO9C16zxubr2WWtbug'
stripe_publishable_key = 'pk_test_ClU5mzNj1YxRRnrdZB5jEO29' |
#Called when SMU is in List mode
class SlaveMaster:
SLAVE = 0
MASTER = 1
| class Slavemaster:
slave = 0
master = 1 |
def private():
pass
class Abra:
def other():
private()
| def private():
pass
class Abra:
def other():
private() |
class Solution:
def majorityElement(self, nums: List[int]) -> int:
counter, target = 0, nums[0]
for i in nums:
if counter == 0:
target = i
if target != i:
counter -= 1
else:
counter += 1
return target
| class Solution:
def majority_element(self, nums: List[int]) -> int:
(counter, target) = (0, nums[0])
for i in nums:
if counter == 0:
target = i
if target != i:
counter -= 1
else:
counter += 1
return target |
class QuotaOptions(object):
def __init__(self,
start_quota: int = 0,
refresh_by: str = "month",
warning_rate: float = 0.8):
self.start_quota = start_quota
self.refresh_by = refresh_by
self.warning_rate = warning_rate
| class Quotaoptions(object):
def __init__(self, start_quota: int=0, refresh_by: str='month', warning_rate: float=0.8):
self.start_quota = start_quota
self.refresh_by = refresh_by
self.warning_rate = warning_rate |
def FoodStoreLol(Money, time, im):
print("What would you like to eat?")
time.sleep(2)
print("!Heres the menu!")
time.sleep(2)
im.show()
time.sleep(2)
eeee = input("Say Any Key to continue.")
FoodList = []
cash = 0
time.sleep(5)
for Loopies in range(3):
order =int(input("What would you like|1.Fries $50, 2.Chicken $250, 3.Burger $500, 4.Drinks $10, 5.None $0| Pick any three!"))
if order == 1:
FoodList.append("Fries")
print("Added Fries to the list")
cash = cash + 50
elif order == 2:
FoodList.append("Chicken")
print("Added Chicken to the list")
cash = cash + 250
elif order == 3:
FoodList.append("Burger")
print("Added Burger to the list")
cash = cash + 500
elif order == 4:
FoodList.append("Drink")
print("Added a Drink to the list")
cash = cash + 10
else:
print("Added None To the list")
print(cash ,"Is your food bill")
print(FoodList ,"Here is your order")
time.sleep(2)
checkfood =int(input("Are you sure want to buy the food? |1.Yes 2.No| >>"))
if checkfood == 1:
print("Ok... Purchasinng...")
if Money < cash:
print("Sorry, You dont have enough Money")
elif Money > cash:
Money = Money - cash
print("Success!")
time.sleep(2)
print("Cooking Food...")
time.sleep(10)
print("Done!!!")
time.sleep(1)
print("Here is your food")
print(FoodList)
print("_____________________________")
time.sleep(10)
else:
print("Ok cancelling the checkout")
| def food_store_lol(Money, time, im):
print('What would you like to eat?')
time.sleep(2)
print('!Heres the menu!')
time.sleep(2)
im.show()
time.sleep(2)
eeee = input('Say Any Key to continue.')
food_list = []
cash = 0
time.sleep(5)
for loopies in range(3):
order = int(input('What would you like|1.Fries $50, 2.Chicken $250, 3.Burger $500, 4.Drinks $10, 5.None $0| Pick any three!'))
if order == 1:
FoodList.append('Fries')
print('Added Fries to the list')
cash = cash + 50
elif order == 2:
FoodList.append('Chicken')
print('Added Chicken to the list')
cash = cash + 250
elif order == 3:
FoodList.append('Burger')
print('Added Burger to the list')
cash = cash + 500
elif order == 4:
FoodList.append('Drink')
print('Added a Drink to the list')
cash = cash + 10
else:
print('Added None To the list')
print(cash, 'Is your food bill')
print(FoodList, 'Here is your order')
time.sleep(2)
checkfood = int(input('Are you sure want to buy the food? |1.Yes 2.No| >>'))
if checkfood == 1:
print('Ok... Purchasinng...')
if Money < cash:
print('Sorry, You dont have enough Money')
elif Money > cash:
money = Money - cash
print('Success!')
time.sleep(2)
print('Cooking Food...')
time.sleep(10)
print('Done!!!')
time.sleep(1)
print('Here is your food')
print(FoodList)
print('_____________________________')
time.sleep(10)
else:
print('Ok cancelling the checkout') |
'''
An array is monotonic if it is either monotone increasing or monotone decreasing.
An array A is monotone increasing if for all i <= j, A[i] <= A[j]. An array A is monotone decreasing if for all i <= j, A[i] >= A[j].
Return true if and only if the given array A is monotonic.
Example 1:
Input: [1,2,2,3]
Output: true
Example 2:
Input: [6,5,4,4]
Output: true
Example 3:
Input: [1,3,2]
Output: false
Example 4:
Input: [1,2,4,5]
Output: true
Example 5:
Input: [1,1,1]
Output: true
Note:
1 <= A.length <= 50000
-100000 <= A[i] <= 100000
'''
def isMonotonic(A):
# if any elements
if len(A)>=1:
# if one or the same elements
# if sum(A)/len(A) == A[0]:
# return True
min_el = min(A)
pos_min = A.index(min_el)
max_el = max(A)
pos_max = A.index(max_el)
print(min_el, pos_min, max_el, pos_max)
# increasing
if pos_min < pos_max:
print("in increasing")
for i in range(len(A)-1):
print("i is ", i, " and A[i] is ", A[i], " and A[i+1] is ", A[i+1])
if not A[i] <= A[i+1]:
return False
else:
# decreasing
print("in decreasing")
for i in range(len(A)-1):
print("i is ", i, " and A[i] is ", A[i], " and A[i+1] is ", A[i+1])
if not A[i] >= A[i+1]:
return False
return True
print(isMonotonic([1,1,1])) # True
# print(isMonotonic([1,2,4,5])) # True
# print(isMonotonic([1,2,1,4,5])) # False
# print(isMonotonic([1,3,2])) # False
# print(isMonotonic([6,5,4,4])) # True
# print(isMonotonic([1,2,2,3])) # True
# print(isMonotonic([5,3,2,4,1])) # False
print(isMonotonic([3,4,2,3])) # False
print(isMonotonic([3])) # True
| """
An array is monotonic if it is either monotone increasing or monotone decreasing.
An array A is monotone increasing if for all i <= j, A[i] <= A[j]. An array A is monotone decreasing if for all i <= j, A[i] >= A[j].
Return true if and only if the given array A is monotonic.
Example 1:
Input: [1,2,2,3]
Output: true
Example 2:
Input: [6,5,4,4]
Output: true
Example 3:
Input: [1,3,2]
Output: false
Example 4:
Input: [1,2,4,5]
Output: true
Example 5:
Input: [1,1,1]
Output: true
Note:
1 <= A.length <= 50000
-100000 <= A[i] <= 100000
"""
def is_monotonic(A):
if len(A) >= 1:
min_el = min(A)
pos_min = A.index(min_el)
max_el = max(A)
pos_max = A.index(max_el)
print(min_el, pos_min, max_el, pos_max)
if pos_min < pos_max:
print('in increasing')
for i in range(len(A) - 1):
print('i is ', i, ' and A[i] is ', A[i], ' and A[i+1] is ', A[i + 1])
if not A[i] <= A[i + 1]:
return False
else:
print('in decreasing')
for i in range(len(A) - 1):
print('i is ', i, ' and A[i] is ', A[i], ' and A[i+1] is ', A[i + 1])
if not A[i] >= A[i + 1]:
return False
return True
print(is_monotonic([1, 1, 1]))
print(is_monotonic([3, 4, 2, 3]))
print(is_monotonic([3])) |
#!/usr/local/bin/python3
def imprime(maximo, atual):
if atual >= maximo:
return
print(atual)
imprime(maximo, atual + 1)
if __name__ == '__main__':
imprime(100, 1)
| def imprime(maximo, atual):
if atual >= maximo:
return
print(atual)
imprime(maximo, atual + 1)
if __name__ == '__main__':
imprime(100, 1) |
project = 'pydatastructs'
modules = ['linear_data_structures']
backend = '_backend'
cpp = 'cpp'
dummy_submodules = ['_arrays.py']
| project = 'pydatastructs'
modules = ['linear_data_structures']
backend = '_backend'
cpp = 'cpp'
dummy_submodules = ['_arrays.py'] |
# Given a list of numbers and a number k.
# Return whether any two numbers from the list add up to k.
#
# For example:
# Give [1,2,3,4] and k of 7
# Return true since 3 + 4 is 7
def input_array():
print("Len of array = ", end='')
array_len = int(input())
print()
array = []
for i in range(array_len):
print("Value of array[{}] = ".format(i), end='')
element = int(input())
array.append(element)
print("Array is: ", array)
return array
def input_k():
print("\nk = ", end='')
k = int(input())
return k
def have_two_element_up_to_k(numbers, k):
for i in range(0, len(numbers) - 1):
for j in range(1, len(numbers)):
if numbers[i] + numbers[j] == k:
return True
return False
def main_program():
numbers = input_array()
k = input_k()
print("\nResult: ", have_two_element_up_to_k(numbers, k))
main_program()
| def input_array():
print('Len of array = ', end='')
array_len = int(input())
print()
array = []
for i in range(array_len):
print('Value of array[{}] = '.format(i), end='')
element = int(input())
array.append(element)
print('Array is: ', array)
return array
def input_k():
print('\nk = ', end='')
k = int(input())
return k
def have_two_element_up_to_k(numbers, k):
for i in range(0, len(numbers) - 1):
for j in range(1, len(numbers)):
if numbers[i] + numbers[j] == k:
return True
return False
def main_program():
numbers = input_array()
k = input_k()
print('\nResult: ', have_two_element_up_to_k(numbers, k))
main_program() |
operator = input()
num_one = int(input())
num_two = int(input())
def multiply_nums(x, y):
result = x * y
return result
def divide_nums(x, y):
if y != 0:
result = int(x / y)
return result
def add_nums(x, y):
result = x + y
return result
def subtract_nums(x, y):
result = x - y
return result
all_commands = {
"multiply": multiply_nums,
"divide": divide_nums,
"add": add_nums,
"subtract": subtract_nums
}
print(all_commands[operator](num_one, num_two))
| operator = input()
num_one = int(input())
num_two = int(input())
def multiply_nums(x, y):
result = x * y
return result
def divide_nums(x, y):
if y != 0:
result = int(x / y)
return result
def add_nums(x, y):
result = x + y
return result
def subtract_nums(x, y):
result = x - y
return result
all_commands = {'multiply': multiply_nums, 'divide': divide_nums, 'add': add_nums, 'subtract': subtract_nums}
print(all_commands[operator](num_one, num_two)) |
print(" I will now count my chickens:")
print("Hens",25+30/6)
print("Roosters", 100-25*3%4)
print("Now I will continue the eggs:")
print(3+2+1-5+4%2-1/4+6)
print("Is it true that 3+2<5-7?")
print(3+2<5-7)
print("What is 3+2?", 3+2)
print("What is 5=7?", 5-7)
print("Oh, that;s why it;s false.")
print("How abaout some more.")
print("Is it geater?", 5>-2)
print("Is it greater or equal?", 5>=-2)
print("Is it less or equal?", 5<=-2) | print(' I will now count my chickens:')
print('Hens', 25 + 30 / 6)
print('Roosters', 100 - 25 * 3 % 4)
print('Now I will continue the eggs:')
print(3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6)
print('Is it true that 3+2<5-7?')
print(3 + 2 < 5 - 7)
print('What is 3+2?', 3 + 2)
print('What is 5=7?', 5 - 7)
print('Oh, that;s why it;s false.')
print('How abaout some more.')
print('Is it geater?', 5 > -2)
print('Is it greater or equal?', 5 >= -2)
print('Is it less or equal?', 5 <= -2) |
# Created by MechAviv
# Wicked Witch Damage Skin | (2433184)
if sm.addDamageSkin(2433184):
sm.chat("'Wicked Witch Damage Skin' Damage Skin has been added to your account's damage skin collection.")
sm.consumeItem() | if sm.addDamageSkin(2433184):
sm.chat("'Wicked Witch Damage Skin' Damage Skin has been added to your account's damage skin collection.")
sm.consumeItem() |
n = int(input())
votos = []
for i in range(n):
x = int(input())
votos.append(x)
if votos[0] >= max(votos):
print("S")
else:
print("N")
| n = int(input())
votos = []
for i in range(n):
x = int(input())
votos.append(x)
if votos[0] >= max(votos):
print('S')
else:
print('N') |
# Dasean Volk, dvolk@usc.edu
# Fall 2021, ITP115
# Section: Boba
# Lab 9
# --------------------------------------SHOW RECOMMENDER & FILE CREATOR----------------------------------------------- #
def display_menu():
print("TV Shows \nPossible genres are action & adventure, animation, comedy, "
"\ndocumentary, drama, mystery & suspense, science fiction & fantasy")
# function: read_file
# parameter 1: user_genre is a string
# parameter 2: file_name is a string with a default value of "shows.csv"
# return value: a list of shows where the user's genre is inside of the show's genre
def read_file(user_genre, file_name="shows.csv"):
show_list = []
open_file = open(file_name, "r")
for line in open_file:
line = line.strip() # always get rid of new lines
info_list = line.split(",")
show_genre = info_list[1]
if user_genre in show_genre:
show_list.append(info_list[0])
open_file.close()
show_list.sort()
return show_list
# function: write_file
# parameter 1: genre is a string
# parameter 2: show_list is a list of show
# return value: None
# write the list to a file
# the name of the file is the genre + ".txt"
def write_file(genre, show_list):
name_file = genre + ".txt"
out_file = open(name_file, "w")
for show in show_list:
print(show, file=out_file)
out_file.close()
def main():
print("TV Shows")
genre_str = ("action & adventure, animation, comedy, "
"documentary, drama, mystery & suspense, science fiction & fantasy")
print("Possible genres are", genre_str)
user = input("Enter a genre: ")
while user not in genre_str:
user = input("Enter a genre: ")
shows = read_file(user)
write_file(user, shows)
main()
| def display_menu():
print('TV Shows \nPossible genres are action & adventure, animation, comedy, \ndocumentary, drama, mystery & suspense, science fiction & fantasy')
def read_file(user_genre, file_name='shows.csv'):
show_list = []
open_file = open(file_name, 'r')
for line in open_file:
line = line.strip()
info_list = line.split(',')
show_genre = info_list[1]
if user_genre in show_genre:
show_list.append(info_list[0])
open_file.close()
show_list.sort()
return show_list
def write_file(genre, show_list):
name_file = genre + '.txt'
out_file = open(name_file, 'w')
for show in show_list:
print(show, file=out_file)
out_file.close()
def main():
print('TV Shows')
genre_str = 'action & adventure, animation, comedy, documentary, drama, mystery & suspense, science fiction & fantasy'
print('Possible genres are', genre_str)
user = input('Enter a genre: ')
while user not in genre_str:
user = input('Enter a genre: ')
shows = read_file(user)
write_file(user, shows)
main() |
print('Mind Mapping')
print('')
q = input('1) ')
q1 = input('1.1) ')
q2 = input('1.2) ')
print('')
w = input('2) ')
w1 = input('2.1) ')
w2 = input('2.2) ')
print('')
e = input('3) ')
e1 = input('3.1) ')
e2 = input('3.2) ')
print('')
r = input('4) ')
r1 = input('4.1) ')
r2 = input('4.2) ')
print('')
print('')
print('1) ' + str(q) + ', ' + str(q1) + ', ' + str(q2))
print('2) ' + str(w) + ', ' + str(w1) + ', ' + str(w2))
print('3) ' + str(e) + ', ' + str(e1) + ', ' + str(e2))
print('4) ' + str(r) + ', ' + str(r1) + ', ' + str(r2))
ext = input('')
| print('Mind Mapping')
print('')
q = input('1) ')
q1 = input('1.1) ')
q2 = input('1.2) ')
print('')
w = input('2) ')
w1 = input('2.1) ')
w2 = input('2.2) ')
print('')
e = input('3) ')
e1 = input('3.1) ')
e2 = input('3.2) ')
print('')
r = input('4) ')
r1 = input('4.1) ')
r2 = input('4.2) ')
print('')
print('')
print('1) ' + str(q) + ', ' + str(q1) + ', ' + str(q2))
print('2) ' + str(w) + ', ' + str(w1) + ', ' + str(w2))
print('3) ' + str(e) + ', ' + str(e1) + ', ' + str(e2))
print('4) ' + str(r) + ', ' + str(r1) + ', ' + str(r2))
ext = input('') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.