content
stringlengths 7
1.05M
|
---|
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)
|
# Given: A positive integer n≤7.
#
# Return: The total number of permutations of length n, followed by a list of all such permutations (in any order).
def to_string(list):
return " ".join(list)
def permute(list, start, end):
if start == end:
print(to_string(list))
else:
for i in range(start, end+1):
list[start], list[i] = list[i], list[start]
permute(list, start+1, end)
list[start], list[i] = list[i], list[start]
n = 6
i = n
intList = []
counter = 1
while i > 0:
intList.append(str(i))
counter = counter * i
i -= 1
print(counter)
permute(intList, 0, len(intList)-1)
|
#
# 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)
|
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)
|
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 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"))
|
#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') |
"""
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('{'))
|
# 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'
}
|
# 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()
|
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)) |
n = int(input())
sum1 = 0
for i in range(1, n + 1):
if n % i == 0:
sum1 += i
print(sum1)
|
class Config:
SCHEME = "https"
HOST = SCHEME + "://mobile-api-gateway.truemoney.com"
DEVICE_OS = "android"
DEVICE_ID = "574e0139a8e4460dac351feac6157871"
DEVICE_TYPE = "Zenfone Max"
DEVICE_VERSION = "7.1.2"
APP_NAME = "wallet"
APP_VERSION = "4.18.0"
HEADERS = {
"User-Agent": "okhttp/3.9.0",
"Connection": "close",
"Accept-Encoding": "gzip, deflate"
}
PARAMS = {
"device_os": DEVICE_OS,
"device_id": DEVICE_ID,
"device_type": DEVICE_TYPE,
"device_version": DEVICE_VERSION,
"app_name": APP_NAME,
"app_version": APP_VERSION
}
BANKS = [
{
"name": "ธนาคารไทยพาณิชย์",
"code": "SCB"
},
{
"name": "ธนาคารกรุงเทพ",
"code": "BBL"
},
{
"name": "ธนาคารกสิกรไทย",
"code": "KBANK"
},
{
"name": "ธนาคารกรุงไทย",
"code": "KTB"
},
{
"name": "ธนาคารทหารไทย",
"code": "TMB"
},
{
"name": "ธนาคารกรุงศรีอยุธยา",
"code": "BAY"
},
{
"name": "ธนาคารธนชาต",
"code": "TBANK"
},
{
"name": "ธนาคารซีไอเอ็มบี ไทย",
"code": "CIMB"
},
{
"name": "ธนาคารอิสลามแห่งประเทศไทย",
"code": "ISBT"
},
{
"name": "ธนาคารแลนด์ แอนด์ เฮาส์",
"code": "LHBANK"
},
{
"name": "ธนาคารยูโอบี",
"code": "UOB"
},
{
"name": "ธนาคารไทยเครดิตเพื่อรายย่อย",
"code": "TCRB"
},
{
"name": "ธนาคารซิตี้แบงก์",
"code": "CITI"
},
{
"name": "ธนาคารสแตนดาร์ดชาร์เตอร์ด",
"code": "SCBT"
},
{
"name": "ธนาคารไอซีบีซี ไทย",
"code": "ICBCT"
},
{
"name": "ธนาคารแห่งประเทศจีน",
"code": "BOC"
}
]
SIGNIN_PATH = "/mobile-api-gateway/api/v1/signin"
SIGNIN_URL = HOST + SIGNIN_PATH
PROFILE_PATH = "/mobile-api-gateway/api/v1/profile"
PROFILE_URL = HOST + PROFILE_PATH
KYC_PROFILE_PATH = "/mobile-api-gateway/api/v1/kyc/customer-profiles"
KYC_PROFILE_URL = HOST + KYC_PROFILE_PATH
OTP_PATH = "/mobile-api-gateway/api/v1/{0}/otp"
OTP_URL = HOST + OTP_PATH
WALLET_DRAFT_TRANSACTION_PATH = "/mobile-api-gateway/api/v1/transfer/draft-transaction/{0}"
WALLET_DRAFT_TRANSACTION_URL = HOST + WALLET_DRAFT_TRANSACTION_PATH
WALLET_OTP_PATH = "/mobile-api-gateway/api/v1/transfer/draft-transaction/{0}/send-otp/{1}"
WALLET_OTP_URL = HOST + WALLET_OTP_PATH
WALLET_TRANSFER_PATH = "/mobile-api-gateway/api/v1/transfer/transaction/{0}/{1}"
WALLET_TRANSFER_URL = HOST + WALLET_TRANSFER_PATH
WALLET_TRANSFER_STATUS_PATH = "/mobile-api-gateway/api/v1/transfer/transaction/{0}/status/{1}"
WALLET_TRANSFER_STATUS_URL = HOST + WALLET_TRANSFER_STATUS_PATH
WITHDRAW_DRAFT_TRANSACTION_PATH = "/mobile-api-gateway/api/v1/withdraw/draft-transaction/{0}"
WITHDRAW_DRAFT_TRANSACTION_URL = HOST + WITHDRAW_DRAFT_TRANSACTION_PATH
WITHDRAW_PATH = "/mobile-api-gateway/api/v1/withdraw/transaction/{0}/{1}"
WITHDRAW_URL = HOST + WITHDRAW_PATH
WITHDRAW_OTP_PATH = "/mobile-api-gateway/api/v1/withdraw/draft-transaction/{0}/send-otp/{1}"
WITHDRAW_OTP_URL = HOST + WITHDRAW_OTP_PATH
WITHDRAW_STATUS_PATH = "/mobile-api-gateway/api/v1/withdraw/transaction/{0}/status/{1}"
WITHDRAW_STATUS_URL = HOST + WITHDRAW_STATUS_PATH
PROMPTPAY_LOOKUP_PATH = "/mobile-api-gateway/api/v1/promptpay/sending/lookup"
PROMPTPAY_LOOKUP_URL = HOST + PROMPTPAY_LOOKUP_PATH
PROMPTPAY_TRANSFER_PATH = "/mobile-api-gateway/api/v1/promptpay/sending/transfer"
PROMPTPAY_TRANSFER_URL = HOST + PROMPTPAY_TRANSFER_PATH
|
def MoveManyStepsForward(numberOfSteps):
for everySingleNumberInTheRange in range(numberOfSteps):
env.step(0)
async def main():
MoveManyStepsForward(50)
await sleep()
MoveManyStepsForward(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
|
#!/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 #
###################################################################
|
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) |
# -*- 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])] |
# Limiar da Matriz Quadrada :: github.com/sliatecinos
# ================================================================================
# Ref.externa: https://www.facebook.com/groups/608492105999336/permalink/2061101090738423/
# Entradas do usuario (lado, limiar, ordem da matriz)
lado_diagonal = input('Estarao "acima" ou "abaixo" da diagonal?: ')
maximo = int(input('Qual o limiar (inteiro)?: '))
ordem = int(input('Qual a ordem da matriz?: '))
# Iteraçao para popular a matriz
i = j = 0
lista_2d = []
for i in range(ordem):
coluna = []
for j in range(ordem):
elemento = int(input('Elemento: '))
coluna.append(elemento)
lista_2d.append(coluna)
# Declaraçao da funçao que ira iterar somente sobre os itens das diagonais
def total(Matriz, Diagonal, Limiar):
soma = 0
for l in range(ordem):
for m in range(ordem):
if Diagonal == 'acima':
if m > l:
soma += Matriz[l][m]
if Diagonal == 'abaixo':
if m < l:
soma += Matriz[l][m]
return soma > Limiar
# Chamada e print do teste
teste = total(Matriz=lista_2d, Diagonal=lado_diagonal, Limiar=maximo)
print(teste)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'''
Реализовать класс Bankomat, моделирующий работу банкомата. В классе должны
содержаться поля для хранения идентификационного номера банкомата, информации о
текущей сумме денег, оставшейся в банкомате, минимальной и максимальной суммах,
которые позволяется снять клиенту в один день.
Реализовать метод инициализации банкомата, метод
загрузки купюр в банкомат и метод снятия определенной суммы денег. Метод снятия денег
должен выполнять проверку на корректность снимаемой суммы: она не должна быть
меньше минимального значения и не должна превышать максимальное значение
'''
class Bankomat:
def __init__(self):
self.id_bankomata = 0
self.ostatok_deneg = 0
self.min = 0
self.max = 0
def add_bankomat(self):
self.id_bankomata = input("ID банкамата: ")
self.ostatok_deneg = input("Денег в банкомате: ")
self.min = input("Минимальная сумма для снятия: ")
self.max = input("Максимальная сумма для снятия: ")
if self.max >= self.ostatok_deneg:
self.max = self.ostatok_deneg
with open(f"{self.id_bankomata}.txt", "w") as file:
file.write(
"ID банкамата: " + self.id_bankomata + "\n"
)
with open(f"{self.id_bankomata}.txt", "a") as file:
file.write(
"Остаток денег: \n" + self.ostatok_deneg + "\n"
)
with open(f"{self.id_bankomata}.txt", "a") as file:
file.write(
"Минимальная сумма для снятия: \n" + self.min + "\n"
)
with open(f"{self.id_bankomata}.txt", "a") as file:
file.write(
"Максимальная сумма для снятия: \n" + self.max + "\n"
)
def add_money(self, id_b):
self.id_bankomata = id_b
add_m = int(input("Внесите сумму денег для зачисления: "))
with open(f"{self.id_bankomata}.txt", "r") as file:
l_str = file.readlines()
with open(f"{self.id_bankomata}.txt", "w") as file:
ost = int(l_str[2])
l_str[2] = add_m + ost
l_str[2] = str(l_str[2]) + '\n'
file.writelines(l_str)
print("Деньги внесены на счет ")
def see_bankomat(self, id_b):
self.id_bankomata = id_b
with open(f"{self.id_bankomata}.txt", "r") as file:
for i in file:
print(i)
def withdraw_money(self, id_b):
self.id_bankomata = id_b
take_m = int(input("Введите сумму, которую хотите снять: "))
if take_m % 100:
print("Такую сумму снять невозможно")
else:
with open(f"{self.id_bankomata}.txt", "r") as file:
l_str = file.readlines()
with open(f"{self.id_bankomata}.txt", "r+") as file:
min = int(l_str[4])
max = int(l_str[6])
if take_m < min or take_m > max:
print("Такую сумму снять невозможно")
else:
with open(f"{self.id_bankomata}.txt", "r") as file:
l_str = file.readlines()
with open(f"{self.id_bankomata}.txt", "r+") as file:
ost = int(l_str[2]) - take_m
l_str[2] = str(ost) + '\n'
if int(l_str[6]) > int(ost):
l_str[6] = l_str[2]
file.writelines(l_str)
print("Деньги сняты со счета ")
def choice():
while True:
command = input("___: ").lower()
if command == 'exit':
break
elif command == 'add_b':
y.add_bankomat()
elif command.startswith('see_b '):
parts = command.split(' ', maxsplit=1)
id_bankomata = (parts[1])
y.see_bankomat(id_bankomata)
elif command.startswith('add_m '):
parts = command.split(' ', maxsplit=1)
id_bankomata = (parts[1])
y.add_money(id_bankomata)
elif command.startswith('withdraw_m '):
parts = command.split(' ', maxsplit=1)
id_bankomata = (parts[1])
y.withdraw_money(id_bankomata)
elif command == 'help':
print("Список команд:\n")
print("add_b - добавить банкомат;")
print("see_b `ID банкомата` - посмотреть банкомат;")
print("add_m `ID банкомата` - внести денги на счет;")
print("withdraw_m `ID банкомата`- снять деньги со счета;")
print("help - отобразить справку;")
print("exit - завершить работу.")
else:
print(f"Введена неизвестная команда {command}")
if __name__ == '__main__':
y = Bankomat()
choice()
|
'''
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!")
|
# 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))) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class QuickSort:
"""
快速排序
"""
def __init__(self):
pass
def quicksort(self, nums):
if len(nums) == 1 or len(nums) == 0:
return nums
less = []
greater = []
middle_num = nums.pop()
for num in nums:
if num > middle_num:
greater.append(num)
if num < middle_num:
less.append(num)
return self.quicksort(less) + [middle_num] + self.quicksort(greater)
if __name__ == '__main__':
print(QuickSort().quicksort([5, 6, 1, 3, 4, 2]))
|
# 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 = ''
# =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
|
# -----------------------------------------------------------------------------
# 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
'''
|
#!/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"
|
"""
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()
|
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)
|
#
# 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)
|
#!/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)
|
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()
|
__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 |
# Tablica T jest długości n, ale zawiera tylko ceil(logn) różnych wartości. Proszę zaproponować
# jak najszybszy algorytm sortujący taką tablicę.
def counting_sort(T, k):
C = [0]*len(T)
B = [0]*10
for i in range(len(T)):
index = T[i]/k
B[int(index % 10)] += 1
for i in range(1, 10):
B[i] += B[i-1]
j = len(T)-1
while j >= 0:
index = T[j]/k
C[B[int(index % 10)]-1] = T[j]
B[int(index % 10)] -= 1
j -= 1
for i in range(len(T)):
T[i] = C[i]
def radix_sort(T):
maximum = 0
for i in range(len(T)):
maximum = max(maximum, T[i])
i = 1
while maximum/i > 0:
counting_sort(T, i)
i *= 10
def digits(number):
length = 0
while number > 0:
length += 1
number //= 10
return length
def sort(T):
max_length = 0
for i in range(len(T)):
max_length = max(max_length, digits(T[i]))
for i in range(len(T)):
T[i] += (10**max_length)
radix_sort(T)
for i in range(len(T)):
T[i] -= (10**max_length)
T = [365, 45137, 12, 45137, 12, 12, 45137, 365, 12]
sort(T)
print(T)
|
# 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'
]
|
def func(max):
res = []
for i in range(1, max):
# 对15取余为0 输出fizzbuzz
if i % 15 == 0:
res.append('fizzbuzz')
# 对3取余为0,输出fizz
elif i % 3 == 0:
res.append('fizz')
# 对5取余为0,输出为buzz
elif i % 5 == 0:
res.append('buzz')
# 不符合以上3种情况,直接输出数字
else:
res.append(str(i))
print(' '.join(res))
func(max=100)
|
# -*- coding: UTF-8 -*-
# https://dormousehole.readthedocs.io/en/latest/config.html#config
class Config(object):
SECRET_KEY = 'e9d37baf44de4b11a76159c50820468f'
SQLALCHEMY_TRACK_MODIFICATIONS = False
SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://xingweidong:xingweidong&123@localhost/idss_stock' # 股票数据库,默认
SQLALCHEMY_BINDS = {
'fund': 'mysql+pymysql://xingweidong:xingweidong&123@localhost/idss_fund' # 基金数据库
}
CHROME_DRIVER = '/Users/xingweidong/envs/selenium/webdriver/chrome/88.0.4324.96/chromedriver'
|
#!/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',
}
|
MONTHS_MAPS = {"janvier" : '01',
"février": '02',
"fevrier": '02',
"mars": '03',
"avril": '04',
"mai": '05',
"juin": '06',
"juillet": '07',
"août": '08',
"aout": '08',
"septembre": '09',
"octobre": '10',
"novembre": '11',
"décembre": '12',
"decembre": '12',
"janv.": '01' ,
"janv": '01',
"fev.": '02',
"fev": '02',
"av.": '04',
"avr.": '04',
"av": '04',
"juil.": '07',
"juil": '07',
"sept.": '09',
"sept": '09',
"oct.": '10',
"oct": '10',
"nov.": '11',
"nov": '11',
"déc.": '12',
"dec.": '12',
"déc": '12',
"dec": '12'}
TEIHEADER = {
"fileDesc": "".join(['<fileDesc><titleStmt><title xml:lang="fr">placeholder</title>',
"<author>Lectaurep</author>",
"<funder>Ministry of Higher Education, Research and Innovation</funder>",
"<respStmt>",
"<resp>Edited and encoded by</resp>",
"<persName><forename>Alix</forename><surname>Chagué</surname></persName>",
"</respStmt><respStmt>",
"<resp>Edited and encoded by</resp>",
"<persName><forename>Hugo</forename><surname>Scheithauer</surname></persName>",
"</respStmt><respStmt>",
"<resp>Transcription by</resp>",
"<orgName>Département du Minutier central des notaires de Paris</orgName>",
'</respStmt><respStmt><resp>Digitization by</resp>',
"<orgName>Archives nationales</orgName></respStmt></titleStmt>",
'<publicationStmt><authority>Lectaurep (Archives nationales, Inria)</authority><availability>',
'<licence target="https://creativecommons.org/licenses/by/4.0/">',
"<p>Distributed under a Creative Commons Attribution 4.0 International (CC BY 4.0)",
'</p></licence></availability><date when-iso="2020"/>',
"</publicationStmt><seriesStmt>",
'<title type="main">Répertoires de notaires de Paris</title>',
"</seriesStmt><sourceDesc><p/></sourceDesc></fileDesc>"]),
"encodingDesc": "".join(["<encodingDesc><projectDesc>",
"<p xml:lang="fr">L'encodage de ce document s'est fait dans ",
"le cadre du projet LECTAUREP</p></projectDesc>",
"<editorialDecl><correction>",
'<p xml:lang="fr">Aucune correction</p></correction>',
'<hyphenation eol="all" rend="sh">',
"<p xml:lang="fr">Toutes les coupures de mots pour ",
"fin de ligne (indiquées principalement avec un tiret",
"simple) ont été conservées.</p>",
"</hyphenation></editorialDecl></encodingDesc>"])
} |
# 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.
"""
|
# 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)
|
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)
|
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()
|
local = {}
incluir = True
while incluir:
nome = input('qual seu nome? :')
local_escolhido = input('Qual local de suas próximas férias? :')
local[nome] = local_escolhido
repetir = input('Gostaria de incluir outro na enquete?(Yes/No):')
if repetir == 'no':
incluir = False
print('Resultados da Enquete')
for nome, local_escolhido in local.items():
print('{} vai passar as férias em {}'.format(nome, local_escolhido))
|
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
|
numero = int(input('Número: '))
dobro = numero*2
triplo = numero*3
raiz = numero**(1/2)
print(f'Dobro: {dobro}, Triplo: {triplo}, Raiz quadrada: {raiz:.2f}')
|
def foo(bar1, bar2, bar3,
bar4
): # FD102
return
|
class Page(object):
'''
页面基类,用于所有页面的继承
初始化,地址,驱动,超时时间
打开网页方法
查找单个元素方法
查找多个元素方法
页面打开检查
调用JavaScript代码
'''
bbs_url='https://mail.qq.com'
def __init__(self,selenium_driver,base_url=bbs_url,parent=None):
self.base_url=base_url
self.timeout=30
self.driver=selenium_driver
self.parent=parent
def _open(self,url):
self.url=self.base_url+url
self.driver.get(self.url)
assert self.on_page() ,'【%s】打开失败'%self.url
def open(self):
return self._open(self.url)
def on_page(self):
print(self.driver.current_url)
return self.driver.current_url==(self.url)
def find_element(self,*loc):
return self.driver.find_element(*loc)
def find_elments(self,*loc):
return self.find_elments(*loc)
def script(self,src):
return self.driver.execute_script(src) |
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)) |
"""
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
|
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
|
''' Esta função conta o número de ocorrências de cada palavra em uma frase '''
def count_words(sentence):
for s in ".:!&@$%^&": sentence=sentence.replace(s,'')
for s in "\n\r\t,_": sentence=sentence.replace(s,' ')
counts={}
for word in sentence.lower().split():
word = word.strip('\'')
if word in counts:
counts[word] += 1
else:
counts[word] = 1
return counts
# código principal
frase = 'O C6 Bank, em sua contestação, reconhece tratar-se de golpe corriqueiro e que com a entrada em vigor do PIX, houve maior vulnerabilidade no sistema de pagamentos e transferências de numerário. O que nos faz concluir que o banco deveria recrudescer seus mecanismos de detecção de fraudes, caso existam de fato, e agir prontamente quando qualquer irregularidade ou suspeita lhe fosse comunicada. Infelizmente, não foi o que ocorreu no presente caso.'
count_words(frase)
|
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 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 '' |
'''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')
|
x:int = 1
o:object = None
x = o = 42
|
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) |
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
|
_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'),
])
|
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 :-
# * * * *
# * * * *
# * * * * * * *
# * *
# * *
# * *
# * * * * * * *
|
"""
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()
|
# 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)
|
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')
|
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))
|
# 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
|
# 2.5 정리
# 이번 장에서는 자연어를 대상으로,
# 특히 컴퓨터에게 '단어의 의미'를 이해하기 위한 주제로 진행함
# 시소러스 기법
'''
단어들의 관련성을 사람이 수작업으로 하나씩 정의한다.
이 작업은 매우 힘들고 (느낌의 미세한 차이를 나타낼 수 없다 등) 표현력에도 한계가 있다.
'''
# 통계 기반 기법
'''
말뭉치로부터 단어의 의미를 자동으로 추출하고, 그 의미를 벡터로 표현한다.
구체적으로
1. 단어의 동시발생 행렬을 만든다.
2. PPMI 행렬로 변환한다.
3. 안정성을 높이기 위해 SVD를 이용해 차원을 감소시켜, 각 단어의 분산 표현을 만든다.
4. 분산 표현에 따르면 의미가 (그리고 문법적인 용법면에서) 비슷한 단어들이 벡터 공간에서도 서로 가까이 모여 있음을 확인한다.
'''
# 전처리 함수
'''
cos_similarity(): 벡터 간 유사도를 측정하는 함수
most_similar(): 유사 단어의 랭킹을 표시하는 함수
'''
# 이번 장에서 배운 내용
'''
1. WordNet 등의 시소러스를 이용하면 유의어를 얻거나 단어 사이의 유사도를 측정하는 등 유용한 작업을 할 수 있다.
2. 시소러스 기반 기법은 시소러스를 작성하는 데 엄청난 인적 자원이 든다거나 새로운 단어에 대응하기 어렵다는 문제가 있다.
3. 현재는 말뭉치를 이용해 단어를 백터화하는 방식이 주로 쓰인다.
4. 최근의 단어 벡터화 기법들은 대부분 '단어의 의미는 주변 단어에 의해 형성된다'는 분포 가설에 기초한다.
5. 통계 기반 기법은 말뭉치 안의 각 단어에 대해서 그 단어의 주변 단어의 빈도를 집계한다(동시발생 행렬).
6. 동시발생 행렬 PPMI 행렬로 변환하고 다시 차원을 감소시킴으로써, 거대한 '희소벡터'를 작은 '밀집벡터'로 변환할 수 있다.
7. 단어의 벡터 공간에서는 의미가 가까운 단어는 그 거리도 가까울 것으로 기대된다.
''' |
"""
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],
}
|
#!/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 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) |
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")
|
## 连接
multiLineStr = 'hell' + \
'o, w' + \
'orld'
print(multiLineStr)
# 会输出 hello, world
## 条件分支
### 条件控制
furry = True
small = True
if furry:
if small:
print(" It' s a cat.")
else:
print(" It' s a bear!")
else:
if small:
print(" It' s a skink!")
else:
print(" It' s a human. Or a hairless bear.")
# 会输出 It' s a cat.
## while 循环
whileList = []
whileNum = 1
while True:
if len(whileList) == 5:
break
if whileNum % 2 == 0:
whileList.append(whileNum)
whileNum += 1
print(whileList)
# 会输出 [2, 4, 6, 8, 10]
whileList = []
whileNum = 1
while whileNum < 10:
if len(whileList) == 5:
break
if whileNum % 2 == 0:
whileList.append(whileNum)
whileNum += 1
else:
whileList.append(9)
print(whileList)
# 会输出 [2, 4, 6, 8, 9]
## for 循环
forList = []
for forNum in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:
if len(forList) == 5:
break
if forNum % 2 == 0:
forList.append(forNum)
else:
forList.append(11)
print(forList)
# 会输出 [2, 4, 6, 8, 10, 11]
|
# 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 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 Author:
enable = True
name = "Someone"
description = (
"台灣/台北/高雄人。現暫居美國,於伊利諾香檳大學(UIUC)就讀資管碩士。近年內的工作與興趣都是軟體工程。"
)
image_url = "https://storage.googleapis.com/blog-someone-tw-static/post/author.png"
url = "/post/1/about"
class Facebook:
enable = True
app_id = "344199519780600"
class Comment:
enable = True
class GoogleTagManager:
enable = True
app_id = "GTM-T95PGM6"
|
# 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:
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""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 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) |
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 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(""))
|
# 자작 문제풀이
# Question number. 003
# Author: Lee Jeongwoo
# Github name: zao95
# ========== Question ==========
# python-packer를 이용하여 실행파일 제작
# ==============================
def abc():
print("a")
abc()
print(hex(id(abc())))
print(hex(id("abc"))) |
# 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() |
#
# 771. Jewels and Stone
#
# You're given strings J representing the types of stones that are jewels, and
# S representing the stones you have.
#
# Each character in S is a type of stone you have. You want to know how many of
# the stones you have are also jewels.
#
# The letters in J are guaranteed distinct, and all characters in J and S are
# letters. Letters are case sensitive, so "a" is considered a different type of
# stone from "A".
#
class Solution:
def numJewelsInStones(self, J: str, S: str) -> int:
# sum((True, False, True)) = 2
return sum(map(J.count, S))
return sum(S.count(j) for j in J)
return sum(i in J for i in S) # i in J 返回 True 或 False
s = Solution()
print(s.numJewelsInStones("aA", "aAAbbbb"))
|
#!/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)
|
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 func():
pass
return
#file length check
if __name__ == '__main__':
try:
f = open('./testfile.txt', 'r') #1.file read -> open('')
length = len(f.read()) #2.length 설정
f.close() #3.자원클로즈
print(length)
except Exception as e:
pass |
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 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 |
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"
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.