content
stringlengths 7
1.05M
| fixed_cases
stringlengths 1
1.28M
|
|---|---|
class Vehicle:
''' Documentation needed here
'''
def __init__(self, numberOfTires, colorOfVehicle):
''' Documentation needed here
'''
self.numberOfTires = numberOfTires
self.colorOfVehicle = colorOfVehicle
def start(self):
''' This function starts the vehicle
'''
print("I started!")
def drive(self):
''' This function drives the vehicle
'''
print("I'm driving!")
def setColor(color):
''' This function updates the color of the vehicle based
on the pass in information
Parameters:
Color -> a color to update the vehicle's color with
'''
this.colorOfVehicle = color
def __repr__(self):
return "I'm a Vehicle!"
|
class Vehicle:
""" Documentation needed here
"""
def __init__(self, numberOfTires, colorOfVehicle):
""" Documentation needed here
"""
self.numberOfTires = numberOfTires
self.colorOfVehicle = colorOfVehicle
def start(self):
""" This function starts the vehicle
"""
print('I started!')
def drive(self):
""" This function drives the vehicle
"""
print("I'm driving!")
def set_color(color):
""" This function updates the color of the vehicle based
on the pass in information
Parameters:
Color -> a color to update the vehicle's color with
"""
this.colorOfVehicle = color
def __repr__(self):
return "I'm a Vehicle!"
|
def tail(filename, n=10):
'Return the last n lines of a file'
with open(filename) as f:
return deque(f, n)
|
def tail(filename, n=10):
"""Return the last n lines of a file"""
with open(filename) as f:
return deque(f, n)
|
render = ez.Node()
aspect2D = ez.Node()
camera = ez.Camera(parent=render)
camera.y = -20
# Create a a model:
dirt = ez.load.texture('dirt.png')
mesh = ez.load.mesh('hex.bam')
model = ez.Model( mesh, parent=render)
model.shader = ez.load.shader('shaded.glsl')
model.set_shader_input('texture0', dirt)
# Our task function:
def task_spin_node(node, task):
node.p += 100 * ez.get_dt()
return task.cont
# Create the task and pass model as the node:
task = ez.make_task(task_spin_node, model)
# You can pass whatever you want into a task: (task will always be last argument)
# Example:
#def task_fuction(a, b, c, d, e, LIST, DICT, task):
# return task.cont
# task = ez.make_task(task_function, a, b, d, c, e, LIST, DICT)
def input(event):
device, name, state = event
if name=='space':
if state==1:
ez.add_task(task)
else:
ez.remove_task(task)
if name == 'escape' and state == 0:
ez.set_scene(ez['menu'])
def logic(dt):
if ez.is_button_down('a'):
pos[0] -= 10*dt
if pos[0] < 1:
pos[0] = 1
if ez.is_button_down('d'):
pos[0] += 10*dt
if pos[0] > 6:
pos[0] = 6
def enter():
ez.window.background_color = 0, 0.0, 0.0
ez.add_input_events(['space'])
L, R, T, B = ez.window.get_aspect2D_edges()
text = ez['text']
text.x = L+0.02
text.y = B+0.03
text.text="SPACE - down: adds the task, release: removes the task"
text.parent = aspect2D
def exit():
ez.remove_input_events(['space'])
# If holding down the space bar and exiting the task can keep running in the background.
# So here we are removing the task to make sure it stops running when leaving the scene.
ez.remove_task(task)
|
render = ez.Node()
aspect2_d = ez.Node()
camera = ez.Camera(parent=render)
camera.y = -20
dirt = ez.load.texture('dirt.png')
mesh = ez.load.mesh('hex.bam')
model = ez.Model(mesh, parent=render)
model.shader = ez.load.shader('shaded.glsl')
model.set_shader_input('texture0', dirt)
def task_spin_node(node, task):
node.p += 100 * ez.get_dt()
return task.cont
task = ez.make_task(task_spin_node, model)
def input(event):
(device, name, state) = event
if name == 'space':
if state == 1:
ez.add_task(task)
else:
ez.remove_task(task)
if name == 'escape' and state == 0:
ez.set_scene(ez['menu'])
def logic(dt):
if ez.is_button_down('a'):
pos[0] -= 10 * dt
if pos[0] < 1:
pos[0] = 1
if ez.is_button_down('d'):
pos[0] += 10 * dt
if pos[0] > 6:
pos[0] = 6
def enter():
ez.window.background_color = (0, 0.0, 0.0)
ez.add_input_events(['space'])
(l, r, t, b) = ez.window.get_aspect2D_edges()
text = ez['text']
text.x = L + 0.02
text.y = B + 0.03
text.text = 'SPACE - down: adds the task, release: removes the task'
text.parent = aspect2D
def exit():
ez.remove_input_events(['space'])
ez.remove_task(task)
|
#
# PySNMP MIB module TIMETRA-CLEAR-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TIMETRA-CLEAR-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:09:48 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
SingleValueConstraint, ConstraintsIntersection, ValueRangeConstraint, ValueSizeConstraint, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ConstraintsIntersection", "ValueRangeConstraint", "ValueSizeConstraint", "ConstraintsUnion")
ModuleCompliance, NotificationGroup, ObjectGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup", "ObjectGroup")
IpAddress, Bits, Integer32, Counter64, NotificationType, MibScalar, MibTable, MibTableRow, MibTableColumn, iso, TimeTicks, Gauge32, Unsigned32, Counter32, ObjectIdentity, ModuleIdentity, MibIdentifier = mibBuilder.importSymbols("SNMPv2-SMI", "IpAddress", "Bits", "Integer32", "Counter64", "NotificationType", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "iso", "TimeTicks", "Gauge32", "Unsigned32", "Counter32", "ObjectIdentity", "ModuleIdentity", "MibIdentifier")
TimeStamp, DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "TimeStamp", "DisplayString", "TextualConvention")
tmnxSRNotifyPrefix, tmnxSRObjs, tmnxSRConfs, timetraSRMIBModules = mibBuilder.importSymbols("TIMETRA-GLOBAL-MIB", "tmnxSRNotifyPrefix", "tmnxSRObjs", "tmnxSRConfs", "timetraSRMIBModules")
tmnxEventAppIndex, = mibBuilder.importSymbols("TIMETRA-LOG-MIB", "tmnxEventAppIndex")
TmnxActionType, TNamedItem = mibBuilder.importSymbols("TIMETRA-TC-MIB", "TmnxActionType", "TNamedItem")
timetraClearMIBModule = ModuleIdentity((1, 3, 6, 1, 4, 1, 6527, 1, 1, 3, 13))
timetraClearMIBModule.setRevisions(('1905-01-24 00:00', '1904-06-02 00:00', '1904-01-15 00:00', '1903-08-15 00:00', '1903-01-20 00:00', '1902-02-27 00:00',))
if mibBuilder.loadTexts: timetraClearMIBModule.setLastUpdated('0501240000Z')
if mibBuilder.loadTexts: timetraClearMIBModule.setOrganization('Alcatel-Lucent')
tmnxClearObjs = MibIdentifier((1, 3, 6, 1, 4, 1, 6527, 3, 1, 2, 13))
tmnxClearNotificationsPrefix = MibIdentifier((1, 3, 6, 1, 4, 1, 6527, 3, 1, 3, 13))
tmnxClearNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 6527, 3, 1, 3, 13, 0))
tmnxClearConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 6527, 3, 1, 1, 13))
tmnxClearTable = MibTable((1, 3, 6, 1, 4, 1, 6527, 3, 1, 2, 13, 1), )
if mibBuilder.loadTexts: tmnxClearTable.setStatus('current')
tmnxClearEntry = MibTableRow((1, 3, 6, 1, 4, 1, 6527, 3, 1, 2, 13, 1, 1), ).setIndexNames((0, "TIMETRA-LOG-MIB", "tmnxEventAppIndex"), (0, "TIMETRA-CLEAR-MIB", "tmnxClearIndex"))
if mibBuilder.loadTexts: tmnxClearEntry.setStatus('current')
tmnxClearIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 6527, 3, 1, 2, 13, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535)))
if mibBuilder.loadTexts: tmnxClearIndex.setStatus('current')
tmnxClearName = MibTableColumn((1, 3, 6, 1, 4, 1, 6527, 3, 1, 2, 13, 1, 1, 2), TNamedItem()).setMaxAccess("readonly")
if mibBuilder.loadTexts: tmnxClearName.setStatus('current')
tmnxClearParams = MibTableColumn((1, 3, 6, 1, 4, 1, 6527, 3, 1, 2, 13, 1, 1, 3), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 255)).clone(hexValue="")).setMaxAccess("readwrite")
if mibBuilder.loadTexts: tmnxClearParams.setStatus('current')
tmnxClearAction = MibTableColumn((1, 3, 6, 1, 4, 1, 6527, 3, 1, 2, 13, 1, 1, 4), TmnxActionType().clone('notApplicable')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: tmnxClearAction.setStatus('current')
tmnxClearLastClearedTime = MibTableColumn((1, 3, 6, 1, 4, 1, 6527, 3, 1, 2, 13, 1, 1, 5), TimeStamp()).setMaxAccess("readonly")
if mibBuilder.loadTexts: tmnxClearLastClearedTime.setStatus('current')
tmnxClearResult = MibTableColumn((1, 3, 6, 1, 4, 1, 6527, 3, 1, 2, 13, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("success", 1), ("failure", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: tmnxClearResult.setStatus('current')
tmnxClearErrorText = MibTableColumn((1, 3, 6, 1, 4, 1, 6527, 3, 1, 2, 13, 1, 1, 7), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: tmnxClearErrorText.setStatus('current')
tmnxClear = NotificationType((1, 3, 6, 1, 4, 1, 6527, 3, 1, 3, 13, 0, 1)).setObjects(("TIMETRA-CLEAR-MIB", "tmnxClearName"), ("TIMETRA-CLEAR-MIB", "tmnxClearParams"), ("TIMETRA-CLEAR-MIB", "tmnxClearLastClearedTime"), ("TIMETRA-CLEAR-MIB", "tmnxClearResult"), ("TIMETRA-CLEAR-MIB", "tmnxClearErrorText"))
if mibBuilder.loadTexts: tmnxClear.setStatus('current')
tmnxClearCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 6527, 3, 1, 1, 13, 1))
tmnxClearGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 6527, 3, 1, 1, 13, 2))
tmnxClearCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 6527, 3, 1, 1, 13, 1, 1)).setObjects(("TIMETRA-CLEAR-MIB", "tmnxClearGroup"), ("TIMETRA-CLEAR-MIB", "tmnxClearNotificationGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
tmnxClearCompliance = tmnxClearCompliance.setStatus('current')
tmnxClearGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 6527, 3, 1, 1, 13, 2, 1)).setObjects(("TIMETRA-CLEAR-MIB", "tmnxClearName"), ("TIMETRA-CLEAR-MIB", "tmnxClearParams"), ("TIMETRA-CLEAR-MIB", "tmnxClearAction"), ("TIMETRA-CLEAR-MIB", "tmnxClearLastClearedTime"), ("TIMETRA-CLEAR-MIB", "tmnxClearResult"), ("TIMETRA-CLEAR-MIB", "tmnxClearErrorText"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
tmnxClearGroup = tmnxClearGroup.setStatus('current')
tmnxClearNotificationGroup = NotificationGroup((1, 3, 6, 1, 4, 1, 6527, 3, 1, 1, 13, 2, 2)).setObjects(("TIMETRA-CLEAR-MIB", "tmnxClear"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
tmnxClearNotificationGroup = tmnxClearNotificationGroup.setStatus('current')
mibBuilder.exportSymbols("TIMETRA-CLEAR-MIB", tmnxClearName=tmnxClearName, tmnxClearAction=tmnxClearAction, tmnxClearGroups=tmnxClearGroups, tmnxClearCompliance=tmnxClearCompliance, tmnxClearCompliances=tmnxClearCompliances, timetraClearMIBModule=timetraClearMIBModule, tmnxClearLastClearedTime=tmnxClearLastClearedTime, tmnxClear=tmnxClear, tmnxClearParams=tmnxClearParams, tmnxClearNotifications=tmnxClearNotifications, tmnxClearResult=tmnxClearResult, PYSNMP_MODULE_ID=timetraClearMIBModule, tmnxClearTable=tmnxClearTable, tmnxClearNotificationsPrefix=tmnxClearNotificationsPrefix, tmnxClearObjs=tmnxClearObjs, tmnxClearConformance=tmnxClearConformance, tmnxClearErrorText=tmnxClearErrorText, tmnxClearNotificationGroup=tmnxClearNotificationGroup, tmnxClearEntry=tmnxClearEntry, tmnxClearIndex=tmnxClearIndex, tmnxClearGroup=tmnxClearGroup)
|
(octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(single_value_constraint, constraints_intersection, value_range_constraint, value_size_constraint, constraints_union) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'SingleValueConstraint', 'ConstraintsIntersection', 'ValueRangeConstraint', 'ValueSizeConstraint', 'ConstraintsUnion')
(module_compliance, notification_group, object_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup', 'ObjectGroup')
(ip_address, bits, integer32, counter64, notification_type, mib_scalar, mib_table, mib_table_row, mib_table_column, iso, time_ticks, gauge32, unsigned32, counter32, object_identity, module_identity, mib_identifier) = mibBuilder.importSymbols('SNMPv2-SMI', 'IpAddress', 'Bits', 'Integer32', 'Counter64', 'NotificationType', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'iso', 'TimeTicks', 'Gauge32', 'Unsigned32', 'Counter32', 'ObjectIdentity', 'ModuleIdentity', 'MibIdentifier')
(time_stamp, display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'TimeStamp', 'DisplayString', 'TextualConvention')
(tmnx_sr_notify_prefix, tmnx_sr_objs, tmnx_sr_confs, timetra_srmib_modules) = mibBuilder.importSymbols('TIMETRA-GLOBAL-MIB', 'tmnxSRNotifyPrefix', 'tmnxSRObjs', 'tmnxSRConfs', 'timetraSRMIBModules')
(tmnx_event_app_index,) = mibBuilder.importSymbols('TIMETRA-LOG-MIB', 'tmnxEventAppIndex')
(tmnx_action_type, t_named_item) = mibBuilder.importSymbols('TIMETRA-TC-MIB', 'TmnxActionType', 'TNamedItem')
timetra_clear_mib_module = module_identity((1, 3, 6, 1, 4, 1, 6527, 1, 1, 3, 13))
timetraClearMIBModule.setRevisions(('1905-01-24 00:00', '1904-06-02 00:00', '1904-01-15 00:00', '1903-08-15 00:00', '1903-01-20 00:00', '1902-02-27 00:00'))
if mibBuilder.loadTexts:
timetraClearMIBModule.setLastUpdated('0501240000Z')
if mibBuilder.loadTexts:
timetraClearMIBModule.setOrganization('Alcatel-Lucent')
tmnx_clear_objs = mib_identifier((1, 3, 6, 1, 4, 1, 6527, 3, 1, 2, 13))
tmnx_clear_notifications_prefix = mib_identifier((1, 3, 6, 1, 4, 1, 6527, 3, 1, 3, 13))
tmnx_clear_notifications = mib_identifier((1, 3, 6, 1, 4, 1, 6527, 3, 1, 3, 13, 0))
tmnx_clear_conformance = mib_identifier((1, 3, 6, 1, 4, 1, 6527, 3, 1, 1, 13))
tmnx_clear_table = mib_table((1, 3, 6, 1, 4, 1, 6527, 3, 1, 2, 13, 1))
if mibBuilder.loadTexts:
tmnxClearTable.setStatus('current')
tmnx_clear_entry = mib_table_row((1, 3, 6, 1, 4, 1, 6527, 3, 1, 2, 13, 1, 1)).setIndexNames((0, 'TIMETRA-LOG-MIB', 'tmnxEventAppIndex'), (0, 'TIMETRA-CLEAR-MIB', 'tmnxClearIndex'))
if mibBuilder.loadTexts:
tmnxClearEntry.setStatus('current')
tmnx_clear_index = mib_table_column((1, 3, 6, 1, 4, 1, 6527, 3, 1, 2, 13, 1, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(1, 65535)))
if mibBuilder.loadTexts:
tmnxClearIndex.setStatus('current')
tmnx_clear_name = mib_table_column((1, 3, 6, 1, 4, 1, 6527, 3, 1, 2, 13, 1, 1, 2), t_named_item()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
tmnxClearName.setStatus('current')
tmnx_clear_params = mib_table_column((1, 3, 6, 1, 4, 1, 6527, 3, 1, 2, 13, 1, 1, 3), octet_string().subtype(subtypeSpec=value_size_constraint(0, 255)).clone(hexValue='')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
tmnxClearParams.setStatus('current')
tmnx_clear_action = mib_table_column((1, 3, 6, 1, 4, 1, 6527, 3, 1, 2, 13, 1, 1, 4), tmnx_action_type().clone('notApplicable')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
tmnxClearAction.setStatus('current')
tmnx_clear_last_cleared_time = mib_table_column((1, 3, 6, 1, 4, 1, 6527, 3, 1, 2, 13, 1, 1, 5), time_stamp()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
tmnxClearLastClearedTime.setStatus('current')
tmnx_clear_result = mib_table_column((1, 3, 6, 1, 4, 1, 6527, 3, 1, 2, 13, 1, 1, 6), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('success', 1), ('failure', 2)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
tmnxClearResult.setStatus('current')
tmnx_clear_error_text = mib_table_column((1, 3, 6, 1, 4, 1, 6527, 3, 1, 2, 13, 1, 1, 7), octet_string().subtype(subtypeSpec=value_size_constraint(0, 255))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
tmnxClearErrorText.setStatus('current')
tmnx_clear = notification_type((1, 3, 6, 1, 4, 1, 6527, 3, 1, 3, 13, 0, 1)).setObjects(('TIMETRA-CLEAR-MIB', 'tmnxClearName'), ('TIMETRA-CLEAR-MIB', 'tmnxClearParams'), ('TIMETRA-CLEAR-MIB', 'tmnxClearLastClearedTime'), ('TIMETRA-CLEAR-MIB', 'tmnxClearResult'), ('TIMETRA-CLEAR-MIB', 'tmnxClearErrorText'))
if mibBuilder.loadTexts:
tmnxClear.setStatus('current')
tmnx_clear_compliances = mib_identifier((1, 3, 6, 1, 4, 1, 6527, 3, 1, 1, 13, 1))
tmnx_clear_groups = mib_identifier((1, 3, 6, 1, 4, 1, 6527, 3, 1, 1, 13, 2))
tmnx_clear_compliance = module_compliance((1, 3, 6, 1, 4, 1, 6527, 3, 1, 1, 13, 1, 1)).setObjects(('TIMETRA-CLEAR-MIB', 'tmnxClearGroup'), ('TIMETRA-CLEAR-MIB', 'tmnxClearNotificationGroup'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
tmnx_clear_compliance = tmnxClearCompliance.setStatus('current')
tmnx_clear_group = object_group((1, 3, 6, 1, 4, 1, 6527, 3, 1, 1, 13, 2, 1)).setObjects(('TIMETRA-CLEAR-MIB', 'tmnxClearName'), ('TIMETRA-CLEAR-MIB', 'tmnxClearParams'), ('TIMETRA-CLEAR-MIB', 'tmnxClearAction'), ('TIMETRA-CLEAR-MIB', 'tmnxClearLastClearedTime'), ('TIMETRA-CLEAR-MIB', 'tmnxClearResult'), ('TIMETRA-CLEAR-MIB', 'tmnxClearErrorText'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
tmnx_clear_group = tmnxClearGroup.setStatus('current')
tmnx_clear_notification_group = notification_group((1, 3, 6, 1, 4, 1, 6527, 3, 1, 1, 13, 2, 2)).setObjects(('TIMETRA-CLEAR-MIB', 'tmnxClear'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
tmnx_clear_notification_group = tmnxClearNotificationGroup.setStatus('current')
mibBuilder.exportSymbols('TIMETRA-CLEAR-MIB', tmnxClearName=tmnxClearName, tmnxClearAction=tmnxClearAction, tmnxClearGroups=tmnxClearGroups, tmnxClearCompliance=tmnxClearCompliance, tmnxClearCompliances=tmnxClearCompliances, timetraClearMIBModule=timetraClearMIBModule, tmnxClearLastClearedTime=tmnxClearLastClearedTime, tmnxClear=tmnxClear, tmnxClearParams=tmnxClearParams, tmnxClearNotifications=tmnxClearNotifications, tmnxClearResult=tmnxClearResult, PYSNMP_MODULE_ID=timetraClearMIBModule, tmnxClearTable=tmnxClearTable, tmnxClearNotificationsPrefix=tmnxClearNotificationsPrefix, tmnxClearObjs=tmnxClearObjs, tmnxClearConformance=tmnxClearConformance, tmnxClearErrorText=tmnxClearErrorText, tmnxClearNotificationGroup=tmnxClearNotificationGroup, tmnxClearEntry=tmnxClearEntry, tmnxClearIndex=tmnxClearIndex, tmnxClearGroup=tmnxClearGroup)
|
n, m = map(int, input().split())
array = [input() for _ in range(n)]
k = int(input())
for row in sorted(array, key=lambda row: int(row.split()[k])):
print(row)
|
(n, m) = map(int, input().split())
array = [input() for _ in range(n)]
k = int(input())
for row in sorted(array, key=lambda row: int(row.split()[k])):
print(row)
|
class WordDictionary:
def __init__(self):
"""
Initialize your data structure here.
"""
self.endWord = False
self.children = [None] * 26
def addWord(self, word: str) -> None:
"""
Adds a word into the data structure.
"""
curr = self
for char in word:
indx = ord(char) - ord('a')
if curr.children[indx] == None:
curr.children[indx] = WordDictionary()
curr = curr.children[indx]
curr.endWord = True
def search(self, word: str) -> bool:
"""
Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
"""
curr = self
for i in range(len(word)):
char = word[i]
indx = ord(char) - ord('a')
if char == '.':
for ch in curr.children:
if ch != None and ch.search(word[i+1:]):
return True
return False
if curr.children[indx] == None:
return False
curr = curr.children[indx]
return curr != None and curr.endWord
# Your WordDictionary object will be instantiated and called as such:
# obj = WordDictionary()
# obj.addWord(word)
# param_2 = obj.search(word)
|
class Worddictionary:
def __init__(self):
"""
Initialize your data structure here.
"""
self.endWord = False
self.children = [None] * 26
def add_word(self, word: str) -> None:
"""
Adds a word into the data structure.
"""
curr = self
for char in word:
indx = ord(char) - ord('a')
if curr.children[indx] == None:
curr.children[indx] = word_dictionary()
curr = curr.children[indx]
curr.endWord = True
def search(self, word: str) -> bool:
"""
Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter.
"""
curr = self
for i in range(len(word)):
char = word[i]
indx = ord(char) - ord('a')
if char == '.':
for ch in curr.children:
if ch != None and ch.search(word[i + 1:]):
return True
return False
if curr.children[indx] == None:
return False
curr = curr.children[indx]
return curr != None and curr.endWord
|
def count(char,word):
total=0
for any in word:
if any in char:
total = total + 1
return total
result = count('a','banana')
print(result)
|
def count(char, word):
total = 0
for any in word:
if any in char:
total = total + 1
return total
result = count('a', 'banana')
print(result)
|
class VariableEngine:
"""A simple package for handling variables in string."""
def __init__(self, prefix: str = None, suffix: str = None):
self.variables = {}
self.prefix = str(prefix) if prefix else '' #If prefix is none prefix defaults to ''
self.suffix = str(suffix) if suffix else self.prefix #If suffix is none suffix defaults to prefix
def add_variable(self, variable: str, value: str):
"""Adds a new variable with a value to the engine."""
if str(variable) in self.variables:
#to avoid duplicate entities
raise NameError(f'Variable "{variable}" already exists.')
self.variables[str(variable)] = str(value)
#aliase, add_var corresponds to add_variable
add_var = add_variable
def clear_variables(self):
"""Removes all variables from the engine."""
del self.variables
self.variables = {}
#aliase, clear_vars corresponds to clear_variables
clear_vars = clear_variables
def remove_variable(self, variable: str):
"""Removes a variable from the engine."""
_variable = str(variable)
if not _variable in self.variables:
raise TypeError(f'There is no such variable: "{variable}".')
del self.variables[_variable]
#aliase, remove_var corresponds to remove_variable
remove_var = remove_variable
def process(self, string: str):
"""Processes a string, replaces variables with its values."""
result = None
for variable, value in self.variables.items():
if not result:
result = str(string)
_variable = f'{self.prefix}{variable}{self.suffix}'
result = result.replace(_variable, value)
return result
|
class Variableengine:
"""A simple package for handling variables in string."""
def __init__(self, prefix: str=None, suffix: str=None):
self.variables = {}
self.prefix = str(prefix) if prefix else ''
self.suffix = str(suffix) if suffix else self.prefix
def add_variable(self, variable: str, value: str):
"""Adds a new variable with a value to the engine."""
if str(variable) in self.variables:
raise name_error(f'Variable "{variable}" already exists.')
self.variables[str(variable)] = str(value)
add_var = add_variable
def clear_variables(self):
"""Removes all variables from the engine."""
del self.variables
self.variables = {}
clear_vars = clear_variables
def remove_variable(self, variable: str):
"""Removes a variable from the engine."""
_variable = str(variable)
if not _variable in self.variables:
raise type_error(f'There is no such variable: "{variable}".')
del self.variables[_variable]
remove_var = remove_variable
def process(self, string: str):
"""Processes a string, replaces variables with its values."""
result = None
for (variable, value) in self.variables.items():
if not result:
result = str(string)
_variable = f'{self.prefix}{variable}{self.suffix}'
result = result.replace(_variable, value)
return result
|
class Solution:
def canBeTypedWords(self, text: str, brokenLetters: str) -> int:
result = 0
words = text.split(" ")
set_chars = set(brokenLetters)
for i in words:
set_word = set(i)
sub = set_word - set_chars
if len(set_word) == len(sub):
result += 1
return result
s = Solution()
print(s.canBeTypedWords("hello world", "ad"))
print(s.canBeTypedWords("leet code", "lt"))
print(s.canBeTypedWords("leet code", "e"))
print(s.canBeTypedWords("assembly is the best", "z"))
|
class Solution:
def can_be_typed_words(self, text: str, brokenLetters: str) -> int:
result = 0
words = text.split(' ')
set_chars = set(brokenLetters)
for i in words:
set_word = set(i)
sub = set_word - set_chars
if len(set_word) == len(sub):
result += 1
return result
s = solution()
print(s.canBeTypedWords('hello world', 'ad'))
print(s.canBeTypedWords('leet code', 'lt'))
print(s.canBeTypedWords('leet code', 'e'))
print(s.canBeTypedWords('assembly is the best', 'z'))
|
#Decorator Pattern
def my_decorator(func):
def wrap_func(*args, **kwargs):
print("**********")
func(*args, **kwargs)
print("**********")
return wrap_func
@my_decorator
def hello(greeting,emoji, withLove="your love"):
print(greeting,emoji, withLove)
hello('yo yo', '<3')
|
def my_decorator(func):
def wrap_func(*args, **kwargs):
print('**********')
func(*args, **kwargs)
print('**********')
return wrap_func
@my_decorator
def hello(greeting, emoji, withLove='your love'):
print(greeting, emoji, withLove)
hello('yo yo', '<3')
|
"""
Write a function to detect if a string is valid or not
"abc_123{}"
"{abc_123}"
"abc_{1}23"
"abc_123{()}()"
"abc_123{()}[()]&"
invalid
"}abc_123{"
"abc_123{"
"ab{[}]"
Raise exception which has the position at which the error occured.
"""
class RaiseException(Exception):
pass
def validate(text):
"""
>>> validate('abc_123')
True
>>> validate('-=*')
False
"""
valid_brackets = {
'{': '}',
'(': ')',
'[': ']',
'<': '>'
}
stack = []
for index, each_char in enumerate(text):
flag = True
if each_char.isalnum() or each_char in '_&':
continue
if each_char in valid_brackets.keys():
stack.append((index,each_char))
continue
if stack and each_char in valid_brackets.values():
temp_char = stack.pop()
if not (each_char == valid_brackets.get(temp_char[1])):
flag = False
continue
else:
flag = False
if not flag:
raise RaiseException('Error at postition {} of input "{}"'.format(index, text))
if stack:
raise RaiseException('Error at postition {} of input "{}"'.format(stack[-1][0], text))
return True
assert True == validate('{')
assert True == validate('abc_123{}&')
assert False == validate('{abc_123}')
assert True == validate('[ab(c_1)23]()[({})]')
assert False == validate('{{abc_123}')
assert False == validate('{abc_123}[(])')
assert True == validate('a{bc_123}4')
assert False == validate('a{bc_123}4-')
print(validate('{'))
|
"""
Write a function to detect if a string is valid or not
"abc_123{}"
"{abc_123}"
"abc_{1}23"
"abc_123{()}()"
"abc_123{()}[()]&"
invalid
"}abc_123{"
"abc_123{"
"ab{[}]"
Raise exception which has the position at which the error occured.
"""
class Raiseexception(Exception):
pass
def validate(text):
"""
>>> validate('abc_123')
True
>>> validate('-=*')
False
"""
valid_brackets = {'{': '}', '(': ')', '[': ']', '<': '>'}
stack = []
for (index, each_char) in enumerate(text):
flag = True
if each_char.isalnum() or each_char in '_&':
continue
if each_char in valid_brackets.keys():
stack.append((index, each_char))
continue
if stack and each_char in valid_brackets.values():
temp_char = stack.pop()
if not each_char == valid_brackets.get(temp_char[1]):
flag = False
continue
else:
flag = False
if not flag:
raise raise_exception('Error at postition {} of input "{}"'.format(index, text))
if stack:
raise raise_exception('Error at postition {} of input "{}"'.format(stack[-1][0], text))
return True
assert True == validate('{')
assert True == validate('abc_123{}&')
assert False == validate('{abc_123}')
assert True == validate('[ab(c_1)23]()[({})]')
assert False == validate('{{abc_123}')
assert False == validate('{abc_123}[(])')
assert True == validate('a{bc_123}4')
assert False == validate('a{bc_123}4-')
print(validate('{'))
|
# Copyright (c) 2017-2018 CRS4
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
# and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all copies or
# substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
# INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
# AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
# DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
CONFIRM_ACTIONS = (
'add',
'delete'
)
ERRORS_MESSAGE = {
'MISSING_PARAM': 'Missing parameters',
'UNKNOWN_ACTION': 'Unknown action',
'INVALID_CONFIRMATION_CODE': 'Confirmation code not valid',
'INVALID_FR_STATUS': 'Invalid flow request status',
'EXPIRED_CONFIRMATION_ID': 'Confirmation code expired',
'INVALID_CONSENT_STATUS': 'Invalid consent status',
'UNKNOWN_CONSENT': 'Unknown consent',
'INVALID_DATA': 'Invalid parameters',
'MISSING_PERSON_ID': 'Missing person id',
'INTERNAL_GATEWAY_ERROR': 'internal_health_gateway_error',
'INVALID_CONSENT_CLIENT': 'invalid_consent_client',
'CONSENT_CONNECTION_ERROR': 'consent_connection_error',
'INVALID_BACKEND_CLIENT': 'invalid_backend_client',
'BACKEND_CONNECTION_ERROR': 'backend_connection_error',
'ALL_CONSENTS_ALREADY_CREATED': 'all_required_consents_already_created'
}
|
confirm_actions = ('add', 'delete')
errors_message = {'MISSING_PARAM': 'Missing parameters', 'UNKNOWN_ACTION': 'Unknown action', 'INVALID_CONFIRMATION_CODE': 'Confirmation code not valid', 'INVALID_FR_STATUS': 'Invalid flow request status', 'EXPIRED_CONFIRMATION_ID': 'Confirmation code expired', 'INVALID_CONSENT_STATUS': 'Invalid consent status', 'UNKNOWN_CONSENT': 'Unknown consent', 'INVALID_DATA': 'Invalid parameters', 'MISSING_PERSON_ID': 'Missing person id', 'INTERNAL_GATEWAY_ERROR': 'internal_health_gateway_error', 'INVALID_CONSENT_CLIENT': 'invalid_consent_client', 'CONSENT_CONNECTION_ERROR': 'consent_connection_error', 'INVALID_BACKEND_CLIENT': 'invalid_backend_client', 'BACKEND_CONNECTION_ERROR': 'backend_connection_error', 'ALL_CONSENTS_ALREADY_CREATED': 'all_required_consents_already_created'}
|
# Copyright 2018 Jetperch LLC
#
# 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.
"""
The USB backend which must be implemented for each platform type.
This module defines the USB backend. Each target platform
(such as Windows, Mac OS/X and Linux), must implement backend that conforms
to this API.
This API is **not** thread-safe. All methods and functions must be invoked
from a single thread.
"""
class DeviceEvent:
ENDPOINT_CALLBACK_STOP = -1 # a callback indicated that streaming should stop
UNDEFINED = 0
COMMUNICATION_ERROR = 1 # an communicate error that prevents this device from functioning, such as device removal
ENDPOINT_CALLBACK_EXCEPTION = 2 # a callback threw an exception
class DeviceDriverApi:
"""The device driver API.
This API is **not** thread-safe. All methods must be invoked from a
single thread.
"""
def __str__(self):
"""Get the user-friendly device string.
:return: f'{product_id_str}:{serial_number_str}'
:raise IOError: On failure.
WARNING: This function must correctly identify the device BEFORE it
is opened. Therefore, it must only use the information available
from USB enumeration.
"""
raise NotImplementedError()
@property
def serial_number(self):
"""Get the assigned serial number.
:return: The serial number string.
This attribute is valid even before the device is opened.
"""
raise NotImplementedError()
def open(self, event_callback_fn):
"""Open the USB device.
:param event_callback_fn: The function(event, message) to call on
asynchronous events, mostly to allow robust handling of device
errors. "event" is one of the :class:`DeviceEvent` values,
and the message is a more detailed description of the event.
:raise IOError: On failure.
The event_callback_fn may be called asynchronous and from other
threads. The event_callback_fn must implement any thread safety.
"""
raise NotImplementedError()
def close(self):
"""Close the USB device."""
raise NotImplementedError()
def control_transfer_out(self, cbk_fn, recipient, type_, request, value=0, index=0, data=None) -> bool:
"""Perform a control transfer with data from host to device.
:param cbk_fn: The function called with the class:`ControlTransferResponse` result.
This method guarantees that cbk_fn will always be called.
cbk_fn may be called BEFORE exiting this method call.
:param recipient: The recipient which is one of ['device', 'interface', 'endpoint', 'other']
:param type_: The type which is one of ['standard', 'class', 'vendor'].
:param request: The bRequest value.
:param value: The wValue value.
:param index: The wIndex value.
:param data: The optional data to transfer from host to device.
None (default) skips the data phase.
:return: True on pending, False on error.
"""
raise NotImplementedError()
def control_transfer_in(self, cbk_fn, recipient, type_, request, value, index, length) -> bool:
"""Perform a control transfer with data from device to host.
:param cbk_fn: The function called with the class:`ControlTransferResponse` result.
This method guarantees that cbk_fn will always be called.
cbk_fn may be called BEFORE exiting this method call.
:param recipient: The recipient which is one of ['device', 'interface', 'endpoint', 'other']
:param type_: The type which is one of ['standard', 'class', 'vendor'].
:param request: The bRequest value.
:param value: The wValue value.
:param index: The wIndex value.
:param length: The maximum number of bytes to transfer from device to host.
:return: True on pending, False on error.
"""
raise NotImplementedError()
def read_stream_start(self, endpoint_id, transfers, block_size, data_fn, process_fn, stop_fn):
"""Read a stream of data using non-blocking (overlapped) IO.
:param endpoint_id: The target endpoint address.
:param transfers: The number of overlapped transfers to use,
each of block_size bytes.
:param block_size: The length of each block in bytes which must be
a multiple of the maximum packet size for the endpoint.
:param data_fn: The function(data) to call on each block
of data. The data is an np.ndarray(dtype=uint8) containing
the raw bytes received for each USB transaction.
The length of data is normally block_size.
Any value less than block_size is the last transfer
in the transaction.
When the device stops, it calls data_fn(None). The
device can stop "automatically" through errors or when data_fn
returns True. Call :meth:`read_stream_stop` to stop from
the caller.
This function will be called from the device's thread. The
data_fn must return quickly to ensure that the USB stream
is not starved.
In all cases, data_fn should return None or False to continue
streaming. data_fn can return True to stop the transmission.
Most implementations use some form of non-blocking IO with
multiple queue (overlapped) transactions that are pended
early. On stop, additional data may be read before the
transaction fully stops.
:param process_fn: The function process_fn() to call after all
USB endpoints have been recently serviced and data_fn was
called at least once. The function should still be quick,
but it can have more latency than data_fn.
:param stop_fn: The function(event, message) called when this endpoint
stops streaming data. See :class:`DeviceEvent` for allowed event
values.
Use :meth:`read_stream_stop` to stop.
"""
raise NotImplementedError()
def read_stream_stop(self, endpoint_id):
"""Stop a read stream.
:param endpoint_id: The target endpoint address.
When stop is complete, the data_fn provided to read_stream_start will
be called with None.
Use :meth:`read_stream_start` to start.
"""
raise NotImplementedError()
def status(self):
"""Get the current device status.
:return: A dict containing the following structure:
endpoints: {
pipe_id: { name: {value: v, units: u}, ...}
...
}
"""
raise NotImplementedError()
def signal(self):
"""Signal that an external event occurred.
This method allows another thread to cause the wait in process
to activate.
"""
raise NotImplementedError()
def process(self, timeout=None):
"""Process any pending events.
:param timeout: The timeout in float seconds.
This method uses the operating-system specific method to wait on
pending events, such select and WaitForMultipleObjects.
"""
raise NotImplementedError()
class DeviceNotify:
def __init__(self, cbk):
"""Start device insertion/removal notification.
:param cbk: The function called on device insertion or removal. The
arguments are (inserted, info). "inserted" is True on insertion
and False on removal. "info" contains platform-specific details
about the device. In general, the application should rescan for
relevant devices.
"""
pass
def close(self):
"""Close and stop the notifications."""
raise NotImplementedError()
def scan(name: str=None):
"""Scan for attached devices.
:param name: The case-insensitive name of the device to scan.
:return: The list of attached backend :class:`Device` instances.
"""
raise NotImplementedError()
|
"""
The USB backend which must be implemented for each platform type.
This module defines the USB backend. Each target platform
(such as Windows, Mac OS/X and Linux), must implement backend that conforms
to this API.
This API is **not** thread-safe. All methods and functions must be invoked
from a single thread.
"""
class Deviceevent:
endpoint_callback_stop = -1
undefined = 0
communication_error = 1
endpoint_callback_exception = 2
class Devicedriverapi:
"""The device driver API.
This API is **not** thread-safe. All methods must be invoked from a
single thread.
"""
def __str__(self):
"""Get the user-friendly device string.
:return: f'{product_id_str}:{serial_number_str}'
:raise IOError: On failure.
WARNING: This function must correctly identify the device BEFORE it
is opened. Therefore, it must only use the information available
from USB enumeration.
"""
raise not_implemented_error()
@property
def serial_number(self):
"""Get the assigned serial number.
:return: The serial number string.
This attribute is valid even before the device is opened.
"""
raise not_implemented_error()
def open(self, event_callback_fn):
"""Open the USB device.
:param event_callback_fn: The function(event, message) to call on
asynchronous events, mostly to allow robust handling of device
errors. "event" is one of the :class:`DeviceEvent` values,
and the message is a more detailed description of the event.
:raise IOError: On failure.
The event_callback_fn may be called asynchronous and from other
threads. The event_callback_fn must implement any thread safety.
"""
raise not_implemented_error()
def close(self):
"""Close the USB device."""
raise not_implemented_error()
def control_transfer_out(self, cbk_fn, recipient, type_, request, value=0, index=0, data=None) -> bool:
"""Perform a control transfer with data from host to device.
:param cbk_fn: The function called with the class:`ControlTransferResponse` result.
This method guarantees that cbk_fn will always be called.
cbk_fn may be called BEFORE exiting this method call.
:param recipient: The recipient which is one of ['device', 'interface', 'endpoint', 'other']
:param type_: The type which is one of ['standard', 'class', 'vendor'].
:param request: The bRequest value.
:param value: The wValue value.
:param index: The wIndex value.
:param data: The optional data to transfer from host to device.
None (default) skips the data phase.
:return: True on pending, False on error.
"""
raise not_implemented_error()
def control_transfer_in(self, cbk_fn, recipient, type_, request, value, index, length) -> bool:
"""Perform a control transfer with data from device to host.
:param cbk_fn: The function called with the class:`ControlTransferResponse` result.
This method guarantees that cbk_fn will always be called.
cbk_fn may be called BEFORE exiting this method call.
:param recipient: The recipient which is one of ['device', 'interface', 'endpoint', 'other']
:param type_: The type which is one of ['standard', 'class', 'vendor'].
:param request: The bRequest value.
:param value: The wValue value.
:param index: The wIndex value.
:param length: The maximum number of bytes to transfer from device to host.
:return: True on pending, False on error.
"""
raise not_implemented_error()
def read_stream_start(self, endpoint_id, transfers, block_size, data_fn, process_fn, stop_fn):
"""Read a stream of data using non-blocking (overlapped) IO.
:param endpoint_id: The target endpoint address.
:param transfers: The number of overlapped transfers to use,
each of block_size bytes.
:param block_size: The length of each block in bytes which must be
a multiple of the maximum packet size for the endpoint.
:param data_fn: The function(data) to call on each block
of data. The data is an np.ndarray(dtype=uint8) containing
the raw bytes received for each USB transaction.
The length of data is normally block_size.
Any value less than block_size is the last transfer
in the transaction.
When the device stops, it calls data_fn(None). The
device can stop "automatically" through errors or when data_fn
returns True. Call :meth:`read_stream_stop` to stop from
the caller.
This function will be called from the device's thread. The
data_fn must return quickly to ensure that the USB stream
is not starved.
In all cases, data_fn should return None or False to continue
streaming. data_fn can return True to stop the transmission.
Most implementations use some form of non-blocking IO with
multiple queue (overlapped) transactions that are pended
early. On stop, additional data may be read before the
transaction fully stops.
:param process_fn: The function process_fn() to call after all
USB endpoints have been recently serviced and data_fn was
called at least once. The function should still be quick,
but it can have more latency than data_fn.
:param stop_fn: The function(event, message) called when this endpoint
stops streaming data. See :class:`DeviceEvent` for allowed event
values.
Use :meth:`read_stream_stop` to stop.
"""
raise not_implemented_error()
def read_stream_stop(self, endpoint_id):
"""Stop a read stream.
:param endpoint_id: The target endpoint address.
When stop is complete, the data_fn provided to read_stream_start will
be called with None.
Use :meth:`read_stream_start` to start.
"""
raise not_implemented_error()
def status(self):
"""Get the current device status.
:return: A dict containing the following structure:
endpoints: {
pipe_id: { name: {value: v, units: u}, ...}
...
}
"""
raise not_implemented_error()
def signal(self):
"""Signal that an external event occurred.
This method allows another thread to cause the wait in process
to activate.
"""
raise not_implemented_error()
def process(self, timeout=None):
"""Process any pending events.
:param timeout: The timeout in float seconds.
This method uses the operating-system specific method to wait on
pending events, such select and WaitForMultipleObjects.
"""
raise not_implemented_error()
class Devicenotify:
def __init__(self, cbk):
"""Start device insertion/removal notification.
:param cbk: The function called on device insertion or removal. The
arguments are (inserted, info). "inserted" is True on insertion
and False on removal. "info" contains platform-specific details
about the device. In general, the application should rescan for
relevant devices.
"""
pass
def close(self):
"""Close and stop the notifications."""
raise not_implemented_error()
def scan(name: str=None):
"""Scan for attached devices.
:param name: The case-insensitive name of the device to scan.
:return: The list of attached backend :class:`Device` instances.
"""
raise not_implemented_error()
|
class Solution:
def numJewelsInStones(self, J: str, S: str) -> int:
#map = {}
#for i in range(len(J)):
# map[J[i]] = 0
count = 0
for i in range(len(S)):
if str([S[i]][0]) in J: count +=1
return count
J = "aAB"
S = "aAAbbbb"
print(Solution().numJewelsInStones(J, S))
|
class Solution:
def num_jewels_in_stones(self, J: str, S: str) -> int:
count = 0
for i in range(len(S)):
if str([S[i]][0]) in J:
count += 1
return count
j = 'aAB'
s = 'aAAbbbb'
print(solution().numJewelsInStones(J, S))
|
n = int(input())
sum1 = 0
for i in range(1, n + 1):
if n % i == 0:
sum1 += i
print(sum1)
|
n = int(input())
sum1 = 0
for i in range(1, n + 1):
if n % i == 0:
sum1 += i
print(sum1)
|
def MoveManyStepsForward(numberOfSteps):
for everySingleNumberInTheRange in range(numberOfSteps):
env.step(0)
async def main():
MoveManyStepsForward(50)
await sleep()
MoveManyStepsForward(150)
|
def move_many_steps_forward(numberOfSteps):
for every_single_number_in_the_range in range(numberOfSteps):
env.step(0)
async def main():
move_many_steps_forward(50)
await sleep()
move_many_steps_forward(150)
|
def distanceK(self, root, target, K):
conn = collections.defaultdict(list)
def connect(parent, child):
if parent and child:
conn[parent.val].append(child.val)
conn[child.val].append(parent.val)
if child.left: connect(child, child.left)
if child.right: connect(child, child.right)
connect(None, root)
bfs = [target.val]
seen = set(bfs)
for i in xrange(K):
bfs = [y for x in bfs for y in conn[x] if y not in seen]
seen |= set(bfs)
return bfs
|
def distance_k(self, root, target, K):
conn = collections.defaultdict(list)
def connect(parent, child):
if parent and child:
conn[parent.val].append(child.val)
conn[child.val].append(parent.val)
if child.left:
connect(child, child.left)
if child.right:
connect(child, child.right)
connect(None, root)
bfs = [target.val]
seen = set(bfs)
for i in xrange(K):
bfs = [y for x in bfs for y in conn[x] if y not in seen]
seen |= set(bfs)
return bfs
|
#!/usr/local/bin/python
# encoding: utf-8
"""
*Code elements for TBS htmlframework*
:Author:
David Young
:Date Created:
April 16, 2013
:dryx syntax:
- ``xxx`` = come back here and do some more work
- ``_someObject`` = a 'private' object that should only be changed for debugging
:Notes:
- If you have any questions requiring this script please email me: davidrobertyoung@gmail.com
"""
###################################################################
# CLASSES #
###################################################################
###################################################################
# PUBLIC FUNCTIONS #
###################################################################
# LAST MODIFIED : April 16, 2013
# CREATED : April 16, 2013
# AUTHOR : DRYX
def code(
content="",
inline=True,
scroll=False):
"""
*Generate a code section*
**Key Arguments:**
- ``content`` -- the content of the code block
- ``inline`` -- inline or block?
- ``scroll`` -- give the block a scroll bar on y-axis?
**Return:**
- ``code`` -- the code section
"""
################ > IMPORTS ################
## STANDARD LIB ##
## THIRD PARTY ##
## LOCAL APPLICATION ##
################ >ACTION(S) ################
if scroll:
scroll = "pre-scrollable"
else:
scroll = ""
if inline:
code = """<code>%(content)s</code>""" % locals()
else:
code = """
<pre class="%(scroll)s"><code>%(content)s</code></pre>""" % locals()
return code
###################################################################
# PRIVATE (HELPER) FUNCTIONS #
###################################################################
###################################################################
# TEMPLATE FUNCTIONS #
###################################################################
|
"""
*Code elements for TBS htmlframework*
:Author:
David Young
:Date Created:
April 16, 2013
:dryx syntax:
- ``xxx`` = come back here and do some more work
- ``_someObject`` = a 'private' object that should only be changed for debugging
:Notes:
- If you have any questions requiring this script please email me: davidrobertyoung@gmail.com
"""
def code(content='', inline=True, scroll=False):
"""
*Generate a code section*
**Key Arguments:**
- ``content`` -- the content of the code block
- ``inline`` -- inline or block?
- ``scroll`` -- give the block a scroll bar on y-axis?
**Return:**
- ``code`` -- the code section
"""
if scroll:
scroll = 'pre-scrollable'
else:
scroll = ''
if inline:
code = '<code>%(content)s</code>' % locals()
else:
code = '\n <pre class="%(scroll)s"><code>%(content)s</code></pre>' % locals()
return code
|
entries = [
{
'env-title': 'atari-enduro',
'score': 0.0,
},
{
'env-title': 'atari-space-invaders',
'score': 656.91,
},
{
'env-title': 'atari-qbert',
'score': 6433.38,
},
{
'env-title': 'atari-seaquest',
'score': 1065.98,
},
{
'env-title': 'atari-pong',
'score': 3.11,
},
{
'env-title': 'atari-beam-rider',
'score': 1959.22,
},
{
'env-title': 'atari-breakout',
'score': 82.94,
},
]
|
entries = [{'env-title': 'atari-enduro', 'score': 0.0}, {'env-title': 'atari-space-invaders', 'score': 656.91}, {'env-title': 'atari-qbert', 'score': 6433.38}, {'env-title': 'atari-seaquest', 'score': 1065.98}, {'env-title': 'atari-pong', 'score': 3.11}, {'env-title': 'atari-beam-rider', 'score': 1959.22}, {'env-title': 'atari-breakout', 'score': 82.94}]
|
name = "fRoDo"
lowercase_name = name.lower()
uppercase_name = name.upper()
titlecase_name = name.title()
print(lowercase_name, uppercase_name, titlecase_name)
|
name = 'fRoDo'
lowercase_name = name.lower()
uppercase_name = name.upper()
titlecase_name = name.title()
print(lowercase_name, uppercase_name, titlecase_name)
|
# -*- coding: utf-8 -*-
"""
Created on Sun Dec 8 11:35:38 2019
@author: john
"""
def intcode(input_list, l):
l = [int(x) for x in l] # Convert list values to ints
end = False # set up a condition for the while
pointer = 0 # initialize the pointer to the first position
# Enter the while loop. Continues as long as end is false,
# and hitting operation 99 sets end to true.
while not end:
instruct = str(l[pointer]).rjust(5,'0')
operation = instruct[len(instruct)-2:]
# Do a little error-handling: break if the mode parameter is invalid for a or b
if(int(instruct[2])>1):
print("A_MODE INVALID\nPointer: "+str(pointer)+", Instruction: "+instruct+"\n")
break
if(int(instruct[1])>1):
print("B_MODE INVALID\nPointer: "+str(pointer)+", Instruction: "+instruct+"\n")
break
# Safe because error-handling above means instruct[1] and [2] _must_ be 0 or 1.
# This absolutely will assign values that are outside of the scope of the command
# but since they won't be used who cares.
if operation in ('01','02','05','06','07','08'):
a_val = l[l[pointer+1]] if instruct[2]=='0' else l[pointer+1]
if operation in ('01','02','05','06','07','08'):
b_val = l[l[pointer+2]] if instruct[1]=='0' else l[pointer+2]
# Run through the possible operations. 99: end.
if operation == '99':
end = True
# 01: add and place
elif operation == '01':
l[l[pointer+3]] = a_val + b_val
pointer += 4
# 02: multiply and place
elif operation == '02':
l[l[pointer+3]] = a_val * b_val
pointer += 4
# 03: input
elif operation == '03':
l[l[pointer+1]] = int(input_list.pop(0))
pointer += 2
# 04: return
elif operation == '04':
ret = l[l[pointer+1]]
pointer += 2
# 05: jump-if-true
elif operation == '05':
if a_val != 0:
pointer = b_val
else:
pointer += 3
# 06: jump-if-false
elif operation == '06':
if a_val == 0:
pointer = b_val
else:
pointer += 3
# 07: less-than flag
elif operation == '07':
if a_val < b_val:
l[l[pointer+3]] = 1
else:
l[l[pointer+3]] = 0
pointer += 4
# 08: equals flag
elif operation == '08':
if a_val == b_val:
l[l[pointer+3]] = 1
else:
l[l[pointer+3]] = 0
pointer += 4
return ret
# Read the parameter permutations in
with open('permutations.txt') as f:
param_list = f.readlines()
# Format it to how I want it
param_list = [i.strip().strip('\"') for i in param_list][1:]
# Read the program in, five times
with open('input.txt') as f:
program = f.readlines()[0].split(',')
# Make it into an instruction list
p1 = [int(i.strip()) for i in program]
p2 = [int(i.strip()) for i in program]
p3 = [int(i.strip()) for i in program]
p4 = [int(i.strip()) for i in program]
p5 = [int(i.strip()) for i in program]
# Make a place for the results
results = []
# Loop through the permutations
for p in param_list:
input_val = 0
input_list = [p[0],input_val]
new_val = intcode(input_list, p1)
new_list = [p[1],new_val]
new_val = intcode(new_list, p2)
new_list = [p[2],new_val]
new_val = intcode(new_list, p3)
new_list = [p[3], new_val]
new_val = intcode(new_list, p4)
new_list = [p[4], new_val]
new_val = intcode(new_list, p5)
results.append([new_val, p])
# Pull the max output
best_param = [i[1] for i in results if i[0] == max([j[0] for j in results])]
|
"""
Created on Sun Dec 8 11:35:38 2019
@author: john
"""
def intcode(input_list, l):
l = [int(x) for x in l]
end = False
pointer = 0
while not end:
instruct = str(l[pointer]).rjust(5, '0')
operation = instruct[len(instruct) - 2:]
if int(instruct[2]) > 1:
print('A_MODE INVALID\nPointer: ' + str(pointer) + ', Instruction: ' + instruct + '\n')
break
if int(instruct[1]) > 1:
print('B_MODE INVALID\nPointer: ' + str(pointer) + ', Instruction: ' + instruct + '\n')
break
if operation in ('01', '02', '05', '06', '07', '08'):
a_val = l[l[pointer + 1]] if instruct[2] == '0' else l[pointer + 1]
if operation in ('01', '02', '05', '06', '07', '08'):
b_val = l[l[pointer + 2]] if instruct[1] == '0' else l[pointer + 2]
if operation == '99':
end = True
elif operation == '01':
l[l[pointer + 3]] = a_val + b_val
pointer += 4
elif operation == '02':
l[l[pointer + 3]] = a_val * b_val
pointer += 4
elif operation == '03':
l[l[pointer + 1]] = int(input_list.pop(0))
pointer += 2
elif operation == '04':
ret = l[l[pointer + 1]]
pointer += 2
elif operation == '05':
if a_val != 0:
pointer = b_val
else:
pointer += 3
elif operation == '06':
if a_val == 0:
pointer = b_val
else:
pointer += 3
elif operation == '07':
if a_val < b_val:
l[l[pointer + 3]] = 1
else:
l[l[pointer + 3]] = 0
pointer += 4
elif operation == '08':
if a_val == b_val:
l[l[pointer + 3]] = 1
else:
l[l[pointer + 3]] = 0
pointer += 4
return ret
with open('permutations.txt') as f:
param_list = f.readlines()
param_list = [i.strip().strip('"') for i in param_list][1:]
with open('input.txt') as f:
program = f.readlines()[0].split(',')
p1 = [int(i.strip()) for i in program]
p2 = [int(i.strip()) for i in program]
p3 = [int(i.strip()) for i in program]
p4 = [int(i.strip()) for i in program]
p5 = [int(i.strip()) for i in program]
results = []
for p in param_list:
input_val = 0
input_list = [p[0], input_val]
new_val = intcode(input_list, p1)
new_list = [p[1], new_val]
new_val = intcode(new_list, p2)
new_list = [p[2], new_val]
new_val = intcode(new_list, p3)
new_list = [p[3], new_val]
new_val = intcode(new_list, p4)
new_list = [p[4], new_val]
new_val = intcode(new_list, p5)
results.append([new_val, p])
best_param = [i[1] for i in results if i[0] == max([j[0] for j in results])]
|
'''
priceIsRight = 15
if priceIsRight:
print("Price is too low!")
if priceIsRight:
print("Price is almost there!")
if priceIsRight:
print("Price is exactly that!")
if priceIsRight:
print("Price is too high!")
'''
priceIsRight = int(input("Enter your number: "))
if priceIsRight < 5:
print("Price is almost there!")
elif priceIsRight >= 5 and priceIsRight <= 9:
print("Price is almost there!")
elif priceIsRight == 10:
print("Price is exactly that!")
else:
print("Price is too high!")
|
"""
priceIsRight = 15
if priceIsRight:
print("Price is too low!")
if priceIsRight:
print("Price is almost there!")
if priceIsRight:
print("Price is exactly that!")
if priceIsRight:
print("Price is too high!")
"""
price_is_right = int(input('Enter your number: '))
if priceIsRight < 5:
print('Price is almost there!')
elif priceIsRight >= 5 and priceIsRight <= 9:
print('Price is almost there!')
elif priceIsRight == 10:
print('Price is exactly that!')
else:
print('Price is too high!')
|
# Copyright (c) 2019-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
#
def f_gold ( arr1 , arr2 , m , n , x ) :
count , l , r = 0 , 0 , n - 1
while ( l < m and r >= 0 ) :
if ( ( arr1 [ l ] + arr2 [ r ] ) == x ) :
l += 1
r -= 1
count += 1
elif ( ( arr1 [ l ] + arr2 [ r ] ) < x ) :
l += 1
else :
r -= 1
return count
#TOFILL
if __name__ == '__main__':
param = [
([5, 5, 7, 10, 14, 14, 17, 21, 32, 34, 37, 40, 40, 40, 46, 46, 50, 50, 51, 55, 57, 62, 65, 67, 67, 69, 70, 70, 72, 73, 76, 77, 77, 78, 84, 85, 85, 86, 87, 88, 88, 89, 89, 90, 93, 99],[2, 5, 8, 8, 10, 12, 13, 15, 17, 18, 20, 20, 21, 27, 28, 31, 34, 37, 40, 46, 48, 52, 53, 54, 54, 58, 59, 60, 66, 68, 68, 69, 70, 71, 72, 73, 77, 77, 80, 84, 84, 92, 92, 95, 97, 97],28,29,23,),
([-84, 52, -34, 96, 16, 92, -64, -74],[-22, 26, -12, -54, 66, 86, 38, 76],6,5,7,),
([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],37,26,42,),
([60, 92, 42, 83, 55, 76, 29, 62],[71, 2, 74, 42, 80, 71, 26, 76],4,7,7,),
([-94, -94, -58, -40, -40, -26, -24, -22, -22, -22, -2, 0, 4, 8, 12, 16, 16, 18, 22, 32, 42, 44, 50, 58, 64, 78, 80, 90],[-86, -84, -78, -76, -72, -70, -62, -58, -54, -54, -50, -46, -44, -40, -30, -28, -16, -10, 10, 36, 36, 48, 70, 84, 84, 90, 94, 98],17,27,17,),
([0, 0, 1, 1, 1, 0, 0, 1, 1, 1],[1, 1, 1, 0, 1, 1, 0, 0, 0, 0],5,8,9,),
([1, 5, 7, 7, 7, 14, 15, 16, 17, 18, 18, 19, 20, 25, 27, 31, 36, 42, 47, 51, 56, 56, 56, 58, 58, 59, 63, 63, 63, 65, 66, 67, 76, 83, 93, 94, 97],[2, 3, 7, 8, 9, 10, 17, 18, 21, 28, 29, 29, 33, 35, 46, 47, 47, 49, 49, 49, 53, 56, 58, 59, 59, 60, 65, 67, 70, 78, 81, 85, 85, 87, 90, 92, 96],28,34,31,),
([78, -74, 52, 56, -8, 92, 14, 56, -72, -92, 32, -94, -26, -8, -66, 72, -24, 36, -84, -4, -68, 14, 78, 40, -82, -10, 16, 56, 6, -16, 30, 24, -32],[-74, 22, -14, -2, 36, 86, -70, -20, -76, -84, -40, -36, 42, 22, -60, -94, -18, 8, -14, -42, -68, 62, -60, 2, 40, -66, 68, 96, 70, 98, -38, -74, -92],16,30,24,),
([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],25,33,33,),
([17, 50, 65, 4, 19, 10, 45, 70, 76, 81, 28, 97, 55, 70, 38, 2, 40, 67, 36, 33, 6, 85, 25],[78, 92, 65, 23, 7, 94, 18, 4, 2, 53, 31, 58, 98, 18, 46, 16, 17, 92, 80, 92, 43, 70, 50],16,22,22,)
]
n_success = 0
for i, parameters_set in enumerate(param):
if f_filled(*parameters_set) == f_gold(*parameters_set):
n_success+=1
print("#Results: %i, %i" % (n_success, len(param)))
|
def f_gold(arr1, arr2, m, n, x):
(count, l, r) = (0, 0, n - 1)
while l < m and r >= 0:
if arr1[l] + arr2[r] == x:
l += 1
r -= 1
count += 1
elif arr1[l] + arr2[r] < x:
l += 1
else:
r -= 1
return count
if __name__ == '__main__':
param = [([5, 5, 7, 10, 14, 14, 17, 21, 32, 34, 37, 40, 40, 40, 46, 46, 50, 50, 51, 55, 57, 62, 65, 67, 67, 69, 70, 70, 72, 73, 76, 77, 77, 78, 84, 85, 85, 86, 87, 88, 88, 89, 89, 90, 93, 99], [2, 5, 8, 8, 10, 12, 13, 15, 17, 18, 20, 20, 21, 27, 28, 31, 34, 37, 40, 46, 48, 52, 53, 54, 54, 58, 59, 60, 66, 68, 68, 69, 70, 71, 72, 73, 77, 77, 80, 84, 84, 92, 92, 95, 97, 97], 28, 29, 23), ([-84, 52, -34, 96, 16, 92, -64, -74], [-22, 26, -12, -54, 66, 86, 38, 76], 6, 5, 7), ([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], 37, 26, 42), ([60, 92, 42, 83, 55, 76, 29, 62], [71, 2, 74, 42, 80, 71, 26, 76], 4, 7, 7), ([-94, -94, -58, -40, -40, -26, -24, -22, -22, -22, -2, 0, 4, 8, 12, 16, 16, 18, 22, 32, 42, 44, 50, 58, 64, 78, 80, 90], [-86, -84, -78, -76, -72, -70, -62, -58, -54, -54, -50, -46, -44, -40, -30, -28, -16, -10, 10, 36, 36, 48, 70, 84, 84, 90, 94, 98], 17, 27, 17), ([0, 0, 1, 1, 1, 0, 0, 1, 1, 1], [1, 1, 1, 0, 1, 1, 0, 0, 0, 0], 5, 8, 9), ([1, 5, 7, 7, 7, 14, 15, 16, 17, 18, 18, 19, 20, 25, 27, 31, 36, 42, 47, 51, 56, 56, 56, 58, 58, 59, 63, 63, 63, 65, 66, 67, 76, 83, 93, 94, 97], [2, 3, 7, 8, 9, 10, 17, 18, 21, 28, 29, 29, 33, 35, 46, 47, 47, 49, 49, 49, 53, 56, 58, 59, 59, 60, 65, 67, 70, 78, 81, 85, 85, 87, 90, 92, 96], 28, 34, 31), ([78, -74, 52, 56, -8, 92, 14, 56, -72, -92, 32, -94, -26, -8, -66, 72, -24, 36, -84, -4, -68, 14, 78, 40, -82, -10, 16, 56, 6, -16, 30, 24, -32], [-74, 22, -14, -2, 36, 86, -70, -20, -76, -84, -40, -36, 42, 22, -60, -94, -18, 8, -14, -42, -68, 62, -60, 2, 40, -66, 68, 96, 70, 98, -38, -74, -92], 16, 30, 24), ([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], 25, 33, 33), ([17, 50, 65, 4, 19, 10, 45, 70, 76, 81, 28, 97, 55, 70, 38, 2, 40, 67, 36, 33, 6, 85, 25], [78, 92, 65, 23, 7, 94, 18, 4, 2, 53, 31, 58, 98, 18, 46, 16, 17, 92, 80, 92, 43, 70, 50], 16, 22, 22)]
n_success = 0
for (i, parameters_set) in enumerate(param):
if f_filled(*parameters_set) == f_gold(*parameters_set):
n_success += 1
print('#Results: %i, %i' % (n_success, len(param)))
|
# coding: utf-8
# BlackSmith general configuration file
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
# Jabber server to connect
SERVER = 'example.com'
# Connecting Port
PORT = 5222
# Jabber server`s connecting Host
HOST = 'example.com'
# Using TLS (True - to enable, False - to disable)
SECURE = True
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
# User`s account
USERNAME = 'username'
# Jabber ID`s Password
PASSWORD = 'password'
# Resourse (please don`t touch it)
RESOURCE = u'simpleApps' # You can write unicode symbols here
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
# Default chatroom nick
DEFAULT_NICK = u'BlackSmith-m.1' # You can write unicode symbols here
# Groupchat message size limit
CHAT_MSG_LIMIT = 1024
# Private/Roster message size limit
PRIV_MSG_LIMIT = 2024
# Incoming message size limit
INC_MSG_LIMIT = 8960
# Working without rights of moder (True - to enable, False - to disable)
MSERVE = False
# Jabber account of bot`s owner
BOSS = 'boss@example.com'
# Memory usage limit (size in kilobytes, 0 - not limited)
MEMORY_LIMIT = 49152
# Admin password, used as a key to command "login"
BOSS_PASS = ''
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
|
server = 'example.com'
port = 5222
host = 'example.com'
secure = True
username = 'username'
password = 'password'
resource = u'simpleApps'
default_nick = u'BlackSmith-m.1'
chat_msg_limit = 1024
priv_msg_limit = 2024
inc_msg_limit = 8960
mserve = False
boss = 'boss@example.com'
memory_limit = 49152
boss_pass = ''
|
# -----------------------------------------------------------------------------
# This piece of work is inspired by Pollere' VerSec:
# https://github.com/pollere/DCT
# But this code is implemented independently without using any line of the
# original one, and released under Apache License.
#
# Copyright (C) 2019-2022 The python-ndn authors
#
# This file is part of python-ndn.
#
# 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.
# -----------------------------------------------------------------------------
lvs_grammar = r'''
?start: file_input
TAG_IDENT: CNAME
RULE_IDENT: "#" CNAME
FN_IDENT: "$" CNAME
name: "/"? component ("/" component)*
component: STR -> component_from_str
| TAG_IDENT -> tag_id
| RULE_IDENT -> rule_id
definition: RULE_IDENT ":" def_expr
def_expr: name ("&" comp_constraints)? ("<=" sign_constraints)?
sign_constraints: RULE_IDENT ("|" RULE_IDENT)*
comp_constraints: cons_set ("|" cons_set)*
cons_set: "{" cons_term ("," cons_term)* "}"
cons_term: TAG_IDENT ":" cons_expr
cons_expr: cons_option ("|" cons_option)*
cons_option: STR -> component_from_str
| TAG_IDENT -> tag_id
| FN_IDENT "(" fn_args ")" -> fn_call
fn_args: (STR | TAG_IDENT)? ("," (STR | TAG_IDENT))*
file_input: definition*
%import common (DIGIT, LETTER, WS, CNAME, CPP_COMMENT)
%import common.ESCAPED_STRING -> STR
%ignore WS
%ignore CPP_COMMENT
'''
|
lvs_grammar = '\n ?start: file_input\n\n TAG_IDENT: CNAME\n RULE_IDENT: "#" CNAME\n FN_IDENT: "$" CNAME\n\n name: "/"? component ("/" component)*\n component: STR -> component_from_str\n | TAG_IDENT -> tag_id\n | RULE_IDENT -> rule_id\n\n definition: RULE_IDENT ":" def_expr\n def_expr: name ("&" comp_constraints)? ("<=" sign_constraints)?\n sign_constraints: RULE_IDENT ("|" RULE_IDENT)*\n comp_constraints: cons_set ("|" cons_set)*\n cons_set: "{" cons_term ("," cons_term)* "}"\n cons_term: TAG_IDENT ":" cons_expr\n cons_expr: cons_option ("|" cons_option)*\n cons_option: STR -> component_from_str\n | TAG_IDENT -> tag_id\n | FN_IDENT "(" fn_args ")" -> fn_call\n fn_args: (STR | TAG_IDENT)? ("," (STR | TAG_IDENT))*\n\n file_input: definition*\n\n %import common (DIGIT, LETTER, WS, CNAME, CPP_COMMENT)\n %import common.ESCAPED_STRING -> STR\n\n %ignore WS\n %ignore CPP_COMMENT\n'
|
#!/usr/bin/env python
# -*- coding: utf-8; -*-
# Copyright (c) 2022 Oracle and/or its affiliates.
# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/
DEFAULT_OCI_CONFIG_FILE = "~/.oci/config"
DEFAULT_PROFILE = "DEFAULT"
DEFAULT_CONDA_PACK_FOLDER = "~/conda"
CONDA_PACK_OS_PREFIX_FORMAT = "oci://<bucket>@<namespace>/<prefix>"
DEFAULT_ADS_CONFIG_FOLDER = "~/.ads_ops"
OPS_IMAGE_BASE = "ads-operators-base"
ML_JOB_IMAGE = "ml-job"
ML_JOB_GPU_IMAGE = "ml-job-gpu"
OPS_IMAGE_GPU_BASE = "ads-operators-gpu-base"
DEFAULT_MANIFEST_VERSION = "1.0"
ADS_CONFIG_FILE_NAME = "config.ini"
ADS_JOBS_CONFIG_FILE_NAME = "ml_job_config.ini"
ADS_DATAFLOW_CONFIG_FILE_NAME = "dataflow_config.ini"
DEFAULT_IMAGE_HOME_DIR = "/home/datascience"
DEFAULT_IMAGE_SCRIPT_DIR = "/etc/datascience"
DEFAULT_IMAGE_CONDA_DIR = "/opt/conda/envs"
DEFAULT_NOTEBOOK_SESSION_SPARK_CONF_DIR = "/home/datascience/spark_conf_dir"
DEFAULT_NOTEBOOK_SESSION_CONDA_DIR = "/home/datascience/conda"
ADS_DATAFLOW_CONFIG_FILE_NAME = "dataflow_config.ini"
|
default_oci_config_file = '~/.oci/config'
default_profile = 'DEFAULT'
default_conda_pack_folder = '~/conda'
conda_pack_os_prefix_format = 'oci://<bucket>@<namespace>/<prefix>'
default_ads_config_folder = '~/.ads_ops'
ops_image_base = 'ads-operators-base'
ml_job_image = 'ml-job'
ml_job_gpu_image = 'ml-job-gpu'
ops_image_gpu_base = 'ads-operators-gpu-base'
default_manifest_version = '1.0'
ads_config_file_name = 'config.ini'
ads_jobs_config_file_name = 'ml_job_config.ini'
ads_dataflow_config_file_name = 'dataflow_config.ini'
default_image_home_dir = '/home/datascience'
default_image_script_dir = '/etc/datascience'
default_image_conda_dir = '/opt/conda/envs'
default_notebook_session_spark_conf_dir = '/home/datascience/spark_conf_dir'
default_notebook_session_conda_dir = '/home/datascience/conda'
ads_dataflow_config_file_name = 'dataflow_config.ini'
|
"""
File: boggle.py
Name:
----------------------------------------
TODO:
"""
# This is the file name of the dictionary txt file
# we will be checking if a word exists by searching through it
FILE = 'dictionary.txt'
dict_list = []
final = []
def main():
"""
TODO:
"""
read_dictionary()
temp = ''
word_lst = []
for i in range(4):
while True:
row = input(str(i + 1) + ' row of letters: ')
ch = row.split()
if len(ch)!= 4 or len(ch[0])!=1 or len(ch[1])!=1 or len(ch[2])!=1 or len(ch[3])!=1:
print('illegal input')
else:
break
for j in range(4):
word_lst.append(ch[j])
for start in range(16):
temp = word_lst[start]
word_lst[start] = ''
find_word(word_lst,[temp],start)
word_lst[start] = temp
print(f'There are {len(final)} words in total.')
def find_word(word_lst,current,now):
if now == 0 or now ==4 or now == 8 or now == 12:
nums = [-4,-3,1,4,5,1000]
elif now ==1 or now ==5 or now ==9 or now ==13 or now ==2 or now ==6 or now ==10 or now ==14 :
nums = [-5, -4, -3, -1, 1, 3, 4, 5,1000]
elif now == 3 or now == 7 or now == 11 or now ==15:
nums =[-5,-4,-1,3,4,1000]
# print(current)
temp = ''
temp2 = ''
a = ''
for word in current:
a+=word
for dict in dict_list:
if len(dict)>=4:
if dict == a:
if a not in final:
final.append(a)
print('Found "'+a+'"')
for num in nums:
# credential = 0
# if 16 > (now+num) > 0:
# if word_lst[now+num] != '':
# credential = 1
# if credential == 0:
# pass
# print(num)
if num > 100:
break
else:
# for num in nums:
# print('now:',now)
# print(num)
# print(word_lst,current)
if 0 <= now + num < 16:
if word_lst[now+num] != '':
temp=''
for ch in current:
temp += ch
# print(word_lst)
# print(temp+word_lst[now+num])
if has_prefix(temp+word_lst[now+num]):
current.append(word_lst[now+num])
temp2 = word_lst[now+num]
word_lst[now+num] = ''
find_word(word_lst,current,now+num)
word_lst[now+num] = temp2
current.pop()
# print('--')
# print(word_lst)
# print(current)
# print('--')
'roof coif hoof '
# nums = [-5,-1,-1,-1,1,3,4,5]
# a = 0
# temp=''
# sub=''
# a=''
# for ch in word_lst:
# if ch != '':
# a =1
# if a == 0:
# print(current)
# else:
# for i in range(16):
# if word_lst[i] != '':
# current.append(word_lst[i])
# a = word_lst[i]
# word_lst[i] = ''
# for num in nums:
# if 0 < i+num < 16:
# if word_lst[i+num] != '':
# for ch in current:
# temp += ch
# if has_prefix(temp+word_lst[i+num]):
# print('-----------')
# print(temp+word_lst[i+num])
# print('-----------')
# current.append(word_lst[i+num])
# sub = word_lst[i+num]
# word_lst[i+num] = ''
# find_word(word_lst,current)
# else:
# word_lst[i+num] = ''
# if len(current)!=0:
# current.pop()
# word_lst[i+num] = sub
# word_lst[i] = a
# if len(current) != 0:
# current.pop()
# print(i)
def read_dictionary():
"""
This function reads file "dictionary.txt" stored in FILE
and appends words in each line into a Python list
"""
with open(FILE, 'r') as f:
for line in f:
word = line.strip()
dict_list.append(word)
def has_prefix(sub_s):
"""
:param sub_s: (str) A substring that is constructed by neighboring letters on a 4x4 square grid
:return: (bool) If there is any words with prefix stored in sub_s
"""
for word in dict_list:
if word.startswith(sub_s):
return True
return False
if __name__ == '__main__':
main()
|
"""
File: boggle.py
Name:
----------------------------------------
TODO:
"""
file = 'dictionary.txt'
dict_list = []
final = []
def main():
"""
TODO:
"""
read_dictionary()
temp = ''
word_lst = []
for i in range(4):
while True:
row = input(str(i + 1) + ' row of letters: ')
ch = row.split()
if len(ch) != 4 or len(ch[0]) != 1 or len(ch[1]) != 1 or (len(ch[2]) != 1) or (len(ch[3]) != 1):
print('illegal input')
else:
break
for j in range(4):
word_lst.append(ch[j])
for start in range(16):
temp = word_lst[start]
word_lst[start] = ''
find_word(word_lst, [temp], start)
word_lst[start] = temp
print(f'There are {len(final)} words in total.')
def find_word(word_lst, current, now):
if now == 0 or now == 4 or now == 8 or (now == 12):
nums = [-4, -3, 1, 4, 5, 1000]
elif now == 1 or now == 5 or now == 9 or (now == 13) or (now == 2) or (now == 6) or (now == 10) or (now == 14):
nums = [-5, -4, -3, -1, 1, 3, 4, 5, 1000]
elif now == 3 or now == 7 or now == 11 or (now == 15):
nums = [-5, -4, -1, 3, 4, 1000]
temp = ''
temp2 = ''
a = ''
for word in current:
a += word
for dict in dict_list:
if len(dict) >= 4:
if dict == a:
if a not in final:
final.append(a)
print('Found "' + a + '"')
for num in nums:
if num > 100:
break
elif 0 <= now + num < 16:
if word_lst[now + num] != '':
temp = ''
for ch in current:
temp += ch
if has_prefix(temp + word_lst[now + num]):
current.append(word_lst[now + num])
temp2 = word_lst[now + num]
word_lst[now + num] = ''
find_word(word_lst, current, now + num)
word_lst[now + num] = temp2
current.pop()
'roof coif hoof '
def read_dictionary():
"""
This function reads file "dictionary.txt" stored in FILE
and appends words in each line into a Python list
"""
with open(FILE, 'r') as f:
for line in f:
word = line.strip()
dict_list.append(word)
def has_prefix(sub_s):
"""
:param sub_s: (str) A substring that is constructed by neighboring letters on a 4x4 square grid
:return: (bool) If there is any words with prefix stored in sub_s
"""
for word in dict_list:
if word.startswith(sub_s):
return True
return False
if __name__ == '__main__':
main()
|
INPUT = ">^^v^<>v<<<v<v^>>v^^^<v<>^^><^<<^vv>>>^<<^>><vv<<v^<^^><>>><>v<><>^^<^^^<><>>vv>vv>v<<^>v<>^>v<v^<>v>><>^v<<<<v^vv^><v>v^>>>vv>v^^^<^^<>>v<^^v<>^<vv^^<^><<>^>><^<>>><><vv><>v<<<><><>v><<>^^^^v>>^>^<v<<vv^^<v<^<^>^^v^^^^^v<><^v><<><^v^>v<<>^<>^^v^<>v<v^>v>^^<vv^v><^<>^v<><^><v^><><><<<<>^vv^>^vvvvv><><^<vv^v^v>v<<^<^^v^<>^<vv><v<v^v<<v<<^^>>^^^v^>v<><^vv<<^<>v<v><><v^^><v<>^^>^^>v^>^<<<<v><v<<>v><^v>^>><v^^<^>v<vvvv<>>>>>^v^^>v<v<^<vv>^>^vv^>vv^^v<<^<^^<>v>vv^v>><>>>v^>^>^^v<>^<v<<>^vv>v^<<v>v<<><v>^vvv<v<vvv^v<vv<v^^^>v><<^<>><v^^>^v^>>^v<^<><v<>>v^<>>v<>>v^^^><^>>vvvv>^v<^><<>>^<>^>vv><v<<>>^^>v^^^><^<<^^v>v<^<<>v>^^vvv^v^>v^<>^^<>v^v>v>v<v^>vv>^^v<>v>>^<>><>v>v^<<vvvv<vvv><v^<^>^v<>>^><v>><>^<v>v<v>vv^>>vvv<>v>v<v^>>^>>v<<>^<>^<>>>^v<<<^<^v>vv^>><<><v^>^v^^^v<>^^vv><>><>>^>v^<v<>v<>>^<<^v>^^^<>^v^><>v<<v>vv^>vv<<>>><<^v^<>v<vv>>>^^<>^><<^>vv>>^<<v^^vv<>>><v>v><^<v<<>>>^^<>>^<^v><>vv^^^v>vvv>^><<>^^>^<<v^<v<^v<<>vvv<^<<>^>^v<vv<^>vvv>v>vv^<v^><>>^vv<^^^vv><^vv<v^<><v^vvv><<^>^^><v<<vv^>v<vv<v>^<>^v<<>v<v^v^>^>^>v<<^vvv<<<v>^^>^<<<<>vv>>^<>^>>>v<v>^^<v^<v<>>>vv>^^v<<>>>^^v><<<v<v<^v<>^^><v<^v<<v^><><^<><v<^^v>>><v^^v<<v^><^<><<v^>><^<>v>v^<><^<v>^v^>^>^vv^>^^<<vv^>vv<^vvv<>>^^<^>v^>^>^<v^><v<v>>>v<<<><^v<<><^<vv^v^^^>v<^^<v^vvv<v<><v<vv<^vv<>vv<v^<>>vvvvv<<>^v^v>vv>>>vvv^^<^<^<><>v<v>><^v><^<<<>><<<v>^>v<>^>^v>>^<>v^<^>><<>^<v>^>^^^>^^<v>>>><>^v^v><<<<vv^<vv<>vv>v<>v^<v^>v><>>>v^<><^vvv>vv^<^<<^<^^v>^>>>v<^<^v^^<^<^>>><v>vv>^<<><>^>>v>^<<>><^<>v<>vv^^>^>vvv^v<<^<^^<vv<>^vvv<^^v^vv^>>v<^>^^<v^<>v<^<^vv>v<<vv>vv>^>vvv>>>^^>v<>^v>v^<^>>v>^^v>>>>v^<v>v<^>v<v<<>>^v<^^<v><^<>>^<<vv^>>v<<v>^v<>><^>vv<v<^>>^^<vvvvvvvvv>>>v<v<>v^<>>^vv<v^^v<<^vvv^<<^><>vv<><<>>v>vv^><>>^^v^>>v^v^><<<>>^^<^v<<^<>>>>^<^>v^><<^>v<^v<^>>^^<<<<><^<^v^v<>>^v<^<<vv^<><^^vv><v^v^v>^>>^>^vv^>^v<v^v<<vvv^><>>^v^^><>v>vv><^>>vv<vvv<<<<^<>vvv^v<v>^<v<^>^<^<v<><>v^^^^<<vv<^^vv<v>><<v^><>>><v^>^v><^>^><vv^<><^<v>><<^vv<>>v^<<v<>v><v<><><vv>^>>v^<^<v>^><>>><^><v^v<>>>^^<^>v<v>vvv<>^<<><v^^>^>>v<^v>^>v>>>vv>v>>v^^^<^<vvv^<>^>^<v^<v^v>v>^>vv>vvv<>v<^>v>^^>>^<vv^^v>v^^^^^v^vv><^<><>^>vv<^>>^vvvv^^^>^<vv>^v<<^><^^>^<>^^>^<<v<^>>>^><<^^>v^v>>^>vvvv>^^v><v>>vv><<<vv<^>v>^^^<v>v^vvv<^><<^>^<>^><<<<<v^<<vv^v>^<>v<v>^>^>><>v^v<^vv^^>vv<<v^v>vv^vvv<<<<>^v<v^^v^v>v<<v>^^<>^vv^^>^>^v^vv^>>v^vv^^<vv><<v^v^^v><vv<^vvv<vv^^<<v>v^v^^^^v<^<^>v>^>v>^vv^v^^<v<^vvvv<<<>^<^^^<^^<>^<><vv<^^<<^>>><v^vvvv>^<>>^^>v^^v^<<v^^^<<<><^<v^v^^v<v^<>v><<v<>^v>v<^><^>vv^^<vvv<^v>>v>^<><v^><^^^<v^>>vv<<<<<^<>^v^v>^vv^<>v>v<^>vv<<^vv>vv<v<><>>v>><v<^<^^>><<v^v<<^><v<^<vv<v<<vv^>^<<><^^>^<^>>^<vv>><v<<vvv<^^v^>^^<^v>^v<v<>v><v^v^<<^<><<v<<^v>v<<>>^>v>>v>>v<^<<^<^>>>v>^^^v><^>^^>>v<<>^v><v>vvv^vv<<<>vvv<<>^>>>v<v<v^<^<^>^<^>v^^v<^^<v<>v<>>^^>^v^>v<<<<^<>v^><<<v>>>><<v^<^vv>v>><>>^<<<^<^^>v<>>v<>vv<<^<<><<^>v^^^vv^>vvvv>>v>v^><<v<>vv^<<><<vvv>^>>>^<<<^<^<<v>^>v<>>v>>vv^^><<<<^^^v>><<^><v><v^^><v<<v^^v^^v>>v<><><<>^><v><^<vv>><^v<>v<vvv<>^>><v>>v<^><<v>^<>^v><^><^^<v>^><^^v^<<><>>^>v^<^v^vv<><^>vv^>v^vvv^<>>^><^<^<>^<<v^v<^v><>^v<v>>^>>^v^vv>><vv><v^^<<^v^<>^v<<>^><^>><v>>v<<<v^^vv<>^^v>>><><><<v^<<<v^<^^><v^>v^^vv<v^<>>vv^<^v<>^v>>v^v>v<^^vv><>^v<<>v^<>v^>>v>vvv<^><><^^>^vv^>>v^>^<^^<><>><<>^^^><^v^v><<<><<^v^vv>v>><^>>><v^>v<v><><v^v<>v^^>>v<<>v>v<v<v<^^<><>v^^<>>v<^v<v>v<><v<v>^<<>v>vv^^<>>^^^<>^^>^v>v>>>^v^v><v^^<><v>^^v^v<^<^^><<v<^<^<>^<>><<>^>>^>^^><v><>v<><>><<<>>>>vv>>>^>>^v<^>v^^^v<<vv>><<<^<<<>>>>>^>vv<^v^<>^<v^>^v><v>vvv<>>>^v^^^v<<<<>>^^<vv<^<^^>^<>v<^<<<>><>>v<^<>^<vvv<^<>><><<v>^^^>^^<<v<v^>^^v^>><<^vv><v>^v>>^<v>v>^^>^v>^vvv<>v^v^^<><vv>vv^>>><>v<^><v<v^<><<<>^v>^v<<<^>^>^>v^v<<><vvv<<v^^<><v>^>>><vv>><v>>v^<vv>>vv<<^v^v<<><^v<vv>>>vv<>>>>^vv>v^<>vv>v^v<v^><v<^^^^^>vv<><<vvv^<v><^<vv><^^^vv^<>^^^^<^><^<>v^<v^v<<^v<<^^<>>^<v^^>>>vv<vvv<>v<<>><^vvv^<<^^<<>>>^<>>>v^^><>><<>><v^v>>>>>><>>><v^<<vvv^>v<>>v^<>vv<><^^^^v^<<^<v^vv><<^^>v<^vvv^v>>v>^>>v>^^><<v^<>v<>vv<^v^vv><v><<vv^v>>v^>>v<^^^>^><<v<>^><>v>>>vvv<v<vv<^>>^v<v>^<^^^^^v><>v><>v^v^v<v^vv^v>vvvv<>vv<<<vv<v<<>^<^>^^v^<<>^<v><^><v<v<><<>v^<<^<><vv>v<<^v>>^v<><v>^>>^^><>v^<^<vvv^>^>^<<<<>vv>^v^v<^^^<vv>><>^^<<v<^<^^>>>v^v<<^^^<v<v<^<>^v<v><v^vv^^v^^v^^<vv<>^<><vv^<^v^<<^><<vvv>^^<^^^<^v>^>^vv><<<^v<v>vv>v<>v^v<v^>v^>>>v^v<>^v<<>^vv>v>v>v^<^>v^^<^>^^^^vv>^^><^>vv^>>^^v>><<<<^><>v<>^<v<vv^>^^><<^><v>v^>^^<^>>><>><v^v<v^<v<vv^v^<<^<vvv>>><vv<^^>>^>^><<v^<>>v>v^v^^><<>vv^v>v^<v><^<>^^<^>v>^<><<<v>^<^<^>^>^>^^v^<<^^v^^<^<>><^>v>>^^<>^^^<<<<v^>^v<^vv>^<<<v<><<v<>vv>>>v><>>><>>v<<<vv><>^v>v<^>><^><><v<>^v^>^v>^v<<><<^<>>v>^><>^>><>><^<v^><v^^<><v><^^>^v^^<>v^<v^<^v<v^^^^^v^<<^>^^^<^v><>^^<<<><<<<<^^>v^vvvv>v<>>vv<^>^v^>v<^vv^v<<><<v>v^v>^^><><^<v^>v><vv><>>><<>^vv<>v>>v<^v>>>v<v>v>v>^vv<<>^^vv<v<^v^<v<v>vv<>^<^<vv<v^<^v^^><<>^>><^v>vv^^v<<^^><<>v^^<><><v^^<v^v>^>^>^>v<^<v>^v^^>v<>vvv<^v<v^v><<v^><<^^><^<<v^v^>v<>^>v><><v>^<v<v>^<^^^>^v<<><<><>vv>v^<>v^><v^v<v><><<v>v<vv><<v>>v>^<<<>vv>>vvv>^^vv^v^^<^^<>v^^<>v>>^^>^>^>v>><^>><>>^<<>><^>v<<<<<<<^v^v<v^<v^^>^<><<v<^>v^>v^vv<<^^vv^>>>>^<>v<^v<>v<vv<^>>v^vv>vv><vv<<^>v>><vv>>>vv^<<<<vv^>v<<<<^^>^^v^><<^<v^>v^>^^<v<>vvv^>^<>vvv<v<^^>v^<<v>><>v<v<>^^<vvv>^>vv><><<<^^vv<v^<v<>v<>><<v><^vv^>^<^>^^^<<<v>vv^<^<<>^>^<vv>v><v<<^><^>^^<vv^v^^>>>>vv^><^^vv><>^<v^v>v<vv>v><<<v>v<v>^><v^^><v>v<^v^>>^^<v^>^^>vv>>vv^><^vv^vv<<^>vv>^v<v><vv><v<vvvvv>^^v^v><v>>>^vv<>v>^^^^<^>><>^v^^^>v<^^<<^^v<vv<>vvv<^>><><^>>^><^<>v<v<<><<v><v^v<>><^>v><<v^<v>v<^<vv^v^v^>vvv^^>v>^<vv^>v^v^<>v>^>>vv>><^^<v<<>^vv<><><<^v<v>v<<vv><>><^v<v>>v^>vvv^v^<<^><v<>^vv^>v^<v<^>>v<v><v><v>>^<<<v^<><<>v>^>^^<v<>>^<>^>^><<<^<<^<<^>^v>>><vvv>><<<<v>>>>>>>^<^v<^>v<>vv<><>v>>^>>^>vv^^><<^<v<v>>^^<<^>v<^>>vv>^<>v><^>v<vv>>>>>>^v<^<<<v^><vv<<>>vv<<><v<><<<v<^<v<>>v<^^^^v^^<^^^<^<vv><<^>><>v<<>v<v<>>>><>v^vv>^>^>>vv^v<v<<><^v>vv^><v<<>v^v<^>vv<<^^v><^>>^^vv<^<>>v^^>><v>^v>>>^>>v>v<>v<^vv><>^<<^>vv>>><><>v^><>v^>v>v><^v<><v<v>^v<<^vv^><^^>><^^^<<<^>v>^v>>><^>><^>>>^^^<^>vv<><<<v^>^<^^>>^^^v^v^v>v<v>>>><^>>>v>^vv<<^^^<^^vv>v<<><v<<^^>v>><<v^^><^>^<^>^v^>v><^<^vv>v>><>^<<vv<<v>v<vv<v>^>^>><^^<v>^v^v<><<>vvv<^<v>^><>^>vvv>>>^><<>><v^^<^<<^v>>^v<v<vv>vv^v^>v<<vvv<^^v^v>^<^>>^>v<^>^v<<><<<^>^<^^^>vv<^^^^vv<v<^^v<<<<v<^v^<><v<<^><<>vv>>><^<^<>>>^>^>>^<<<<<^^v>^>^<>vvv^^<^><^>^^v>^vv^><v^<^<<v^<vvv<<^v<><^><^>>>v>^v>^>^v<vv^v>><v><^><v^^>v^>^<><<><>v<v^>vvv^>^>>v<>^><^>^><vvv>^^v^v>v<>^v^><^>>v>v^><<<^>>^<>^<>>v><>>v^>^>^^<>>v^>^<vvvv<^vvvv^>>vv^<v^v>^vv<>v<>^<v<v>v>^^><^>vv^<^v^<<^<^<><vv<^v<^v><>>>^v^<<^><^>vv<v>v<^>vv^>v<<<>^<><v<^^^>v><^^<>^<^<v^vv^<<^>><<v^v<^vvv<<<>>vvvv^v^^^>v<>>><<>vvv<<^^^>v>v>>v<<v<v^v^>^^v>^><^<><<v^<v<v^^^><>v^^^<v>vv<>^>^^vv>^<<^v<^v><v>>>^>>><^<<>^v>>^>vv<<<v<>^<v><v^<^<>v>v^^v^>><<^v<<<<>v>v>v^^<^><>^^<<<v>vv<>>>^>>v<><v^>^<><vv>v>v^v<v^<^>>^>><<^^<^^v<vv<>><<<v<^<<^^^>vvv^<vvv<^>vv><>><<<^<v^v^^<<^vvv^^<^<><<>^<^<>>vvv<>^<>v^v<><>>v^v><<>>>vvv>v<>^>>^><^>vv<<>>v<<^><>v>>^^<v>^>^<<>><^<<vv<^<vv^vv><>>>><^<v>^>vv<v><>^<>vvvvv^vv<<v<>>>^<<><>^^vvv>>>vv<<^^><^v^^v<>^^>^><^>v^^^^v<^<<vv<vv<>vv^^>v^vv>v><>>vv>^<^<v^v^>>v^v^^v>^>vv^>v<vvvv<^v<^v>^v>^^v<<^>^^<<>^><^v>>>vv^>^^>vvvv>>v<^<v>^>>>v^<><^<^^<v>vv^^><v>v^<>^^^>>><^^v>v>^<<>^<v^>vvv^>^^^><v<^>>v<v>>^v><<><<>v<^<<>^><>^>vv>^<v>^^v<<^v^vvv^^>^vv^<^>^>^^v>v^>^<<><<^>v>>vv^vv><v>>^<<^<v^^<^<v^^vv^><^^<^^><v^^>v^^^<^<>^<>>^v<^vvv^^v^<><^>>>>>v><><<<>vv<^v>><<>vvv<><<vv<<<^>v^^>>^>^v>><><^^v<>><>>v^>^<vv><<<>><><<v>^^<>>v<><^<vv>vv<^v>^<<<<v<^<<^^>>^<><^>><<>^>v>^^^v>>^<^^v><v^v>^><<><>>^>>^<<v<>^v<>^>^<v>>vv>^vvv<<v<<^>^>^<<^^<>^^^^vvv<>^vv<vvvvv^^>^^<^>>><>v^<><^<<^>v^^v<>>^vv<>v^^<>>v^vvvvv<<v^<v^^>>><vvvvv>><^>vv>v^v^<v<^>^^><^>^^^^v<><^v<<>v^>v>>vv<<>^<v^^>vvv>^^<v^<>vv^><>><v^^v<>^>>^>v><>>^^v>^>^>>>^>v<^v>v>^<^^^^^>>v<v<>>v<<^>^<v<<>^^>><<^><>v<>^^^vv<>^^>><<^^>v>vv>vv>v^>^v>v^^<>>><<v><v<<>>v><>vvv^^v>^^>^vvvv^>^<>^vvvv><v><v<>>><>^<^vv<>^v<^v<>^vvv<<>><vvv^>>^><<vv^<v^>^<v<<^^>^^<^^v^>v<>v^v><>><v^^>>^vvv><^vv>v^<^<^v>>v^^>^vvv^<v^^v^^>v<^<>>^<>>>^^<><^^vv<>^vv^<>>>>^^<<^^<>vv^^><>^^<v<<v>^<v^^>^v<><><>vvv>^v^>>vv<<^v<<>><v>^><^>>>^<^<^^>vv^<<^<>>^^><><<v>^^<v>>v<<vvvv>^v^vv>><^^<<^>>v>v<^^^<^><^^vv>^vv<^<vv<>v><^<><v><^^^>>^<><^<v>>>>v^<v>>>>>v<><^^>v<^<^>><v<>^>vv>^^v^v^<<v<><<<^v^><<^<><<<<v<^>><<<>v>>vv><vv<><<^<^<><vv>^^^^<>v<<<<v>vv<>vv^^^>><>vv^><>>^vv<<><^^vv<>v^>>^<<>^<v^<^>v<"
visited = set()
visited.add((0,0))
robo_x, robo_y, santa_x, santa_y = 0,0,0,0
roboturn = False
for c in INPUT:
if roboturn:
if c == '>':
robo_x+=1
if c == '<':
robo_x-=1
if c == '^':
robo_y+=1
if c == 'v':
robo_y-=1
visited.add((robo_x,robo_y))
else:
if c == '>':
santa_x+=1
if c == '<':
santa_x-=1
if c == '^':
santa_y+=1
if c == 'v':
santa_y-=1
visited.add((santa_x,santa_y))
roboturn = not roboturn
print("Visited %d houses" % len(visited))
|
input = '>^^v^<>v<<<v<v^>>v^^^<v<>^^><^<<^vv>>>^<<^>><vv<<v^<^^><>>><>v<><>^^<^^^<><>>vv>vv>v<<^>v<>^>v<v^<>v>><>^v<<<<v^vv^><v>v^>>>vv>v^^^<^^<>>v<^^v<>^<vv^^<^><<>^>><^<>>><><vv><>v<<<><><>v><<>^^^^v>>^>^<v<<vv^^<v<^<^>^^v^^^^^v<><^v><<><^v^>v<<>^<>^^v^<>v<v^>v>^^<vv^v><^<>^v<><^><v^><><><<<<>^vv^>^vvvvv><><^<vv^v^v>v<<^<^^v^<>^<vv><v<v^v<<v<<^^>>^^^v^>v<><^vv<<^<>v<v><><v^^><v<>^^>^^>v^>^<<<<v><v<<>v><^v>^>><v^^<^>v<vvvv<>>>>>^v^^>v<v<^<vv>^>^vv^>vv^^v<<^<^^<>v>vv^v>><>>>v^>^>^^v<>^<v<<>^vv>v^<<v>v<<><v>^vvv<v<vvv^v<vv<v^^^>v><<^<>><v^^>^v^>>^v<^<><v<>>v^<>>v<>>v^^^><^>>vvvv>^v<^><<>>^<>^>vv><v<<>>^^>v^^^><^<<^^v>v<^<<>v>^^vvv^v^>v^<>^^<>v^v>v>v<v^>vv>^^v<>v>>^<>><>v>v^<<vvvv<vvv><v^<^>^v<>>^><v>><>^<v>v<v>vv^>>vvv<>v>v<v^>>^>>v<<>^<>^<>>>^v<<<^<^v>vv^>><<><v^>^v^^^v<>^^vv><>><>>^>v^<v<>v<>>^<<^v>^^^<>^v^><>v<<v>vv^>vv<<>>><<^v^<>v<vv>>>^^<>^><<^>vv>>^<<v^^vv<>>><v>v><^<v<<>>>^^<>>^<^v><>vv^^^v>vvv>^><<>^^>^<<v^<v<^v<<>vvv<^<<>^>^v<vv<^>vvv>v>vv^<v^><>>^vv<^^^vv><^vv<v^<><v^vvv><<^>^^><v<<vv^>v<vv<v>^<>^v<<>v<v^v^>^>^>v<<^vvv<<<v>^^>^<<<<>vv>>^<>^>>>v<v>^^<v^<v<>>>vv>^^v<<>>>^^v><<<v<v<^v<>^^><v<^v<<v^><><^<><v<^^v>>><v^^v<<v^><^<><<v^>><^<>v>v^<><^<v>^v^>^>^vv^>^^<<vv^>vv<^vvv<>>^^<^>v^>^>^<v^><v<v>>>v<<<><^v<<><^<vv^v^^^>v<^^<v^vvv<v<><v<vv<^vv<>vv<v^<>>vvvvv<<>^v^v>vv>>>vvv^^<^<^<><>v<v>><^v><^<<<>><<<v>^>v<>^>^v>>^<>v^<^>><<>^<v>^>^^^>^^<v>>>><>^v^v><<<<vv^<vv<>vv>v<>v^<v^>v><>>>v^<><^vvv>vv^<^<<^<^^v>^>>>v<^<^v^^<^<^>>><v>vv>^<<><>^>>v>^<<>><^<>v<>vv^^>^>vvv^v<<^<^^<vv<>^vvv<^^v^vv^>>v<^>^^<v^<>v<^<^vv>v<<vv>vv>^>vvv>>>^^>v<>^v>v^<^>>v>^^v>>>>v^<v>v<^>v<v<<>>^v<^^<v><^<>>^<<vv^>>v<<v>^v<>><^>vv<v<^>>^^<vvvvvvvvv>>>v<v<>v^<>>^vv<v^^v<<^vvv^<<^><>vv<><<>>v>vv^><>>^^v^>>v^v^><<<>>^^<^v<<^<>>>>^<^>v^><<^>v<^v<^>>^^<<<<><^<^v^v<>>^v<^<<vv^<><^^vv><v^v^v>^>>^>^vv^>^v<v^v<<vvv^><>>^v^^><>v>vv><^>>vv<vvv<<<<^<>vvv^v<v>^<v<^>^<^<v<><>v^^^^<<vv<^^vv<v>><<v^><>>><v^>^v><^>^><vv^<><^<v>><<^vv<>>v^<<v<>v><v<><><vv>^>>v^<^<v>^><>>><^><v^v<>>>^^<^>v<v>vvv<>^<<><v^^>^>>v<^v>^>v>>>vv>v>>v^^^<^<vvv^<>^>^<v^<v^v>v>^>vv>vvv<>v<^>v>^^>>^<vv^^v>v^^^^^v^vv><^<><>^>vv<^>>^vvvv^^^>^<vv>^v<<^><^^>^<>^^>^<<v<^>>>^><<^^>v^v>>^>vvvv>^^v><v>>vv><<<vv<^>v>^^^<v>v^vvv<^><<^>^<>^><<<<<v^<<vv^v>^<>v<v>^>^>><>v^v<^vv^^>vv<<v^v>vv^vvv<<<<>^v<v^^v^v>v<<v>^^<>^vv^^>^>^v^vv^>>v^vv^^<vv><<v^v^^v><vv<^vvv<vv^^<<v>v^v^^^^v<^<^>v>^>v>^vv^v^^<v<^vvvv<<<>^<^^^<^^<>^<><vv<^^<<^>>><v^vvvv>^<>>^^>v^^v^<<v^^^<<<><^<v^v^^v<v^<>v><<v<>^v>v<^><^>vv^^<vvv<^v>>v>^<><v^><^^^<v^>>vv<<<<<^<>^v^v>^vv^<>v>v<^>vv<<^vv>vv<v<><>>v>><v<^<^^>><<v^v<<^><v<^<vv<v<<vv^>^<<><^^>^<^>>^<vv>><v<<vvv<^^v^>^^<^v>^v<v<>v><v^v^<<^<><<v<<^v>v<<>>^>v>>v>>v<^<<^<^>>>v>^^^v><^>^^>>v<<>^v><v>vvv^vv<<<>vvv<<>^>>>v<v<v^<^<^>^<^>v^^v<^^<v<>v<>>^^>^v^>v<<<<^<>v^><<<v>>>><<v^<^vv>v>><>>^<<<^<^^>v<>>v<>vv<<^<<><<^>v^^^vv^>vvvv>>v>v^><<v<>vv^<<><<vvv>^>>>^<<<^<^<<v>^>v<>>v>>vv^^><<<<^^^v>><<^><v><v^^><v<<v^^v^^v>>v<><><<>^><v><^<vv>><^v<>v<vvv<>^>><v>>v<^><<v>^<>^v><^><^^<v>^><^^v^<<><>>^>v^<^v^vv<><^>vv^>v^vvv^<>>^><^<^<>^<<v^v<^v><>^v<v>>^>>^v^vv>><vv><v^^<<^v^<>^v<<>^><^>><v>>v<<<v^^vv<>^^v>>><><><<v^<<<v^<^^><v^>v^^vv<v^<>>vv^<^v<>^v>>v^v>v<^^vv><>^v<<>v^<>v^>>v>vvv<^><><^^>^vv^>>v^>^<^^<><>><<>^^^><^v^v><<<><<^v^vv>v>><^>>><v^>v<v><><v^v<>v^^>>v<<>v>v<v<v<^^<><>v^^<>>v<^v<v>v<><v<v>^<<>v>vv^^<>>^^^<>^^>^v>v>>>^v^v><v^^<><v>^^v^v<^<^^><<v<^<^<>^<>><<>^>>^>^^><v><>v<><>><<<>>>>vv>>>^>>^v<^>v^^^v<<vv>><<<^<<<>>>>>^>vv<^v^<>^<v^>^v><v>vvv<>>>^v^^^v<<<<>>^^<vv<^<^^>^<>v<^<<<>><>>v<^<>^<vvv<^<>><><<v>^^^>^^<<v<v^>^^v^>><<^vv><v>^v>>^<v>v>^^>^v>^vvv<>v^v^^<><vv>vv^>>><>v<^><v<v^<><<<>^v>^v<<<^>^>^>v^v<<><vvv<<v^^<><v>^>>><vv>><v>>v^<vv>>vv<<^v^v<<><^v<vv>>>vv<>>>>^vv>v^<>vv>v^v<v^><v<^^^^^>vv<><<vvv^<v><^<vv><^^^vv^<>^^^^<^><^<>v^<v^v<<^v<<^^<>>^<v^^>>>vv<vvv<>v<<>><^vvv^<<^^<<>>>^<>>>v^^><>><<>><v^v>>>>>><>>><v^<<vvv^>v<>>v^<>vv<><^^^^v^<<^<v^vv><<^^>v<^vvv^v>>v>^>>v>^^><<v^<>v<>vv<^v^vv><v><<vv^v>>v^>>v<^^^>^><<v<>^><>v>>>vvv<v<vv<^>>^v<v>^<^^^^^v><>v><>v^v^v<v^vv^v>vvvv<>vv<<<vv<v<<>^<^>^^v^<<>^<v><^><v<v<><<>v^<<^<><vv>v<<^v>>^v<><v>^>>^^><>v^<^<vvv^>^>^<<<<>vv>^v^v<^^^<vv>><>^^<<v<^<^^>>>v^v<<^^^<v<v<^<>^v<v><v^vv^^v^^v^^<vv<>^<><vv^<^v^<<^><<vvv>^^<^^^<^v>^>^vv><<<^v<v>vv>v<>v^v<v^>v^>>>v^v<>^v<<>^vv>v>v>v^<^>v^^<^>^^^^vv>^^><^>vv^>>^^v>><<<<^><>v<>^<v<vv^>^^><<^><v>v^>^^<^>>><>><v^v<v^<v<vv^v^<<^<vvv>>><vv<^^>>^>^><<v^<>>v>v^v^^><<>vv^v>v^<v><^<>^^<^>v>^<><<<v>^<^<^>^>^>^^v^<<^^v^^<^<>><^>v>>^^<>^^^<<<<v^>^v<^vv>^<<<v<><<v<>vv>>>v><>>><>>v<<<vv><>^v>v<^>><^><><v<>^v^>^v>^v<<><<^<>>v>^><>^>><>><^<v^><v^^<><v><^^>^v^^<>v^<v^<^v<v^^^^^v^<<^>^^^<^v><>^^<<<><<<<<^^>v^vvvv>v<>>vv<^>^v^>v<^vv^v<<><<v>v^v>^^><><^<v^>v><vv><>>><<>^vv<>v>>v<^v>>>v<v>v>v>^vv<<>^^vv<v<^v^<v<v>vv<>^<^<vv<v^<^v^^><<>^>><^v>vv^^v<<^^><<>v^^<><><v^^<v^v>^>^>^>v<^<v>^v^^>v<>vvv<^v<v^v><<v^><<^^><^<<v^v^>v<>^>v><><v>^<v<v>^<^^^>^v<<><<><>vv>v^<>v^><v^v<v><><<v>v<vv><<v>>v>^<<<>vv>>vvv>^^vv^v^^<^^<>v^^<>v>>^^>^>^>v>><^>><>>^<<>><^>v<<<<<<<^v^v<v^<v^^>^<><<v<^>v^>v^vv<<^^vv^>>>>^<>v<^v<>v<vv<^>>v^vv>vv><vv<<^>v>><vv>>>vv^<<<<vv^>v<<<<^^>^^v^><<^<v^>v^>^^<v<>vvv^>^<>vvv<v<^^>v^<<v>><>v<v<>^^<vvv>^>vv><><<<^^vv<v^<v<>v<>><<v><^vv^>^<^>^^^<<<v>vv^<^<<>^>^<vv>v><v<<^><^>^^<vv^v^^>>>>vv^><^^vv><>^<v^v>v<vv>v><<<v>v<v>^><v^^><v>v<^v^>>^^<v^>^^>vv>>vv^><^vv^vv<<^>vv>^v<v><vv><v<vvvvv>^^v^v><v>>>^vv<>v>^^^^<^>><>^v^^^>v<^^<<^^v<vv<>vvv<^>><><^>>^><^<>v<v<<><<v><v^v<>><^>v><<v^<v>v<^<vv^v^v^>vvv^^>v>^<vv^>v^v^<>v>^>>vv>><^^<v<<>^vv<><><<^v<v>v<<vv><>><^v<v>>v^>vvv^v^<<^><v<>^vv^>v^<v<^>>v<v><v><v>>^<<<v^<><<>v>^>^^<v<>>^<>^>^><<<^<<^<<^>^v>>><vvv>><<<<v>>>>>>>^<^v<^>v<>vv<><>v>>^>>^>vv^^><<^<v<v>>^^<<^>v<^>>vv>^<>v><^>v<vv>>>>>>^v<^<<<v^><vv<<>>vv<<><v<><<<v<^<v<>>v<^^^^v^^<^^^<^<vv><<^>><>v<<>v<v<>>>><>v^vv>^>^>>vv^v<v<<><^v>vv^><v<<>v^v<^>vv<<^^v><^>>^^vv<^<>>v^^>><v>^v>>>^>>v>v<>v<^vv><>^<<^>vv>>><><>v^><>v^>v>v><^v<><v<v>^v<<^vv^><^^>><^^^<<<^>v>^v>>><^>><^>>>^^^<^>vv<><<<v^>^<^^>>^^^v^v^v>v<v>>>><^>>>v>^vv<<^^^<^^vv>v<<><v<<^^>v>><<v^^><^>^<^>^v^>v><^<^vv>v>><>^<<vv<<v>v<vv<v>^>^>><^^<v>^v^v<><<>vvv<^<v>^><>^>vvv>>>^><<>><v^^<^<<^v>>^v<v<vv>vv^v^>v<<vvv<^^v^v>^<^>>^>v<^>^v<<><<<^>^<^^^>vv<^^^^vv<v<^^v<<<<v<^v^<><v<<^><<>vv>>><^<^<>>>^>^>>^<<<<<^^v>^>^<>vvv^^<^><^>^^v>^vv^><v^<^<<v^<vvv<<^v<><^><^>>>v>^v>^>^v<vv^v>><v><^><v^^>v^>^<><<><>v<v^>vvv^>^>>v<>^><^>^><vvv>^^v^v>v<>^v^><^>>v>v^><<<^>>^<>^<>>v><>>v^>^>^^<>>v^>^<vvvv<^vvvv^>>vv^<v^v>^vv<>v<>^<v<v>v>^^><^>vv^<^v^<<^<^<><vv<^v<^v><>>>^v^<<^><^>vv<v>v<^>vv^>v<<<>^<><v<^^^>v><^^<>^<^<v^vv^<<^>><<v^v<^vvv<<<>>vvvv^v^^^>v<>>><<>vvv<<^^^>v>v>>v<<v<v^v^>^^v>^><^<><<v^<v<v^^^><>v^^^<v>vv<>^>^^vv>^<<^v<^v><v>>>^>>><^<<>^v>>^>vv<<<v<>^<v><v^<^<>v>v^^v^>><<^v<<<<>v>v>v^^<^><>^^<<<v>vv<>>>^>>v<><v^>^<><vv>v>v^v<v^<^>>^>><<^^<^^v<vv<>><<<v<^<<^^^>vvv^<vvv<^>vv><>><<<^<v^v^^<<^vvv^^<^<><<>^<^<>>vvv<>^<>v^v<><>>v^v><<>>>vvv>v<>^>>^><^>vv<<>>v<<^><>v>>^^<v>^>^<<>><^<<vv<^<vv^vv><>>>><^<v>^>vv<v><>^<>vvvvv^vv<<v<>>>^<<><>^^vvv>>>vv<<^^><^v^^v<>^^>^><^>v^^^^v<^<<vv<vv<>vv^^>v^vv>v><>>vv>^<^<v^v^>>v^v^^v>^>vv^>v<vvvv<^v<^v>^v>^^v<<^>^^<<>^><^v>>>vv^>^^>vvvv>>v<^<v>^>>>v^<><^<^^<v>vv^^><v>v^<>^^^>>><^^v>v>^<<>^<v^>vvv^>^^^><v<^>>v<v>>^v><<><<>v<^<<>^><>^>vv>^<v>^^v<<^v^vvv^^>^vv^<^>^>^^v>v^>^<<><<^>v>>vv^vv><v>>^<<^<v^^<^<v^^vv^><^^<^^><v^^>v^^^<^<>^<>>^v<^vvv^^v^<><^>>>>>v><><<<>vv<^v>><<>vvv<><<vv<<<^>v^^>>^>^v>><><^^v<>><>>v^>^<vv><<<>><><<v>^^<>>v<><^<vv>vv<^v>^<<<<v<^<<^^>>^<><^>><<>^>v>^^^v>>^<^^v><v^v>^><<><>>^>>^<<v<>^v<>^>^<v>>vv>^vvv<<v<<^>^>^<<^^<>^^^^vvv<>^vv<vvvvv^^>^^<^>>><>v^<><^<<^>v^^v<>>^vv<>v^^<>>v^vvvvv<<v^<v^^>>><vvvvv>><^>vv>v^v^<v<^>^^><^>^^^^v<><^v<<>v^>v>>vv<<>^<v^^>vvv>^^<v^<>vv^><>><v^^v<>^>>^>v><>>^^v>^>^>>>^>v<^v>v>^<^^^^^>>v<v<>>v<<^>^<v<<>^^>><<^><>v<>^^^vv<>^^>><<^^>v>vv>vv>v^>^v>v^^<>>><<v><v<<>>v><>vvv^^v>^^>^vvvv^>^<>^vvvv><v><v<>>><>^<^vv<>^v<^v<>^vvv<<>><vvv^>>^><<vv^<v^>^<v<<^^>^^<^^v^>v<>v^v><>><v^^>>^vvv><^vv>v^<^<^v>>v^^>^vvv^<v^^v^^>v<^<>>^<>>>^^<><^^vv<>^vv^<>>>>^^<<^^<>vv^^><>^^<v<<v>^<v^^>^v<><><>vvv>^v^>>vv<<^v<<>><v>^><^>>>^<^<^^>vv^<<^<>>^^><><<v>^^<v>>v<<vvvv>^v^vv>><^^<<^>>v>v<^^^<^><^^vv>^vv<^<vv<>v><^<><v><^^^>>^<><^<v>>>>v^<v>>>>>v<><^^>v<^<^>><v<>^>vv>^^v^v^<<v<><<<^v^><<^<><<<<v<^>><<<>v>>vv><vv<><<^<^<><vv>^^^^<>v<<<<v>vv<>vv^^^>><>vv^><>>^vv<<><^^vv<>v^>>^<<>^<v^<^>v<'
visited = set()
visited.add((0, 0))
(robo_x, robo_y, santa_x, santa_y) = (0, 0, 0, 0)
roboturn = False
for c in INPUT:
if roboturn:
if c == '>':
robo_x += 1
if c == '<':
robo_x -= 1
if c == '^':
robo_y += 1
if c == 'v':
robo_y -= 1
visited.add((robo_x, robo_y))
else:
if c == '>':
santa_x += 1
if c == '<':
santa_x -= 1
if c == '^':
santa_y += 1
if c == 'v':
santa_y -= 1
visited.add((santa_x, santa_y))
roboturn = not roboturn
print('Visited %d houses' % len(visited))
|
def timer(start: float, end: float) -> str:
"""
Timer function. Compute execution time from strart to end (end - start).
:param start: start time
:param end: end time
:return: end - start
"""
hours, rem = divmod(end - start, 3600)
minutes, seconds = divmod(rem, 60)
return "{:0>2}:{:0>2}:{:05.2f}".format(int(hours), int(minutes), seconds)
|
def timer(start: float, end: float) -> str:
"""
Timer function. Compute execution time from strart to end (end - start).
:param start: start time
:param end: end time
:return: end - start
"""
(hours, rem) = divmod(end - start, 3600)
(minutes, seconds) = divmod(rem, 60)
return '{:0>2}:{:0>2}:{:05.2f}'.format(int(hours), int(minutes), seconds)
|
#
# PySNMP MIB module CISCO-IMAGE-UPGRADE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-IMAGE-UPGRADE-MIB
# Produced by pysmi-0.3.4 at Wed May 1 12:01:48 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, ConstraintsIntersection, ValueSizeConstraint, SingleValueConstraint, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ConstraintsIntersection", "ValueSizeConstraint", "SingleValueConstraint", "ConstraintsUnion")
ciscoMgmt, = mibBuilder.importSymbols("CISCO-SMI", "ciscoMgmt")
EntPhysicalIndexOrZero, = mibBuilder.importSymbols("CISCO-TC", "EntPhysicalIndexOrZero")
entPhysicalIndex, = mibBuilder.importSymbols("ENTITY-MIB", "entPhysicalIndex")
SnmpAdminString, = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString")
ModuleCompliance, ObjectGroup, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "ObjectGroup", "NotificationGroup")
MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, Unsigned32, Integer32, iso, Counter64, ModuleIdentity, ObjectIdentity, Gauge32, IpAddress, MibIdentifier, Counter32, Bits, NotificationType = mibBuilder.importSymbols("SNMPv2-SMI", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "TimeTicks", "Unsigned32", "Integer32", "iso", "Counter64", "ModuleIdentity", "ObjectIdentity", "Gauge32", "IpAddress", "MibIdentifier", "Counter32", "Bits", "NotificationType")
RowStatus, DisplayString, TimeStamp, TextualConvention, TruthValue = mibBuilder.importSymbols("SNMPv2-TC", "RowStatus", "DisplayString", "TimeStamp", "TextualConvention", "TruthValue")
ciscoImageUpgradeMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 9, 9, 360))
ciscoImageUpgradeMIB.setRevisions(('2011-03-28 00:00', '2008-03-18 00:00', '2007-07-18 00:00', '2006-12-21 00:00', '2004-01-20 00:00', '2003-11-04 00:00', '2003-10-28 00:00', '2003-07-11 00:00', '2003-07-08 00:00', '2003-06-01 00:00',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: ciscoImageUpgradeMIB.setRevisionsDescriptions(("Added new group ciuUpgradeOpNewGroup. Added new enum 'systemPreupgradeBegin' to ciuUpgradeOpStatusOperation. Added ciuUpgradeOpLastCommand and ciuUpgradeOpLastStatus to the varbind list of ciuUpgradeOpCompletionNotify. Added new compliance ciuImageUpgradeComplianceRev4 and deprecated ciuImageUpgradeComplianceRev3. Added ciuUpgradeJobStatusNotifyOnCompletion.", "Added new enum 'compactFlashTcamSanity' to ciuUpgradeOpStatusOperation.", 'Added new enums to ciuUpgradeOpStatusOperation.', 'Added new enums to ciuUpgradeOpStatus and ciuUpgradeOpStatusOperation. Added new trap ciuUpgradeJobStatusNotify. Changed type for ciuUpgradeOpStatusModule to EntPhysicalIndexOrZero. Added ciuUpgradeNotificationGroupSup group, deprecated ciuImageUpgradeComplianceRev2 and added ciuImageUpgradeComplianceRev3 ', "Added new enums to ciuUpgradeOpStatus and ciuUpgradeOpStatusOperation. Corrected description for 'configSync' enum defined in ciuUpgradeOpStatusOperation object. ", 'Updated compliance statement. Removed ciuImageLocInputGroup from conditionally mandatory.', 'Added ciuUpgradeMiscInfoTable. Added more enums to ciuUpgradeOpStatusOperation. Added ciuUpgradeMiscInfoGroup, deprecated ciuImageUpgradeComplianceRev1 and added ciuImageUpgradeComplianceRev2.', 'Changed: ciuImageLocInputURI identifier from 2 to 1, ciuImageLocInputEntryStatus identifier from 3 to 2 and ciuImageVariableName from 2 to 1. Added recommendedAction to ciuUpgradeOpStatusOperation.', 'Added ciscoImageUpgradeMisc, added ciuUpgradeMiscAutoCopy under the group ciscoImageUpgradeMisc. Added ciuUpgradeMiscGroup, deprecated ciuImageUpgradeCompliance and added ciuImageUpgradeComplianceReve1.', 'Initial version of this MIB module.',))
if mibBuilder.loadTexts: ciscoImageUpgradeMIB.setLastUpdated('201103280000Z')
if mibBuilder.loadTexts: ciscoImageUpgradeMIB.setOrganization('Cisco Systems Inc.')
if mibBuilder.loadTexts: ciscoImageUpgradeMIB.setContactInfo(' Cisco Systems Customer Service Postal: 170 W Tasman Drive San Jose, CA 95134 USA Tel: +1 800 553 -NETS E-mail: cs-san@cisco.com')
if mibBuilder.loadTexts: ciscoImageUpgradeMIB.setDescription("This mib provides, objects to upgrade images on modules in the system, objects showing the status of the upgrade operation, and objects showing the type of images that could be run in the system. For example the modules could be Controller card, Line card .. etc. The system fills up the ciuImageVariableTable with the type of images the system can support. For performing an upgrade operation a management application must first read this table and use this info in other tables, as explained below. The ciuImageURITable table is also filled by the system and provides the image name presently running for each type of image in the system. The user is allowed to configure a new image name for each image type as listed in ciuImageVariableTable. The system would use this image on the particular module on the next reboot. The management application on deciding to do an upgrade operation must first check if an upgrade operation is already in progress in the system. This is done by reading the ciuUpgradeOpCommand and if it contains 'none', signifies that no other upgrade operation is in progress. Any other value, signifies that upgrade is in progress and a new upgrade operation is not allowed. To start an 'install' operation, first the user must perform a 'check' operation to do the version compatibility for the given set of image files (provided using the ciuImageLocInputTable) against the current system configuration. Only if the result of this operation is 'success' can the user proceed to do an install operation. The tables, ciuVersionCompChkTable, ciuUpgradeImageVersionTable, ciuUpgradeOpStatusTable, provide the result of the 'check' or 'install' operation performed using ciuUpgradeOpCommand. These tables are in addition to objects ciuUpgradeOpStatus, ciuUpgradeOpTimeStarted, ciuUpgradeOpTimeCompleted, ciuUpgradeOpStatusReason. The ciuUpgradeOpStatus object provides the status of the selected upgrade operation. An option is available for user to upgrade only some modules, provided using ciuUpgradeTargetTable. If this table is empty than an upgrade operation would be performed on all the modules in the system.")
ciscoImageUpgradeMIBNotifs = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 360, 0))
ciscoImageUpgradeMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 360, 1))
ciscoImageUpgradeMIBConform = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 360, 2))
ciscoImageUpgradeConfig = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1))
ciscoImageUpgradeOp = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 4))
ciscoImageUpgradeMisc = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 10))
class CiuImageVariableTypeName(TextualConvention, OctetString):
description = "The type of image that the system can run. e.g. Let us say that the device has 3 image variables names - 'system', 'kickstart' and 'ilce'. This TC would, then be as follows: system kickstart ilce. "
status = 'current'
subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(1, 32)
ciuTotalImageVariables = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 1), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ciuTotalImageVariables.setStatus('current')
if mibBuilder.loadTexts: ciuTotalImageVariables.setDescription('Total number of image variables supported in the device at this time.')
ciuImageVariableTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 2), )
if mibBuilder.loadTexts: ciuImageVariableTable.setStatus('current')
if mibBuilder.loadTexts: ciuImageVariableTable.setDescription('A table listing the image variable types that exist in the device. ')
ciuImageVariableEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 2, 1), ).setIndexNames((0, "CISCO-IMAGE-UPGRADE-MIB", "ciuImageVariableName"))
if mibBuilder.loadTexts: ciuImageVariableEntry.setStatus('current')
if mibBuilder.loadTexts: ciuImageVariableEntry.setDescription('A ciuImageVariableEntry entry. Each entry provides the image variable type existing in the device. ')
ciuImageVariableName = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 2, 1, 1), CiuImageVariableTypeName()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ciuImageVariableName.setStatus('current')
if mibBuilder.loadTexts: ciuImageVariableName.setDescription("The type of image that the system can run. The value of this object depends on the underlying agent. e.g. Let us say that the device has 3 image variables names - 'system', 'kickstart' and 'ilce'. This table , then will list these 3 strings as entries such as follows: ciuImageVariableName system kickstart ilce The user can assign images (using ciuImageURITable) to these variables and the system will use the assigned values to boot. ")
ciuImageURITable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 3), )
if mibBuilder.loadTexts: ciuImageURITable.setStatus('current')
if mibBuilder.loadTexts: ciuImageURITable.setDescription("A table listing the Universal Resource Identifier(URI) of images that are assigned to variables of the ciuImageVariableTable. In the example for ciuImageVariableTable, there are 3 image types. This table will list the names for those image types as follows - entPhysicalIndex ciuImageVariableName ciuImageURI 25 'system' m9200-ek9-mgz.1.0.bin 25 'kickstart' boot-1.0.bin 26 'ilce' linecard-1.0.bin In this example, the 'system' image name is 'm9200-ek9-mgz.1.0.bin', the 'ilce' image name is 'linecard-1.0.bin' and the 'kickstart' image name is 'boot-1.0.bin'. ")
ciuImageURIEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 3, 1), ).setIndexNames((0, "ENTITY-MIB", "entPhysicalIndex"), (0, "CISCO-IMAGE-UPGRADE-MIB", "ciuImageVariableName"))
if mibBuilder.loadTexts: ciuImageURIEntry.setStatus('current')
if mibBuilder.loadTexts: ciuImageURIEntry.setDescription('A ciuImageURITable entry. Each entry provides the Image URI corresponding to this image variable name, identified by ciuImageVariableName, on this module identified by entPhysicalIndex. Each such module of the type PhysicalClass module(9), has an entry in entPhysicalTable in ENTITY-MIB, where that entry is identified by entPhysicalIndex. Only modules capable of running images, identified by ciuImageVariableName would have an entry in this table. ')
ciuImageURI = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 3, 1, 1), SnmpAdminString()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: ciuImageURI.setStatus('current')
if mibBuilder.loadTexts: ciuImageURI.setDescription('This object contains the string value of the image corresponding to ciuImageVariableName on this entity.')
ciuUpgradeOpCommand = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 4, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("none", 1), ("done", 2), ("install", 3), ("check", 4)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: ciuUpgradeOpCommand.setStatus('current')
if mibBuilder.loadTexts: ciuUpgradeOpCommand.setDescription("The command to be executed. Note that it is possible for a system to support only a subset of these commands. If a command is unsupported, it will complete immediatly with the 'invalidOperation' error being reported in the ciuUpgradeOpStatus object. The 'check' must be performed first before 'install' command can be executed. If 'install' is performed first the operation would fail. So 'install' will be allowed only if a read of this object returns 'check' and the value of object ciuUpgradeOpStatus is 'success'. Also 'check' will be allowed only if a read of this object returns 'none'. Command Remarks none if this object is read without performing any operation listed above, 'none' would be returned. Also 'none' would be returned for a read operation if a cleanup of the previous upgrade operation is completed either through the issue of 'done' command or the maximum timeout of 5 minutes is elapsed. Setting this object to 'none', agent would return a success without any upgrade operation being performed. done if this object returns any value other than 'none', then setting this to 'done' would do the required cleanup of previous upgrade operation and make the system ready for any new upgrade operation. This is needed because the system maintains the status of the previous upgrade operation for a maximum time of 5 minutes before it does the cleanup. During this period no new upgrade operation is allowed. install for all the physical entities listed in the ciuUpgradeTargetTable perform the required upgrade operation listed in that table. However the upgrade operation for a module would not be done if the current running image and the image to be upgraded given as an input through the ciuImageLocInputTable are the same. check check the version compatibility for the given set of image files against the current system configuration. ")
ciuUpgradeOpStatus = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 4, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))).clone(namedValues=NamedValues(("none", 1), ("invalidOperation", 2), ("failure", 3), ("inProgress", 4), ("success", 5), ("abortInProgress", 6), ("abortSuccess", 7), ("abortFailed", 8), ("successReset", 9), ("fsUpgReset", 10))).clone('none')).setMaxAccess("readonly")
if mibBuilder.loadTexts: ciuUpgradeOpStatus.setStatus('current')
if mibBuilder.loadTexts: ciuUpgradeOpStatus.setDescription('The status of the specified operation. none(1) - no operation was performed. invalidOperation(2) - the selected operation is not supported. failure(3) - the selected operation has failed. inProgress(4) - specified operation is active. success(5) - specified operation has completed successfully. abortInProgress(6) - abort in progress. abortSuccess(7) - abort operation successful. abortFailed(8) - abort failed. successReset(9) - specified operation has completed successfully and the system will reset. fsUpgReset(10) - fabric switch upgrade reset.')
ciuUpgradeOpNotifyOnCompletion = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 4, 3), TruthValue().clone('false')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: ciuUpgradeOpNotifyOnCompletion.setStatus('current')
if mibBuilder.loadTexts: ciuUpgradeOpNotifyOnCompletion.setDescription("Specifies whether or not a notification should be generated on the completion of an operation. If 'true', ciuUpgradeOpCompletionNotify will be generated, else if 'false' it would not be. It is the responsibility of the management entity to ensure that the SNMP administrative model is configured in such a way as to allow the notification to be delivered. This object can only be modified alongwith ciuUpgradeOpCommand object.This object returns default value when ciuUpgradeOpCommand object contains 'none'. To SET this object a multivarbind set containing this object and ciuUpgradeOpCommand must be done in the same PDU for the operation to succeed.")
ciuUpgradeOpTimeStarted = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 4, 4), TimeStamp()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ciuUpgradeOpTimeStarted.setStatus('current')
if mibBuilder.loadTexts: ciuUpgradeOpTimeStarted.setDescription("Specifies the time the upgrade operation was started. This object would return 0 if ciuUpgradeOpCommand contains 'none'.")
ciuUpgradeOpTimeCompleted = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 4, 5), TimeStamp()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ciuUpgradeOpTimeCompleted.setStatus('current')
if mibBuilder.loadTexts: ciuUpgradeOpTimeCompleted.setDescription("Specifies the time the upgrade operation completed. This object would return 0 if ciuUpgradeOpCommand contains 'none'. ")
ciuUpgradeOpAbort = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 4, 6), TruthValue().clone('false')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: ciuUpgradeOpAbort.setStatus('current')
if mibBuilder.loadTexts: ciuUpgradeOpAbort.setDescription("Provides the means to abort an operation. If this object is set to 'true' when an upgrade operation is in progress and the corresponding instance of ciuUpgradeOpCommand has the value 'install' or 'check', then the operation will be aborted. Setting this object to 'true' when ciuUpgradeOpCommand has a different value other than 'install' or 'check' will fail. If retrieved, this object always has the value 'false'. ")
ciuUpgradeOpStatusReason = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 4, 7), SnmpAdminString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ciuUpgradeOpStatusReason.setStatus('current')
if mibBuilder.loadTexts: ciuUpgradeOpStatusReason.setDescription("Specifies the description of the cause of 'failed' state of the object 'ciuUpgradeOpStatus'. This object would be a null string if value of 'ciuUpgradeOpStatus' is anything other than 'failure'.")
ciuUpgradeOpLastCommand = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 4, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("none", 1), ("done", 2), ("install", 3), ("check", 4)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: ciuUpgradeOpLastCommand.setStatus('current')
if mibBuilder.loadTexts: ciuUpgradeOpLastCommand.setDescription("This object indicates previous OpCommand value. It will be updated after new OpCommand is set and delivered to upgrade process. 'none' if this object is read without performing any operation listed above, 'none' would be returned. Also 'none' would be returned for a read operation if a cleanup of the previous upgrade operation is completed either through the issue of 'done' command or the maximum timeout of 5 minutes is elapsed. Setting this object to 'none', agent would return a success without any upgrade operation being performed. 'done' if this object returns any value other than 'none', then setting this to 'done' would do the required cleanup of previous upgrade operation and make the system ready for any new upgrade operation. This is needed because the system maintains the status of the previous upgrade operation for a maximum time of 5 minutes before it does the cleanup. During this period no new upgrade operation is allowed. 'install' perform the required upgrade operation listed in ciuUpgradeTargetTable table. However the upgrade operation for a module would not be done if the current running image and the image to be upgraded given as an input through the ciuImageLocInputTable are the same. 'check' check the version compatibility for the given set of image files against the current system configuration.")
ciuUpgradeOpLastStatus = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 4, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))).clone(namedValues=NamedValues(("none", 1), ("invalidOperation", 2), ("failure", 3), ("inProgress", 4), ("success", 5), ("abortInProgress", 6), ("abortSuccess", 7), ("abortFailed", 8), ("successReset", 9), ("fsUpgReset", 10)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: ciuUpgradeOpLastStatus.setStatus('current')
if mibBuilder.loadTexts: ciuUpgradeOpLastStatus.setDescription("This object indicates previous OpStatus value. It will be updated after new OpCommand is set and delivered to upgrade process. 'none' - no operation was performed. 'invalidOperation' - the selected operation is not supported. 'failure' - the selected operation has failed. 'inProgress' - specified operation is active. 'success' - specified operation has completed successfully. 'abortInProgress' - abort in progress. 'abortSuccess' - abort operation successful. 'abortFailed' - abort failed. 'successReset' - specified operation has completed successfully and the system will reset. 'fsUpgReset' - fabric switch upgrade reset.")
ciuUpgradeOpLastStatusReason = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 4, 10), SnmpAdminString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ciuUpgradeOpLastStatusReason.setStatus('current')
if mibBuilder.loadTexts: ciuUpgradeOpLastStatusReason.setDescription('This object indicates the previous OpStatusReason value. It will be updated after new OpCommand is set and delivered to upgrade process.')
ciuUpgradeJobStatusNotifyOnCompletion = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 4, 11), TruthValue()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: ciuUpgradeJobStatusNotifyOnCompletion.setStatus('current')
if mibBuilder.loadTexts: ciuUpgradeJobStatusNotifyOnCompletion.setDescription("This object specifies whether or not ciuUpgradeJobStatusCompletionNotify notification should be generated on the completion of an operation. If 'true', ciuUpgradeJobStatusCompletionNotify will be generated, else if 'false' it would not be.")
ciuUpgradeTargetTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 5), )
if mibBuilder.loadTexts: ciuUpgradeTargetTable.setStatus('current')
if mibBuilder.loadTexts: ciuUpgradeTargetTable.setDescription('A table listing the modules and the type of upgrade operation to be performed on these modules. ')
ciuUpgradeTargetEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 5, 1), ).setIndexNames((0, "ENTITY-MIB", "entPhysicalIndex"))
if mibBuilder.loadTexts: ciuUpgradeTargetEntry.setStatus('current')
if mibBuilder.loadTexts: ciuUpgradeTargetEntry.setDescription("Each entry provides the module that needs to be upgraded and the type of operation that needs to be performed on this module. The upgrade operation, selected using the object 'ciuUpgradeOpCommand', would be performed on each and every module represented by an entry in this table. Each such module of the type PhysicalClass module(9), has an entry in entPhysicalTable in ENTITY-MIB, where that entry is identified by entPhysicalIndex. Only modules capable of running images, identified by ciuImageVariableName would have an entry in this table. This table cannot be modified when ciuUpgradeOpCommand object contains value other than 'none'. ")
ciuUpgradeTargetAction = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 5, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("image", 1), ("bios", 2), ("loader", 3), ("bootrom", 4)))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: ciuUpgradeTargetAction.setStatus('current')
if mibBuilder.loadTexts: ciuUpgradeTargetAction.setDescription("The type of operation to be performed on this module. image - upgrade image. bios - upgrade bios. loader - upgrade loader.loader is the program that loads and starts the operating system bootrom - upgrade boot rom This object cannot be modified while the corresponding value of ciuUpgradeTargetEntryStatus is equal to 'active'. It is okay to support only a subset of the enums defined above. ")
ciuUpgradeTargetEntryStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 5, 1, 2), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: ciuUpgradeTargetEntryStatus.setStatus('current')
if mibBuilder.loadTexts: ciuUpgradeTargetEntryStatus.setDescription('The status of this table entry. A multivarbind set containing this object and ciuUpgradeTargetAction must be done in the same PDU for the operation to succeed. ')
ciuImageLocInputTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 6), )
if mibBuilder.loadTexts: ciuImageLocInputTable.setStatus('current')
if mibBuilder.loadTexts: ciuImageLocInputTable.setDescription('A table listing the URI of the images that need to be upgraded. ')
ciuImageLocInputEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 6, 1), ).setIndexNames((0, "CISCO-IMAGE-UPGRADE-MIB", "ciuImageVariableName"))
if mibBuilder.loadTexts: ciuImageLocInputEntry.setStatus('current')
if mibBuilder.loadTexts: ciuImageLocInputEntry.setDescription("Each entry provides the image location URI that need to be upgraded. This table cannot be modified if ciuUpgradeOpCommand object contains any value other than 'none' ")
ciuImageLocInputURI = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 6, 1, 1), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 255))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: ciuImageLocInputURI.setStatus('current')
if mibBuilder.loadTexts: ciuImageLocInputURI.setDescription("An ASCII string specifying the system image location. For example the string could be 'bootflash:file1'. This object cannot be modified while the corresponding value of ciuImageLocInputEntryStatus is equal to 'active'. ")
ciuImageLocInputEntryStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 6, 1, 2), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: ciuImageLocInputEntryStatus.setStatus('current')
if mibBuilder.loadTexts: ciuImageLocInputEntryStatus.setDescription('The status of this table entry. ')
ciuVersionCompChkTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 7), )
if mibBuilder.loadTexts: ciuVersionCompChkTable.setStatus('current')
if mibBuilder.loadTexts: ciuVersionCompChkTable.setDescription("A table showing the result of the version compatibility check operation performed in response to the option 'check' selected for ciuUpgradeOpCommand. The table would be emptied out once the value of ciuUpgradeOpCommand object is 'none'. ")
ciuVersionCompChkEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 7, 1), ).setIndexNames((0, "ENTITY-MIB", "entPhysicalIndex"))
if mibBuilder.loadTexts: ciuVersionCompChkEntry.setStatus('current')
if mibBuilder.loadTexts: ciuVersionCompChkEntry.setDescription('An entry containing the results of the version compatibility check operation performed on each module, identified by entPhysicalIndex. Each such module of the type PhysicalClass module(9), has an entry in entPhysicalTable in ENTITY-MIB, where that entry is identified by entPhysicalIndex. Only modules capable of running images, identified by ciuImageVariableName would have an entry in this table. ')
ciuVersionCompImageSame = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 7, 1, 1), TruthValue()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ciuVersionCompImageSame.setStatus('current')
if mibBuilder.loadTexts: ciuVersionCompImageSame.setDescription(' Specifies whether for this module the image provided by the user for upgrade is same as the current running image. ')
ciuVersionCompUpgradable = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 7, 1, 2), TruthValue()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ciuVersionCompUpgradable.setStatus('current')
if mibBuilder.loadTexts: ciuVersionCompUpgradable.setDescription(" Specifies whether the set of images provided in ciuImageLocInputTable are compatible with each other as far as this module is concerned. If 'true' the set of images provided are compatible and can be run on this module else they are not compatible. This module would not come up if it is booted with a uncompatible set of image. ")
ciuVersionCompUpgradeAction = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 7, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8))).clone(namedValues=NamedValues(("none", 1), ("other", 2), ("rollingUpgrade", 3), ("switchOverReset", 4), ("reset", 5), ("copy", 6), ("notApplicable", 7), ("plugin", 8)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: ciuVersionCompUpgradeAction.setStatus('current')
if mibBuilder.loadTexts: ciuVersionCompUpgradeAction.setDescription(" Specifies the type of upgrade action that would be performed on this module if ciuUpgradeOpCommand were set to 'install' or to 'check'. none(1) : is no upgrade action. other(2) : actions other than defined here rollingUpgrade(3) : modules would be upgraded one at a time. switchOverReset(4): all the modules would be reset after a switchover happens at the same time. reset(5) : all the modules would be reset without or before a switchover. copy(6) : then image upgrade would not be done, but only bios/loader/bootrom would be updated and will take effect on next reload. notApplicable(7) : upgrade action is not possible because image is not upgradable. plugin(8) : upgrading plugin only instead of full image.")
ciuVersionCompUpgradeBios = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 7, 1, 4), TruthValue()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ciuVersionCompUpgradeBios.setStatus('current')
if mibBuilder.loadTexts: ciuVersionCompUpgradeBios.setDescription(" Specifies whether the BIOS will be upgraded. If 'true' the bios would be upgraded else it would not.")
ciuVersionCompUpgradeBootrom = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 7, 1, 5), TruthValue()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ciuVersionCompUpgradeBootrom.setStatus('current')
if mibBuilder.loadTexts: ciuVersionCompUpgradeBootrom.setDescription(" Specifies whether the bootrom will be upgraded. If 'true' the bootrom would be upgraded else it would not.")
ciuVersionCompUpgradeLoader = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 7, 1, 6), TruthValue()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ciuVersionCompUpgradeLoader.setStatus('current')
if mibBuilder.loadTexts: ciuVersionCompUpgradeLoader.setDescription(" Specifies whether the loader will be upgraded. If 'true' the loader would be upgraded else it would not.")
ciuVersionCompUpgradeImpact = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 7, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("other", 1), ("nonDisruptive", 2), ("disruptive", 3), ("notApplicable", 4)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: ciuVersionCompUpgradeImpact.setStatus('current')
if mibBuilder.loadTexts: ciuVersionCompUpgradeImpact.setDescription(' Specifies the impact of the upgrade operation that would have on this module. other(1) : reasons other than defined here nonDisruptive(2): this module would be upgraded without disruption of traffic. disruptive(3) : this module would be upgraded with disruption of traffic. notApplicable(4): upgrade is not possible because image is not upgradable. ')
ciuVersionCompUpgradeReason = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 7, 1, 8), SnmpAdminString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ciuVersionCompUpgradeReason.setStatus('current')
if mibBuilder.loadTexts: ciuVersionCompUpgradeReason.setDescription("This object would give the reason for the following cases: 1)value of object ciuVersionCompUpgradable is 'false' then it would give the reason why the module is not upgradable. 2)the value of object ciuversionCompUpgradeAction is either 'switchOverReset' or 'reset' and value of object ciuVersionCompUpgradable is 'true'. 3)the value of object ciuVersionCompUpgradeImpact is 'disruptive' and value of objects, ciuVersionCompUpgradable is 'true' and ciuversionCompUpgradeAction is neither 'switchOverReset' nor 'reset. This object would have the reason in the above listed order. It would be a null string for all the other values of the above mentioned objects. ")
ciuUpgradeImageVersionTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 8), )
if mibBuilder.loadTexts: ciuUpgradeImageVersionTable.setStatus('current')
if mibBuilder.loadTexts: ciuUpgradeImageVersionTable.setDescription("A table showing the current version of images running on the modules and the images they would be upgraded with. The table would be emptied out once the value of ciuUpgradeOpCommand object is 'none'. This table becomes valid when value of ciuUpgradeOpStatus is 'success' in response to 'check' operation selected using ciuUpgradeOpCommand. ")
ciuUpgradeImageVersionEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 8, 1), ).setIndexNames((0, "ENTITY-MIB", "entPhysicalIndex"), (0, "CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeImageVersionIndex"))
if mibBuilder.loadTexts: ciuUpgradeImageVersionEntry.setStatus('current')
if mibBuilder.loadTexts: ciuUpgradeImageVersionEntry.setDescription('An entry containing the current version of image running on a particular module and the images they would be upgraded with. An ciuUpgradeImageVersionVarName identifies the type of software running on this module, identified by entPhysicalIndex. It is possible that the same module, identified by entPhysicalIndex, can run multiple instances of the software type identified by ciuUpgradeImageVersionVarName. Each such module of the type PhysicalClass module(9), has an entry in entPhysicalTable in ENTITY-MIB, where that entry is identified by entPhysicalIndex. Only modules capable of running images, identified by ciuImageVariableName would have an entry in this table. ')
ciuUpgradeImageVersionIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 8, 1, 1), Unsigned32())
if mibBuilder.loadTexts: ciuUpgradeImageVersionIndex.setStatus('current')
if mibBuilder.loadTexts: ciuUpgradeImageVersionIndex.setDescription('This is an arbitrary integer which uniquely identifies different rows which have the same value of entPhysicalIndex.')
ciuUpgradeImageVersionVarName = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 8, 1, 2), CiuImageVariableTypeName()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ciuUpgradeImageVersionVarName.setStatus('current')
if mibBuilder.loadTexts: ciuUpgradeImageVersionVarName.setDescription('The type of image on this module. ')
ciuUpgradeImageVersionRunning = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 8, 1, 3), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: ciuUpgradeImageVersionRunning.setStatus('current')
if mibBuilder.loadTexts: ciuUpgradeImageVersionRunning.setDescription('An ASCII string specifying the running image version. ')
ciuUpgradeImageVersionNew = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 8, 1, 4), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: ciuUpgradeImageVersionNew.setStatus('current')
if mibBuilder.loadTexts: ciuUpgradeImageVersionNew.setDescription('An ASCII string specifying what the new image version would be after an upgrade. ')
ciuUpgradeImageVersionUpgReqd = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 8, 1, 5), TruthValue()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ciuUpgradeImageVersionUpgReqd.setStatus('current')
if mibBuilder.loadTexts: ciuUpgradeImageVersionUpgReqd.setDescription(" Specifies whether an upgrade is required for this software component, identified by entPhysicalIndex and ciuUpgradeImageVersionVarName. If the value of objects ciuUpgradeImageVersionRunning and ciuUpgradeImageVersionNew are same then the value of this object would be 'false' else it would be 'true'. If 'true' then this software component, identified by ciuUpgradeImageVersionVarName needs to be upgraded else it would not.")
ciuUpgradeOpStatusTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 9), )
if mibBuilder.loadTexts: ciuUpgradeOpStatusTable.setStatus('current')
if mibBuilder.loadTexts: ciuUpgradeOpStatusTable.setDescription("A table showing the result of the upgrade operation selected from ciuUpgradeOpCommand in ciuUpgradeOpTable. The table would be emptied out once the value of ciuUpgradeOpCommand object is 'none'. ")
ciuUpgradeOpStatusEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 9, 1), ).setIndexNames((0, "CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeOpStatusOperIndex"))
if mibBuilder.loadTexts: ciuUpgradeOpStatusEntry.setStatus('current')
if mibBuilder.loadTexts: ciuUpgradeOpStatusEntry.setDescription('An entry containing the status of the upgrade operation. ')
ciuUpgradeOpStatusOperIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 9, 1, 1), Unsigned32())
if mibBuilder.loadTexts: ciuUpgradeOpStatusOperIndex.setStatus('current')
if mibBuilder.loadTexts: ciuUpgradeOpStatusOperIndex.setDescription('This is an arbitrary integer which identifies uniquely an entry in this table. ')
ciuUpgradeOpStatusOperation = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 9, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35))).clone(namedValues=NamedValues(("unknown", 1), ("other", 2), ("copy", 3), ("verify", 4), ("versionExtraction", 5), ("imageSync", 6), ("configSync", 7), ("preUpgrade", 8), ("forceDownload", 9), ("moduleOnline", 10), ("hitlessLCUpgrade", 11), ("hitfulLCUpgrade", 12), ("unusedBootvar", 13), ("convertStartUp", 14), ("looseIncompatibility", 15), ("haSeqNumMismatch", 16), ("unknownModuleOnline", 17), ("recommendedAction", 18), ("recoveryAction", 19), ("remainingAction", 20), ("additionalInfo", 21), ("settingBootvars", 22), ("informLcmFsUpg", 23), ("sysmgrSaveRuntimeStateAndSuccessReset", 24), ("kexecLoadUpgImages", 25), ("fsUpgCleanup", 26), ("saveMtsState", 27), ("fsUpgBegin", 28), ("lcWarmBootStatus", 29), ("waitStateVerificationStatus", 30), ("informLcmFsUpgExternalLc", 31), ("externalLcWarmBootStatus", 32), ("total", 33), ("compactFlashTcamSanity", 34), ("systemPreupgradeBegin", 35)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: ciuUpgradeOpStatusOperation.setStatus('current')
if mibBuilder.loadTexts: ciuUpgradeOpStatusOperation.setDescription("Specifies the operation that is currently in progress or completed in response to the ciuUpgradeOpCommand. 'unknown' - operation status unknown. 'other' - operation status other than defined here. 'copy' - the image is being copied from ciuUpgradeOpStatusSrcImageLoc to ciuUpgradeOpStatusDestImageLoc. 'verify' - copied images are being verified for checksum and input consistency. 'versionExtraction' - extracting the version info from image. 'imageSync' - Syncing image to the standby supervisor, if standby supervisor exists. 'configSync' - saving running configuration to startup configuration and syncing it to standby supervisor, if it exists. 'preUpgrade' - Upgrading Bios/loader/bootrom 'forceDownload' - This module is being force downloaded. 'moduleOnline' - waiting for this module to come online 'hitlessLCUpgrade' - Upgrading hitless 'hitfulLCUpgrade' - Upgrading hitful 'unusedBootvar' - The image variable name type supplied as input for upgrade operation is unused. 'convertStartUp' - converting the startup config. 'looseIncompatibility' - incomplete support for current running config in the new image. 'haSeqNumMismatch' - High availability sequence number mismatch, so the module will be power cycled. 'unknownModuleOnline' - this module was powered down before switchover and has now come online. 'recommendedAction' - Specifies the recommended action if upgrading operation fails. If this object value is 'recommendedAction' then the object 'ciuUpgradeOpStatusSrcImageLoc' would contain the string specifying the recommended action. 'recoveryAction' - Specifies that installer is doing a recovery because of install failure. If this object value is 'recoveryAction' then the object 'ciuUpgradeOpStatusSrcImageLoc' would contain the string specifying the recovery action. 'remainingAction' - Specifies the remaining actions that have not been performed due to install failure. If this object value is 'remainingAction' then the object 'ciuUpgradeOpStatusSrcImageLoc' would contain the information about the remaining actions. 'additionalInfo' - Specifies the additional info the installer conveys to the user. If this object value is 'additionalInfo' then the object 'ciuUpgradeOpStatusSrcImageLoc' would contain the information. 'settingBootvars' - setting the boot variables. 'informLcmFsUpg' - save linecard runtime state. 'sysmgrSaveRuntimeStateAndSuccessReset' - save supervisor runtime state and terminate all services. 'kexecLoadUpgImages' - load upgrade images into memory. 'fsUpgCleanup' - cleanup file system for upgrade. 'saveMtsState' - saving persistent transaction messages. 'fsUpgBegin' - notify services that upgrade is about to begin. 'lcWarmBootStatus' - linecard upgrade status. 'waitStateVerificationStatus' - supervisor state verification with the new image. 'informLcmFsUpgExternalLc' - save external linecard runtime state. 'externalLcWarmBootStatus' - external linecard upgrade status. 'total' - total. 'compactFlashTcamSanity' - compact flash and TCAM sanity test. 'systemPreupgradeBegin' - notify services of beginning of upgrade. ")
ciuUpgradeOpStatusModule = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 9, 1, 3), EntPhysicalIndexOrZero()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ciuUpgradeOpStatusModule.setStatus('current')
if mibBuilder.loadTexts: ciuUpgradeOpStatusModule.setDescription('The physical entity of the module for which this status is being shown. For example such an entity is one of the type PhysicalClass module(9). This object must contain the same value as the entPhysicalIndex of the physical entity from entPhysicalTable in ENTITY-MIB. ')
ciuUpgradeOpStatusSrcImageLoc = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 9, 1, 4), SnmpAdminString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ciuUpgradeOpStatusSrcImageLoc.setStatus('current')
if mibBuilder.loadTexts: ciuUpgradeOpStatusSrcImageLoc.setDescription("An ASCII string specifying the source image location. For example the string could be 'bootflash:file1'. This object is only valid if the value of ciuUpgradeOpStatusOperation is 'copy'.")
ciuUpgradeOpStatusDestImageLoc = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 9, 1, 5), SnmpAdminString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ciuUpgradeOpStatusDestImageLoc.setStatus('current')
if mibBuilder.loadTexts: ciuUpgradeOpStatusDestImageLoc.setDescription("An ASCII string specifying the destination image location. For example the string could be 'bootflash:file1'.")
ciuUpgradeOpStatusJobStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 9, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6))).clone(namedValues=NamedValues(("unknown", 1), ("other", 2), ("failed", 3), ("inProgress", 4), ("success", 5), ("planned", 6)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: ciuUpgradeOpStatusJobStatus.setStatus('current')
if mibBuilder.loadTexts: ciuUpgradeOpStatusJobStatus.setDescription("The status of this operation. 'unknown' - operation status unknown. 'other' - operation status other than defined here. 'failed' - this operation has failed 'inProgress' - this operation is active 'success' - this operation has completed successfully. 'planned' - this operation would be executed at later point of time.")
ciuUpgradeOpStatusPercentCompl = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 9, 1, 7), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ciuUpgradeOpStatusPercentCompl.setStatus('current')
if mibBuilder.loadTexts: ciuUpgradeOpStatusPercentCompl.setDescription('The percentage completion of the upgrade operation selected from ciuUpgradeOpTable. If this object is invalid for a particular operation, identified by ciuUpgradeOpStatusOperation, then the value of this object would be -1. ')
ciuUpgradeOpStatusJobStatusReas = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 9, 1, 8), SnmpAdminString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ciuUpgradeOpStatusJobStatusReas.setStatus('current')
if mibBuilder.loadTexts: ciuUpgradeOpStatusJobStatusReas.setDescription("Specifies the description of the cause of 'failed' state of the object 'ciuUpgradeOpStatusJobStatus'. This object would be a null string if value of 'ciuUpgradeOpStatusJobStatus' is anything other than 'failed'.")
ciuUpgradeMiscAutoCopy = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 10, 1), TruthValue().clone('false')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: ciuUpgradeMiscAutoCopy.setStatus('current')
if mibBuilder.loadTexts: ciuUpgradeMiscAutoCopy.setDescription("Specifies whether or not the images on the active supervisor will be copied to the standby supervisor, if the standby supervisor exists. If the standby supervisor does not exist, the setting of this object to 'true' will not have any effect and no image copy will be done. ciuImageURITable lists all the images for the supervisor cards as well as the line cards. If this object is set to 'true', all the images pointed to by the instances of ciuImageURI will be automatically copied to the standby supervisor. For example, assume that the ciuImageURITable looks like below - entPhysicalIndex ciuImageVariableName ciuImageURI 25 'system' bootflash://image.bin 25 'kickstart' slot0://boot.bin 26 'ilce' bootflash://linecard.bin So, if the ciuUpgradeMiscAutoCopy is 'true', then bootflash://image.bin from the active supervisor will be copied to the bootflash://image.bin on the standby supervisor; slot0://boot.bin will be copied to the slot0://boot.bin on the standby supervisor etc. If this object is set to 'false' then this copying of the images will not be done.")
ciuUpgradeMiscInfoTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 11), )
if mibBuilder.loadTexts: ciuUpgradeMiscInfoTable.setStatus('current')
if mibBuilder.loadTexts: ciuUpgradeMiscInfoTable.setDescription("A table showing additional information such as warnings during upgrade. The table would be emptied out once the value of ciuUpgradeOpCommand object is 'none'. ")
ciuUpgradeMiscInfoEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 11, 1), ).setIndexNames((0, "CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeMiscInfoIndex"))
if mibBuilder.loadTexts: ciuUpgradeMiscInfoEntry.setStatus('current')
if mibBuilder.loadTexts: ciuUpgradeMiscInfoEntry.setDescription('An entry containing additional information of upgrade operation being performed on modules. Each entry is uniquely identified by ciuUpgradeMiscInfoIndex. If the info given in object ciuUpgradeMiscInfoDescr is not for any module then the value of ciuUpgradeMiscInfoModule would be 0.')
ciuUpgradeMiscInfoIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 11, 1, 1), Unsigned32())
if mibBuilder.loadTexts: ciuUpgradeMiscInfoIndex.setStatus('current')
if mibBuilder.loadTexts: ciuUpgradeMiscInfoIndex.setDescription('This is an arbitrary integer which identifies uniquely an entry in this table. ')
ciuUpgradeMiscInfoModule = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 11, 1, 2), EntPhysicalIndexOrZero()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ciuUpgradeMiscInfoModule.setStatus('current')
if mibBuilder.loadTexts: ciuUpgradeMiscInfoModule.setDescription('The entPhysicalIndex of the module. The value of this object would be 0 if the information shown in ciuUpgradeMiscInfoDescr is not for any module.')
ciuUpgradeMiscInfoDescr = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 11, 1, 3), SnmpAdminString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: ciuUpgradeMiscInfoDescr.setStatus('current')
if mibBuilder.loadTexts: ciuUpgradeMiscInfoDescr.setDescription('Specifies the miscelleneous information of the upgrade operation.')
ciuUpgradeOpCompletionNotify = NotificationType((1, 3, 6, 1, 4, 1, 9, 9, 360, 0, 1)).setObjects(("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeOpCommand"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeOpStatus"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeOpTimeCompleted"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeOpLastCommand"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeOpLastStatus"))
if mibBuilder.loadTexts: ciuUpgradeOpCompletionNotify.setStatus('current')
if mibBuilder.loadTexts: ciuUpgradeOpCompletionNotify.setDescription('A ciuUpgradeOpCompletionNotify is sent at the completion of upgrade operation denoted by ciuUpgradeOpCommand object if such a notification was requested when the operation was initiated. ciuUpgradeOpCommand indicates the type of operation. ciuUpgradeOpStatus indicates the result of the operation. ciuUpgradeOpTimeCompleted indicates the time when the operation is completed. ciuUpgradeopLastCommand indicates the previous operation that was executed. ciuUpgradeOpLastStatus indicates the result of previous operation.')
ciuUpgradeJobStatusNotify = NotificationType((1, 3, 6, 1, 4, 1, 9, 9, 360, 0, 2)).setObjects(("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeOpStatusOperation"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeOpStatusModule"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeOpStatusSrcImageLoc"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeOpStatusDestImageLoc"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeOpStatusJobStatus"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeOpStatusPercentCompl"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeOpStatusJobStatusReas"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeOpStatus"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeOpStatusReason"))
if mibBuilder.loadTexts: ciuUpgradeJobStatusNotify.setStatus('current')
if mibBuilder.loadTexts: ciuUpgradeJobStatusNotify.setDescription('A ciuUpgradeJobStatusNotify is sent when there is status change in the upgrade process. ciuUpgradeOpStatusOperation indicates the operation to change the upgrade status. ciuUpgradeOpStatusModule indicates which module is affected. ciuUpgradeOpStatusSrcImageLoc indicates location of source image if applicable. ciuUpgradeOpStatusDestImageLoc indicates location of destination image if applicable. ciuUpgradeOpStatusJobStatus indicates the result of this operation to change the status. ciuUpgradeOpStatusPercentCompl indicates percentage of the operation that has been completed. ciuUpgradeOpStatusJobStatusReas gives explanation of the faiure if there is a failure. ciuUpgradeOpStatus indicates the result of the operation at higher level. ciuUpgradeOpStatusReason gives detailed explanation if ciuUpgradeOpStatus is not successful.')
ciuImageUpgradeCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 360, 2, 1))
ciuImageUpgradeGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 360, 2, 2))
ciuImageUpgradeCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 360, 2, 1, 1)).setObjects(("CISCO-IMAGE-UPGRADE-MIB", "ciuImageUpgradeGroup"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuImageVariableGroup"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuImageURIGroup"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeOpGroup"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuImageLocInputGroup"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuVersionCompChkGroup"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeImageVersionGroup"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeOpStatusGroup"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeNotificationGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciuImageUpgradeCompliance = ciuImageUpgradeCompliance.setStatus('deprecated')
if mibBuilder.loadTexts: ciuImageUpgradeCompliance.setDescription("Compliance statement for Image Upgrade MIB. For the (mandatory) ciuImageLocInputGroup, it is compliant to allow only a limited number of entries to be created and concurrently 'active' in the ciuImageLocInputTable table. ")
ciuImageUpgradeComplianceRev1 = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 360, 2, 1, 2)).setObjects(("CISCO-IMAGE-UPGRADE-MIB", "ciuImageUpgradeGroup"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuImageVariableGroup"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuImageURIGroup"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeOpGroup"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuImageLocInputGroup"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuVersionCompChkGroup"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeImageVersionGroup"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeOpStatusGroup"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeNotificationGroup"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeMiscGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciuImageUpgradeComplianceRev1 = ciuImageUpgradeComplianceRev1.setStatus('deprecated')
if mibBuilder.loadTexts: ciuImageUpgradeComplianceRev1.setDescription("Compliance statement for Image Upgrade MIB. For the (mandatory) ciuImageLocInputGroup, it is compliant to allow only a limited number of entries to be created and concurrently 'active' in the ciuImageLocInputTable table. ")
ciuImageUpgradeComplianceRev2 = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 360, 2, 1, 3)).setObjects(("CISCO-IMAGE-UPGRADE-MIB", "ciuImageUpgradeGroup"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuImageVariableGroup"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuImageURIGroup"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeOpGroup"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuImageLocInputGroup"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuVersionCompChkGroup"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeImageVersionGroup"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeOpStatusGroup"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeNotificationGroup"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeMiscGroup"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeMiscInfoGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciuImageUpgradeComplianceRev2 = ciuImageUpgradeComplianceRev2.setStatus('deprecated')
if mibBuilder.loadTexts: ciuImageUpgradeComplianceRev2.setDescription("Compliance statement for Image Upgrade MIB. For the (mandatory) ciuImageLocInputGroup, it is compliant to allow only a limited number of entries to be created and concurrently 'active' in the ciuImageLocInputTable table.")
ciuImageUpgradeComplianceRev3 = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 360, 2, 1, 4)).setObjects(("CISCO-IMAGE-UPGRADE-MIB", "ciuImageUpgradeGroup"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuImageVariableGroup"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuImageURIGroup"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeOpGroup"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuImageLocInputGroup"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuVersionCompChkGroup"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeImageVersionGroup"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeOpStatusGroup"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeNotificationGroup"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeNotificationGroupSup"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeMiscGroup"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeMiscInfoGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciuImageUpgradeComplianceRev3 = ciuImageUpgradeComplianceRev3.setStatus('deprecated')
if mibBuilder.loadTexts: ciuImageUpgradeComplianceRev3.setDescription("Compliance statement for Image Upgrade MIB. For the (mandatory) ciuImageLocInputGroup, it is compliant to allow only a limited number of entries to be created and concurrently 'active' in the ciuImageLocInputTable table.")
ciuImageUpgradeComplianceRev4 = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 360, 2, 1, 5)).setObjects(("CISCO-IMAGE-UPGRADE-MIB", "ciuImageUpgradeGroup"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuImageVariableGroup"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuImageURIGroup"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeOpGroup"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuImageLocInputGroup"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuVersionCompChkGroup"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeImageVersionGroup"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeOpStatusGroup"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeNotificationGroup"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeNotificationGroupSup"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeMiscGroup"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeMiscInfoGroup"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeOpNewGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciuImageUpgradeComplianceRev4 = ciuImageUpgradeComplianceRev4.setStatus('current')
if mibBuilder.loadTexts: ciuImageUpgradeComplianceRev4.setDescription("Compliance statement for Image Upgrade MIB. For the (mandatory) ciuImageLocInputGroup, it is compliant to allow only a limited number of entries to be created and concurrently 'active' in the ciuImageLocInputTable table.")
ciuImageUpgradeGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 360, 2, 2, 1)).setObjects(("CISCO-IMAGE-UPGRADE-MIB", "ciuTotalImageVariables"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciuImageUpgradeGroup = ciuImageUpgradeGroup.setStatus('current')
if mibBuilder.loadTexts: ciuImageUpgradeGroup.setDescription('A collection of objects providing information about Image upgrade. ')
ciuImageVariableGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 360, 2, 2, 2)).setObjects(("CISCO-IMAGE-UPGRADE-MIB", "ciuImageVariableName"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciuImageVariableGroup = ciuImageVariableGroup.setStatus('current')
if mibBuilder.loadTexts: ciuImageVariableGroup.setDescription('A group containing an object providing information about the type of the system images.')
ciuImageURIGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 360, 2, 2, 3)).setObjects(("CISCO-IMAGE-UPGRADE-MIB", "ciuImageURI"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciuImageURIGroup = ciuImageURIGroup.setStatus('current')
if mibBuilder.loadTexts: ciuImageURIGroup.setDescription('A group containing an object providing information about the name of system variable or parameter.')
ciuUpgradeOpGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 360, 2, 2, 4)).setObjects(("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeOpCommand"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeOpStatus"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeOpNotifyOnCompletion"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeOpTimeStarted"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeOpTimeCompleted"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeOpAbort"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeOpStatusReason"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciuUpgradeOpGroup = ciuUpgradeOpGroup.setStatus('current')
if mibBuilder.loadTexts: ciuUpgradeOpGroup.setDescription('A collection of objects for Upgrade operation.')
ciuUpgradeTargetGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 360, 2, 2, 5)).setObjects(("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeTargetAction"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeTargetEntryStatus"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciuUpgradeTargetGroup = ciuUpgradeTargetGroup.setStatus('current')
if mibBuilder.loadTexts: ciuUpgradeTargetGroup.setDescription('A collection of objects giving the modules and the type of image to be upgraded.')
ciuImageLocInputGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 360, 2, 2, 6)).setObjects(("CISCO-IMAGE-UPGRADE-MIB", "ciuImageLocInputURI"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuImageLocInputEntryStatus"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciuImageLocInputGroup = ciuImageLocInputGroup.setStatus('current')
if mibBuilder.loadTexts: ciuImageLocInputGroup.setDescription('A collection of objects giving the location of the images to be upgraded.')
ciuVersionCompChkGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 360, 2, 2, 7)).setObjects(("CISCO-IMAGE-UPGRADE-MIB", "ciuVersionCompImageSame"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuVersionCompUpgradable"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuVersionCompUpgradeAction"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuVersionCompUpgradeBios"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuVersionCompUpgradeBootrom"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuVersionCompUpgradeLoader"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuVersionCompUpgradeImpact"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuVersionCompUpgradeReason"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciuVersionCompChkGroup = ciuVersionCompChkGroup.setStatus('current')
if mibBuilder.loadTexts: ciuVersionCompChkGroup.setDescription('A collection of objects showing the results of the version compatibility check done.')
ciuUpgradeImageVersionGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 360, 2, 2, 8)).setObjects(("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeImageVersionVarName"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeImageVersionRunning"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeImageVersionNew"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeImageVersionUpgReqd"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciuUpgradeImageVersionGroup = ciuUpgradeImageVersionGroup.setStatus('current')
if mibBuilder.loadTexts: ciuUpgradeImageVersionGroup.setDescription('A collection of objects showing the current running images and the images to be upgraded with.')
ciuUpgradeOpStatusGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 360, 2, 2, 9)).setObjects(("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeOpStatusOperation"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeOpStatusModule"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeOpStatusSrcImageLoc"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeOpStatusDestImageLoc"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeOpStatusJobStatus"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeOpStatusPercentCompl"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeOpStatusJobStatusReas"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciuUpgradeOpStatusGroup = ciuUpgradeOpStatusGroup.setStatus('current')
if mibBuilder.loadTexts: ciuUpgradeOpStatusGroup.setDescription('A collection of objects showing the status of the upgrade operation.')
ciuUpgradeNotificationGroup = NotificationGroup((1, 3, 6, 1, 4, 1, 9, 9, 360, 2, 2, 10)).setObjects(("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeOpCompletionNotify"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciuUpgradeNotificationGroup = ciuUpgradeNotificationGroup.setStatus('current')
if mibBuilder.loadTexts: ciuUpgradeNotificationGroup.setDescription('A collection of notifications for upgrade operations. ')
ciuUpgradeMiscGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 360, 2, 2, 11)).setObjects(("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeMiscAutoCopy"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciuUpgradeMiscGroup = ciuUpgradeMiscGroup.setStatus('current')
if mibBuilder.loadTexts: ciuUpgradeMiscGroup.setDescription('A collection of objects for Miscelleneous operation.')
ciuUpgradeMiscInfoGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 360, 2, 2, 12)).setObjects(("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeMiscInfoModule"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeMiscInfoDescr"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciuUpgradeMiscInfoGroup = ciuUpgradeMiscInfoGroup.setStatus('current')
if mibBuilder.loadTexts: ciuUpgradeMiscInfoGroup.setDescription('A collection of objects for Miscelleneous info for upgrade operation.')
ciuUpgradeNotificationGroupSup = NotificationGroup((1, 3, 6, 1, 4, 1, 9, 9, 360, 2, 2, 13)).setObjects(("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeJobStatusNotify"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciuUpgradeNotificationGroupSup = ciuUpgradeNotificationGroupSup.setStatus('current')
if mibBuilder.loadTexts: ciuUpgradeNotificationGroupSup.setDescription('A collection of notifications for upgrade operations. ')
ciuUpgradeOpNewGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 360, 2, 2, 14)).setObjects(("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeJobStatusNotifyOnCompletion"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeOpLastCommand"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeOpLastStatus"), ("CISCO-IMAGE-UPGRADE-MIB", "ciuUpgradeOpLastStatusReason"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciuUpgradeOpNewGroup = ciuUpgradeOpNewGroup.setStatus('current')
if mibBuilder.loadTexts: ciuUpgradeOpNewGroup.setDescription('A collection of objects for Upgrade operation.')
mibBuilder.exportSymbols("CISCO-IMAGE-UPGRADE-MIB", ciuUpgradeImageVersionUpgReqd=ciuUpgradeImageVersionUpgReqd, ciuUpgradeOpAbort=ciuUpgradeOpAbort, ciuImageLocInputURI=ciuImageLocInputURI, ciuUpgradeOpGroup=ciuUpgradeOpGroup, ciuUpgradeOpStatusReason=ciuUpgradeOpStatusReason, ciuVersionCompUpgradeReason=ciuVersionCompUpgradeReason, ciuTotalImageVariables=ciuTotalImageVariables, ciuUpgradeJobStatusNotify=ciuUpgradeJobStatusNotify, ciuUpgradeImageVersionTable=ciuUpgradeImageVersionTable, ciuUpgradeTargetAction=ciuUpgradeTargetAction, ciuUpgradeOpStatusOperation=ciuUpgradeOpStatusOperation, ciuImageVariableName=ciuImageVariableName, ciuUpgradeImageVersionIndex=ciuUpgradeImageVersionIndex, ciuUpgradeOpStatusModule=ciuUpgradeOpStatusModule, ciuVersionCompChkGroup=ciuVersionCompChkGroup, ciuVersionCompUpgradeImpact=ciuVersionCompUpgradeImpact, ciuUpgradeMiscGroup=ciuUpgradeMiscGroup, ciuUpgradeOpStatusOperIndex=ciuUpgradeOpStatusOperIndex, ciuImageUpgradeGroup=ciuImageUpgradeGroup, ciuImageLocInputEntryStatus=ciuImageLocInputEntryStatus, ciuUpgradeOpStatus=ciuUpgradeOpStatus, ciuImageURIGroup=ciuImageURIGroup, ciuUpgradeMiscInfoTable=ciuUpgradeMiscInfoTable, ciuUpgradeTargetEntry=ciuUpgradeTargetEntry, ciscoImageUpgradeMIB=ciscoImageUpgradeMIB, ciuImageVariableTable=ciuImageVariableTable, ciuUpgradeOpStatusJobStatusReas=ciuUpgradeOpStatusJobStatusReas, ciuUpgradeOpLastCommand=ciuUpgradeOpLastCommand, ciuVersionCompUpgradeBios=ciuVersionCompUpgradeBios, ciuImageUpgradeComplianceRev3=ciuImageUpgradeComplianceRev3, ciuVersionCompUpgradeLoader=ciuVersionCompUpgradeLoader, ciuUpgradeTargetTable=ciuUpgradeTargetTable, ciuUpgradeOpCompletionNotify=ciuUpgradeOpCompletionNotify, ciscoImageUpgradeMIBObjects=ciscoImageUpgradeMIBObjects, ciuVersionCompChkTable=ciuVersionCompChkTable, ciuUpgradeOpStatusTable=ciuUpgradeOpStatusTable, ciuImageURI=ciuImageURI, ciuUpgradeOpStatusSrcImageLoc=ciuUpgradeOpStatusSrcImageLoc, ciuImageLocInputEntry=ciuImageLocInputEntry, ciuUpgradeImageVersionGroup=ciuUpgradeImageVersionGroup, ciuVersionCompImageSame=ciuVersionCompImageSame, ciuUpgradeMiscInfoGroup=ciuUpgradeMiscInfoGroup, ciuUpgradeOpLastStatusReason=ciuUpgradeOpLastStatusReason, ciuUpgradeMiscInfoIndex=ciuUpgradeMiscInfoIndex, ciuUpgradeMiscInfoEntry=ciuUpgradeMiscInfoEntry, ciuUpgradeImageVersionRunning=ciuUpgradeImageVersionRunning, ciuImageVariableEntry=ciuImageVariableEntry, CiuImageVariableTypeName=CiuImageVariableTypeName, ciscoImageUpgradeMisc=ciscoImageUpgradeMisc, ciscoImageUpgradeConfig=ciscoImageUpgradeConfig, ciuImageUpgradeCompliances=ciuImageUpgradeCompliances, ciuUpgradeOpStatusDestImageLoc=ciuUpgradeOpStatusDestImageLoc, ciuImageLocInputGroup=ciuImageLocInputGroup, ciuUpgradeOpTimeCompleted=ciuUpgradeOpTimeCompleted, ciuUpgradeMiscInfoModule=ciuUpgradeMiscInfoModule, ciuUpgradeTargetGroup=ciuUpgradeTargetGroup, ciuImageVariableGroup=ciuImageVariableGroup, ciuImageURITable=ciuImageURITable, ciscoImageUpgradeMIBNotifs=ciscoImageUpgradeMIBNotifs, ciuVersionCompUpgradeAction=ciuVersionCompUpgradeAction, ciuUpgradeMiscAutoCopy=ciuUpgradeMiscAutoCopy, ciuUpgradeOpNotifyOnCompletion=ciuUpgradeOpNotifyOnCompletion, ciuUpgradeImageVersionNew=ciuUpgradeImageVersionNew, ciuUpgradeOpCommand=ciuUpgradeOpCommand, ciuImageUpgradeGroups=ciuImageUpgradeGroups, ciuVersionCompUpgradeBootrom=ciuVersionCompUpgradeBootrom, ciuUpgradeOpStatusPercentCompl=ciuUpgradeOpStatusPercentCompl, ciuUpgradeNotificationGroupSup=ciuUpgradeNotificationGroupSup, ciuUpgradeOpStatusJobStatus=ciuUpgradeOpStatusJobStatus, ciuUpgradeJobStatusNotifyOnCompletion=ciuUpgradeJobStatusNotifyOnCompletion, ciuUpgradeOpNewGroup=ciuUpgradeOpNewGroup, ciuUpgradeImageVersionEntry=ciuUpgradeImageVersionEntry, ciuUpgradeOpTimeStarted=ciuUpgradeOpTimeStarted, ciuUpgradeTargetEntryStatus=ciuUpgradeTargetEntryStatus, ciuImageUpgradeComplianceRev4=ciuImageUpgradeComplianceRev4, ciuUpgradeOpStatusGroup=ciuUpgradeOpStatusGroup, ciuImageURIEntry=ciuImageURIEntry, ciuUpgradeOpLastStatus=ciuUpgradeOpLastStatus, ciuVersionCompUpgradable=ciuVersionCompUpgradable, ciuVersionCompChkEntry=ciuVersionCompChkEntry, ciuUpgradeMiscInfoDescr=ciuUpgradeMiscInfoDescr, ciuImageLocInputTable=ciuImageLocInputTable, ciuUpgradeImageVersionVarName=ciuUpgradeImageVersionVarName, ciuImageUpgradeCompliance=ciuImageUpgradeCompliance, ciuUpgradeNotificationGroup=ciuUpgradeNotificationGroup, ciscoImageUpgradeMIBConform=ciscoImageUpgradeMIBConform, ciuImageUpgradeComplianceRev2=ciuImageUpgradeComplianceRev2, ciuUpgradeOpStatusEntry=ciuUpgradeOpStatusEntry, PYSNMP_MODULE_ID=ciscoImageUpgradeMIB, ciuImageUpgradeComplianceRev1=ciuImageUpgradeComplianceRev1, ciscoImageUpgradeOp=ciscoImageUpgradeOp)
|
(integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, constraints_intersection, value_size_constraint, single_value_constraint, constraints_union) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueRangeConstraint', 'ConstraintsIntersection', 'ValueSizeConstraint', 'SingleValueConstraint', 'ConstraintsUnion')
(cisco_mgmt,) = mibBuilder.importSymbols('CISCO-SMI', 'ciscoMgmt')
(ent_physical_index_or_zero,) = mibBuilder.importSymbols('CISCO-TC', 'EntPhysicalIndexOrZero')
(ent_physical_index,) = mibBuilder.importSymbols('ENTITY-MIB', 'entPhysicalIndex')
(snmp_admin_string,) = mibBuilder.importSymbols('SNMP-FRAMEWORK-MIB', 'SnmpAdminString')
(module_compliance, object_group, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'ObjectGroup', 'NotificationGroup')
(mib_scalar, mib_table, mib_table_row, mib_table_column, time_ticks, unsigned32, integer32, iso, counter64, module_identity, object_identity, gauge32, ip_address, mib_identifier, counter32, bits, notification_type) = mibBuilder.importSymbols('SNMPv2-SMI', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'TimeTicks', 'Unsigned32', 'Integer32', 'iso', 'Counter64', 'ModuleIdentity', 'ObjectIdentity', 'Gauge32', 'IpAddress', 'MibIdentifier', 'Counter32', 'Bits', 'NotificationType')
(row_status, display_string, time_stamp, textual_convention, truth_value) = mibBuilder.importSymbols('SNMPv2-TC', 'RowStatus', 'DisplayString', 'TimeStamp', 'TextualConvention', 'TruthValue')
cisco_image_upgrade_mib = module_identity((1, 3, 6, 1, 4, 1, 9, 9, 360))
ciscoImageUpgradeMIB.setRevisions(('2011-03-28 00:00', '2008-03-18 00:00', '2007-07-18 00:00', '2006-12-21 00:00', '2004-01-20 00:00', '2003-11-04 00:00', '2003-10-28 00:00', '2003-07-11 00:00', '2003-07-08 00:00', '2003-06-01 00:00'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts:
ciscoImageUpgradeMIB.setRevisionsDescriptions(("Added new group ciuUpgradeOpNewGroup. Added new enum 'systemPreupgradeBegin' to ciuUpgradeOpStatusOperation. Added ciuUpgradeOpLastCommand and ciuUpgradeOpLastStatus to the varbind list of ciuUpgradeOpCompletionNotify. Added new compliance ciuImageUpgradeComplianceRev4 and deprecated ciuImageUpgradeComplianceRev3. Added ciuUpgradeJobStatusNotifyOnCompletion.", "Added new enum 'compactFlashTcamSanity' to ciuUpgradeOpStatusOperation.", 'Added new enums to ciuUpgradeOpStatusOperation.', 'Added new enums to ciuUpgradeOpStatus and ciuUpgradeOpStatusOperation. Added new trap ciuUpgradeJobStatusNotify. Changed type for ciuUpgradeOpStatusModule to EntPhysicalIndexOrZero. Added ciuUpgradeNotificationGroupSup group, deprecated ciuImageUpgradeComplianceRev2 and added ciuImageUpgradeComplianceRev3 ', "Added new enums to ciuUpgradeOpStatus and ciuUpgradeOpStatusOperation. Corrected description for 'configSync' enum defined in ciuUpgradeOpStatusOperation object. ", 'Updated compliance statement. Removed ciuImageLocInputGroup from conditionally mandatory.', 'Added ciuUpgradeMiscInfoTable. Added more enums to ciuUpgradeOpStatusOperation. Added ciuUpgradeMiscInfoGroup, deprecated ciuImageUpgradeComplianceRev1 and added ciuImageUpgradeComplianceRev2.', 'Changed: ciuImageLocInputURI identifier from 2 to 1, ciuImageLocInputEntryStatus identifier from 3 to 2 and ciuImageVariableName from 2 to 1. Added recommendedAction to ciuUpgradeOpStatusOperation.', 'Added ciscoImageUpgradeMisc, added ciuUpgradeMiscAutoCopy under the group ciscoImageUpgradeMisc. Added ciuUpgradeMiscGroup, deprecated ciuImageUpgradeCompliance and added ciuImageUpgradeComplianceReve1.', 'Initial version of this MIB module.'))
if mibBuilder.loadTexts:
ciscoImageUpgradeMIB.setLastUpdated('201103280000Z')
if mibBuilder.loadTexts:
ciscoImageUpgradeMIB.setOrganization('Cisco Systems Inc.')
if mibBuilder.loadTexts:
ciscoImageUpgradeMIB.setContactInfo(' Cisco Systems Customer Service Postal: 170 W Tasman Drive San Jose, CA 95134 USA Tel: +1 800 553 -NETS E-mail: cs-san@cisco.com')
if mibBuilder.loadTexts:
ciscoImageUpgradeMIB.setDescription("This mib provides, objects to upgrade images on modules in the system, objects showing the status of the upgrade operation, and objects showing the type of images that could be run in the system. For example the modules could be Controller card, Line card .. etc. The system fills up the ciuImageVariableTable with the type of images the system can support. For performing an upgrade operation a management application must first read this table and use this info in other tables, as explained below. The ciuImageURITable table is also filled by the system and provides the image name presently running for each type of image in the system. The user is allowed to configure a new image name for each image type as listed in ciuImageVariableTable. The system would use this image on the particular module on the next reboot. The management application on deciding to do an upgrade operation must first check if an upgrade operation is already in progress in the system. This is done by reading the ciuUpgradeOpCommand and if it contains 'none', signifies that no other upgrade operation is in progress. Any other value, signifies that upgrade is in progress and a new upgrade operation is not allowed. To start an 'install' operation, first the user must perform a 'check' operation to do the version compatibility for the given set of image files (provided using the ciuImageLocInputTable) against the current system configuration. Only if the result of this operation is 'success' can the user proceed to do an install operation. The tables, ciuVersionCompChkTable, ciuUpgradeImageVersionTable, ciuUpgradeOpStatusTable, provide the result of the 'check' or 'install' operation performed using ciuUpgradeOpCommand. These tables are in addition to objects ciuUpgradeOpStatus, ciuUpgradeOpTimeStarted, ciuUpgradeOpTimeCompleted, ciuUpgradeOpStatusReason. The ciuUpgradeOpStatus object provides the status of the selected upgrade operation. An option is available for user to upgrade only some modules, provided using ciuUpgradeTargetTable. If this table is empty than an upgrade operation would be performed on all the modules in the system.")
cisco_image_upgrade_mib_notifs = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 360, 0))
cisco_image_upgrade_mib_objects = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 360, 1))
cisco_image_upgrade_mib_conform = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 360, 2))
cisco_image_upgrade_config = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1))
cisco_image_upgrade_op = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 4))
cisco_image_upgrade_misc = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 10))
class Ciuimagevariabletypename(TextualConvention, OctetString):
description = "The type of image that the system can run. e.g. Let us say that the device has 3 image variables names - 'system', 'kickstart' and 'ilce'. This TC would, then be as follows: system kickstart ilce. "
status = 'current'
subtype_spec = OctetString.subtypeSpec + value_size_constraint(1, 32)
ciu_total_image_variables = mib_scalar((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 1), unsigned32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ciuTotalImageVariables.setStatus('current')
if mibBuilder.loadTexts:
ciuTotalImageVariables.setDescription('Total number of image variables supported in the device at this time.')
ciu_image_variable_table = mib_table((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 2))
if mibBuilder.loadTexts:
ciuImageVariableTable.setStatus('current')
if mibBuilder.loadTexts:
ciuImageVariableTable.setDescription('A table listing the image variable types that exist in the device. ')
ciu_image_variable_entry = mib_table_row((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 2, 1)).setIndexNames((0, 'CISCO-IMAGE-UPGRADE-MIB', 'ciuImageVariableName'))
if mibBuilder.loadTexts:
ciuImageVariableEntry.setStatus('current')
if mibBuilder.loadTexts:
ciuImageVariableEntry.setDescription('A ciuImageVariableEntry entry. Each entry provides the image variable type existing in the device. ')
ciu_image_variable_name = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 2, 1, 1), ciu_image_variable_type_name()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ciuImageVariableName.setStatus('current')
if mibBuilder.loadTexts:
ciuImageVariableName.setDescription("The type of image that the system can run. The value of this object depends on the underlying agent. e.g. Let us say that the device has 3 image variables names - 'system', 'kickstart' and 'ilce'. This table , then will list these 3 strings as entries such as follows: ciuImageVariableName system kickstart ilce The user can assign images (using ciuImageURITable) to these variables and the system will use the assigned values to boot. ")
ciu_image_uri_table = mib_table((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 3))
if mibBuilder.loadTexts:
ciuImageURITable.setStatus('current')
if mibBuilder.loadTexts:
ciuImageURITable.setDescription("A table listing the Universal Resource Identifier(URI) of images that are assigned to variables of the ciuImageVariableTable. In the example for ciuImageVariableTable, there are 3 image types. This table will list the names for those image types as follows - entPhysicalIndex ciuImageVariableName ciuImageURI 25 'system' m9200-ek9-mgz.1.0.bin 25 'kickstart' boot-1.0.bin 26 'ilce' linecard-1.0.bin In this example, the 'system' image name is 'm9200-ek9-mgz.1.0.bin', the 'ilce' image name is 'linecard-1.0.bin' and the 'kickstart' image name is 'boot-1.0.bin'. ")
ciu_image_uri_entry = mib_table_row((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 3, 1)).setIndexNames((0, 'ENTITY-MIB', 'entPhysicalIndex'), (0, 'CISCO-IMAGE-UPGRADE-MIB', 'ciuImageVariableName'))
if mibBuilder.loadTexts:
ciuImageURIEntry.setStatus('current')
if mibBuilder.loadTexts:
ciuImageURIEntry.setDescription('A ciuImageURITable entry. Each entry provides the Image URI corresponding to this image variable name, identified by ciuImageVariableName, on this module identified by entPhysicalIndex. Each such module of the type PhysicalClass module(9), has an entry in entPhysicalTable in ENTITY-MIB, where that entry is identified by entPhysicalIndex. Only modules capable of running images, identified by ciuImageVariableName would have an entry in this table. ')
ciu_image_uri = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 3, 1, 1), snmp_admin_string()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
ciuImageURI.setStatus('current')
if mibBuilder.loadTexts:
ciuImageURI.setDescription('This object contains the string value of the image corresponding to ciuImageVariableName on this entity.')
ciu_upgrade_op_command = mib_scalar((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 4, 1), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4))).clone(namedValues=named_values(('none', 1), ('done', 2), ('install', 3), ('check', 4)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
ciuUpgradeOpCommand.setStatus('current')
if mibBuilder.loadTexts:
ciuUpgradeOpCommand.setDescription("The command to be executed. Note that it is possible for a system to support only a subset of these commands. If a command is unsupported, it will complete immediatly with the 'invalidOperation' error being reported in the ciuUpgradeOpStatus object. The 'check' must be performed first before 'install' command can be executed. If 'install' is performed first the operation would fail. So 'install' will be allowed only if a read of this object returns 'check' and the value of object ciuUpgradeOpStatus is 'success'. Also 'check' will be allowed only if a read of this object returns 'none'. Command Remarks none if this object is read without performing any operation listed above, 'none' would be returned. Also 'none' would be returned for a read operation if a cleanup of the previous upgrade operation is completed either through the issue of 'done' command or the maximum timeout of 5 minutes is elapsed. Setting this object to 'none', agent would return a success without any upgrade operation being performed. done if this object returns any value other than 'none', then setting this to 'done' would do the required cleanup of previous upgrade operation and make the system ready for any new upgrade operation. This is needed because the system maintains the status of the previous upgrade operation for a maximum time of 5 minutes before it does the cleanup. During this period no new upgrade operation is allowed. install for all the physical entities listed in the ciuUpgradeTargetTable perform the required upgrade operation listed in that table. However the upgrade operation for a module would not be done if the current running image and the image to be upgraded given as an input through the ciuImageLocInputTable are the same. check check the version compatibility for the given set of image files against the current system configuration. ")
ciu_upgrade_op_status = mib_scalar((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 4, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))).clone(namedValues=named_values(('none', 1), ('invalidOperation', 2), ('failure', 3), ('inProgress', 4), ('success', 5), ('abortInProgress', 6), ('abortSuccess', 7), ('abortFailed', 8), ('successReset', 9), ('fsUpgReset', 10))).clone('none')).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ciuUpgradeOpStatus.setStatus('current')
if mibBuilder.loadTexts:
ciuUpgradeOpStatus.setDescription('The status of the specified operation. none(1) - no operation was performed. invalidOperation(2) - the selected operation is not supported. failure(3) - the selected operation has failed. inProgress(4) - specified operation is active. success(5) - specified operation has completed successfully. abortInProgress(6) - abort in progress. abortSuccess(7) - abort operation successful. abortFailed(8) - abort failed. successReset(9) - specified operation has completed successfully and the system will reset. fsUpgReset(10) - fabric switch upgrade reset.')
ciu_upgrade_op_notify_on_completion = mib_scalar((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 4, 3), truth_value().clone('false')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
ciuUpgradeOpNotifyOnCompletion.setStatus('current')
if mibBuilder.loadTexts:
ciuUpgradeOpNotifyOnCompletion.setDescription("Specifies whether or not a notification should be generated on the completion of an operation. If 'true', ciuUpgradeOpCompletionNotify will be generated, else if 'false' it would not be. It is the responsibility of the management entity to ensure that the SNMP administrative model is configured in such a way as to allow the notification to be delivered. This object can only be modified alongwith ciuUpgradeOpCommand object.This object returns default value when ciuUpgradeOpCommand object contains 'none'. To SET this object a multivarbind set containing this object and ciuUpgradeOpCommand must be done in the same PDU for the operation to succeed.")
ciu_upgrade_op_time_started = mib_scalar((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 4, 4), time_stamp()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ciuUpgradeOpTimeStarted.setStatus('current')
if mibBuilder.loadTexts:
ciuUpgradeOpTimeStarted.setDescription("Specifies the time the upgrade operation was started. This object would return 0 if ciuUpgradeOpCommand contains 'none'.")
ciu_upgrade_op_time_completed = mib_scalar((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 4, 5), time_stamp()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ciuUpgradeOpTimeCompleted.setStatus('current')
if mibBuilder.loadTexts:
ciuUpgradeOpTimeCompleted.setDescription("Specifies the time the upgrade operation completed. This object would return 0 if ciuUpgradeOpCommand contains 'none'. ")
ciu_upgrade_op_abort = mib_scalar((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 4, 6), truth_value().clone('false')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
ciuUpgradeOpAbort.setStatus('current')
if mibBuilder.loadTexts:
ciuUpgradeOpAbort.setDescription("Provides the means to abort an operation. If this object is set to 'true' when an upgrade operation is in progress and the corresponding instance of ciuUpgradeOpCommand has the value 'install' or 'check', then the operation will be aborted. Setting this object to 'true' when ciuUpgradeOpCommand has a different value other than 'install' or 'check' will fail. If retrieved, this object always has the value 'false'. ")
ciu_upgrade_op_status_reason = mib_scalar((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 4, 7), snmp_admin_string()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ciuUpgradeOpStatusReason.setStatus('current')
if mibBuilder.loadTexts:
ciuUpgradeOpStatusReason.setDescription("Specifies the description of the cause of 'failed' state of the object 'ciuUpgradeOpStatus'. This object would be a null string if value of 'ciuUpgradeOpStatus' is anything other than 'failure'.")
ciu_upgrade_op_last_command = mib_scalar((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 4, 8), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4))).clone(namedValues=named_values(('none', 1), ('done', 2), ('install', 3), ('check', 4)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ciuUpgradeOpLastCommand.setStatus('current')
if mibBuilder.loadTexts:
ciuUpgradeOpLastCommand.setDescription("This object indicates previous OpCommand value. It will be updated after new OpCommand is set and delivered to upgrade process. 'none' if this object is read without performing any operation listed above, 'none' would be returned. Also 'none' would be returned for a read operation if a cleanup of the previous upgrade operation is completed either through the issue of 'done' command or the maximum timeout of 5 minutes is elapsed. Setting this object to 'none', agent would return a success without any upgrade operation being performed. 'done' if this object returns any value other than 'none', then setting this to 'done' would do the required cleanup of previous upgrade operation and make the system ready for any new upgrade operation. This is needed because the system maintains the status of the previous upgrade operation for a maximum time of 5 minutes before it does the cleanup. During this period no new upgrade operation is allowed. 'install' perform the required upgrade operation listed in ciuUpgradeTargetTable table. However the upgrade operation for a module would not be done if the current running image and the image to be upgraded given as an input through the ciuImageLocInputTable are the same. 'check' check the version compatibility for the given set of image files against the current system configuration.")
ciu_upgrade_op_last_status = mib_scalar((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 4, 9), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10))).clone(namedValues=named_values(('none', 1), ('invalidOperation', 2), ('failure', 3), ('inProgress', 4), ('success', 5), ('abortInProgress', 6), ('abortSuccess', 7), ('abortFailed', 8), ('successReset', 9), ('fsUpgReset', 10)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ciuUpgradeOpLastStatus.setStatus('current')
if mibBuilder.loadTexts:
ciuUpgradeOpLastStatus.setDescription("This object indicates previous OpStatus value. It will be updated after new OpCommand is set and delivered to upgrade process. 'none' - no operation was performed. 'invalidOperation' - the selected operation is not supported. 'failure' - the selected operation has failed. 'inProgress' - specified operation is active. 'success' - specified operation has completed successfully. 'abortInProgress' - abort in progress. 'abortSuccess' - abort operation successful. 'abortFailed' - abort failed. 'successReset' - specified operation has completed successfully and the system will reset. 'fsUpgReset' - fabric switch upgrade reset.")
ciu_upgrade_op_last_status_reason = mib_scalar((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 4, 10), snmp_admin_string()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ciuUpgradeOpLastStatusReason.setStatus('current')
if mibBuilder.loadTexts:
ciuUpgradeOpLastStatusReason.setDescription('This object indicates the previous OpStatusReason value. It will be updated after new OpCommand is set and delivered to upgrade process.')
ciu_upgrade_job_status_notify_on_completion = mib_scalar((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 4, 11), truth_value()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
ciuUpgradeJobStatusNotifyOnCompletion.setStatus('current')
if mibBuilder.loadTexts:
ciuUpgradeJobStatusNotifyOnCompletion.setDescription("This object specifies whether or not ciuUpgradeJobStatusCompletionNotify notification should be generated on the completion of an operation. If 'true', ciuUpgradeJobStatusCompletionNotify will be generated, else if 'false' it would not be.")
ciu_upgrade_target_table = mib_table((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 5))
if mibBuilder.loadTexts:
ciuUpgradeTargetTable.setStatus('current')
if mibBuilder.loadTexts:
ciuUpgradeTargetTable.setDescription('A table listing the modules and the type of upgrade operation to be performed on these modules. ')
ciu_upgrade_target_entry = mib_table_row((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 5, 1)).setIndexNames((0, 'ENTITY-MIB', 'entPhysicalIndex'))
if mibBuilder.loadTexts:
ciuUpgradeTargetEntry.setStatus('current')
if mibBuilder.loadTexts:
ciuUpgradeTargetEntry.setDescription("Each entry provides the module that needs to be upgraded and the type of operation that needs to be performed on this module. The upgrade operation, selected using the object 'ciuUpgradeOpCommand', would be performed on each and every module represented by an entry in this table. Each such module of the type PhysicalClass module(9), has an entry in entPhysicalTable in ENTITY-MIB, where that entry is identified by entPhysicalIndex. Only modules capable of running images, identified by ciuImageVariableName would have an entry in this table. This table cannot be modified when ciuUpgradeOpCommand object contains value other than 'none'. ")
ciu_upgrade_target_action = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 5, 1, 1), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4))).clone(namedValues=named_values(('image', 1), ('bios', 2), ('loader', 3), ('bootrom', 4)))).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
ciuUpgradeTargetAction.setStatus('current')
if mibBuilder.loadTexts:
ciuUpgradeTargetAction.setDescription("The type of operation to be performed on this module. image - upgrade image. bios - upgrade bios. loader - upgrade loader.loader is the program that loads and starts the operating system bootrom - upgrade boot rom This object cannot be modified while the corresponding value of ciuUpgradeTargetEntryStatus is equal to 'active'. It is okay to support only a subset of the enums defined above. ")
ciu_upgrade_target_entry_status = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 5, 1, 2), row_status()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
ciuUpgradeTargetEntryStatus.setStatus('current')
if mibBuilder.loadTexts:
ciuUpgradeTargetEntryStatus.setDescription('The status of this table entry. A multivarbind set containing this object and ciuUpgradeTargetAction must be done in the same PDU for the operation to succeed. ')
ciu_image_loc_input_table = mib_table((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 6))
if mibBuilder.loadTexts:
ciuImageLocInputTable.setStatus('current')
if mibBuilder.loadTexts:
ciuImageLocInputTable.setDescription('A table listing the URI of the images that need to be upgraded. ')
ciu_image_loc_input_entry = mib_table_row((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 6, 1)).setIndexNames((0, 'CISCO-IMAGE-UPGRADE-MIB', 'ciuImageVariableName'))
if mibBuilder.loadTexts:
ciuImageLocInputEntry.setStatus('current')
if mibBuilder.loadTexts:
ciuImageLocInputEntry.setDescription("Each entry provides the image location URI that need to be upgraded. This table cannot be modified if ciuUpgradeOpCommand object contains any value other than 'none' ")
ciu_image_loc_input_uri = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 6, 1, 1), snmp_admin_string().subtype(subtypeSpec=value_size_constraint(1, 255))).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
ciuImageLocInputURI.setStatus('current')
if mibBuilder.loadTexts:
ciuImageLocInputURI.setDescription("An ASCII string specifying the system image location. For example the string could be 'bootflash:file1'. This object cannot be modified while the corresponding value of ciuImageLocInputEntryStatus is equal to 'active'. ")
ciu_image_loc_input_entry_status = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 6, 1, 2), row_status()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
ciuImageLocInputEntryStatus.setStatus('current')
if mibBuilder.loadTexts:
ciuImageLocInputEntryStatus.setDescription('The status of this table entry. ')
ciu_version_comp_chk_table = mib_table((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 7))
if mibBuilder.loadTexts:
ciuVersionCompChkTable.setStatus('current')
if mibBuilder.loadTexts:
ciuVersionCompChkTable.setDescription("A table showing the result of the version compatibility check operation performed in response to the option 'check' selected for ciuUpgradeOpCommand. The table would be emptied out once the value of ciuUpgradeOpCommand object is 'none'. ")
ciu_version_comp_chk_entry = mib_table_row((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 7, 1)).setIndexNames((0, 'ENTITY-MIB', 'entPhysicalIndex'))
if mibBuilder.loadTexts:
ciuVersionCompChkEntry.setStatus('current')
if mibBuilder.loadTexts:
ciuVersionCompChkEntry.setDescription('An entry containing the results of the version compatibility check operation performed on each module, identified by entPhysicalIndex. Each such module of the type PhysicalClass module(9), has an entry in entPhysicalTable in ENTITY-MIB, where that entry is identified by entPhysicalIndex. Only modules capable of running images, identified by ciuImageVariableName would have an entry in this table. ')
ciu_version_comp_image_same = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 7, 1, 1), truth_value()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ciuVersionCompImageSame.setStatus('current')
if mibBuilder.loadTexts:
ciuVersionCompImageSame.setDescription(' Specifies whether for this module the image provided by the user for upgrade is same as the current running image. ')
ciu_version_comp_upgradable = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 7, 1, 2), truth_value()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ciuVersionCompUpgradable.setStatus('current')
if mibBuilder.loadTexts:
ciuVersionCompUpgradable.setDescription(" Specifies whether the set of images provided in ciuImageLocInputTable are compatible with each other as far as this module is concerned. If 'true' the set of images provided are compatible and can be run on this module else they are not compatible. This module would not come up if it is booted with a uncompatible set of image. ")
ciu_version_comp_upgrade_action = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 7, 1, 3), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4, 5, 6, 7, 8))).clone(namedValues=named_values(('none', 1), ('other', 2), ('rollingUpgrade', 3), ('switchOverReset', 4), ('reset', 5), ('copy', 6), ('notApplicable', 7), ('plugin', 8)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ciuVersionCompUpgradeAction.setStatus('current')
if mibBuilder.loadTexts:
ciuVersionCompUpgradeAction.setDescription(" Specifies the type of upgrade action that would be performed on this module if ciuUpgradeOpCommand were set to 'install' or to 'check'. none(1) : is no upgrade action. other(2) : actions other than defined here rollingUpgrade(3) : modules would be upgraded one at a time. switchOverReset(4): all the modules would be reset after a switchover happens at the same time. reset(5) : all the modules would be reset without or before a switchover. copy(6) : then image upgrade would not be done, but only bios/loader/bootrom would be updated and will take effect on next reload. notApplicable(7) : upgrade action is not possible because image is not upgradable. plugin(8) : upgrading plugin only instead of full image.")
ciu_version_comp_upgrade_bios = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 7, 1, 4), truth_value()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ciuVersionCompUpgradeBios.setStatus('current')
if mibBuilder.loadTexts:
ciuVersionCompUpgradeBios.setDescription(" Specifies whether the BIOS will be upgraded. If 'true' the bios would be upgraded else it would not.")
ciu_version_comp_upgrade_bootrom = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 7, 1, 5), truth_value()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ciuVersionCompUpgradeBootrom.setStatus('current')
if mibBuilder.loadTexts:
ciuVersionCompUpgradeBootrom.setDescription(" Specifies whether the bootrom will be upgraded. If 'true' the bootrom would be upgraded else it would not.")
ciu_version_comp_upgrade_loader = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 7, 1, 6), truth_value()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ciuVersionCompUpgradeLoader.setStatus('current')
if mibBuilder.loadTexts:
ciuVersionCompUpgradeLoader.setDescription(" Specifies whether the loader will be upgraded. If 'true' the loader would be upgraded else it would not.")
ciu_version_comp_upgrade_impact = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 7, 1, 7), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4))).clone(namedValues=named_values(('other', 1), ('nonDisruptive', 2), ('disruptive', 3), ('notApplicable', 4)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ciuVersionCompUpgradeImpact.setStatus('current')
if mibBuilder.loadTexts:
ciuVersionCompUpgradeImpact.setDescription(' Specifies the impact of the upgrade operation that would have on this module. other(1) : reasons other than defined here nonDisruptive(2): this module would be upgraded without disruption of traffic. disruptive(3) : this module would be upgraded with disruption of traffic. notApplicable(4): upgrade is not possible because image is not upgradable. ')
ciu_version_comp_upgrade_reason = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 7, 1, 8), snmp_admin_string()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ciuVersionCompUpgradeReason.setStatus('current')
if mibBuilder.loadTexts:
ciuVersionCompUpgradeReason.setDescription("This object would give the reason for the following cases: 1)value of object ciuVersionCompUpgradable is 'false' then it would give the reason why the module is not upgradable. 2)the value of object ciuversionCompUpgradeAction is either 'switchOverReset' or 'reset' and value of object ciuVersionCompUpgradable is 'true'. 3)the value of object ciuVersionCompUpgradeImpact is 'disruptive' and value of objects, ciuVersionCompUpgradable is 'true' and ciuversionCompUpgradeAction is neither 'switchOverReset' nor 'reset. This object would have the reason in the above listed order. It would be a null string for all the other values of the above mentioned objects. ")
ciu_upgrade_image_version_table = mib_table((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 8))
if mibBuilder.loadTexts:
ciuUpgradeImageVersionTable.setStatus('current')
if mibBuilder.loadTexts:
ciuUpgradeImageVersionTable.setDescription("A table showing the current version of images running on the modules and the images they would be upgraded with. The table would be emptied out once the value of ciuUpgradeOpCommand object is 'none'. This table becomes valid when value of ciuUpgradeOpStatus is 'success' in response to 'check' operation selected using ciuUpgradeOpCommand. ")
ciu_upgrade_image_version_entry = mib_table_row((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 8, 1)).setIndexNames((0, 'ENTITY-MIB', 'entPhysicalIndex'), (0, 'CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeImageVersionIndex'))
if mibBuilder.loadTexts:
ciuUpgradeImageVersionEntry.setStatus('current')
if mibBuilder.loadTexts:
ciuUpgradeImageVersionEntry.setDescription('An entry containing the current version of image running on a particular module and the images they would be upgraded with. An ciuUpgradeImageVersionVarName identifies the type of software running on this module, identified by entPhysicalIndex. It is possible that the same module, identified by entPhysicalIndex, can run multiple instances of the software type identified by ciuUpgradeImageVersionVarName. Each such module of the type PhysicalClass module(9), has an entry in entPhysicalTable in ENTITY-MIB, where that entry is identified by entPhysicalIndex. Only modules capable of running images, identified by ciuImageVariableName would have an entry in this table. ')
ciu_upgrade_image_version_index = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 8, 1, 1), unsigned32())
if mibBuilder.loadTexts:
ciuUpgradeImageVersionIndex.setStatus('current')
if mibBuilder.loadTexts:
ciuUpgradeImageVersionIndex.setDescription('This is an arbitrary integer which uniquely identifies different rows which have the same value of entPhysicalIndex.')
ciu_upgrade_image_version_var_name = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 8, 1, 2), ciu_image_variable_type_name()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ciuUpgradeImageVersionVarName.setStatus('current')
if mibBuilder.loadTexts:
ciuUpgradeImageVersionVarName.setDescription('The type of image on this module. ')
ciu_upgrade_image_version_running = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 8, 1, 3), snmp_admin_string().subtype(subtypeSpec=value_size_constraint(1, 255))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ciuUpgradeImageVersionRunning.setStatus('current')
if mibBuilder.loadTexts:
ciuUpgradeImageVersionRunning.setDescription('An ASCII string specifying the running image version. ')
ciu_upgrade_image_version_new = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 8, 1, 4), snmp_admin_string().subtype(subtypeSpec=value_size_constraint(1, 255))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ciuUpgradeImageVersionNew.setStatus('current')
if mibBuilder.loadTexts:
ciuUpgradeImageVersionNew.setDescription('An ASCII string specifying what the new image version would be after an upgrade. ')
ciu_upgrade_image_version_upg_reqd = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 8, 1, 5), truth_value()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ciuUpgradeImageVersionUpgReqd.setStatus('current')
if mibBuilder.loadTexts:
ciuUpgradeImageVersionUpgReqd.setDescription(" Specifies whether an upgrade is required for this software component, identified by entPhysicalIndex and ciuUpgradeImageVersionVarName. If the value of objects ciuUpgradeImageVersionRunning and ciuUpgradeImageVersionNew are same then the value of this object would be 'false' else it would be 'true'. If 'true' then this software component, identified by ciuUpgradeImageVersionVarName needs to be upgraded else it would not.")
ciu_upgrade_op_status_table = mib_table((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 9))
if mibBuilder.loadTexts:
ciuUpgradeOpStatusTable.setStatus('current')
if mibBuilder.loadTexts:
ciuUpgradeOpStatusTable.setDescription("A table showing the result of the upgrade operation selected from ciuUpgradeOpCommand in ciuUpgradeOpTable. The table would be emptied out once the value of ciuUpgradeOpCommand object is 'none'. ")
ciu_upgrade_op_status_entry = mib_table_row((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 9, 1)).setIndexNames((0, 'CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeOpStatusOperIndex'))
if mibBuilder.loadTexts:
ciuUpgradeOpStatusEntry.setStatus('current')
if mibBuilder.loadTexts:
ciuUpgradeOpStatusEntry.setDescription('An entry containing the status of the upgrade operation. ')
ciu_upgrade_op_status_oper_index = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 9, 1, 1), unsigned32())
if mibBuilder.loadTexts:
ciuUpgradeOpStatusOperIndex.setStatus('current')
if mibBuilder.loadTexts:
ciuUpgradeOpStatusOperIndex.setDescription('This is an arbitrary integer which identifies uniquely an entry in this table. ')
ciu_upgrade_op_status_operation = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 9, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35))).clone(namedValues=named_values(('unknown', 1), ('other', 2), ('copy', 3), ('verify', 4), ('versionExtraction', 5), ('imageSync', 6), ('configSync', 7), ('preUpgrade', 8), ('forceDownload', 9), ('moduleOnline', 10), ('hitlessLCUpgrade', 11), ('hitfulLCUpgrade', 12), ('unusedBootvar', 13), ('convertStartUp', 14), ('looseIncompatibility', 15), ('haSeqNumMismatch', 16), ('unknownModuleOnline', 17), ('recommendedAction', 18), ('recoveryAction', 19), ('remainingAction', 20), ('additionalInfo', 21), ('settingBootvars', 22), ('informLcmFsUpg', 23), ('sysmgrSaveRuntimeStateAndSuccessReset', 24), ('kexecLoadUpgImages', 25), ('fsUpgCleanup', 26), ('saveMtsState', 27), ('fsUpgBegin', 28), ('lcWarmBootStatus', 29), ('waitStateVerificationStatus', 30), ('informLcmFsUpgExternalLc', 31), ('externalLcWarmBootStatus', 32), ('total', 33), ('compactFlashTcamSanity', 34), ('systemPreupgradeBegin', 35)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ciuUpgradeOpStatusOperation.setStatus('current')
if mibBuilder.loadTexts:
ciuUpgradeOpStatusOperation.setDescription("Specifies the operation that is currently in progress or completed in response to the ciuUpgradeOpCommand. 'unknown' - operation status unknown. 'other' - operation status other than defined here. 'copy' - the image is being copied from ciuUpgradeOpStatusSrcImageLoc to ciuUpgradeOpStatusDestImageLoc. 'verify' - copied images are being verified for checksum and input consistency. 'versionExtraction' - extracting the version info from image. 'imageSync' - Syncing image to the standby supervisor, if standby supervisor exists. 'configSync' - saving running configuration to startup configuration and syncing it to standby supervisor, if it exists. 'preUpgrade' - Upgrading Bios/loader/bootrom 'forceDownload' - This module is being force downloaded. 'moduleOnline' - waiting for this module to come online 'hitlessLCUpgrade' - Upgrading hitless 'hitfulLCUpgrade' - Upgrading hitful 'unusedBootvar' - The image variable name type supplied as input for upgrade operation is unused. 'convertStartUp' - converting the startup config. 'looseIncompatibility' - incomplete support for current running config in the new image. 'haSeqNumMismatch' - High availability sequence number mismatch, so the module will be power cycled. 'unknownModuleOnline' - this module was powered down before switchover and has now come online. 'recommendedAction' - Specifies the recommended action if upgrading operation fails. If this object value is 'recommendedAction' then the object 'ciuUpgradeOpStatusSrcImageLoc' would contain the string specifying the recommended action. 'recoveryAction' - Specifies that installer is doing a recovery because of install failure. If this object value is 'recoveryAction' then the object 'ciuUpgradeOpStatusSrcImageLoc' would contain the string specifying the recovery action. 'remainingAction' - Specifies the remaining actions that have not been performed due to install failure. If this object value is 'remainingAction' then the object 'ciuUpgradeOpStatusSrcImageLoc' would contain the information about the remaining actions. 'additionalInfo' - Specifies the additional info the installer conveys to the user. If this object value is 'additionalInfo' then the object 'ciuUpgradeOpStatusSrcImageLoc' would contain the information. 'settingBootvars' - setting the boot variables. 'informLcmFsUpg' - save linecard runtime state. 'sysmgrSaveRuntimeStateAndSuccessReset' - save supervisor runtime state and terminate all services. 'kexecLoadUpgImages' - load upgrade images into memory. 'fsUpgCleanup' - cleanup file system for upgrade. 'saveMtsState' - saving persistent transaction messages. 'fsUpgBegin' - notify services that upgrade is about to begin. 'lcWarmBootStatus' - linecard upgrade status. 'waitStateVerificationStatus' - supervisor state verification with the new image. 'informLcmFsUpgExternalLc' - save external linecard runtime state. 'externalLcWarmBootStatus' - external linecard upgrade status. 'total' - total. 'compactFlashTcamSanity' - compact flash and TCAM sanity test. 'systemPreupgradeBegin' - notify services of beginning of upgrade. ")
ciu_upgrade_op_status_module = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 9, 1, 3), ent_physical_index_or_zero()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ciuUpgradeOpStatusModule.setStatus('current')
if mibBuilder.loadTexts:
ciuUpgradeOpStatusModule.setDescription('The physical entity of the module for which this status is being shown. For example such an entity is one of the type PhysicalClass module(9). This object must contain the same value as the entPhysicalIndex of the physical entity from entPhysicalTable in ENTITY-MIB. ')
ciu_upgrade_op_status_src_image_loc = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 9, 1, 4), snmp_admin_string()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ciuUpgradeOpStatusSrcImageLoc.setStatus('current')
if mibBuilder.loadTexts:
ciuUpgradeOpStatusSrcImageLoc.setDescription("An ASCII string specifying the source image location. For example the string could be 'bootflash:file1'. This object is only valid if the value of ciuUpgradeOpStatusOperation is 'copy'.")
ciu_upgrade_op_status_dest_image_loc = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 9, 1, 5), snmp_admin_string()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ciuUpgradeOpStatusDestImageLoc.setStatus('current')
if mibBuilder.loadTexts:
ciuUpgradeOpStatusDestImageLoc.setDescription("An ASCII string specifying the destination image location. For example the string could be 'bootflash:file1'.")
ciu_upgrade_op_status_job_status = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 9, 1, 6), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4, 5, 6))).clone(namedValues=named_values(('unknown', 1), ('other', 2), ('failed', 3), ('inProgress', 4), ('success', 5), ('planned', 6)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ciuUpgradeOpStatusJobStatus.setStatus('current')
if mibBuilder.loadTexts:
ciuUpgradeOpStatusJobStatus.setDescription("The status of this operation. 'unknown' - operation status unknown. 'other' - operation status other than defined here. 'failed' - this operation has failed 'inProgress' - this operation is active 'success' - this operation has completed successfully. 'planned' - this operation would be executed at later point of time.")
ciu_upgrade_op_status_percent_compl = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 9, 1, 7), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ciuUpgradeOpStatusPercentCompl.setStatus('current')
if mibBuilder.loadTexts:
ciuUpgradeOpStatusPercentCompl.setDescription('The percentage completion of the upgrade operation selected from ciuUpgradeOpTable. If this object is invalid for a particular operation, identified by ciuUpgradeOpStatusOperation, then the value of this object would be -1. ')
ciu_upgrade_op_status_job_status_reas = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 9, 1, 8), snmp_admin_string()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ciuUpgradeOpStatusJobStatusReas.setStatus('current')
if mibBuilder.loadTexts:
ciuUpgradeOpStatusJobStatusReas.setDescription("Specifies the description of the cause of 'failed' state of the object 'ciuUpgradeOpStatusJobStatus'. This object would be a null string if value of 'ciuUpgradeOpStatusJobStatus' is anything other than 'failed'.")
ciu_upgrade_misc_auto_copy = mib_scalar((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 10, 1), truth_value().clone('false')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
ciuUpgradeMiscAutoCopy.setStatus('current')
if mibBuilder.loadTexts:
ciuUpgradeMiscAutoCopy.setDescription("Specifies whether or not the images on the active supervisor will be copied to the standby supervisor, if the standby supervisor exists. If the standby supervisor does not exist, the setting of this object to 'true' will not have any effect and no image copy will be done. ciuImageURITable lists all the images for the supervisor cards as well as the line cards. If this object is set to 'true', all the images pointed to by the instances of ciuImageURI will be automatically copied to the standby supervisor. For example, assume that the ciuImageURITable looks like below - entPhysicalIndex ciuImageVariableName ciuImageURI 25 'system' bootflash://image.bin 25 'kickstart' slot0://boot.bin 26 'ilce' bootflash://linecard.bin So, if the ciuUpgradeMiscAutoCopy is 'true', then bootflash://image.bin from the active supervisor will be copied to the bootflash://image.bin on the standby supervisor; slot0://boot.bin will be copied to the slot0://boot.bin on the standby supervisor etc. If this object is set to 'false' then this copying of the images will not be done.")
ciu_upgrade_misc_info_table = mib_table((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 11))
if mibBuilder.loadTexts:
ciuUpgradeMiscInfoTable.setStatus('current')
if mibBuilder.loadTexts:
ciuUpgradeMiscInfoTable.setDescription("A table showing additional information such as warnings during upgrade. The table would be emptied out once the value of ciuUpgradeOpCommand object is 'none'. ")
ciu_upgrade_misc_info_entry = mib_table_row((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 11, 1)).setIndexNames((0, 'CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeMiscInfoIndex'))
if mibBuilder.loadTexts:
ciuUpgradeMiscInfoEntry.setStatus('current')
if mibBuilder.loadTexts:
ciuUpgradeMiscInfoEntry.setDescription('An entry containing additional information of upgrade operation being performed on modules. Each entry is uniquely identified by ciuUpgradeMiscInfoIndex. If the info given in object ciuUpgradeMiscInfoDescr is not for any module then the value of ciuUpgradeMiscInfoModule would be 0.')
ciu_upgrade_misc_info_index = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 11, 1, 1), unsigned32())
if mibBuilder.loadTexts:
ciuUpgradeMiscInfoIndex.setStatus('current')
if mibBuilder.loadTexts:
ciuUpgradeMiscInfoIndex.setDescription('This is an arbitrary integer which identifies uniquely an entry in this table. ')
ciu_upgrade_misc_info_module = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 11, 1, 2), ent_physical_index_or_zero()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ciuUpgradeMiscInfoModule.setStatus('current')
if mibBuilder.loadTexts:
ciuUpgradeMiscInfoModule.setDescription('The entPhysicalIndex of the module. The value of this object would be 0 if the information shown in ciuUpgradeMiscInfoDescr is not for any module.')
ciu_upgrade_misc_info_descr = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 360, 1, 1, 11, 1, 3), snmp_admin_string()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
ciuUpgradeMiscInfoDescr.setStatus('current')
if mibBuilder.loadTexts:
ciuUpgradeMiscInfoDescr.setDescription('Specifies the miscelleneous information of the upgrade operation.')
ciu_upgrade_op_completion_notify = notification_type((1, 3, 6, 1, 4, 1, 9, 9, 360, 0, 1)).setObjects(('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeOpCommand'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeOpStatus'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeOpTimeCompleted'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeOpLastCommand'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeOpLastStatus'))
if mibBuilder.loadTexts:
ciuUpgradeOpCompletionNotify.setStatus('current')
if mibBuilder.loadTexts:
ciuUpgradeOpCompletionNotify.setDescription('A ciuUpgradeOpCompletionNotify is sent at the completion of upgrade operation denoted by ciuUpgradeOpCommand object if such a notification was requested when the operation was initiated. ciuUpgradeOpCommand indicates the type of operation. ciuUpgradeOpStatus indicates the result of the operation. ciuUpgradeOpTimeCompleted indicates the time when the operation is completed. ciuUpgradeopLastCommand indicates the previous operation that was executed. ciuUpgradeOpLastStatus indicates the result of previous operation.')
ciu_upgrade_job_status_notify = notification_type((1, 3, 6, 1, 4, 1, 9, 9, 360, 0, 2)).setObjects(('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeOpStatusOperation'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeOpStatusModule'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeOpStatusSrcImageLoc'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeOpStatusDestImageLoc'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeOpStatusJobStatus'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeOpStatusPercentCompl'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeOpStatusJobStatusReas'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeOpStatus'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeOpStatusReason'))
if mibBuilder.loadTexts:
ciuUpgradeJobStatusNotify.setStatus('current')
if mibBuilder.loadTexts:
ciuUpgradeJobStatusNotify.setDescription('A ciuUpgradeJobStatusNotify is sent when there is status change in the upgrade process. ciuUpgradeOpStatusOperation indicates the operation to change the upgrade status. ciuUpgradeOpStatusModule indicates which module is affected. ciuUpgradeOpStatusSrcImageLoc indicates location of source image if applicable. ciuUpgradeOpStatusDestImageLoc indicates location of destination image if applicable. ciuUpgradeOpStatusJobStatus indicates the result of this operation to change the status. ciuUpgradeOpStatusPercentCompl indicates percentage of the operation that has been completed. ciuUpgradeOpStatusJobStatusReas gives explanation of the faiure if there is a failure. ciuUpgradeOpStatus indicates the result of the operation at higher level. ciuUpgradeOpStatusReason gives detailed explanation if ciuUpgradeOpStatus is not successful.')
ciu_image_upgrade_compliances = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 360, 2, 1))
ciu_image_upgrade_groups = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 360, 2, 2))
ciu_image_upgrade_compliance = module_compliance((1, 3, 6, 1, 4, 1, 9, 9, 360, 2, 1, 1)).setObjects(('CISCO-IMAGE-UPGRADE-MIB', 'ciuImageUpgradeGroup'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuImageVariableGroup'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuImageURIGroup'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeOpGroup'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuImageLocInputGroup'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuVersionCompChkGroup'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeImageVersionGroup'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeOpStatusGroup'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeNotificationGroup'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciu_image_upgrade_compliance = ciuImageUpgradeCompliance.setStatus('deprecated')
if mibBuilder.loadTexts:
ciuImageUpgradeCompliance.setDescription("Compliance statement for Image Upgrade MIB. For the (mandatory) ciuImageLocInputGroup, it is compliant to allow only a limited number of entries to be created and concurrently 'active' in the ciuImageLocInputTable table. ")
ciu_image_upgrade_compliance_rev1 = module_compliance((1, 3, 6, 1, 4, 1, 9, 9, 360, 2, 1, 2)).setObjects(('CISCO-IMAGE-UPGRADE-MIB', 'ciuImageUpgradeGroup'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuImageVariableGroup'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuImageURIGroup'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeOpGroup'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuImageLocInputGroup'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuVersionCompChkGroup'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeImageVersionGroup'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeOpStatusGroup'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeNotificationGroup'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeMiscGroup'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciu_image_upgrade_compliance_rev1 = ciuImageUpgradeComplianceRev1.setStatus('deprecated')
if mibBuilder.loadTexts:
ciuImageUpgradeComplianceRev1.setDescription("Compliance statement for Image Upgrade MIB. For the (mandatory) ciuImageLocInputGroup, it is compliant to allow only a limited number of entries to be created and concurrently 'active' in the ciuImageLocInputTable table. ")
ciu_image_upgrade_compliance_rev2 = module_compliance((1, 3, 6, 1, 4, 1, 9, 9, 360, 2, 1, 3)).setObjects(('CISCO-IMAGE-UPGRADE-MIB', 'ciuImageUpgradeGroup'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuImageVariableGroup'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuImageURIGroup'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeOpGroup'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuImageLocInputGroup'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuVersionCompChkGroup'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeImageVersionGroup'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeOpStatusGroup'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeNotificationGroup'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeMiscGroup'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeMiscInfoGroup'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciu_image_upgrade_compliance_rev2 = ciuImageUpgradeComplianceRev2.setStatus('deprecated')
if mibBuilder.loadTexts:
ciuImageUpgradeComplianceRev2.setDescription("Compliance statement for Image Upgrade MIB. For the (mandatory) ciuImageLocInputGroup, it is compliant to allow only a limited number of entries to be created and concurrently 'active' in the ciuImageLocInputTable table.")
ciu_image_upgrade_compliance_rev3 = module_compliance((1, 3, 6, 1, 4, 1, 9, 9, 360, 2, 1, 4)).setObjects(('CISCO-IMAGE-UPGRADE-MIB', 'ciuImageUpgradeGroup'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuImageVariableGroup'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuImageURIGroup'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeOpGroup'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuImageLocInputGroup'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuVersionCompChkGroup'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeImageVersionGroup'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeOpStatusGroup'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeNotificationGroup'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeNotificationGroupSup'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeMiscGroup'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeMiscInfoGroup'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciu_image_upgrade_compliance_rev3 = ciuImageUpgradeComplianceRev3.setStatus('deprecated')
if mibBuilder.loadTexts:
ciuImageUpgradeComplianceRev3.setDescription("Compliance statement for Image Upgrade MIB. For the (mandatory) ciuImageLocInputGroup, it is compliant to allow only a limited number of entries to be created and concurrently 'active' in the ciuImageLocInputTable table.")
ciu_image_upgrade_compliance_rev4 = module_compliance((1, 3, 6, 1, 4, 1, 9, 9, 360, 2, 1, 5)).setObjects(('CISCO-IMAGE-UPGRADE-MIB', 'ciuImageUpgradeGroup'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuImageVariableGroup'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuImageURIGroup'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeOpGroup'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuImageLocInputGroup'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuVersionCompChkGroup'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeImageVersionGroup'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeOpStatusGroup'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeNotificationGroup'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeNotificationGroupSup'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeMiscGroup'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeMiscInfoGroup'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeOpNewGroup'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciu_image_upgrade_compliance_rev4 = ciuImageUpgradeComplianceRev4.setStatus('current')
if mibBuilder.loadTexts:
ciuImageUpgradeComplianceRev4.setDescription("Compliance statement for Image Upgrade MIB. For the (mandatory) ciuImageLocInputGroup, it is compliant to allow only a limited number of entries to be created and concurrently 'active' in the ciuImageLocInputTable table.")
ciu_image_upgrade_group = object_group((1, 3, 6, 1, 4, 1, 9, 9, 360, 2, 2, 1)).setObjects(('CISCO-IMAGE-UPGRADE-MIB', 'ciuTotalImageVariables'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciu_image_upgrade_group = ciuImageUpgradeGroup.setStatus('current')
if mibBuilder.loadTexts:
ciuImageUpgradeGroup.setDescription('A collection of objects providing information about Image upgrade. ')
ciu_image_variable_group = object_group((1, 3, 6, 1, 4, 1, 9, 9, 360, 2, 2, 2)).setObjects(('CISCO-IMAGE-UPGRADE-MIB', 'ciuImageVariableName'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciu_image_variable_group = ciuImageVariableGroup.setStatus('current')
if mibBuilder.loadTexts:
ciuImageVariableGroup.setDescription('A group containing an object providing information about the type of the system images.')
ciu_image_uri_group = object_group((1, 3, 6, 1, 4, 1, 9, 9, 360, 2, 2, 3)).setObjects(('CISCO-IMAGE-UPGRADE-MIB', 'ciuImageURI'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciu_image_uri_group = ciuImageURIGroup.setStatus('current')
if mibBuilder.loadTexts:
ciuImageURIGroup.setDescription('A group containing an object providing information about the name of system variable or parameter.')
ciu_upgrade_op_group = object_group((1, 3, 6, 1, 4, 1, 9, 9, 360, 2, 2, 4)).setObjects(('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeOpCommand'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeOpStatus'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeOpNotifyOnCompletion'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeOpTimeStarted'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeOpTimeCompleted'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeOpAbort'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeOpStatusReason'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciu_upgrade_op_group = ciuUpgradeOpGroup.setStatus('current')
if mibBuilder.loadTexts:
ciuUpgradeOpGroup.setDescription('A collection of objects for Upgrade operation.')
ciu_upgrade_target_group = object_group((1, 3, 6, 1, 4, 1, 9, 9, 360, 2, 2, 5)).setObjects(('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeTargetAction'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeTargetEntryStatus'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciu_upgrade_target_group = ciuUpgradeTargetGroup.setStatus('current')
if mibBuilder.loadTexts:
ciuUpgradeTargetGroup.setDescription('A collection of objects giving the modules and the type of image to be upgraded.')
ciu_image_loc_input_group = object_group((1, 3, 6, 1, 4, 1, 9, 9, 360, 2, 2, 6)).setObjects(('CISCO-IMAGE-UPGRADE-MIB', 'ciuImageLocInputURI'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuImageLocInputEntryStatus'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciu_image_loc_input_group = ciuImageLocInputGroup.setStatus('current')
if mibBuilder.loadTexts:
ciuImageLocInputGroup.setDescription('A collection of objects giving the location of the images to be upgraded.')
ciu_version_comp_chk_group = object_group((1, 3, 6, 1, 4, 1, 9, 9, 360, 2, 2, 7)).setObjects(('CISCO-IMAGE-UPGRADE-MIB', 'ciuVersionCompImageSame'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuVersionCompUpgradable'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuVersionCompUpgradeAction'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuVersionCompUpgradeBios'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuVersionCompUpgradeBootrom'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuVersionCompUpgradeLoader'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuVersionCompUpgradeImpact'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuVersionCompUpgradeReason'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciu_version_comp_chk_group = ciuVersionCompChkGroup.setStatus('current')
if mibBuilder.loadTexts:
ciuVersionCompChkGroup.setDescription('A collection of objects showing the results of the version compatibility check done.')
ciu_upgrade_image_version_group = object_group((1, 3, 6, 1, 4, 1, 9, 9, 360, 2, 2, 8)).setObjects(('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeImageVersionVarName'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeImageVersionRunning'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeImageVersionNew'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeImageVersionUpgReqd'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciu_upgrade_image_version_group = ciuUpgradeImageVersionGroup.setStatus('current')
if mibBuilder.loadTexts:
ciuUpgradeImageVersionGroup.setDescription('A collection of objects showing the current running images and the images to be upgraded with.')
ciu_upgrade_op_status_group = object_group((1, 3, 6, 1, 4, 1, 9, 9, 360, 2, 2, 9)).setObjects(('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeOpStatusOperation'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeOpStatusModule'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeOpStatusSrcImageLoc'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeOpStatusDestImageLoc'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeOpStatusJobStatus'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeOpStatusPercentCompl'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeOpStatusJobStatusReas'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciu_upgrade_op_status_group = ciuUpgradeOpStatusGroup.setStatus('current')
if mibBuilder.loadTexts:
ciuUpgradeOpStatusGroup.setDescription('A collection of objects showing the status of the upgrade operation.')
ciu_upgrade_notification_group = notification_group((1, 3, 6, 1, 4, 1, 9, 9, 360, 2, 2, 10)).setObjects(('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeOpCompletionNotify'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciu_upgrade_notification_group = ciuUpgradeNotificationGroup.setStatus('current')
if mibBuilder.loadTexts:
ciuUpgradeNotificationGroup.setDescription('A collection of notifications for upgrade operations. ')
ciu_upgrade_misc_group = object_group((1, 3, 6, 1, 4, 1, 9, 9, 360, 2, 2, 11)).setObjects(('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeMiscAutoCopy'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciu_upgrade_misc_group = ciuUpgradeMiscGroup.setStatus('current')
if mibBuilder.loadTexts:
ciuUpgradeMiscGroup.setDescription('A collection of objects for Miscelleneous operation.')
ciu_upgrade_misc_info_group = object_group((1, 3, 6, 1, 4, 1, 9, 9, 360, 2, 2, 12)).setObjects(('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeMiscInfoModule'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeMiscInfoDescr'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciu_upgrade_misc_info_group = ciuUpgradeMiscInfoGroup.setStatus('current')
if mibBuilder.loadTexts:
ciuUpgradeMiscInfoGroup.setDescription('A collection of objects for Miscelleneous info for upgrade operation.')
ciu_upgrade_notification_group_sup = notification_group((1, 3, 6, 1, 4, 1, 9, 9, 360, 2, 2, 13)).setObjects(('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeJobStatusNotify'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciu_upgrade_notification_group_sup = ciuUpgradeNotificationGroupSup.setStatus('current')
if mibBuilder.loadTexts:
ciuUpgradeNotificationGroupSup.setDescription('A collection of notifications for upgrade operations. ')
ciu_upgrade_op_new_group = object_group((1, 3, 6, 1, 4, 1, 9, 9, 360, 2, 2, 14)).setObjects(('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeJobStatusNotifyOnCompletion'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeOpLastCommand'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeOpLastStatus'), ('CISCO-IMAGE-UPGRADE-MIB', 'ciuUpgradeOpLastStatusReason'))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciu_upgrade_op_new_group = ciuUpgradeOpNewGroup.setStatus('current')
if mibBuilder.loadTexts:
ciuUpgradeOpNewGroup.setDescription('A collection of objects for Upgrade operation.')
mibBuilder.exportSymbols('CISCO-IMAGE-UPGRADE-MIB', ciuUpgradeImageVersionUpgReqd=ciuUpgradeImageVersionUpgReqd, ciuUpgradeOpAbort=ciuUpgradeOpAbort, ciuImageLocInputURI=ciuImageLocInputURI, ciuUpgradeOpGroup=ciuUpgradeOpGroup, ciuUpgradeOpStatusReason=ciuUpgradeOpStatusReason, ciuVersionCompUpgradeReason=ciuVersionCompUpgradeReason, ciuTotalImageVariables=ciuTotalImageVariables, ciuUpgradeJobStatusNotify=ciuUpgradeJobStatusNotify, ciuUpgradeImageVersionTable=ciuUpgradeImageVersionTable, ciuUpgradeTargetAction=ciuUpgradeTargetAction, ciuUpgradeOpStatusOperation=ciuUpgradeOpStatusOperation, ciuImageVariableName=ciuImageVariableName, ciuUpgradeImageVersionIndex=ciuUpgradeImageVersionIndex, ciuUpgradeOpStatusModule=ciuUpgradeOpStatusModule, ciuVersionCompChkGroup=ciuVersionCompChkGroup, ciuVersionCompUpgradeImpact=ciuVersionCompUpgradeImpact, ciuUpgradeMiscGroup=ciuUpgradeMiscGroup, ciuUpgradeOpStatusOperIndex=ciuUpgradeOpStatusOperIndex, ciuImageUpgradeGroup=ciuImageUpgradeGroup, ciuImageLocInputEntryStatus=ciuImageLocInputEntryStatus, ciuUpgradeOpStatus=ciuUpgradeOpStatus, ciuImageURIGroup=ciuImageURIGroup, ciuUpgradeMiscInfoTable=ciuUpgradeMiscInfoTable, ciuUpgradeTargetEntry=ciuUpgradeTargetEntry, ciscoImageUpgradeMIB=ciscoImageUpgradeMIB, ciuImageVariableTable=ciuImageVariableTable, ciuUpgradeOpStatusJobStatusReas=ciuUpgradeOpStatusJobStatusReas, ciuUpgradeOpLastCommand=ciuUpgradeOpLastCommand, ciuVersionCompUpgradeBios=ciuVersionCompUpgradeBios, ciuImageUpgradeComplianceRev3=ciuImageUpgradeComplianceRev3, ciuVersionCompUpgradeLoader=ciuVersionCompUpgradeLoader, ciuUpgradeTargetTable=ciuUpgradeTargetTable, ciuUpgradeOpCompletionNotify=ciuUpgradeOpCompletionNotify, ciscoImageUpgradeMIBObjects=ciscoImageUpgradeMIBObjects, ciuVersionCompChkTable=ciuVersionCompChkTable, ciuUpgradeOpStatusTable=ciuUpgradeOpStatusTable, ciuImageURI=ciuImageURI, ciuUpgradeOpStatusSrcImageLoc=ciuUpgradeOpStatusSrcImageLoc, ciuImageLocInputEntry=ciuImageLocInputEntry, ciuUpgradeImageVersionGroup=ciuUpgradeImageVersionGroup, ciuVersionCompImageSame=ciuVersionCompImageSame, ciuUpgradeMiscInfoGroup=ciuUpgradeMiscInfoGroup, ciuUpgradeOpLastStatusReason=ciuUpgradeOpLastStatusReason, ciuUpgradeMiscInfoIndex=ciuUpgradeMiscInfoIndex, ciuUpgradeMiscInfoEntry=ciuUpgradeMiscInfoEntry, ciuUpgradeImageVersionRunning=ciuUpgradeImageVersionRunning, ciuImageVariableEntry=ciuImageVariableEntry, CiuImageVariableTypeName=CiuImageVariableTypeName, ciscoImageUpgradeMisc=ciscoImageUpgradeMisc, ciscoImageUpgradeConfig=ciscoImageUpgradeConfig, ciuImageUpgradeCompliances=ciuImageUpgradeCompliances, ciuUpgradeOpStatusDestImageLoc=ciuUpgradeOpStatusDestImageLoc, ciuImageLocInputGroup=ciuImageLocInputGroup, ciuUpgradeOpTimeCompleted=ciuUpgradeOpTimeCompleted, ciuUpgradeMiscInfoModule=ciuUpgradeMiscInfoModule, ciuUpgradeTargetGroup=ciuUpgradeTargetGroup, ciuImageVariableGroup=ciuImageVariableGroup, ciuImageURITable=ciuImageURITable, ciscoImageUpgradeMIBNotifs=ciscoImageUpgradeMIBNotifs, ciuVersionCompUpgradeAction=ciuVersionCompUpgradeAction, ciuUpgradeMiscAutoCopy=ciuUpgradeMiscAutoCopy, ciuUpgradeOpNotifyOnCompletion=ciuUpgradeOpNotifyOnCompletion, ciuUpgradeImageVersionNew=ciuUpgradeImageVersionNew, ciuUpgradeOpCommand=ciuUpgradeOpCommand, ciuImageUpgradeGroups=ciuImageUpgradeGroups, ciuVersionCompUpgradeBootrom=ciuVersionCompUpgradeBootrom, ciuUpgradeOpStatusPercentCompl=ciuUpgradeOpStatusPercentCompl, ciuUpgradeNotificationGroupSup=ciuUpgradeNotificationGroupSup, ciuUpgradeOpStatusJobStatus=ciuUpgradeOpStatusJobStatus, ciuUpgradeJobStatusNotifyOnCompletion=ciuUpgradeJobStatusNotifyOnCompletion, ciuUpgradeOpNewGroup=ciuUpgradeOpNewGroup, ciuUpgradeImageVersionEntry=ciuUpgradeImageVersionEntry, ciuUpgradeOpTimeStarted=ciuUpgradeOpTimeStarted, ciuUpgradeTargetEntryStatus=ciuUpgradeTargetEntryStatus, ciuImageUpgradeComplianceRev4=ciuImageUpgradeComplianceRev4, ciuUpgradeOpStatusGroup=ciuUpgradeOpStatusGroup, ciuImageURIEntry=ciuImageURIEntry, ciuUpgradeOpLastStatus=ciuUpgradeOpLastStatus, ciuVersionCompUpgradable=ciuVersionCompUpgradable, ciuVersionCompChkEntry=ciuVersionCompChkEntry, ciuUpgradeMiscInfoDescr=ciuUpgradeMiscInfoDescr, ciuImageLocInputTable=ciuImageLocInputTable, ciuUpgradeImageVersionVarName=ciuUpgradeImageVersionVarName, ciuImageUpgradeCompliance=ciuImageUpgradeCompliance, ciuUpgradeNotificationGroup=ciuUpgradeNotificationGroup, ciscoImageUpgradeMIBConform=ciscoImageUpgradeMIBConform, ciuImageUpgradeComplianceRev2=ciuImageUpgradeComplianceRev2, ciuUpgradeOpStatusEntry=ciuUpgradeOpStatusEntry, PYSNMP_MODULE_ID=ciscoImageUpgradeMIB, ciuImageUpgradeComplianceRev1=ciuImageUpgradeComplianceRev1, ciscoImageUpgradeOp=ciscoImageUpgradeOp)
|
#!/opt/local/bin/python
sum_3_5 = 0
for i in range(1,1000):
if i % 3 == 0 or i % 5 == 0:
print(i)
sum_3_5 += i
print(sum_3_5)
|
sum_3_5 = 0
for i in range(1, 1000):
if i % 3 == 0 or i % 5 == 0:
print(i)
sum_3_5 += i
print(sum_3_5)
|
class Animal(object):
def __init__(self, name):
self.name = name
def eat(self, food):
print("%s is eating %s" % (self.name, food))
class Dog(Animal):
def fetch(self, thing):
print("%s goes after the %s" % (self.name, thing))
class Cat(Animal):
def swatstring(self):
print("%s shred the string!" % self.name)
d = Dog("Roger")
c = Cat("Fluffy")
d.fetch("paper")
d.eat("dog food")
print("--------")
c.eat("cat food")
c.swatstring()
# The below methods would fail, since the instances doesn't have
# have access to the other class.
c.fetch("frizbee")
d.swatstring()
|
class Animal(object):
def __init__(self, name):
self.name = name
def eat(self, food):
print('%s is eating %s' % (self.name, food))
class Dog(Animal):
def fetch(self, thing):
print('%s goes after the %s' % (self.name, thing))
class Cat(Animal):
def swatstring(self):
print('%s shred the string!' % self.name)
d = dog('Roger')
c = cat('Fluffy')
d.fetch('paper')
d.eat('dog food')
print('--------')
c.eat('cat food')
c.swatstring()
c.fetch('frizbee')
d.swatstring()
|
__version__ = '0.0.1'
__url__ = 'http://github.com/blazaid/pycodes/'
__author__ = 'blazaid'
def check_ean13():
pass
|
__version__ = '0.0.1'
__url__ = 'http://github.com/blazaid/pycodes/'
__author__ = 'blazaid'
def check_ean13():
pass
|
class Parser:
"""The Parser is the class that handles the player's input. The player
writes commands, and the parser performs natural language understanding
in order to interpret what the player intended, and how that intent
is reflected in the simulated world.
"""
def __init__(self, game):
# A list of all of the commands that the player has issued.
self.command_history = []
# A pointer to the game.
self.game = game
def get_player_intent(self,command):
command = command.lower()
if "," in command:
# Let the player type in a comma separted sequence of commands
return "sequence"
elif self.get_direction(command):
# Check for the direction intent
return "direction"
elif command.lower() == "look" or command.lower() == "l":
# when the user issues a "look" command, re-describe what they see
return "redescribe"
elif "examine " in command or command.lower().startswith("x "):
return "examine"
elif "take " in command or "get " in command:
return "take"
elif "drop " in command:
return "drop"
elif "inventory" in command or command.lower() == "i":
return "inventory"
else:
for item in self.game.get_items_in_scope():
special_commands = item.get_commands()
for special_command in special_commands:
if command == special_command.lower():
return "special"
def parse_command(self, command):
# add this command to the history
self.command_history.append(command)
# By default, none of the intents end the game. The following are ways this
# flag can be changed to True.
# * Going to a certain place.
# * Entering a certain special command
# * Picking up a certain object.
end_game = False
# Intents are functions that can be executed
intent = self.get_player_intent(command)
if intent == "direction":
end_game = self.go_in_direction(command)
elif intent == "redescribe":
self.game.describe()
elif intent == "examine":
self.examine(command)
elif intent == "take":
end_game = self.take(command)
elif intent == "drop":
self.drop(command)
elif intent == "inventory":
self.check_inventory() #Tam: Actually there is no usage of the command in here, so I will remove it out of the parameters list passed in the function, old: self.check_inventory(command)
elif intent == "special":
end_game = self.run_special_command(command)
elif intent == "sequence":
#end_game = self.execute_sequence(command)
self.execute_sequence(command) #Tam3 change it as this function dont return value
else:
print("I'm not sure what you want to do.")
return end_game
### Intent Functions ###
def go_in_direction(self, command):
""" The user wants to in some direction """
direction = self.get_direction(command)
if direction:
if direction in self.game.curr_location.connections:
if self.game.curr_location.is_blocked(direction, self.game):
# check to see whether that direction is blocked.
print(self.game.curr_location.get_block_description(direction))
else:
# if it's not blocked, then move there
self.game.curr_location = self.game.curr_location.connections[direction]
# If moving to this location ends the game, only describe the location
# and not the available items or actions.
if self.game.curr_location.end_game:
self.game.describe_current_location()
else:
self.game.describe()
else:
print("You can't go %s from here." % direction.capitalize())
return self.game.curr_location.end_game
def check_inventory(self): #Tam: Actually there is no usage of the command in here, so I will remove it out of the parameters list passed in the function, old: def check_inventory(self,command):
""" The player wants to check their inventory"""
if len(self.game.inventory) == 0:
print("You don't have anything.")
else:
descriptions = []
for item_name in self.game.inventory:
item = self.game.inventory[item_name]
descriptions.append(item.description)
print("You have: ", end = '')
print(*descriptions, sep = ", ",)
def examine(self, command):
""" The player wants to examine something """
command = command.lower()
matched_item = False
# check whether any of the items at this location match the command
for item_name in self.game.curr_location.items:
if item_name in command:
item = self.game.curr_location.items[item_name]
if item.examine_text:
print(item.examine_text)
matched_item = True
break
# check whether any of the items in the inventory match the command
for item_name in self.game.inventory:
if item_name in command:
item = self.game.inventory[item_name]
if item.examine_text:
print(item.examine_text)
matched_item = True
# fail
if not matched_item:
print("You don't see anything special.")
def take(self, command):
""" The player wants to put something in their inventory """
command = command.lower()
matched_item = False
# This gets set to True if posession of this object ends the game.
end_game = False
# check whether any of the items at this location match the command
for item_name in self.game.curr_location.items:
if item_name in command:
item = self.game.curr_location.items[item_name]
if item.gettable:
self.game.add_to_inventory(item)
self.game.curr_location.remove_item(item)
print(item.take_text)
end_game = item.end_game
else:
print("You cannot take the %s." % item_name)
matched_item = True
break
# check whether any of the items in the inventory match the command
if not matched_item:
for item_name in self.game.inventory:
if item_name in command:
print("You already have the %s." % item_name)
matched_item = True
# fail
if not matched_item:
print("You can't find it.")
return end_game
def drop(self, command):
""" The player wants to remove something from their inventory """
command = command.lower()
matched_item = False
# check whether any of the items in the inventory match the command
if not matched_item:
for item_name in self.game.inventory:
if item_name in command:
matched_item = True
item = self.game.inventory[item_name]
self.game.curr_location.add_item(item_name, item)
self.game.inventory.pop(item_name)
print("You drop the %s." % item_name)
break
# fail
if not matched_item:
print("You don't have that.")
def run_special_command(self, command):
"""Run a special command associated with one of the items in this location
or in the player's inventory"""
for item in self.game.get_items_in_scope():
special_commands = item.get_commands()
for special_command in special_commands:
if command == special_command.lower():
return item.do_action(special_command, self.game)
def execute_sequence(self, command):
for cmd in command.split(","):
cmd = cmd.strip()
self.parse_command(cmd)
#return 1 #Tam add to pass the error
def get_direction(self, command):
command = command.lower()
if command == "n" or "north" in command:
return "north"
if command == "s" or "south" in command:
return "south"
if command == "e" or "east" in command:
return "east"
if command == "w" or "west" in command:
return "west"
if command == "up":
return "up"
if command == "down":
return "down"
if command.startswith("go out"):
return "out"
if command.startswith("go in"):
return "in"
for exit in self.game.curr_location.connections.keys():
if command == exit.lower() or command == "go " + exit.lower():
return exit
return None
|
class Parser:
"""The Parser is the class that handles the player's input. The player
writes commands, and the parser performs natural language understanding
in order to interpret what the player intended, and how that intent
is reflected in the simulated world.
"""
def __init__(self, game):
self.command_history = []
self.game = game
def get_player_intent(self, command):
command = command.lower()
if ',' in command:
return 'sequence'
elif self.get_direction(command):
return 'direction'
elif command.lower() == 'look' or command.lower() == 'l':
return 'redescribe'
elif 'examine ' in command or command.lower().startswith('x '):
return 'examine'
elif 'take ' in command or 'get ' in command:
return 'take'
elif 'drop ' in command:
return 'drop'
elif 'inventory' in command or command.lower() == 'i':
return 'inventory'
else:
for item in self.game.get_items_in_scope():
special_commands = item.get_commands()
for special_command in special_commands:
if command == special_command.lower():
return 'special'
def parse_command(self, command):
self.command_history.append(command)
end_game = False
intent = self.get_player_intent(command)
if intent == 'direction':
end_game = self.go_in_direction(command)
elif intent == 'redescribe':
self.game.describe()
elif intent == 'examine':
self.examine(command)
elif intent == 'take':
end_game = self.take(command)
elif intent == 'drop':
self.drop(command)
elif intent == 'inventory':
self.check_inventory()
elif intent == 'special':
end_game = self.run_special_command(command)
elif intent == 'sequence':
self.execute_sequence(command)
else:
print("I'm not sure what you want to do.")
return end_game
def go_in_direction(self, command):
""" The user wants to in some direction """
direction = self.get_direction(command)
if direction:
if direction in self.game.curr_location.connections:
if self.game.curr_location.is_blocked(direction, self.game):
print(self.game.curr_location.get_block_description(direction))
else:
self.game.curr_location = self.game.curr_location.connections[direction]
if self.game.curr_location.end_game:
self.game.describe_current_location()
else:
self.game.describe()
else:
print("You can't go %s from here." % direction.capitalize())
return self.game.curr_location.end_game
def check_inventory(self):
""" The player wants to check their inventory"""
if len(self.game.inventory) == 0:
print("You don't have anything.")
else:
descriptions = []
for item_name in self.game.inventory:
item = self.game.inventory[item_name]
descriptions.append(item.description)
print('You have: ', end='')
print(*descriptions, sep=', ')
def examine(self, command):
""" The player wants to examine something """
command = command.lower()
matched_item = False
for item_name in self.game.curr_location.items:
if item_name in command:
item = self.game.curr_location.items[item_name]
if item.examine_text:
print(item.examine_text)
matched_item = True
break
for item_name in self.game.inventory:
if item_name in command:
item = self.game.inventory[item_name]
if item.examine_text:
print(item.examine_text)
matched_item = True
if not matched_item:
print("You don't see anything special.")
def take(self, command):
""" The player wants to put something in their inventory """
command = command.lower()
matched_item = False
end_game = False
for item_name in self.game.curr_location.items:
if item_name in command:
item = self.game.curr_location.items[item_name]
if item.gettable:
self.game.add_to_inventory(item)
self.game.curr_location.remove_item(item)
print(item.take_text)
end_game = item.end_game
else:
print('You cannot take the %s.' % item_name)
matched_item = True
break
if not matched_item:
for item_name in self.game.inventory:
if item_name in command:
print('You already have the %s.' % item_name)
matched_item = True
if not matched_item:
print("You can't find it.")
return end_game
def drop(self, command):
""" The player wants to remove something from their inventory """
command = command.lower()
matched_item = False
if not matched_item:
for item_name in self.game.inventory:
if item_name in command:
matched_item = True
item = self.game.inventory[item_name]
self.game.curr_location.add_item(item_name, item)
self.game.inventory.pop(item_name)
print('You drop the %s.' % item_name)
break
if not matched_item:
print("You don't have that.")
def run_special_command(self, command):
"""Run a special command associated with one of the items in this location
or in the player's inventory"""
for item in self.game.get_items_in_scope():
special_commands = item.get_commands()
for special_command in special_commands:
if command == special_command.lower():
return item.do_action(special_command, self.game)
def execute_sequence(self, command):
for cmd in command.split(','):
cmd = cmd.strip()
self.parse_command(cmd)
def get_direction(self, command):
command = command.lower()
if command == 'n' or 'north' in command:
return 'north'
if command == 's' or 'south' in command:
return 'south'
if command == 'e' or 'east' in command:
return 'east'
if command == 'w' or 'west' in command:
return 'west'
if command == 'up':
return 'up'
if command == 'down':
return 'down'
if command.startswith('go out'):
return 'out'
if command.startswith('go in'):
return 'in'
for exit in self.game.curr_location.connections.keys():
if command == exit.lower() or command == 'go ' + exit.lower():
return exit
return None
|
# List of the training runs for the different target dataset sizes
TRAINING_RUNS = [
'large_dataset/20200616_090434',
'medium_dataset/20200616_214425',
'small_dataset/20200617_143139'
]
|
training_runs = ['large_dataset/20200616_090434', 'medium_dataset/20200616_214425', 'small_dataset/20200617_143139']
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# ---------------------------------------------------------------------
# Copyright (c) 2012 Michael Hull.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# - Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# - Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materials provided with the
# distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# ----------------------------------------------------------------------
class StandardTags(object):
# Its important the spellings are the same;
# since we use the values in setattr() to automatically populate classes.
Voltage = 'Voltage'
CurrentDensity = 'CurrentDensity'
Current = 'Current'
Conductance = 'Conductance'
ConductanceDensity = 'ConductanceDensity'
StateVariable = 'StateVariable'
StateTimeConstant = 'StateTimeConstant'
StateSteadyState = 'StateSteadyState'
NMDAVoltageDependancy = 'NMDAVoltageDependancy'
NMDAVoltageDependancySS = 'NMDAVoltageDependancySS'
NMDAConductanceWithVDep = 'NMDAConductanceWithVDep'
Event = 'Event'
DefaultUnits = {
Voltage: 'mV',
CurrentDensity: 'mA/cm2',
Current: 'pA',
ConductanceDensity: 'mS/cm2',
Conductance: 'pS',
StateVariable: '',
StateTimeConstant: 'ms',
StateSteadyState: '',
NMDAVoltageDependancy: '',
NMDAVoltageDependancySS: '',
}
label = {
Voltage: 'Voltage',
CurrentDensity: 'Current Density',
Current: 'Current',
ConductanceDensity: 'Conductance Density',
Conductance: 'Conductance',
StateVariable: 'State Variable',
StateTimeConstant: 'StateVariable Time Constant',
StateSteadyState: 'StateVariable Steddy State',
NMDAVoltageDependancy: 'NMDA Voltage Dependancy',
NMDAVoltageDependancySS: 'NMDA Voltage Dependancy Steady State',
}
|
class Standardtags(object):
voltage = 'Voltage'
current_density = 'CurrentDensity'
current = 'Current'
conductance = 'Conductance'
conductance_density = 'ConductanceDensity'
state_variable = 'StateVariable'
state_time_constant = 'StateTimeConstant'
state_steady_state = 'StateSteadyState'
nmda_voltage_dependancy = 'NMDAVoltageDependancy'
nmda_voltage_dependancy_ss = 'NMDAVoltageDependancySS'
nmda_conductance_with_v_dep = 'NMDAConductanceWithVDep'
event = 'Event'
default_units = {Voltage: 'mV', CurrentDensity: 'mA/cm2', Current: 'pA', ConductanceDensity: 'mS/cm2', Conductance: 'pS', StateVariable: '', StateTimeConstant: 'ms', StateSteadyState: '', NMDAVoltageDependancy: '', NMDAVoltageDependancySS: ''}
label = {Voltage: 'Voltage', CurrentDensity: 'Current Density', Current: 'Current', ConductanceDensity: 'Conductance Density', Conductance: 'Conductance', StateVariable: 'State Variable', StateTimeConstant: 'StateVariable Time Constant', StateSteadyState: 'StateVariable Steddy State', NMDAVoltageDependancy: 'NMDA Voltage Dependancy', NMDAVoltageDependancySS: 'NMDA Voltage Dependancy Steady State'}
|
# Copyright 2021 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Module for input resolution exceptions.
Theses exceptions can be raised from ResolverStartegy or ResolverOp
implementation, and each exception is specially handled in input resolution
process. Other errors raised during the input resolution will not be catched
and be propagated to the input resolution caller.
"""
# Disable lint errors that enforces all exception name to end with -Error.
# pylint: disable=g-bad-exception-name
class InputResolutionError(Exception):
"""Base exception class for input resolution related errors."""
class InputResolutionSignal(Exception):
"""Base exception class for non-error input resolution signals."""
class SkipSignal(InputResolutionSignal):
"""Special signal to resolve empty input resolution result.
Normally empty input resolution result is regarded as an error (in synchronous
pipeline). Raising SkipSignal would resolve empty list input without an error.
TFX Conditional uses SkipSignal to _not_ execute components if the branch
predicate evaluates to false.
"""
|
"""Module for input resolution exceptions.
Theses exceptions can be raised from ResolverStartegy or ResolverOp
implementation, and each exception is specially handled in input resolution
process. Other errors raised during the input resolution will not be catched
and be propagated to the input resolution caller.
"""
class Inputresolutionerror(Exception):
"""Base exception class for input resolution related errors."""
class Inputresolutionsignal(Exception):
"""Base exception class for non-error input resolution signals."""
class Skipsignal(InputResolutionSignal):
"""Special signal to resolve empty input resolution result.
Normally empty input resolution result is regarded as an error (in synchronous
pipeline). Raising SkipSignal would resolve empty list input without an error.
TFX Conditional uses SkipSignal to _not_ execute components if the branch
predicate evaluates to false.
"""
|
# print("{:~^45}".format(" Simple while loop "))
# i = 1
# while i<=5 :
# print(i)
# i += 1
# print("\n{:~^45}".format(" Example: sum all numbers in [1..100] "))
# i = 1
# sum = 0
# while i <= 100:
# sum += i
# i += 1
# print("sum = ", sum)
# print("\n{:~^45}".format(" Task: sum even numbers in [1..100] "))
# i = 1
# sum = 0
# while i<=100:
# if i%2 == 0:
# sum += i
# i += 1
# print("sum = ", sum)
# print("\n{:~^45}".format(" Example of else clause in while "))
# i = 1
# while i <= 5:
# # if i==3 : break
# print(i)
# i += 1
# else:
# print("Condition is not true when i = ", i)
print("\n{:~^45}".format("Emulate do-while loop"))
# ask user to enter a name (string), until it contains at least 3 symbols
while True:
user_name = input("Enter a name (at least 3 symbols): ")
user_name_length = len(user_name)
if user_name_length > 3: break
print("Thank you, {}!".format(user_name))
# print("\nEnter number, but not 0")
# user_number = int(input("Enter a number, but not 0, please: "))
# while user_number == 0:
# user_number = input("Enter a number, but not 0, please: ")
# print("Your number is ", user_number)
|
print('\n{:~^45}'.format('Emulate do-while loop'))
while True:
user_name = input('Enter a name (at least 3 symbols): ')
user_name_length = len(user_name)
if user_name_length > 3:
break
print('Thank you, {}!'.format(user_name))
|
aqiRanges = (0, 50, 100, 150, 200, 300, 500)
aqiDescriptions = ("Good", "Moderate", "Unhealthy for Sensitive Groups",
"Unhealthy", "Very Unhealthy", "Hazardous")
aqiDescription = ""
pm25ranges = (0, 12, 35.4, 55.4, 150.4, 250.4, 500.4)
pm10ranges = (0, 54, 154, 254, 354, 424, 604)
no2ranges = (0, 53, 100, 360, 649, 1249, 2049)
so2ranges = (0, 35, 75, 185, 304, 604, 1004)
coranges = (0, 4.4, 9.4, 12.4, 15.4, 30.4, 50.4)
iHigh, iLow, cHigh, cLow, cP = 0, 0, 0, 0, 0
location = input("Where is this measurement taken from? ")
# This code only takes acceptable inputs and asks again if an out of boud input is entered
def takeInput(upperBound, message):
while True:
tempinput = float(input(message))
if (tempinput < 0) or (tempinput > upperBound):
print(
f"Entered value is out of range, please use a value between 0 and {upperBound}")
else:
break
return (tempinput)
def calculateAQI(name, ranges):
cP = takeInput(ranges[6], str(
f"Enter the value for the {name} concentration : "))
index = 0
for upper in ranges:
if cP <= upper:
cHigh = upper
# IMPORTANT NOTE:
# This code uses the uperbound of the previous index as the lower bound.
# I discussed this change with Sumona and we agreed that it was a good
# change as it results in a more reasonable result when edge casses in
# between the specified ranges are entered. This will result in this
# program returning slightly different results but I talked with Sumona
# and she just said to write out a coment that explaid this change so that
# the TA will know why
cLow = ranges[index - 1]
iHigh = aqiRanges[index]
iLow = aqiRanges[index - 1]
break
index += 1
return(((iHigh-iLow)/(cHigh-cLow)*(cP-cLow))+iLow)
results = []
endMessages = []
# hashmap for
pollutantRanges = {"PM2.5": pm25ranges, "PM10": pm10ranges,
"NO2": no2ranges, "SO2": so2ranges, "CO": coranges}
keys = dict.keys(pollutantRanges)
#iterate over the polutants to receive the data and prosses it
for key in keys:
result = calculateAQI(key, pollutantRanges[key])
endMessages.append(f"The Air Quality Index of {key} is {result}")
results.append(result)
maxAqi = max(results)
index = 0
for upper in aqiRanges:
if maxAqi <= upper:
print(
f"The Air Quality Index in {location} is {maxAqi}, this is {aqiDescriptions[index - 1]}")
break
index += 1
for endMessage in endMessages:
print(endMessage)
|
aqi_ranges = (0, 50, 100, 150, 200, 300, 500)
aqi_descriptions = ('Good', 'Moderate', 'Unhealthy for Sensitive Groups', 'Unhealthy', 'Very Unhealthy', 'Hazardous')
aqi_description = ''
pm25ranges = (0, 12, 35.4, 55.4, 150.4, 250.4, 500.4)
pm10ranges = (0, 54, 154, 254, 354, 424, 604)
no2ranges = (0, 53, 100, 360, 649, 1249, 2049)
so2ranges = (0, 35, 75, 185, 304, 604, 1004)
coranges = (0, 4.4, 9.4, 12.4, 15.4, 30.4, 50.4)
(i_high, i_low, c_high, c_low, c_p) = (0, 0, 0, 0, 0)
location = input('Where is this measurement taken from? ')
def take_input(upperBound, message):
while True:
tempinput = float(input(message))
if tempinput < 0 or tempinput > upperBound:
print(f'Entered value is out of range, please use a value between 0 and {upperBound}')
else:
break
return tempinput
def calculate_aqi(name, ranges):
c_p = take_input(ranges[6], str(f'Enter the value for the {name} concentration : '))
index = 0
for upper in ranges:
if cP <= upper:
c_high = upper
c_low = ranges[index - 1]
i_high = aqiRanges[index]
i_low = aqiRanges[index - 1]
break
index += 1
return (iHigh - iLow) / (cHigh - cLow) * (cP - cLow) + iLow
results = []
end_messages = []
pollutant_ranges = {'PM2.5': pm25ranges, 'PM10': pm10ranges, 'NO2': no2ranges, 'SO2': so2ranges, 'CO': coranges}
keys = dict.keys(pollutantRanges)
for key in keys:
result = calculate_aqi(key, pollutantRanges[key])
endMessages.append(f'The Air Quality Index of {key} is {result}')
results.append(result)
max_aqi = max(results)
index = 0
for upper in aqiRanges:
if maxAqi <= upper:
print(f'The Air Quality Index in {location} is {maxAqi}, this is {aqiDescriptions[index - 1]}')
break
index += 1
for end_message in endMessages:
print(endMessage)
|
def test_evens():
yield check_even_cls
class Test(object):
def test_evens(self):
yield check_even_cls
class Check(object):
def __call__(self):
pass
check_even_cls = Check()
|
def test_evens():
yield check_even_cls
class Test(object):
def test_evens(self):
yield check_even_cls
class Check(object):
def __call__(self):
pass
check_even_cls = check()
|
def sommig(n):
result = 0
while(n>=1):
result += n
n-=1
return result
print(sommig(3))
print(sommig(8))
print(sommig(17))
print(sommig(33))
|
def sommig(n):
result = 0
while n >= 1:
result += n
n -= 1
return result
print(sommig(3))
print(sommig(8))
print(sommig(17))
print(sommig(33))
|
class Job(object):
def __init__(self, server_host, job_id, train_strategy, train_model, train_model_class_name, aggregate_strategy,
distillation_alpha=None):
self.server_host = server_host
self.job_id = job_id
self.train_strategy = train_strategy
self.train_model = train_model
self.train_model_class_name = train_model_class_name
self.aggregate_strategy = aggregate_strategy
self.alpha = distillation_alpha
def set_server_host(self, server_host):
self.server_host = server_host
def set_job_id(self, job_id):
self.job_id = job_id
def get_job_id(self):
return self.job_id
def set_train_strategy(self, train_strategy):
self.train_strategy = train_strategy
def set_train_model(self, train_model):
self.train_model = train_model
def set_train_model_class_name(self, train_model_class_name):
self.train_model_class_name = train_model_class_name
def get_train_model_class_name(self):
return self.train_model_class_name
def get_server_host(self):
return self.server_host
def get_train_strategy(self):
return self.train_strategy
def get_train_model(self):
return self.train_model
def set_aggregate_stragety(self, aggregate_strategy):
self.aggregate_strategy = aggregate_strategy
def get_aggregate_strategy(self):
return self.aggregate_strategy
def set_distillation_alpha(self, alpha):
self.alpha = alpha
def get_distillation_alpha(self):
return self.alpha
|
class Job(object):
def __init__(self, server_host, job_id, train_strategy, train_model, train_model_class_name, aggregate_strategy, distillation_alpha=None):
self.server_host = server_host
self.job_id = job_id
self.train_strategy = train_strategy
self.train_model = train_model
self.train_model_class_name = train_model_class_name
self.aggregate_strategy = aggregate_strategy
self.alpha = distillation_alpha
def set_server_host(self, server_host):
self.server_host = server_host
def set_job_id(self, job_id):
self.job_id = job_id
def get_job_id(self):
return self.job_id
def set_train_strategy(self, train_strategy):
self.train_strategy = train_strategy
def set_train_model(self, train_model):
self.train_model = train_model
def set_train_model_class_name(self, train_model_class_name):
self.train_model_class_name = train_model_class_name
def get_train_model_class_name(self):
return self.train_model_class_name
def get_server_host(self):
return self.server_host
def get_train_strategy(self):
return self.train_strategy
def get_train_model(self):
return self.train_model
def set_aggregate_stragety(self, aggregate_strategy):
self.aggregate_strategy = aggregate_strategy
def get_aggregate_strategy(self):
return self.aggregate_strategy
def set_distillation_alpha(self, alpha):
self.alpha = alpha
def get_distillation_alpha(self):
return self.alpha
|
def foo(bar1, bar2, bar3,
bar4
): # FD102
return
|
def foo(bar1, bar2, bar3, bar4):
return
|
class Solution:
def canPermutePalindrome(self, s: str) -> bool:
wordset = set()
for c in s:
if c in wordset:
wordset.remove(c)
else:
wordset.add(c)
return len(wordset)<=1
A = Solution()
s = "aab"
print(A.canPermutePalindrome(s))
|
class Solution:
def can_permute_palindrome(self, s: str) -> bool:
wordset = set()
for c in s:
if c in wordset:
wordset.remove(c)
else:
wordset.add(c)
return len(wordset) <= 1
a = solution()
s = 'aab'
print(A.canPermutePalindrome(s))
|
"""
Constants used by the Data Structure Generator (DSG)
and the Spec Executor
"""
# MAGIC Numbers:
# Data spec magic number
DSG_MAGIC_NUM = 0x5B7CA17E
# Application data magic number
APPDATA_MAGIC_NUM = 0xAD130AD6
# Version of the file produced by the DSE
DSE_VERSION = 0x00010000
# DSG Arrays and tables sizes:
MAX_REGISTERS = 16
MAX_MEM_REGIONS = 16
MAX_STRUCT_SLOTS = 16
MAX_STRUCT_ELEMENTS = 255
MAX_PACKSPEC_SLOTS = 16
MAX_CONSTRUCTORS = 16
MAX_PARAM_LISTS = 16
MAX_RNGS = 16
MAX_RANDOM_DISTS = 16
APP_PTR_TABLE_HEADER_BYTE_SIZE = 8
APP_PTR_TABLE_BYTE_SIZE = APP_PTR_TABLE_HEADER_BYTE_SIZE + MAX_MEM_REGIONS * 4
# Constants used by DSG command encoding:
LEN1 = 0
LEN2 = 1
LEN3 = 2
LEN4 = 3
NO_REGS = 0
DEST_ONLY = 4
SRC1_ONLY = 2
SRC1_AND_SRC2 = 3
DEST_AND_SRC1 = 6
ALL_REGS = 7
# return values from functions of the data spec executor
END_SPEC_EXECUTOR = -1
|
"""
Constants used by the Data Structure Generator (DSG)
and the Spec Executor
"""
dsg_magic_num = 1534894462
appdata_magic_num = 2903706326
dse_version = 65536
max_registers = 16
max_mem_regions = 16
max_struct_slots = 16
max_struct_elements = 255
max_packspec_slots = 16
max_constructors = 16
max_param_lists = 16
max_rngs = 16
max_random_dists = 16
app_ptr_table_header_byte_size = 8
app_ptr_table_byte_size = APP_PTR_TABLE_HEADER_BYTE_SIZE + MAX_MEM_REGIONS * 4
len1 = 0
len2 = 1
len3 = 2
len4 = 3
no_regs = 0
dest_only = 4
src1_only = 2
src1_and_src2 = 3
dest_and_src1 = 6
all_regs = 7
end_spec_executor = -1
|
def get_sea_monster():
sea_monster = [
" # ",
"# ## ## ###",
" # # # # # # ",
]
return sea_monster, len(sea_monster), len(sea_monster[0])
def mark_sea_monsters_at_coord(grid, x, y):
sm, sm_y, sm_x = get_sea_monster()
for yval in range(y, y + sm_y):
for xval in range(x, x + sm_x):
if sm[yval - y][xval - x] == "#" and grid[yval][xval] != "#":
return False, grid
for yval in range(y, y + sm_y):
for xval in range(x, x + sm_x):
if sm[yval - y][xval - x] == "#":
grid[yval][xval] = "O"
return True, grid
def mark_sea_monsters(grid):
dimy = len(grid)
dimx = len(grid[0])
_, sm_y, sm_x = get_sea_monster()
sm_found = False
for y in range(dimy - sm_y):
for x in range(dimx - sm_x):
marked, grid = mark_sea_monsters_at_coord(grid, x, y)
sm_found = sm_found or marked
return sm_found, grid
|
def get_sea_monster():
sea_monster = [' # ', '# ## ## ###', ' # # # # # # ']
return (sea_monster, len(sea_monster), len(sea_monster[0]))
def mark_sea_monsters_at_coord(grid, x, y):
(sm, sm_y, sm_x) = get_sea_monster()
for yval in range(y, y + sm_y):
for xval in range(x, x + sm_x):
if sm[yval - y][xval - x] == '#' and grid[yval][xval] != '#':
return (False, grid)
for yval in range(y, y + sm_y):
for xval in range(x, x + sm_x):
if sm[yval - y][xval - x] == '#':
grid[yval][xval] = 'O'
return (True, grid)
def mark_sea_monsters(grid):
dimy = len(grid)
dimx = len(grid[0])
(_, sm_y, sm_x) = get_sea_monster()
sm_found = False
for y in range(dimy - sm_y):
for x in range(dimx - sm_x):
(marked, grid) = mark_sea_monsters_at_coord(grid, x, y)
sm_found = sm_found or marked
return (sm_found, grid)
|
def check_if_multiple(test_num,list_of_multiples):
for i in list_of_multiples:
if not i:
continue
if not test_num%i:
return test_num
return 0
def sum_of_multiples(number, multiples_list = None):
multiples_list = multiples_list or [3,5]
#implicitly check if None is passed to the function
return sum(list(filter(lambda x: check_if_multiple(x,multiples_list),range(1,number))))
#the above line:
#uses a lambda to call check_if_multiple multiple times with different values of x, fixing the mutliples list
#filters out any returns that are false (returned zero)
#lists the returned answers
#and sums them together - as requested!
|
def check_if_multiple(test_num, list_of_multiples):
for i in list_of_multiples:
if not i:
continue
if not test_num % i:
return test_num
return 0
def sum_of_multiples(number, multiples_list=None):
multiples_list = multiples_list or [3, 5]
return sum(list(filter(lambda x: check_if_multiple(x, multiples_list), range(1, number))))
|
def algorithm_name(id, config):
algorithm = config['experiment.simple']['algorithm'].rsplit('.', 1)[1]
# env = config['experiment.simple']['environment'].rsplit('.', 1)[1]
tr_radius = get_setting(config, 'algorithm.subdomainbo', 'tr_radius')
beta = get_setting(config, 'model', 'beta')
tr_method = get_setting(config, 'algorithm.subdomainbo','tr_method')
max_queries_tr = get_setting(config, 'algorithm.subdomainbo', 'max_queries_tr')
acquisition = ''
if 'algorithm.subdomainbo' in config and 'acquisition' in config['algorithm.subdomainbo']:
acquisition = f"-{config['algorithm.subdomainbo']['acquisition'].rsplit('.', maxsplit=1)[1]}"
return f"{id}-{algorithm}{tr_radius}{tr_method}{max_queries_tr}{acquisition}{beta}"
def get_setting(config, section, setting):
if section in config and setting in config[section]:
return f"-{config[section][setting]}"
return ''
|
def algorithm_name(id, config):
algorithm = config['experiment.simple']['algorithm'].rsplit('.', 1)[1]
tr_radius = get_setting(config, 'algorithm.subdomainbo', 'tr_radius')
beta = get_setting(config, 'model', 'beta')
tr_method = get_setting(config, 'algorithm.subdomainbo', 'tr_method')
max_queries_tr = get_setting(config, 'algorithm.subdomainbo', 'max_queries_tr')
acquisition = ''
if 'algorithm.subdomainbo' in config and 'acquisition' in config['algorithm.subdomainbo']:
acquisition = f"-{config['algorithm.subdomainbo']['acquisition'].rsplit('.', maxsplit=1)[1]}"
return f'{id}-{algorithm}{tr_radius}{tr_method}{max_queries_tr}{acquisition}{beta}'
def get_setting(config, section, setting):
if section in config and setting in config[section]:
return f'-{config[section][setting]}'
return ''
|
'''This module contains the output formatters for pyPaSWAS'''
class DefaultFormatter(object):
'''This is the default formatter for pyPasWas.
All available formatters inherit from this formatter.
The results are parsed into a temporary file, which can be used by the main
program for permanent storage, printing etc.
'''
def __init__(self, logger, hitlist, outputfile):
self.name = ''
self.logger = logger
self.logger.debug('Initializing formatter...')
self.hitlist = hitlist
self.outputfile = outputfile
self._set_name()
self.logger.debug('Initialized {0}'.format(self.name))
def _format_hit(self, hit):
'''This method may be overruled to enable other formats for printed results.'''
self.logger.debug('Formatting hit {0}'.format(hit.get_seq_id()))
formatted_hit = ', '.join([hit.get_seq_id(), hit.get_target_id(), str(hit.seq_location[0]), str(hit.seq_location[1]),
str(hit.target_location[0]), str(hit.target_location[1]), str(hit.score), str(hit.matches),
str(hit.mismatches), str(len(hit.alignment) - hit.matches - hit.mismatches),
str(len(hit.alignment)), str(hit.score / len(hit.alignment)),
str(hit.sequence_info.original_length), str(hit.target_info.original_length),
str(hit.score / hit.sequence_info.original_length),
str(hit.score / hit.target_info.original_length), str(hit.distance)])
formatted_hit = '\n'.join([formatted_hit, hit.sequence_match, hit.alignment, hit.target_match])
return formatted_hit
def _set_name(self):
'''Name of the formatter. Used for logging'''
self.name = 'defaultformatter'
def _get_hits(self):
'''Returns ordered list of hits'''
hits = self.hitlist.real_hits.values()
return sorted(hits, key=lambda hit: (hit.get_seq_id(), hit.get_target_id(), hit.score))
def print_results(self):
'''sets, formats and prints the results to a file.'''
self.logger.debug('printing results...')
output = open(self.outputfile, 'w')
for hit in self._get_hits():
formatted_hit = self._format_hit(hit)
output.write(formatted_hit + "\n")
self.logger.debug('finished printing results')
class SamFormatter(DefaultFormatter):
'''This Formatter is used to create SAM output
See http://samtools.sourceforge.net/SAM1.pdf
'''
def __init__(self, logger, hitlist, outputfile):
'''Since the header contains information about the target sequences and must be
present before alignment lines, formatted lines are stored before printing.
'''
DefaultFormatter.__init__(self, logger, hitlist, outputfile)
self.sq_lines = {}
self.record_lines = []
def _set_name(self):
'''Name of the formatter. Used for logging'''
self.name = 'SAM formatter'
def _format_hit(self, hit):
'''Adds a header line to self.sq_lines and an alignment line to self.record_lines.
The following mappings are used for header lines:
SN: hit.get_target_id()
LN: hit.full_target.original_length
'''
self.logger.debug('Formatting hit {0}'.format(hit.get_seq_id()))
#add a header line for the target id if not already present
if hit.get_target_id() not in self.sq_lines:
if hit.get_target_id()[-2:] != 'RC':
self.sq_lines[hit.get_target_id()] = hit.get_sam_sq()
else:
self.sq_lines[hit.get_target_id()[:-3]] = hit.get_sam_sq()
#add a line for the hit
self.record_lines.append(hit.get_sam_line())
def print_results(self):
'''sets, formats and prints the results to a file.'''
self.logger.info('formatting results...')
#format header and hit lines
for hit in self._get_hits():
self._format_hit(hit)
self.logger.debug('printing results...')
output = open(self.outputfile, 'w')
#write the header lines to the file
header_string = '@HD\tVN:1.4\tSO:unknown'
output.write(header_string + '\n')
for header_line in self.sq_lines:
output.write(self.sq_lines[header_line] + '\n')
#program information header line
output.write('@PG\tID:0\tPN:paswas\tVN:3.0\n')
#write the hit lines to the output file
for line in self.record_lines:
output.write(line + '\n')
output.close()
self.logger.debug('finished printing results')
class TrimmerFormatter(DefaultFormatter):
'''This Formatter is used to create SAM output
See http://samtools.sourceforge.net/SAM1.pdf
'''
def __init__(self, logger, hitlist, outputfile):
'''Since the header contains information about the target sequences and must be
present before alignment lines, formatted lines are stored before printing.
'''
DefaultFormatter.__init__(self, logger, hitlist, outputfile)
self.sq_lines = {}
self.record_lines = []
def _set_name(self):
'''Name of the formatter. Used for logging'''
self.name = 'SAM formatter'
def _format_hit(self, hit):
'''Adds a header line to self.sq_lines and an alignment line to self.record_lines.
The following mappings are used for header lines:
SN: hit.get_target_id()
LN: hit.full_target.original_length
'''
self.logger.debug('Formatting hit {0}'.format(hit.get_seq_id()))
self.record_lines.append(hit.get_trimmed_line())
def print_results(self):
'''sets, formats and prints the results to a file.'''
self.logger.info('formatting results...')
#format header and hit lines
for hit in self._get_hits():
self._format_hit(hit)
self.logger.debug('printing results...')
output = open(self.outputfile, 'w')
#write the hit lines to the output file
for line in self.record_lines:
output.write(line + '\n')
output.close()
self.logger.debug('finished printing results')
class FASTA(DefaultFormatter):
'''This Formatter is used to create FASTA output
'''
def __init__(self, logger, hitlist, outputfile):
'''Since the header contains information about the target sequences and must be
present before alignment lines, formatted lines are stored before printing.
'''
DefaultFormatter.__init__(self, logger, hitlist, outputfile)
self.sq_lines = {}
self.record_lines = []
def _set_name(self):
'''Name of the formatter. Used for logging'''
self.name = 'FASTA formatter'
def _format_hit(self, hit):
'''Adds a header line to self.sq_lines and an alignment line to self.record_lines.
The following mappings are used for header lines:
SN: hit.get_target_id()
LN: hit.full_target.original_length
'''
self.logger.debug('Formatting hit {0}'.format(hit.get_seq_id()))
self.record_lines.append(hit.get_full_fasta())
def print_results(self):
'''sets, formats and prints the results to a file.'''
self.logger.info('formatting results...')
#format header and hit lines
for hit in self._get_hits():
self._format_hit(hit)
self.logger.debug('printing results...')
output = open(self.outputfile, 'w')
#write the hit lines to the output file
for line in self.record_lines:
output.write(line + '\n')
output.close()
self.logger.debug('finished printing results')
|
"""This module contains the output formatters for pyPaSWAS"""
class Defaultformatter(object):
"""This is the default formatter for pyPasWas.
All available formatters inherit from this formatter.
The results are parsed into a temporary file, which can be used by the main
program for permanent storage, printing etc.
"""
def __init__(self, logger, hitlist, outputfile):
self.name = ''
self.logger = logger
self.logger.debug('Initializing formatter...')
self.hitlist = hitlist
self.outputfile = outputfile
self._set_name()
self.logger.debug('Initialized {0}'.format(self.name))
def _format_hit(self, hit):
"""This method may be overruled to enable other formats for printed results."""
self.logger.debug('Formatting hit {0}'.format(hit.get_seq_id()))
formatted_hit = ', '.join([hit.get_seq_id(), hit.get_target_id(), str(hit.seq_location[0]), str(hit.seq_location[1]), str(hit.target_location[0]), str(hit.target_location[1]), str(hit.score), str(hit.matches), str(hit.mismatches), str(len(hit.alignment) - hit.matches - hit.mismatches), str(len(hit.alignment)), str(hit.score / len(hit.alignment)), str(hit.sequence_info.original_length), str(hit.target_info.original_length), str(hit.score / hit.sequence_info.original_length), str(hit.score / hit.target_info.original_length), str(hit.distance)])
formatted_hit = '\n'.join([formatted_hit, hit.sequence_match, hit.alignment, hit.target_match])
return formatted_hit
def _set_name(self):
"""Name of the formatter. Used for logging"""
self.name = 'defaultformatter'
def _get_hits(self):
"""Returns ordered list of hits"""
hits = self.hitlist.real_hits.values()
return sorted(hits, key=lambda hit: (hit.get_seq_id(), hit.get_target_id(), hit.score))
def print_results(self):
"""sets, formats and prints the results to a file."""
self.logger.debug('printing results...')
output = open(self.outputfile, 'w')
for hit in self._get_hits():
formatted_hit = self._format_hit(hit)
output.write(formatted_hit + '\n')
self.logger.debug('finished printing results')
class Samformatter(DefaultFormatter):
"""This Formatter is used to create SAM output
See http://samtools.sourceforge.net/SAM1.pdf
"""
def __init__(self, logger, hitlist, outputfile):
"""Since the header contains information about the target sequences and must be
present before alignment lines, formatted lines are stored before printing.
"""
DefaultFormatter.__init__(self, logger, hitlist, outputfile)
self.sq_lines = {}
self.record_lines = []
def _set_name(self):
"""Name of the formatter. Used for logging"""
self.name = 'SAM formatter'
def _format_hit(self, hit):
"""Adds a header line to self.sq_lines and an alignment line to self.record_lines.
The following mappings are used for header lines:
SN: hit.get_target_id()
LN: hit.full_target.original_length
"""
self.logger.debug('Formatting hit {0}'.format(hit.get_seq_id()))
if hit.get_target_id() not in self.sq_lines:
if hit.get_target_id()[-2:] != 'RC':
self.sq_lines[hit.get_target_id()] = hit.get_sam_sq()
else:
self.sq_lines[hit.get_target_id()[:-3]] = hit.get_sam_sq()
self.record_lines.append(hit.get_sam_line())
def print_results(self):
"""sets, formats and prints the results to a file."""
self.logger.info('formatting results...')
for hit in self._get_hits():
self._format_hit(hit)
self.logger.debug('printing results...')
output = open(self.outputfile, 'w')
header_string = '@HD\tVN:1.4\tSO:unknown'
output.write(header_string + '\n')
for header_line in self.sq_lines:
output.write(self.sq_lines[header_line] + '\n')
output.write('@PG\tID:0\tPN:paswas\tVN:3.0\n')
for line in self.record_lines:
output.write(line + '\n')
output.close()
self.logger.debug('finished printing results')
class Trimmerformatter(DefaultFormatter):
"""This Formatter is used to create SAM output
See http://samtools.sourceforge.net/SAM1.pdf
"""
def __init__(self, logger, hitlist, outputfile):
"""Since the header contains information about the target sequences and must be
present before alignment lines, formatted lines are stored before printing.
"""
DefaultFormatter.__init__(self, logger, hitlist, outputfile)
self.sq_lines = {}
self.record_lines = []
def _set_name(self):
"""Name of the formatter. Used for logging"""
self.name = 'SAM formatter'
def _format_hit(self, hit):
"""Adds a header line to self.sq_lines and an alignment line to self.record_lines.
The following mappings are used for header lines:
SN: hit.get_target_id()
LN: hit.full_target.original_length
"""
self.logger.debug('Formatting hit {0}'.format(hit.get_seq_id()))
self.record_lines.append(hit.get_trimmed_line())
def print_results(self):
"""sets, formats and prints the results to a file."""
self.logger.info('formatting results...')
for hit in self._get_hits():
self._format_hit(hit)
self.logger.debug('printing results...')
output = open(self.outputfile, 'w')
for line in self.record_lines:
output.write(line + '\n')
output.close()
self.logger.debug('finished printing results')
class Fasta(DefaultFormatter):
"""This Formatter is used to create FASTA output
"""
def __init__(self, logger, hitlist, outputfile):
"""Since the header contains information about the target sequences and must be
present before alignment lines, formatted lines are stored before printing.
"""
DefaultFormatter.__init__(self, logger, hitlist, outputfile)
self.sq_lines = {}
self.record_lines = []
def _set_name(self):
"""Name of the formatter. Used for logging"""
self.name = 'FASTA formatter'
def _format_hit(self, hit):
"""Adds a header line to self.sq_lines and an alignment line to self.record_lines.
The following mappings are used for header lines:
SN: hit.get_target_id()
LN: hit.full_target.original_length
"""
self.logger.debug('Formatting hit {0}'.format(hit.get_seq_id()))
self.record_lines.append(hit.get_full_fasta())
def print_results(self):
"""sets, formats and prints the results to a file."""
self.logger.info('formatting results...')
for hit in self._get_hits():
self._format_hit(hit)
self.logger.debug('printing results...')
output = open(self.outputfile, 'w')
for line in self.record_lines:
output.write(line + '\n')
output.close()
self.logger.debug('finished printing results')
|
x:int = 1
o:object = None
x = o = 42
|
x: int = 1
o: object = None
x = o = 42
|
m = int(input())
m = m % 1440
a = m // 60
b = m % 60
print(a, b)
|
m = int(input())
m = m % 1440
a = m // 60
b = m % 60
print(a, b)
|
# by Kami Bigdely
# Remove control flag
# Reference: https://stackoverflow.com/a/10140333/81306
# This code snippet reads up to the end of the file
n = 16
file = 'foobar.file'
def readfile(file, n):
with open(file, 'rb') as fp:
chunk = fp.read(n)
if chunk == '': # end of file, stop running.
return
print(chunk)
# process(chunk)
readfile(file, n)
|
n = 16
file = 'foobar.file'
def readfile(file, n):
with open(file, 'rb') as fp:
chunk = fp.read(n)
if chunk == '':
return
print(chunk)
readfile(file, n)
|
class Solution:
def minDeletionSize(self, A: List[str]) -> int:
res = 0
for col_str in zip(*A):
if list(col_str) != sorted(col_str):
res += 1
return res
|
class Solution:
def min_deletion_size(self, A: List[str]) -> int:
res = 0
for col_str in zip(*A):
if list(col_str) != sorted(col_str):
res += 1
return res
|
_base_ = [
'../_base_/models/simmim_swin-base.py',
'../_base_/datasets/imagenet_simmim.py',
'../_base_/schedules/adamw_coslr-200e_in1k.py',
'../_base_/default_runtime.py',
]
# data
data = dict(samples_per_gpu=128)
# optimizer
optimizer = dict(
lr=2e-4 * 2048 / 512,
betas=(0.9, 0.999),
eps=1e-8,
paramwise_options={
'norm': dict(weight_decay=0.),
'bias': dict(weight_decay=0.),
'absolute_pos_embed': dict(weight_decay=0.),
'relative_position_bias_table': dict(weight_decay=0.0)
})
# clip gradient
optimizer_config = dict(grad_clip=dict(max_norm=5.0))
# learning policy
lr_config = dict(
policy='CosineAnnealing',
min_lr=1e-5 * 2048 / 512,
warmup='linear',
warmup_iters=10,
warmup_ratio=1e-6 / 2e-4,
warmup_by_epoch=True,
by_epoch=False)
# mixed precision
fp16 = dict(loss_scale='dynamic')
# schedule
runner = dict(max_epochs=100)
# runtime
checkpoint_config = dict(interval=1, max_keep_ckpts=3, out_dir='')
persistent_workers = True
log_config = dict(
interval=100, hooks=[
dict(type='TextLoggerHook'),
])
|
_base_ = ['../_base_/models/simmim_swin-base.py', '../_base_/datasets/imagenet_simmim.py', '../_base_/schedules/adamw_coslr-200e_in1k.py', '../_base_/default_runtime.py']
data = dict(samples_per_gpu=128)
optimizer = dict(lr=0.0002 * 2048 / 512, betas=(0.9, 0.999), eps=1e-08, paramwise_options={'norm': dict(weight_decay=0.0), 'bias': dict(weight_decay=0.0), 'absolute_pos_embed': dict(weight_decay=0.0), 'relative_position_bias_table': dict(weight_decay=0.0)})
optimizer_config = dict(grad_clip=dict(max_norm=5.0))
lr_config = dict(policy='CosineAnnealing', min_lr=1e-05 * 2048 / 512, warmup='linear', warmup_iters=10, warmup_ratio=1e-06 / 0.0002, warmup_by_epoch=True, by_epoch=False)
fp16 = dict(loss_scale='dynamic')
runner = dict(max_epochs=100)
checkpoint_config = dict(interval=1, max_keep_ckpts=3, out_dir='')
persistent_workers = True
log_config = dict(interval=100, hooks=[dict(type='TextLoggerHook')])
|
height = int(input())
for i in range(1,height+1):
for j in range(1, height+1):
if(i == height//2 or i == height or j == 1 or j == height and i >= height//2 or (j%2==1 and i<= height//2)):
print("*",end=" ")
else:
print(end=" ")
print()
# Sample Input :- 7
# Output :-
# * * * *
# * * * *
# * * * * * * *
# * *
# * *
# * *
# * * * * * * *
|
height = int(input())
for i in range(1, height + 1):
for j in range(1, height + 1):
if i == height // 2 or i == height or j == 1 or (j == height and i >= height // 2) or (j % 2 == 1 and i <= height // 2):
print('*', end=' ')
else:
print(end=' ')
print()
|
"""
We *could* implement our own Vulkan backend, so we would not need the wgpu lib.
It would be a lot of work to build and maintain though, so unless the
Rust wgpu project is abandoned or something, this is probably a bad idea.
"""
raise NotImplementedError()
|
"""
We *could* implement our own Vulkan backend, so we would not need the wgpu lib.
It would be a lot of work to build and maintain though, so unless the
Rust wgpu project is abandoned or something, this is probably a bad idea.
"""
raise not_implemented_error()
|
# Copyright (c) 2015-2020 Avere Systems, Inc. All Rights Reserved.
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See LICENSE in the project root for license information.
__version__ = "0.5.4.3"
__version_info__ = (0, 5, 4, 3)
|
__version__ = '0.5.4.3'
__version_info__ = (0, 5, 4, 3)
|
house = [ ['hallway', 14.35],
['kitchen', 15.0],
['living room', 19.0],
['bedroom', 12.5],
['bathroom', 8.75] ]
# Code the for loop
for x in house:
print(str(x[0]) + ' area is ' + str(x[1]) + 'm')
|
house = [['hallway', 14.35], ['kitchen', 15.0], ['living room', 19.0], ['bedroom', 12.5], ['bathroom', 8.75]]
for x in house:
print(str(x[0]) + ' area is ' + str(x[1]) + 'm')
|
lst = []
num = int(input("Input the number of items: "))
for n in range(num):
# Arguments for Ordinal Numbers in a Set
ord = str(n+1)
if n == 0:
ord += "st"
elif n == 1:
ord += "nd"
elif n == 2:
ord += "rd"
else:
ord += "th"
numbers = int(input("Enter the "+ ord +" value: "))
lst.append(numbers)
print("The sum of the values is: ", sum(lst))
print("The mean is equal to: ", float(sum(lst) / num))
|
lst = []
num = int(input('Input the number of items: '))
for n in range(num):
ord = str(n + 1)
if n == 0:
ord += 'st'
elif n == 1:
ord += 'nd'
elif n == 2:
ord += 'rd'
else:
ord += 'th'
numbers = int(input('Enter the ' + ord + ' value: '))
lst.append(numbers)
print('The sum of the values is: ', sum(lst))
print('The mean is equal to: ', float(sum(lst) / num))
|
# Author: Konrad Lindenbach <klindenb@ualberta.ca>,
# Emmanuel Odeke <odeke@ualberta.ca>
# Copyright (c) 2014
# Table name strings
MESSAGE_TABLE_KEY = "Message"
RECEIPIENT_TABLE_KEY = "Receipient"
MESSAGE_MARKER_TABLE_KEY = "MessageMarker"
MAX_NAME_LENGTH = 60 # Arbitrary value
MAX_BODY_LENGTH = 200 # Arbitrary value
MAX_ALIAS_LENGTH = 60 # Arbitrary value
MAX_TOKEN_LENGTH = 512 # Arbitrary value
MAX_SUBJECT_LENGTH = 80 # Arbitrary value
MAX_PROFILE_URI_LENGTH = 400 # Arbitrary value
|
message_table_key = 'Message'
receipient_table_key = 'Receipient'
message_marker_table_key = 'MessageMarker'
max_name_length = 60
max_body_length = 200
max_alias_length = 60
max_token_length = 512
max_subject_length = 80
max_profile_uri_length = 400
|
"""
Each dataset has bug report ids and the ids of duplicate bug reports.
"""
class BugDataset(object):
def __init__(self, file):
f = open(file, 'r')
self.info = f.readline().strip()
self.bugIds = [id for id in f.readline().strip().split()]
self.duplicateIds = [id for id in f.readline().strip().split()]
|
"""
Each dataset has bug report ids and the ids of duplicate bug reports.
"""
class Bugdataset(object):
def __init__(self, file):
f = open(file, 'r')
self.info = f.readline().strip()
self.bugIds = [id for id in f.readline().strip().split()]
self.duplicateIds = [id for id in f.readline().strip().split()]
|
CFG = {
"spatial_input": 2,
"spatial_output": 2,
"temporal_input": 8,
"temporal_output": 12,
"bins": [0, 0.01, 0.1, 1.2],
"noise_weight": [0.05, 1, 4, 8],
"noise_weight_eth": [0.175, 1.5, 4, 8],
}
|
cfg = {'spatial_input': 2, 'spatial_output': 2, 'temporal_input': 8, 'temporal_output': 12, 'bins': [0, 0.01, 0.1, 1.2], 'noise_weight': [0.05, 1, 4, 8], 'noise_weight_eth': [0.175, 1.5, 4, 8]}
|
#!/usr/bin/env python3
def main():
lb_size = int(input())
spectrum = list(map(int, input().split()))
result = sequence_peptide(spectrum, lb_size)
print('-'.join(list(map(str, result))))
AMINO_MASSES = [57, 71, 87, 97, 99, 101, 103, 113, 114, 115, 128, 129, 131, 137, 147, 156, 163, 186]
def _attach_amino_mass(peptide: tuple) -> list:
"""
"Attach" all possible amino acid masses to the given peptide and return the resulting peptides
"""
return [peptide + (mass,) for mass in AMINO_MASSES]
def _cyclospectrum_score(peptide: tuple, spectrum: set) -> int:
"""
Calculate the cyclospectrum score for the given peptide
"""
cyclospectrum = set()
for cycle_len in range(1, len(peptide)):
peptide_extended = peptide + peptide[:(cycle_len - 1)]
for cycle_start_pos in range(len(peptide)):
cyclospectrum.add(_peptide_mass(peptide_extended[cycle_start_pos:(cycle_start_pos + cycle_len)]))
cyclospectrum.add(0)
cyclospectrum.add(_peptide_mass(peptide))
return len(spectrum.intersection(cyclospectrum))
def _peptide_mass(peptide: tuple):
"""
Calculate peptide mass
"""
return sum(peptide)
def _expand_leaderboard(leaderboard: list, spectrum: set):
"""
Expand the leaderboard
:param leaderboard: leaderboard of peptides
:return: a new leaderboard (noncut), ordered DESC
"""
lb_len = len(leaderboard)
for i in range(lb_len):
p_pair = leaderboard[i]
new_peptides = _attach_amino_mass(p_pair[1])
for new_peptide in new_peptides:
leaderboard.append([_cyclospectrum_score(new_peptide, spectrum), new_peptide])
for i in range(lb_len):
leaderboard.pop(0)
leaderboard.sort(key=lambda p: p[0], reverse=True)
def sequence_peptide(spectrum: list, lb_size: int) -> list:
"""
Sequence a peptide using a leaderboad algorithm
:param spectrum: spectrum of a peptide (not an ideal one)
:param lb_size: leaderboard size
:return: the leading peptide
"""
parent_mass = spectrum[-1]
spectrum = set(spectrum)
leaderboard = [[0, ()]]
leader = [0, ()]
while len(leaderboard) > 0:
_expand_leaderboard(leaderboard, spectrum)
i = 0
while True:
if i >= len(leaderboard) or i >= lb_size:
break
p_pair = leaderboard[i]
peptide_mass = _peptide_mass(p_pair[1])
if peptide_mass == parent_mass:
if p_pair[0] > leader[0]:
leader = p_pair
else:
leaderboard.pop(i)
continue
elif peptide_mass > parent_mass:
leaderboard.pop(i)
continue
i += 1
leaderboard = leaderboard[:lb_size]
return leader[1]
if __name__ == '__main__':
main()
|
def main():
lb_size = int(input())
spectrum = list(map(int, input().split()))
result = sequence_peptide(spectrum, lb_size)
print('-'.join(list(map(str, result))))
amino_masses = [57, 71, 87, 97, 99, 101, 103, 113, 114, 115, 128, 129, 131, 137, 147, 156, 163, 186]
def _attach_amino_mass(peptide: tuple) -> list:
"""
"Attach" all possible amino acid masses to the given peptide and return the resulting peptides
"""
return [peptide + (mass,) for mass in AMINO_MASSES]
def _cyclospectrum_score(peptide: tuple, spectrum: set) -> int:
"""
Calculate the cyclospectrum score for the given peptide
"""
cyclospectrum = set()
for cycle_len in range(1, len(peptide)):
peptide_extended = peptide + peptide[:cycle_len - 1]
for cycle_start_pos in range(len(peptide)):
cyclospectrum.add(_peptide_mass(peptide_extended[cycle_start_pos:cycle_start_pos + cycle_len]))
cyclospectrum.add(0)
cyclospectrum.add(_peptide_mass(peptide))
return len(spectrum.intersection(cyclospectrum))
def _peptide_mass(peptide: tuple):
"""
Calculate peptide mass
"""
return sum(peptide)
def _expand_leaderboard(leaderboard: list, spectrum: set):
"""
Expand the leaderboard
:param leaderboard: leaderboard of peptides
:return: a new leaderboard (noncut), ordered DESC
"""
lb_len = len(leaderboard)
for i in range(lb_len):
p_pair = leaderboard[i]
new_peptides = _attach_amino_mass(p_pair[1])
for new_peptide in new_peptides:
leaderboard.append([_cyclospectrum_score(new_peptide, spectrum), new_peptide])
for i in range(lb_len):
leaderboard.pop(0)
leaderboard.sort(key=lambda p: p[0], reverse=True)
def sequence_peptide(spectrum: list, lb_size: int) -> list:
"""
Sequence a peptide using a leaderboad algorithm
:param spectrum: spectrum of a peptide (not an ideal one)
:param lb_size: leaderboard size
:return: the leading peptide
"""
parent_mass = spectrum[-1]
spectrum = set(spectrum)
leaderboard = [[0, ()]]
leader = [0, ()]
while len(leaderboard) > 0:
_expand_leaderboard(leaderboard, spectrum)
i = 0
while True:
if i >= len(leaderboard) or i >= lb_size:
break
p_pair = leaderboard[i]
peptide_mass = _peptide_mass(p_pair[1])
if peptide_mass == parent_mass:
if p_pair[0] > leader[0]:
leader = p_pair
else:
leaderboard.pop(i)
continue
elif peptide_mass > parent_mass:
leaderboard.pop(i)
continue
i += 1
leaderboard = leaderboard[:lb_size]
return leader[1]
if __name__ == '__main__':
main()
|
def fullName(first_name, last_name):
return f'Your first name is {first_name} and last name is {last_name}'
print(fullName(first_name = 'Qaidjohar', last_name = 'Jawadwala'))
# name = fullName('Qaidjohar','Jawadwala')
# print(name)
|
def full_name(first_name, last_name):
return f'Your first name is {first_name} and last name is {last_name}'
print(full_name(first_name='Qaidjohar', last_name='Jawadwala'))
|
iN = int(input())
a_list = list(map(int, input().split()))
multi4 = len([a for a in a_list if a % 4 == 0])
odd_num = len([a for a in a_list if a % 2 != 0])
even_num = len(a_list) - odd_num
not4 = even_num - multi4
if not4 >0 :
if odd_num <= multi4:
print("Yes")
else:
print("No")
else:
if odd_num <= multi4 + 1:
print("Yes")
else:
print("No")
|
i_n = int(input())
a_list = list(map(int, input().split()))
multi4 = len([a for a in a_list if a % 4 == 0])
odd_num = len([a for a in a_list if a % 2 != 0])
even_num = len(a_list) - odd_num
not4 = even_num - multi4
if not4 > 0:
if odd_num <= multi4:
print('Yes')
else:
print('No')
elif odd_num <= multi4 + 1:
print('Yes')
else:
print('No')
|
# Time complexity: O(n^3 log n + klogk)
# Space complexity: O(k)
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
nums.sort()
res = []
length = len(nums)
for i in range(0, length - 3):
if i != 0 and nums[i] == nums[i - 1]:
continue
for j in range(i + 1, length - 2):
if j != i + 1 and nums[j] == nums[j - 1]:
continue
sum = target - nums[i] - nums[j]
left, right = j + 1, length - 1
while left < right:
if nums[left] + nums[right] == sum:
res.append([nums[i], nums[j], nums[left], nums[right]])
right -= 1
left += 1
while left < right and nums[left] == nums[left - 1]:
left += 1
while left < right and nums[right] == nums[right + 1]:
right -= 1
elif nums[left] + nums[right] > sum:
right -= 1
else:
left += 1
return res
|
class Solution:
def four_sum(self, nums: List[int], target: int) -> List[List[int]]:
nums.sort()
res = []
length = len(nums)
for i in range(0, length - 3):
if i != 0 and nums[i] == nums[i - 1]:
continue
for j in range(i + 1, length - 2):
if j != i + 1 and nums[j] == nums[j - 1]:
continue
sum = target - nums[i] - nums[j]
(left, right) = (j + 1, length - 1)
while left < right:
if nums[left] + nums[right] == sum:
res.append([nums[i], nums[j], nums[left], nums[right]])
right -= 1
left += 1
while left < right and nums[left] == nums[left - 1]:
left += 1
while left < right and nums[right] == nums[right + 1]:
right -= 1
elif nums[left] + nums[right] > sum:
right -= 1
else:
left += 1
return res
|
class GKRect(object):
"""
GKRect is a lightweight rectangle object that is used in many places in Sketch.
It has many of the same methods as MSRect but they cannot always be used
interchangeably
"""
def __init__(self, x, y, width, height):
self._x = x
self._y = y
self._width = width
self._height = height
@property
def x(self):
return self._x
@property
def y(self):
return self._y
@property
def width(self):
return self._width
@property
def height(self):
return self._height
|
class Gkrect(object):
"""
GKRect is a lightweight rectangle object that is used in many places in Sketch.
It has many of the same methods as MSRect but they cannot always be used
interchangeably
"""
def __init__(self, x, y, width, height):
self._x = x
self._y = y
self._width = width
self._height = height
@property
def x(self):
return self._x
@property
def y(self):
return self._y
@property
def width(self):
return self._width
@property
def height(self):
return self._height
|
class Problem2:
def __init__(self, campoints=None, campoints_true = None, robposes=None):
self._campoints = campoints
self._robposes = robposes
self._campoints_true = campoints_true
@property
def campoints(self):
return self._campoints
@campoints.setter
def campoints(self, campoints):
self._campoints = campoints
@property
def campoints_true(self):
return self._campoints_true
@campoints_true.setter
def campoints_true(self, campoints_true):
self._campoints_true = campoints_true
@property
def robposes(self):
return self._robposes
@robposes.setter
def robposes(self, robposes):
self._robposes = robposes
|
class Problem2:
def __init__(self, campoints=None, campoints_true=None, robposes=None):
self._campoints = campoints
self._robposes = robposes
self._campoints_true = campoints_true
@property
def campoints(self):
return self._campoints
@campoints.setter
def campoints(self, campoints):
self._campoints = campoints
@property
def campoints_true(self):
return self._campoints_true
@campoints_true.setter
def campoints_true(self, campoints_true):
self._campoints_true = campoints_true
@property
def robposes(self):
return self._robposes
@robposes.setter
def robposes(self, robposes):
self._robposes = robposes
|
# Copyright (c) 2009 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'conditions': [
['OS!="win"', {
'variables': {
'config_h_dir':
'.', # crafted for gcc/linux.
},
}, { # else, OS=="win"
'variables': {
'config_h_dir':
'src/vsprojects', # crafted for msvc.
},
'target_defaults': {
'msvs_disabled_warnings': [
4018, # signed/unsigned mismatch in comparison
4244, # implicit conversion, possible loss of data
4355, # 'this' used in base member initializer list
],
'defines!': [
'WIN32_LEAN_AND_MEAN', # Protobuf defines this itself.
],
},
}]
],
'targets': [
# The "lite" lib is about 1/7th the size of the heavy lib,
# but it doesn't support some of the more exotic features of
# protobufs, like reflection. To generate C++ code that can link
# against the lite version of the library, add the option line:
#
# option optimize_for = LITE_RUNTIME;
#
# to your .proto file.
{
'target_name': 'protobuf_lite',
'type': '<(library)',
'toolsets': ['host', 'target'],
'sources': [
'src/src/google/protobuf/stubs/common.h',
'src/src/google/protobuf/stubs/once.h',
'src/src/google/protobuf/extension_set.h',
'src/src/google/protobuf/generated_message_util.h',
'src/src/google/protobuf/message_lite.h',
'src/src/google/protobuf/repeated_field.h',
'src/src/google/protobuf/wire_format_lite.h',
'src/src/google/protobuf/wire_format_lite_inl.h',
'src/src/google/protobuf/io/coded_stream.h',
'src/src/google/protobuf/io/zero_copy_stream.h',
'src/src/google/protobuf/io/zero_copy_stream_impl_lite.h',
'src/src/google/protobuf/stubs/common.cc',
'src/src/google/protobuf/stubs/once.cc',
'src/src/google/protobuf/stubs/hash.cc',
'src/src/google/protobuf/stubs/hash.h',
'src/src/google/protobuf/stubs/map-util.h',
'src/src/google/protobuf/stubs/stl_util-inl.h',
'src/src/google/protobuf/extension_set.cc',
'src/src/google/protobuf/generated_message_util.cc',
'src/src/google/protobuf/message_lite.cc',
'src/src/google/protobuf/repeated_field.cc',
'src/src/google/protobuf/wire_format_lite.cc',
'src/src/google/protobuf/io/coded_stream.cc',
'src/src/google/protobuf/io/zero_copy_stream.cc',
'src/src/google/protobuf/io/zero_copy_stream_impl_lite.cc',
'<(config_h_dir)/config.h',
],
'include_dirs': [
'<(config_h_dir)',
'src/src',
],
# This macro must be defined to suppress the use of dynamic_cast<>,
# which requires RTTI.
'defines': [
'GOOGLE_PROTOBUF_NO_RTTI',
],
'direct_dependent_settings': {
'include_dirs': [
'<(config_h_dir)',
'src/src',
],
'defines': [
'GOOGLE_PROTOBUF_NO_RTTI',
],
},
},
# This is the full, heavy protobuf lib that's needed for c++ .proto's
# that don't specify the LITE_RUNTIME option. The protocol
# compiler itself (protoc) falls into that category.
{
'target_name': 'protobuf',
'type': '<(library)',
'toolsets': ['host'],
'sources': [
'src/src/google/protobuf/descriptor.h',
'src/src/google/protobuf/descriptor.pb.h',
'src/src/google/protobuf/descriptor_database.h',
'src/src/google/protobuf/dynamic_message.h',
'src/src/google/protobuf/generated_message_reflection.h',
'src/src/google/protobuf/message.h',
'src/src/google/protobuf/reflection_ops.h',
'src/src/google/protobuf/service.h',
'src/src/google/protobuf/text_format.h',
'src/src/google/protobuf/unknown_field_set.h',
'src/src/google/protobuf/wire_format.h',
'src/src/google/protobuf/wire_format_inl.h',
'src/src/google/protobuf/io/gzip_stream.h',
'src/src/google/protobuf/io/printer.h',
'src/src/google/protobuf/io/tokenizer.h',
'src/src/google/protobuf/io/zero_copy_stream_impl.h',
'src/src/google/protobuf/compiler/code_generator.h',
'src/src/google/protobuf/compiler/command_line_interface.h',
'src/src/google/protobuf/compiler/importer.h',
'src/src/google/protobuf/compiler/parser.h',
'src/src/google/protobuf/stubs/substitute.cc',
'src/src/google/protobuf/stubs/substitute.h',
'src/src/google/protobuf/stubs/strutil.cc',
'src/src/google/protobuf/stubs/strutil.h',
'src/src/google/protobuf/stubs/structurally_valid.cc',
'src/src/google/protobuf/descriptor.cc',
'src/src/google/protobuf/descriptor.pb.cc',
'src/src/google/protobuf/descriptor_database.cc',
'src/src/google/protobuf/dynamic_message.cc',
'src/src/google/protobuf/extension_set_heavy.cc',
'src/src/google/protobuf/generated_message_reflection.cc',
'src/src/google/protobuf/message.cc',
'src/src/google/protobuf/reflection_ops.cc',
'src/src/google/protobuf/service.cc',
'src/src/google/protobuf/text_format.cc',
'src/src/google/protobuf/unknown_field_set.cc',
'src/src/google/protobuf/wire_format.cc',
# This file pulls in zlib, but it's not actually used by protoc, so
# instead of compiling zlib for the host, let's just exclude this.
# 'src/src/google/protobuf/io/gzip_stream.cc',
'src/src/google/protobuf/io/printer.cc',
'src/src/google/protobuf/io/tokenizer.cc',
'src/src/google/protobuf/io/zero_copy_stream_impl.cc',
'src/src/google/protobuf/compiler/importer.cc',
'src/src/google/protobuf/compiler/parser.cc',
],
'dependencies': [
'protobuf_lite',
],
'export_dependent_settings': [
'protobuf_lite',
],
},
{
'target_name': 'protoc',
'type': 'executable',
'toolsets': ['host'],
'sources': [
'src/src/google/protobuf/compiler/code_generator.cc',
'src/src/google/protobuf/compiler/command_line_interface.cc',
'src/src/google/protobuf/compiler/cpp/cpp_enum.cc',
'src/src/google/protobuf/compiler/cpp/cpp_enum.h',
'src/src/google/protobuf/compiler/cpp/cpp_enum_field.cc',
'src/src/google/protobuf/compiler/cpp/cpp_enum_field.h',
'src/src/google/protobuf/compiler/cpp/cpp_extension.cc',
'src/src/google/protobuf/compiler/cpp/cpp_extension.h',
'src/src/google/protobuf/compiler/cpp/cpp_field.cc',
'src/src/google/protobuf/compiler/cpp/cpp_field.h',
'src/src/google/protobuf/compiler/cpp/cpp_file.cc',
'src/src/google/protobuf/compiler/cpp/cpp_file.h',
'src/src/google/protobuf/compiler/cpp/cpp_generator.cc',
'src/src/google/protobuf/compiler/cpp/cpp_helpers.cc',
'src/src/google/protobuf/compiler/cpp/cpp_helpers.h',
'src/src/google/protobuf/compiler/cpp/cpp_message.cc',
'src/src/google/protobuf/compiler/cpp/cpp_message.h',
'src/src/google/protobuf/compiler/cpp/cpp_message_field.cc',
'src/src/google/protobuf/compiler/cpp/cpp_message_field.h',
'src/src/google/protobuf/compiler/cpp/cpp_primitive_field.cc',
'src/src/google/protobuf/compiler/cpp/cpp_primitive_field.h',
'src/src/google/protobuf/compiler/cpp/cpp_service.cc',
'src/src/google/protobuf/compiler/cpp/cpp_service.h',
'src/src/google/protobuf/compiler/cpp/cpp_string_field.cc',
'src/src/google/protobuf/compiler/cpp/cpp_string_field.h',
'src/src/google/protobuf/compiler/java/java_enum.cc',
'src/src/google/protobuf/compiler/java/java_enum.h',
'src/src/google/protobuf/compiler/java/java_enum_field.cc',
'src/src/google/protobuf/compiler/java/java_enum_field.h',
'src/src/google/protobuf/compiler/java/java_extension.cc',
'src/src/google/protobuf/compiler/java/java_extension.h',
'src/src/google/protobuf/compiler/java/java_field.cc',
'src/src/google/protobuf/compiler/java/java_field.h',
'src/src/google/protobuf/compiler/java/java_file.cc',
'src/src/google/protobuf/compiler/java/java_file.h',
'src/src/google/protobuf/compiler/java/java_generator.cc',
'src/src/google/protobuf/compiler/java/java_helpers.cc',
'src/src/google/protobuf/compiler/java/java_helpers.h',
'src/src/google/protobuf/compiler/java/java_message.cc',
'src/src/google/protobuf/compiler/java/java_message.h',
'src/src/google/protobuf/compiler/java/java_message_field.cc',
'src/src/google/protobuf/compiler/java/java_message_field.h',
'src/src/google/protobuf/compiler/java/java_primitive_field.cc',
'src/src/google/protobuf/compiler/java/java_primitive_field.h',
'src/src/google/protobuf/compiler/java/java_service.cc',
'src/src/google/protobuf/compiler/java/java_service.h',
'src/src/google/protobuf/compiler/python/python_generator.cc',
'src/src/google/protobuf/compiler/main.cc',
],
'dependencies': [
'protobuf',
],
'include_dirs': [
'<(config_h_dir)',
'src/src',
],
},
],
}
# Local Variables:
# tab-width:2
# indent-tabs-mode:nil
# End:
# vim: set expandtab tabstop=2 shiftwidth=2:
|
{'conditions': [['OS!="win"', {'variables': {'config_h_dir': '.'}}, {'variables': {'config_h_dir': 'src/vsprojects'}, 'target_defaults': {'msvs_disabled_warnings': [4018, 4244, 4355], 'defines!': ['WIN32_LEAN_AND_MEAN']}}]], 'targets': [{'target_name': 'protobuf_lite', 'type': '<(library)', 'toolsets': ['host', 'target'], 'sources': ['src/src/google/protobuf/stubs/common.h', 'src/src/google/protobuf/stubs/once.h', 'src/src/google/protobuf/extension_set.h', 'src/src/google/protobuf/generated_message_util.h', 'src/src/google/protobuf/message_lite.h', 'src/src/google/protobuf/repeated_field.h', 'src/src/google/protobuf/wire_format_lite.h', 'src/src/google/protobuf/wire_format_lite_inl.h', 'src/src/google/protobuf/io/coded_stream.h', 'src/src/google/protobuf/io/zero_copy_stream.h', 'src/src/google/protobuf/io/zero_copy_stream_impl_lite.h', 'src/src/google/protobuf/stubs/common.cc', 'src/src/google/protobuf/stubs/once.cc', 'src/src/google/protobuf/stubs/hash.cc', 'src/src/google/protobuf/stubs/hash.h', 'src/src/google/protobuf/stubs/map-util.h', 'src/src/google/protobuf/stubs/stl_util-inl.h', 'src/src/google/protobuf/extension_set.cc', 'src/src/google/protobuf/generated_message_util.cc', 'src/src/google/protobuf/message_lite.cc', 'src/src/google/protobuf/repeated_field.cc', 'src/src/google/protobuf/wire_format_lite.cc', 'src/src/google/protobuf/io/coded_stream.cc', 'src/src/google/protobuf/io/zero_copy_stream.cc', 'src/src/google/protobuf/io/zero_copy_stream_impl_lite.cc', '<(config_h_dir)/config.h'], 'include_dirs': ['<(config_h_dir)', 'src/src'], 'defines': ['GOOGLE_PROTOBUF_NO_RTTI'], 'direct_dependent_settings': {'include_dirs': ['<(config_h_dir)', 'src/src'], 'defines': ['GOOGLE_PROTOBUF_NO_RTTI']}}, {'target_name': 'protobuf', 'type': '<(library)', 'toolsets': ['host'], 'sources': ['src/src/google/protobuf/descriptor.h', 'src/src/google/protobuf/descriptor.pb.h', 'src/src/google/protobuf/descriptor_database.h', 'src/src/google/protobuf/dynamic_message.h', 'src/src/google/protobuf/generated_message_reflection.h', 'src/src/google/protobuf/message.h', 'src/src/google/protobuf/reflection_ops.h', 'src/src/google/protobuf/service.h', 'src/src/google/protobuf/text_format.h', 'src/src/google/protobuf/unknown_field_set.h', 'src/src/google/protobuf/wire_format.h', 'src/src/google/protobuf/wire_format_inl.h', 'src/src/google/protobuf/io/gzip_stream.h', 'src/src/google/protobuf/io/printer.h', 'src/src/google/protobuf/io/tokenizer.h', 'src/src/google/protobuf/io/zero_copy_stream_impl.h', 'src/src/google/protobuf/compiler/code_generator.h', 'src/src/google/protobuf/compiler/command_line_interface.h', 'src/src/google/protobuf/compiler/importer.h', 'src/src/google/protobuf/compiler/parser.h', 'src/src/google/protobuf/stubs/substitute.cc', 'src/src/google/protobuf/stubs/substitute.h', 'src/src/google/protobuf/stubs/strutil.cc', 'src/src/google/protobuf/stubs/strutil.h', 'src/src/google/protobuf/stubs/structurally_valid.cc', 'src/src/google/protobuf/descriptor.cc', 'src/src/google/protobuf/descriptor.pb.cc', 'src/src/google/protobuf/descriptor_database.cc', 'src/src/google/protobuf/dynamic_message.cc', 'src/src/google/protobuf/extension_set_heavy.cc', 'src/src/google/protobuf/generated_message_reflection.cc', 'src/src/google/protobuf/message.cc', 'src/src/google/protobuf/reflection_ops.cc', 'src/src/google/protobuf/service.cc', 'src/src/google/protobuf/text_format.cc', 'src/src/google/protobuf/unknown_field_set.cc', 'src/src/google/protobuf/wire_format.cc', 'src/src/google/protobuf/io/printer.cc', 'src/src/google/protobuf/io/tokenizer.cc', 'src/src/google/protobuf/io/zero_copy_stream_impl.cc', 'src/src/google/protobuf/compiler/importer.cc', 'src/src/google/protobuf/compiler/parser.cc'], 'dependencies': ['protobuf_lite'], 'export_dependent_settings': ['protobuf_lite']}, {'target_name': 'protoc', 'type': 'executable', 'toolsets': ['host'], 'sources': ['src/src/google/protobuf/compiler/code_generator.cc', 'src/src/google/protobuf/compiler/command_line_interface.cc', 'src/src/google/protobuf/compiler/cpp/cpp_enum.cc', 'src/src/google/protobuf/compiler/cpp/cpp_enum.h', 'src/src/google/protobuf/compiler/cpp/cpp_enum_field.cc', 'src/src/google/protobuf/compiler/cpp/cpp_enum_field.h', 'src/src/google/protobuf/compiler/cpp/cpp_extension.cc', 'src/src/google/protobuf/compiler/cpp/cpp_extension.h', 'src/src/google/protobuf/compiler/cpp/cpp_field.cc', 'src/src/google/protobuf/compiler/cpp/cpp_field.h', 'src/src/google/protobuf/compiler/cpp/cpp_file.cc', 'src/src/google/protobuf/compiler/cpp/cpp_file.h', 'src/src/google/protobuf/compiler/cpp/cpp_generator.cc', 'src/src/google/protobuf/compiler/cpp/cpp_helpers.cc', 'src/src/google/protobuf/compiler/cpp/cpp_helpers.h', 'src/src/google/protobuf/compiler/cpp/cpp_message.cc', 'src/src/google/protobuf/compiler/cpp/cpp_message.h', 'src/src/google/protobuf/compiler/cpp/cpp_message_field.cc', 'src/src/google/protobuf/compiler/cpp/cpp_message_field.h', 'src/src/google/protobuf/compiler/cpp/cpp_primitive_field.cc', 'src/src/google/protobuf/compiler/cpp/cpp_primitive_field.h', 'src/src/google/protobuf/compiler/cpp/cpp_service.cc', 'src/src/google/protobuf/compiler/cpp/cpp_service.h', 'src/src/google/protobuf/compiler/cpp/cpp_string_field.cc', 'src/src/google/protobuf/compiler/cpp/cpp_string_field.h', 'src/src/google/protobuf/compiler/java/java_enum.cc', 'src/src/google/protobuf/compiler/java/java_enum.h', 'src/src/google/protobuf/compiler/java/java_enum_field.cc', 'src/src/google/protobuf/compiler/java/java_enum_field.h', 'src/src/google/protobuf/compiler/java/java_extension.cc', 'src/src/google/protobuf/compiler/java/java_extension.h', 'src/src/google/protobuf/compiler/java/java_field.cc', 'src/src/google/protobuf/compiler/java/java_field.h', 'src/src/google/protobuf/compiler/java/java_file.cc', 'src/src/google/protobuf/compiler/java/java_file.h', 'src/src/google/protobuf/compiler/java/java_generator.cc', 'src/src/google/protobuf/compiler/java/java_helpers.cc', 'src/src/google/protobuf/compiler/java/java_helpers.h', 'src/src/google/protobuf/compiler/java/java_message.cc', 'src/src/google/protobuf/compiler/java/java_message.h', 'src/src/google/protobuf/compiler/java/java_message_field.cc', 'src/src/google/protobuf/compiler/java/java_message_field.h', 'src/src/google/protobuf/compiler/java/java_primitive_field.cc', 'src/src/google/protobuf/compiler/java/java_primitive_field.h', 'src/src/google/protobuf/compiler/java/java_service.cc', 'src/src/google/protobuf/compiler/java/java_service.h', 'src/src/google/protobuf/compiler/python/python_generator.cc', 'src/src/google/protobuf/compiler/main.cc'], 'dependencies': ['protobuf'], 'include_dirs': ['<(config_h_dir)', 'src/src']}]}
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""gitogether
Scripts:
+ :mod:`.__main__` - argparse entry point
Module:
"""
__version__ = (0, 0, 0)
|
"""gitogether
Scripts:
+ :mod:`.__main__` - argparse entry point
Module:
"""
__version__ = (0, 0, 0)
|
# https://leetcode.com/problems/binary-tree-preorder-traversal
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
if root is None:
return []
acc = [root.val]
acc.extend(self.preorderTraversal(root.left))
acc.extend(self.preorderTraversal(root.right))
return acc
|
class Solution:
def preorder_traversal(self, root: Optional[TreeNode]) -> List[int]:
if root is None:
return []
acc = [root.val]
acc.extend(self.preorderTraversal(root.left))
acc.extend(self.preorderTraversal(root.right))
return acc
|
class Solution:
def get_num(self, s, start):
index = start
while index < len(s) and s[index].isdigit():
index += 1
return int(s[start:index]), index
def calculate_helper(self, s, start):
result, sign, index = 0, 1, start
operator = ['+', '-']
while index < len(s):
if s[index].isdigit():
num, index = self.get_num(s, index)
elif s[index] in operator:
result += sign * num
sign = (-1, 1)[s[index] == "+"]
index += 1
elif s[index] == ' ':
index += 1
elif s[index] == '(':
num, index = self.calculate_helper(s, index+1)
elif s[index] == ')':
break
result += sign * num
return result, index + 1
def calculate(self, s):
return self.calculate_helper(s, 0)[0]
def calculate2(self, s):
result, num, sign, stack = 0, 0, 1, []
operator = ['-', '+']
for char in s:
if char.isdigit():
num = 10 * num + int(char)
elif char in operator:
result += sign * num
num = 0
sign = (-1, 1)[char == "+"]
elif char == "(":
stack.append(result)
stack.append(sign)
result, sign = 0, 1
elif char == ")":
result += sign * num
result *= stack.pop()
result += stack.pop()
num = 0
return result + num * sign
|
class Solution:
def get_num(self, s, start):
index = start
while index < len(s) and s[index].isdigit():
index += 1
return (int(s[start:index]), index)
def calculate_helper(self, s, start):
(result, sign, index) = (0, 1, start)
operator = ['+', '-']
while index < len(s):
if s[index].isdigit():
(num, index) = self.get_num(s, index)
elif s[index] in operator:
result += sign * num
sign = (-1, 1)[s[index] == '+']
index += 1
elif s[index] == ' ':
index += 1
elif s[index] == '(':
(num, index) = self.calculate_helper(s, index + 1)
elif s[index] == ')':
break
result += sign * num
return (result, index + 1)
def calculate(self, s):
return self.calculate_helper(s, 0)[0]
def calculate2(self, s):
(result, num, sign, stack) = (0, 0, 1, [])
operator = ['-', '+']
for char in s:
if char.isdigit():
num = 10 * num + int(char)
elif char in operator:
result += sign * num
num = 0
sign = (-1, 1)[char == '+']
elif char == '(':
stack.append(result)
stack.append(sign)
(result, sign) = (0, 1)
elif char == ')':
result += sign * num
result *= stack.pop()
result += stack.pop()
num = 0
return result + num * sign
|
text = "zeub"
hexa = ""
for i in text:
hexa += str(hex(ord(i)))[2:].zfill(4)
print(hexa)
hexa = "002B00330033003600380039003000300034003000300030" #YOLOO
hexa = [hexa[i:i+4] for i in range(0, len(hexa), 4)]
text=""
for i in hexa:
text+=chr(int(i, 16))
print(text)
|
text = 'zeub\x1a'
hexa = ''
for i in text:
hexa += str(hex(ord(i)))[2:].zfill(4)
print(hexa)
hexa = '002B00330033003600380039003000300034003000300030'
hexa = [hexa[i:i + 4] for i in range(0, len(hexa), 4)]
text = ''
for i in hexa:
text += chr(int(i, 16))
print(text)
|
class Node:
def __init__(self, value: int) -> None:
self.value = value
self.left = None
self.right = None
class BinarySearchTree:
def __init__(self) -> None:
self.root = None
def insert(self, value: int) -> bool:
new_node = Node(value)
if self.root is None:
self.root = new_node
return True
temp = self.root
while (True):
if new_node.value == temp.value:
return False
if new_node.value < temp.value:
if temp.left is None:
temp.left = new_node
return True
temp = temp.left
else:
if temp.right is None:
temp.right = new_node
return True
temp = temp.right
my_tree = BinarySearchTree()
my_tree.insert(2)
my_tree.insert(1)
my_tree.insert(3)
print(my_tree.root.value)
print(my_tree.root.left.value)
print(my_tree.root.right.value)
|
class Node:
def __init__(self, value: int) -> None:
self.value = value
self.left = None
self.right = None
class Binarysearchtree:
def __init__(self) -> None:
self.root = None
def insert(self, value: int) -> bool:
new_node = node(value)
if self.root is None:
self.root = new_node
return True
temp = self.root
while True:
if new_node.value == temp.value:
return False
if new_node.value < temp.value:
if temp.left is None:
temp.left = new_node
return True
temp = temp.left
else:
if temp.right is None:
temp.right = new_node
return True
temp = temp.right
my_tree = binary_search_tree()
my_tree.insert(2)
my_tree.insert(1)
my_tree.insert(3)
print(my_tree.root.value)
print(my_tree.root.left.value)
print(my_tree.root.right.value)
|
class ArrayStack:
def __init__(self):
self.data = []
def isEmpty(self):
return len(self.data) == 0
def push(self, val):
return self.data.append(val)
def pop(self):
if self.isEmpty():
raise Empty("Stack underflow!")
return self.data.pop()
def peek(self):
if self.isEmpty():
raise Empty("Stack is empty!")
return self.data[-1]
def longestSubstring(expr):
stk = ArrayStack()
subLen = 0
prevLen = 0
for c in expr:
if c == '(':
stk.push(c)
if subLen:
prevLen = subLen
subLen = 0
print(subLen, prevLen)
elif c == ')':
if stk.isEmpty():
if prevLen < subLen:
prevLen = subLen
subLen = 0
print(subLen, prevLen)
else:
stk.pop()
subLen += 2
print(subLen)
print("end", subLen, prevLen)
if stk.isEmpty():
return subLen+prevLen
elif subLen > prevLen:
return subLen
else:
return prevLen
print("length of - ()(())", longestSubstring("()(())"))
#print("length of - ((((", longestSubstring("(((("))
#print("length of - ()()()", longestSubstring("()()()"))
#print("length of -", longestSubstring(""))
|
class Arraystack:
def __init__(self):
self.data = []
def is_empty(self):
return len(self.data) == 0
def push(self, val):
return self.data.append(val)
def pop(self):
if self.isEmpty():
raise empty('Stack underflow!')
return self.data.pop()
def peek(self):
if self.isEmpty():
raise empty('Stack is empty!')
return self.data[-1]
def longest_substring(expr):
stk = array_stack()
sub_len = 0
prev_len = 0
for c in expr:
if c == '(':
stk.push(c)
if subLen:
prev_len = subLen
sub_len = 0
print(subLen, prevLen)
elif c == ')':
if stk.isEmpty():
if prevLen < subLen:
prev_len = subLen
sub_len = 0
print(subLen, prevLen)
else:
stk.pop()
sub_len += 2
print(subLen)
print('end', subLen, prevLen)
if stk.isEmpty():
return subLen + prevLen
elif subLen > prevLen:
return subLen
else:
return prevLen
print('length of - ()(())', longest_substring('()(())'))
|
# pylint: skip-file
'''
Contains banner for the application.
'''
class COLORS:
RED = '\033[91m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
LINK = '\033[94m'
PURPLE = '\033[95m'
CYAN = '\033[96m'
PRIMARY = '\033[97m'
SECONDARY = '\033[90m'
END = '\033[0m'
PINK = '\033[95m'
banner = f"""
{COLORS.GREEN}
___ __ ___ __ __
/\ | | | / \ |\/| /\ | / \ |__)
/~~\ \__/ | \__/ | | /~~\ | \__/ | \
{COLORS.PINK}
- Made with <3
{COLORS.SECONDARY}Find out more at:{COLORS.LINK} github.com/Aayush9029/Authomator{COLORS.END}
"""
def print_banner():
'''
Function to print the banner.
'''
print(banner)
if __name__ == '__main__':
print_banner()
|
"""
Contains banner for the application.
"""
class Colors:
red = '\x1b[91m'
green = '\x1b[92m'
yellow = '\x1b[93m'
link = '\x1b[94m'
purple = '\x1b[95m'
cyan = '\x1b[96m'
primary = '\x1b[97m'
secondary = '\x1b[90m'
end = '\x1b[0m'
pink = '\x1b[95m'
banner = f'\n{COLORS.GREEN}\n ___ __ ___ __ __ \n /\\ | | | / \\ |\\/| /\\ | / \\ |__) \n/~~\\ \\__/ | \\__/ | | /~~\\ | \\__/ | \\ \n{COLORS.PINK}\n - Made with <3 \n\n{COLORS.SECONDARY}Find out more at:{COLORS.LINK} github.com/Aayush9029/Authomator{COLORS.END}\n'
def print_banner():
"""
Function to print the banner.
"""
print(banner)
if __name__ == '__main__':
print_banner()
|
#!/usr/bin/env python3
"""
Consider a list (list = []). You can perform the following commands:
insert i e: Insert integer e at position i.
print: Print the list.
remove e: Delete the first occurrence of integer e.
append e: Insert integer e at the end of the list.
sort: Sort the list.
pop: Pop the last element from the list.
reverse: Reverse the list.
Initialize your list and read in the value of n followed by n lines of commands
where each command will be of the 7 types listed above. Iterate through each
command in order and perform the corresponding operation on your list.
Example:
n = 4
append 1
append 2
inset 3 1
print
: Append 1 to the list, [1].
: Append 2 to the list, [1, 2].
: Insert 3 at index 1, [1, 3, 2].
: Print the array.
Output:
[1, 3, 2]
Input Format:
The first line contains an integer, n, denoting the number of commands.
Each line i of the n subsequent lines contains one of the commands described above.
Constraints:
The elements added to the list must be integers.
Output Format:
For each command of type print, print the list on a new line.
Sample Input:
12
insert 0 5
insert 1 10
insert 0 6
print
remove 6
append 9
append 1
sort
print
pop
reverse
print
Sample Output:
[6, 5, 10]
[1, 5, 9, 10]
[9, 5, 1]
"""
def operate_on_list(command, a_list):
if len(command) >= 1:
# The command has something in it
command_parts = command.split()
list_command = str(command_parts[0])
# If the command has two parts
if len(command_parts) >= 2:
arg1 = int(command_parts[1])
# If the command has three parts
if len(command_parts) >= 3:
arg2 = int(command_parts[2])
if list_command == "print":
print(a_list)
elif list_command == "reverse":
a_list.reverse()
elif list_command == "sort":
a_list.sort()
elif list_command == "pop":
a_list.pop()
elif list_command == "insert":
a_list.insert(arg1, arg2)
elif list_command == "append":
a_list.append(arg1)
elif list_command == "remove":
a_list.remove(arg1)
if __name__ == "__main__":
N = int(input())
the_list = []
for i in range(N):
command = input() # take the input as a string
operate_on_list(command, the_list)
|
"""
Consider a list (list = []). You can perform the following commands:
insert i e: Insert integer e at position i.
print: Print the list.
remove e: Delete the first occurrence of integer e.
append e: Insert integer e at the end of the list.
sort: Sort the list.
pop: Pop the last element from the list.
reverse: Reverse the list.
Initialize your list and read in the value of n followed by n lines of commands
where each command will be of the 7 types listed above. Iterate through each
command in order and perform the corresponding operation on your list.
Example:
n = 4
append 1
append 2
inset 3 1
print
: Append 1 to the list, [1].
: Append 2 to the list, [1, 2].
: Insert 3 at index 1, [1, 3, 2].
: Print the array.
Output:
[1, 3, 2]
Input Format:
The first line contains an integer, n, denoting the number of commands.
Each line i of the n subsequent lines contains one of the commands described above.
Constraints:
The elements added to the list must be integers.
Output Format:
For each command of type print, print the list on a new line.
Sample Input:
12
insert 0 5
insert 1 10
insert 0 6
print
remove 6
append 9
append 1
sort
print
pop
reverse
print
Sample Output:
[6, 5, 10]
[1, 5, 9, 10]
[9, 5, 1]
"""
def operate_on_list(command, a_list):
if len(command) >= 1:
command_parts = command.split()
list_command = str(command_parts[0])
if len(command_parts) >= 2:
arg1 = int(command_parts[1])
if len(command_parts) >= 3:
arg2 = int(command_parts[2])
if list_command == 'print':
print(a_list)
elif list_command == 'reverse':
a_list.reverse()
elif list_command == 'sort':
a_list.sort()
elif list_command == 'pop':
a_list.pop()
elif list_command == 'insert':
a_list.insert(arg1, arg2)
elif list_command == 'append':
a_list.append(arg1)
elif list_command == 'remove':
a_list.remove(arg1)
if __name__ == '__main__':
n = int(input())
the_list = []
for i in range(N):
command = input()
operate_on_list(command, the_list)
|
arr = []
b = False
with open("input","r") as f:
for i in f.readlines():
arr = arr + [int(i.rstrip("\n"))]
length = len(arr)
for i in range(0,length):
for j in range(0,length):
for k in range(0,length):
if (arr[i]+arr[j]+arr[k] == 2020):
print("Result = ", arr[i]*arr[j]*arr[k])
b = True
if (b):
break
|
arr = []
b = False
with open('input', 'r') as f:
for i in f.readlines():
arr = arr + [int(i.rstrip('\n'))]
length = len(arr)
for i in range(0, length):
for j in range(0, length):
for k in range(0, length):
if arr[i] + arr[j] + arr[k] == 2020:
print('Result = ', arr[i] * arr[j] * arr[k])
b = True
if b:
break
|
def classify(number):
return _classify(number) if number != 1 else 'deficient'
def _classify(number) -> str:
classif: str
aliquot: int = _aliquot(number)
if aliquot > number:
classif = 'abundant'
elif aliquot < number:
classif = 'deficient'
else:
classif = 'perfect'
return classif
def _factor_gen(number):
yield 1 # always a divisor
for n in range(2, int(number ** 0.5) + 1):
if number % n == 0: # is a divisor
yield n
if n * n != number: # is a divisor and not the square root
yield number // n
def _aliquot(number) -> int:
if number < 1: raise ValueError('invalid number')
return sum(_factor_gen(number))
|
def classify(number):
return _classify(number) if number != 1 else 'deficient'
def _classify(number) -> str:
classif: str
aliquot: int = _aliquot(number)
if aliquot > number:
classif = 'abundant'
elif aliquot < number:
classif = 'deficient'
else:
classif = 'perfect'
return classif
def _factor_gen(number):
yield 1
for n in range(2, int(number ** 0.5) + 1):
if number % n == 0:
yield n
if n * n != number:
yield (number // n)
def _aliquot(number) -> int:
if number < 1:
raise value_error('invalid number')
return sum(_factor_gen(number))
|
def f(a):
a += 2
return a
b = 1
b = f(b)
print(b)
|
def f(a):
a += 2
return a
b = 1
b = f(b)
print(b)
|
"""
Simple yeetroot example
"""
def yeetRoot():
num = int( input( "which number would you like the square root of? "))
# return print( "the square root of {} is: {:.5f}".format( num, num**.5) )
return num**.5
|
"""
Simple yeetroot example
"""
def yeet_root():
num = int(input('which number would you like the square root of? '))
return num ** 0.5
|
db = "https://raw.githubusercontent.com/nytimes/covid-19-data/master/us-counties.csv"
# database file downloaded from
# https://www.weather.gov/source/gis/Shapefiles/County/c_03mr20.zip
# to get the lat and long values for US counties
dbf = "./c_03mr20.dbf"
|
db = 'https://raw.githubusercontent.com/nytimes/covid-19-data/master/us-counties.csv'
dbf = './c_03mr20.dbf'
|
class ServiceManager() :
"""
1. definition
2. table
"""
def get_view_obj(self):
"""
get view data for net config
:return:
"""
pass
def set_view_obj(self, obj):
"""
set net config data edited on view
:param obj:
:return:
"""
pass
def get_batchver_list(self, nn_id, nn_ver):
"""
return list of batch version list
:param nn_id:
:param nn_ver:
:return:
"""
return None
def delete_batchver_info(self, nn_id, nn_ver, batch_ver):
"""
:param nn_id:
:param nn_ver:
:param batch_ver:
:return:
"""
return None
def set_active_batchver(self, nn_id, nn_ver, batch_ver):
"""
:param nn_id:
:param nn_ver:
:param batch_ver:
:return:
"""
return None
|
class Servicemanager:
"""
1. definition
2. table
"""
def get_view_obj(self):
"""
get view data for net config
:return:
"""
pass
def set_view_obj(self, obj):
"""
set net config data edited on view
:param obj:
:return:
"""
pass
def get_batchver_list(self, nn_id, nn_ver):
"""
return list of batch version list
:param nn_id:
:param nn_ver:
:return:
"""
return None
def delete_batchver_info(self, nn_id, nn_ver, batch_ver):
"""
:param nn_id:
:param nn_ver:
:param batch_ver:
:return:
"""
return None
def set_active_batchver(self, nn_id, nn_ver, batch_ver):
"""
:param nn_id:
:param nn_ver:
:param batch_ver:
:return:
"""
return None
|
load(
"@bazel_tools//tools/cpp:cc_toolchain_config_lib.bzl",
"action_config",
"feature",
"flag_group",
"flag_set",
"tool",
"tool_path",
"with_feature_set",
)
load("@bazel_tools//tools/build_defs/cc:action_names.bzl", "ACTION_NAMES")
def _impl(ctx):
if (ctx.attr.cpu == "k8" and ctx.attr.compiler == "clang7"):
toolchain_identifier = "clang7_toolchain"
else:
fail("Unreachable")
host_system_name = "local"
target_system_name = "local"
target_cpu = "k8"
target_libc = "local"
if (ctx.attr.cpu == "k8" and ctx.attr.compiler == "clang7"):
compiler = "clang7"
else:
fail("Unreachable")
abi_version = "local"
abi_libc_version = "local"
cc_target_os = None
builtin_sysroot = None
all_compile_actions = [
ACTION_NAMES.c_compile,
ACTION_NAMES.cpp_compile,
ACTION_NAMES.linkstamp_compile,
ACTION_NAMES.assemble,
ACTION_NAMES.preprocess_assemble,
ACTION_NAMES.cpp_header_parsing,
ACTION_NAMES.cpp_module_compile,
ACTION_NAMES.cpp_module_codegen,
ACTION_NAMES.clif_match,
ACTION_NAMES.lto_backend,
]
all_cpp_compile_actions = [
ACTION_NAMES.cpp_compile,
ACTION_NAMES.linkstamp_compile,
ACTION_NAMES.cpp_header_parsing,
ACTION_NAMES.cpp_module_compile,
ACTION_NAMES.cpp_module_codegen,
ACTION_NAMES.clif_match,
]
preprocessor_compile_actions = [
ACTION_NAMES.c_compile,
ACTION_NAMES.cpp_compile,
ACTION_NAMES.linkstamp_compile,
ACTION_NAMES.preprocess_assemble,
ACTION_NAMES.cpp_header_parsing,
ACTION_NAMES.cpp_module_compile,
ACTION_NAMES.clif_match,
]
codegen_compile_actions = [
ACTION_NAMES.c_compile,
ACTION_NAMES.cpp_compile,
ACTION_NAMES.linkstamp_compile,
ACTION_NAMES.assemble,
ACTION_NAMES.preprocess_assemble,
ACTION_NAMES.cpp_module_codegen,
ACTION_NAMES.lto_backend,
]
all_link_actions = [
ACTION_NAMES.cpp_link_executable,
ACTION_NAMES.cpp_link_dynamic_library,
ACTION_NAMES.cpp_link_nodeps_dynamic_library,
]
objcopy_embed_data_action = action_config(
action_name = "objcopy_embed_data",
enabled = True,
tools = [tool(path = "/usr/bin/objcopy")],
)
action_configs = [objcopy_embed_data_action]
supports_pic_feature = feature(name = "supports_pic", enabled = True)
objcopy_embed_flags_feature = feature(
name = "objcopy_embed_flags",
enabled = True,
flag_sets = [
flag_set(
actions = ["objcopy_embed_data"],
flag_groups = [flag_group(flags = ["-I", "binary"])],
),
],
)
dbg_feature = feature(name = "dbg")
sysroot_feature = feature(
name = "sysroot",
enabled = True,
flag_sets = [
flag_set(
actions = [
ACTION_NAMES.preprocess_assemble,
ACTION_NAMES.linkstamp_compile,
ACTION_NAMES.c_compile,
ACTION_NAMES.cpp_compile,
ACTION_NAMES.cpp_header_parsing,
ACTION_NAMES.cpp_module_compile,
ACTION_NAMES.cpp_module_codegen,
ACTION_NAMES.lto_backend,
ACTION_NAMES.clif_match,
ACTION_NAMES.cpp_link_executable,
ACTION_NAMES.cpp_link_dynamic_library,
ACTION_NAMES.cpp_link_nodeps_dynamic_library,
],
flag_groups = [
flag_group(
flags = ["--sysroot=%{sysroot}"],
expand_if_available = "sysroot",
),
],
),
],
)
if (ctx.attr.cpu == "k8" and ctx.attr.compiler == "clang7"):
unfiltered_compile_flags_feature = feature(
name = "unfiltered_compile_flags",
enabled = True,
flag_sets = [
flag_set(
actions = [
ACTION_NAMES.assemble,
ACTION_NAMES.preprocess_assemble,
ACTION_NAMES.linkstamp_compile,
ACTION_NAMES.c_compile,
ACTION_NAMES.cpp_compile,
ACTION_NAMES.cpp_header_parsing,
ACTION_NAMES.cpp_module_compile,
ACTION_NAMES.cpp_module_codegen,
ACTION_NAMES.lto_backend,
ACTION_NAMES.clif_match,
],
flag_groups = [
flag_group(
flags = [
"-Wno-deprecated-declarations",
"-Wno-builtin-macro-redefined",
"-D__DATE__=\"redacted\"",
"-D__TIMESTAMP__=\"redacted\"",
"-D__TIME__=\"redacted\"",
],
),
],
),
],
)
else:
unfiltered_compile_flags_feature = None
if (ctx.attr.cpu == "k8" and ctx.attr.compiler == "clang7"):
default_link_flags_feature = feature(
name = "default_link_flags",
enabled = True,
flag_sets = [
flag_set(
actions = all_link_actions,
flag_groups = [
flag_group(
flags = [
"-lstdc++",
"-lm",
"-fuse-ld=gold",
"-Wl,-no-as-needed",
"-Wl,-z,relro,-z,now",
"-B/usr/bin",
"-B/usr/bin",
],
),
],
),
flag_set(
actions = all_link_actions,
flag_groups = [flag_group(flags = ["-Wl,--gc-sections"])],
with_features = [with_feature_set(features = ["opt"])],
),
],
)
else:
default_link_flags_feature = None
coverage_feature = feature(
name = "coverage",
flag_sets = [
flag_set(
actions = [
ACTION_NAMES.preprocess_assemble,
ACTION_NAMES.c_compile,
ACTION_NAMES.cpp_compile,
ACTION_NAMES.cpp_header_parsing,
"c++-header-preprocessing",
ACTION_NAMES.cpp_module_compile,
],
flag_groups = [flag_group(flags = ["-fprofile-arcs", "-ftest-coverage"])],
),
flag_set(
actions = [
"c++-link-interface-dynamic-library",
ACTION_NAMES.cpp_link_dynamic_library,
ACTION_NAMES.cpp_link_executable,
],
flag_groups = [flag_group(flags = ["-lgcov"])],
),
],
provides = ["profile"],
)
supports_start_end_lib_feature = feature(name = "supports_start_end_lib", enabled = True)
opt_feature = feature(name = "opt")
fastbuild_feature = feature(name = "fastbuild")
user_compile_flags_feature = feature(
name = "user_compile_flags",
enabled = True,
flag_sets = [
flag_set(
actions = [
ACTION_NAMES.assemble,
ACTION_NAMES.preprocess_assemble,
ACTION_NAMES.linkstamp_compile,
ACTION_NAMES.c_compile,
ACTION_NAMES.cpp_compile,
ACTION_NAMES.cpp_header_parsing,
ACTION_NAMES.cpp_module_compile,
ACTION_NAMES.cpp_module_codegen,
ACTION_NAMES.lto_backend,
ACTION_NAMES.clif_match,
],
flag_groups = [
flag_group(
flags = ["%{user_compile_flags}"],
iterate_over = "user_compile_flags",
expand_if_available = "user_compile_flags",
),
],
),
],
)
if (ctx.attr.cpu == "k8" and ctx.attr.compiler == "clang7"):
default_compile_flags_feature = feature(
name = "default_compile_flags",
enabled = True,
flag_sets = [
flag_set(
actions = [
ACTION_NAMES.assemble,
ACTION_NAMES.preprocess_assemble,
ACTION_NAMES.linkstamp_compile,
ACTION_NAMES.c_compile,
ACTION_NAMES.cpp_compile,
ACTION_NAMES.cpp_header_parsing,
ACTION_NAMES.cpp_module_compile,
ACTION_NAMES.cpp_module_codegen,
ACTION_NAMES.lto_backend,
ACTION_NAMES.clif_match,
],
flag_groups = [
flag_group(
flags = [
"-U_FORTIFY_SOURCE",
"-fstack-protector",
"-Wall",
"-B/usr/bin",
"-B/usr/bin",
"-fno-omit-frame-pointer",
"-fcolor-diagnostics",
],
),
],
),
flag_set(
actions = [
ACTION_NAMES.assemble,
ACTION_NAMES.preprocess_assemble,
ACTION_NAMES.linkstamp_compile,
ACTION_NAMES.c_compile,
ACTION_NAMES.cpp_compile,
ACTION_NAMES.cpp_header_parsing,
ACTION_NAMES.cpp_module_compile,
ACTION_NAMES.cpp_module_codegen,
ACTION_NAMES.lto_backend,
ACTION_NAMES.clif_match,
],
flag_groups = [flag_group(flags = ["-g"])],
with_features = [with_feature_set(features = ["dbg"])],
),
flag_set(
actions = [
ACTION_NAMES.assemble,
ACTION_NAMES.preprocess_assemble,
ACTION_NAMES.linkstamp_compile,
ACTION_NAMES.c_compile,
ACTION_NAMES.cpp_compile,
ACTION_NAMES.cpp_header_parsing,
ACTION_NAMES.cpp_module_compile,
ACTION_NAMES.cpp_module_codegen,
ACTION_NAMES.lto_backend,
ACTION_NAMES.clif_match,
],
flag_groups = [
flag_group(
flags = [
"-ggdb",
"-O2",
"-D_FORTIFY_SOURCE=1",
"-DNDEBUG",
"-ffunction-sections",
"-fdata-sections",
],
),
],
with_features = [with_feature_set(features = ["opt"])],
),
flag_set(
actions = [
ACTION_NAMES.assemble,
ACTION_NAMES.preprocess_assemble,
ACTION_NAMES.linkstamp_compile,
ACTION_NAMES.c_compile,
ACTION_NAMES.cpp_compile,
ACTION_NAMES.cpp_header_parsing,
ACTION_NAMES.cpp_module_compile,
ACTION_NAMES.cpp_module_codegen,
ACTION_NAMES.lto_backend,
ACTION_NAMES.clif_match,
],
flag_groups = [flag_group(flags = ["-g"])],
with_features = [with_feature_set(features = ["fastbuild"])],
),
flag_set(
actions = [
ACTION_NAMES.linkstamp_compile,
ACTION_NAMES.cpp_compile,
ACTION_NAMES.cpp_header_parsing,
ACTION_NAMES.cpp_module_compile,
ACTION_NAMES.cpp_module_codegen,
ACTION_NAMES.lto_backend,
ACTION_NAMES.clif_match,
],
flag_groups = [
flag_group(
flags = [
"-Werror",
"-std=c++17",
"-Wall",
"-B/usr/bin",
"-B/usr/bin",
"-Wunused-parameter",
"-fno-omit-frame-pointer",
"-Werror=sign-compare",
],
),
],
),
],
)
else:
default_compile_flags_feature = None
supports_dynamic_linker_feature = feature(name = "supports_dynamic_linker", enabled = True)
features = [
default_compile_flags_feature,
default_link_flags_feature,
coverage_feature,
supports_dynamic_linker_feature,
supports_start_end_lib_feature,
supports_pic_feature,
objcopy_embed_flags_feature,
opt_feature,
dbg_feature,
fastbuild_feature,
user_compile_flags_feature,
sysroot_feature,
unfiltered_compile_flags_feature,
]
if (ctx.attr.cpu == "k8" and ctx.attr.compiler == "clang7"):
cxx_builtin_include_directories = [
"/usr/lib/llvm-7/lib/clang/7.1.0/include",
"/usr/local/include",
"/usr/include",
]
else:
fail("Unreachable")
artifact_name_patterns = []
make_variables = []
if (ctx.attr.cpu == "k8" and ctx.attr.compiler == "clang7"):
tool_paths = [
tool_path(name = "ld", path = "/usr/bin/ld"),
tool_path(name = "cpp", path = "/usr/bin/cpp"),
tool_path(name = "dwp", path = "/usr/bin/dwp"),
tool_path(name = "gcov", path = "/usr/bin/gcov"),
tool_path(name = "nm", path = "/usr/bin/nm"),
tool_path(name = "objcopy", path = "/usr/bin/objcopy"),
tool_path(name = "objdump", path = "/usr/bin/objdump"),
tool_path(name = "strip", path = "/usr/bin/strip"),
tool_path(name = "gcc", path = "/usr/bin/clang-7"),
tool_path(name = "ar", path = "/usr/bin/ar"),
]
else:
fail("Unreachable")
out = ctx.actions.declare_file(ctx.label.name)
ctx.actions.write(out, "Fake executable")
return [
cc_common.create_cc_toolchain_config_info(
ctx = ctx,
features = features,
action_configs = action_configs,
artifact_name_patterns = artifact_name_patterns,
cxx_builtin_include_directories = cxx_builtin_include_directories,
toolchain_identifier = toolchain_identifier,
host_system_name = host_system_name,
target_system_name = target_system_name,
target_cpu = target_cpu,
target_libc = target_libc,
compiler = compiler,
abi_version = abi_version,
abi_libc_version = abi_libc_version,
tool_paths = tool_paths,
make_variables = make_variables,
builtin_sysroot = builtin_sysroot,
cc_target_os = cc_target_os,
),
DefaultInfo(
executable = out,
),
]
cc_toolchain_config = rule(
implementation = _impl,
attrs = {
"cpu": attr.string(mandatory = True, values = ["k8"]),
"compiler": attr.string(mandatory = True, values = ["clang7"]),
},
provides = [CcToolchainConfigInfo],
executable = True,
)
|
load('@bazel_tools//tools/cpp:cc_toolchain_config_lib.bzl', 'action_config', 'feature', 'flag_group', 'flag_set', 'tool', 'tool_path', 'with_feature_set')
load('@bazel_tools//tools/build_defs/cc:action_names.bzl', 'ACTION_NAMES')
def _impl(ctx):
if ctx.attr.cpu == 'k8' and ctx.attr.compiler == 'clang7':
toolchain_identifier = 'clang7_toolchain'
else:
fail('Unreachable')
host_system_name = 'local'
target_system_name = 'local'
target_cpu = 'k8'
target_libc = 'local'
if ctx.attr.cpu == 'k8' and ctx.attr.compiler == 'clang7':
compiler = 'clang7'
else:
fail('Unreachable')
abi_version = 'local'
abi_libc_version = 'local'
cc_target_os = None
builtin_sysroot = None
all_compile_actions = [ACTION_NAMES.c_compile, ACTION_NAMES.cpp_compile, ACTION_NAMES.linkstamp_compile, ACTION_NAMES.assemble, ACTION_NAMES.preprocess_assemble, ACTION_NAMES.cpp_header_parsing, ACTION_NAMES.cpp_module_compile, ACTION_NAMES.cpp_module_codegen, ACTION_NAMES.clif_match, ACTION_NAMES.lto_backend]
all_cpp_compile_actions = [ACTION_NAMES.cpp_compile, ACTION_NAMES.linkstamp_compile, ACTION_NAMES.cpp_header_parsing, ACTION_NAMES.cpp_module_compile, ACTION_NAMES.cpp_module_codegen, ACTION_NAMES.clif_match]
preprocessor_compile_actions = [ACTION_NAMES.c_compile, ACTION_NAMES.cpp_compile, ACTION_NAMES.linkstamp_compile, ACTION_NAMES.preprocess_assemble, ACTION_NAMES.cpp_header_parsing, ACTION_NAMES.cpp_module_compile, ACTION_NAMES.clif_match]
codegen_compile_actions = [ACTION_NAMES.c_compile, ACTION_NAMES.cpp_compile, ACTION_NAMES.linkstamp_compile, ACTION_NAMES.assemble, ACTION_NAMES.preprocess_assemble, ACTION_NAMES.cpp_module_codegen, ACTION_NAMES.lto_backend]
all_link_actions = [ACTION_NAMES.cpp_link_executable, ACTION_NAMES.cpp_link_dynamic_library, ACTION_NAMES.cpp_link_nodeps_dynamic_library]
objcopy_embed_data_action = action_config(action_name='objcopy_embed_data', enabled=True, tools=[tool(path='/usr/bin/objcopy')])
action_configs = [objcopy_embed_data_action]
supports_pic_feature = feature(name='supports_pic', enabled=True)
objcopy_embed_flags_feature = feature(name='objcopy_embed_flags', enabled=True, flag_sets=[flag_set(actions=['objcopy_embed_data'], flag_groups=[flag_group(flags=['-I', 'binary'])])])
dbg_feature = feature(name='dbg')
sysroot_feature = feature(name='sysroot', enabled=True, flag_sets=[flag_set(actions=[ACTION_NAMES.preprocess_assemble, ACTION_NAMES.linkstamp_compile, ACTION_NAMES.c_compile, ACTION_NAMES.cpp_compile, ACTION_NAMES.cpp_header_parsing, ACTION_NAMES.cpp_module_compile, ACTION_NAMES.cpp_module_codegen, ACTION_NAMES.lto_backend, ACTION_NAMES.clif_match, ACTION_NAMES.cpp_link_executable, ACTION_NAMES.cpp_link_dynamic_library, ACTION_NAMES.cpp_link_nodeps_dynamic_library], flag_groups=[flag_group(flags=['--sysroot=%{sysroot}'], expand_if_available='sysroot')])])
if ctx.attr.cpu == 'k8' and ctx.attr.compiler == 'clang7':
unfiltered_compile_flags_feature = feature(name='unfiltered_compile_flags', enabled=True, flag_sets=[flag_set(actions=[ACTION_NAMES.assemble, ACTION_NAMES.preprocess_assemble, ACTION_NAMES.linkstamp_compile, ACTION_NAMES.c_compile, ACTION_NAMES.cpp_compile, ACTION_NAMES.cpp_header_parsing, ACTION_NAMES.cpp_module_compile, ACTION_NAMES.cpp_module_codegen, ACTION_NAMES.lto_backend, ACTION_NAMES.clif_match], flag_groups=[flag_group(flags=['-Wno-deprecated-declarations', '-Wno-builtin-macro-redefined', '-D__DATE__="redacted"', '-D__TIMESTAMP__="redacted"', '-D__TIME__="redacted"'])])])
else:
unfiltered_compile_flags_feature = None
if ctx.attr.cpu == 'k8' and ctx.attr.compiler == 'clang7':
default_link_flags_feature = feature(name='default_link_flags', enabled=True, flag_sets=[flag_set(actions=all_link_actions, flag_groups=[flag_group(flags=['-lstdc++', '-lm', '-fuse-ld=gold', '-Wl,-no-as-needed', '-Wl,-z,relro,-z,now', '-B/usr/bin', '-B/usr/bin'])]), flag_set(actions=all_link_actions, flag_groups=[flag_group(flags=['-Wl,--gc-sections'])], with_features=[with_feature_set(features=['opt'])])])
else:
default_link_flags_feature = None
coverage_feature = feature(name='coverage', flag_sets=[flag_set(actions=[ACTION_NAMES.preprocess_assemble, ACTION_NAMES.c_compile, ACTION_NAMES.cpp_compile, ACTION_NAMES.cpp_header_parsing, 'c++-header-preprocessing', ACTION_NAMES.cpp_module_compile], flag_groups=[flag_group(flags=['-fprofile-arcs', '-ftest-coverage'])]), flag_set(actions=['c++-link-interface-dynamic-library', ACTION_NAMES.cpp_link_dynamic_library, ACTION_NAMES.cpp_link_executable], flag_groups=[flag_group(flags=['-lgcov'])])], provides=['profile'])
supports_start_end_lib_feature = feature(name='supports_start_end_lib', enabled=True)
opt_feature = feature(name='opt')
fastbuild_feature = feature(name='fastbuild')
user_compile_flags_feature = feature(name='user_compile_flags', enabled=True, flag_sets=[flag_set(actions=[ACTION_NAMES.assemble, ACTION_NAMES.preprocess_assemble, ACTION_NAMES.linkstamp_compile, ACTION_NAMES.c_compile, ACTION_NAMES.cpp_compile, ACTION_NAMES.cpp_header_parsing, ACTION_NAMES.cpp_module_compile, ACTION_NAMES.cpp_module_codegen, ACTION_NAMES.lto_backend, ACTION_NAMES.clif_match], flag_groups=[flag_group(flags=['%{user_compile_flags}'], iterate_over='user_compile_flags', expand_if_available='user_compile_flags')])])
if ctx.attr.cpu == 'k8' and ctx.attr.compiler == 'clang7':
default_compile_flags_feature = feature(name='default_compile_flags', enabled=True, flag_sets=[flag_set(actions=[ACTION_NAMES.assemble, ACTION_NAMES.preprocess_assemble, ACTION_NAMES.linkstamp_compile, ACTION_NAMES.c_compile, ACTION_NAMES.cpp_compile, ACTION_NAMES.cpp_header_parsing, ACTION_NAMES.cpp_module_compile, ACTION_NAMES.cpp_module_codegen, ACTION_NAMES.lto_backend, ACTION_NAMES.clif_match], flag_groups=[flag_group(flags=['-U_FORTIFY_SOURCE', '-fstack-protector', '-Wall', '-B/usr/bin', '-B/usr/bin', '-fno-omit-frame-pointer', '-fcolor-diagnostics'])]), flag_set(actions=[ACTION_NAMES.assemble, ACTION_NAMES.preprocess_assemble, ACTION_NAMES.linkstamp_compile, ACTION_NAMES.c_compile, ACTION_NAMES.cpp_compile, ACTION_NAMES.cpp_header_parsing, ACTION_NAMES.cpp_module_compile, ACTION_NAMES.cpp_module_codegen, ACTION_NAMES.lto_backend, ACTION_NAMES.clif_match], flag_groups=[flag_group(flags=['-g'])], with_features=[with_feature_set(features=['dbg'])]), flag_set(actions=[ACTION_NAMES.assemble, ACTION_NAMES.preprocess_assemble, ACTION_NAMES.linkstamp_compile, ACTION_NAMES.c_compile, ACTION_NAMES.cpp_compile, ACTION_NAMES.cpp_header_parsing, ACTION_NAMES.cpp_module_compile, ACTION_NAMES.cpp_module_codegen, ACTION_NAMES.lto_backend, ACTION_NAMES.clif_match], flag_groups=[flag_group(flags=['-ggdb', '-O2', '-D_FORTIFY_SOURCE=1', '-DNDEBUG', '-ffunction-sections', '-fdata-sections'])], with_features=[with_feature_set(features=['opt'])]), flag_set(actions=[ACTION_NAMES.assemble, ACTION_NAMES.preprocess_assemble, ACTION_NAMES.linkstamp_compile, ACTION_NAMES.c_compile, ACTION_NAMES.cpp_compile, ACTION_NAMES.cpp_header_parsing, ACTION_NAMES.cpp_module_compile, ACTION_NAMES.cpp_module_codegen, ACTION_NAMES.lto_backend, ACTION_NAMES.clif_match], flag_groups=[flag_group(flags=['-g'])], with_features=[with_feature_set(features=['fastbuild'])]), flag_set(actions=[ACTION_NAMES.linkstamp_compile, ACTION_NAMES.cpp_compile, ACTION_NAMES.cpp_header_parsing, ACTION_NAMES.cpp_module_compile, ACTION_NAMES.cpp_module_codegen, ACTION_NAMES.lto_backend, ACTION_NAMES.clif_match], flag_groups=[flag_group(flags=['-Werror', '-std=c++17', '-Wall', '-B/usr/bin', '-B/usr/bin', '-Wunused-parameter', '-fno-omit-frame-pointer', '-Werror=sign-compare'])])])
else:
default_compile_flags_feature = None
supports_dynamic_linker_feature = feature(name='supports_dynamic_linker', enabled=True)
features = [default_compile_flags_feature, default_link_flags_feature, coverage_feature, supports_dynamic_linker_feature, supports_start_end_lib_feature, supports_pic_feature, objcopy_embed_flags_feature, opt_feature, dbg_feature, fastbuild_feature, user_compile_flags_feature, sysroot_feature, unfiltered_compile_flags_feature]
if ctx.attr.cpu == 'k8' and ctx.attr.compiler == 'clang7':
cxx_builtin_include_directories = ['/usr/lib/llvm-7/lib/clang/7.1.0/include', '/usr/local/include', '/usr/include']
else:
fail('Unreachable')
artifact_name_patterns = []
make_variables = []
if ctx.attr.cpu == 'k8' and ctx.attr.compiler == 'clang7':
tool_paths = [tool_path(name='ld', path='/usr/bin/ld'), tool_path(name='cpp', path='/usr/bin/cpp'), tool_path(name='dwp', path='/usr/bin/dwp'), tool_path(name='gcov', path='/usr/bin/gcov'), tool_path(name='nm', path='/usr/bin/nm'), tool_path(name='objcopy', path='/usr/bin/objcopy'), tool_path(name='objdump', path='/usr/bin/objdump'), tool_path(name='strip', path='/usr/bin/strip'), tool_path(name='gcc', path='/usr/bin/clang-7'), tool_path(name='ar', path='/usr/bin/ar')]
else:
fail('Unreachable')
out = ctx.actions.declare_file(ctx.label.name)
ctx.actions.write(out, 'Fake executable')
return [cc_common.create_cc_toolchain_config_info(ctx=ctx, features=features, action_configs=action_configs, artifact_name_patterns=artifact_name_patterns, cxx_builtin_include_directories=cxx_builtin_include_directories, toolchain_identifier=toolchain_identifier, host_system_name=host_system_name, target_system_name=target_system_name, target_cpu=target_cpu, target_libc=target_libc, compiler=compiler, abi_version=abi_version, abi_libc_version=abi_libc_version, tool_paths=tool_paths, make_variables=make_variables, builtin_sysroot=builtin_sysroot, cc_target_os=cc_target_os), default_info(executable=out)]
cc_toolchain_config = rule(implementation=_impl, attrs={'cpu': attr.string(mandatory=True, values=['k8']), 'compiler': attr.string(mandatory=True, values=['clang7'])}, provides=[CcToolchainConfigInfo], executable=True)
|
for i in range(plan_arguments['RUN_NUM']):
############################################# CC #############################################
add_test(name='cc_feature_rtest',
tags=['L10', 'cc'],
args=[' -rtlarg +uvm_set_config_int=uvm_test_top,layers,%d ' % plan_arguments['LAYER_NUM'], get_seed_args(), DISABLE_COMPARE_ALL_UNITS_SB_ARG],
module='nvdla_uvm_test',
config=['nvdla_utb'],
desc=''' None reuse CC random case, input data format is fixed as feature ''')
add_test(name='cc_pitch_rtest',
tags=['L10', 'cc'],
args=[' -rtlarg +uvm_set_config_int=uvm_test_top,layers,%d ' % plan_arguments['LAYER_NUM'], get_seed_args(), DISABLE_COMPARE_ALL_UNITS_SB_ARG],
module='nvdla_uvm_test',
config=['nvdla_utb'],
desc=''' None reuse CC random case, input data format is fixed as image ''')
add_test(name='cc_feature_data_full_reuse_rtest',
tags=['L10', 'cc'],
args=[' -rtlarg +uvm_set_config_int=uvm_test_top,layers,2 ', get_seed_args(), DISABLE_COMPARE_ALL_UNITS_SB_ARG], # for reuse case, at least 2 layers are required
module='nvdla_uvm_test',
config=['nvdla_utb'],
desc=''' CC reuse input data random case, input data format is fixed as feature ''')
add_test(name='cc_feature_weight_full_reuse_rtest',
tags=['L10', 'cc'],
args=[' -rtlarg +uvm_set_config_int=uvm_test_top,layers,2 ', get_seed_args(), DISABLE_COMPARE_ALL_UNITS_SB_ARG], # for reuse case, at least 2 layers are required
module='nvdla_uvm_test',
config=['nvdla_utb'],
desc=''' CC reuse weight random case, input data format is fixed as feature ''')
add_test(name='cc_image_data_full_reuse_rtest',
tags=['L10', 'cc'],
args=[' -rtlarg +uvm_set_config_int=uvm_test_top,layers,2 ', get_seed_args(), DISABLE_COMPARE_ALL_UNITS_SB_ARG], # for reuse case, at least 2 layers are required
module='nvdla_uvm_test',
config=['nvdla_utb'],
desc=''' CC reuse input data random case, input data format is fixed as image ''')
add_test(name='cc_rtest',
tags=['L10', 'cc'],
args=[' -rtlarg +uvm_set_config_int=uvm_test_top,layers,%d ' % plan_arguments['LAYER_NUM'], get_seed_args(), DISABLE_COMPARE_ALL_UNITS_SB_ARG],
module='nvdla_uvm_test',
config=['nvdla_utb'],
desc=''' None reuse CC random case ''')
############################################## PDP #############################################
add_test(name='pdp_split_rtest',
tags=['L10', 'pdp'],
args=[' -rtlarg +uvm_set_config_int=uvm_test_top,layers,%d ' % plan_arguments['LAYER_NUM'], get_seed_args(), DISABLE_COMPARE_ALL_UNITS_SB_ARG],
module='nvdla_uvm_test',
config=['nvdla_utb'],
desc=''' PDP random case, fixed to split mode ''')
add_test(name='pdp_non_split_rtest',
tags=['L10', 'pdp'],
args=[' -rtlarg +uvm_set_config_int=uvm_test_top,layers,%d ' % plan_arguments['LAYER_NUM'], get_seed_args(), DISABLE_COMPARE_ALL_UNITS_SB_ARG],
module='nvdla_uvm_test',
config=['nvdla_utb'],
desc=''' PDP random case, fixed to non-split mode ''')
add_test(name='pdp_rtest',
tags=['L10', 'pdp'],
args=[' -rtlarg +uvm_set_config_int=uvm_test_top,layers,%d ' % plan_arguments['LAYER_NUM'], get_seed_args(), DISABLE_COMPARE_ALL_UNITS_SB_ARG],
module='nvdla_uvm_test',
config=['nvdla_utb'],
desc=''' PDP random case ''')
############################################# SDP #############################################
if 'NVDLA_SDP_BS_ENABLE' in project.PROJVAR and project.PROJVAR['NVDLA_SDP_BS_ENABLE'] is True:
add_test(name='sdp_bs_rtest',
tags=['L10', 'sdp'],
args=[' -rtlarg +uvm_set_config_int=uvm_test_top,layers,%d ' % plan_arguments['LAYER_NUM'], get_seed_args(), DISABLE_COMPARE_ALL_UNITS_SB_ARG],
module='nvdla_uvm_test',
config=['nvdla_utb'],
desc=''' SDP offline random case, with BS enabled and not bypassed ''')
if 'NVDLA_SDP_BN_ENABLE' in project.PROJVAR and project.PROJVAR['NVDLA_SDP_BN_ENABLE'] is True:
add_test(name='sdp_bn_rtest',
tags=['L10', 'sdp'],
args=[' -rtlarg +uvm_set_config_int=uvm_test_top,layers,%d ' % plan_arguments['LAYER_NUM'], get_seed_args(), DISABLE_COMPARE_ALL_UNITS_SB_ARG],
module='nvdla_uvm_test',
config=['nvdla_utb'],
desc=''' SDP offline random case, with BN enabled and not bypassed ''')
if 'NVDLA_SDP_EW_ENABLE' in project.PROJVAR and project.PROJVAR['NVDLA_SDP_EW_ENABLE'] is True:
add_test(name='sdp_ew_rtest',
tags=['L10', 'sdp'],
args=[' -rtlarg +uvm_set_config_int=uvm_test_top,layers,%d ' % plan_arguments['LAYER_NUM'], get_seed_args(), DISABLE_COMPARE_ALL_UNITS_SB_ARG],
module='nvdla_uvm_test',
config=['nvdla_utb'],
desc=''' SDP offline random case, with EW enabled and not bypassed ''')
add_test(name='sdp_rtest',
tags=['L10', 'sdp'],
args=[' -rtlarg +uvm_set_config_int=uvm_test_top,layers,%d ' % plan_arguments['LAYER_NUM'], get_seed_args(), DISABLE_COMPARE_ALL_UNITS_SB_ARG],
module='nvdla_uvm_test',
config=['nvdla_utb'],
desc=''' SDP offline random case ''')
############################################# CDP #############################################
add_test(name='cdp_exp_rtest',
tags=['L10', 'cdp'],
args=[' -rtlarg +uvm_set_config_int=uvm_test_top,layers,%d ' % plan_arguments['LAYER_NUM'], get_seed_args(), DISABLE_COMPARE_ALL_UNITS_SB_ARG],
module='nvdla_uvm_test',
config=['nvdla_utb'],
desc=''' CDP random case, fixed to EXPONENT mode of LE LUT ''')
add_test(name='cdp_lin_rtest',
tags=['L10', 'cdp'],
args=[' -rtlarg +uvm_set_config_int=uvm_test_top,layers,%d ' % plan_arguments['LAYER_NUM'], get_seed_args(), DISABLE_COMPARE_ALL_UNITS_SB_ARG],
module='nvdla_uvm_test',
config=['nvdla_utb'],
desc=''' CDP random case, fixed to LINEAR mode of LE LUT ''')
add_test(name='cdp_rtest',
tags=['L10', 'cdp'],
args=[' -rtlarg +uvm_set_config_int=uvm_test_top,layers,%d ' % plan_arguments['LAYER_NUM'], get_seed_args(), DISABLE_COMPARE_ALL_UNITS_SB_ARG],
module='nvdla_uvm_test',
config=['nvdla_utb'],
desc=''' CDP random case ''')
|
for i in range(plan_arguments['RUN_NUM']):
add_test(name='cc_feature_rtest', tags=['L10', 'cc'], args=[' -rtlarg +uvm_set_config_int=uvm_test_top,layers,%d ' % plan_arguments['LAYER_NUM'], get_seed_args(), DISABLE_COMPARE_ALL_UNITS_SB_ARG], module='nvdla_uvm_test', config=['nvdla_utb'], desc=' None reuse CC random case, input data format is fixed as feature ')
add_test(name='cc_pitch_rtest', tags=['L10', 'cc'], args=[' -rtlarg +uvm_set_config_int=uvm_test_top,layers,%d ' % plan_arguments['LAYER_NUM'], get_seed_args(), DISABLE_COMPARE_ALL_UNITS_SB_ARG], module='nvdla_uvm_test', config=['nvdla_utb'], desc=' None reuse CC random case, input data format is fixed as image ')
add_test(name='cc_feature_data_full_reuse_rtest', tags=['L10', 'cc'], args=[' -rtlarg +uvm_set_config_int=uvm_test_top,layers,2 ', get_seed_args(), DISABLE_COMPARE_ALL_UNITS_SB_ARG], module='nvdla_uvm_test', config=['nvdla_utb'], desc=' CC reuse input data random case, input data format is fixed as feature ')
add_test(name='cc_feature_weight_full_reuse_rtest', tags=['L10', 'cc'], args=[' -rtlarg +uvm_set_config_int=uvm_test_top,layers,2 ', get_seed_args(), DISABLE_COMPARE_ALL_UNITS_SB_ARG], module='nvdla_uvm_test', config=['nvdla_utb'], desc=' CC reuse weight random case, input data format is fixed as feature ')
add_test(name='cc_image_data_full_reuse_rtest', tags=['L10', 'cc'], args=[' -rtlarg +uvm_set_config_int=uvm_test_top,layers,2 ', get_seed_args(), DISABLE_COMPARE_ALL_UNITS_SB_ARG], module='nvdla_uvm_test', config=['nvdla_utb'], desc=' CC reuse input data random case, input data format is fixed as image ')
add_test(name='cc_rtest', tags=['L10', 'cc'], args=[' -rtlarg +uvm_set_config_int=uvm_test_top,layers,%d ' % plan_arguments['LAYER_NUM'], get_seed_args(), DISABLE_COMPARE_ALL_UNITS_SB_ARG], module='nvdla_uvm_test', config=['nvdla_utb'], desc=' None reuse CC random case ')
add_test(name='pdp_split_rtest', tags=['L10', 'pdp'], args=[' -rtlarg +uvm_set_config_int=uvm_test_top,layers,%d ' % plan_arguments['LAYER_NUM'], get_seed_args(), DISABLE_COMPARE_ALL_UNITS_SB_ARG], module='nvdla_uvm_test', config=['nvdla_utb'], desc=' PDP random case, fixed to split mode ')
add_test(name='pdp_non_split_rtest', tags=['L10', 'pdp'], args=[' -rtlarg +uvm_set_config_int=uvm_test_top,layers,%d ' % plan_arguments['LAYER_NUM'], get_seed_args(), DISABLE_COMPARE_ALL_UNITS_SB_ARG], module='nvdla_uvm_test', config=['nvdla_utb'], desc=' PDP random case, fixed to non-split mode ')
add_test(name='pdp_rtest', tags=['L10', 'pdp'], args=[' -rtlarg +uvm_set_config_int=uvm_test_top,layers,%d ' % plan_arguments['LAYER_NUM'], get_seed_args(), DISABLE_COMPARE_ALL_UNITS_SB_ARG], module='nvdla_uvm_test', config=['nvdla_utb'], desc=' PDP random case ')
if 'NVDLA_SDP_BS_ENABLE' in project.PROJVAR and project.PROJVAR['NVDLA_SDP_BS_ENABLE'] is True:
add_test(name='sdp_bs_rtest', tags=['L10', 'sdp'], args=[' -rtlarg +uvm_set_config_int=uvm_test_top,layers,%d ' % plan_arguments['LAYER_NUM'], get_seed_args(), DISABLE_COMPARE_ALL_UNITS_SB_ARG], module='nvdla_uvm_test', config=['nvdla_utb'], desc=' SDP offline random case, with BS enabled and not bypassed ')
if 'NVDLA_SDP_BN_ENABLE' in project.PROJVAR and project.PROJVAR['NVDLA_SDP_BN_ENABLE'] is True:
add_test(name='sdp_bn_rtest', tags=['L10', 'sdp'], args=[' -rtlarg +uvm_set_config_int=uvm_test_top,layers,%d ' % plan_arguments['LAYER_NUM'], get_seed_args(), DISABLE_COMPARE_ALL_UNITS_SB_ARG], module='nvdla_uvm_test', config=['nvdla_utb'], desc=' SDP offline random case, with BN enabled and not bypassed ')
if 'NVDLA_SDP_EW_ENABLE' in project.PROJVAR and project.PROJVAR['NVDLA_SDP_EW_ENABLE'] is True:
add_test(name='sdp_ew_rtest', tags=['L10', 'sdp'], args=[' -rtlarg +uvm_set_config_int=uvm_test_top,layers,%d ' % plan_arguments['LAYER_NUM'], get_seed_args(), DISABLE_COMPARE_ALL_UNITS_SB_ARG], module='nvdla_uvm_test', config=['nvdla_utb'], desc=' SDP offline random case, with EW enabled and not bypassed ')
add_test(name='sdp_rtest', tags=['L10', 'sdp'], args=[' -rtlarg +uvm_set_config_int=uvm_test_top,layers,%d ' % plan_arguments['LAYER_NUM'], get_seed_args(), DISABLE_COMPARE_ALL_UNITS_SB_ARG], module='nvdla_uvm_test', config=['nvdla_utb'], desc=' SDP offline random case ')
add_test(name='cdp_exp_rtest', tags=['L10', 'cdp'], args=[' -rtlarg +uvm_set_config_int=uvm_test_top,layers,%d ' % plan_arguments['LAYER_NUM'], get_seed_args(), DISABLE_COMPARE_ALL_UNITS_SB_ARG], module='nvdla_uvm_test', config=['nvdla_utb'], desc=' CDP random case, fixed to EXPONENT mode of LE LUT ')
add_test(name='cdp_lin_rtest', tags=['L10', 'cdp'], args=[' -rtlarg +uvm_set_config_int=uvm_test_top,layers,%d ' % plan_arguments['LAYER_NUM'], get_seed_args(), DISABLE_COMPARE_ALL_UNITS_SB_ARG], module='nvdla_uvm_test', config=['nvdla_utb'], desc=' CDP random case, fixed to LINEAR mode of LE LUT ')
add_test(name='cdp_rtest', tags=['L10', 'cdp'], args=[' -rtlarg +uvm_set_config_int=uvm_test_top,layers,%d ' % plan_arguments['LAYER_NUM'], get_seed_args(), DISABLE_COMPARE_ALL_UNITS_SB_ARG], module='nvdla_uvm_test', config=['nvdla_utb'], desc=' CDP random case ')
|
'''Example test script.
Basic checks of device before processed
Input Variables:
args - arguments dictionary given to demo tester that may be used to
changed nature of test.
dev - Example device under test
name - Name of test being run.
results - Results map of all tests.
Test Specific Arguments:
args["hw_rev"] - hardware revision to expect
'''
expected_hw_rev = args["hw_rev"]
output_good("Welcome")
output_normal("Reading device 3.3V power rail.")
mV = dev.read_3v3_rail()
store_value("V3.3 power rail mV", mV)
threshold_check(mV, 3300, 90, "mV", "Power rail check")
output_normal("Checking device current draw.")
mA = dev.read_current()
store_value("mA draw", mA)
threshold_check(mA, 150, 10, "mA", "Power draw")
output_normal("Read hardware revision from device pull ups.")
hw_rev = dev.read_revision()
store_value("HW Rev", hw_rev)
exact_check(hw_rev, expected_hw_rev, "Hardware revision")
|
"""Example test script.
Basic checks of device before processed
Input Variables:
args - arguments dictionary given to demo tester that may be used to
changed nature of test.
dev - Example device under test
name - Name of test being run.
results - Results map of all tests.
Test Specific Arguments:
args["hw_rev"] - hardware revision to expect
"""
expected_hw_rev = args['hw_rev']
output_good('Welcome')
output_normal('Reading device 3.3V power rail.')
m_v = dev.read_3v3_rail()
store_value('V3.3 power rail mV', mV)
threshold_check(mV, 3300, 90, 'mV', 'Power rail check')
output_normal('Checking device current draw.')
m_a = dev.read_current()
store_value('mA draw', mA)
threshold_check(mA, 150, 10, 'mA', 'Power draw')
output_normal('Read hardware revision from device pull ups.')
hw_rev = dev.read_revision()
store_value('HW Rev', hw_rev)
exact_check(hw_rev, expected_hw_rev, 'Hardware revision')
|
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 4 20:13:02 2018
@author: User
"""
def checkit(s1, s2):
for i in s1:
for j in s2:
if i == j:
s1 = s1[1:]
s2 = s2[1:]
print(i,j, s1, s2)
if len(s1) >=1 and len(s2) ==0:
return True
return False
print(checkit("I am a string","I am a"))
|
"""
Created on Sun Feb 4 20:13:02 2018
@author: User
"""
def checkit(s1, s2):
for i in s1:
for j in s2:
if i == j:
s1 = s1[1:]
s2 = s2[1:]
print(i, j, s1, s2)
if len(s1) >= 1 and len(s2) == 0:
return True
return False
print(checkit('I am a string', 'I am a'))
|
# 3-9. Dinner Guests: Working with one of the programs from Exercises 3-4 through 3-7 (page 46),
# use len() to print a message indicating the number of people you are inviting to dinner.
guests = ['Antonio', 'Emanuel', 'Francisco']
message = "1.- Hello dear uncle " + guests[0] + ", I hope you can come this 16th for a mexican dinner in my house."
print(message)
message = "2.- Hi " + guests[1] + "! The next monday we'll have a dinner, you should come here to spend time with " \
"friends for a while, also we will have some beers. "
print(message)
message = "3.- Hello grandpa " + guests[2] + "!, my mother told me that we will have a dinner next monday and we want" \
" that you come here because we miss you. "
print(message)
print('\n')
print(len(guests))
|
guests = ['Antonio', 'Emanuel', 'Francisco']
message = '1.- Hello dear uncle ' + guests[0] + ', I hope you can come this 16th for a mexican dinner in my house.'
print(message)
message = '2.- Hi ' + guests[1] + "! The next monday we'll have a dinner, you should come here to spend time with friends for a while, also we will have some beers. "
print(message)
message = '3.- Hello grandpa ' + guests[2] + '!, my mother told me that we will have a dinner next monday and we want that you come here because we miss you. '
print(message)
print('\n')
print(len(guests))
|
#https://adventofcode.com/2021/day/1
input2="""131
140
136
135
155
175
178
186
187
189
194
195
203
193
178
179
180
188
204
214
215
252
253
261
281
294
293
299
300
301
307
333
324
322
323
335
319
312
313
312
320
323
324
336
341
347
357
358
363
357
334
348
364
365
367
370
369
373
344
328
330
327
339
340
341
335
342
347
349
355
348
359
360
341
342
322
321
324
323
322
324
327
340
341
353
383
387
391
422
424
422
426
429
427
428
445
421
423
429
414
411
407
409
402
422
425
423
427
424
430
428
432
433
434
429
430
406
407
411
420
412
419
422
424
425
426
428
430
432
431
432
433
449
450
453
457
459
462
482
470
471
488
495
496
499
503
516
526
531
532
541
555
554
567
558
557
560
561
566
580
581
582
594
595
598
599
582
589
593
589
592
593
590
606
615
623
627
628
630
636
641
657
658
693
695
698
707
713
714
720
721
723
721
720
707
679
699
676
667
663
664
666
660
663
673
677
662
660
663
683
681
674
689
698
699
704
705
696
697
702
693
694
700
699
681
684
690
669
673
688
691
692
691
688
685
656
638
634
651
665
670
672
685
689
709
711
714
715
735
734
738
737
738
744
765
769
776
809
819
812
814
821
794
793
796
794
815
827
831
834
840
850
846
849
842
847
846
849
850
857
885
887
888
887
883
894
895
913
917
913
915
917
918
920
929
959
961
958
954
956
962
966
959
966
967
969
972
978
993
998
1006
1007
1010
1011
1015
1037
1047
1051
1029
1050
1052
1054
1033
1040
1036
1021
1031
1033
1058
1070
1066
1064
1052
1051
1057
1058
1059
1060
1071
1080
1081
1083
1086
1075
1083
1092
1095
1101
1113
1078
1080
1075
1077
1080
1083
1090
1092
1091
1092
1093
1097
1099
1103
1104
1105
1109
1084
1101
1103
1109
1101
1099
1096
1099
1103
1104
1105
1119
1123
1095
1096
1095
1132
1149
1164
1165
1182
1180
1198
1207
1210
1213
1218
1239
1235
1236
1242
1243
1276
1279
1282
1283
1299
1301
1294
1298
1304
1301
1303
1313
1312
1316
1317
1319
1320
1315
1318
1326
1330
1332
1331
1334
1319
1316
1308
1306
1309
1312
1310
1329
1318
1321
1335
1310
1311
1313
1329
1331
1335
1341
1355
1356
1357
1360
1378
1373
1374
1373
1377
1378
1383
1379
1380
1376
1370
1369
1380
1381
1382
1381
1383
1377
1401
1403
1408
1417
1406
1407
1409
1411
1414
1420
1419
1426
1456
1452
1453
1454
1453
1450
1442
1430
1434
1435
1439
1440
1441
1442
1463
1464
1471
1469
1471
1472
1433
1436
1434
1440
1446
1447
1452
1454
1441
1434
1420
1404
1396
1412
1423
1424
1437
1450
1452
1457
1458
1422
1423
1433
1436
1453
1484
1485
1460
1457
1458
1464
1465
1467
1468
1475
1476
1471
1470
1471
1473
1470
1473
1474
1490
1482
1484
1508
1515
1522
1521
1514
1518
1520
1522
1530
1528
1523
1535
1537
1539
1541
1533
1528
1531
1538
1539
1541
1547
1551
1550
1545
1546
1548
1551
1566
1577
1586
1587
1588
1613
1615
1631
1638
1639
1640
1645
1648
1642
1640
1643
1673
1679
1669
1673
1666
1669
1674
1682
1683
1700
1698
1709
1717
1729
1743
1745
1746
1744
1714
1722
1727
1734
1735
1745
1752
1751
1772
1788
1794
1798
1804
1798
1793
1796
1806
1809
1815
1816
1815
1813
1812
1817
1818
1821
1825
1821
1853
1827
1822
1825
1834
1833
1830
1836
1837
1838
1840
1841
1846
1841
1842
1845
1862
1863
1896
1898
1884
1885
1893
1892
1895
1896
1894
1903
1902
1907
1915
1919
1922
1923
1921
1924
1925
1927
1931
1932
1939
1940
1939
1959
1965
1975
1973
1974
1982
1983
1988
1992
1995
1994
1995
1994
2000
2001
2029
2030
2005
2006
2009
2013
2017
2014
2041
2042
2052
2047
2048
2052
2051
2053
2052
2069
2058
2059
2060
2061
2063
2062
2065
2066
2070
2072
2075
2061
2038
2037
2024
2022
2023
2011
2032
2037
2026
2027
2028
2034
2038
2039
2029
2042
2031
2033
2046
2048
2041
2049
2050
2052
2063
2064
2065
2067
2086
2070
2078
2087
2086
2089
2075
2076
2101
2103
2115
2095
2109
2112
2115
2126
2152
2129
2132
2117
2116
2119
2128
2127
2139
2140
2141
2145
2146
2125
2136
2132
2121
2125
2126
2134
2135
2142
2148
2149
2133
2137
2156
2160
2161
2162
2164
2176
2177
2179
2183
2184
2186
2187
2190
2195
2216
2210
2209
2206
2214
2211
2216
2223
2224
2225
2230
2242
2246
2248
2268
2272
2273
2278
2279
2280
2281
2275
2276
2282
2283
2278
2285
2288
2289
2286
2290
2285
2291
2294
2287
2293
2315
2314
2315
2325
2323
2328
2308
2312
2322
2361
2364
2366
2364
2369
2368
2384
2387
2390
2396
2370
2371
2377
2378
2377
2379
2395
2384
2381
2395
2401
2412
2411
2412
2414
2420
2422
2408
2425
2427
2428
2438
2442
2445
2456
2462
2461
2469
2467
2472
2471
2469
2449
2448
2442
2459
2460
2474
2477
2478
2480
2483
2468
2444
2442
2444
2460
2456
2445
2437
2430
2432
2457
2463
2467
2474
2477
2475
2478
2477
2478
2480
2485
2471
2495
2509
2514
2522
2523
2533
2515
2518
2539
2535
2543
2580
2586
2601
2602
2600
2602
2598
2597
2598
2605
2597
2596
2600
2602
2599
2605
2613
2614
2611
2603
2602
2601
2607
2608
2606
2598
2599
2602
2597
2605
2611
2612
2613
2645
2657
2662
2668
2669
2652
2655
2661
2663
2662
2664
2677
2695
2702
2738
2739
2738
2740
2728
2720
2714
2720
2712
2724
2725
2736
2745
2742
2747
2749
2744
2746
2750
2753
2759
2760
2761
2731
2733
2735
2736
2737
2741
2739
2740
2744
2745
2755
2744
2746
2748
2752
2750
2755
2736
2740
2742
2753
2752
2755
2780
2781
2783
2786
2788
2786
2796
2790
2789
2798
2816
2817
2815
2817
2819
2820
2825
2823
2827
2853
2856
2861
2862
2854
2873
2887
2884
2888
2884
2885
2893
2902
2901
2902
2904
2908
2909
2911
2914
2929
2931
2935
2934
2935
2934
2917
2918
2921
2926
2932
2937
2947
2928
2946
2971
2973
2972
2969
2972
2973
2978
2977
2968
2961
2962
2982
2987
2989
2990
2993
2995
2987
2991
2992
3002
3003
3004
3005
3011
3012
3031
3029
3036
3041
3069
3070
3087
3077
3090
3087
3066
3078
3080
3081
3071
3074
3075
3074
3069
3070
3078
3086
3080
3086
3088
3096
3098
3103
3117
3114
3143
3148
3149
3150
3149
3151
3165
3169
3172
3183
3184
3185
3190
3204
3218
3230
3231
3248
3249
3252
3249
3246
3268
3273
3274
3277
3289
3257
3269
3279
3267
3284
3312
3315
3314
3317
3310
3315
3314
3304
3305
3308
3322
3326
3331
3336
3339
3345
3348
3349
3348
3350
3348
3350
3362
3363
3373
3368
3349
3347
3344
3362
3364
3365
3374
3380
3390
3387
3389
3391
3392
3390
3388
3389
3395
3415
3416
3414
3415
3416
3417
3420
3418
3422
3421
3428
3421
3422
3424
3421
3422
3419
3416
3392
3396
3408
3399
3400
3403
3392
3398
3393
3415
3436
3458
3459
3467
3469
3472
3480
3489
3491
3490
3521
3518
3517
3518
3502
3510
3505
3506
3508
3509
3510
3506
3504
3505
3522
3525
3531
3524
3522
3517
3523
3526
3512
3516
3521
3535
3544
3539
3514
3519
3525
3523
3530
3529
3534
3526
3523
3525
3522
3509
3510
3523
3522
3516
3518
3522
3539
3540
3546
3551
3556
3566
3545
3573
3574
3576
3581
3582
3602
3604
3606
3590
3596
3598
3599
3607
3573
3592
3599
3607
3609
3617
3621
3606
3602
3599
3609
3602
3598
3607
3612
3613
3630
3632
3634
3636
3642
3651
3655
3662
3687
3688
3689
3684
3664
3663
3667
3645
3647
3649
3660
3673
3665
3663
3633
3656
3658
3669
3672
3673
3675
3683
3684
3685
3683
3687
3699
3703
3707
3717
3749
3763
3767
3771
3774
3790
3801
3808
3813
3814
3819
3835
3834
3835
3836
3837
3836
3837
3839
3844
3845
3831
3830
3828
3829
3830
3846
3844
3825
3811
3806
3809
3807
3826
3836
3847
3848
3849
3850
3863
3869
3868
3869
3870
3871
3867
3868
3872
3871
3874
3875
3874
3876
3879
3884
3901
3904
3901
3915
3905
3904
3889
3914
3917
3931
3932
3930
3932
3937
3943
3939
3941
3943
3930
3929
3945
3954
3972
3996
3997
4000
4001
3995
4025
4027
4034
4035
4050
4074
4071
4077
4078
4085
4087
4088
4091
4090
4091
4092
4089
4091
4096
4094
4095
4107
4109
4130
4131
4124
4136
4139
4153
4161
4173
4149
4154
4148
4150
4128
4160
4164
4168
4169
4158
4165
4174
4171
4195
4200
4201
4195
4198
4201
4202
4196
4203
4211
4209
4210
4217
4220
4203
4193
4194
4197
4193
4195
4196
4195
4197
4218
4222
4236
4223
4225
4242
4262
4265
4256
4260
4270
4271
4276
4272
4275
4297
4304
4297
4299
4302
4303
4301
4306
4337
4341
4342
4343
4345
4346
4351
4350
4338
4331
4337
4331
4345
4309
4311
4327
4328
4335
4360
4362
4364
4360
4357
4359
4367
4368
4352
4351
4347
4360
4356
4357
4362
4363
4357
4362
4367
4385
4388
4392
4395
4397
4398
4387
4395
4399
4402
4403
4424
4434
4443
4444
4445
4456
4457
4466
4470
4469
4470
4471
4505
4499
4500
4476
4483
4475
4476
4486
4496
4495
4504
4503
4516
4518
4517
4525
4527
4530
4532
4533
4535
4537
4541
4544
4546
4549
4551
4552
4555
4556
4563
4580
4583
4600
4589
4581
4585
4583
4585
4592
4585
4595
4605
4598
4601
4600
4603
4598
4628
4630
4626
4630
4632
4631
4632
4619
4633
4643
4630
4640
4660
4671
4675
4682
4697
4695
4700
4704
4705
4710
4721
4727
4732
4728
4729
4735
4743
4744
4754
4760
4766
4758
4762
4760
4763
4782
4786
4787
4789
4801
4804
4782
4752
4755
4757
4758
4757
4766
4778
4779
4769
4781
4777
4785
4786
4788
4796
4795
4796
4797
4805
4804
4814
4812
4815
4806
4805
4807
4805
4806
4807
4810
4845
4846
4855
4853
4859
4862
4867
4873
4879
4881
4880
4883
4880
4886
4892
4898
4903
4902
4905
4909
4914
4915
4917
4939
4941
4933
4932
4940
4945
4961
4966
4955
4960
4979
4980
4981
4970
4968
4970
4989
4996
5003
4983
4984
5006
5014
5018
5023
5042
5043
5050
5051
5076
5052
5055
5068
5059
5058
5035
5059
5060
5061
5068
5044
5043
5044
5045
5047
5048
5051
5044
5045
5049
5072
5080
5078
5101
5100
5092
5112
5111
5107
5113
5116
5123
5129
5127
5151
5176
5188
5189
5202
5204
5197
5199
5196
5201
5200
5203
5207
5209
5217
5218
5204
5206
5207
5208
5195
5201
5202
5199
5229
5228
5229
5233
5232
5227
5228
5229
5238
5236
5238
5243
5245
5244
5245
5230
5244
5258
5259
5268
5271
5274
5271
5272
5277
5300
5327
5358
5359
5360
5361
5364
5370
5375
5376
5384
5383
5384
5385
5389
5390
5395
5397
5413
5418
5434
5433
5449
5445
5447
5453
5454
5458
5460
5448
5452
5464
5469
5480
5481
5482
5486
5496
5499
5500
5527
5501
5476
5474
5475
5463
5462
5458
5459
5470
5473
5481
5493
5494
5495
5496
5497
5498
5495
5498
5496
5490
5491
5493
5495
5489
5514
5533
5541
5531
5537
5513
5531
5532
5533
5532
5526
5535
5553
5551
5554
5553
5555
5551
5557
5556
5558
5555
5554
5552
5566
5574
5577
5583
5584
5588
5590
5603
5610
5617
5619
5618
5619
5618
5630
5635
5638
5650
5659
5660
5672
5670
5676
5673
5675
5680
5682
5685
5688
5682
5683
5696
5700
5722
5714
5713
5710
5712
5740
5741
5739
5740
5746
5756
5769
5770
5757
5748
5766
5770"""
input1="""199
200
208
210
200
207
240
269
260
263"""
entries = list(map(int, input1.split('\n')))
entries = list(map(int, input2.split('\n')))
count = 0
for i in range(len(entries)):
if i > 0:
count = count + 1 if entries[i] > entries[i-1] else count
print('a', count)
# Part 2
entries = list(map(int, input1.split('\n')))
entries = list(map(int, input2.split('\n')))
count = 0
for i in range(len(entries)):
if i > 0 and i + 1 < len(entries) and i + 2 < len(entries):
count = count + 1 if (entries[i] + entries[i+1] + entries[i+2]) > (entries[i-1] + entries[i] + entries[i+1]) else count
print('b', count)
|
input2 = '131\n140\n136\n135\n155\n175\n178\n186\n187\n189\n194\n195\n203\n193\n178\n179\n180\n188\n204\n214\n215\n252\n253\n261\n281\n294\n293\n299\n300\n301\n307\n333\n324\n322\n323\n335\n319\n312\n313\n312\n320\n323\n324\n336\n341\n347\n357\n358\n363\n357\n334\n348\n364\n365\n367\n370\n369\n373\n344\n328\n330\n327\n339\n340\n341\n335\n342\n347\n349\n355\n348\n359\n360\n341\n342\n322\n321\n324\n323\n322\n324\n327\n340\n341\n353\n383\n387\n391\n422\n424\n422\n426\n429\n427\n428\n445\n421\n423\n429\n414\n411\n407\n409\n402\n422\n425\n423\n427\n424\n430\n428\n432\n433\n434\n429\n430\n406\n407\n411\n420\n412\n419\n422\n424\n425\n426\n428\n430\n432\n431\n432\n433\n449\n450\n453\n457\n459\n462\n482\n470\n471\n488\n495\n496\n499\n503\n516\n526\n531\n532\n541\n555\n554\n567\n558\n557\n560\n561\n566\n580\n581\n582\n594\n595\n598\n599\n582\n589\n593\n589\n592\n593\n590\n606\n615\n623\n627\n628\n630\n636\n641\n657\n658\n693\n695\n698\n707\n713\n714\n720\n721\n723\n721\n720\n707\n679\n699\n676\n667\n663\n664\n666\n660\n663\n673\n677\n662\n660\n663\n683\n681\n674\n689\n698\n699\n704\n705\n696\n697\n702\n693\n694\n700\n699\n681\n684\n690\n669\n673\n688\n691\n692\n691\n688\n685\n656\n638\n634\n651\n665\n670\n672\n685\n689\n709\n711\n714\n715\n735\n734\n738\n737\n738\n744\n765\n769\n776\n809\n819\n812\n814\n821\n794\n793\n796\n794\n815\n827\n831\n834\n840\n850\n846\n849\n842\n847\n846\n849\n850\n857\n885\n887\n888\n887\n883\n894\n895\n913\n917\n913\n915\n917\n918\n920\n929\n959\n961\n958\n954\n956\n962\n966\n959\n966\n967\n969\n972\n978\n993\n998\n1006\n1007\n1010\n1011\n1015\n1037\n1047\n1051\n1029\n1050\n1052\n1054\n1033\n1040\n1036\n1021\n1031\n1033\n1058\n1070\n1066\n1064\n1052\n1051\n1057\n1058\n1059\n1060\n1071\n1080\n1081\n1083\n1086\n1075\n1083\n1092\n1095\n1101\n1113\n1078\n1080\n1075\n1077\n1080\n1083\n1090\n1092\n1091\n1092\n1093\n1097\n1099\n1103\n1104\n1105\n1109\n1084\n1101\n1103\n1109\n1101\n1099\n1096\n1099\n1103\n1104\n1105\n1119\n1123\n1095\n1096\n1095\n1132\n1149\n1164\n1165\n1182\n1180\n1198\n1207\n1210\n1213\n1218\n1239\n1235\n1236\n1242\n1243\n1276\n1279\n1282\n1283\n1299\n1301\n1294\n1298\n1304\n1301\n1303\n1313\n1312\n1316\n1317\n1319\n1320\n1315\n1318\n1326\n1330\n1332\n1331\n1334\n1319\n1316\n1308\n1306\n1309\n1312\n1310\n1329\n1318\n1321\n1335\n1310\n1311\n1313\n1329\n1331\n1335\n1341\n1355\n1356\n1357\n1360\n1378\n1373\n1374\n1373\n1377\n1378\n1383\n1379\n1380\n1376\n1370\n1369\n1380\n1381\n1382\n1381\n1383\n1377\n1401\n1403\n1408\n1417\n1406\n1407\n1409\n1411\n1414\n1420\n1419\n1426\n1456\n1452\n1453\n1454\n1453\n1450\n1442\n1430\n1434\n1435\n1439\n1440\n1441\n1442\n1463\n1464\n1471\n1469\n1471\n1472\n1433\n1436\n1434\n1440\n1446\n1447\n1452\n1454\n1441\n1434\n1420\n1404\n1396\n1412\n1423\n1424\n1437\n1450\n1452\n1457\n1458\n1422\n1423\n1433\n1436\n1453\n1484\n1485\n1460\n1457\n1458\n1464\n1465\n1467\n1468\n1475\n1476\n1471\n1470\n1471\n1473\n1470\n1473\n1474\n1490\n1482\n1484\n1508\n1515\n1522\n1521\n1514\n1518\n1520\n1522\n1530\n1528\n1523\n1535\n1537\n1539\n1541\n1533\n1528\n1531\n1538\n1539\n1541\n1547\n1551\n1550\n1545\n1546\n1548\n1551\n1566\n1577\n1586\n1587\n1588\n1613\n1615\n1631\n1638\n1639\n1640\n1645\n1648\n1642\n1640\n1643\n1673\n1679\n1669\n1673\n1666\n1669\n1674\n1682\n1683\n1700\n1698\n1709\n1717\n1729\n1743\n1745\n1746\n1744\n1714\n1722\n1727\n1734\n1735\n1745\n1752\n1751\n1772\n1788\n1794\n1798\n1804\n1798\n1793\n1796\n1806\n1809\n1815\n1816\n1815\n1813\n1812\n1817\n1818\n1821\n1825\n1821\n1853\n1827\n1822\n1825\n1834\n1833\n1830\n1836\n1837\n1838\n1840\n1841\n1846\n1841\n1842\n1845\n1862\n1863\n1896\n1898\n1884\n1885\n1893\n1892\n1895\n1896\n1894\n1903\n1902\n1907\n1915\n1919\n1922\n1923\n1921\n1924\n1925\n1927\n1931\n1932\n1939\n1940\n1939\n1959\n1965\n1975\n1973\n1974\n1982\n1983\n1988\n1992\n1995\n1994\n1995\n1994\n2000\n2001\n2029\n2030\n2005\n2006\n2009\n2013\n2017\n2014\n2041\n2042\n2052\n2047\n2048\n2052\n2051\n2053\n2052\n2069\n2058\n2059\n2060\n2061\n2063\n2062\n2065\n2066\n2070\n2072\n2075\n2061\n2038\n2037\n2024\n2022\n2023\n2011\n2032\n2037\n2026\n2027\n2028\n2034\n2038\n2039\n2029\n2042\n2031\n2033\n2046\n2048\n2041\n2049\n2050\n2052\n2063\n2064\n2065\n2067\n2086\n2070\n2078\n2087\n2086\n2089\n2075\n2076\n2101\n2103\n2115\n2095\n2109\n2112\n2115\n2126\n2152\n2129\n2132\n2117\n2116\n2119\n2128\n2127\n2139\n2140\n2141\n2145\n2146\n2125\n2136\n2132\n2121\n2125\n2126\n2134\n2135\n2142\n2148\n2149\n2133\n2137\n2156\n2160\n2161\n2162\n2164\n2176\n2177\n2179\n2183\n2184\n2186\n2187\n2190\n2195\n2216\n2210\n2209\n2206\n2214\n2211\n2216\n2223\n2224\n2225\n2230\n2242\n2246\n2248\n2268\n2272\n2273\n2278\n2279\n2280\n2281\n2275\n2276\n2282\n2283\n2278\n2285\n2288\n2289\n2286\n2290\n2285\n2291\n2294\n2287\n2293\n2315\n2314\n2315\n2325\n2323\n2328\n2308\n2312\n2322\n2361\n2364\n2366\n2364\n2369\n2368\n2384\n2387\n2390\n2396\n2370\n2371\n2377\n2378\n2377\n2379\n2395\n2384\n2381\n2395\n2401\n2412\n2411\n2412\n2414\n2420\n2422\n2408\n2425\n2427\n2428\n2438\n2442\n2445\n2456\n2462\n2461\n2469\n2467\n2472\n2471\n2469\n2449\n2448\n2442\n2459\n2460\n2474\n2477\n2478\n2480\n2483\n2468\n2444\n2442\n2444\n2460\n2456\n2445\n2437\n2430\n2432\n2457\n2463\n2467\n2474\n2477\n2475\n2478\n2477\n2478\n2480\n2485\n2471\n2495\n2509\n2514\n2522\n2523\n2533\n2515\n2518\n2539\n2535\n2543\n2580\n2586\n2601\n2602\n2600\n2602\n2598\n2597\n2598\n2605\n2597\n2596\n2600\n2602\n2599\n2605\n2613\n2614\n2611\n2603\n2602\n2601\n2607\n2608\n2606\n2598\n2599\n2602\n2597\n2605\n2611\n2612\n2613\n2645\n2657\n2662\n2668\n2669\n2652\n2655\n2661\n2663\n2662\n2664\n2677\n2695\n2702\n2738\n2739\n2738\n2740\n2728\n2720\n2714\n2720\n2712\n2724\n2725\n2736\n2745\n2742\n2747\n2749\n2744\n2746\n2750\n2753\n2759\n2760\n2761\n2731\n2733\n2735\n2736\n2737\n2741\n2739\n2740\n2744\n2745\n2755\n2744\n2746\n2748\n2752\n2750\n2755\n2736\n2740\n2742\n2753\n2752\n2755\n2780\n2781\n2783\n2786\n2788\n2786\n2796\n2790\n2789\n2798\n2816\n2817\n2815\n2817\n2819\n2820\n2825\n2823\n2827\n2853\n2856\n2861\n2862\n2854\n2873\n2887\n2884\n2888\n2884\n2885\n2893\n2902\n2901\n2902\n2904\n2908\n2909\n2911\n2914\n2929\n2931\n2935\n2934\n2935\n2934\n2917\n2918\n2921\n2926\n2932\n2937\n2947\n2928\n2946\n2971\n2973\n2972\n2969\n2972\n2973\n2978\n2977\n2968\n2961\n2962\n2982\n2987\n2989\n2990\n2993\n2995\n2987\n2991\n2992\n3002\n3003\n3004\n3005\n3011\n3012\n3031\n3029\n3036\n3041\n3069\n3070\n3087\n3077\n3090\n3087\n3066\n3078\n3080\n3081\n3071\n3074\n3075\n3074\n3069\n3070\n3078\n3086\n3080\n3086\n3088\n3096\n3098\n3103\n3117\n3114\n3143\n3148\n3149\n3150\n3149\n3151\n3165\n3169\n3172\n3183\n3184\n3185\n3190\n3204\n3218\n3230\n3231\n3248\n3249\n3252\n3249\n3246\n3268\n3273\n3274\n3277\n3289\n3257\n3269\n3279\n3267\n3284\n3312\n3315\n3314\n3317\n3310\n3315\n3314\n3304\n3305\n3308\n3322\n3326\n3331\n3336\n3339\n3345\n3348\n3349\n3348\n3350\n3348\n3350\n3362\n3363\n3373\n3368\n3349\n3347\n3344\n3362\n3364\n3365\n3374\n3380\n3390\n3387\n3389\n3391\n3392\n3390\n3388\n3389\n3395\n3415\n3416\n3414\n3415\n3416\n3417\n3420\n3418\n3422\n3421\n3428\n3421\n3422\n3424\n3421\n3422\n3419\n3416\n3392\n3396\n3408\n3399\n3400\n3403\n3392\n3398\n3393\n3415\n3436\n3458\n3459\n3467\n3469\n3472\n3480\n3489\n3491\n3490\n3521\n3518\n3517\n3518\n3502\n3510\n3505\n3506\n3508\n3509\n3510\n3506\n3504\n3505\n3522\n3525\n3531\n3524\n3522\n3517\n3523\n3526\n3512\n3516\n3521\n3535\n3544\n3539\n3514\n3519\n3525\n3523\n3530\n3529\n3534\n3526\n3523\n3525\n3522\n3509\n3510\n3523\n3522\n3516\n3518\n3522\n3539\n3540\n3546\n3551\n3556\n3566\n3545\n3573\n3574\n3576\n3581\n3582\n3602\n3604\n3606\n3590\n3596\n3598\n3599\n3607\n3573\n3592\n3599\n3607\n3609\n3617\n3621\n3606\n3602\n3599\n3609\n3602\n3598\n3607\n3612\n3613\n3630\n3632\n3634\n3636\n3642\n3651\n3655\n3662\n3687\n3688\n3689\n3684\n3664\n3663\n3667\n3645\n3647\n3649\n3660\n3673\n3665\n3663\n3633\n3656\n3658\n3669\n3672\n3673\n3675\n3683\n3684\n3685\n3683\n3687\n3699\n3703\n3707\n3717\n3749\n3763\n3767\n3771\n3774\n3790\n3801\n3808\n3813\n3814\n3819\n3835\n3834\n3835\n3836\n3837\n3836\n3837\n3839\n3844\n3845\n3831\n3830\n3828\n3829\n3830\n3846\n3844\n3825\n3811\n3806\n3809\n3807\n3826\n3836\n3847\n3848\n3849\n3850\n3863\n3869\n3868\n3869\n3870\n3871\n3867\n3868\n3872\n3871\n3874\n3875\n3874\n3876\n3879\n3884\n3901\n3904\n3901\n3915\n3905\n3904\n3889\n3914\n3917\n3931\n3932\n3930\n3932\n3937\n3943\n3939\n3941\n3943\n3930\n3929\n3945\n3954\n3972\n3996\n3997\n4000\n4001\n3995\n4025\n4027\n4034\n4035\n4050\n4074\n4071\n4077\n4078\n4085\n4087\n4088\n4091\n4090\n4091\n4092\n4089\n4091\n4096\n4094\n4095\n4107\n4109\n4130\n4131\n4124\n4136\n4139\n4153\n4161\n4173\n4149\n4154\n4148\n4150\n4128\n4160\n4164\n4168\n4169\n4158\n4165\n4174\n4171\n4195\n4200\n4201\n4195\n4198\n4201\n4202\n4196\n4203\n4211\n4209\n4210\n4217\n4220\n4203\n4193\n4194\n4197\n4193\n4195\n4196\n4195\n4197\n4218\n4222\n4236\n4223\n4225\n4242\n4262\n4265\n4256\n4260\n4270\n4271\n4276\n4272\n4275\n4297\n4304\n4297\n4299\n4302\n4303\n4301\n4306\n4337\n4341\n4342\n4343\n4345\n4346\n4351\n4350\n4338\n4331\n4337\n4331\n4345\n4309\n4311\n4327\n4328\n4335\n4360\n4362\n4364\n4360\n4357\n4359\n4367\n4368\n4352\n4351\n4347\n4360\n4356\n4357\n4362\n4363\n4357\n4362\n4367\n4385\n4388\n4392\n4395\n4397\n4398\n4387\n4395\n4399\n4402\n4403\n4424\n4434\n4443\n4444\n4445\n4456\n4457\n4466\n4470\n4469\n4470\n4471\n4505\n4499\n4500\n4476\n4483\n4475\n4476\n4486\n4496\n4495\n4504\n4503\n4516\n4518\n4517\n4525\n4527\n4530\n4532\n4533\n4535\n4537\n4541\n4544\n4546\n4549\n4551\n4552\n4555\n4556\n4563\n4580\n4583\n4600\n4589\n4581\n4585\n4583\n4585\n4592\n4585\n4595\n4605\n4598\n4601\n4600\n4603\n4598\n4628\n4630\n4626\n4630\n4632\n4631\n4632\n4619\n4633\n4643\n4630\n4640\n4660\n4671\n4675\n4682\n4697\n4695\n4700\n4704\n4705\n4710\n4721\n4727\n4732\n4728\n4729\n4735\n4743\n4744\n4754\n4760\n4766\n4758\n4762\n4760\n4763\n4782\n4786\n4787\n4789\n4801\n4804\n4782\n4752\n4755\n4757\n4758\n4757\n4766\n4778\n4779\n4769\n4781\n4777\n4785\n4786\n4788\n4796\n4795\n4796\n4797\n4805\n4804\n4814\n4812\n4815\n4806\n4805\n4807\n4805\n4806\n4807\n4810\n4845\n4846\n4855\n4853\n4859\n4862\n4867\n4873\n4879\n4881\n4880\n4883\n4880\n4886\n4892\n4898\n4903\n4902\n4905\n4909\n4914\n4915\n4917\n4939\n4941\n4933\n4932\n4940\n4945\n4961\n4966\n4955\n4960\n4979\n4980\n4981\n4970\n4968\n4970\n4989\n4996\n5003\n4983\n4984\n5006\n5014\n5018\n5023\n5042\n5043\n5050\n5051\n5076\n5052\n5055\n5068\n5059\n5058\n5035\n5059\n5060\n5061\n5068\n5044\n5043\n5044\n5045\n5047\n5048\n5051\n5044\n5045\n5049\n5072\n5080\n5078\n5101\n5100\n5092\n5112\n5111\n5107\n5113\n5116\n5123\n5129\n5127\n5151\n5176\n5188\n5189\n5202\n5204\n5197\n5199\n5196\n5201\n5200\n5203\n5207\n5209\n5217\n5218\n5204\n5206\n5207\n5208\n5195\n5201\n5202\n5199\n5229\n5228\n5229\n5233\n5232\n5227\n5228\n5229\n5238\n5236\n5238\n5243\n5245\n5244\n5245\n5230\n5244\n5258\n5259\n5268\n5271\n5274\n5271\n5272\n5277\n5300\n5327\n5358\n5359\n5360\n5361\n5364\n5370\n5375\n5376\n5384\n5383\n5384\n5385\n5389\n5390\n5395\n5397\n5413\n5418\n5434\n5433\n5449\n5445\n5447\n5453\n5454\n5458\n5460\n5448\n5452\n5464\n5469\n5480\n5481\n5482\n5486\n5496\n5499\n5500\n5527\n5501\n5476\n5474\n5475\n5463\n5462\n5458\n5459\n5470\n5473\n5481\n5493\n5494\n5495\n5496\n5497\n5498\n5495\n5498\n5496\n5490\n5491\n5493\n5495\n5489\n5514\n5533\n5541\n5531\n5537\n5513\n5531\n5532\n5533\n5532\n5526\n5535\n5553\n5551\n5554\n5553\n5555\n5551\n5557\n5556\n5558\n5555\n5554\n5552\n5566\n5574\n5577\n5583\n5584\n5588\n5590\n5603\n5610\n5617\n5619\n5618\n5619\n5618\n5630\n5635\n5638\n5650\n5659\n5660\n5672\n5670\n5676\n5673\n5675\n5680\n5682\n5685\n5688\n5682\n5683\n5696\n5700\n5722\n5714\n5713\n5710\n5712\n5740\n5741\n5739\n5740\n5746\n5756\n5769\n5770\n5757\n5748\n5766\n5770'
input1 = '199\n200\n208\n210\n200\n207\n240\n269\n260\n263'
entries = list(map(int, input1.split('\n')))
entries = list(map(int, input2.split('\n')))
count = 0
for i in range(len(entries)):
if i > 0:
count = count + 1 if entries[i] > entries[i - 1] else count
print('a', count)
entries = list(map(int, input1.split('\n')))
entries = list(map(int, input2.split('\n')))
count = 0
for i in range(len(entries)):
if i > 0 and i + 1 < len(entries) and (i + 2 < len(entries)):
count = count + 1 if entries[i] + entries[i + 1] + entries[i + 2] > entries[i - 1] + entries[i] + entries[i + 1] else count
print('b', count)
|
# Copyright 2019 The Bazel Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Bash runfiles library init code for test_rules.bzl."""
# Init code to load the runfiles.bash file.
# The runfiles library itself defines rlocation which you would need to look
# up the library's runtime location, thus we have a chicken-and-egg problem.
INIT_BASH_RUNFILES = [
"# --- begin runfiles.bash initialization ---",
"# Copy-pasted from Bazel Bash runfiles library (tools/bash/runfiles/runfiles.bash).",
"set -euo pipefail",
'if [[ ! -d "${RUNFILES_DIR:-/dev/null}" && ! -f "${RUNFILES_MANIFEST_FILE:-/dev/null}" ]]; then',
' if [[ -f "$0.runfiles_manifest" ]]; then',
' export RUNFILES_MANIFEST_FILE="$0.runfiles_manifest"',
' elif [[ -f "$0.runfiles/MANIFEST" ]]; then',
' export RUNFILES_MANIFEST_FILE="$0.runfiles/MANIFEST"',
' elif [[ -f "$0.runfiles/bazel_tools/tools/bash/runfiles/runfiles.bash" ]]; then',
' export RUNFILES_DIR="$0.runfiles"',
" fi",
"fi",
'if [[ -f "${RUNFILES_DIR:-/dev/null}/bazel_tools/tools/bash/runfiles/runfiles.bash" ]]; then',
' source "${RUNFILES_DIR}/bazel_tools/tools/bash/runfiles/runfiles.bash"',
'elif [[ -f "${RUNFILES_MANIFEST_FILE:-/dev/null}" ]]; then',
' source "$(grep -m1 "^bazel_tools/tools/bash/runfiles/runfiles.bash " \\',
' "$RUNFILES_MANIFEST_FILE" | cut -d " " -f 2-)"',
"else",
' echo >&2 "ERROR: cannot find @bazel_tools//tools/bash/runfiles:runfiles.bash"',
" exit 1",
"fi",
"# --- end runfiles.bash initialization ---",
]
# Label of the runfiles library.
BASH_RUNFILES_DEP = "@bazel_tools//tools/bash/runfiles"
|
"""Bash runfiles library init code for test_rules.bzl."""
init_bash_runfiles = ['# --- begin runfiles.bash initialization ---', '# Copy-pasted from Bazel Bash runfiles library (tools/bash/runfiles/runfiles.bash).', 'set -euo pipefail', 'if [[ ! -d "${RUNFILES_DIR:-/dev/null}" && ! -f "${RUNFILES_MANIFEST_FILE:-/dev/null}" ]]; then', ' if [[ -f "$0.runfiles_manifest" ]]; then', ' export RUNFILES_MANIFEST_FILE="$0.runfiles_manifest"', ' elif [[ -f "$0.runfiles/MANIFEST" ]]; then', ' export RUNFILES_MANIFEST_FILE="$0.runfiles/MANIFEST"', ' elif [[ -f "$0.runfiles/bazel_tools/tools/bash/runfiles/runfiles.bash" ]]; then', ' export RUNFILES_DIR="$0.runfiles"', ' fi', 'fi', 'if [[ -f "${RUNFILES_DIR:-/dev/null}/bazel_tools/tools/bash/runfiles/runfiles.bash" ]]; then', ' source "${RUNFILES_DIR}/bazel_tools/tools/bash/runfiles/runfiles.bash"', 'elif [[ -f "${RUNFILES_MANIFEST_FILE:-/dev/null}" ]]; then', ' source "$(grep -m1 "^bazel_tools/tools/bash/runfiles/runfiles.bash " \\', ' "$RUNFILES_MANIFEST_FILE" | cut -d " " -f 2-)"', 'else', ' echo >&2 "ERROR: cannot find @bazel_tools//tools/bash/runfiles:runfiles.bash"', ' exit 1', 'fi', '# --- end runfiles.bash initialization ---']
bash_runfiles_dep = '@bazel_tools//tools/bash/runfiles'
|
class TierFulfillmentMessages(object):
RROR_PROCESSING_TIER_REQUEST = 'There has been an error processing the tier config request. Error description: {}'
class BasePurchaseMessages:
pass
class BaseChangeMessages:
pass
class BaseSuspendMessages:
NOTHING_TO_DO = 'Suspend method for request {} - Nothing to do'
class BaseCancelMessages:
ACTIVATION_TILE_RESPONSE = 'Operation cancel done successfully'
class BaseSharedMessages:
ACTIVATING_TEMPLATE_ERROR = 'There has been a problem activating the template. Description {}'
EMPTY_ACTIVATION_TILE = 'Activation tile response for marketplace {} cannot be empty'
ERROR_GETTING_CONFIGURATION = 'There was an exception while getting configured info for the specified ' \
'marketplace {}'
NOT_FOUND_TEMPLATE = 'It was not found any template of type <{}> for the marketplace with id <{}>. ' \
'Please review the configuration.'
NOT_ALLOWED_DOWNSIZE = 'At least one of the requested items at the order is downsized which ' \
' is not allowed. Please review your order.'
RESPONSE_ERROR = 'Error: {} -> {}'
RESPONSE_DOES_NOT_HAVE_ATTRIBUTE = 'Response does not have attribute {}. Check your request params. ' \
'Response status - {}'
WAITING_SUBSCRIPTION_ACTIVATION = 'The subscription has been updated, waiting Vendor/ISV to update the ' \
'subscription status'
class Message:
class Shared(BaseSharedMessages):
tier_request = TierFulfillmentMessages()
class Purchase(BasePurchaseMessages):
FAIL_REPEATED_PRODUCTS = 'It has been detected repeated products for the same purchase. ' \
'Please review the configured plan.'
class Change(BaseChangeMessages):
pass
class Suspend(BaseSuspendMessages):
pass
class Cancel(BaseCancelMessages):
pass
|
class Tierfulfillmentmessages(object):
rror_processing_tier_request = 'There has been an error processing the tier config request. Error description: {}'
class Basepurchasemessages:
pass
class Basechangemessages:
pass
class Basesuspendmessages:
nothing_to_do = 'Suspend method for request {} - Nothing to do'
class Basecancelmessages:
activation_tile_response = 'Operation cancel done successfully'
class Basesharedmessages:
activating_template_error = 'There has been a problem activating the template. Description {}'
empty_activation_tile = 'Activation tile response for marketplace {} cannot be empty'
error_getting_configuration = 'There was an exception while getting configured info for the specified marketplace {}'
not_found_template = 'It was not found any template of type <{}> for the marketplace with id <{}>. Please review the configuration.'
not_allowed_downsize = 'At least one of the requested items at the order is downsized which is not allowed. Please review your order.'
response_error = 'Error: {} -> {}'
response_does_not_have_attribute = 'Response does not have attribute {}. Check your request params. Response status - {}'
waiting_subscription_activation = 'The subscription has been updated, waiting Vendor/ISV to update the subscription status'
class Message:
class Shared(BaseSharedMessages):
tier_request = tier_fulfillment_messages()
class Purchase(BasePurchaseMessages):
fail_repeated_products = 'It has been detected repeated products for the same purchase. Please review the configured plan.'
class Change(BaseChangeMessages):
pass
class Suspend(BaseSuspendMessages):
pass
class Cancel(BaseCancelMessages):
pass
|
#! /usr/bin/python
# -*- coding: iso-8859-15 -*-
n = int(input("Ingrese la cantidad de datos: "))
suma = 0
for i in range(n):
x = float(input("Ingrese el dato: "))
suma = suma + x
prom = suma / n
print("El promedio es: " ,prom)
|
n = int(input('Ingrese la cantidad de datos: '))
suma = 0
for i in range(n):
x = float(input('Ingrese el dato: '))
suma = suma + x
prom = suma / n
print('El promedio es: ', prom)
|
"""
.. module:: djstripe.management.
:synopsis: dj-stripe - management module, contains commands.
"""
|
"""
.. module:: djstripe.management.
:synopsis: dj-stripe - management module, contains commands.
"""
|
N = int(input())
AS = [int(x) for x in input().split()]
ok = []
for i in range(N):
for j in range(N):
if i == j:
continue
if AS[i] % AS[j] == 0:
break
else:
ok.append(i)
print(len(ok))
|
n = int(input())
as = [int(x) for x in input().split()]
ok = []
for i in range(N):
for j in range(N):
if i == j:
continue
if AS[i] % AS[j] == 0:
break
else:
ok.append(i)
print(len(ok))
|
class Point:
def __init__(self, x: int, y: int):
self.x = x
self.y = y
def getX(self) -> int:
return self.x
def getY(self) -> int:
return self.y
def setX(self, x: int) -> None:
self.x = x
def setY(self, y: int) -> None:
self.y = y
|
class Point:
def __init__(self, x: int, y: int):
self.x = x
self.y = y
def get_x(self) -> int:
return self.x
def get_y(self) -> int:
return self.y
def set_x(self, x: int) -> None:
self.x = x
def set_y(self, y: int) -> None:
self.y = y
|
#!/usr/bin/env python3
usb_codes = {
0x04:"aA", 0x05:"bB", 0x06:"cC", 0x07:"dD", 0x08:"eE", 0x09:"fF",
0x0A:"gG", 0x0B:"hH", 0x0C:"iI", 0x0D:"jJ", 0x0E:"kK", 0x0F:"lL",
0x10:"mM", 0x11:"nN", 0x12:"oO", 0x13:"pP", 0x14:"qQ", 0x15:"rR",
0x16:"sS", 0x17:"tT", 0x18:"uU", 0x19:"vV", 0x1A:"wW", 0x1B:"xX",
0x1C:"yY", 0x1D:"zZ", 0x1E:"1!", 0x1F:"2@", 0x20:"3#", 0x21:"4$",
0x22:"5%", 0x23:"6^", 0x24:"7&", 0x25:"8*", 0x26:"9(", 0x27:"0)",
0x2C:" ", 0x2D:"-_", 0x2E:"=+", 0x2F:"[{", 0x30:"]}", 0x32:"#~",
0x33:";:", 0x34:"'\"", 0x36:",<", 0x37:".>", 0x4f:">", 0x50:"<"
}
buff = ""
pos = 0
for x in open("strokes","r").readlines():
x = x.strip()
if not x:
continue
code = int(x[4:6],16)
if code == 0:
continue
if code == 0x28:
buff += "[ENTER]"
continue
if int(x[0:2],16) == 2 or int(x[0:2],16) == 0x20:
buff += usb_codes[code][1]
else:
buff += usb_codes[code][0]
print(buff)
|
usb_codes = {4: 'aA', 5: 'bB', 6: 'cC', 7: 'dD', 8: 'eE', 9: 'fF', 10: 'gG', 11: 'hH', 12: 'iI', 13: 'jJ', 14: 'kK', 15: 'lL', 16: 'mM', 17: 'nN', 18: 'oO', 19: 'pP', 20: 'qQ', 21: 'rR', 22: 'sS', 23: 'tT', 24: 'uU', 25: 'vV', 26: 'wW', 27: 'xX', 28: 'yY', 29: 'zZ', 30: '1!', 31: '2@', 32: '3#', 33: '4$', 34: '5%', 35: '6^', 36: '7&', 37: '8*', 38: '9(', 39: '0)', 44: ' ', 45: '-_', 46: '=+', 47: '[{', 48: ']}', 50: '#~', 51: ';:', 52: '\'"', 54: ',<', 55: '.>', 79: '>', 80: '<'}
buff = ''
pos = 0
for x in open('strokes', 'r').readlines():
x = x.strip()
if not x:
continue
code = int(x[4:6], 16)
if code == 0:
continue
if code == 40:
buff += '[ENTER]'
continue
if int(x[0:2], 16) == 2 or int(x[0:2], 16) == 32:
buff += usb_codes[code][1]
else:
buff += usb_codes[code][0]
print(buff)
|
# original problems
def easy_sum(a, b):
"""Takes two numbers and returns their sum"""
return a + b
def easy_product(a, b):
"""Takes two numbers and returns their product"""
return a * b
def easy_concat(a, b):
"""Takes two strings and returns their concatenation"""
return a + b
def easy_emptylist(l):
"""Takes a list and returns True for empty list, False for nonempty"""
return not l
def easy_iseven(x):
"""Takes a number and returns True if it's even, otherwise False"""
return x % 2 == 0
def easy_and(b1, b2):
"Takes two booleans and returns their AND"
return b1 and b2
def easy_or(b1, b2):
"""Takes two booleans and returns their OR"""
return b1 or b2
def easy_lt(a, b):
"""Takes two numbers and return whether num1 is less than num2"""
return a < b
# new sp2 2018
def easy_contains(a, b):
"""Takes in 2 non-empty strings and returns True if the first value contains a substring that matches the second value."""
return b in a
def easy_helloname(a):
"""Takes in a string representing a name and returns a new string saying hello in a very specific format, e.g., if the name is 'Dave', it should return 'Hello, Dave!'"""
return 'Hello, {}!'.format(a)
def easy_iscat(a):
"""Takes in a string and returns 'meow' if it is the exact string 'cat', otherwise 'woof'."""
return 'meow' if a == 'cat' else 'woof'
|
def easy_sum(a, b):
"""Takes two numbers and returns their sum"""
return a + b
def easy_product(a, b):
"""Takes two numbers and returns their product"""
return a * b
def easy_concat(a, b):
"""Takes two strings and returns their concatenation"""
return a + b
def easy_emptylist(l):
"""Takes a list and returns True for empty list, False for nonempty"""
return not l
def easy_iseven(x):
"""Takes a number and returns True if it's even, otherwise False"""
return x % 2 == 0
def easy_and(b1, b2):
"""Takes two booleans and returns their AND"""
return b1 and b2
def easy_or(b1, b2):
"""Takes two booleans and returns their OR"""
return b1 or b2
def easy_lt(a, b):
"""Takes two numbers and return whether num1 is less than num2"""
return a < b
def easy_contains(a, b):
"""Takes in 2 non-empty strings and returns True if the first value contains a substring that matches the second value."""
return b in a
def easy_helloname(a):
"""Takes in a string representing a name and returns a new string saying hello in a very specific format, e.g., if the name is 'Dave', it should return 'Hello, Dave!'"""
return 'Hello, {}!'.format(a)
def easy_iscat(a):
"""Takes in a string and returns 'meow' if it is the exact string 'cat', otherwise 'woof'."""
return 'meow' if a == 'cat' else 'woof'
|
"""
Function analysis module which sets function APIs based
on function's name matching impapi. This should ideally go
early in the module order to get the APIs marked asap.
"""
def analyzeFunction(vw, fva):
fname = vw.getName(fva)
api = vw.getImpApi(fname)
if api == None:
return
rettype,retname,callconv,callname,callargs = api
callargs = [ callargs[i] if callargs[i][1] else (callargs[i][0],'arg%d' % i) for i in xrange(len(callargs)) ]
vw.setFunctionApi(fva, (rettype,retname,callconv,callname,callargs))
|
"""
Function analysis module which sets function APIs based
on function's name matching impapi. This should ideally go
early in the module order to get the APIs marked asap.
"""
def analyze_function(vw, fva):
fname = vw.getName(fva)
api = vw.getImpApi(fname)
if api == None:
return
(rettype, retname, callconv, callname, callargs) = api
callargs = [callargs[i] if callargs[i][1] else (callargs[i][0], 'arg%d' % i) for i in xrange(len(callargs))]
vw.setFunctionApi(fva, (rettype, retname, callconv, callname, callargs))
|
class Solution:
def solve(self, matrix, target):
for r in range(len(matrix)):
for c in range(len(matrix[0])):
if r-1 >= 0: matrix[r][c] += matrix[r-1][c]
if c-1 >= 0: matrix[r][c] += matrix[r][c-1]
if r-1 >= 0 and c-1 >= 0: matrix[r][c] -= matrix[r-1][c-1]
l,r = 0,min(len(matrix),len(matrix[0]))
ans = 0
def works(x):
return any(matrix[r][c]-(matrix[r-x][c] if r-x>=0 else 0)-(matrix[r][c-x] if c-x>=0 else 0)+(matrix[r-x][c-x] if r-x>=0 and c-x>=0 else 0) <= target for r in range(x-1,len(matrix)) for c in range(x-1,len(matrix[0])))
while l<=r:
m = (l+r)//2
if works(m):
ans = m
l = m+1
else:
r = m-1
return ans**2
|
class Solution:
def solve(self, matrix, target):
for r in range(len(matrix)):
for c in range(len(matrix[0])):
if r - 1 >= 0:
matrix[r][c] += matrix[r - 1][c]
if c - 1 >= 0:
matrix[r][c] += matrix[r][c - 1]
if r - 1 >= 0 and c - 1 >= 0:
matrix[r][c] -= matrix[r - 1][c - 1]
(l, r) = (0, min(len(matrix), len(matrix[0])))
ans = 0
def works(x):
return any((matrix[r][c] - (matrix[r - x][c] if r - x >= 0 else 0) - (matrix[r][c - x] if c - x >= 0 else 0) + (matrix[r - x][c - x] if r - x >= 0 and c - x >= 0 else 0) <= target for r in range(x - 1, len(matrix)) for c in range(x - 1, len(matrix[0]))))
while l <= r:
m = (l + r) // 2
if works(m):
ans = m
l = m + 1
else:
r = m - 1
return ans ** 2
|
"""
File: settings.py
Author: Luke Mason
Description: Main application development settings file
"""
SCREEN_WIDTH = 1920
SCREEN_HEIGHT = 1080
WIDTH = 800
HEIGHT = 900
PAD = 15
APP_NAME = 'PyGraph' # Str of app name for window title
DEBUG = 1 # Puts the app in debug mode (extra logging to console).
LOG = 1 # Puts the app in log mode, (shows success/error messages in console).
COLOR = {
'black': (0, 0, 0),
'white': (255, 255, 255),
'focus': (255, 25, 133)
}
FONT = 'Calibri'
FONT_SIZE = 25
# VIEWS = [
# 'home', # Main home app
# # 'graph', # Graph interaction
# # 'save', # Graph save/load
# # 'settings' # App user settings
# ]
_QUIT = -2
|
"""
File: settings.py
Author: Luke Mason
Description: Main application development settings file
"""
screen_width = 1920
screen_height = 1080
width = 800
height = 900
pad = 15
app_name = 'PyGraph'
debug = 1
log = 1
color = {'black': (0, 0, 0), 'white': (255, 255, 255), 'focus': (255, 25, 133)}
font = 'Calibri'
font_size = 25
_quit = -2
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.