content
stringlengths 7
1.05M
|
|---|
try:
raise Exception()
except Exception as e:
print("hello", str(e))
|
database = {
'default': 'mysql',
'connections': {
'mysql': {
'name': 'mytodo',
'username': 'root',
'password': '',
'connection': 'mysql:host=127.0.0.1',
},
},
'migrations': 'migrations',
}
|
# CONCATENATION
firstName = "Helder"
lastName = "Pereira"
fullName = "Helder" + " " + lastName
print(fullName)
|
#!/usr/bin/python
# -*- coding:utf-8 -*-
'''
sqlmapapi restful interface
by zhangh (zhanghang.org#gmail.com)
'''
# api
task_new = "task/new"
task_del = "task/<taskid>/delete"
admin_task_list = "admin/<taskid>/list"
admin_task_flush = "admin/<taskid>/flush"
option_task_list = "option/<taskid>/list"
option_task_get = "option/<taskid>/get"
option_task_set = "option/<taskid>/set"
scan_task_start = "scan/<taskid>/start"
scan_task_stop = "scan/<taskid>/stop"
scan_task_kill = "scan/<taskid>/kill"
scan_task_status = "scan/<taskid>/status"
scan_task_data = "scan/<taskid>/data"
scan_task_log = "scan/<taskid>/log/<start>/<end>"
scan_task_log = "scan/<taskid>/log"
download_task = "download/<taskid>/<target>/<filename:path>"
# config
taskid = "<taskid>"
dbOld = 0
dbNew = 1
host = '172.22.1.44'
port = 2000
password = 'SEC'
joblist = 'job.set'
sqlinj = 'sqlinj'
|
def path_initial_steps(path, node):
'''
takes in a list of arcs and a node and returns the list of nodes the node can reach
'''
initial_steps = []
for arc in path:
if arc[0] == node:
initial_steps.append(arc)
return initial_steps
def path_end_points(path, node):
'''
takes in a list of arcs and a node and returns the list of nodes the node can reach
'''
nodes_reachable = []
initial_steps = path_initial_steps(path, node)
while len(initial_steps) > 0:
new_steps = []
for arc in initial_steps:
nodes_reachable.append(arc[1])
new_steps.append(arc[1])
new_arcs = []
for node in new_steps:
arcs_per_node = path_initial_steps(path, node)
if len(arcs_per_node) > 0:
for arc2 in arcs_per_node:
new_arcs.append(arc2)
initial_steps = new_arcs
return nodes_reachable
def is_projective_arc(path, arc):
head = arc[0]
dependent = arc[1]
nodes_reachable = path_end_points(path, head)
if head < dependent:
relevant_nodes = [x for x in range(head + 1, dependent)]
else:
relevant_nodes = [x for x in range(dependent + 1, head)]
for node in relevant_nodes:
if node not in nodes_reachable:
return False
return True
def is_projective_tree(tree):
for arc in tree:
if not is_projective_arc(tree, arc):
return False
return True
|
print('-- ์ฑ์ ์ฒ๋ฆฌ ํ๋ก๊ทธ๋จ v1 --')
name = input("์ด๋ฆ์ ์
๋ ฅํ์ธ์")
kor = int(input("๊ตญ์ด ์ ์๋ฅผ ์
๋ ฅํ์ธ์"))
eng = int(input("์์ด ์ ์๋ฅผ ์
๋ ฅํ์ธ์"))
mat = int(input("์ํ ์ ์๋ฅผ ์
๋ ฅํ์ธ์"))
def getTotal():
tot = kor + mat + eng
return tot
def getAverage():
avg = getTotal() / 3
return avg
def getGrade():
avg = getAverage()
grd = '๊ฐ'
if avg >= 90:
grd = '์'
elif avg >= 80:
grd = '์ฐ'
elif avg >= 70:
grd = '๋ฏธ'
elif avg >= 60:
grd = '์'
return grd
fmt = '์ด๋ฆ: %s ๊ตญ์ด: %d ์ํ: %d ์์ด: %d ์ด์ : %d ํ๊ท : %.2f ํ์ : %s'
print(fmt % (name, kor, eng, mat, getTotal(), getAverage(), getGrade()))
|
#!/usr/bin/env python3
"""
determine the shape of a matrix
"""
def matrix_shape(matrix):
"""
function to calculatre matrix shape
"""
shape = []
while type(matrix) is list:
shape.append(len(matrix))
matrix = matrix[0]
return shape
|
try:
palavra = 'Palavrinha'
print(palavra)
except NameError as erro:
print('Ocorreu um NameError ', erro) # (Neste caso nรฃo serรก executado).
except (KeyError, IndexError) as erro:
print('Ocorreu um KeyError ou um IndexError ', erro) # (Neste caso nรฃo serรก executado).
except Exception as erro:
print('Ocorreu um erro inesperado ', erro) # (Neste caso nรฃo serรก executado).
# Executarรก independentemente se o try foi executado com sucesso ou nรฃo.
finally:
print('Executo independentemente de tudo')
palavra = 'Vazio'
print('Continuaรงรฃo do cรณdigo')
print(palavra)
|
"""Basic registry for model builders."""
BUILDERS = dict()
def register(name):
"""Registers a new model builder function under the given model name."""
def add_to_dict(func):
BUILDERS[name] = func
return func
return add_to_dict
def get_builder(model_name):
"""Fetches the model builder function associated with the given model name"""
return BUILDERS[model_name]
|
"""
Title | Project
Author: Keegan Skeate
Contact: <keegan@cannlytics.com>
Created:
Updated:
License: MIT License <https://github.com/cannlytics/cannlytics-ai/blob/main/LICENSE>
"""
# Initialize a Socrata client.
# app_token = os.environ.get('APP_TOKEN', None)
# client = Socrata('opendata.mass-cannabis-control.com', app_token)
# # Get sales by product type.
# products = client.get('xwf2-j7g9', limit=2000)
# products_data = pd.DataFrame.from_records(products)
# # Get licensees.
# licensees = client.get("hmwt-yiqy", limit=2000)
# licensees_data = pd.DataFrame.from_records(licensees)
# # Get the monthly average price per ounce.
# avg_price = client.get("rqtv-uenj", limit=2000)
# avg_price_data = pd.DataFrame.from_records(avg_price)
# # Get production stats (total employees, total plants, etc.)
# production = client.get("j3q7-3usu", limit=2000, order='saledate DESC')
# production_data = pd.DataFrame.from_records(production)
|
# ืืฉืืช ืขืจืืื "ืฉืื ,ืฉืืจ ืขืฉืจืื ื ืืืืจืืืช ืืชืื ืชื
#a=5 #ืืฉืืช ืขืจื ืืชื
#print(a) #ืคืื ืืขืจื ืฉื ืชื
#b=6 #ืืฉืืช ืขืจื ืืชื
#a=b #ืืฉืืช ืขืจื ืฉื ืชื ืื ืืชืื ืืื
#print(a) #ืคืื ืฉื ืขืจื ืชื ืืื-ืืชืืฆืื 6
#print(b) #ืคืื ืฉื ืชื ืื - ืืชืืฆืื 6
#print(a,b) #ืคืื ืฉื ืขืจืื 2 ืชืืื ืื ืืฆื ืื
#***************************************************
a="moti "
print(a)
b='yair'
print(b)
print("my name is: ",a,b)
#***************************************************
a="moti " #ืืฉืืช ืืืจืืืช ืืชื
print(a) #ืคืื ืืขืจื ืฉื ืชื
b='yair' #ืืฉืืช ืืืจืืืช ืืชื
print(b) #ืคืื ืืขืจื ืฉื ืชื
print("my name is: ",a,b) #ืคืื ืืขืจื ืฉื ืชื
# ืขืจืืื ืืืืืืื ืื
#a=5 #ืืฉืืช ืขืจื ืืชื
#b=3 #ืืฉืืช ืขืจื ืืชื
#x=True #ืชื ืืืงืก ืืื ืืืืืืื ื
#x=a==b #ืฉืืืชื:ืืื ืืื=ืื ? ืืชืฉืืื ืฉืืืจื ืืื ืฉืงืจ
#print(x) #ืคืื ืืืืืืื ื ืฉื ืืชื
#ืืคืฉืจ ืืืฉืืืช ืื ืืื ืืืจืืืืช
#a="abcd" #ืืฉืืช ืืืจืืืช ืืชื
#b="c" #ืืฉืืช ืืืจืืืช ืืชื
#x=True #ืชื ืืืงืก ืืื ืืืืืืื ื
#x=b in a #ืฉืืืชื ืืื ืื ื ืืฆื ืืชืื ืืื? ืืชืฉืืื ืฉืืืจื ืืื ืืืช
#print(x) #ืคืื ืืืืืืื ื ืฉื ืืชื
#ืืคืฉืจ ืืืฉืืืช ืื ืืื ืืืจืืืืช
#a="abcd" #ืืฉืืช ืืืจืืืช ืืชื
#b="c" #ืืฉืืช ืืืจืืืช ืืชื
#x=True #ืชื ืืืงืก ืืื ืืืืืืื ื
#x=a in b #ืืื ืืื ืืชืื ืื? ืืชืฉืืื ืฉืืืจื ืืื ืฉืงืจ
#print(x) #ืคืื ืืืืืืื ื ืฉื ืืชื
#***************************************************
# ืงืืืช ืงืื ืืืืฉืชืืฉ
#input("your name is: ") # ืืืืฉื ืืงืืื ืืช ืืืฉืคื ืืืืฉืชืืฉ ืืงืืื ืืช ืฉืื
#ืืื ืกืช ืคืขืืืช ืงืื ืืชืื ืชื
#ืืืกืืื ืืืชืืื
#name=input("your name is: ") #ืืืืจ ืืงืืืช ืฉื ืืืฉืชืืฉ ,ืฉืื ืืืฉืืจ ืืชืืืืืจืืืช
#print("Hi",name,"how are you today ?") #ืฉืืืื ืืืืจืืืช ืฉื ืฉื ืืืฉืชืืฉ ืืืฉืคื
#***************************************************
# ืืกืืช ืืืคืืกืื ืฉื ืืฉืชื ืื
#number=input("enter a number: ") #ืืฉืืช ืืืงืืื ืฉื ืืืฉืชืืฉ ืืชื ืฉืื ืืืจืืืช
#print(int(number)+1) # ืืกืืช ืืืคืืก ืืืจืืืช ืืืืคืืก ืืกืคืจ ืฉืื
#number=input("enter a number: ") #ืืฉืืช ืืืงืืื ืฉื ืืืฉืชืืฉ ืืชื ืฉืื ืืืจืืืช
#print(float(number)+1) #ืืกืืช ืืืคืืก ืืืจืืืช ืืืืคืืก ืฉืืจ ืขืฉืจืื ื
#number=input("enter a number: ") #ืืฉืืช ืืืงืืื ืฉื ืืืฉืชืืฉ ืืชื ืฉืื ืืืจืืืช
#print(float(number)**3) #ืืกืืช ืืืคืืก ืืืจืืืช ืืืืคืืก ืฉืืจ ืขืฉืจืื ื ืืืืงืช 3
#ืืืืคืช ืขืจืืื ืืื ืชืืื
#prati="moti" #ืืฉืืช ืืืจืืืช ืืชื
#mishpaha="yair" #ืืฉืืช ืืืจืืืช ืืชื
#prati,mishpaha=mishpaha,prati #ืืืืคืช ืืขืจืืื ืืื ืืชืืื
#print(prati) #ืคืื ืืฉื ืืคืจืื - ืืชืืฆืื ืืืืจ
#print(mishpaha) #ืคืื ืฉื ืืืฉืคืื - ืืชืืฆืื ืืืื
#ืืืื ืกืืืื ืฉื ืืืืืืงืืื
list=["1","2","3","4","5","6"] #ืจืฉืืื
x=list[0::2] #ืจืฉืืื
t= ", ".join(x) #ืืืจืืืช
z = list[-1] #ืืืจืืืช
a=3 #ืืกืคืจ ืฉืื
b=float(3) #ืืกืคืจ ืขืฉืจืื ื
c=True #ืืืืืื ื
print(c)
print(type(c))
|
def x():
return 1
x()
|
class Constants:
ha2kcalmol = 627.509 # Hartee^-1 kcal mol^-1
ha2kJmol = 2625.50 # Hartree^-1 kJ mol^-1
eV2ha = 0.0367493 # Hartree ev^-1
a02ang = 0.529177 # ร
bohr^-1
ang2a0 = 1.0 / a02ang # bohr ร
^-1
kcal2kJ = 4.184 # kJ kcal^-1
|
class Screen:
"""
Abstract class for drawing to the LCD
The main program will transition between
displaying various "screens" based on
high-level logic
"""
def draw(self, cr):
raise NotImplementedError("Must implement draw")
def stop(self):
"""
Some screens may need to initialize threads in order
to display content. These screens should terminate
those threads when this method is called.
"""
pass
"""
Name of this screen (for manual triggering via shared memory)
"""
def get_name(self):
raise NotImplementedError("Must implement get_name")
|
class MudAction:
"""
Contains all of the information about attempted physical actions within
the world. Whenever a Mob, Item, Character, etc tries to do anything in
the game world, an instance is created and sent around to all the other
chars, items, room, etc.
"""
def __init__(self, actionType, playerRef, data1='', \
data2='', data3='', string=''):
self.info = {}
self.info['actionType'] = actionType
self.info['playerRef'] = playerRef
self.info['data1'] = data1
self.info['data2'] = data2
self.info['data3'] = data3
self.info['string'] = string
def setType(self, type):
"""Sets the action type to the provided string."""
self.info['actionType'] = type
def setData1(self, data):
"""Sets the Data1 field of the action."""
self.info['data1'] = data
def setData2(self, data):
"""Sets the Data2 field of the action."""
self.info['data2'] = data
def setData3(self, data):
"""Sets the Data3 field of the action."""
self.info['data3'] = data
def setString(self, data):
"""Sets the string field of the action."""
# TODO: Probably not neccessary to call this string. Holdover from
# the translated C++ code.
self.string = data
def getType(self):
"""Returns the type of action."""
return self.info['actionType']
def getPlayerRef(self):
"""Returns a reference to the player who generated the action."""
return self.info['playerRef']
def getString(self):
"""Returns the String value of the action."""
return self.info['string']
def getData1(self):
"""Returns the data1 field."""
return self.info['data1']
def getData2(self):
"""Returns the data2 field."""
return self.info['data2']
def getData3(self):
"""Returns the data3 field."""
return self.info['data3']
class TimedAction(MudAction):
def __init__(self, actionType, playerRef, data1='', \
data2='', data3='', string=''):
MudAction.__init__(self, actionType, playerRef, data1='', \
data2='', data3='', string='')
self.executionTime = None
self.actionEvent = None
self.valid = True
def getExecutionTime(self):
"""
Returns the time (in miliseconds after start of MUD) that the
action should be executed.
"""
return self.executionTime
def setExecutionTime(self, time):
"""
Sets the time (in milliseconds after the MUD has started) that the
action should be executed.
"""
self.executionTime = time
def hook(self):
"""
This hooks a timed action to all it's references.
"""
# TODO: Some error checking code in case the instance/hook no longer
# exists? Same for unhook...
if type(self.getPlayerRef()) == 'instance':
self.getPlayerRef().addHook(self)
if type(self.getData1()) == 'instance':
self.getData1().addHook(self)
if type(self.getData2()) == 'instance':
self.getData1().addHook(self)
if type(self.getData3()) == 'instance':
self.getData1().addHook(self)
def unhook(self):
"""
This removes a timed action from all it's references.
"""
if type(self.getPlayerRef()) == 'instance':
self.getPlayerRef().removeHook(self)
if type(self.getData1()) == 'instance':
self.getData1().removeHook(self)
if type(self.getData2()) == 'instance':
self.getData1().removeHook(self)
if type(self.getData3()) == 'instance':
self.getData1().removeHook(self)
def setValid(self, value):
"""
Sets the validity of the action.
"""
if value == True:
self.valid = True
elif value == False:
self.valid = False
else:
#TODO: Code to notify that it is an invalid value?
return
|
def internet_on():
with open("error_log.csv", "a") as error_log:
error_log.write("\n{0},Log,Testing Internet connection.".format(strftime("%Y-%m-%d %H:%M:%S")))
global ledSwitch
global connected
global powerSwitch
try:
powerSwitch = 0
urllib.request.urlopen('http://216.58.207.206')
#urllib.urlopen('http://216.58.207.206', timeout=4)
with open("error_log.csv", "a") as error_log:
error_log.write("\n{0},Log,We have an internet connection.".format(strftime("%Y-%m-%d %H:%M:%S")))
ledSwitch = 1
Thread(target = led_green_alert).start()
try:
powerSwitch = 0
tts = gTTS(text="Code green! All communication systems are online and working within normal parameters." , lang='en')
tts.save("internet_on.mp3")
os.system("mpg321 -q internet_on.mp3")
except:
powerSwitch = 1
os.system("mpg321 -q internet_on_backup.mp3")
pass
connected = 1
ledSwitch = 0
time.sleep(2)
except:
powerSwitch = 1
with open("error_log.csv", "a") as error_log:
error_log.write("\n{0},Error,No internet connection.".format(strftime("%Y-%m-%d %H:%M:%S")))
ledSwitch = 1
Thread(target = led_red_alert).start()
try:
powerSwitch = 1
tts = gTTS(text="Alert! All communications are down. Alert! Systems running in emergency mode. Alert! Restoring communications, priority alpha." , lang='en')
tts.save("internet_off.mp3")
os.system("mpg321 -q internet_off.mp3")
os.system("mpg321 -q vader_breathe.mp3")
os.system("mpg321 -q vader_dont_fail.mp3")
except:
powerSwitch = 1
os.system("mpg321 -q internet_off_backup.mp3")
os.system("mpg321 -q vader_breathe.mp3")
os.system("mpg321 -q vader_dont_fail.mp3")
pass
connected = 0
ledSwitch = 0
time.sleep(2)
pass
def internet_on_thread():
global powerSwitch
global ledSwitch
global connected
while True:
time.sleep(180)
with open("error_log.csv", "a") as error_log:
error_log.write("\n{0},Log,Testing Internet connection.".format(strftime("%Y-%m-%d %H:%M:%S")))
if connected == 1:
try:
powerSwitch = 0
urllib.request.urlopen('http://216.58.207.206')
#urllib.urlopen('http://216.58.207.206', timeout=4)
with open("error_log.csv", "a") as error_log:
error_log.write("\n{0},Log,We have an internet connection.".format(strftime("%Y-%m-%d %H:%M:%S")))
connected = 1
except:
powerSwitch = 1
with open("error_log.csv", "a") as error_log:
error_log.write("\n{0},Error,No internet connection.".format(strftime("%Y-%m-%d %H:%M:%S")))
ledSwitch = 1
Thread(target = led_red_alert).start()
try:
powerSwitch = 1
tts = gTTS(text="Alert! All communications are down. Alert! Systems running in emergency mode. Alert! Restoring communications, priority alpha." , lang='en')
tts.save("internet_off.mp3")
os.system("mpg321 -q internet_off.mp3")
os.system("mpg321 -q vader_breathe.mp3")
os.system("mpg321 -q vader_dont_fail.mp3")
except:
powerSwitch = 1
os.system("mpg321 -q internet_off_backup.mp3")
os.system("mpg321 -q vader_breathe.mp3")
os.system("mpg321 -q vader_dont_fail.mp3")
pass
ledSwitch = 0
connected = 0
time.sleep(2)
pass
elif connected == 0:
try:
powerSwitch = 0
urllib.request.urlopen('http://216.58.192.142')
with open("error_log.csv", "a") as error_log:
error_log.write("\n{0},Log,We have an internet connection.".format(strftime("%Y-%m-%d %H:%M:%S")))
ledSwitch = 1
Thread(target = led_green_alert).start()
try:
powerSwitch = 0
tts = gTTS(text="Code green! All communication systems are online and working within normal parameters." , lang='en')
tts.save("internet_on.mp3")
os.system("mpg321 -q internet_on.mp3")
except:
powerSwitch = 1
os.system("mpg321 -q internet_on_backup.mp3")
pass
ledSwitch = 0
connected = 1
time.sleep(2)
except:
powerSwitch = 1
with open("error_log.csv", "a") as error_log:
error_log.write("\n{0},Error,No internet connection.".format(strftime("%Y-%m-%d %H:%M:%S")))
connected = 0
pass
|
# coding: utf-8
"""*****************************************************************************
* Copyright (C) 2018 Microchip Technology Inc. and its subsidiaries.
*
* Subject to your compliance with these terms, you may use Microchip software
* and any derivatives exclusively with Microchip products. It is your
* responsibility to comply with third party license terms applicable to your
* use of third party software (including open source software) that may
* accompany Microchip software.
*
* THIS SOFTWARE IS SUPPLIED BY MICROCHIP "AS IS". NO WARRANTIES, WHETHER
* EXPRESS, IMPLIED OR STATUTORY, APPLY TO THIS SOFTWARE, INCLUDING ANY IMPLIED
* WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY, AND FITNESS FOR A
* PARTICULAR PURPOSE.
*
* IN NO EVENT WILL MICROCHIP BE LIABLE FOR ANY INDIRECT, SPECIAL, PUNITIVE,
* INCIDENTAL OR CONSEQUENTIAL LOSS, DAMAGE, COST OR EXPENSE OF ANY KIND
* WHATSOEVER RELATED TO THE SOFTWARE, HOWEVER CAUSED, EVEN IF MICROCHIP HAS
* BEEN ADVISED OF THE POSSIBILITY OR THE DAMAGES ARE FORESEEABLE. TO THE
* FULLEST EXTENT ALLOWED BY LAW, MICROCHIP'S TOTAL LIABILITY ON ALL CLAIMS IN
* ANY WAY RELATED TO THIS SOFTWARE WILL NOT EXCEED THE AMOUNT OF FEES, IF ANY,
* THAT YOU HAVE PAID DIRECTLY TO MICROCHIP FOR THIS SOFTWARE.
*****************************************************************************"""
###################################################################################################
########################################## Callbacks #############################################
###################################################################################################
def updateSupcConfigVisibleProperty(symbol, event):
symbol.setVisible(event["value"])
def updateBOD33PrescalerVisibleProperty(symbol, event):
if supcSym_BOD33_STDBYCFG.getValue() == 1 or supcSym_BOD33_RUNHIB.getValue() == True or supcSym_BOD33_RUNBKUP.getValue() == True:
symbol.setVisible(True)
else:
symbol.setVisible(False)
def updateVrefVisibleProperty(symbol, event):
if supcSym_VREF_VREFOE.getValue() == True and supcSym_VREF_ONDEMAND.getValue() == False:
symbol.setVisible(False)
else:
symbol.setVisible(True)
def interruptControl(symbol, event):
Database.setSymbolValue("core", InterruptVector, event["value"], 2)
Database.setSymbolValue("core", InterruptHandlerLock, event["value"], 2)
if event["value"] == True:
Database.setSymbolValue("core", InterruptHandler, supcInstanceName.getValue() + "_BODDET_InterruptHandler", 2)
else:
Database.setSymbolValue("core", InterruptHandler, supcInstanceName.getValue() + "_BODDET_Handler", 2)
###################################################################################################
########################################## Component #############################################
###################################################################################################
def instantiateComponent(supcComponent):
global supcSym_BOD33_STDBYCFG
global supcSym_BOD33_RUNHIB
global supcSym_BOD33_RUNBKUP
global supcSym_VREF_VREFOE
global supcSym_VREF_ONDEMAND
global supcInstanceName
global InterruptVector
global InterruptHandler
global InterruptHandlerLock
global supcSym_INTENSET
supcInstanceName = supcComponent.createStringSymbol("SUPC_INSTANCE_NAME", None)
supcInstanceName.setVisible(False)
supcInstanceName.setDefaultValue(supcComponent.getID().upper())
#BOD33 Menu
supcSym_BOD33_Menu= supcComponent.createMenuSymbol("BOD33_MENU", None)
supcSym_BOD33_Menu.setLabel("VDD Brown-Out Detector (BOD33) Configuration")
#BOD33 interrupt mode
supcSym_INTENSET = supcComponent.createBooleanSymbol("SUPC_INTERRUPT_ENABLE", supcSym_BOD33_Menu)
supcSym_INTENSET.setLabel("Enable BOD Interrupt")
supcSym_INTENSET.setDefaultValue(False)
# Interrupt Warning status
supcSym_IntEnComment = supcComponent.createCommentSymbol("SUPC_INTERRUPT_ENABLE_COMMENT", supcSym_BOD33_Menu)
supcSym_IntEnComment.setVisible(False)
supcSym_IntEnComment.setLabel("Warning!!! SUPC Interrupt is Disabled in Interrupt Manager")
supcSym_IntEnComment.setDependencies(interruptControl, ["SUPC_INTERRUPT_ENABLE"])
#BOD33 RUNHIB
supcSym_BOD33_RUNHIB = supcComponent.createBooleanSymbol("SUPC_BOD33_RUNHIB", supcSym_BOD33_Menu)
supcSym_BOD33_RUNHIB.setLabel("Run in Hibernate Mode")
supcSym_BOD33_RUNHIB.setDescription("Configures BOD33 operation in Hibernate Sleep Mode")
supcSym_BOD33_RUNHIB.setDefaultValue(False)
#BOD33 RUNBKUP
supcSym_BOD33_RUNBKUP = supcComponent.createBooleanSymbol("SUPC_BOD33_RUNBKUP", supcSym_BOD33_Menu)
supcSym_BOD33_RUNBKUP.setLabel("Run in Backup Mode")
supcSym_BOD33_RUNBKUP.setDescription("Configures BOD33 operation in Backup Sleep Mode")
supcSym_BOD33_RUNBKUP.setDefaultValue(False)
#BOD33 RUNSTDBY
supcSym_BOD33_RUNSTDBY = supcComponent.createBooleanSymbol("SUPC_BOD33_RUNSTDBY", supcSym_BOD33_Menu)
supcSym_BOD33_RUNSTDBY.setLabel("Run in Standby Mode")
supcSym_BOD33_RUNSTDBY.setDescription("Configures BOD33 operation in Standby Sleep Mode")
supcSym_BOD33_RUNSTDBY.setDefaultValue(False)
#BOD33 STDBYCFG mode
supcSym_BOD33_STDBYCFG = supcComponent.createKeyValueSetSymbol("SUPC_BOD33_STDBYCFG", supcSym_BOD33_Menu)
supcSym_BOD33_STDBYCFG.setLabel("Select Standby Mode Operation")
supcSym_BOD33_STDBYCFG.setDescription("Configures whether BOD33 should operate in continuous or sampling mode in Standby Sleep Mode")
supcSym_BOD33_STDBYCFG.addKey("CONT_MODE", "0", "Continuous Mode")
supcSym_BOD33_STDBYCFG.addKey("SAMP_MODE", "1", "Sampling Mode")
supcSym_BOD33_STDBYCFG.setDefaultValue(0)
supcSym_BOD33_STDBYCFG.setOutputMode("Value")
supcSym_BOD33_STDBYCFG.setDisplayMode("Description")
supcSym_BOD33_STDBYCFG.setVisible(False)
supcSym_BOD33_STDBYCFG.setDependencies(updateSupcConfigVisibleProperty, ["SUPC_BOD33_RUNSTDBY"])
#BOD33 PSEL
supcSym_BOD33_PSEL = supcComponent.createKeyValueSetSymbol("SUPC_BOD33_PSEL", supcSym_BOD33_Menu)
supcSym_BOD33_PSEL.setLabel("Select Prescaler for Sampling Clock")
supcSym_BOD33_PSEL.setDescription("Configures the sampling clock prescaler when BOD33 is operating in sampling Mode")
supcSym_BOD33_PSEL.setVisible(False)
supcSym_BOD33_PSEL.setDependencies(updateBOD33PrescalerVisibleProperty, ["SUPC_BOD33_STDBYCFG", "SUPC_BOD33_RUNHIB", "SUPC_BOD33_RUNBKUP"])
supcBOD33PselNode = ATDF.getNode("/avr-tools-device-file/modules/module@[name=\"SUPC\"]/value-group@[name=\"SUPC_BOD33__PSEL\"]")
supcBOD33PselValues = []
supcBOD33PselValues = supcBOD33PselNode.getChildren()
#PSEL value 0 is not usable in sampling mode. Thus the loop starts from 1.
for index in range (1, len(supcBOD33PselValues)):
supcBOD33PselKeyName = supcBOD33PselValues[index].getAttribute("name")
supcBOD33PselKeyDescription = supcBOD33PselValues[index].getAttribute("caption")
supcBOD33PselKeyValue = supcBOD33PselValues[index].getAttribute("value")
supcSym_BOD33_PSEL.addKey(supcBOD33PselKeyName, supcBOD33PselKeyValue, supcBOD33PselKeyDescription)
supcSym_BOD33_PSEL.setDefaultValue(0)
supcSym_BOD33_PSEL.setOutputMode("Value")
supcSym_BOD33_PSEL.setDisplayMode("Description")
#BOD Configuration comment
supcSym_BOD33_FuseComment = supcComponent.createCommentSymbol("SUPC_CONFIG_COMMENT", supcSym_BOD33_Menu)
supcSym_BOD33_FuseComment.setLabel("Note: Configure BOD33 Fuses using 'System' component")
#VREG Menu
supcSym_VREG_Menu= supcComponent.createMenuSymbol("VREG_MENU", None)
supcSym_VREG_Menu.setLabel("Voltage Regulator (VREG) Configuration")
#VREG RUNBKUP mode
supcSym_VREG_RUNBKUP = supcComponent.createKeyValueSetSymbol("SUPC_VREG_RUNBKUP", supcSym_VREG_Menu)
supcSym_VREG_RUNBKUP.setLabel("Main Voltage Regulator operation in backup sleep")
supcSym_VREG_RUNBKUP.setDescription("Selects Main Voltage Regulator operation in backup sleep")
supcSym_VREG_RUNBKUP.addKey("REG_OFF", "0", "Regulator stopped")
supcSym_VREG_RUNBKUP.addKey("REG_ON", "1", "Regulator not stopped")
supcSym_VREG_RUNBKUP.setDefaultValue(0)
supcSym_VREG_RUNBKUP.setOutputMode("Value")
supcSym_VREG_RUNBKUP.setDisplayMode("Description")
#VREG VESN
supcSym_VREG_VSEN = supcComponent.createBooleanSymbol("SUPC_VREG_VSEN", supcSym_VREG_Menu)
supcSym_VREG_VSEN.setLabel("Enable Voltage Scaling")
supcSym_VREG_VSEN.setDescription("Enable smooth transition of VDDCORE")
supcSym_VREG_VSEN.setDefaultValue(False)
#VREG VSPER
supcSym_VREG_VSPER = supcComponent.createIntegerSymbol("SUPC_VREG_VSPER", supcSym_VREG_Menu)
supcSym_VREG_VSPER.setLabel("Voltage Scaling Period")
supcSym_VREG_VSEN.setDescription("The time is ((2^VSPER) * T), where T is an internal period (typ 250 ns).")
supcSym_VREG_VSPER.setDefaultValue(0)
supcSym_VREG_VSPER.setMin(0)
supcSym_VREG_VSPER.setMax(7)
supcSym_VREG_VSPER.setVisible(False)
supcSym_VREG_VSPER.setDependencies(updateSupcConfigVisibleProperty, ["SUPC_VREG_VSEN"])
#VREF Menu
supcSym_VREF_Menu= supcComponent.createMenuSymbol("VREF_MENU", None)
supcSym_VREF_Menu.setLabel("Voltage Reference (VREF) Configuration")
supcSym_VREF_SEL = supcComponent.createKeyValueSetSymbol("SUPC_VREF_SEL", supcSym_VREF_Menu)
supcSym_VREF_SEL.setLabel("Voltage Reference value")
supcSym_VREF_SEL.setDescription("Select the Voltage Reference typical value")
supcVREFSelNode = ATDF.getNode("/avr-tools-device-file/modules/module@[name=\"SUPC\"]/value-group@[name=\"SUPC_VREF__SEL\"]")
supcVREFSelValues = []
supcVREFSelValues = supcVREFSelNode.getChildren()
for index in range (0, len(supcVREFSelValues)):
supcVREFSelKeyName = supcVREFSelValues[index].getAttribute("name")
supcVREFSelKeyDescription = supcVREFSelValues[index].getAttribute("caption")
supcVREFSelKeyValue = supcVREFSelValues[index].getAttribute("value")
supcSym_VREF_SEL.addKey(supcVREFSelKeyName, supcVREFSelKeyValue, supcVREFSelKeyDescription)
supcSym_VREF_SEL.setDefaultValue(0)
supcSym_VREF_SEL.setOutputMode("Value")
supcSym_VREF_SEL.setDisplayMode("Description")
#VREF ONDEMAND mode
supcSym_VREF_ONDEMAND = supcComponent.createBooleanSymbol("SUPC_VREF_ONDEMAND", supcSym_VREF_Menu)
supcSym_VREF_ONDEMAND.setLabel("Enable On demand")
supcSym_VREF_ONDEMAND.setDescription("If this option is enabled, the voltage reference is disabled when no peripheral is requesting it.")
supcSym_VREF_ONDEMAND.setDefaultValue(False)
#VREF RUNSTDBY mode
supcSym_VREF_RUNSTDBY = supcComponent.createBooleanSymbol("SUPC_VREF_RUNSTDBY", supcSym_VREF_Menu)
supcSym_VREF_RUNSTDBY.setLabel("Enable Run in Standby")
supcSym_VREF_RUNSTDBY.setDescription("Enable VREF operation in Standby Sleep Mode")
#VREF VREFOE
supcSym_VREF_VREFOE = supcComponent.createBooleanSymbol("SUPC_VREF_VREFOE", supcSym_VREF_Menu)
supcSym_VREF_VREFOE.setLabel("Enable VREF output")
supcSym_VREF_VREFOE.setDescription("Enable VREF connection to ADC. If ONDEMAND is 0 and VREF is enabled, Temperature Sensor cannot be used")
supcSym_VREF_VREFOE.setDefaultValue(False)
#VREF TSEN
supcSym_VREF_TSEN = supcComponent.createBooleanSymbol("SUPC_VREF_TSEN", supcSym_VREF_Menu)
supcSym_VREF_TSEN.setLabel("Enable Temperature Sensor")
supcSym_VREF_TSEN.setDescription("Enable Temperature Sensor connection to ADC")
supcSym_VREF_TSEN.setDefaultValue(False)
supcSym_VREF_TSEN.setDependencies(updateVrefVisibleProperty, ["SUPC_VREF_ONDEMAND", "SUPC_VREF_VREFOE"])
#BBPS Menu
supcSym_BBPS_Menu= supcComponent.createMenuSymbol("SUPC_BBPS", None)
supcSym_BBPS_Menu.setLabel("Battery Backup Power Switch Configuraiton")
#BBPS supply switching
supcSym_BBPS = supcComponent.createBooleanSymbol("SUPC_BBPS_WAKEEN", supcSym_BBPS_Menu)
supcSym_BBPS.setLabel("Wake Device on BBPS Switching")
supcSym_BBPS.setDescription("The device can be woken up when switched from battery backup power to Main Power.")
#SUPC Output pin configuration
#For pin names, refer 'Supply Controller Pinout' in Datasheet
supcSym_BKOUT_Menu= supcComponent.createMenuSymbol("SUPC_BKOUT", None)
supcSym_BKOUT_Menu.setLabel("SUPC Output pin configuraiton")
#SUPC Output pin 0
supcSym_BKOUT0 = supcComponent.createBooleanSymbol("SUPC_BKOUT_0", supcSym_BKOUT_Menu)
supcSym_BKOUT0.setLabel("Enable OUT0")
supcSym_BKOUT0.setDescription("OUT0 pin can be driven by SUPC. It can be toggled by SUPC, based on RTC Events")
supcSym_BKOUT0.setDefaultValue(False)
#RTCTGCL 0
supcSym_BKOUT_RTCTGL0 = supcComponent.createBooleanSymbol("SUPC_BKOUT_RTCTGCL0", supcSym_BKOUT0)
supcSym_BKOUT_RTCTGL0.setLabel("Toggle OUT0 on RTC Event")
supcSym_BKOUT_RTCTGL0.setDescription("OUT0 pin can be toggled by SUPC, based on RTC Events")
supcSym_BKOUT_RTCTGL0.setDependencies(updateSupcConfigVisibleProperty, ["SUPC_BKOUT_0"])
supcSym_BKOUT_RTCTGL0.setVisible(False)
#SUPC Output pin 1
supcSym_BKOUT1 = supcComponent.createBooleanSymbol("SUPC_BKOUT_1", supcSym_BKOUT_Menu)
supcSym_BKOUT1.setLabel("Enable OUT1")
supcSym_BKOUT1.setDescription("OUT1 pin can be driven by SUPC. It can be toggled by SUPC, based on RTC Events")
supcSym_BKOUT1.setDefaultValue(False)
#RTCTGCL 1
supcSym_BKOUT_RTCTGL1 = supcComponent.createBooleanSymbol("SUPC_BKOUT_RTCTGCL1", supcSym_BKOUT1)
supcSym_BKOUT_RTCTGL1.setLabel("Toggle OUT1 on RTC Event")
supcSym_BKOUT_RTCTGL1.setDescription("OUT1 pin can be toggled by SUPC, based on RTC Events")
supcSym_BKOUT_RTCTGL1.setDependencies(updateSupcConfigVisibleProperty, ["SUPC_BKOUT_1"])
supcSym_BKOUT_RTCTGL1.setVisible(False)
############################################################################
#### Dependency ####
############################################################################
InterruptVector = supcInstanceName.getValue() + "_BODDET_INTERRUPT_ENABLE"
InterruptHandler = supcInstanceName.getValue() + "_BODDET_INTERRUPT_HANDLER"
InterruptHandlerLock = supcInstanceName.getValue()+ "_BODDET_INTERRUPT_HANDLER_LOCK"
###################################################################################################
####################################### Code Generation ##########################################
###################################################################################################
configName = Variables.get("__CONFIGURATION_NAME")
supcSym_HeaderFile = supcComponent.createFileSymbol("SUPC_HEADER", None)
supcSym_HeaderFile.setSourcePath("../peripheral/supc_u2407/templates/plib_supc.h.ftl")
supcSym_HeaderFile.setOutputName("plib_"+supcInstanceName.getValue().lower()+".h")
supcSym_HeaderFile.setDestPath("/peripheral/supc/")
supcSym_HeaderFile.setProjectPath("config/" + configName + "/peripheral/supc/")
supcSym_HeaderFile.setType("HEADER")
supcSym_HeaderFile.setMarkup(True)
supcSym_SourceFile = supcComponent.createFileSymbol("SUPC_SOURCE", None)
supcSym_SourceFile.setSourcePath("../peripheral/supc_u2407/templates/plib_supc.c.ftl")
supcSym_SourceFile.setOutputName("plib_"+supcInstanceName.getValue().lower()+".c")
supcSym_SourceFile.setDestPath("/peripheral/supc/")
supcSym_SourceFile.setProjectPath("config/" + configName + "/peripheral/supc/")
supcSym_SourceFile.setType("SOURCE")
supcSym_SourceFile.setMarkup(True)
supcSym_SystemInitFile = supcComponent.createFileSymbol("SUPC_SYS_INT", None)
supcSym_SystemInitFile.setType("STRING")
supcSym_SystemInitFile.setOutputName("core.LIST_SYSTEM_INIT_C_SYS_INITIALIZE_PERIPHERALS")
supcSym_SystemInitFile.setSourcePath("../peripheral/supc_u2407/templates/system/initialization.c.ftl")
supcSym_SystemInitFile.setMarkup(True)
supcSym_SystemDefFile = supcComponent.createFileSymbol("SUPC_SYS_DEF", None)
supcSym_SystemDefFile.setType("STRING")
supcSym_SystemDefFile.setOutputName("core.LIST_SYSTEM_DEFINITIONS_H_INCLUDES")
supcSym_SystemDefFile.setSourcePath("../peripheral/supc_u2407/templates/system/definitions.h.ftl")
supcSym_SystemDefFile.setMarkup(True)
|
# encoding: utf-8
# module System.Linq.Dynamic calls itself Dynamic
# from Wms.RemotingImplementation,Version=1.23.1.0,Culture=neutral,PublicKeyToken=null
# by generator 1.145
# no doc
# no important
# no functions
# classes
class DynamicClass(object):
# no doc
def ZZZ(self):
"""hardcoded/mock instance of the class"""
return DynamicClass()
instance=ZZZ()
"""hardcoded/returns an instance of the class"""
def ToString(self):
""" ToString(self: DynamicClass) -> str """
pass
class DynamicExpression(object):
# no doc
def ZZZ(self):
"""hardcoded/mock instance of the class"""
return DynamicExpression()
instance=ZZZ()
"""hardcoded/returns an instance of the class"""
@staticmethod
def CreateClass(properties):
"""
CreateClass(*properties: Array[DynamicProperty]) -> Type
CreateClass(properties: IEnumerable[DynamicProperty]) -> Type
"""
pass
@staticmethod
def Parse(resultType,expression,values):
""" Parse(resultType: Type,expression: str,*values: Array[object]) -> Expression """
pass
@staticmethod
def ParseLambda(*__args):
"""
ParseLambda(itType: Type,resultType: Type,expression: str,*values: Array[object]) -> LambdaExpression
ParseLambda(parameters: Array[ParameterExpression],resultType: Type,expression: str,*values: Array[object]) -> LambdaExpression
ParseLambda[(T,S)](expression: str,*values: Array[object]) -> Expression[Func[T,S]]
"""
pass
__all__=[
'CreateClass',
'Parse',
'ParseLambda',
]
class DynamicProperty(object):
""" DynamicProperty(name: str,type: Type) """
def ZZZ(self):
"""hardcoded/mock instance of the class"""
return DynamicProperty()
instance=ZZZ()
"""hardcoded/returns an instance of the class"""
@staticmethod
def __new__(self,name,type):
""" __new__(cls: type,name: str,type: Type) """
pass
Name=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: Name(self: DynamicProperty) -> str
"""
Type=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: Type(self: DynamicProperty) -> Type
"""
class DynamicQueryable(object):
# no doc
def ZZZ(self):
"""hardcoded/mock instance of the class"""
return DynamicQueryable()
instance=ZZZ()
"""hardcoded/returns an instance of the class"""
@staticmethod
def Any(source):
""" Any(source: IQueryable) -> bool """
pass
@staticmethod
def Count(source):
""" Count(source: IQueryable) -> int """
pass
@staticmethod
def GroupBy(source,keySelector,elementSelector,values):
""" GroupBy(source: IQueryable,keySelector: str,elementSelector: str,*values: Array[object]) -> IQueryable """
pass
@staticmethod
def OrderBy(source,ordering,values):
"""
OrderBy[T](source: IQueryable[T],ordering: str,*values: Array[object]) -> IQueryable[T]
OrderBy(source: IQueryable,ordering: str,*values: Array[object]) -> IQueryable
"""
pass
@staticmethod
def Select(source,selector,values):
""" Select(source: IQueryable,selector: str,*values: Array[object]) -> IQueryable """
pass
@staticmethod
def Skip(source,count):
""" Skip(source: IQueryable,count: int) -> IQueryable """
pass
@staticmethod
def Take(source,count):
""" Take(source: IQueryable,count: int) -> IQueryable """
pass
@staticmethod
def Where(source,predicate,values):
"""
Where[T](source: IQueryable[T],predicate: str,*values: Array[object]) -> IQueryable[T]
Where(source: IQueryable,predicate: str,*values: Array[object]) -> IQueryable
"""
pass
__all__=[
'Any',
'Count',
'GroupBy',
'OrderBy',
'Select',
'Skip',
'Take',
'Where',
]
class ParseException(Exception):
""" ParseException(message: str,position: int) """
def ZZZ(self):
"""hardcoded/mock instance of the class"""
return ParseException()
instance=ZZZ()
"""hardcoded/returns an instance of the class"""
def ToString(self):
""" ToString(self: ParseException) -> str """
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
@staticmethod
def __new__(self,message,position):
""" __new__(cls: type,message: str,position: int) """
pass
def __str__(self,*args):
pass
Position=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Get: Position(self: ParseException) -> int
"""
SerializeObjectState=None
|
"""
This problem was asked by Stripe.
Given an array of integers, find the first missing positive integer in linear time and constant space. In other words,
find the lowest positive integer that does not exist in the array. The array can contain duplicates and
negative numbers as well.
For example, the input [3, 4, -1, 1] should give 2. The input [1, 2, 0] should give 3.
You can modify the input array in-place.
"""
# i really had no clue how to do it in linear time and constant space, here are some answers, though:
# https://stackoverflow.com/questions/51346136/given-an-array-of-integers-find-the-first-missing-positive-integer-in-linear-ti
# using the indices does the trick
def lowest_integer(numbers):
min_number = min(numbers)
max_number = max(numbers)
if (min_number > 1):
return 1
else:
lowest_integer = max_number + 1
"""
kudos to pmcarpan from stackoverflow:
Assuming the array can be modified,
We divide the array into 2 parts such that the first part consists of only positive numbers. Say we have the starting index as 0 and the ending index as end(exclusive).
We traverse the array from index 0 to end. We take the absolute value of the element at that index - say the value is x.
If x > end we do nothing.
If not, we make the sign of the element at index x-1 negative. (Clarification: We do not toggle the sign. If the value is positive, it becomes negative. If it is negative, it remains negative. In pseudo code, this would be something like if (arr[x-1] > 0) arr[x-1] = -arr[x-1] and not arr[x-1] = -arr[x-1].)
Finally, we traverse the array once more from index 0 to end. In case we encounter a positive element at some index, we output index + 1. This is the answer. However, if we do not encounter any positive element, it means that integers 1 to end occur in the array. We output end + 1.
It can also be the case that all the numbers are non-positive making end = 0. The output end + 1 = 1 remains correct.
All the steps can be done in O(n) time and using O(1) space.
Example:
Initial Array: 1 -1 -5 -3 3 4 2 8
Step 1 partition: 1 8 2 4 3 | -3 -5 -1, end = 5
In step 2 we change the signs of the positive numbers to keep track of which integers have already occurred. For example, here array[2] = -2 < 0, it suggests that 2 + 1 = 3 has already occurred in the array. Basically, we change the value of the element having index i to negative if i+1 is in the array.
Step 2 Array changes to: -1 -8 -2 -4 3 | -3 -5 -1
In step 3, if some value array[index] is positive, it means that we did not find any integer of value index + 1 in step 2.
Step 3: Traversing from index 0 to end, we find array[4] = 3 > 0
The answer is 4 + 1 = 5
"""
|
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 28 15:57:01 2014
Reference URL: http://carina.fcaglp.unlp.edu.ar/ida/archivos/tabla_constantes.pdf
@author: yang
"""
# ---- Universal constants
# universal gravitational constant: N/m^2/kg^{-2}
G = 6.67e-11
# ---- Earth
# acceleration due to gravity at sea level: m/s^2
g = 9.81
# Radias of the Earth: m
Re = 6.37e6
# rotation rate of the Earth: s^{-1}
Omega = 7.292e-5
# ---- Air
# Typical density of air at sea level: kg/m^3
rho_a = 1.25
# gas constant for dry air: J/K/kg
Rd = 287
# specific heat of dry air at constant pressure: J/K/kg
cp = 1004
# specific heat of dry air at constant volume: J/K/kg
cv = 717
# ---- Water
# density of liquid water at 0^0C: kg/m^3
rho_w = 1e3
# gas constant for water vapor
Rv = 461
# latent heat of vaporization at 0^0C: J/kg
Lv = 2.50e6
# molecular weight ratio of H2O to dry air
epsilon = 0.622
# ---- Others
T0 = 273.15
|
#
# PySNMP MIB module ATM-TC-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ATM-TC-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:04:02 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")
ValueSizeConstraint, ValueRangeConstraint, ConstraintsUnion, SingleValueConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "ValueRangeConstraint", "ConstraintsUnion", "SingleValueConstraint", "ConstraintsIntersection")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
ObjectIdentity, NotificationType, Integer32, ModuleIdentity, TimeTicks, Gauge32, Bits, MibScalar, MibTable, MibTableRow, MibTableColumn, Counter64, iso, MibIdentifier, IpAddress, Counter32, Unsigned32, mib_2 = mibBuilder.importSymbols("SNMPv2-SMI", "ObjectIdentity", "NotificationType", "Integer32", "ModuleIdentity", "TimeTicks", "Gauge32", "Bits", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Counter64", "iso", "MibIdentifier", "IpAddress", "Counter32", "Unsigned32", "mib-2")
TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString")
atmTCMIB = ModuleIdentity((1, 3, 6, 1, 2, 1, 37, 3))
if mibBuilder.loadTexts: atmTCMIB.setLastUpdated('9810190200Z')
if mibBuilder.loadTexts: atmTCMIB.setOrganization('IETF AToMMIB Working Group')
class AtmAddr(TextualConvention, OctetString):
status = 'current'
displayHint = '1x'
subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(0, 40)
class AtmConnCastType(TextualConvention, Integer32):
status = 'current'
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3))
namedValues = NamedValues(("p2p", 1), ("p2mpRoot", 2), ("p2mpLeaf", 3))
class AtmConnKind(TextualConvention, Integer32):
status = 'current'
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))
namedValues = NamedValues(("pvc", 1), ("svcIncoming", 2), ("svcOutgoing", 3), ("spvcInitiator", 4), ("spvcTarget", 5))
class AtmIlmiNetworkPrefix(TextualConvention, OctetString):
reference = 'ATM Forum, Integrated Local Management Interface (ILMI) Specification, Version 4.0, af-ilmi-0065.000, September 1996, Section 9 ATM Forum, ATM User-Network Interface Signalling Specification, Version 4.0 (UNI 4.0), af-sig-0061.000, June 1996, Section 3'
status = 'current'
subtypeSpec = OctetString.subtypeSpec + ConstraintsUnion(ValueSizeConstraint(8, 8), ValueSizeConstraint(13, 13), )
class AtmInterfaceType(TextualConvention, Integer32):
status = 'current'
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13))
namedValues = NamedValues(("other", 1), ("autoConfig", 2), ("ituDss2", 3), ("atmfUni3Dot0", 4), ("atmfUni3Dot1", 5), ("atmfUni4Dot0", 6), ("atmfIispUni3Dot0", 7), ("atmfIispUni3Dot1", 8), ("atmfIispUni4Dot0", 9), ("atmfPnni1Dot0", 10), ("atmfBici2Dot0", 11), ("atmfUniPvcOnly", 12), ("atmfNniPvcOnly", 13))
class AtmServiceCategory(TextualConvention, Integer32):
reference = 'ATM Forum Traffic Management Specification, Version 4.0, af-tm-0056.000, June 1996.'
status = 'current'
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6))
namedValues = NamedValues(("other", 1), ("cbr", 2), ("rtVbr", 3), ("nrtVbr", 4), ("abr", 5), ("ubr", 6))
class AtmSigDescrParamIndex(TextualConvention, Integer32):
status = 'current'
subtypeSpec = Integer32.subtypeSpec + ValueRangeConstraint(0, 2147483647)
class AtmTrafficDescrParamIndex(TextualConvention, Integer32):
status = 'current'
subtypeSpec = Integer32.subtypeSpec + ValueRangeConstraint(0, 2147483647)
class AtmVcIdentifier(TextualConvention, Integer32):
status = 'current'
subtypeSpec = Integer32.subtypeSpec + ValueRangeConstraint(0, 65535)
class AtmVpIdentifier(TextualConvention, Integer32):
status = 'current'
subtypeSpec = Integer32.subtypeSpec + ValueRangeConstraint(0, 4095)
class AtmVorXAdminStatus(TextualConvention, Integer32):
status = 'current'
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2))
namedValues = NamedValues(("up", 1), ("down", 2))
class AtmVorXLastChange(TextualConvention, TimeTicks):
status = 'current'
class AtmVorXOperStatus(TextualConvention, Integer32):
status = 'current'
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3))
namedValues = NamedValues(("up", 1), ("down", 2), ("unknown", 3))
atmTrafficDescriptorTypes = MibIdentifier((1, 3, 6, 1, 2, 1, 37, 1, 1))
atmObjectIdentities = MibIdentifier((1, 3, 6, 1, 2, 1, 37, 3, 1))
atmNoTrafficDescriptor = ObjectIdentity((1, 3, 6, 1, 2, 1, 37, 1, 1, 1))
if mibBuilder.loadTexts: atmNoTrafficDescriptor.setStatus('deprecated')
atmNoClpNoScr = ObjectIdentity((1, 3, 6, 1, 2, 1, 37, 1, 1, 2))
if mibBuilder.loadTexts: atmNoClpNoScr.setStatus('current')
atmClpNoTaggingNoScr = ObjectIdentity((1, 3, 6, 1, 2, 1, 37, 1, 1, 3))
if mibBuilder.loadTexts: atmClpNoTaggingNoScr.setStatus('deprecated')
atmClpTaggingNoScr = ObjectIdentity((1, 3, 6, 1, 2, 1, 37, 1, 1, 4))
if mibBuilder.loadTexts: atmClpTaggingNoScr.setStatus('deprecated')
atmNoClpScr = ObjectIdentity((1, 3, 6, 1, 2, 1, 37, 1, 1, 5))
if mibBuilder.loadTexts: atmNoClpScr.setStatus('current')
atmClpNoTaggingScr = ObjectIdentity((1, 3, 6, 1, 2, 1, 37, 1, 1, 6))
if mibBuilder.loadTexts: atmClpNoTaggingScr.setStatus('current')
atmClpTaggingScr = ObjectIdentity((1, 3, 6, 1, 2, 1, 37, 1, 1, 7))
if mibBuilder.loadTexts: atmClpTaggingScr.setStatus('current')
atmClpNoTaggingMcr = ObjectIdentity((1, 3, 6, 1, 2, 1, 37, 1, 1, 8))
if mibBuilder.loadTexts: atmClpNoTaggingMcr.setStatus('current')
atmClpTransparentNoScr = ObjectIdentity((1, 3, 6, 1, 2, 1, 37, 1, 1, 9))
if mibBuilder.loadTexts: atmClpTransparentNoScr.setStatus('current')
atmClpTransparentScr = ObjectIdentity((1, 3, 6, 1, 2, 1, 37, 1, 1, 10))
if mibBuilder.loadTexts: atmClpTransparentScr.setStatus('current')
atmNoClpTaggingNoScr = ObjectIdentity((1, 3, 6, 1, 2, 1, 37, 1, 1, 11))
if mibBuilder.loadTexts: atmNoClpTaggingNoScr.setStatus('current')
atmNoClpNoScrCdvt = ObjectIdentity((1, 3, 6, 1, 2, 1, 37, 1, 1, 12))
if mibBuilder.loadTexts: atmNoClpNoScrCdvt.setStatus('current')
atmNoClpScrCdvt = ObjectIdentity((1, 3, 6, 1, 2, 1, 37, 1, 1, 13))
if mibBuilder.loadTexts: atmNoClpScrCdvt.setStatus('current')
atmClpNoTaggingScrCdvt = ObjectIdentity((1, 3, 6, 1, 2, 1, 37, 1, 1, 14))
if mibBuilder.loadTexts: atmClpNoTaggingScrCdvt.setStatus('current')
atmClpTaggingScrCdvt = ObjectIdentity((1, 3, 6, 1, 2, 1, 37, 1, 1, 15))
if mibBuilder.loadTexts: atmClpTaggingScrCdvt.setStatus('current')
mibBuilder.exportSymbols("ATM-TC-MIB", atmNoTrafficDescriptor=atmNoTrafficDescriptor, PYSNMP_MODULE_ID=atmTCMIB, AtmInterfaceType=AtmInterfaceType, AtmVcIdentifier=AtmVcIdentifier, atmClpTaggingScr=atmClpTaggingScr, AtmVpIdentifier=AtmVpIdentifier, atmObjectIdentities=atmObjectIdentities, atmNoClpNoScrCdvt=atmNoClpNoScrCdvt, AtmIlmiNetworkPrefix=AtmIlmiNetworkPrefix, atmClpNoTaggingMcr=atmClpNoTaggingMcr, AtmServiceCategory=AtmServiceCategory, atmNoClpScrCdvt=atmNoClpScrCdvt, AtmVorXAdminStatus=AtmVorXAdminStatus, AtmVorXLastChange=AtmVorXLastChange, AtmSigDescrParamIndex=AtmSigDescrParamIndex, AtmAddr=AtmAddr, atmNoClpScr=atmNoClpScr, atmTrafficDescriptorTypes=atmTrafficDescriptorTypes, AtmVorXOperStatus=AtmVorXOperStatus, atmClpTaggingScrCdvt=atmClpTaggingScrCdvt, AtmTrafficDescrParamIndex=AtmTrafficDescrParamIndex, AtmConnKind=AtmConnKind, atmClpTaggingNoScr=atmClpTaggingNoScr, AtmConnCastType=AtmConnCastType, atmClpNoTaggingScr=atmClpNoTaggingScr, atmNoClpTaggingNoScr=atmNoClpTaggingNoScr, atmClpNoTaggingScrCdvt=atmClpNoTaggingScrCdvt, atmNoClpNoScr=atmNoClpNoScr, atmClpNoTaggingNoScr=atmClpNoTaggingNoScr, atmTCMIB=atmTCMIB, atmClpTransparentScr=atmClpTransparentScr, atmClpTransparentNoScr=atmClpTransparentNoScr)
|
class Member(object):
"""
A member of the etcd cluster.
:ivar id: ID of the member
:ivar name: human-readable name of the member
:ivar peer_urls: list of URLs the member exposes to the cluster for
communication
:ivar client_urls: list of URLs the member exposes to clients for
communication
"""
def __init__(self, id, name, peer_urls, client_urls, etcd_client=None):
self.id = id
self.name = name
self.peer_urls = peer_urls
self.client_urls = client_urls
self._etcd_client = etcd_client
def __str__(self):
return ('Member {id}: peer urls: {peer_urls}, client '
'urls: {client_urls}'.format(id=self.id,
peer_urls=self.peer_urls,
client_urls=self.client_urls))
def remove(self):
"""Remove this member from the cluster."""
self._etcd_client.remove_member(self.id)
def update(self, peer_urls):
"""
Update the configuration of this member.
:param peer_urls: new list of peer urls the member will use to
communicate with the cluster
"""
self._etcd_client.update_member(self.id, peer_urls)
@property
def active_alarms(self):
"""Get active alarms of the member.
:returns: Alarms
"""
return self._etcd_client.list_alarms(member_id=self.id)
|
def expectOne(vals):
assert len(vals) == 1
return vals[0]
|
class CSVDumper:
@classmethod
def dump(self, matrix, encoding='sjis'):
rows = []
for row in matrix:
fields = []
for field in row:
if field is None:
fields.append('')
elif str(field).isdigit():
fields.append(str(field))
else:
fields.append('"{0}"'.format(str(field).replace('"', '""')))
rows.append(','.join(fields))
return '\n'.join(rows).encode(encoding, 'ignore')
|
'''Hercy wants to save money for his first car. He puts money
in the Leetcode bank every day.
He starts by putting in $1 on Monday, the first day. Every day from Tuesday to Sunday,
he will put in $1 more than the day before. On every subsequent Monday,
he will put in $1 more than the previous Monday.
Given n, return the total amount of money he will have in the
Leetcode bank at the end of the nth day.
Example 1:
Input: n = 4
Output: 10
Explanation: After the 4th day, the total is 1 + 2 + 3 + 4 = 10.
'''
class Lb:
def totalMoney(self, n: int) -> int:
x=0
carr=n//7
rem=n%7
for i in range (carr+1,rem+carr+1):
x+=i
for i in range(carr):
x += 7 * (i + 4)
return x
print(Lb().totalMoney(10))
print(Lb().totalMoney(100))
print(Lb().totalMoney(8))
print(Lb().totalMoney(3))
print(Lb().totalMoney(900))
print(Lb().totalMoney(128))
|
# Radix Sort is an improvement over Counting Sort
# Counting Sort is highly inefficient with large ranges
# Radix sort sorts digit by digit from least to most significant digit.
# It can be imagined as a bucket sort based on place values.
def radixSort(array, base=10):
# Get the maximum in the array to find the maximum number of digits
# Since we are sorting digit wise
m = max(array)
# Initially we start by sorting the least significant digit
placeValue = 1
# We loop till all digits have been sorted
while m/placeValue > 0:
# Apply digit wise counting Sort
# Find the occurence of each digit and store that value
occurence = [0]*base
for element in array:
occurence[int((element/placeValue) % base)] += 1
# Since occurence array is already sorted by index, the actual position of the element will
# be the next of sum of all occurences before it
for i in range(1, base):
occurence[i] += occurence[i-1]
temp = [0]*len(array)
# Traverse array backwards to count down occurences
for i in range(len(array)-1, -1, -1):
pos = array[i]/placeValue
temp[occurence[int(pos % base)]-1] = array[i]
occurence[int(pos % base)] -= 1
# Copy temproary array to original one
for i, val in enumerate(temp):
array[i] = val
# The next digit will be the immediate next placevalue [tens, hundreds in the decimal system]
placeValue *= base
return array
# Driver code
a = [40, 122, 1, 5, 28, 99]
print(radixSort(a))
# Since radix sort is not a comparison based one, the time complexity is linear
# Worst case: O(d(n+b))
# Where n is the len of array, d is the number of maximum digits and b is the base
|
'''
-- Make required Folder & open Integrated CMD in it !
In CMD type :
[To make exact copy of system base python but no modules included!]
-- pip install virtualenv
-- virtualenv [nameOfSubFolderInRequiredFolder] // Here I used VirtualEnvironment
--OR--
To make exact copy of system base python[with Modules] :
-- virtualenv --system-site-packages [nameOfSubFolderInRequiredFolder] // Here I used VirtualEnvironment
To activate :
-- .\[nameOfSubFolderInRequiredFolder]\Scripts\activate // Here I used VirtualEnvironment
To deactivate :
-- deactivate
To get guide in Virtual Environment :
-- pip freeze > requirements.txt
To install modules mentioned in requirements.txt :
-- pip install -r .\requirements.txt
'''
|
# *Exercรญcio Python 14: Escreva um programa que converta uma temperatura digitando em graus Celsius e converta para graus Fahrenheit.
celsius = float(input('Insira a temperatura em Celsius: '))
faren = 9 * celsius / 5 + 32
print('A temperatura {:.0f} em Fahrenheit รฉ {:.0f}'.format(celsius, faren))
|
ME = '''
query getMe {
me {
username
isStaff
isSuperuser
isAgreed
profile {
id
oauthType
name
nameKo
nameEn
bio
bioKo
bioEn
email
phone
organization
nationality
image
avatarUrl
}
}
}
'''
UPDATE_PROFILE = '''
mutation UpdateProfile($data: ProfileInput!) {
updateProfile(data: $data) {
profile {
id
oauthType
name
nameKo
nameEn
bio
bioKo
bioEn
email
phone
organization
nationality
image
avatarUrl
}
}
}
'''
UPDATE_AGREEMENT = '''
mutation UpdateAgreement($isPrivacyPolicy: Boolean, $isTermsOfService: Boolean) {
updateAgreement(isPrivacyPolicy: $isPrivacyPolicy, isTermsOfService: $isTermsOfService) {
isAgreedAll
user {
username
isStaff
isSuperuser
isAgreed
profile {
id
oauthType
name
nameKo
nameEn
bio
bioKo
bioEn
email
phone
organization
nationality
image
avatarUrl
}
}
}
}
'''
PATRONS = '''
query getPatrons {
patrons {
id
name
nameKo
nameEn
bio
bioKo
bioEn
organization
image
avatarUrl
}
}
'''
|
# Saber se algo รฉ numรฉrico, nรฃo pode colocar o tipo primitivo.
n = input('Digite algo: ')
print(n.isnumeric())
|
# -*- coding: utf-8 -*-
args = input().split()
n1, n2, n3 = list(map (int, args))
average = (lambda a, b, c: (a + b + c)/3)(n1, n2, n3)
result = (lambda av: "Approved" if av >= 6 else "Disapproved")
print(result(average))
|
# leetcode
class Solution:
def isPalindrome(self, s: str) -> bool:
s_cp = s.replace(" ", "").lower()
clean_s = ''
for l in s_cp:
# check if num
if ord(l) >= 48 and ord(l) <= 57:
clean_s += l
elif ord(l) >= 97 and ord(l) <= 122:
clean_s += l
return clean_s == clean_s[::-1]
|
'''
Two intervals i1, i2overlap if the following requirements are satisfied:
requirement 1: i1.end >= i2.start
requirement 2: i1.start <= i2.end
We preprocess the list by sorting intervals by starts increasingly.
In this way, requirement 2 i1.start <= i2.start < i2.end is promised.
We only have to compare i1.end with i2.start to see if requirement 1 is satisfied.
'''
def merge(intervals):
# Sort by first element in list children
intervals = sorted(intervals, key=lambda x: x[0])
result = []
for cur in intervals:
if len(result) < 1:
result.append(cur)
else:
prev = result[-1]
if prev[-1] >= cur[0]:
prev[-1] = max(prev[-1], cur[-1])
else:
result.append(cur)
return result
def merge_intervals2(intervals):
if not intervals or len(intervals) <=1:
return intervals
result = []
i = len(intervals)-1
while i >= 0:
arr = list(range(intervals[i][0], intervals[i][-1]+1))
k = 0
for j in range(1, len(intervals)):
if intervals[i-j][-1] in arr:
k +=1
if k > 0:
result.append([intervals[i-k][0],arr[-1]])
else:
result.append([arr[0], arr[-1]])
i = i-k-1
return list(reversed(result))
intervals = [[1,3],[2,6],[8,10],[15,18]]
intervals2 = [[1,4],[4,5]]
print(merge(intervals))
print(merge(intervals2))
print(merge2(intervals))
print(merge2(intervals2))
|
"""
110. Balanced Binary Tree
Given a binary tree, determine if it is height-balanced.
For this problem, a height-balanced binary tree is defined as:
a binary tree in which the left and right subtrees of every node differ in height by no more than 1.
Example 1:
Given the following tree [3,9,20,null,null,15,7]:
3
/ \
9 20
/ \
15 7
Return true.
Example 2:
Given the following tree [1,2,2,3,3,null,null,4,4]:
1
/ \
2 2
/ \
3 3
/ \
4 4
Return false.
"""
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isBalanced(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
def dfs(root):
if not root:
return 0, 1
l, res_l = dfs(root.left)
r, res_r = dfs(root.right)
if res_l and res_r and (-1 <= l-r <= 1):
res = 1
else:
res = 0
return max(l,r)+1, res
return dfs(root)[1] == 1
|
"""Utility to store int or float parameters with a label
The label is added merely for information: there is no
extra functionality associated with it.
The module has a factory class Parameter(value, label)
which returns either ParameterInt ot ParameterFloat
depending on type(value).
"""
class ParameterInt(int):
"""Integer parameter with a label"""
def __new__(cls, *args):
"""Arguements:
args[0] is the value
"""
return super(ParameterInt, cls).__new__(cls, args[0])
def __init__(self, value, label):
"""Arguments
value (integer): the value
label (string, Label, ...): associated label
"""
super(ParameterInt, self).__init__()
self.label = label
def __repr__(self):
"""Return string including the label"""
parameter = "value= {!s}, label= {!r}".format(self, self.label)
return "ParameterInt({!s})".format(parameter)
class ParameterFloat(float):
"""Real parameter with label"""
def __new__(cls, *args):
"""Arguments:
args[0] is the value
"""
return super(ParameterFloat, cls).__new__(cls, args[0])
def __init__(self, value, label):
"""Arguments
value (float): the value
label (string, Label, ...): a description
"""
super(ParameterFloat, self).__init__()
self.label = label
def __repr__(self):
"""Return a string including the label"""
parameter = "value= {!s}, label= {!r}".format(self, self.label)
return "ParameterFloat({!s})".format(parameter)
class Parameter(object):
"""A factory to return a Parameter of the correct type"""
def __new__(cls, value, label):
"""Arguments:
value (int or float)
label (string or Label)
"""
if isinstance(value, int):
return ParameterInt(value, label)
elif isinstance(value, float):
return ParameterFloat(value, label)
else:
raise TypeError("A Parameter is either int or float")
|
#
# PySNMP MIB module Nortel-Magellan-Passport-DataCollectionMIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Nortel-Magellan-Passport-DataCollectionMIB
# Produced by pysmi-0.3.4 at Wed May 1 14:26:47 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")
SingleValueConstraint, ValueRangeConstraint, ConstraintsUnion, ValueSizeConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ValueRangeConstraint", "ConstraintsUnion", "ValueSizeConstraint", "ConstraintsIntersection")
DisplayString, StorageType, RowStatus, Unsigned32, Integer32, Gauge32, Counter32 = mibBuilder.importSymbols("Nortel-Magellan-Passport-StandardTextualConventionsMIB", "DisplayString", "StorageType", "RowStatus", "Unsigned32", "Integer32", "Gauge32", "Counter32")
NonReplicated, EnterpriseDateAndTime, AsciiString = mibBuilder.importSymbols("Nortel-Magellan-Passport-TextualConventionsMIB", "NonReplicated", "EnterpriseDateAndTime", "AsciiString")
passportMIBs, components = mibBuilder.importSymbols("Nortel-Magellan-Passport-UsefulDefinitionsMIB", "passportMIBs", "components")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
MibScalar, MibTable, MibTableRow, MibTableColumn, ModuleIdentity, Bits, TimeTicks, iso, Integer32, Unsigned32, IpAddress, Counter64, Gauge32, Counter32, ObjectIdentity, MibIdentifier, NotificationType = mibBuilder.importSymbols("SNMPv2-SMI", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ModuleIdentity", "Bits", "TimeTicks", "iso", "Integer32", "Unsigned32", "IpAddress", "Counter64", "Gauge32", "Counter32", "ObjectIdentity", "MibIdentifier", "NotificationType")
TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString")
dataCollectionMIB = MibIdentifier((1, 3, 6, 1, 4, 1, 562, 2, 4, 2, 14))
col = MibIdentifier((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21))
colRowStatusTable = MibTable((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21, 1), )
if mibBuilder.loadTexts: colRowStatusTable.setStatus('mandatory')
if mibBuilder.loadTexts: colRowStatusTable.setDescription('This entry controls the addition and deletion of col components.')
colRowStatusEntry = MibTableRow((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21, 1, 1), ).setIndexNames((0, "Nortel-Magellan-Passport-DataCollectionMIB", "colIndex"))
if mibBuilder.loadTexts: colRowStatusEntry.setStatus('mandatory')
if mibBuilder.loadTexts: colRowStatusEntry.setDescription('A single entry in the table represents a single col component.')
colRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21, 1, 1, 1), RowStatus()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: colRowStatus.setStatus('mandatory')
if mibBuilder.loadTexts: colRowStatus.setDescription('This variable is used as the basis for SNMP naming of col components. These components can be added.')
colComponentName = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21, 1, 1, 2), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: colComponentName.setStatus('mandatory')
if mibBuilder.loadTexts: colComponentName.setDescription("This variable provides the component's string name for use with the ASCII Console Interface")
colStorageType = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21, 1, 1, 4), StorageType()).setMaxAccess("readonly")
if mibBuilder.loadTexts: colStorageType.setStatus('mandatory')
if mibBuilder.loadTexts: colStorageType.setDescription('This variable represents the storage type value for the col tables.')
colIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21, 1, 1, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5, 6))).clone(namedValues=NamedValues(("accounting", 0), ("alarm", 1), ("log", 2), ("debug", 3), ("scn", 4), ("trap", 5), ("stats", 6))))
if mibBuilder.loadTexts: colIndex.setStatus('mandatory')
if mibBuilder.loadTexts: colIndex.setDescription('This variable represents the index for the col tables.')
colProvTable = MibTable((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21, 10), )
if mibBuilder.loadTexts: colProvTable.setStatus('mandatory')
if mibBuilder.loadTexts: colProvTable.setDescription('This group specifies all of the provisioning data for a DCS Collector.')
colProvEntry = MibTableRow((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21, 10, 1), ).setIndexNames((0, "Nortel-Magellan-Passport-DataCollectionMIB", "colIndex"))
if mibBuilder.loadTexts: colProvEntry.setStatus('mandatory')
if mibBuilder.loadTexts: colProvEntry.setDescription('An entry in the colProvTable.')
colAgentQueueSize = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21, 10, 1, 1), Unsigned32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(0, 0), ValueRangeConstraint(20, 10000), ))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: colAgentQueueSize.setStatus('obsolete')
if mibBuilder.loadTexts: colAgentQueueSize.setDescription("This attribute has been replaced with the agentQueueSize attribute in the Lp Engineering DataStream Ov component. Upon migration, if the existing provisioned value of this attribute is the same as the system default for this type of data, no new components are added because the default is what the DataStream component already would be using. Otherwise, if the value is not the same as the system default, then for each Lp which is provisioned at the time of the migration, a DataStream is provisioned and the Ov's agentQueueSize is set to the non-default value.")
colStatsTable = MibTable((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21, 11), )
if mibBuilder.loadTexts: colStatsTable.setStatus('mandatory')
if mibBuilder.loadTexts: colStatsTable.setDescription('This group specifies the statistics operational attributes of the DCS Collector, Agent and Spooler components.')
colStatsEntry = MibTableRow((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21, 11, 1), ).setIndexNames((0, "Nortel-Magellan-Passport-DataCollectionMIB", "colIndex"))
if mibBuilder.loadTexts: colStatsEntry.setStatus('mandatory')
if mibBuilder.loadTexts: colStatsEntry.setDescription('An entry in the colStatsTable.')
colCurrentQueueSize = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21, 11, 1, 1), Gauge32().subtype(subtypeSpec=ValueRangeConstraint(0, 4294967295))).setMaxAccess("readonly")
if mibBuilder.loadTexts: colCurrentQueueSize.setStatus('mandatory')
if mibBuilder.loadTexts: colCurrentQueueSize.setDescription('This gauge contains the current number of records held by this DCS component.')
colRecordsRx = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21, 11, 1, 2), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: colRecordsRx.setStatus('mandatory')
if mibBuilder.loadTexts: colRecordsRx.setDescription('This counter contains the cumulative number of records received by a DCS component, from applications which send data to it, since the processor last restarted. This counter wraps to 0 when the maximum value is exceeded.')
colRecordsDiscarded = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21, 11, 1, 3), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: colRecordsDiscarded.setStatus('mandatory')
if mibBuilder.loadTexts: colRecordsDiscarded.setDescription('This is the cumulative number of records discarded by this DCS component since the processor last restarted. This counter wraps to 0 when the maximum value is exceeded.')
colTimesTable = MibTable((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21, 266), )
if mibBuilder.loadTexts: colTimesTable.setStatus('mandatory')
if mibBuilder.loadTexts: colTimesTable.setDescription('This attribute specifies the scheduled times at which data should be collected. Only accounting applications need the capability to generate data in this way. Setting this attribute for other streams has no effect. The user can enter the times in any order and duplicates are prevented at data entry. There is a limit of 24 entries, which is imposed at semantic check time. The collection times are triggered in chronological order. A semantic check error is issued if any 2 entries are less than 1 hour apart or if any 2 entries are more than 12 hours apart (which implies that if any entries are provided, there must be at least 2 entries). Note that by default (that is, in the absence of a provisioned schedule), a Virtual Circuit (VC) starts its own 12-hour accounting timer. If any collection times are provisioned here, then the Time- Of-Day-Accounting (TODA) method is used in place of 12-hour accounting. This is applicable to both Switched VCs and Permanent VCs.')
colTimesEntry = MibTableRow((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21, 266, 1), ).setIndexNames((0, "Nortel-Magellan-Passport-DataCollectionMIB", "colIndex"), (0, "Nortel-Magellan-Passport-DataCollectionMIB", "colTimesValue"))
if mibBuilder.loadTexts: colTimesEntry.setStatus('mandatory')
if mibBuilder.loadTexts: colTimesEntry.setDescription('An entry in the colTimesTable.')
colTimesValue = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21, 266, 1, 1), EnterpriseDateAndTime().subtype(subtypeSpec=ValueSizeConstraint(5, 5)).setFixedLength(5)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: colTimesValue.setStatus('mandatory')
if mibBuilder.loadTexts: colTimesValue.setDescription('This variable represents both the value and the index for the colTimesTable.')
colTimesRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21, 266, 1, 2), RowStatus()).setMaxAccess("writeonly")
if mibBuilder.loadTexts: colTimesRowStatus.setStatus('mandatory')
if mibBuilder.loadTexts: colTimesRowStatus.setDescription('This variable is used to control the addition and deletion of individual values of the colTimesTable.')
colLastTable = MibTable((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21, 275), )
if mibBuilder.loadTexts: colLastTable.setStatus('obsolete')
if mibBuilder.loadTexts: colLastTable.setDescription('Note: This was made obsolete in R4.1 (BD0108A). This attribute is used for Collector/stats and Collector/account. For statistics, when collection is turned off, or prior to the very first probe, the value is the empty list. Otherwise, this is the network time at which the last probe was sent out (that is, the last time that statistics were collected from, or at least reset by, the applications providing them). For accounting, when no entries exist in collectionTimes, or prior to the very first collection time, the value is the empty list. Otherwise, this is the network time at which the last time-of-day changeover occurred.')
colLastEntry = MibTableRow((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21, 275, 1), ).setIndexNames((0, "Nortel-Magellan-Passport-DataCollectionMIB", "colIndex"), (0, "Nortel-Magellan-Passport-DataCollectionMIB", "colLastValue"))
if mibBuilder.loadTexts: colLastEntry.setStatus('obsolete')
if mibBuilder.loadTexts: colLastEntry.setDescription('An entry in the colLastTable.')
colLastValue = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21, 275, 1, 1), EnterpriseDateAndTime().subtype(subtypeSpec=ValueSizeConstraint(19, 19)).setFixedLength(19)).setMaxAccess("readonly")
if mibBuilder.loadTexts: colLastValue.setStatus('obsolete')
if mibBuilder.loadTexts: colLastValue.setDescription('This variable represents both the value and the index for the colLastTable.')
colPeakTable = MibTable((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21, 279), )
if mibBuilder.loadTexts: colPeakTable.setStatus('mandatory')
if mibBuilder.loadTexts: colPeakTable.setDescription('This attribute specifies the length of the accounting peak water mark interval. It is at least one minute and at most 15 minutes long. An accounting peak water mark within a given accounting interval is the accounting count which occured during a peak water mark interval with the highest traffic. Peak water marks are used to determine traffic bursts. If no value is provisioned for this attribute value of 5 minutes is assumed. Peak water mark is only measured if attribute collectionTimes in Collector/account is provisioned.')
colPeakEntry = MibTableRow((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21, 279, 1), ).setIndexNames((0, "Nortel-Magellan-Passport-DataCollectionMIB", "colIndex"), (0, "Nortel-Magellan-Passport-DataCollectionMIB", "colPeakValue"))
if mibBuilder.loadTexts: colPeakEntry.setStatus('mandatory')
if mibBuilder.loadTexts: colPeakEntry.setDescription('An entry in the colPeakTable.')
colPeakValue = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21, 279, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 15))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: colPeakValue.setStatus('mandatory')
if mibBuilder.loadTexts: colPeakValue.setDescription('This variable represents both the value and the index for the colPeakTable.')
colPeakRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21, 279, 1, 2), RowStatus()).setMaxAccess("writeonly")
if mibBuilder.loadTexts: colPeakRowStatus.setStatus('mandatory')
if mibBuilder.loadTexts: colPeakRowStatus.setDescription('This variable is used to control the addition and deletion of individual values of the colPeakTable.')
colSp = MibIdentifier((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21, 2))
colSpRowStatusTable = MibTable((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21, 2, 1), )
if mibBuilder.loadTexts: colSpRowStatusTable.setStatus('mandatory')
if mibBuilder.loadTexts: colSpRowStatusTable.setDescription('This entry controls the addition and deletion of colSp components.')
colSpRowStatusEntry = MibTableRow((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21, 2, 1, 1), ).setIndexNames((0, "Nortel-Magellan-Passport-DataCollectionMIB", "colIndex"), (0, "Nortel-Magellan-Passport-DataCollectionMIB", "colSpIndex"))
if mibBuilder.loadTexts: colSpRowStatusEntry.setStatus('mandatory')
if mibBuilder.loadTexts: colSpRowStatusEntry.setDescription('A single entry in the table represents a single colSp component.')
colSpRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21, 2, 1, 1, 1), RowStatus()).setMaxAccess("readonly")
if mibBuilder.loadTexts: colSpRowStatus.setStatus('mandatory')
if mibBuilder.loadTexts: colSpRowStatus.setDescription('This variable is used as the basis for SNMP naming of colSp components. These components cannot be added nor deleted.')
colSpComponentName = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21, 2, 1, 1, 2), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: colSpComponentName.setStatus('mandatory')
if mibBuilder.loadTexts: colSpComponentName.setDescription("This variable provides the component's string name for use with the ASCII Console Interface")
colSpStorageType = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21, 2, 1, 1, 4), StorageType()).setMaxAccess("readonly")
if mibBuilder.loadTexts: colSpStorageType.setStatus('mandatory')
if mibBuilder.loadTexts: colSpStorageType.setDescription('This variable represents the storage type value for the colSp tables.')
colSpIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21, 2, 1, 1, 10), NonReplicated())
if mibBuilder.loadTexts: colSpIndex.setStatus('mandatory')
if mibBuilder.loadTexts: colSpIndex.setDescription('This variable represents the index for the colSp tables.')
colSpProvTable = MibTable((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21, 2, 10), )
if mibBuilder.loadTexts: colSpProvTable.setStatus('mandatory')
if mibBuilder.loadTexts: colSpProvTable.setDescription('This group specifies all of the provisioning data for a DCS Spooler.')
colSpProvEntry = MibTableRow((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21, 2, 10, 1), ).setIndexNames((0, "Nortel-Magellan-Passport-DataCollectionMIB", "colIndex"), (0, "Nortel-Magellan-Passport-DataCollectionMIB", "colSpIndex"))
if mibBuilder.loadTexts: colSpProvEntry.setStatus('mandatory')
if mibBuilder.loadTexts: colSpProvEntry.setDescription('An entry in the colSpProvTable.')
colSpSpooling = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21, 2, 10, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("off", 0), ("on", 1)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: colSpSpooling.setStatus('mandatory')
if mibBuilder.loadTexts: colSpSpooling.setDescription('This attribute specifies whether or not this type of data is spooled to the disk. If set to off, it is roughly equivalent to Locking the Spooler (except this will survive processor restarts). The following defaults are used: - alarm: on - accounting: on - log: on - debug: off - scn: on - trap: off (see Note below) - stats: on Note that SNMP Traps cannot be spooled. A semantic check prevents the user from setting the value to on for the trap stream.')
colSpMaximumNumberOfFiles = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21, 2, 10, 1, 2), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(0, 200))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: colSpMaximumNumberOfFiles.setStatus('mandatory')
if mibBuilder.loadTexts: colSpMaximumNumberOfFiles.setDescription("This attribute specifies the maximum number of files that should be kept on the disk in the directory containing the closed files of this type. The value 0 is defined to mean 'unlimited'. A different default for each type of Spooler is defined as follows: - alarm: 30 - accounting: 200 - debug: 2 - log: 10 - scn: 10 - trap: 2 (this value is meaningless and is ignored) - stats: 200")
colSpStateTable = MibTable((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21, 2, 11), )
if mibBuilder.loadTexts: colSpStateTable.setStatus('mandatory')
if mibBuilder.loadTexts: colSpStateTable.setDescription('This group contains the three OSI State attributes and the six OSI Status attributes. The descriptions generically indicate what each attribute implies about the component. Note that not all the values and state combinations described here are supported by every component which uses this group. For component-specific information and the valid state combinations, refer to NTP 241- 7001-150, Passport Operations and Maintenance Guide.')
colSpStateEntry = MibTableRow((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21, 2, 11, 1), ).setIndexNames((0, "Nortel-Magellan-Passport-DataCollectionMIB", "colIndex"), (0, "Nortel-Magellan-Passport-DataCollectionMIB", "colSpIndex"))
if mibBuilder.loadTexts: colSpStateEntry.setStatus('mandatory')
if mibBuilder.loadTexts: colSpStateEntry.setDescription('An entry in the colSpStateTable.')
colSpAdminState = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21, 2, 11, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("locked", 0), ("unlocked", 1), ("shuttingDown", 2))).clone('unlocked')).setMaxAccess("readonly")
if mibBuilder.loadTexts: colSpAdminState.setStatus('mandatory')
if mibBuilder.loadTexts: colSpAdminState.setDescription('This attribute indicates the OSI Administrative State of the component. The value locked indicates that the component is administratively prohibited from providing services for its users. A Lock or Lock - force command has been previously issued for this component. When the value is locked, the value of usageState must be idle. The value shuttingDown indicates that the component is administratively permitted to provide service to its existing users only. A Lock command was issued against the component and it is in the process of shutting down. The value unlocked indicates that the component is administratively permitted to provide services for its users. To enter this state, issue an Unlock command to this component. The OSI Status attributes, if supported by the component, may provide more details, qualifying the state of the component.')
colSpOperationalState = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21, 2, 11, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1))).clone('disabled')).setMaxAccess("readonly")
if mibBuilder.loadTexts: colSpOperationalState.setStatus('mandatory')
if mibBuilder.loadTexts: colSpOperationalState.setDescription('This attribute indicates the OSI Operational State of the component. The value enabled indicates that the component is available for operation. Note that if adminState is locked, it would still not be providing service. The value disabled indicates that the component is not available for operation. For example, something is wrong with the component itself, or with another component on which this one depends. If the value is disabled, the usageState must be idle. The OSI Status attributes, if supported by the component, may provide more details, qualifying the state of the component.')
colSpUsageState = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21, 2, 11, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("idle", 0), ("active", 1), ("busy", 2))).clone('idle')).setMaxAccess("readonly")
if mibBuilder.loadTexts: colSpUsageState.setStatus('mandatory')
if mibBuilder.loadTexts: colSpUsageState.setDescription('This attribute indicates the OSI Usage State of the component. The value idle indicates that the component is not currently in use. The value active indicates that the component is in use and has spare capacity to provide for additional users. The value busy indicates that the component is in use and has no spare operating capacity for additional users at this time. The OSI Status attributes, if supported by the component, may provide more details, qualifying the state of the component.')
colSpAvailabilityStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21, 2, 11, 1, 4), OctetString().subtype(subtypeSpec=ValueSizeConstraint(2, 2)).setFixedLength(2)).setMaxAccess("readonly")
if mibBuilder.loadTexts: colSpAvailabilityStatus.setStatus('mandatory')
if mibBuilder.loadTexts: colSpAvailabilityStatus.setDescription('If supported by the component, this attribute indicates the OSI Availability status of the component. Note that, even though it is defined as a multi-valued set, at most one value is shown to the user. When no values are in the set, this indicates that either the attribute is not supported or that none of the status conditions described below are present. The value inTest indicates that the resource is undergoing a test procedure. If adminState is locked or shuttingDown, the normal users are precluded from using the resource and controlStatus is reservedForTest. Tests that do not exclude additional users can be present in any operational or administrative state but the reservedForTest condition should not be present. The value failed indicates that the component has an internal fault that prevents it from operating. The operationalState is disabled. The value dependency indicates that the component cannot operate because some other resource on which it depends is unavailable. The operationalState is disabled. The value powerOff indicates the resource requires power to be applied and it is not powered on. The operationalState is disabled. The value offLine indicates the resource requires a routine operation (either manual, automatic, or both) to be performed to place it on-line and make it available for use. The operationalState is disabled. The value offDuty indicates the resource is inactive in accordance with a predetermined time schedule. In the absence of other disabling conditions, the operationalState is enabled or disabled. The value degraded indicates the service provided by the component is degraded in some way, such as in speed or operating capacity. However, the resource remains available for service. The operationalState is enabled. The value notInstalled indicates the resource is not present. The operationalState is disabled. The value logFull is not used. Description of bits: inTest(0) failed(1) powerOff(2) offLine(3) offDuty(4) dependency(5) degraded(6) notInstalled(7) logFull(8)')
colSpProceduralStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21, 2, 11, 1, 5), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 1)).setFixedLength(1)).setMaxAccess("readonly")
if mibBuilder.loadTexts: colSpProceduralStatus.setStatus('mandatory')
if mibBuilder.loadTexts: colSpProceduralStatus.setDescription("If supported by the component, this attribute indicates the OSI Procedural status of the component. Note that, even though it is defined as a multi-valued set, at most one value is shown to the user. When no values are in the set, this indicates that either the attribute is not supported or that none of the status conditions described below are present. The value initializationRequired indicates (for a resource which doesn't initialize autonomously) that initialization is required before it can perform its normal functions, and this procedure has not been initiated. The operationalState is disabled. The value notInitialized indicates (for a resource which does initialize autonomously) that initialization is required before it can perform its normal functions, and this procedure has not been initiated. The operationalState may be enabled or disabled. The value initializing indicates that initialization has been initiated but is not yet complete. The operationalState may be enabled or disabled. The value reporting indicates the resource has completed some processing operation and is notifying the results. The operationalState is enabled. The value terminating indicates the component is in a termination phase. If the resource doesn't reinitialize autonomously, operationalState is disabled; otherwise it is enabled or disabled. Description of bits: initializationRequired(0) notInitialized(1) initializing(2) reporting(3) terminating(4)")
colSpControlStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21, 2, 11, 1, 6), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 1)).setFixedLength(1)).setMaxAccess("readonly")
if mibBuilder.loadTexts: colSpControlStatus.setStatus('mandatory')
if mibBuilder.loadTexts: colSpControlStatus.setDescription('If supported by the component, this attribute indicates the OSI Control status of the component. Note that, even though it is defined as a multi-valued set, at most one value is shown to the user. When no values are in the set, this indicates that either the attribute is not supported or that none of the status conditions described below are present. The value subjectToTest indicates the resource is available but tests may be conducted simultaneously at unpredictable times, which may cause it to exhibit unusual characteristics. The value partOfServicesLocked indicates that part of the service is restricted from users of a resource. The adminState is unlocked. The value reservedForTest indicates that the component is administratively unavailable because it is undergoing a test procedure. The adminState is locked. The value suspended indicates that the service has been administratively suspended. Description of bits: subjectToTest(0) partOfServicesLocked(1) reservedForTest(2) suspended(3)')
colSpAlarmStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21, 2, 11, 1, 7), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 1)).setFixedLength(1)).setMaxAccess("readonly")
if mibBuilder.loadTexts: colSpAlarmStatus.setStatus('mandatory')
if mibBuilder.loadTexts: colSpAlarmStatus.setDescription('If supported by the component, this attribute indicates the OSI Alarm status of the component. Note that, even though it is defined as a multi-valued set, at most one value is shown to the user. When no values are in the set, this indicates that either the attribute is not supported or that none of the status conditions described below are present. The value underRepair indicates the component is currently being repaired. The operationalState is enabled or disabled. The value critical indicates one or more critical alarms are outstanding against the component. Other, less severe, alarms may also be outstanding. The operationalState is enabled or disabled. The value major indicates one or more major alarms are outstanding against the component. Other, less severe, alarms may also be outstanding. The operationalState is enabled or disabled. The value minor indicates one or more minor alarms are outstanding against the component. Other, less severe, alarms may also be outstanding. The operationalState is enabled or disabled. The value alarmOutstanding generically indicates that an alarm of some severity is outstanding against the component. Description of bits: underRepair(0) critical(1) major(2) minor(3) alarmOutstanding(4)')
colSpStandbyStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21, 2, 11, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 15))).clone(namedValues=NamedValues(("hotStandby", 0), ("coldStandby", 1), ("providingService", 2), ("notSet", 15))).clone('notSet')).setMaxAccess("readonly")
if mibBuilder.loadTexts: colSpStandbyStatus.setStatus('mandatory')
if mibBuilder.loadTexts: colSpStandbyStatus.setDescription('If supported by the component, this attribute indicates the OSI Standby status of the component. The value notSet indicates that either the attribute is not supported or that none of the status conditions described below are present. Note that this is a non-standard value, used because the original specification indicated this attribute was set-valued and thus, did not provide a value to indicate that none of the other three are applicable. The value hotStandby indicates that the resource is not providing service but will be immediately able to take over the role of the resource to be backed up, without initialization activity, and containing the same information as the resource to be backed up. The value coldStandby indicates the resource is a backup for another resource but will not be immediately able to take over the role of the backed up resource and will require some initialization activity. The value providingService indicates that this component, as a backup resource, is currently backing up another resource.')
colSpUnknownStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21, 2, 11, 1, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("false", 0), ("true", 1))).clone('false')).setMaxAccess("readonly")
if mibBuilder.loadTexts: colSpUnknownStatus.setStatus('mandatory')
if mibBuilder.loadTexts: colSpUnknownStatus.setDescription('This attribute indicates the OSI Unknown status of the component. The value false indicates that all of the other OSI State and Status attribute values can be considered accurate. The value true indicates that the actual state of the component is not known for sure.')
colSpOperTable = MibTable((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21, 2, 12), )
if mibBuilder.loadTexts: colSpOperTable.setStatus('mandatory')
if mibBuilder.loadTexts: colSpOperTable.setDescription('This group contains the operational attributes specific to a DCS Spooler.')
colSpOperEntry = MibTableRow((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21, 2, 12, 1), ).setIndexNames((0, "Nortel-Magellan-Passport-DataCollectionMIB", "colIndex"), (0, "Nortel-Magellan-Passport-DataCollectionMIB", "colSpIndex"))
if mibBuilder.loadTexts: colSpOperEntry.setStatus('mandatory')
if mibBuilder.loadTexts: colSpOperEntry.setDescription('An entry in the colSpOperTable.')
colSpSpoolingFileName = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21, 2, 12, 1, 1), AsciiString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readonly")
if mibBuilder.loadTexts: colSpSpoolingFileName.setStatus('mandatory')
if mibBuilder.loadTexts: colSpSpoolingFileName.setDescription('When spooling is on, this attribute contains the name of the open file into which data is currently being spooled. When spooling is off, the value of this attribute is the empty string.')
colSpStatsTable = MibTable((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21, 2, 13), )
if mibBuilder.loadTexts: colSpStatsTable.setStatus('mandatory')
if mibBuilder.loadTexts: colSpStatsTable.setDescription('This group specifies the statistics operational attributes of the DCS Collector, Agent and Spooler components.')
colSpStatsEntry = MibTableRow((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21, 2, 13, 1), ).setIndexNames((0, "Nortel-Magellan-Passport-DataCollectionMIB", "colIndex"), (0, "Nortel-Magellan-Passport-DataCollectionMIB", "colSpIndex"))
if mibBuilder.loadTexts: colSpStatsEntry.setStatus('mandatory')
if mibBuilder.loadTexts: colSpStatsEntry.setDescription('An entry in the colSpStatsTable.')
colSpCurrentQueueSize = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21, 2, 13, 1, 1), Gauge32().subtype(subtypeSpec=ValueRangeConstraint(0, 4294967295))).setMaxAccess("readonly")
if mibBuilder.loadTexts: colSpCurrentQueueSize.setStatus('mandatory')
if mibBuilder.loadTexts: colSpCurrentQueueSize.setDescription('This gauge contains the current number of records held by this DCS component.')
colSpRecordsRx = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21, 2, 13, 1, 2), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: colSpRecordsRx.setStatus('mandatory')
if mibBuilder.loadTexts: colSpRecordsRx.setDescription('This counter contains the cumulative number of records received by a DCS component, from applications which send data to it, since the processor last restarted. This counter wraps to 0 when the maximum value is exceeded.')
colSpRecordsDiscarded = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21, 2, 13, 1, 3), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: colSpRecordsDiscarded.setStatus('mandatory')
if mibBuilder.loadTexts: colSpRecordsDiscarded.setDescription('This is the cumulative number of records discarded by this DCS component since the processor last restarted. This counter wraps to 0 when the maximum value is exceeded.')
colAg = MibIdentifier((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21, 3))
colAgRowStatusTable = MibTable((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21, 3, 1), )
if mibBuilder.loadTexts: colAgRowStatusTable.setStatus('mandatory')
if mibBuilder.loadTexts: colAgRowStatusTable.setDescription('*** THIS TABLE CURRENTLY NOT IMPLEMENTED *** This entry controls the addition and deletion of colAg components.')
colAgRowStatusEntry = MibTableRow((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21, 3, 1, 1), ).setIndexNames((0, "Nortel-Magellan-Passport-DataCollectionMIB", "colIndex"), (0, "Nortel-Magellan-Passport-DataCollectionMIB", "colAgIndex"))
if mibBuilder.loadTexts: colAgRowStatusEntry.setStatus('mandatory')
if mibBuilder.loadTexts: colAgRowStatusEntry.setDescription('A single entry in the table represents a single colAg component.')
colAgRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21, 3, 1, 1, 1), RowStatus()).setMaxAccess("readonly")
if mibBuilder.loadTexts: colAgRowStatus.setStatus('mandatory')
if mibBuilder.loadTexts: colAgRowStatus.setDescription('This variable is used as the basis for SNMP naming of colAg components. These components cannot be added nor deleted.')
colAgComponentName = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21, 3, 1, 1, 2), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: colAgComponentName.setStatus('mandatory')
if mibBuilder.loadTexts: colAgComponentName.setDescription("This variable provides the component's string name for use with the ASCII Console Interface")
colAgStorageType = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21, 3, 1, 1, 4), StorageType()).setMaxAccess("readonly")
if mibBuilder.loadTexts: colAgStorageType.setStatus('mandatory')
if mibBuilder.loadTexts: colAgStorageType.setDescription('This variable represents the storage type value for the colAg tables.')
colAgIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21, 3, 1, 1, 10), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 15)))
if mibBuilder.loadTexts: colAgIndex.setStatus('mandatory')
if mibBuilder.loadTexts: colAgIndex.setDescription('This variable represents the index for the colAg tables.')
colAgStatsTable = MibTable((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21, 3, 10), )
if mibBuilder.loadTexts: colAgStatsTable.setStatus('mandatory')
if mibBuilder.loadTexts: colAgStatsTable.setDescription('*** THIS TABLE CURRENTLY NOT IMPLEMENTED *** This group specifies the statistics operational attributes of the DCS Collector, Agent and Spooler components.')
colAgStatsEntry = MibTableRow((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21, 3, 10, 1), ).setIndexNames((0, "Nortel-Magellan-Passport-DataCollectionMIB", "colIndex"), (0, "Nortel-Magellan-Passport-DataCollectionMIB", "colAgIndex"))
if mibBuilder.loadTexts: colAgStatsEntry.setStatus('mandatory')
if mibBuilder.loadTexts: colAgStatsEntry.setDescription('An entry in the colAgStatsTable.')
colAgCurrentQueueSize = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21, 3, 10, 1, 1), Gauge32().subtype(subtypeSpec=ValueRangeConstraint(0, 4294967295))).setMaxAccess("readonly")
if mibBuilder.loadTexts: colAgCurrentQueueSize.setStatus('mandatory')
if mibBuilder.loadTexts: colAgCurrentQueueSize.setDescription('This gauge contains the current number of records held by this DCS component.')
colAgRecordsRx = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21, 3, 10, 1, 2), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: colAgRecordsRx.setStatus('mandatory')
if mibBuilder.loadTexts: colAgRecordsRx.setDescription('This counter contains the cumulative number of records received by a DCS component, from applications which send data to it, since the processor last restarted. This counter wraps to 0 when the maximum value is exceeded.')
colAgRecordsDiscarded = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21, 3, 10, 1, 3), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: colAgRecordsDiscarded.setStatus('mandatory')
if mibBuilder.loadTexts: colAgRecordsDiscarded.setDescription('This is the cumulative number of records discarded by this DCS component since the processor last restarted. This counter wraps to 0 when the maximum value is exceeded.')
colAgAgentStatsTable = MibTable((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21, 3, 11), )
if mibBuilder.loadTexts: colAgAgentStatsTable.setStatus('mandatory')
if mibBuilder.loadTexts: colAgAgentStatsTable.setDescription('*** THIS TABLE CURRENTLY NOT IMPLEMENTED *** This group contains the statistical attributes specific to the DCS Agent components.')
colAgAgentStatsEntry = MibTableRow((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21, 3, 11, 1), ).setIndexNames((0, "Nortel-Magellan-Passport-DataCollectionMIB", "colIndex"), (0, "Nortel-Magellan-Passport-DataCollectionMIB", "colAgIndex"))
if mibBuilder.loadTexts: colAgAgentStatsEntry.setStatus('mandatory')
if mibBuilder.loadTexts: colAgAgentStatsEntry.setDescription('An entry in the colAgAgentStatsTable.')
colAgRecordsNotGenerated = MibTableColumn((1, 3, 6, 1, 4, 1, 562, 2, 4, 1, 21, 3, 11, 1, 1), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: colAgRecordsNotGenerated.setStatus('mandatory')
if mibBuilder.loadTexts: colAgRecordsNotGenerated.setDescription('This attribute counts the records of a particular event type on this Card which could not be generated by some application due to some problem such as insufficient resources. One cannot tell exactly which event could not be generated, nor which application instance tried to generate it, but when this count increases, it is an indicator that some re-engineering may be required and will provide some idea as to why a record is missing. This counter wraps to 0 when the maximum value is exceeded.')
dataCollectionGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 562, 2, 4, 2, 14, 1))
dataCollectionGroupBE = MibIdentifier((1, 3, 6, 1, 4, 1, 562, 2, 4, 2, 14, 1, 5))
dataCollectionGroupBE00 = MibIdentifier((1, 3, 6, 1, 4, 1, 562, 2, 4, 2, 14, 1, 5, 1))
dataCollectionGroupBE00A = MibIdentifier((1, 3, 6, 1, 4, 1, 562, 2, 4, 2, 14, 1, 5, 1, 2))
dataCollectionCapabilities = MibIdentifier((1, 3, 6, 1, 4, 1, 562, 2, 4, 2, 14, 3))
dataCollectionCapabilitiesBE = MibIdentifier((1, 3, 6, 1, 4, 1, 562, 2, 4, 2, 14, 3, 5))
dataCollectionCapabilitiesBE00 = MibIdentifier((1, 3, 6, 1, 4, 1, 562, 2, 4, 2, 14, 3, 5, 1))
dataCollectionCapabilitiesBE00A = MibIdentifier((1, 3, 6, 1, 4, 1, 562, 2, 4, 2, 14, 3, 5, 1, 2))
mibBuilder.exportSymbols("Nortel-Magellan-Passport-DataCollectionMIB", colSpProvEntry=colSpProvEntry, dataCollectionCapabilitiesBE=dataCollectionCapabilitiesBE, colTimesEntry=colTimesEntry, colSpSpooling=colSpSpooling, colAgAgentStatsEntry=colAgAgentStatsEntry, colSpStorageType=colSpStorageType, colProvEntry=colProvEntry, colTimesTable=colTimesTable, colSp=colSp, colAgRowStatusTable=colAgRowStatusTable, colAgRecordsDiscarded=colAgRecordsDiscarded, colRowStatusEntry=colRowStatusEntry, colAgAgentStatsTable=colAgAgentStatsTable, colSpCurrentQueueSize=colSpCurrentQueueSize, colSpSpoolingFileName=colSpSpoolingFileName, colSpOperEntry=colSpOperEntry, dataCollectionMIB=dataCollectionMIB, colSpMaximumNumberOfFiles=colSpMaximumNumberOfFiles, colAg=colAg, colSpComponentName=colSpComponentName, dataCollectionCapabilitiesBE00A=dataCollectionCapabilitiesBE00A, dataCollectionGroup=dataCollectionGroup, colAgentQueueSize=colAgentQueueSize, dataCollectionCapabilities=dataCollectionCapabilities, colRowStatusTable=colRowStatusTable, colSpUsageState=colSpUsageState, colSpStandbyStatus=colSpStandbyStatus, colIndex=colIndex, colLastTable=colLastTable, colSpIndex=colSpIndex, colAgRecordsNotGenerated=colAgRecordsNotGenerated, colPeakRowStatus=colPeakRowStatus, colSpAlarmStatus=colSpAlarmStatus, colTimesRowStatus=colTimesRowStatus, colSpAvailabilityStatus=colSpAvailabilityStatus, colAgIndex=colAgIndex, colSpUnknownStatus=colSpUnknownStatus, colComponentName=colComponentName, colSpRowStatusTable=colSpRowStatusTable, colLastValue=colLastValue, colSpRowStatus=colSpRowStatus, colPeakTable=colPeakTable, colSpRowStatusEntry=colSpRowStatusEntry, colTimesValue=colTimesValue, colSpOperationalState=colSpOperationalState, colAgCurrentQueueSize=colAgCurrentQueueSize, colSpOperTable=colSpOperTable, colCurrentQueueSize=colCurrentQueueSize, dataCollectionGroupBE00A=dataCollectionGroupBE00A, colSpProceduralStatus=colSpProceduralStatus, colSpStateEntry=colSpStateEntry, col=col, colAgStatsEntry=colAgStatsEntry, colSpControlStatus=colSpControlStatus, colStatsTable=colStatsTable, colSpRecordsDiscarded=colSpRecordsDiscarded, colPeakValue=colPeakValue, colSpRecordsRx=colSpRecordsRx, colAgStatsTable=colAgStatsTable, colAgRecordsRx=colAgRecordsRx, colRowStatus=colRowStatus, colAgRowStatusEntry=colAgRowStatusEntry, colSpAdminState=colSpAdminState, colAgComponentName=colAgComponentName, colRecordsRx=colRecordsRx, colAgStorageType=colAgStorageType, colRecordsDiscarded=colRecordsDiscarded, colSpStatsTable=colSpStatsTable, colStatsEntry=colStatsEntry, colSpStatsEntry=colSpStatsEntry, colProvTable=colProvTable, dataCollectionCapabilitiesBE00=dataCollectionCapabilitiesBE00, colStorageType=colStorageType, colAgRowStatus=colAgRowStatus, colSpProvTable=colSpProvTable, colSpStateTable=colSpStateTable, colPeakEntry=colPeakEntry, dataCollectionGroupBE=dataCollectionGroupBE, colLastEntry=colLastEntry, dataCollectionGroupBE00=dataCollectionGroupBE00)
|
numbers = [-1,0]
target = -1
hashMap = {}
for index, num in enumerate(numbers):
diff = target - num
if diff in hashMap:
print([hashMap[diff]+1, index+1])
hashMap[num] = index
|
#SCOPE USING NONLOCAL KEYWORD
x = 10#GLOBAL VARIABLE X
def outer():
x=20#LOCAL VARIABLE X
y=30#LOCAL VARIABLE Y
print("outer func x before inner call:", x)
print("outer func y before inner call:", y)
def inner():
nonlocal y#LOCAL VARIABLE Y REFERS TO ITS ABOVE LEVEL OUTER Y
global x#REFERS GLOBAL X
x=30#MAKS GLOBAL X TO 30
y=40#MAKES LOCAL Y IN OUTER TO 40
print("inner func x :", x)
print("inner func y :", y)
inner()
print("outer func x after inner call:", x)
print("outer func y after inner call:", y)
print("x before outer call:", x)
outer()
print("x after outer call:", x)
'''
OUTPUT:
x before outer call:10
outer func x before inner call:20
outer func y before inner call:30
inner func x :30
inner func y :30
outer func x after inner call:20
outer func y after inner call:40
x before outer call:30'''
|
"""
1. Clarification
2. Possible solutions
- dp
3. Coding
4. Tests
"""
# T=O(n), S=O(n)
# dp[i][j], i: day, j:
# 0 - have a share of stock
# 1 - have no stock and cool down next day
# 2 - have no stock and no cool down next day
class Solution:
def maxProfit(self, prices: List[int]) -> int:
if not prices: return 0
n = len(prices)
dp = [[0] * 3 for _ in range(n)]
dp[0][0], dp[0][1], dp[0][2] = -prices[0], 0, 0
for i in range(1, n):
dp[i][0] = max(dp[i - 1][0], dp[i - 1][2] - prices[i])
dp[i][1] = dp[i - 1][0] + prices[i]
dp[i][2] = max(dp[i - 1][1], dp[i - 1][2])
return max(dp[n - 1][1], dp[n - 1][2])
|
#========================================================================================================
# TOPIC: PYTHON - Modules
#========================================================================================================
# NOTES: * Any Python file is a module.
# * Module is a file with Python statements, file extension ".py"
# * Modules have classes, functions and variables
# * Using the ModuleName.FunctionName is the notation to refer to the
# module objects (classes, functions and variables)
# * Modules can import other modules.
# * The keyword "import <module-name>" is used to import a module
# * The keyword "from <module-name> import <function1>" enables the developer to import
# specific objects of a module.
# * Python comes with a library of standard modules
#
#
#========================================================================================================
#
# FILE-NAME : 013_module.py
# DEPENDANT-FILES : These are the files and libraries needed to run this program ;
# 013_module.py and 013_module_usage.py
#
# AUTHOR : learnpython.com / Hemaxi
# (c) 2013
#
# DESC : Python Modules , used to organize code.
#
#========================================================================================================
# Declare GLOBAL Variables
# Some variables
country_1 = "USA"
country_2 = "China"
country_3 = "India"
# GLOBAL list
list_world_nations = ["USA", "China", "India"]
# GLOBAL tuple
tuple_world_nations = ("USA", "China", "India")
# GLOBAL dictionary
dictionary_world_nations = {'Country_1':'USA', 'Country_1':'China', 'Country_1':'India'}
# Module Function WITHOUT a return type
def module_function_add(in_number1, in_number2):
"This function add the two input numbers"
return in_number1 + in_number2
#========================================================================================================
# END OF CODE
#========================================================================================================
|
# Define a sum_of_lengths function that accepts a list of strings.
# The function should return the sum of the string lengths.
#
# EXAMPLES
# sum_of_lengths(["Hello", "Bob"]) => 8
# sum_of_lengths(["Nonsense"]) => 8
# sum_of_lengths(["Nonsense", "or", "confidence"]) => 20
def sum_of_lengths(array):
sum = 0
for element in array:
sum += len(element)
return sum
print(sum_of_lengths(['Hello', 'Bob']))
print(sum_of_lengths(['Nonsense']))
print(sum_of_lengths(['Nonsense', 'or', 'confidence']))
|
# Generates an infinite series of odd numbers
def odds():
n = 1
while True:
yield n
n += 2
def pi_series():
odd_nums = odds()
approximation = 0
while True:
approximation += (4 / next(odd_nums))
yield approximation
approximation -= (4 / next(odd_nums))
yield approximation
approx_pi = pi_series()
# The higher the range used here the closer to an acurate approximation of PI.
for x in range(10000):
print(next(approx_pi))
|
data = [
{'v': 'v0.1', 't': 1391},
{'v': 'v0.1', 't': 1394},
{'v': 'v0.1', 't': 1300},
{'v': 'v0.1', 't': 1321},
{'v': 'v0.1.3', 't': 1491},
{'v': 'v0.1.3', 't': 1494},
{'v': 'v0.1.3', 't': 1400},
{'v': 'v0.1.3', 't': 1421},
{'v': 'v0.1.2', 't': 1291},
{'v': 'v0.1.2', 't': 1294},
{'v': 'v0.1.2', 't': 1200},
{'v': 'v0.1.2', 't': 1221},
{'v': 'v0.0.2', 't': 294},
{'v': 'v0.0.2', 't': 200},
{'v': 'v0.0.20', 't': 221},
{'v': 'v0.0.20', 't': 294},
{'v': 'v0.0.20', 't': 200},
{'v': 'v0.0.19', 't': 321},
{'v': 'v0.0.19', 't': 294},
{'v': 'v0.0.19', 't': 200},
{'v': 'v0.3', 't': 621},
{'v': 'v0.3', 't': 421},
{'v': 'v0.3', 't': 794},
{'v': 'v0.3', 't': 300},
{'v': 'v0.3', 't': 121}
]
def version_str_to_int(version_str: str) -> int:
parts = version_str.split('.')
if len(parts) > 3:
raise VersionError(f'version tag "{version_str}" should only have 3 parts (major, minor, patch numbers)')
elif len(parts) == 0:
raise VersionError(f'version tag "{version_str}" should have at least major number')
major = 0
minor = 0
patch = 0
try:
if parts[0][0] == 'v':
major = int(parts[0][1:])
else:
major = int(parts[0])
if len(parts) > 1:
minor = int(parts[1])
if len(parts) > 2:
patch = int(parts[2])
except Exception as e:
print(f'unable to parse version tag "{version_str}": {e}')
version_int = major * 1000 * 1000 + minor * 1000 + patch
return version_int
data.sort(key=lambda x: (-version_str_to_int(x['v']), -x['t']))
print(data)
|
# Najdi palindrom
# Napรญลกte definรญciu funkcie najdi_palindrom, ktorรก berie parametre veta a n. Funkcia vo vete nรกjde palindrรณm dฤบลพky n a vrรกti ho ako nรกvratovรบ hodnotu. Ak sa vo vete ลพiadny takรฝto palindrรณm nenachรกdza, funkcia vyhodรญ chybu typu LookupError. (Funkcia bude ignorovaลฅ veฤพkosลฅ pรญsmen a medzery.)
# Sample Input 1:
# 'Petr jede v kajaku', 5
# Sample Output 1:
# 'kajak'
# Sample Input 2:
# 'Kuna nanuk nemรก rรกda', 9
# Sample Output 2:
# 'kunananuk'
# Sample Input 3:
# 'Milujem Python', 3
# Sample Output 3:
# LookupError
def najdi_palindrom(veta: str, n: int) -> str:
pole = veta.split()
slovo = ''
vysledok = False
for index in range(0, len(pole)):
slovo = slovo + pole[index]
slovo2 = ''
for i in range(0, len(slovo)):
slovo2 = slovo[(i+1-n):(i+1)]
if(len(slovo2) == n):
if (slovo2.lower() == slovo2[::-1].lower()):
vysledok = slovo2.lower()
if(vysledok == False):
raise LookupError()
return vysledok
print(najdi_palindrom('Kuna nanuk nemรก rรกda', 9))
|
def minimum(a):
b=list[0]
i=0
while i<len(list):
if list[i]<b:
b=list[i]
i=i+1
return(b)
list=[5,3,1,6,5,4,7,6]
print(minimum(list))
|
lista = []
for i in range(5):
lista.append(int(input(f'numero {i}: ')))
if i == 0:
maior_valor = menor_valor = lista[i]
if lista[i] > maior_valor:
maior_valor = lista[i]
elif lista[i] < menor_valor:
menor_valor = lista[i]
print('=-'*30)
print(f'maior valor digitado:{maior_valor} nas posiรงรตes:', end='')
for posicao, valores in enumerate(lista):
if valores == maior_valor:
print(f'{posicao}...', end='')
print()
print(f'menor valor digitado:{menor_valor} nas posiรงรตes:', end='')
for posicao, valores in enumerate(lista):
if valores == menor_valor:
print(f'{posicao}...', end='')
#Exercรญcio Python 078:
# Faรงa um programa que leia 5 valores numรฉricos e
# guarde-os em uma lista. No final, mostre qual foi
# o maior e o menor valor digitado e
# as suas respectivas posiรงรตes na lista.
|
__about__="Class method vs Static Method."
class MyClass:
def method(self):
print("Instance of method called", self)
@classmethod
def classmethod(cls):
print("Instance of classmethod called", cls)
@staticmethod
def staticmethod():
print("Instance of staticmethod called")
|
'''
Class for adding the expreimental data for the cell model
'''
class Experimental:
def __init__(self):
self.experimental_data = dict()
def define_exp(self, **kwargs):
for exp_type, data in kwargs.items():
self.experimental_data.update({exp_type: data})
|
def get_hard_coded_app_id_dict():
# Matches, manually added, from game names to Steam appIDs
hard_coded_dict = {
# Manually fix matches for which the automatic name matching (based on Levenshtein distance) is wrong:
"The Missing": "842910",
"Pillars of Eternity 2": "560130",
"Dragon Quest XI": "742120",
"DRAGON QUEST XI: Echoes of an Elusive Age": "742120",
"Dragon Quest XI: Echoes of an Elusive Age": "742120",
"Dragon Quest XI: Shadows of an Elusive Age": "742120",
"Atelier Rorona ~The Alchemist of Arland~ DX": "936160",
"Megaman 11": "742300",
"Mega Man 11": "742300",
"Ys VIII: Lacrimosa of DANA": "579180",
"The Curse of the Pharaohs (Assassin's Creed Origins)": "662351",
"ATOM RPG": "552620",
"Spider-Man": "-1",
"F76": "-2",
"Deltarune": "-4",
"DELTARUNE": "-4",
"The Orb Vallis (Warframe Expansion)": "-101",
"CSGO: Danger Zone": "-102",
"Epic Game Launcher": "-201",
}
return hard_coded_dict
def check_database_of_problematic_game_names(game_name):
hard_coded_dict = get_hard_coded_app_id_dict()
is_a_problematic_game_name = bool(game_name in hard_coded_dict.keys())
return is_a_problematic_game_name
def find_hard_coded_app_id(game_name_input):
hard_coded_dict = get_hard_coded_app_id_dict()
hard_coded_app_id = hard_coded_dict[game_name_input]
return hard_coded_app_id
if __name__ == '__main__':
hard_coded_dict = get_hard_coded_app_id_dict()
|
rates = list() # Equals to: rates = []
genres = list()
ages = list()
another_one = True
while another_one:
genre = input('Please enter your genre (either M or F): ')
genres.append(genre)
age = int(input('Type your age: '))
ages.append(age)
rate = input('You rate the product as '
'1-unsatisfactory 2-bad 3-regular 4-good 5-great: ')
rates.append(rate)
print()
another_one = input('Do you want to add another client\'s rate (Y/N): ')
print()
if another_one == 'N':
another_one = False
counter = 0
females = 0
females_40 = 0
females_50 = 0
men_rate_un = 0
while counter < len(genres):
if genres[counter] == "F":
females += 1
if ages[counter] > 50 and rates[counter] == 4:
females_50 += 1
elif ages[counter] > 40 and rates[counter] == 4:
females_40 += 1
else:
if rates[counter] == 1:
men_rate_un += 1
counter += 1
men = len(genres) - females
print(f'{females_40} women over 40 years old rated the product as good.')
print(f'{females_50} women over 50 years old rated the product as good.')
print(f'{men_rate_un} men rated the product as unsatisfactory.')
print(f'{females} women partipated in the survey.')
print(f'{men} men partipated in the survey.')
|
# Forma procedural de criar uma conta
def cria_conta(numero, titular, saldo, limite):
'''
-> Cria uma conta bancรกria
:param numero: nรบmero da conta bancรกria (string)
:param titular: nome do titular (string)
:param saldo: saldo inicial da conta (float)
:param limite: limite de saldo da conta (float)
:return: retorna um dicionรกrio
'''
conta = {'numero': numero, 'titular': titular, 'saldo': saldo, 'limite': limite}
return conta
def deposita(conta, valor):
'''
-> Deposita um valor no saldo da conta
:param conta: conta a ser passada
:param valor: valor a ser adicionado ao saldo
:return: sem retorno
'''
conta['saldo'] += valor
def saca(conta, valor):
'''
-> Saca um valor no saldo da conta
:param conta: conta a ser passada
:param valor: valor a ser subtraido do saldo
:return: sem retorno
'''
conta['saldo'] -= valor
def extrato(conta):
'''
-> Imprimi o nรบmero e o saldo da conta
:param conta: conta a ser passada
:return: sem retorno
'''
print('Nรบmero: {} \nSaldo: R$ {:.2f}'.format(conta['numero'], conta['saldo']))
conta1 = cria_conta('123-7', 'Joรฃo', 500, 1000)
deposita(conta1, 200)
saca(conta1, 300)
extrato(conta1)
|
def euclidean_distance(x1, y1, x2, y2):
"""Compute euclidean distance between two points."""
def which_start_and_pitstop(pitstop_num, pitstop_coords, start_coords):
"""Computes the relevant pitstop and startpoint info.
Extracts the pitstop coordinates, relevant startpoint number and
startpoint coordinates and returns them."""
# Write your code here
return my_pitstop_coord, my_start_coord, my_start_num
# Feel free to add more utility functions
|
greetings = ["hey", "howdy", "hi", "hello", "hi there"]
questions = ["how_are_you_feeling", "how_are_you", "what_is_your_name", "how_old_are_you", "where_are_you_from", "are_you_a_boy_or_a_girl", "what_up"]
insults = ["dumb", "stupid", "Ugly", "Retard", "Retarded", "suck"]
complements = ["great", "awesome"]
cuss_words = ["fucking", "god damn"]
moods = ["Aweful", "bad", "not so good", "alright", "good", "Great", "amazing"]
whys = ["why_is_that","why","how_come"]
name = "Stewart"
mood_level = 3
talk_level = 2
age = 2
cuss_box = []
memory_box = []
|
#Desenvolver um algoritmo que faรงa a leitura de um nรบmero inteiro positivo e que,
#para esse nรบmero, mostre todos os seus divisores.
def divisor():
try:
num=int(input('Indique um nรบmero: '))
while num<0:
num=int(input('Nรบmero Invรกlido!\nIndique um nรบmero: '))
except ValueError:
print('Nรฃo foi inserido um nรบmero.')
for i in range(1,num+1):
if num%i==0:
print(i, end=' ')
divisor()
|
def extractEachKth(inputArray, k):
return [x for i, x in enumerate(inputArray) if (i + 1) % k != 0]
print(extractEachKth([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 3))
|
# Sage version information for Python scripts
# This file is auto-generated by the sage-update-version script, do not edit!
version = '9.3.beta7'
date = '2021-02-07'
banner = 'SageMath version 9.3.beta7, Release Date: 2021-02-07'
|
_attrs = {
"base": attr.string(
mandatory = True
),
# See: https://github.com/opencontainers/image-spec/blob/main/config.md#properties
"entrypoint": attr.string_list(),
"cmd": attr.string_list(),
"labels": attr.string_list(),
"tag": attr.string_list(),
"layers": attr.label_list(),
}
def _strip_external(path):
return path[len("external/"):] if path.startswith("external/") else path
def _impl(ctx):
toolchain = ctx.toolchains["@rules_container//container:toolchain_type"]
launcher = ctx.actions.declare_file("crane.sh")
# TODO: dynamically get --platform from toolchain
ctx.actions.write(
launcher,
"""#!/usr/bin/env bash
set -euo pipefail
{crane} $@""".format(
crane = toolchain.containerinfo.crane_path,
),
is_executable = True,
)
# Pull the image
pull = ctx.actions.args()
tar = ctx.actions.declare_file("base_%s.tar" % ctx.label.name)
pull.add_all([
"append",
"--base",
ctx.attr.base,
"--output",
tar,
"--new_tag",
ctx.label.name,
])
inputs = list()
inputs.extend(toolchain.containerinfo.crane_files)
if ctx.attr.layers:
pull.add("--new_layer")
for layer in ctx.attr.layers:
inputs.extend(layer[DefaultInfo].files.to_list())
pull.add_all(layer[DefaultInfo].files)
ctx.actions.run(
inputs = inputs,
arguments = [pull],
outputs = [tar],
executable = launcher,
progress_message = "Pulling base image and appending new layers (%s)" % ctx.attr.base
)
# Mutate it
mutate = ctx.actions.args()
resultTar = ctx.actions.declare_file("%s.tar" % ctx.label.name)
mutate.add_all([
"mutate",
"--tag",
ctx.label.name,
tar,
"--output",
resultTar
])
if ctx.attr.entrypoint:
mutate.add_joined("--entrypoint", ctx.attr.entrypoint, join_with=",")
if ctx.attr.cmd:
mutate.add_joined("--cmd", ctx.attr.cmd, join_with=",")
ctx.actions.run(
inputs = [tar] + toolchain.containerinfo.crane_files,
arguments = [mutate],
outputs = [resultTar],
executable = launcher,
progress_message = "Mutating base image (%s)" % ctx.attr.base
)
return [
DefaultInfo(
files = depset([resultTar]),
),
]
container = struct(
implementation = _impl,
attrs = _attrs,
toolchains = ["@rules_container//container:toolchain_type"],
)
|
"""DESAFIO 44"""
print('-=-'*13)
valor = float(input('Qual o valor do pagamento? R$ '))
print('-=-'*13)
print("""Qual a forma de pagamento?
[1]โ ร vista dinheiro/cheque: 10% de desconto
[2]โ ร vista no cartรฃo: 5% de desconto
[3]โ em atรฉ 2x no cartรฃo: preรงo formal
[4]โ 3x ou mais no cartรฃo: 20% de juros""")
forma = int(input('\nDigite sua escolha: '))
print('-=-'*13)
if forma == 1:
des = valor - (valor*0.1)
print("""Valor bruto: R${} reais
Valor do desconto: R${:.2f} reais
Valor a Pagar: R${:.2f} reais""".format(valor,valor*0.1, des))
elif forma == 2:
desc = valor - (valor*0.05)
print("""Valor bruto: R$ {:.2f} reais
Valor do desconto: R${:.2f} reais
Valor a pagar: R$ {:.2f} reais""".format(valor, valor*0.05, desc))
elif forma == 3:
desc = 0
print("""Valor bruto: R$ {:.2f} reais
Valor do desconto: R$ {:.2f} reais
Valor a pagar: R$ {:.2f}""".format(valor, valor*0, valor))
elif forma == 4:
acres = valor + (valor*0.2)
par = int(input('Em quantas parcelas deseja passar? '))
print('-=-'*13)
print("""Valor bruto: R$ {:.2f} reais
Quantidade de parcelas: {}
Valor do Acrรฉscimo de 20%: R$ {:.2f} reais
Valor a pagar: R$ {:.2f} reais""".format(valor,par, valor*0.2, acres))
else:
print('Opรงรฃo invรกlida de pagamento, tente novamente.')
print('-=-'*13)
|
def numsum(n):
''' The recursive sum of all digits in a number
unit a single character is obtained'''
res = sum([int(i) for i in str(n)])
if res < 10: return res
else : return numsum(res)
for n in range(1,101):
response = 'Fizz'*(numsum(n) in [3,6,9]) + \
'Buzz'*(str(n)[-1] in ['5','0'])\
or n
print(response)
|
class Solution:
def matrixScore(self, A):
"""
:type A: List[List[int]]
:rtype: int
"""
if not A or not A[0]: return 0
n, m = len(A), len(A[0])
tot = n*2**(m-1)
for i in range(1, m):
zero = sum(A[j][0]^A[j][i] for j in range(n))
tot += max(zero, n-zero)*2**(m-i-1)
return tot
class Solution:
def matrixScore(self, A):
if not A or not A[0]: return 0
n, m = len(A), len(A[0])
tot = 0
for i in range(m):
zero = sum(A[j][0]^A[j][i] for j in range(n))
tot += max(zero, n-zero)*2**(m-i-1)
return tot
class Solution:
def matrixScore(self, A):
"""
:type A: List[List[int]]
:rtype: int
"""
M = len(A)
N = len(A[0])
res = M << (N - 1)
for j in range(1, N):
m = sum(A[i][j] == A[i][0] for i in range(M))
res += max(m, M - m) <<(N - 1 - j)
return res
class Solution:
def matrixScore(self, A: List[List[int]]) -> int:
for i in range(len(A)):
if A[i][0] == 0:
self.flip_row(A, i)
return self.dfs(A, 1)
def dfs(self, a, j):
if j == len(a[0]):
return sum([int(''.join(map(str, a[i])), 2) for i in range(len(a))])
count = sum([1 for i in range(len(a)) if a[i][j]])
if count < (len(a)+1)//2:
self.flip_col(a, j)
return self.dfs(a, j + 1)
def flip_row(self, a, i):
for j in range(len(a[0])):
a[i][j] = int(not a[i][j])
def flip_col(self, a, j):
for i in range(len(a)):
a[i][j] = int(not a[i][j])
|
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import json\n",
"import plotly\n",
"import pandas as pd\n",
"\n",
"from nltk.stem import WordNetLemmatizer\n",
"from nltk.tokenize import word_tokenize\n",
"\n",
"from flask import Flask\n",
"from flask import render_template, request, jsonify\n",
"from plotly.graph_objs import Bar\n",
"from sklearn.externals import joblib\n",
"from sqlalchemy import create_engine\n",
"\n",
"\n",
"app = Flask(__name__)\n",
"\n",
"def tokenize(text):\n",
" tokens = word_tokenize(text)\n",
" lemmatizer = WordNetLemmatizer()\n",
"\n",
" clean_tokens = []\n",
" for tok in tokens:\n",
" clean_tok = lemmatizer.lemmatize(tok).lower().strip()\n",
" clean_tokens.append(clean_tok)\n",
"\n",
" return clean_tokens\n",
"\n",
"# load data\n",
"engine = create_engine('sqlite:///../data/DisasterResponse.db')\n",
"df = pd.read_sql_table('Messages', engine)\n",
"\n",
"# load model\n",
"model = joblib.load(\"../models/classifier.pkl\")\n",
"\n",
"\n",
"# index webpage displays cool visuals and receives user input text for model\n",
"@app.route('/')\n",
"@app.route('/index')\n",
"\n",
"def index():\n",
" \n",
" # extract data needed for visuals\n",
" # Calculate message count by genre and related status \n",
" genre_related = df[df['related']==1].groupby('genre').count()['message']\n",
" genre_not_rel = df[df['related']==0].groupby('genre').count()['message']\n",
" genre_names = list(genre_related.index)\n",
" \n",
" # Calculate proportion of each category with label = 1\n",
" cat_props = df.drop(['id', 'message', 'original', 'genre'], axis = 1).sum()/len(df)\n",
" cat_props = cat_props.sort_values(ascending = False)\n",
" cat_names = list(cat_props.index)\n",
" \n",
"\n",
" # create visuals\n",
" graphs = [\n",
" {\n",
" 'data': [\n",
" Bar(\n",
" x=genre_names,\n",
" y=genre_related,\n",
" name = 'Related'\n",
" ),\n",
" \n",
" Bar(\n",
" x=genre_names,\n",
" y=genre_not_rel,\n",
" name = 'Not Related'\n",
" )\n",
" ],\n",
"\n",
" 'layout': {\n",
" 'title': 'Distribution of Messages by Genre and Related Status',\n",
" 'yaxis': {\n",
" 'title': \"Count\"\n",
" },\n",
" 'xaxis': {\n",
" 'title': \"Genre\"\n",
" },\n",
" 'barmode': 'group'\n",
" }\n",
" },\n",
" {\n",
" 'data': [\n",
" Bar(\n",
" x=cat_names,\n",
" y=cat_props\n",
" )\n",
" ],\n",
"\n",
" 'layout': {\n",
" 'title': 'Proportion of Messages by Category',\n",
" 'yaxis': {\n",
" 'title': \"Proportion\"\n",
" },\n",
" 'xaxis': {\n",
" 'title': \"Category\",\n",
" 'tickangle': -45\n",
" }\n",
" }\n",
" }\n",
" ]\n",
" \n",
" # encode plotly graphs in JSON\n",
" ids = [\"graph-{}\".format(i) for i, _ in enumerate(graphs)]\n",
" graphJSON = json.dumps(graphs, cls=plotly.utils.PlotlyJSONEncoder)\n",
" \n",
" # render web page with plotly graphs\n",
" return render_template('master.html', ids=ids, graphJSON=graphJSON)\n",
"\n",
"# web page that handles user query and displays model results\n",
"@app.route('/go')\n",
"def go():\n",
" # save user input in query\n",
" query = request.args.get('query', '') \n",
"\n",
" # use model to predict classification for query\n",
" classification_labels = model.predict([query])[0]\n",
" classification_results = dict(zip(df.columns[4:], classification_labels))\n",
"\n",
" # This will render the go.html Please see that file. \n",
" return render_template(\n",
" 'go.html',\n",
" query=query,\n",
" classification_result=classification_results\n",
" )\n",
"\n",
"\n",
"def main():\n",
" app.run(host='0.0.0.0', port=3001, debug=True)\n",
"\n",
"\n",
"if __name__ == '__main__':\n",
" main()"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
|
# Solution 1
# O(n^2) time / O(1) space
# n - number of buildings
def largestRectangleUnderSkyline(buildings):
maxArea = 0
for pillarIdx in range(len(buildings)):
currentHeight = buildings[pillarIdx]
furthestLeft = pillarIdx
while furthestLeft > 0 and buildings[furthestLeft - 1] >= currentHeight:
furthestLeft -= 1
furthestRight = pillarIdx
while furthestRight < len(buildings) - 1 and buildings[furthestRight + 1] >= currentHeight:
furthestRight += 1
areaWithCurrentBuilding = (furthestRight - furthestLeft + 1) * currentHeight
maxArea = max(areaWithCurrentBuilding, maxArea)
return maxArea
# Solution 2
# O(n) time / O(n) space
# n - number of buildings
def largestRectangleUnderSkyline(buildings):
pillarIndices = []
maxArea = 0
for idx, height in enumerate(buildings + [0]):
while len(pillarIndices) != 0 and buildings[pillarIndices[len(pillarIndices) - 1]] >= height:
pillarHeight = buildings[pillarIndices.pop()]
width = idx if len(pillarIndices) == 0 else idx - pillarIndices[len(pillarIndices) - 1] - 1
maxArea = max(width * pillarHeight, maxArea)
pillarIndices.append(idx)
return maxArea
|
t=int(input())
while(t):
t=t-1
n=int(input())
c=0
a=list(map(int,input().split()))
b=[]
b.append(int(a[0]))
for i in range(1,len(a)):
b.append(min(int(a[i]),int(b[i-1])))
for i in range(0,len(a)):
if(int(a[i])==int(b[i])):
c+=1
print(c)
|
#!/usr/bin/env python3
__author__ = "Mert Erol"
# This signature is required for the automated grading to work.
# Do not rename the function or change its list of parameters!
def visualize(records):
pclass_1 = 0
pclass_1_alive = 0
pclass_2 = 0
pclass_2_alive = 0
pclass_3 = 0
pclass_3_alive = 0
dataset = records[1]
for p in dataset:
pclass = p[1]
alive = p[0]
#first class counter
if pclass == 1:
pclass_1 += 1
if alive == True:
pclass_1_alive += 1
#second class counter
elif pclass == 2:
pclass_2 += 1
if alive == True:
pclass_2_alive += 1
#third class counter
elif pclass == 3:
pclass_3 += 1
if alive == True:
pclass_3_alive += 1
#percentage of passengers in each class
totpas = len(dataset)
tot_1 = round((pclass_1/totpas * 100), 1)
tot_2 = round((pclass_2/totpas * 100), 1)
tot_3 = round((pclass_3/totpas * 100), 1)
#percentage of each passanger that survived in each class
surv_1 = round((pclass_1_alive/pclass_1 * 100), 1)
surv_2 = round((pclass_2_alive/pclass_2 * 100), 1)
surv_3 = round((pclass_3_alive/pclass_3 * 100), 1)
#building the visual step by step
string = "== 1st Class ==\n"
string += "Total |" + (round(tot_1/5)) * "*" + str((20- round(tot_1/5))* " ") + "| " + str(tot_1) + "%\n"
string += "Alive |" + (round(surv_1/5)) * "*" + str((20-round(surv_1/5)) * " ") + "| " + str(surv_1) + "%\n"
string += "== 2nd Class ==\n"
string += "Total |" + (round(tot_2/5)) * "*" + str((20- round(tot_2/5))* " ") + "| " + str(tot_2) + "%\n"
string += "Alive |" + (round(surv_2/5)) * "*" + str((20-round(surv_2/5)) * " ") + "| " + str(surv_2) + "%\n"
string += "== 3rd Class ==\n"
string += "Total |" + (round(tot_3/5)) * "*" + str((20- round(tot_3/5))* " ") + "| " + str(tot_3) + "%\n"
string += "Alive |" + (round(surv_3/5)) * "*" + str((20-round(surv_3/5)) * " ") + "| " + str(surv_3) + "%\n"
return string
# The following line calls the function and prints the return
# value to the Console. This way you can check what it does.
# However, we encourage you to write tests, because then you
# can easily test many different values on every "Test & Run"!
if __name__ == '__main__':
print(visualize((
('Survived', 'Pclass', 'Name', 'Gender', 'Age', 'Fare'),
[
(True, 1, 'Cumings Mrs. John Bradley (Florence Briggs Thayer)',
'female', 38, 71.2833),
(True, 2, 'Flunky Mr Hazelnut', 'female', 18, 51.2),
(False, 3, 'Heikkinen Miss. Laina', 'female', 26, 7.925)
]
)))
|
# Dummy class for packages that have no MPI
class MPIDummy(object):
def __init__(self):
pass
def Get_rank(self):
return 0
def Get_size(self):
return 1
def barrier(self):
pass
def send(self, lnlike0, dest=1, tag=55):
pass
def recv(self, source=1, tag=55):
pass
def Iprobe(self, source=1, tag=55):
pass
# Global object representing no MPI:
COMM_WORLD = MPIDummy()
|
def gcd(a, b):
factors_a = []
for i in range(1, a+1):
if (a%i) == 0:
factors_a.append(i)
factors_b = []
for i in range(1, b+1):
if (b%i) == 0:
factors_b.append(i)
common_factors = []
for i in factors_a:
if i in factors_b:
common_factors.append(i)
return (common_factors[-1])
def p(s):
print(s)
if __name__ == "__main__":
p("input a:")
a = int(input())
p("input b:")
b = int(input())
p("gcd of "+str(a)+" and "+str(b)+" is:")
print(gcd(a, b))
|
"""Pygame Zero, a zero-boilerplate game framework for education.
You shouldn't need to import things from the 'pgzero' package directly; just
use 'pgzrun' to run the game file.
"""
__version__ = '1.2'
|
# Specialization: Google IT Automation with Python
# Course 01: Crash Course with Python
# Week 3 Module Part 1 - Practice Quiz
# Student: Shawn Solomon
# Learning Platform: Coursera.org
# Scripting examples encountered during the Module Part 1 Practice Quiz:
# 02. Fill in the blanks to make the print_prime_factors function print all the prime factors of a number.
# A prime factor is a number that is prime and divides another without a remainder.
# def print_prime_factors(number):
# # Start with two, which is the first prime
# factor = ___
# # Keep going until the factor is larger than the number
# while factor <= number:
# # Check if factor is a divisor of number
# if number % factor == ___:
# # If it is, print it and divide the original number
# print(factor)
# number = number / factor
# else:
# # If it's not, increment the factor by one
# ___
# return "Done"
#
# print_prime_factors(100)
# # Should print 2,2,5,5
# # DO NOT DELETE THIS COMMENT
def print_prime_factors(number):
# Start with two, which is the first prime
factor = 2
# Keep going until the factor is larger than the number
while factor <= number:
# Check if factor is a divisor of number
if number % factor == 0:
# If it is, print it and divide the original number
print(factor)
number = number / factor
else:
# If it's not, increment the factor by one
factor += 1
return "Done"
print_prime_factors(100)
# Should print 2,2,5,5
# DO NOT DELETE THIS COMMENT
# 03. The following code can lead to an infinite loop. Fix the code so that it can finish successfully for all numbers.
# Note: Try running your function with the number 0 as the input, and see what you get!
# def is_power_of_two(n):
# # Check if the number can be divided by two without a remainder
# while n % 2 == 0:
# n = n / 2
# # If after dividing by two the number is 1, it's a power of two
# if n == 1:
# return True
# return False
#
#
# print(is_power_of_two(0)) # Should be False
# print(is_power_of_two(1)) # Should be True
# print(is_power_of_two(8)) # Should be True
# print(is_power_of_two(9)) # Should be False
def is_power_of_two(n):
# Check if the number can be divided by two without a remainder
while n % 2 == 0:
if n == 0:
return False
n = n / 2
# If after dividing by two the number is 1, it's a power of two
if n == 1:
return True
return False
print(is_power_of_two(0)) # Should be False
print(is_power_of_two(1)) # Should be True
print(is_power_of_two(8)) # Should be True
print(is_power_of_two(9)) # Should be False
# 04. Fill in the empty function so that it returns the sum of all the divisors of a number, without including it.
# A divisor is a number that divides into another without a remainder.
# def sum_divisors(n):
# sum = 0
# # Return the sum of all divisors of n, not including n
# return sum
#
# print(sum_divisors(0))
# # 0
# print(sum_divisors(3)) # Should sum of 1
# # 1
# print(sum_divisors(36)) # Should sum of 1+2+3+4+6+9+12+18
# # 55
# print(sum_divisors(102)) # Should be sum of 2+3+6+17+34+51
# # 114
def sum_divisors(number):
sum = 0
divs = 1
while divs < number:
# Check if factor is a divisor of number
if number == 0:
return 0
if number % divs == 0:
# If it is, print it and divide the original number
sum = sum + divs
divs = divs + 1
else:
divs += 1
# Return the sum of all divisors of n, not including n
return sum
print(sum_divisors(0))
# 0
print(sum_divisors(3)) # Should sum of 1
# 1
print(sum_divisors(36)) # Should sum of 1+2+3+4+6+9+12+18
# 55
print(sum_divisors(102)) # Should be sum of 2+3+6+17+34+51
# 114
# 05. The multiplication_table function prints the results of a number passed to it multiplied by 1 through 5.
# An additional requirement is that the result is not to exceed 25, which is done with the break statement.
# Fill in the blanks to complete the function to satisfy these conditions.
# def multiplication_table(number):
# # Initialize the starting point of the multiplication table
# multiplier = 1
# # Only want to loop through 5
# while multiplier <= 5:
# result = ___
# # What is the additional condition to exit out of the loop?
# if ___ :
# break
# print(str(number) + "x" + str(multiplier) + "=" + str(result))
# # Increment the variable for the loop
# ___ += 1
#
# multiplication_table(3)
# # Should print: 3x1=3 3x2=6 3x3=9 3x4=12 3x5=15
#
# multiplication_table(5)
# # Should print: 5x1=5 5x2=10 5x3=15 5x4=20 5x5=25
#
# multiplication_table(8)
# # Should print: 8x1=8 8x2=16 8x3=24
def multiplication_table(number):
# Initialize the starting point of the multiplication table
multiplier = 1
# Only want to loop through 5
while multiplier <= 5:
result = number * multiplier
# What is the additional condition to exit out of the loop?
if result > 25 :
break
print(str(number) + "x" + str(multiplier) + "=" + str(result))
# Increment the variable for the loop
multiplier += 1
multiplication_table(3)
# Should print: 3x1=3 3x2=6 3x3=9 3x4=12 3x5=15
multiplication_table(5)
# Should print: 5x1=5 5x2=10 5x3=15 5x4=20 5x5=25
multiplication_table(8)
# Should print: 8x1=8 8x2=16 8x3=24
|
test = """2H2 + O2 -> 2H2O"""
def times_sep(s):
elem = []
times = []
checking_pro = False
last = 0
for i in range(len(s)):
if checking_pro:
if s[i].isalpha() and not s[i].islower() or s[i].isdigit():
elem.append(s[last])
checking_pro = False
if s[i].islower() and s[i].isalpha():
elem.append(s[i-1]+s[i])
if s[i].isupper():
checking_pro = True
if s[i].isupper() and i == len(s)-1:
elem.append(s[i])
last = (i)
last = 0
checking_pro = False
for i in range(1, len(s)):
if checking_pro:
if s[i].isupper():
times.append(1)
checking_pro = False
if s[i].isdigit():times.append(int(s[i]))
if s[i].isalpha():
checking_pro = True
if s[i].isupper() and i == len(s)-1:
times.append(1)
return list(zip(elem, times))
def coeff_sep(ele):
d = {}
for i in ele:
coeff = ""
for j in i:
if not j.isdigit():
break
coeff += j
d.update({i[len(coeff):]: coeff if coeff != "" else 1})
return d
def checker(equation):
a = equation.split(" -> ")
reactants = a[0].split(" + ")
products = a[1].split(" + ")
stoichiometry = coeff_sep(reactants), coeff_sep(products)
print(*stoichiometry, sep="\n")
for i in stoichiometry:
for j in i.keys():
print(times_sep(j))
checker(test)
# print(times_sep("H2O"))
|
#4: Skriv alle primtal mellem 1 og 100
for primtal in range(2, 101):
for i in range(2, primtal):
if (primtal % i) == 0:
break
else:
print(primtal)
|
class Checkers:
def __init__(self):
pass
def is_operation(self, command):
operations = ['+', '-', 'x', '*', '/',
'plus', 'minus', 'times', 'divide']
for operation in operations:
if operation in command:
return True
|
# noinspection PyUnusedLocal
# skus = unicode string
class InvalidOfferException(Exception):
def __init__(self, expression, message):
self.expression = expression
self.message = message
def checkout(skus):
products = {
'A': productA, 'B': productB, 'C': productC,'D': productD,'E': productE,
'F': productF, 'G': productG, 'H': productH,'I': productI,'J': productJ,
'K': productK, 'L': productL, 'M': productM,'N': productN,'O': productO,
'P': productP, 'Q': productQ, 'R': productR,'S': productS,'T': productT,
'U': productU, 'V': productV, 'W': productW,'X': productX,'Y': productY,
'Z': productZ}
competing_offers = [
[Offer({productB: 2}, 45), Offer({productB: 1, productE: 2}, 80)],
[Offer({productQ: 3}, 80), Offer({productR: 3, productQ:1}, 150)]
]
non_competing_offers = [
Offer({productA: 5}, 200, Offer({productA: 3}, 130)),
Offer({productH: 10}, 80, Offer({productH: 5}, 45)),
Offer({productV: 3}, 130, Offer({productV: 2}, 90)),
Offer({productF: 3}, 20),
Offer({productK: 2}, 120),
Offer({productU: 4}, 120),
Offer({productN: 3, productM:1}, 120),
Offer({productP: 5}, 200)
]
group_offers = [GroupOffer([productS, productT, productX, productY, productZ], 3, 45)]
basket = Basket(competing_offers, non_competing_offers, group_offers, {}, 0)
for letter in skus:
try:
basket.add_item(products[letter])
except Exception as e:
return -1
return basket.calculate_value()
class GroupOffer:
def __init__(self, elements, required_number, price):
self.elements = elements.copy()
self.elements.sort(key= lambda l: l.standardPrice, reverse=True)
self.required_number = required_number
self.price = price
def apply_offer(self, basket):
value_ranked_collection = [(x,basket.items.get(x, 0)) for x in self.elements]
number_of_items = sum(j for _, j in value_ranked_collection)
if (number_of_items < self.required_number):
raise InvalidOfferException("Invalid Offer")
still_required = self.required_number
for item_tuple in value_ranked_collection:
count = item_tuple[1]
item = item_tuple[0]
if count == 0:
continue
if count < still_required:
still_required = still_required - count
basket.remove_items(item, count)
else:
basket.remove_items(item, still_required)
break
basket.add_item_price(self.price)
return basket
class Offer:
def __init__(self, combinationDict, dealPrice, dominated_offer=None):
self.combinationDict = combinationDict
self.dealPrice = dealPrice
self.dominated_offer = dominated_offer
def apply_offer(self, basket):
for key, value in self.combinationDict.items():
if value > basket.items[key]:
raise InvalidOfferException("Invalid Offer")
for key,value in self.combinationDict.items():
basket.remove_items(key, value)
basket.add_item_price(self.dealPrice)
return basket
class Item:
def __init__(self, name, standardPrice):
self.name = name
self.standardPrice = standardPrice
class Basket:
def __init__(self, competing_offers, non_competing_offers, group_offers, items, price):
self.non_competing_offers = non_competing_offers.copy()
self.competing_offers = competing_offers.copy()
self.items = items.copy()
self.price = price
self.group_offers = group_offers.copy()
def add_item(self, item):
if item in self.items:
self.items[item] += 1
else:
self.items[item] = 1
def remove_items(self, item, count):
self.items[item] = self.items[item] - count
def add_item_price(self, price):
self.price += price
def calculate_value(self):
if self.non_competing_offers:
self.apply_non_competing_offers()
if self.group_offers:
self.apply_group_offers()
if self.competing_offers:
competing_offer = self.competing_offers[0]
return min(self.apply_competing_offer(competing_offer[0], competing_offer[1], competing_offer),
self.apply_competing_offer(competing_offer[1], competing_offer[0], competing_offer))
for item, count in self.items.items():
self.price += item.standardPrice * count
return self.price
def apply_non_competing_offers(self):
for offer in self.non_competing_offers:
while True:
try:
self = offer.apply_offer(self)
except:
try:
self = offer.dominated_offer.apply_offer(self)
except:
break
break
def apply_group_offers(self):
for offer in self.group_offers:
while True:
try:
self = offer.apply_offer(self)
except:
break
def apply_competing_offer(self, offer, alternative, competing_offer):
basket = Basket(self.competing_offers,[],[],self.items, self.price)
try:
basket = offer.apply_offer(basket)
except:
basket.competing_offers.remove(competing_offer)
basket.non_competing_offers.append(alternative)
return basket.calculate_value()
productA = Item('A',50)
productB = Item('B',30)
productC = Item('C',20)
productD = Item('D',15)
productE = Item('E',40)
productF = Item('F',10)
productG = Item('G',20)
productH = Item('H',10)
productI = Item('I',35)
productJ = Item('J',60)
productK = Item('K',70)
productL = Item('L',90)
productM = Item('M',15)
productN = Item('N',40)
productO = Item('O',10)
productP = Item('P',50)
productQ = Item('Q',30)
productR = Item('R',50)
productS = Item('S',20)
productT = Item('T',20)
productU = Item('U',40)
productV = Item('V',50)
productW = Item('W',20)
productX = Item('X',17)
productY = Item('Y',20)
productZ = Item('Z',21)
|
str = "RahulShettyAcademy.com"
str1 = "Consulting firm"
str3 = "RahulShetty"
print(str[1]) #a
print(str[0:5]) # if you want substring in python
print(str+str1) # concatenation
print(str3 in str) # substring check
var = str.split(".")
print(var)
print(var[0])
str4 = " great "
print(str4.strip())
print(str4.lstrip())
print(str4.rstrip())
|
class Solution:
def secondHighest(self, s: str) -> int:
a = []
for i in s:
if i.isdigit():
a.append(int(i))
stack = [-1]
maxs = max(a)
for i in a:
if i < maxs:
while stack and stack[-1] < i:
stack.pop()
stack.append(i)
return stack[-1]
if __name__ == '__main__':
s = Solution()
t = "asdac456a453dqwe1865s4df645s495q6w1e6qw13e"
print(s.secondHighest(t))
|
'''
Fibonacci Sequence
'''
print("Enter a number for Fibonacci")
f = input()
|
def get_common_elements(seq1,seq2,seq3):
common = set(seq1) & set(seq2) & set(seq3)
return tuple(common)
print(get_common_elements("abcd",['a','b', 'd'],('b','c', 'd')))
# , {"a","b","c","d", "e"}
def get_common_elements_multi(*multy_arg):
if len(multy_arg) == 0:
return ()
my_set = set(multy_arg[0])
for el in multy_arg[1:]:
my_set = my_set.intersection(set(el))
return tuple(my_set)
print(get_common_elements_multi("abcd",['a','b', 'd'],('b','c', 'd'), {"a","b","c","d", "e"}, {"a","c","d", "e"}))
print(get_common_elements_multi("Valdis", "Voldemฤrs", "Voldemorts", "Volodja"))
print(get_common_elements_multi())
|
class Duration:
def __init__(self, hours: int = 0, minutes: int = 0, seconds: int = 0):
# setup the class instance and convert any provided times to seconds
self.total_duration: int = (hours * 60 * 60) + (minutes * 60) + seconds
def __add__(self, other):
new_total: int = self.total_duration + other.total_duration
return Duration(seconds=new_total)
def get_hours(self) -> int:
# return only the hours
return self.total_duration // (60 * 60)
def get_minutes(self) -> int:
# return only the minutes
return (self.total_duration % (60 * 60)) // 60
def get_seconds(self) -> int:
# return only the seconds
return (self.total_duration % (60 * 60)) % 60
def get_all(self) -> tuple[int, int, int]:
# return the total duration as hours, minutes & seconds individually
return self.get_hours(), self.get_minutes(), self.get_minutes()
def __str__(self) -> str:
# quick and simple representation of the duration
return f'{self.get_hours()}hrs {self.get_minutes()}mins {self.get_seconds()}secs'
|
# https://lospec.com/palette-list/pear36
COLORS = [
"#5e315b",
"#8c3f5d",
"#ba6156",
"#f2a65e",
"#ffe478",
"#cfff70",
"#8fde5d",
"#3ca370",
"#3d6e70",
"#323e4f",
"#322947",
"#473b78",
"#4b5bab",
"#4da6ff",
"#66ffe3",
"#ffffeb",
"#c2c2d1",
"#7e7e8f",
"#606070",
"#43434f",
"#272736",
"#3e2347",
"#57294b",
"#964253",
"#e36956",
"#ffb570",
"#ff9166",
"#eb564b",
"#b0305c",
"#73275c",
"#422445",
"#5a265e",
"#80366b",
"#bd4882",
"#ff6b97",
"#ffb5b5",
"#ef7379",
]
POINT_GRADIENT = [
COLORS[-7],
COLORS[-6],
COLORS[-5],
COLORS[-4],
COLORS[-3],
COLORS[-2],
]
TEAM_1_PALLETE = [
COLORS[25],
COLORS[3],
COLORS[26],
COLORS[24],
COLORS[27],
]
TEAM_2_PALLETE = [
COLORS[14],
COLORS[13],
COLORS[12],
COLORS[11],
COLORS[10],
]
GREYSCALE = [
COLORS[15],
COLORS[16],
COLORS[17],
COLORS[18],
COLORS[19],
]
|
nome=(input("Informe o nome do aluno: "))
n1=int(input("Informe a nota da prova: "))
n2=int(input("Informe a nota do trabalho: "))
n3=int(input("Informe a nota do seminรกrio: "))
media = (n1 + n2 + n3) /3
if media >= 7:
print(nome," APROVADO!")
elif media >=3 :
nf = (50 - (media * 7))/3
print(nome," precisa de tirar", nf, "na pova final!")
elif media <3:
print(nome," REPROVADO!")
|
fout = open('output.txt', 'w')
line1 = "This here's the wattle,\n"
fout.write(line1)
line2 = "the emblem of our land.\n"
fout.write(line2)
fout.close()
|
class Solution:
def subarraysDivByK(self, A: List[int], K: int) -> int:
"""Prefix sum.
Running time: O(n) where n is the length of A.
"""
n = len(A)
pre = 0
res = 0
d = {0: 1}
for a in A:
pre = (pre + a) % K
res += d.get(pre, 0)
d[pre] = d.get(pre, 0) + 1
return res
|
def unique_markers(n_markers):
"""Returns a unique list of distinguishable markers. These are predominantly based
on the default seaborn markers.
Parameters
----------
n_markers
The number of markers to return (max=11).
"""
markers = [
"circle",
"x",
"diamond",
"cross",
"square",
"star-diamond",
"triangle-up",
"star-square",
"triangle-down",
"pentagon",
"hexagon",
]
assert n_markers <= len(markers)
return markers[:n_markers]
def unique_colors(n_colors):
"""Returns a unique list of distinguishable colors. These are taken from the
default seaborn `colorblind` color palette.
Parameters
----------
n_colors
The number of colors to return (max=10).
"""
colors = [
(0.004, 0.451, 0.698),
(0.871, 0.561, 0.020),
(0.008, 0.620, 0.451),
(0.835, 0.369, 0.000),
(0.800, 0.471, 0.737),
(0.792, 0.569, 0.380),
(0.984, 0.686, 0.894),
(0.580, 0.580, 0.580),
(0.925, 0.882, 0.200),
(0.337, 0.706, 0.914),
]
assert n_colors <= len(colors)
return colors[:n_colors]
|
"""
This file contains the functional tests for the `devices` blueprint.
These tests use GETs and POSTs to different URLs to check for the
proper behavior of the `devices` blueprint.
"""
def test_inventory(client):
"""
GIVEN a Flask application configured for testing
WHEN the '/inventory/<category>' page is requested (GET)
with a sample category
THEN check the response is valid
"""
response = client.get('/inventory/Phone')
assert response.status_code == 200
def test_add_device(client):
"""
GIVEN a Flask application configured for testing
WHEN the '/add_device' page is requested (GET)
THEN check the response is valid
"""
response = client.get('/add_device')
assert response.status_code == 200
assert b'Name' in response.data
assert b'Type' in response.data
assert b'Serial' in response.data
assert b'Model' in response.data
assert b'MAC Address' in response.data
assert b'Device Status' in response.data
assert b'Purchase Date' in response.data
assert b'Owner Username' in response.data
assert b'Device Category' in response.data
assert b'Notes' in response.data
assert b'Add/Update Device' in response.data
def test_select_device(client):
"""
GIVEN a Flask application configured for testing
WHEN the '/select_device' page is requested (GET)
with a sample letter range
THEN check the response is valid
"""
response = client.get('/select_device/AF')
assert response.status_code == 200
# TODO:
# def test_edit_or_delete(client):
# """
# GIVEN a Flask application configured for testing
# WHEN the '/select_device' page is requested (GET)
# THEN check the response is valid
# """
# def test_delete_result(client):
# """
# GIVEN a Flask application configured for testing
# WHEN the '/select_device' page is requested (GET)
# THEN check the response is valid
# """
# def test_edit_result(client):
# """
# GIVEN a Flask application configured for testing
# WHEN the '/edit_result' page is posted to (POST)
# THEN check the response is valid
# """
|
def main(fn):
with open(fn, 'r') as f:
lines = [li.strip() for li in f.readlines()]
cmds = list()
for li in lines:
fields = li.split()
cmds.append([fields[0], int(fields[1])])
is_looping, acc = run(cmds)
print(acc)
for i in range(len(cmds)):
if not flip_cmd(cmds[i]):
continue
is_looping, acc = run(cmds)
if not is_looping:
print(acc)
break
flip_cmd(cmds[i])
def flip_cmd(cmd):
if cmd[0] == 'nop':
cmd[0] = 'jmp'
elif cmd[0] == 'jmp':
cmd[0] = 'nop'
else:
return False
return True
def run(cmds):
acc = 0
pc = 0
visited = set()
is_looping = False
while pc != len(cmds):
if pc in visited:
is_looping = True
break
visited.add(pc)
cmd, val = cmds[pc]
if cmd == 'nop':
pc += 1
elif cmd == 'acc':
acc += val
pc += 1
elif cmd == 'jmp':
pc += val
else:
raise ValueError
return is_looping, acc
if __name__ == '__main__':
fn = 'input.txt'
#fn = 'test.txt'
main(fn)
|
class Solution(object):
def exist(self, board, word):
"""
:type board: List[List[str]]
:type word: str
:rtype: bool
"""
def dfs(word, idx, r, c):
m, n = len(board), len(board[0])
if idx == len(word):
return True
if (not (0 <= r < m and 0 <= c < n)) or word[idx] != board[r][c]:
return False
for i, j in ((r - 1, c), (r + 1, c), (r, c - 1), (r, c + 1)):
if (i, j) not in visited:
visited.add((i, j))
if dfs(word, idx + 1, i, j):
return True
visited.remove((i, j))
return False
visited = set()
for i, row in enumerate(board):
for j, val in enumerate(row):
visited.add((i, j))
if dfs(word, 0, i, j):
return True
visited.clear()
return False
|
print ('hello world')
print ('hello second time')
print ('Again and Again')
|
#!/usr/bin/env python3
disc_size = [17, 19, 7, 13, 5, 3]
disc_pos = [5, 8, 1, 7, 1, 0]
def solve():
shift_pos = [(disc_pos[i]+i+1)%disc_size[i] for i in range(len(disc_pos))]
t = 0
while max(shift_pos) != 0:
shift_pos = [(shift_pos[i]+1)%disc_size[i] for i in range(len(shift_pos))]
t += 1
print(t)
solve()
disc_size += [11]
disc_pos += [0]
solve()
|
'''
enable extension for this user
link :
https://bits.bitcoin.org.hk/extensions?usr=dd09c7b0fe33480ab28252c9c9b85c6b&enable=lnurlp
create a lnurlp pay link
needs an admin key
POST /lnurlp/api/v1/links
Headers
{"X-Api-Key": <admin_key>}
Body (application/json)
{"description": <string> "amount": <integer> "max": <integer> "min": <integer> "comment_chars": <integer>}
Returns 201 CREATED (application/json)
{"lnurl": <string>}
'''
|
"""
Person class
"""
# Create a Person class with the following properties
# 1. name
# 2. age
# 3. social security number
|
class Config:
def __init__(self):
self.DARKNET_PATH = "lib/pyyolo/darknet"
self.DATACFG = "data/obj.data"
self.CFGFILE = "cfg/yolo-obj.cfg"
self.WEIGHTFILE_SKETCH = "models/yolo-obj_final_sketch.weights"
self.WEIGHTFILE_TEMPLATES = "models/yolo-obj_45000.weights"
self.CLASSESFILE = "data/predefined_classes.txt"
self.THRESH = 0.45
self.HIER_THRESH = 0.5
self.OUT_DIR = "server/static/images"
self.ASSET_DIR = "assets"
# Snap to grid
self.gheight = 200
self.gwidth = 200
# Color code
self.cc_default = (0, 255, 0)
self.cc_blue = (255, 0, 0)
self.cc_green = (0, 255, 0)
self.cc_red = (0, 0, 255)
self.color_scheme = {
"red": self.cc_red,
"green": self.cc_green,
"blue": self.cc_blue,
"default": self.cc_default,
}
|
# coding = utf-8
# Create date: 2018-11-6
# Author :Bowen Lee
def test_kernel_headers(ros_kvm_init, cloud_config_url):
command = 'sleep 10; sudo system-docker inspect kernel-headers'
kwargs = dict(cloud_config='{url}test_kernel_headers.yml'.format(url=cloud_config_url),
is_install_to_hard_drive=True)
tuple_return = ros_kvm_init(**kwargs)
client = tuple_return[0]
stdin, stdout, stderr = client.exec_command(command)
output = stdout.read().decode('utf-8')
client.close()
assert ('kernel-headers' in output)
|
NAME='router_xmldir'
CFLAGS = []
LDFLAGS = []
LIBS = []
GCC_LIST = ['router_xmldir']
|
class Solution:
def brokenCalc(self, X, Y):
res = 0
while X < Y:
res += Y % 2 + 1
Y = (Y + 1) // 2
return res + X - Y
|
class RemoteDockerException(RuntimeError):
pass
class InstanceNotRunning(RemoteDockerException):
pass
|
# 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 flipMatchVoyage(self, root: TreeNode, voyage: List[int]) -> List[int]:
self.ix = 0
self.flipped = []
self.n = len(voyage)
def preorder(node):
if node:
if node.val == voyage[self.ix]:
self.ix += 1
if self.ix < self.n and node.left and node.left.val != voyage[self.ix]:
self.flipped.append(node.val)
preorder(node.right)
preorder(node.left)
else:
preorder(node.left)
preorder(node.right)
else:
self.flipped.append(-1)
preorder(root)
if self.flipped:
for flg in self.flipped:
if flg == -1:
self.flipped = [-1]
break
return self.flipped
|
"""
@author: magician
@date: 2019/12/19
@file: key_word_demo.py
"""
def safe_division(number, divisor, ignore_overflow=False, ignore_zero_division=False):
"""
safe_division
:param number:
:param divisor:
:param ignore_overflow:
:param ignore_zero_division:
:return:
"""
try:
return number / divisor
except OverflowError:
if ignore_overflow:
return 0
else:
raise
except ZeroDivisionError:
if ignore_zero_division:
return float('inf')
else:
raise
def safe_division_d(number, divisor, **kwargs):
"""
safe_division_d
:param number:
:param divisor:
:param kwargs:
:return:
"""
# ignore_overflow = kwargs.pop('ignore_overflow', False)
# ignore_zero_div = kwargs.pop('ignore_zero_division', False)
if kwargs:
raise TypeError('Unexpected **kwargs:{0}'.format(kwargs))
return True
if __name__ == '__main__':
result = safe_division(1.0, 10**500, True, False)
print(result)
result = safe_division(1, 0, False, True)
print(result)
try:
safe_division(1, 10**500, ignore_overflow=True)
except Exception as e:
print(e)
try:
safe_division(1, 0, ignore_overflow=False)
except Exception as e:
print(e)
|
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
"""
Tencent is pleased to support the open source community by making Metis available.
Copyright (C) 2018 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
https://opensource.org/licenses/BSD-3-Clause
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.
"""
TSD_OP_SUCCESS = 0
TSD_THROW_EXP = 1000
TSD_CHECK_PARAM_FAILED = 1002
TSD_FILE_FORMAT_ERR = 1003
TSD_CAL_FEATURE_ERR = 2001
TSD_READ_FEATURE_FAILED = 2002
TSD_TRAIN_ERR = 2003
TSD_LACK_SAMPLE = 2004
ERR_CODE = {
TSD_OP_SUCCESS: "ๆไฝๆๅ",
TSD_THROW_EXP: "ๆๅบๅผๅธธ",
TSD_CHECK_PARAM_FAILED: "ๅๆฐๆฃๆฅๅคฑ่ดฅ",
TSD_FILE_FORMAT_ERR: "ๆไปถๆ ผๅผๆ่ฏฏ",
TSD_CAL_FEATURE_ERR: "็นๅพ่ฎก็ฎๅบ้",
TSD_READ_FEATURE_FAILED: "่ฏปๅ็นๅพๆฐๆฎๅคฑ่ดฅ",
TSD_TRAIN_ERR: "่ฎญ็ปๅบ้",
TSD_LACK_SAMPLE: "็ผบๅฐๆญฃๆ ทๆฌๆ่ดๆ ทๆฌ",
}
|
def run_api_workflow_with_assertions(workflow_specification, current_request, test_context):
current_request_result = current_request(test_context)
if current_request_result is not None and current_request_result["continue_workflow"]:
run_api_workflow_with_assertions(
workflow_specification,
workflow_specification[current_request_result["next_request"]],
current_request_result["test_context"]
)
|
INPUT_SCHEMA = {
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "Deriva Demo Input",
"description": ("Input schema for the demo DERIVA ingest Action Provider. This Action "
"Provider can restore a DERIVA backup to a new or existing catalog, "
"or create a new DERIVA catalog from a BDBag containing TableSchema."),
"type": "object",
"properties": {
"data_url": {
"type": "string",
"format": "uri",
"description": "The URL or path to the data for DERIVA ingest."
},
'''
"fair_re_path": {
"type": "string",
"description": ("Path on the FAIR Research Examples endpoint, to support "
"Globus Transfer (with Automate) input.")
},
"restore": {
"type": "boolean",
"description": ("Whether or not this is a restoration of a backed-up catalog (true), "
"or an ingest of TableSchema data (false). When true, data_url "
"must point to a DERIVA backup. When false, data_url must point "
"to a BDBag of TableSchema data. The default is false.")
},
'''
"operation": {
"type": "string",
"description": ("The operation to perform on the data. If the data is a DERIVA backup "
"to restore, use 'restore'. If the data is TableSchema to ingest into "
"a new or existing DERIVA catalog, use 'ingest'. If you are only "
"modifying the parameters of one catalog, use 'modify'."),
"enum": [
"restore",
"ingest",
"modify"
]
},
"server": {
"type": "string",
"description": ("The DERIVA server to ingest into. By default, will use the DERIVA "
"demo server.")
},
"catalog_id": {
"type": ["string", "integer"],
"description": ("The existing catalog ID to ingest into, or the name of a pre-defined "
"catalog (e.g. 'prod'). To create a new catalog, do not specify "
"this value. If specified, the catalog must exist.")
},
"catalog_acls": {
"type": "object",
"description": ("The DERIVA permissions to apply to a new catalog. "
"If no ACLs are provided here and a new catalog is being created, "
"default ACLs will be used."),
"properties": {
"owner": {
"type": "array",
"description": "Formatted UUIDs for 'owner' permissions.",
"items": {
"type": "string",
"description": "One UUID"
}
},
"insert": {
"type": "array",
"description": "Formatted UUIDs for 'insert' permissions.",
"items": {
"type": "string",
"description": "One UUID"
}
},
"update": {
"type": "array",
"description": "Formatted UUIDs for 'update' permissions.",
"items": {
"type": "string",
"description": "One UUID"
}
},
"delete": {
"type": "array",
"description": "Formatted UUIDs for 'delete' permissions.",
"items": {
"type": "string",
"description": "One UUID"
}
},
"select": {
"type": "array",
"description": "Formatted UUIDs for 'select' permissions.",
"items": {
"type": "string",
"description": "One UUID"
}
},
"enumerate": {
"type": "array",
"description": "Formatted UUIDs for 'enumerate' permissions.",
"items": {
"type": "string",
"description": "One UUID"
}
}
}
}
},
"required": ["operation"]
}
# TODO
OUTPUT_SCHEMA = {
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "Deriva Demo Output",
"description": "Output schema for the demo Deriva ingest Action Provider.",
"type": "object",
"properties": {
},
"required": [
]
}
|
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 2 07:15:26 2022
@author: ACER
"""
# lista en blanco
lista = []
#lista con elementos
รฑistElementos = [1,3,4,5]
#acceder a los elementos
listAlumnos = ["adri","rither","jose","juan"]
alumnoPos_1 =listAlumnos[len(listAlumnos)-1] #'juan'
#obtener el tamanio de la lista
tamanioListaAlumnos = len(listAlumnos)
print("el tamaรฑo de la lista alumnos es :",tamanioListaAlumnos)
#insertar elementos a una Lista
lista.appens(1)
lista.appens(2)
lista.appens(5)
# lista [1,2,3]
#lista [1,2,3,5]
# insertar un elemento en un indice de la lista
#insert (indice(0,tamanio_1),elemento)
lista.insert(2,3)
print(lista)
# eliminar elementos de una lista
# lista [1,2,3,5]
lista.pop(0)
# lista [2,3]
print(lista)
listaDocentes = ['jhonny','caballero','haku']
listaDocentes.remove('caballero')
#['jhonny', 'haku']
print(listaDocentes)
# iterar listas
for Docente in listaDocentes:
print(Docente)
tamanioListaDocentes = len(listaDocentes)
for i in range(0, tamanioListaDocentes):
print(listaDocentes[i])
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.