content
stringlengths 7
1.05M
| fixed_cases
stringlengths 1
1.28M
|
---|---|
'''
Created on 2020-04-15 14:50:02
Last modified on 2020-05-07 21:21:10
Python 2.7.16
v0.1
@author: L. F. Pereira ([email protected])
Main goal
---------
Develop functions to get data from odb files.
'''
#%% history outputs
def get_xydata_from_nodes_history_output(odb, nodes, variable,
directions=(1, 2, 3),
step_name=None):
'''
Given a node array, returns the values for time and the given variable.
Assumes the variable was requested in history outputs.
Parameters
----------
odb : Abaqus odb object
nodes : array-like of Abaqus OdbMeshNode objects
variable : str
It only works for vector-like variables. e.g. 'U' and 'RF'
directions : array
Directions for which to extract values.
step_name : str
If None, it uses the last step.
Returns
-------
y : array-like, shape = [n_nodes x [n_increments x n_directions]]
Notes
-----
-Assumes all the nodes have history output and the array contains each node
only once.
'''
# initialization
if not step_name:
step_name = odb.steps.keys()[-1]
step = odb.steps[step_name]
# collect data
y = []
for node in nodes:
instance_name = node.instanceName if node.instanceName else 'ASSEMBLY'
name = 'Node ' + instance_name + '.' + str(node.label)
historyOutputs = step.historyRegions[name].historyOutputs
node_data = []
for direction in directions:
node_data.append([data[1] for data in historyOutputs['%s%i' % (variable, direction)].data])
y.append(node_data)
return y
#%% field outputs
def get_ydata_from_nodeSets_field_output(odb, nodeSet, variable,
directions=(1, 2, 3), step_name=None,
frames=None):
'''
Given a node set, returns the values for the given variable.
It may take a while to run.
Parameters
----------
odb : Abaqus odb object
nodeSet : Abaqus nodeSet object
variable : str
It only works for vector-like variables. e.g. 'U' and 'RF'
directions : array
Directions for which to extract values. The value will be subtracted
by 1 when accessing abaqus data.
frames : array-like of Abaqus OdbFrame objects
If frames are available from outside, use it because it may significantly
decreases the computational time.
step_name : str
If None, it uses the last step. Only required if frames=None.
Returns
-------
values : array-like, shape = [n_increments x n_directions x n_nodes]]
'''
# TODO: extend to scalar and tensor like variables
# TODO: change name to accept also elements (position should be an input)
# access frames
if not frames:
if not step_name:
step_name = odb.steps.keys()[-1]
frames = [frame for frame in odb.steps[step_name].frames]
# collect data
values = []
for frame in frames:
varFieldOutputs = frame.fieldOutputs[variable]
outputs = varFieldOutputs.getSubset(region=nodeSet).values
output_frame = []
for direction in directions:
output_frame.append([output.data[direction - 1] for output in outputs])
values.append(output_frame)
return values
#%% other
def get_eigenvalues(odb, frames=None, step_name=None):
'''
Parameters
----------
odb : Abaqus odb object
frames : array-like of Abaqus OdbFrame objects
step_name : str
If None, it uses the last step. Only required if frames=None.
'''
# access frames
if not frames:
if not step_name:
step_name = odb.steps.keys()[-1]
frames = [frame for frame in odb.steps[step_name].frames]
# get eigenvalues
eigenvalues = [float(frame.description.split('EigenValue =')[1]) for frame in list(frames)[1:]]
return eigenvalues
| """
Created on 2020-04-15 14:50:02
Last modified on 2020-05-07 21:21:10
Python 2.7.16
v0.1
@author: L. F. Pereira ([email protected])
Main goal
---------
Develop functions to get data from odb files.
"""
def get_xydata_from_nodes_history_output(odb, nodes, variable, directions=(1, 2, 3), step_name=None):
"""
Given a node array, returns the values for time and the given variable.
Assumes the variable was requested in history outputs.
Parameters
----------
odb : Abaqus odb object
nodes : array-like of Abaqus OdbMeshNode objects
variable : str
It only works for vector-like variables. e.g. 'U' and 'RF'
directions : array
Directions for which to extract values.
step_name : str
If None, it uses the last step.
Returns
-------
y : array-like, shape = [n_nodes x [n_increments x n_directions]]
Notes
-----
-Assumes all the nodes have history output and the array contains each node
only once.
"""
if not step_name:
step_name = odb.steps.keys()[-1]
step = odb.steps[step_name]
y = []
for node in nodes:
instance_name = node.instanceName if node.instanceName else 'ASSEMBLY'
name = 'Node ' + instance_name + '.' + str(node.label)
history_outputs = step.historyRegions[name].historyOutputs
node_data = []
for direction in directions:
node_data.append([data[1] for data in historyOutputs['%s%i' % (variable, direction)].data])
y.append(node_data)
return y
def get_ydata_from_node_sets_field_output(odb, nodeSet, variable, directions=(1, 2, 3), step_name=None, frames=None):
"""
Given a node set, returns the values for the given variable.
It may take a while to run.
Parameters
----------
odb : Abaqus odb object
nodeSet : Abaqus nodeSet object
variable : str
It only works for vector-like variables. e.g. 'U' and 'RF'
directions : array
Directions for which to extract values. The value will be subtracted
by 1 when accessing abaqus data.
frames : array-like of Abaqus OdbFrame objects
If frames are available from outside, use it because it may significantly
decreases the computational time.
step_name : str
If None, it uses the last step. Only required if frames=None.
Returns
-------
values : array-like, shape = [n_increments x n_directions x n_nodes]]
"""
if not frames:
if not step_name:
step_name = odb.steps.keys()[-1]
frames = [frame for frame in odb.steps[step_name].frames]
values = []
for frame in frames:
var_field_outputs = frame.fieldOutputs[variable]
outputs = varFieldOutputs.getSubset(region=nodeSet).values
output_frame = []
for direction in directions:
output_frame.append([output.data[direction - 1] for output in outputs])
values.append(output_frame)
return values
def get_eigenvalues(odb, frames=None, step_name=None):
"""
Parameters
----------
odb : Abaqus odb object
frames : array-like of Abaqus OdbFrame objects
step_name : str
If None, it uses the last step. Only required if frames=None.
"""
if not frames:
if not step_name:
step_name = odb.steps.keys()[-1]
frames = [frame for frame in odb.steps[step_name].frames]
eigenvalues = [float(frame.description.split('EigenValue =')[1]) for frame in list(frames)[1:]]
return eigenvalues |
P = {}
# Imputers
P['mean imp'] = {'strategy': 'mean'}
P['median imp'] = {'strategy': 'median'}
P['most freq imp'] = {'strategy': 'most_frequent'}
P['constant imp'] = {'strategy': 'constant'}
P['iterative imp'] = {'initial_strategy': 'mean',
'skip_complete': True}
| p = {}
P['mean imp'] = {'strategy': 'mean'}
P['median imp'] = {'strategy': 'median'}
P['most freq imp'] = {'strategy': 'most_frequent'}
P['constant imp'] = {'strategy': 'constant'}
P['iterative imp'] = {'initial_strategy': 'mean', 'skip_complete': True} |
#23212 | Contract with Mastema
isDS = chr.getJob() == 3100
sm.setSpeakerID(2450017)
if not sm.canHold(1142342):
sm.sendSayOkay("Please make space in your equip inventory.")
sm.dispose()
if sm.sendAskYesNo("Everything is ready. Let us begin the contract ritual. Focus on your mind."):
sm.jobAdvance(isDS and 3110 or 3120)
sm.giveItem(isDS and 1142342 or 1142554)
sm.giveAndEquip(isDS and 1099002 or 1099007) #todo: upgrade instead of replace secondary? (potentials)
sm.completeQuest(parentID)
sm.setPlayerAsSpeaker()
sm.sendNext("#b(You feel a curious energy flowing into you.)")
sm.setSpeakerID(2450017)
sm.sendNext("There... our contract is made. Now we can communicate through our minds. Isn't that neat?")
sm.dispose()
else:
sm.dispose()
| is_ds = chr.getJob() == 3100
sm.setSpeakerID(2450017)
if not sm.canHold(1142342):
sm.sendSayOkay('Please make space in your equip inventory.')
sm.dispose()
if sm.sendAskYesNo('Everything is ready. Let us begin the contract ritual. Focus on your mind.'):
sm.jobAdvance(isDS and 3110 or 3120)
sm.giveItem(isDS and 1142342 or 1142554)
sm.giveAndEquip(isDS and 1099002 or 1099007)
sm.completeQuest(parentID)
sm.setPlayerAsSpeaker()
sm.sendNext('#b(You feel a curious energy flowing into you.)')
sm.setSpeakerID(2450017)
sm.sendNext("There... our contract is made. Now we can communicate through our minds. Isn't that neat?")
sm.dispose()
else:
sm.dispose() |
#prob:lem statement: Make the below pattern. Here, n =4
#4 4 4 4 4 4 4
#4 3 3 3 3 3 4
#4 3 2 2 2 3 4
#4 3 2 1 2 3 4
#4 3 2 2 2 3 4
#4 3 3 3 3 3 4
#4 4 4 4 4 4 4
n=int(input("enter any number: "))
#n is the number for the outermost lines and val is the value to be printed in row i column j
#for first left quadrant
for i in range(1,n+1):
for j in range(1,n+1):
if(i<j):
val=i
else:
val=j
print(n-val+1, end = "")
#for right top quadrant
for j in range(n-1,0,-1):
if(i<j):
val=i
else:
val=j
print(n-val+1,end="")
print()
#for bottom left quadrant
for i in range(n-1,0,-1):
for j in range(1,n+1):
if(i<j):
val=i
else:
val=j
print(n-val+1,end="")
#for bottom right quadrant
for j in range(n-1,0,-1):
if(i<j):
val=i
else:
val=j
print(n-val+1,end="")
print()
| n = int(input('enter any number: '))
for i in range(1, n + 1):
for j in range(1, n + 1):
if i < j:
val = i
else:
val = j
print(n - val + 1, end='')
for j in range(n - 1, 0, -1):
if i < j:
val = i
else:
val = j
print(n - val + 1, end='')
print()
for i in range(n - 1, 0, -1):
for j in range(1, n + 1):
if i < j:
val = i
else:
val = j
print(n - val + 1, end='')
for j in range(n - 1, 0, -1):
if i < j:
val = i
else:
val = j
print(n - val + 1, end='')
print() |
class IntegralCalculator:
def __init__(self):
self.value = 0
self.last_time = 0
def get_current_integral(self) -> float:
return self.value
def get_and_update_integral(self, new_x, new_time) -> float:
self.update_integral(new_x, new_time)
return self.get_current_integral()
def update_integral(self, new_x, new_time):
if self.last_time == 0:
self.last_time = new_time
dt = new_time - self.last_time
self.value += dt * new_x
self.last_time = new_time
| class Integralcalculator:
def __init__(self):
self.value = 0
self.last_time = 0
def get_current_integral(self) -> float:
return self.value
def get_and_update_integral(self, new_x, new_time) -> float:
self.update_integral(new_x, new_time)
return self.get_current_integral()
def update_integral(self, new_x, new_time):
if self.last_time == 0:
self.last_time = new_time
dt = new_time - self.last_time
self.value += dt * new_x
self.last_time = new_time |
DEBUG = True
TEMPLATE_DEBUG = DEBUG
# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts
ALLOWED_HOSTS = []
ADMINS = (
('Joe Admin', '[email protected]'),
)
MANAGERS = ADMINS
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'chain',
'USER': 'yoda',
'PASSWORD': '123',
'HOST': 'localhost', # use domain socket (127.0.0.1 for TCP)
'PORT': '',
'CONN_MAX_AGE': 600, # keep connections open up to 10 minutes
}
}
# these will be used by the collector scripts and should match the username and
# password provided in the .htpasswd file that nginx is looking at
COLLECTOR_AUTH = ('yoda', '123')
# Make this unique, and don't share it with anybody.
SECRET_KEY = 'jakd82l?las{19ka0n%laoeb*klanql0?kdj01kdnc1(n=lbac'
# Local time zone for this installation. Choices can be found here:
# http://en.wikipedia.org/wiki/List_of_tz_zones_by_name
# although not all choices may be available on all operating systems.
# In a Windows environment this must be set to your system time zone.
TIME_ZONE = 'America/New_York'
# Language code for this installation. All choices can be found here:
# http://www.i18nguy.com/unicode/language-identifiers.html
LANGUAGE_CODE = 'en-us'
ZMQ_PASSTHROUGH_URL_PULL = 'tcp://127.0.0.1:31416'
ZMQ_PASSTHROUGH_URL_PUB = 'tcp://127.0.0.1:31417'
# leave the websocket host as None if it is the same as the Django host
WEBSOCKET_HOST = None
# this is the path the user will see in stream links, so it needs to match your
# front end webserver (e.g. nginx) configuration. Note this configuration has
# the trailing but not leading slash
WEBSOCKET_PATH = 'ws/'
| debug = True
template_debug = DEBUG
allowed_hosts = []
admins = (('Joe Admin', '[email protected]'),)
managers = ADMINS
databases = {'default': {'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'chain', 'USER': 'yoda', 'PASSWORD': '123', 'HOST': 'localhost', 'PORT': '', 'CONN_MAX_AGE': 600}}
collector_auth = ('yoda', '123')
secret_key = 'jakd82l?las{19ka0n%laoeb*klanql0?kdj01kdnc1(n=lbac'
time_zone = 'America/New_York'
language_code = 'en-us'
zmq_passthrough_url_pull = 'tcp://127.0.0.1:31416'
zmq_passthrough_url_pub = 'tcp://127.0.0.1:31417'
websocket_host = None
websocket_path = 'ws/' |
def countApplesAndOranges(s, t, a, b, apples, oranges):
# Write your code here
fallen_apples = 0
fallen_oranges = 0
for apple in apples:
if a + apple >= s and a + apple <= t:
fallen_apples += 1
for orange in oranges:
if b + orange >= s and b + orange <= t:
fallen_oranges += 1
print(fallen_apples)
print(fallen_oranges)
| def count_apples_and_oranges(s, t, a, b, apples, oranges):
fallen_apples = 0
fallen_oranges = 0
for apple in apples:
if a + apple >= s and a + apple <= t:
fallen_apples += 1
for orange in oranges:
if b + orange >= s and b + orange <= t:
fallen_oranges += 1
print(fallen_apples)
print(fallen_oranges) |
# Create a set and check if element already exists.
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
return len(nums) != len(set(nums)) | class Solution:
def contains_duplicate(self, nums: List[int]) -> bool:
return len(nums) != len(set(nums)) |
i = 2
while True:
if i % 3 == 0:
break
print(i)
i += 2 | i = 2
while True:
if i % 3 == 0:
break
print(i)
i += 2 |
vector_collection = {
'none': None,
'empty': [],
'numerals': [1, 1, 2, 3, 5, 8, 13, 21],
'strings': ['foo', 'bar', 'zen'],
'cities': ['san fransisco', 'buenos aires', 'bern', 'kinshasa-brazzaville', 'nairobi']
}
| vector_collection = {'none': None, 'empty': [], 'numerals': [1, 1, 2, 3, 5, 8, 13, 21], 'strings': ['foo', 'bar', 'zen'], 'cities': ['san fransisco', 'buenos aires', 'bern', 'kinshasa-brazzaville', 'nairobi']} |
'''
Key points:
- recognize that this is very similar to merging intervals (https://leetcode.com/problems/merge-intervals/description/)
- it doesn't matter which employee an interval belongs to, so just flatten
- can build result array while merging, don't have to do afterward (and don't need full merged arr)
'''
def employeeFreeTime(self, schedule):
ints = sorted([i for s in schedule for i in s], key=lambda x: x.start)
res, pre = [], ints[0]
for i in ints[1:]:
if i.start <= pre.end and i.end > pre.end:
pre.end = i.end
elif i.start > pre.end:
res.append(Interval(pre.end, i.start))
pre = i
return res
| """
Key points:
- recognize that this is very similar to merging intervals (https://leetcode.com/problems/merge-intervals/description/)
- it doesn't matter which employee an interval belongs to, so just flatten
- can build result array while merging, don't have to do afterward (and don't need full merged arr)
"""
def employee_free_time(self, schedule):
ints = sorted([i for s in schedule for i in s], key=lambda x: x.start)
(res, pre) = ([], ints[0])
for i in ints[1:]:
if i.start <= pre.end and i.end > pre.end:
pre.end = i.end
elif i.start > pre.end:
res.append(interval(pre.end, i.start))
pre = i
return res |
ligne_vide = ['o','o','o','o','o','o','o','o','o']
ligne_courte = ['o','o','.','.','.','.','.','o','o']
ligne_longue = ['o','.','.','.','.','.','.','.','o']
arche_vide = [ligne_vide,ligne_courte,ligne_longue,ligne_longue,ligne_courte,ligne_vide]
#print(arche_vide)
def affiche_ligne (l) :
s=''
for c in l :
s+=c
print(s)
def affiche_grille (g) :
for i in range(len(g)-1,-1,-1) :
affiche_ligne(g[i])
#affiche_grille(arche_vide)
def copie_grille(g) :
r = []
for l in g :
r+=[list(l)]
return r
#arche_pleine=copie_grille(arche_vide)
#arche_pleine[2][1]='i'
#affiche_grille(arche_vide)
#affiche_grille(arche_pleine)
lion_1 = ('L',1,[(0,0),(1,0)])
lion_2 = ('L',2,[(0,0),(0,1),(1,1)])
girafe_1 = ('G',1,[(0,0),(1,0),(1,1)])
girafe_2 = ('G',2,[(0,0),(0,1)])
hippopotame_1 = ('H',1,[(0,0),(1,0)])
hippopotame_2 = ('H',2,[(0,0),(1,0),(2,0)])
zebre_1 = ('Z',1,[(0,0),(1,0)])
zebre_2 = ('Z',2,[(0,0),(0,1)])
elephant_1 = ('E',1,[(0,0),(1,0)])
elephant_2 = ('E',2,[(0,0),(0,1),(1,0)])
liste_animaux = [lion_1,lion_2,girafe_1,girafe_2,hippopotame_1,hippopotame_2,zebre_1,zebre_2,elephant_1,elephant_2]
#print(liste_animaux)
def est_dans_grille (position) :
return position[0] >= 0 and position[0]<=8 and position[1]>=0 and position[1]<=7
def case_libre (position,grille) :
return est_dans_grille(position) and grille[position[1]][position[0]] == '.'
def place_libre (position,grille,animal) :
r = True
(x,y) = position
for (dx,dy) in animal[2] :
p = (x+dx,y+dy)
r = r and case_libre(p,grille)
return r
#test, on attend False, True, False, True
#print(place_libre((0,0),arche_vide,elephant_2))
#print(place_libre((2,1),arche_vide,elephant_2))
#print(place_libre((5,4),arche_vide,elephant_2))
#print(place_libre((6,3),arche_vide,elephant_2))
def installe_animal (position,grille,animal) :
(x,y) = position
for (dx,dy) in animal[2] :
p = (x+dx,y+dy)
grille[p[1]][p[0]] = animal[0]
def enleve_animal (position,grille,animal) :
(x,y) = position
for (dx,dy) in animal[2] :
p = (x+dx,y+dy)
grille[p[1]][p[0]] = '.'
#arche_pleine = copie_grille(arche_vide)
#installe_animal((6,3),arche_pleine,elephant_2)
#affiche_grille(arche_pleine)
#enleve_animal((6,3),arche_pleine,elephant_2)
#affiche_grille(arche_pleine)
def installe_tous (placement,grille) :
for (a,p) in placement :
if not place_libre(p,grille,a) :
return False
else :
installe_animal(p,grille,a)
return True
placement_1 = [(lion_1,(2,4)),\
(lion_2,(4,3)),\
(girafe_1,(6,2)),\
(girafe_2,(6,3)),\
(hippopotame_1,(2,1)),\
(hippopotame_2,(4,1)),\
(zebre_1,(3,2)),\
(zebre_2,(5,2)),\
(elephant_1,(2,3)),\
(elephant_2,(1,2))]
arche_pleine = copie_grille (arche_vide)
print("installe tous = ", installe_tous(placement_1,arche_pleine))
affiche_grille(arche_pleine)
print("")
def decale_animal (animal,position) :
place = []
(x,y) = position
for (dx,dy) in animal[2] :
place += [(x+dx,y+dy)]
return place
def cases_voisines (place) :
voisines = []
for (x,y) in place :
voisines += [(x+1,y),(x,y+1),(x-1,y),(x,y-1)]
return voisines
def sont_voisins (a1,p1,a2,p2) :
place_1 = decale_animal(a1,p1)
place_2 = decale_animal(a2,p2)
voisines_1 = cases_voisines(place_1)
r = False
for c in voisines_1 :
r = r or ( c in place_2 )
return r
# test sur placement_1
#print(sont_voisins(lion_1,(2,4),lion_2,(4,3)))
#print(sont_voisins(girafe_1,(6,2),girafe_2,(6,3)))
#print(sont_voisins(lion_1,(2,4),girafe_2,(6,3)))
#print(sont_voisins(lion_2,(4,3),girafe_2,(6,3)))
def cherche_animal (type_anim,num,installation) :
for i in range(len(installation)) :
(a,p) = installation[i]
if a[0] == type_anim and a[1] == num :
return i
return -1
#print (cherche_animal('G',2,placement_1))
#print (cherche_animal('Z',1,placement_1))
#print (cherche_animal('G',3,placement_1))
def verifie_voisinages (installation) :
r = True
for t in ['L','G','H','Z','E'] :
i1 = cherche_animal(t,1,installation)
i2 = cherche_animal(t,2,installation)
(a1,p1) = installation[i1]
(a2,p2) = installation[i2]
r = r and sont_voisins (a1,p1,a2,p2)
# print (a1,a2,sont_voisins (a1,p1,a2,p2))
return r
#print(verifie_voisinages(placement_1))
def calculer_installation (grille, animaux, installation) :
if animaux == [] :
return verifie_voisinages(installation)
else :
a = animaux[0]
for y in range(len(grille)) :
for x in range(len(grille[0])) :
if place_libre((x,y),grille,a) :
installe_animal((x,y),grille,a)
r = calculer_installation(grille,animaux[1:],[(a,(x,y))] + installation)
if r :
return r
else :
enleve_animal((x,y),grille,a)
return False
arche = copie_grille(arche_vide)
installe_animal((4,1),arche,lion_2)
affiche_grille(arche)
installation = [(lion_2,(4,1))]
animaux = [lion_1,girafe_1,girafe_2,hippopotame_1,hippopotame_2,zebre_1,zebre_2,elephant_1,elephant_2]
calculer_installation(arche,animaux,installation)
affiche_grille(arche)
| ligne_vide = ['o', 'o', 'o', 'o', 'o', 'o', 'o', 'o', 'o']
ligne_courte = ['o', 'o', '.', '.', '.', '.', '.', 'o', 'o']
ligne_longue = ['o', '.', '.', '.', '.', '.', '.', '.', 'o']
arche_vide = [ligne_vide, ligne_courte, ligne_longue, ligne_longue, ligne_courte, ligne_vide]
def affiche_ligne(l):
s = ''
for c in l:
s += c
print(s)
def affiche_grille(g):
for i in range(len(g) - 1, -1, -1):
affiche_ligne(g[i])
def copie_grille(g):
r = []
for l in g:
r += [list(l)]
return r
lion_1 = ('L', 1, [(0, 0), (1, 0)])
lion_2 = ('L', 2, [(0, 0), (0, 1), (1, 1)])
girafe_1 = ('G', 1, [(0, 0), (1, 0), (1, 1)])
girafe_2 = ('G', 2, [(0, 0), (0, 1)])
hippopotame_1 = ('H', 1, [(0, 0), (1, 0)])
hippopotame_2 = ('H', 2, [(0, 0), (1, 0), (2, 0)])
zebre_1 = ('Z', 1, [(0, 0), (1, 0)])
zebre_2 = ('Z', 2, [(0, 0), (0, 1)])
elephant_1 = ('E', 1, [(0, 0), (1, 0)])
elephant_2 = ('E', 2, [(0, 0), (0, 1), (1, 0)])
liste_animaux = [lion_1, lion_2, girafe_1, girafe_2, hippopotame_1, hippopotame_2, zebre_1, zebre_2, elephant_1, elephant_2]
def est_dans_grille(position):
return position[0] >= 0 and position[0] <= 8 and (position[1] >= 0) and (position[1] <= 7)
def case_libre(position, grille):
return est_dans_grille(position) and grille[position[1]][position[0]] == '.'
def place_libre(position, grille, animal):
r = True
(x, y) = position
for (dx, dy) in animal[2]:
p = (x + dx, y + dy)
r = r and case_libre(p, grille)
return r
def installe_animal(position, grille, animal):
(x, y) = position
for (dx, dy) in animal[2]:
p = (x + dx, y + dy)
grille[p[1]][p[0]] = animal[0]
def enleve_animal(position, grille, animal):
(x, y) = position
for (dx, dy) in animal[2]:
p = (x + dx, y + dy)
grille[p[1]][p[0]] = '.'
def installe_tous(placement, grille):
for (a, p) in placement:
if not place_libre(p, grille, a):
return False
else:
installe_animal(p, grille, a)
return True
placement_1 = [(lion_1, (2, 4)), (lion_2, (4, 3)), (girafe_1, (6, 2)), (girafe_2, (6, 3)), (hippopotame_1, (2, 1)), (hippopotame_2, (4, 1)), (zebre_1, (3, 2)), (zebre_2, (5, 2)), (elephant_1, (2, 3)), (elephant_2, (1, 2))]
arche_pleine = copie_grille(arche_vide)
print('installe tous = ', installe_tous(placement_1, arche_pleine))
affiche_grille(arche_pleine)
print('')
def decale_animal(animal, position):
place = []
(x, y) = position
for (dx, dy) in animal[2]:
place += [(x + dx, y + dy)]
return place
def cases_voisines(place):
voisines = []
for (x, y) in place:
voisines += [(x + 1, y), (x, y + 1), (x - 1, y), (x, y - 1)]
return voisines
def sont_voisins(a1, p1, a2, p2):
place_1 = decale_animal(a1, p1)
place_2 = decale_animal(a2, p2)
voisines_1 = cases_voisines(place_1)
r = False
for c in voisines_1:
r = r or c in place_2
return r
def cherche_animal(type_anim, num, installation):
for i in range(len(installation)):
(a, p) = installation[i]
if a[0] == type_anim and a[1] == num:
return i
return -1
def verifie_voisinages(installation):
r = True
for t in ['L', 'G', 'H', 'Z', 'E']:
i1 = cherche_animal(t, 1, installation)
i2 = cherche_animal(t, 2, installation)
(a1, p1) = installation[i1]
(a2, p2) = installation[i2]
r = r and sont_voisins(a1, p1, a2, p2)
return r
def calculer_installation(grille, animaux, installation):
if animaux == []:
return verifie_voisinages(installation)
else:
a = animaux[0]
for y in range(len(grille)):
for x in range(len(grille[0])):
if place_libre((x, y), grille, a):
installe_animal((x, y), grille, a)
r = calculer_installation(grille, animaux[1:], [(a, (x, y))] + installation)
if r:
return r
else:
enleve_animal((x, y), grille, a)
return False
arche = copie_grille(arche_vide)
installe_animal((4, 1), arche, lion_2)
affiche_grille(arche)
installation = [(lion_2, (4, 1))]
animaux = [lion_1, girafe_1, girafe_2, hippopotame_1, hippopotame_2, zebre_1, zebre_2, elephant_1, elephant_2]
calculer_installation(arche, animaux, installation)
affiche_grille(arche) |
class TalkMessage:
def __init__(self, messageId, timeStamp, body, senderAvatarId, senderAvatarName, senderAccountId, senderAccountName, receiverAvatarId, receiverAvatarName, receiverAccountId, receiverAccountName, talkType, extraInfo=None):
self.timeStamp = timeStamp
self.body = body
self.senderAvatarId = senderAvatarId
self.senderAvatarName = senderAvatarName
self.senderAccountId = senderAccountId
self.senderAccountName = senderAccountName
self.receiverAvatarId = receiverAvatarId
self.receiverAvatarName = receiverAvatarName
self.receiverAccountId = receiverAccountId
self.receiverAccountName = receiverAccountName
self.talkType = talkType
self.extraInfo = extraInfo
self.messageId = messageId
def getMessageId(self):
return self.messageId
def setMessageId(self, id):
self.messageId = id
def getTimeStamp(self):
return self.timeStamp
def setTimeStamp(self, timeStamp):
self.timeStamp = timeStamp
def getBody(self):
return self.body
def setBody(self, body):
self.body = body
def getSenderAvatarId(self):
return self.senderAvatarId
def setSenderAvatarId(self, senderAvatarId):
self.senderAvatarId = senderAvatarId
def getSenderAvatarName(self):
return self.senderAvatarName
def setSenderAvatarName(self, senderAvatarName):
self.senderAvatarName = senderAvatarName
def getSenderAccountId(self):
return self.senderAccountId
def setSenderAccountId(self, senderAccountId):
self.senderAccountId = senderAccountId
def getSenderAccountName(self):
return self.senderAccountName
def setSenderAccountName(self, senderAccountName):
self.senderAccountName = senderAccountName
def getReceiverAvatarId(self):
return self.receiverAvatarId
def setReceiverAvatarId(self, receiverAvatarId):
self.receiverAvatarId = receiverAvatarId
def getReceiverAvatarName(self):
return self.receiverAvatarName
def setReceiverAvatarName(self, receiverAvatarName):
self.receiverAvatarName = receiverAvatarName
def getReceiverAccountId(self):
return self.receiverAccountId
def setReceiverAccountId(self, receiverAccountId):
self.receiverAccountId = receiverAccountId
def getReceiverAccountName(self):
return self.receiverAccountName
def setReceiverAccountName(self, receiverAccountName):
self.receiverAccountName = receiverAccountName
def getTalkType(self):
return self.talkType
def setTalkType(self, talkType):
self.talkType = talkType
def getExtraInfo(self):
return self.extraInfo
def setExtraInfo(self, extraInfo):
self.extraInfo = extraInfo | class Talkmessage:
def __init__(self, messageId, timeStamp, body, senderAvatarId, senderAvatarName, senderAccountId, senderAccountName, receiverAvatarId, receiverAvatarName, receiverAccountId, receiverAccountName, talkType, extraInfo=None):
self.timeStamp = timeStamp
self.body = body
self.senderAvatarId = senderAvatarId
self.senderAvatarName = senderAvatarName
self.senderAccountId = senderAccountId
self.senderAccountName = senderAccountName
self.receiverAvatarId = receiverAvatarId
self.receiverAvatarName = receiverAvatarName
self.receiverAccountId = receiverAccountId
self.receiverAccountName = receiverAccountName
self.talkType = talkType
self.extraInfo = extraInfo
self.messageId = messageId
def get_message_id(self):
return self.messageId
def set_message_id(self, id):
self.messageId = id
def get_time_stamp(self):
return self.timeStamp
def set_time_stamp(self, timeStamp):
self.timeStamp = timeStamp
def get_body(self):
return self.body
def set_body(self, body):
self.body = body
def get_sender_avatar_id(self):
return self.senderAvatarId
def set_sender_avatar_id(self, senderAvatarId):
self.senderAvatarId = senderAvatarId
def get_sender_avatar_name(self):
return self.senderAvatarName
def set_sender_avatar_name(self, senderAvatarName):
self.senderAvatarName = senderAvatarName
def get_sender_account_id(self):
return self.senderAccountId
def set_sender_account_id(self, senderAccountId):
self.senderAccountId = senderAccountId
def get_sender_account_name(self):
return self.senderAccountName
def set_sender_account_name(self, senderAccountName):
self.senderAccountName = senderAccountName
def get_receiver_avatar_id(self):
return self.receiverAvatarId
def set_receiver_avatar_id(self, receiverAvatarId):
self.receiverAvatarId = receiverAvatarId
def get_receiver_avatar_name(self):
return self.receiverAvatarName
def set_receiver_avatar_name(self, receiverAvatarName):
self.receiverAvatarName = receiverAvatarName
def get_receiver_account_id(self):
return self.receiverAccountId
def set_receiver_account_id(self, receiverAccountId):
self.receiverAccountId = receiverAccountId
def get_receiver_account_name(self):
return self.receiverAccountName
def set_receiver_account_name(self, receiverAccountName):
self.receiverAccountName = receiverAccountName
def get_talk_type(self):
return self.talkType
def set_talk_type(self, talkType):
self.talkType = talkType
def get_extra_info(self):
return self.extraInfo
def set_extra_info(self, extraInfo):
self.extraInfo = extraInfo |
''' While Loops
Used to execute a set of statements(code) continuously as long as a condition is True.
The while loop needs to be setup in a way that as long as a condition is True, Then stop when the condition becomes False.
While loop can have optional else clause.
'''
i = 1
| """ While Loops
Used to execute a set of statements(code) continuously as long as a condition is True.
The while loop needs to be setup in a way that as long as a condition is True, Then stop when the condition becomes False.
While loop can have optional else clause.
"""
i = 1 |
def get_f(f, i, mode):
try:
if mode == 0:
return f[f[i]]
if mode == 1:
return f[i]
except KeyError:
return 0
raise NotImplementedError
def set_f(f, value, i, mode):
if mode == 0:
f[f[i]] = value
return
if mode == 1:
f[i] = value
return
raise NotImplementedError
def main():
f = [int(i) for i in [line.rstrip("\n") for line in open("Data.txt")][0].split(",")]
input = 1
i = 0
while True:
opcode = int(str(f[i])[-2:])
try:
immediate = int(str(f[i])[:-2])
except ValueError:
immediate = 0
i1 = immediate % 10
i2 = immediate//10 % 10
if opcode == 99:
break
elif opcode == 1:
set_f(f, get_f(f, i + 1, i1) + get_f(f, i + 2, i2), i + 3, 0)
i += 4
elif opcode == 2:
set_f(f, get_f(f, i + 1, i1)*get_f(f, i + 2, i2), i + 3, 0)
i += 4
elif opcode == 3:
set_f(f, input, i + 1, 0)
i += 2
elif opcode == 4:
print(get_f(f, i + 1, i1))
i += 2
else:
raise NotImplementedError
if __name__ == "__main__":
main()
| def get_f(f, i, mode):
try:
if mode == 0:
return f[f[i]]
if mode == 1:
return f[i]
except KeyError:
return 0
raise NotImplementedError
def set_f(f, value, i, mode):
if mode == 0:
f[f[i]] = value
return
if mode == 1:
f[i] = value
return
raise NotImplementedError
def main():
f = [int(i) for i in [line.rstrip('\n') for line in open('Data.txt')][0].split(',')]
input = 1
i = 0
while True:
opcode = int(str(f[i])[-2:])
try:
immediate = int(str(f[i])[:-2])
except ValueError:
immediate = 0
i1 = immediate % 10
i2 = immediate // 10 % 10
if opcode == 99:
break
elif opcode == 1:
set_f(f, get_f(f, i + 1, i1) + get_f(f, i + 2, i2), i + 3, 0)
i += 4
elif opcode == 2:
set_f(f, get_f(f, i + 1, i1) * get_f(f, i + 2, i2), i + 3, 0)
i += 4
elif opcode == 3:
set_f(f, input, i + 1, 0)
i += 2
elif opcode == 4:
print(get_f(f, i + 1, i1))
i += 2
else:
raise NotImplementedError
if __name__ == '__main__':
main() |
USER = "__DUMMY_TRANSFORMERS_USER__"
FULL_NAME = "Dummy User"
PASS = "__DUMMY_TRANSFORMERS_PASS__"
# Not critical, only usable on the sandboxed CI instance.
TOKEN = "hf_94wBhPGp6KrrTH3KDchhKpRxZwd6dmHWLL"
ENDPOINT_PRODUCTION = "https://huggingface.co"
ENDPOINT_STAGING = "https://hub-ci.huggingface.co"
ENDPOINT_STAGING_BASIC_AUTH = f"https://{USER}:{PASS}@hub-ci.huggingface.co"
ENDPOINT_PRODUCTION_URL_SCHEME = (
ENDPOINT_PRODUCTION + "/{repo_id}/resolve/{revision}/{filename}"
)
| user = '__DUMMY_TRANSFORMERS_USER__'
full_name = 'Dummy User'
pass = '__DUMMY_TRANSFORMERS_PASS__'
token = 'hf_94wBhPGp6KrrTH3KDchhKpRxZwd6dmHWLL'
endpoint_production = 'https://huggingface.co'
endpoint_staging = 'https://hub-ci.huggingface.co'
endpoint_staging_basic_auth = f'https://{USER}:{PASS}@hub-ci.huggingface.co'
endpoint_production_url_scheme = ENDPOINT_PRODUCTION + '/{repo_id}/resolve/{revision}/{filename}' |
print("copy content from auto created ex23_sample_05.txt to ex23_sample_06.txt using 1 line only")
input('In powershell: echo "This is a unicode Test." > ex23_sample_05.txt ')
in_file = open('c:\\users\\roy\\ex23_sample_05.txt', encoding = 'utf-16').read()
out_file = open('c:\\users\\roy\\ex23_sample_06.txt', 'w', encoding = 'utf-16').write(in_file)
print("DONE!\n")
#-------------------------------------------------------------------
print("-------------------------------------------------------------")
print("copy content from languages.txt within ex23 to languages2.txt using 1 line only")
in_file = open('c:\\users\\roy\\languages.txt', encoding = 'utf-8').read()
# When set encoding = utf-16 --> UnicodeDecodeError: 'utf-16-le' codec can't decode bytes in position 812-813: illegal UTF-16 surrogate
# When set encoding = utf-16, errors = 'ignore' --> UnicodeError: UTF-16 stream does not start with BOM
out_file = open('c:\\users\\roy\\languages2.txt', 'w', encoding = 'utf-8').write(in_file)
# Before add encoding = utf-8 -->UnicodeEncodeError: 'gbk' codec can't encode character '\u0a73' in position 4: illegal multibyte sequence
print("DONE!\n")
# bytes can only contain ASCII literal characters. | print('copy content from auto created ex23_sample_05.txt to ex23_sample_06.txt using 1 line only')
input('In powershell: echo "This is a unicode Test." > ex23_sample_05.txt ')
in_file = open('c:\\users\\roy\\ex23_sample_05.txt', encoding='utf-16').read()
out_file = open('c:\\users\\roy\\ex23_sample_06.txt', 'w', encoding='utf-16').write(in_file)
print('DONE!\n')
print('-------------------------------------------------------------')
print('copy content from languages.txt within ex23 to languages2.txt using 1 line only')
in_file = open('c:\\users\\roy\\languages.txt', encoding='utf-8').read()
out_file = open('c:\\users\\roy\\languages2.txt', 'w', encoding='utf-8').write(in_file)
print('DONE!\n') |
sum = 0
count = 0
while True:
try:
name = input()
distance = int(input())
sum += distance
count += 1
except EOFError:
break
print("{:.1f}".format(sum/count)) | sum = 0
count = 0
while True:
try:
name = input()
distance = int(input())
sum += distance
count += 1
except EOFError:
break
print('{:.1f}'.format(sum / count)) |
# -*- coding: utf-8 -*-
#from scrapy.settings.default_settings import DOWNLOAD_DELAY
#from scrapy.settings.default_settings import ITEM_PIPELINES
# Scrapy settings for fbo_scraper project
#
# For simplicity, this file contains only the most important settings by
# default. All the other settings are documented here:
#
# http://doc.scrapy.org/en/latest/topics/settings.html
#
BOT_NAME = 'packard_scraper'
SPIDER_MODULES = ['packard_scraper.spiders']
ITEM_PIPELINES = {'packard_scraper.pipelines.FboScraperExcelPipeline':0}
NEWSPIDER_MODULE = 'packard_scraper.spiders'
ROBOTSTXT_OBEY = True
RANDOMIZE_DOWNLOAD_DELAY = True
DOWNLOAD_DELAY = 5.0
# Crawl responsibly by identifying yourself (and your website) on the user-agent
# !!! ATTENTION: PLEASE REPLACE WITH YOUR OWN WEBSITE IF YOU ARE GOING TO USE USER_AGENT!
USER_AGENT = 'packard_scraper (+http://research.umd.edu/)'
| bot_name = 'packard_scraper'
spider_modules = ['packard_scraper.spiders']
item_pipelines = {'packard_scraper.pipelines.FboScraperExcelPipeline': 0}
newspider_module = 'packard_scraper.spiders'
robotstxt_obey = True
randomize_download_delay = True
download_delay = 5.0
user_agent = 'packard_scraper (+http://research.umd.edu/)' |
#Factorial de un numero, usar recursividad.
def factorial(number):
if number == 0:
return 1
return number * factorial(number - 1)
if __name__ == '__main__':
number = int(input('Ingrese numero a convertir en factorial: '))
result = factorial(number)
print('El resultado es: {}'.format(result))
| def factorial(number):
if number == 0:
return 1
return number * factorial(number - 1)
if __name__ == '__main__':
number = int(input('Ingrese numero a convertir en factorial: '))
result = factorial(number)
print('El resultado es: {}'.format(result)) |
class Student:
def __init__(self, name, school):
self.name = name
self.school = school
self.marks = []
def average(self):
return sum(self.marks) / len(self.marks)
def go_to_school(self):
return "I'm going to {}".format(self.school)
anna = Student("Anna", "Oxford")
rolf = Student("Rolf", "Harvard")
print(anna.go_to_school())
print(rolf.go_to_school())
###
class Student:
def __init__(self, name, school):
self.name = name
self.school = school
self.marks = []
def average(self):
return sum(self.marks) / len(self.marks)
def go_to_school(self):
return "I'm going to school"
anna = Student("Anna", "Oxford")
rolf = Student("Rolf", "Harvard")
print(anna.go_to_school())
print(rolf.go_to_school())
###
class Student:
def __init__(self, name, school):
self.name = name
self.school = school
self.marks = []
def average(self):
return sum(self.marks) / len(self.marks)
@staticmethod
def go_to_school():
return "I'm going to school"
anna = Student("Anna", "Oxford")
rolf = Student("Rolf", "Harvard")
print(anna.go_to_school())
print(rolf.go_to_school())
###
class Student:
def __init__(self, name, school):
self.name = name
self.school = school
self.marks = []
def average(self):
return sum(self.marks) / len(self.marks)
def friend(self, friend_name):
return Student(friend_name, self.school)
anna = Student("Anna", "Oxford")
friend = anna.friend("Greg")
print(friend.name)
print(friend.school)
| class Student:
def __init__(self, name, school):
self.name = name
self.school = school
self.marks = []
def average(self):
return sum(self.marks) / len(self.marks)
def go_to_school(self):
return "I'm going to {}".format(self.school)
anna = student('Anna', 'Oxford')
rolf = student('Rolf', 'Harvard')
print(anna.go_to_school())
print(rolf.go_to_school())
class Student:
def __init__(self, name, school):
self.name = name
self.school = school
self.marks = []
def average(self):
return sum(self.marks) / len(self.marks)
def go_to_school(self):
return "I'm going to school"
anna = student('Anna', 'Oxford')
rolf = student('Rolf', 'Harvard')
print(anna.go_to_school())
print(rolf.go_to_school())
class Student:
def __init__(self, name, school):
self.name = name
self.school = school
self.marks = []
def average(self):
return sum(self.marks) / len(self.marks)
@staticmethod
def go_to_school():
return "I'm going to school"
anna = student('Anna', 'Oxford')
rolf = student('Rolf', 'Harvard')
print(anna.go_to_school())
print(rolf.go_to_school())
class Student:
def __init__(self, name, school):
self.name = name
self.school = school
self.marks = []
def average(self):
return sum(self.marks) / len(self.marks)
def friend(self, friend_name):
return student(friend_name, self.school)
anna = student('Anna', 'Oxford')
friend = anna.friend('Greg')
print(friend.name)
print(friend.school) |
# Part 2 on day 2 on advent of code
#
# Tyler Stuessi
def get_bathroom_code():
# get input
code = ""
keypaths = []
try:
while True:
raw = input()
keypaths.append(raw)
except EOFError:
pass
# hard code the grid
grid = [["0", "0", "1", "0", "0"],
["0", "2", "3", "4", "0"],
["5", "6", "7", "8", "9"],
["0", "A", "B", "C", "0"],
["0", "0", "D", "0", "0"]]
row = 2
col = 2
for path in keypaths:
for c in path:
if c == "L" and col != 0 and grid[row][col-1] != "0":
col -= 1
elif c == "U" and row != 0 and grid[row-1][col] != "0":
row -= 1
elif c == "D" and row != len(grid)-1 and grid[row+1][col] != "0":
row += 1
elif c == "R" and col != len(grid[row])-1 and grid[row][col+1] != "0":
col += 1
code += grid[row][col]
return code
if __name__ == "__main__":
print(get_bathroom_code())
| def get_bathroom_code():
code = ''
keypaths = []
try:
while True:
raw = input()
keypaths.append(raw)
except EOFError:
pass
grid = [['0', '0', '1', '0', '0'], ['0', '2', '3', '4', '0'], ['5', '6', '7', '8', '9'], ['0', 'A', 'B', 'C', '0'], ['0', '0', 'D', '0', '0']]
row = 2
col = 2
for path in keypaths:
for c in path:
if c == 'L' and col != 0 and (grid[row][col - 1] != '0'):
col -= 1
elif c == 'U' and row != 0 and (grid[row - 1][col] != '0'):
row -= 1
elif c == 'D' and row != len(grid) - 1 and (grid[row + 1][col] != '0'):
row += 1
elif c == 'R' and col != len(grid[row]) - 1 and (grid[row][col + 1] != '0'):
col += 1
code += grid[row][col]
return code
if __name__ == '__main__':
print(get_bathroom_code()) |
def fizz_buzz(input):
result = []
for x in range(1, input + 1):
value = ''
if x % 3 == 0:
value += 'Fizz'
if x % 5 == 0:
value += 'Buzz'
value = value or x
result.append(value)
return result
| def fizz_buzz(input):
result = []
for x in range(1, input + 1):
value = ''
if x % 3 == 0:
value += 'Fizz'
if x % 5 == 0:
value += 'Buzz'
value = value or x
result.append(value)
return result |
# This sample tests annotated types on global variables.
# This should generate an error because the declared
# type below does not match the assigned type.
glob_var1 = 4
# This should generate an error because the declared
# type doesn't match the later declared type.
glob_var1 = Exception() # type: str
glob_var1 = Exception() # type: Exception
# This should generate an error because the assigned
# type doesn't match the declared type.
glob_var1 = "hello" # type: Exception
# This should generate an error.
glob_var2 = 5
def func1():
global glob_var1
global glob_var2
# This should generate an error.
glob_var1 = 3
glob_var2 = "hello" # type: str
| glob_var1 = 4
glob_var1 = exception()
glob_var1 = exception()
glob_var1 = 'hello'
glob_var2 = 5
def func1():
global glob_var1
global glob_var2
glob_var1 = 3
glob_var2 = 'hello' |
N = int(input())
for i in range(1, N):
print(' ' * (N - i) + '*' * ((i * 2) - 1))
for i in range(N, 0, -1):
print(' ' * (N - i) + '*' * ((i * 2) - 1)) | n = int(input())
for i in range(1, N):
print(' ' * (N - i) + '*' * (i * 2 - 1))
for i in range(N, 0, -1):
print(' ' * (N - i) + '*' * (i * 2 - 1)) |
#!/usr/bin/env python
__all__ = [
"test_misc",
"test_dictarray",
"test_table",
"test_transform",
"test_recode_alignment",
"test_union_dict",
]
__author__ = ""
__copyright__ = "Copyright 2007-2022, The Cogent Project"
__credits__ = [
"Jeremy Widmann",
"Sandra Smit",
"Gavin Huttley",
"Rob Knight",
"Zongzhi Liu",
"Amanda Birmingham",
"Greg Caporaso",
]
__license__ = "BSD-3"
__version__ = "2022.4.20a1"
__maintainer__ = "Gavin Huttley"
__email__ = "[email protected]"
__status__ = "Production"
| __all__ = ['test_misc', 'test_dictarray', 'test_table', 'test_transform', 'test_recode_alignment', 'test_union_dict']
__author__ = ''
__copyright__ = 'Copyright 2007-2022, The Cogent Project'
__credits__ = ['Jeremy Widmann', 'Sandra Smit', 'Gavin Huttley', 'Rob Knight', 'Zongzhi Liu', 'Amanda Birmingham', 'Greg Caporaso']
__license__ = 'BSD-3'
__version__ = '2022.4.20a1'
__maintainer__ = 'Gavin Huttley'
__email__ = '[email protected]'
__status__ = 'Production' |
class Config(object):
DEBUG = False
TESTING = False
SECRET_KEY = "B\xb2?.\xdf\x9f\xa7m\xf8\x8a%,\xf7\xc4\xfa\x91"
MONGO_URI="mongodb://localhost:27017/test"
IMAGE_UPLOADS = "/home/username/projects/my_app/app/static/images/uploads"
SESSION_COOKIE_SECURE = False
class ProductionConfig(Config):
DEBUG = False
MONGO_URI="mongodb://localhost:27017/"
DB_NAME="test"
IMAGE_UPLOADS = "/home/username/projects/my_app/app/static/images/uploads"
SESSION_COOKIE_SECURE = True
class DevelopmentConfig(Config):
DEBUG = True
MONGO_URI="mongodb://localhost:27017/"
DB_NAME="test"
IMAGE_UPLOADS = "/home/username/projects/my_app/app/static/images/uploads"
SESSION_COOKIE_SECURE = False
class TestingConfig(Config):
TESTING = True
MONGO_URI="mongodb://localhost:27017/test"
IMAGE_UPLOADS = "/home/username/projects/my_app/app/static/images/uploads"
SESSION_COOKIE_SECURE = False | class Config(object):
debug = False
testing = False
secret_key = 'B²?.ß\x9f§mø\x8a%,÷Äú\x91'
mongo_uri = 'mongodb://localhost:27017/test'
image_uploads = '/home/username/projects/my_app/app/static/images/uploads'
session_cookie_secure = False
class Productionconfig(Config):
debug = False
mongo_uri = 'mongodb://localhost:27017/'
db_name = 'test'
image_uploads = '/home/username/projects/my_app/app/static/images/uploads'
session_cookie_secure = True
class Developmentconfig(Config):
debug = True
mongo_uri = 'mongodb://localhost:27017/'
db_name = 'test'
image_uploads = '/home/username/projects/my_app/app/static/images/uploads'
session_cookie_secure = False
class Testingconfig(Config):
testing = True
mongo_uri = 'mongodb://localhost:27017/test'
image_uploads = '/home/username/projects/my_app/app/static/images/uploads'
session_cookie_secure = False |
# Real part of spherical harmonic Y_(4,2)(theta,phi)
def Y(l,m):
def g(theta,phi):
R = abs(fp.re(fp.spherharm(l,m,theta,phi)))
x = R*fp.cos(phi)*fp.sin(theta)
y = R*fp.sin(phi)*fp.sin(theta)
z = R*fp.cos(theta)
return [x,y,z]
return g
fp.splot(Y(4,2), [0,fp.pi], [0,2*fp.pi], points=300)
| def y(l, m):
def g(theta, phi):
r = abs(fp.re(fp.spherharm(l, m, theta, phi)))
x = R * fp.cos(phi) * fp.sin(theta)
y = R * fp.sin(phi) * fp.sin(theta)
z = R * fp.cos(theta)
return [x, y, z]
return g
fp.splot(y(4, 2), [0, fp.pi], [0, 2 * fp.pi], points=300) |
number = int(input())
if number % 2 == 1 or 6 <= number <= 20:
print('Weird')
elif 2 <= number <= 5 or number > 20:
print('Not Weird')
| number = int(input())
if number % 2 == 1 or 6 <= number <= 20:
print('Weird')
elif 2 <= number <= 5 or number > 20:
print('Not Weird') |
'''
Exercise 5:
Take the following Python code that stores a string:
str = 'X-DSPAM-Confidence:0.8475'
Use find and string slicing to extract the portion of the string\
after the colon character and then use the float function to
convert the extracted string into a floating point number.
'''
string = 'X-DSPAM-Confidence:0.8475'
num_index = string.find(':')
num_float = float(string[num_index+1:])
print(num_float, type(num_float)) | """
Exercise 5:
Take the following Python code that stores a string:
str = 'X-DSPAM-Confidence:0.8475'
Use find and string slicing to extract the portion of the string after the colon character and then use the float function to
convert the extracted string into a floating point number.
"""
string = 'X-DSPAM-Confidence:0.8475'
num_index = string.find(':')
num_float = float(string[num_index + 1:])
print(num_float, type(num_float)) |
class Song:
def __init__(self, name, length, single):
self.name = name
self.length = length
self.single = single
def get_info(self):
return f"{self.name} - {self.length}"
#Test code
# song = Song("Running in the 90s", 3.45, False)
# print(song.get_info()) | class Song:
def __init__(self, name, length, single):
self.name = name
self.length = length
self.single = single
def get_info(self):
return f'{self.name} - {self.length}' |
class MyCircularQueue:
def __init__(self, k: int):
self.q = [None] * k
self.maxlen = k
self.front = 0
self.rear = 0
def enQueue(self, value: int) -> bool:
if self.q[self.rear] is None:
self.q[self.rear] = value
self.rear = (self.rear + 1 ) % self.maxlen
return True
return False
def deQueue(self) -> bool:
if self.front == self.rear and self.q[self.front] is None:
return False
self.q[self.front] = None
self.front = (self.front +1) % self.maxlen
return True
def Front(self) -> int:
if self.q[self.front] is None:
return -1
return self.q[self.front]
def Rear(self) -> int:
if self.q[self.rear -1] is None:
return -1
return self.q[self.rear-1]
def isEmpty(self) -> bool:
if self.front == self.rear and self.q[self.rear] is None:
return True
return False
def isFull(self) -> bool:
if self.front == self.rear and self.q[self.rear] is not None:
return True
return False
# Your MyCircularQueue object will be instantiated and called as such:
# obj = MyCircularQueue(k)
# param_1 = obj.enQueue(value)
# param_2 = obj.deQueue()
# param_3 = obj.Front()
# param_4 = obj.Rear()
# param_5 = obj.isEmpty()
# param_6 = obj.isFull()
| class Mycircularqueue:
def __init__(self, k: int):
self.q = [None] * k
self.maxlen = k
self.front = 0
self.rear = 0
def en_queue(self, value: int) -> bool:
if self.q[self.rear] is None:
self.q[self.rear] = value
self.rear = (self.rear + 1) % self.maxlen
return True
return False
def de_queue(self) -> bool:
if self.front == self.rear and self.q[self.front] is None:
return False
self.q[self.front] = None
self.front = (self.front + 1) % self.maxlen
return True
def front(self) -> int:
if self.q[self.front] is None:
return -1
return self.q[self.front]
def rear(self) -> int:
if self.q[self.rear - 1] is None:
return -1
return self.q[self.rear - 1]
def is_empty(self) -> bool:
if self.front == self.rear and self.q[self.rear] is None:
return True
return False
def is_full(self) -> bool:
if self.front == self.rear and self.q[self.rear] is not None:
return True
return False |
_base_ = [
'../_base_/models/lxmert/lxmert_pretrain_config.py',
'../_base_/datasets/lxmert/lxmert_pretrain.py',
'../_base_/default_runtime.py',
]
| _base_ = ['../_base_/models/lxmert/lxmert_pretrain_config.py', '../_base_/datasets/lxmert/lxmert_pretrain.py', '../_base_/default_runtime.py'] |
def print_all_binary_strings(n):
helper(n, "")
print("-------------------")
def helper(n, s, lvl = 0):
space = (" " * lvl) + s
print(space)
if(len(s) == n):
print(s)
else:
helper(n, s + "0", lvl + 1)
helper(n, s + "1", lvl + 1)
print_all_binary_strings(1)
print_all_binary_strings(2)
print_all_binary_strings(3)
print_all_binary_strings(4) | def print_all_binary_strings(n):
helper(n, '')
print('-------------------')
def helper(n, s, lvl=0):
space = ' ' * lvl + s
print(space)
if len(s) == n:
print(s)
else:
helper(n, s + '0', lvl + 1)
helper(n, s + '1', lvl + 1)
print_all_binary_strings(1)
print_all_binary_strings(2)
print_all_binary_strings(3)
print_all_binary_strings(4) |
# DEBUG FLAGS
TRAIN_JUST_ONE_BATCH = False
TRAIN_JUST_ONE_ROUND = False
PROFILE = False
CHECK_GRADS = False
# Basic
LEARNING_RATE_DEFAULT = 1e-2 # 0.01
MAX_EPOCHS_DEFAULT = 100
EVAL_FREQ_DEFAULT = 5
BATCH_SIZE_DEFAULT = 5
WORKERS_DEFAULT = 4
OPTIMIZER_DEFAULT = 'ADAM'
WEIGHT_DECAY_DEFAULT = 0.01
DATA_DIR_DEFAULT = 'data/EEG_age_data/'
LOG_DIR_DEFAULT = 'log/'
USE_GPU_DEFAULT = 1
GPU_ID_DEFAULT = 0
NETWORK_DEFAULT = 'BAPM'
NETWORKS = ['FeedForward', 'GRUNet', 'BAPM', 'BAPM1', 'BAPM2']
MODE_DEFAULT = 'train'
EVAL_DEFAULT = 'model_save/eval.pt' # should be a model file name
MODEL_SAVE_DIR_DEFAULT = 'model_save/'
MAX_NORM_DEFAULT = 10.0
NUM_HEADS_DEFAULT = 3
FEAT_DIM_DEFAULT = 1
HIDDEN_DIM_DEFAULT = 5
LOSS_FUNC_DEFAULT = 'SmoothL1Loss'
SMOOTH_L1_LOSS_BETA_DEFAULT = 1
FOLDS_DEFAULT = 5
VALID_K_DEFAULT = -1
# DIY
TOTAL_TIMESTAMPS = 245760
EEG_FREQUENCY = 1024
NUM_NODES = 63
NUM_SUBJECTS = 111
BAD_SUBJECT_IDS = [2, 14, 17, 18, 19, 20, 26, 35, 41, 64, 72] # Delete bad samples
SAMPLE_SPLIT_DEFAULT = 16
NUM_SAMPLES_DEFAULT = -1
STCNN_STRIDE_FACTOR_DEFAULT = 4
SHUFFLE_RANDOM_SEED = 666
CUSTOMIZE_GRAPH_DEFAULT = 0
| train_just_one_batch = False
train_just_one_round = False
profile = False
check_grads = False
learning_rate_default = 0.01
max_epochs_default = 100
eval_freq_default = 5
batch_size_default = 5
workers_default = 4
optimizer_default = 'ADAM'
weight_decay_default = 0.01
data_dir_default = 'data/EEG_age_data/'
log_dir_default = 'log/'
use_gpu_default = 1
gpu_id_default = 0
network_default = 'BAPM'
networks = ['FeedForward', 'GRUNet', 'BAPM', 'BAPM1', 'BAPM2']
mode_default = 'train'
eval_default = 'model_save/eval.pt'
model_save_dir_default = 'model_save/'
max_norm_default = 10.0
num_heads_default = 3
feat_dim_default = 1
hidden_dim_default = 5
loss_func_default = 'SmoothL1Loss'
smooth_l1_loss_beta_default = 1
folds_default = 5
valid_k_default = -1
total_timestamps = 245760
eeg_frequency = 1024
num_nodes = 63
num_subjects = 111
bad_subject_ids = [2, 14, 17, 18, 19, 20, 26, 35, 41, 64, 72]
sample_split_default = 16
num_samples_default = -1
stcnn_stride_factor_default = 4
shuffle_random_seed = 666
customize_graph_default = 0 |
# The contents of this file has been derived code from the Twisted project
# (http://twistedmatrix.com/). The original author is Jp Calderone.
# Twisted project license follows:
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
class FolderNameError(ValueError):
pass
def encode(s):
if isinstance(s, str) and sum(n for n in (ord(c) for c in s) if n > 127):
raise FolderNameError("%r contains characters not valid in a str folder name. "
"Convert to unicode first?" % s)
r = []
_in = []
for c in s:
if ord(c) in (range(0x20, 0x26) + range(0x27, 0x7f)):
if _in:
r.extend(['&', modified_base64(''.join(_in)), '-'])
del _in[:]
r.append(str(c))
elif c == '&':
if _in:
r.extend(['&', modified_base64(''.join(_in)), '-'])
del _in[:]
r.append('&-')
else:
_in.append(c)
if _in:
r.extend(['&', modified_base64(''.join(_in)), '-'])
return ''.join(r)
def decode(s):
r = []
decode = []
for c in s:
if c == '&' and not decode:
decode.append('&')
elif c == '-' and decode:
if len(decode) == 1:
r.append('&')
else:
r.append(modified_unbase64(''.join(decode[1:])))
decode = []
elif decode:
decode.append(c)
else:
r.append(c)
if decode:
r.append(modified_unbase64(''.join(decode[1:])))
out = ''.join(r)
if not isinstance(out, unicode):
out = unicode(out, 'latin-1')
return out
def modified_base64(s):
s_utf7 = s.encode('utf-7')
return s_utf7[1:-1].replace('/', ',')
def modified_unbase64(s):
s_utf7 = '+' + s.replace(',', '/') + '-'
return s_utf7.decode('utf-7')
| class Foldernameerror(ValueError):
pass
def encode(s):
if isinstance(s, str) and sum((n for n in (ord(c) for c in s) if n > 127)):
raise folder_name_error('%r contains characters not valid in a str folder name. Convert to unicode first?' % s)
r = []
_in = []
for c in s:
if ord(c) in range(32, 38) + range(39, 127):
if _in:
r.extend(['&', modified_base64(''.join(_in)), '-'])
del _in[:]
r.append(str(c))
elif c == '&':
if _in:
r.extend(['&', modified_base64(''.join(_in)), '-'])
del _in[:]
r.append('&-')
else:
_in.append(c)
if _in:
r.extend(['&', modified_base64(''.join(_in)), '-'])
return ''.join(r)
def decode(s):
r = []
decode = []
for c in s:
if c == '&' and (not decode):
decode.append('&')
elif c == '-' and decode:
if len(decode) == 1:
r.append('&')
else:
r.append(modified_unbase64(''.join(decode[1:])))
decode = []
elif decode:
decode.append(c)
else:
r.append(c)
if decode:
r.append(modified_unbase64(''.join(decode[1:])))
out = ''.join(r)
if not isinstance(out, unicode):
out = unicode(out, 'latin-1')
return out
def modified_base64(s):
s_utf7 = s.encode('utf-7')
return s_utf7[1:-1].replace('/', ',')
def modified_unbase64(s):
s_utf7 = '+' + s.replace(',', '/') + '-'
return s_utf7.decode('utf-7') |
# debug
DEBUG = False
| debug = False |
'''1. Write a Python function that takes a sequence of numbers and determines whether
all the numbers are different from each other.'''
def unique(string):
if len(string) == len(set(string)):
ans = 'True'
else:
ans = 'False'
return ans
print(unique((1, 2, 3, 4)))
print(unique((1, 3, 3, 4)))
| """1. Write a Python function that takes a sequence of numbers and determines whether
all the numbers are different from each other."""
def unique(string):
if len(string) == len(set(string)):
ans = 'True'
else:
ans = 'False'
return ans
print(unique((1, 2, 3, 4)))
print(unique((1, 3, 3, 4))) |
try:
var1 += 1
except:
var1 = 1
def __quick_unload_script():
print("Unloaded: %s" % str(var1))
print(f"Just edit and save! {var1}")
| try:
var1 += 1
except:
var1 = 1
def __quick_unload_script():
print('Unloaded: %s' % str(var1))
print(f'Just edit and save! {var1}') |
class MissingKeyError(Exception):
pass
class NoneError(Exception):
pass
| class Missingkeyerror(Exception):
pass
class Noneerror(Exception):
pass |
#Also called as Circular Queue
class Queue:
def __init__(self, maxSize):
self.items = maxSize * [None] # To initialize a list with a limit set make a list with the size u want and make all the elements None
self.maxSize = maxSize
self.start = -1
self.top = -1
def __str__(self):
values = [str(x) for x in self.items]
return " ".join(values)
def isFull(self):
if self.top + 1 == self.start:
return True
elif self.start ==0 and self.top+1 == self.top:
return True
else:
return False
def isEmpty(self):
if self.top == -1:
return True
else:
return False
def enqueue(self, value):
if self.isFull():
print("Queue is full :/")
else:
if self.top+1 == self.maxSize: #if queue is not full but top is at the end of the queue it means that we have dequeued elements and now when we enquue elements they will be added at the start of the queu and not the end
self.top = 0
else: #regular adding at the end of the queue
self.top+=1
if self.start == -1:
self.start=0
self.items[self.top] = value
return "Element is inserted at the end of the queue"
def dequeue(self):
if self.isEmpty():
print("Queue is empty")
else:
firstelement = self.items[self.start]
start = self.start
if self.start == self.top: #only 1 element
self.start = -1
self.top = -1
elif self.start + 1 == self.maxSize:
self.start = 0
else:
self.start+=1
self.items[start] = None
return firstelement
def peek(self):
if self.isEmpty():
print("Queue is empty")
else:
return self.items[self.start]
def delete(self):
self.items = self.maxSize * [None]
self.top = -1
self.start = -1
customqueue = Queue(3)
customqueue.enqueue(1)
customqueue.enqueue(2)
customqueue.enqueue(3)
print(customqueue.dequeue())
print(customqueue)
print(customqueue.peek()) #returns 2 not None wow
| class Queue:
def __init__(self, maxSize):
self.items = maxSize * [None]
self.maxSize = maxSize
self.start = -1
self.top = -1
def __str__(self):
values = [str(x) for x in self.items]
return ' '.join(values)
def is_full(self):
if self.top + 1 == self.start:
return True
elif self.start == 0 and self.top + 1 == self.top:
return True
else:
return False
def is_empty(self):
if self.top == -1:
return True
else:
return False
def enqueue(self, value):
if self.isFull():
print('Queue is full :/')
else:
if self.top + 1 == self.maxSize:
self.top = 0
else:
self.top += 1
if self.start == -1:
self.start = 0
self.items[self.top] = value
return 'Element is inserted at the end of the queue'
def dequeue(self):
if self.isEmpty():
print('Queue is empty')
else:
firstelement = self.items[self.start]
start = self.start
if self.start == self.top:
self.start = -1
self.top = -1
elif self.start + 1 == self.maxSize:
self.start = 0
else:
self.start += 1
self.items[start] = None
return firstelement
def peek(self):
if self.isEmpty():
print('Queue is empty')
else:
return self.items[self.start]
def delete(self):
self.items = self.maxSize * [None]
self.top = -1
self.start = -1
customqueue = queue(3)
customqueue.enqueue(1)
customqueue.enqueue(2)
customqueue.enqueue(3)
print(customqueue.dequeue())
print(customqueue)
print(customqueue.peek()) |
def checkorders(orders: [str]) -> [bool]:
results = []
for i in orders:
flag = True
stock = []
for j in i:
if j in '([{':
stock.append(j)
else:
if stock == []:
flag = False
break
symbol = stock.pop()
if not match(symbol, j):
flag = False
break
if stock != []:
flag = False
results.append(flag)
return results
def match(opens,closers):
return '([{'.index(opens) == ')]}'.index(closers)
print(checkorders(['()','(','{}[]','[][][]','[{]{]']))
| def checkorders(orders: [str]) -> [bool]:
results = []
for i in orders:
flag = True
stock = []
for j in i:
if j in '([{':
stock.append(j)
else:
if stock == []:
flag = False
break
symbol = stock.pop()
if not match(symbol, j):
flag = False
break
if stock != []:
flag = False
results.append(flag)
return results
def match(opens, closers):
return '([{'.index(opens) == ')]}'.index(closers)
print(checkorders(['()', '(', '{}[]', '[][][]', '[{]{]'])) |
a = int(input())
b = int(input())
if a > b:
print(a)
else:
print(b)
| a = int(input())
b = int(input())
if a > b:
print(a)
else:
print(b) |
a,b = map(int,input().split())
ans=0
k=1
while a or b:
ans+=k*(((b%3)-(a%3))%3)
a//=3
b//=3
k*=3
print(ans) | (a, b) = map(int, input().split())
ans = 0
k = 1
while a or b:
ans += k * ((b % 3 - a % 3) % 3)
a //= 3
b //= 3
k *= 3
print(ans) |
# Minimum Remove to Make Valid Parentheses: https://leetcode.com/problems/minimum-remove-to-make-valid-parentheses/
# Given a string s of '(' , ')' and lowercase English characters.
# Your task is to remove the minimum number of parentheses ( '(' or ')', in any positions ) so that the resulting parentheses string is valid and return any valid string.
# Formally, a parentheses string is valid if and only if:
# It is the empty string, contains only lowercase characters, or
# It can be written as AB (A concatenated with B), where A and B are valid strings, or
# It can be written as (A), where A is a valid string.
# This problem seems really tricky but honestly you are checking that whenever you add a ( or ) that it is valid
# otherwise you add it to your count
# so the two ones are if you have a ( it is only valid if you have a ) so if you find a ) after it at somepoint it is valid
# or if you have a ) there has to be something before it aka ( so if you have an empty stack you can add it to the count
# Now the other piece of this is you need to add all ( and remove them once you have a valid combo as it has been
# validated
# Oh I read this a bit wrong since we need to return a valid string our stack needs to hold the index at which the invalid parens
# are so that we can remove them before returning
class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
stack = []
for index in range(len(s)):
char = s[index]
if char == ')':
if len(stack) == 0:
stack.append(index)
else:
if s[stack[-1]] == '(':
stack.pop()
else:
stack.append(index)
elif char == '(':
stack.append(index)
result = ''
index = 0
for i in range(len(s)):
if index < len(stack) and stack[index] == i:
index += 1
continue
result += s[i]
return result
# The above works but there is definitely some improvements that could be made as I am not using a set to remove values
# but rather going across iteratively. The reason why we could use a set is that we know if a value is invalid by if it
# is still on the stack once we have finished parsing or if we have an invalid char befor it.
# The above runs in O(N) and uses O(N) space and actually so will this second piece but it will be a slight improvement
# as the string building will be using an O(1) that requires no extra operations
def minRemoveToMakeValid(self, s: str) -> str:
remove = set()
stack = []
for i in range(len(s)):
if s[i] == '(':
stack.append(i)
elif s[i] == ')':
if len(stack) > 0 and s[stack[-1]] == '(':
stack.pop()
else:
remove.add(i)
while stack:
remove.add(stack.pop())
result = ''
for i in range(len(s)):
if i not in remove:
result += s[i]
return result
# This is just a slight improvement and doesn't effect the big O
# Score Card
# Did I need hints? Nope
# Did you finish within 30 min? 10
# Was the solution optimal? Yup
# Were there any bugs? None
# 5 5 5 5 = 5
| class Solution:
def min_remove_to_make_valid(self, s: str) -> str:
stack = []
for index in range(len(s)):
char = s[index]
if char == ')':
if len(stack) == 0:
stack.append(index)
elif s[stack[-1]] == '(':
stack.pop()
else:
stack.append(index)
elif char == '(':
stack.append(index)
result = ''
index = 0
for i in range(len(s)):
if index < len(stack) and stack[index] == i:
index += 1
continue
result += s[i]
return result
def min_remove_to_make_valid(self, s: str) -> str:
remove = set()
stack = []
for i in range(len(s)):
if s[i] == '(':
stack.append(i)
elif s[i] == ')':
if len(stack) > 0 and s[stack[-1]] == '(':
stack.pop()
else:
remove.add(i)
while stack:
remove.add(stack.pop())
result = ''
for i in range(len(s)):
if i not in remove:
result += s[i]
return result |
app_name = "users"
urlpatterns = [
]
| app_name = 'users'
urlpatterns = [] |
#def divisor is from:
#https://www.w3resource.com/python-exercises/basic/python-basic-1-exercise-24.php
def divisor(n):
for i in range(n):
x = len([i for i in range(1, n+1) if not n % i])
return x
nums = []
i = 0
while i < 20:
preNum = int(input())
if(preNum > 0):
nums.append([divisor(preNum), preNum])
i += 1
nums.sort()
f=nums[len(nums)-1]
x=f.copy()
y = (x[::-1])
print(*y, sep=" ")
| def divisor(n):
for i in range(n):
x = len([i for i in range(1, n + 1) if not n % i])
return x
nums = []
i = 0
while i < 20:
pre_num = int(input())
if preNum > 0:
nums.append([divisor(preNum), preNum])
i += 1
nums.sort()
f = nums[len(nums) - 1]
x = f.copy()
y = x[::-1]
print(*y, sep=' ') |
s, t = 7, 11
a, b = 5, 15
m, n = 3, 2
apple = [-2, 2, 1]
orange = [5, -6]
a_score, b_score = 0, 0
''' too slow
for i in apple:
if (a + i) in list(range(s, t+1)):
a_score +=1
for i in orange:
if (b + i) in list(range(s, t+1)):
b_score +=1
'''
for i in apple:
if (a+i >= s) and (a+i <= t):
a_score += 1
for i in orange:
if (b+i >= s) and (b+i <= t):
b_score +=1
| (s, t) = (7, 11)
(a, b) = (5, 15)
(m, n) = (3, 2)
apple = [-2, 2, 1]
orange = [5, -6]
(a_score, b_score) = (0, 0)
' too slow\nfor i in apple:\n if (a + i) in list(range(s, t+1)):\n a_score +=1\n\nfor i in orange:\n if (b + i) in list(range(s, t+1)):\n b_score +=1\n\n'
for i in apple:
if a + i >= s and a + i <= t:
a_score += 1
for i in orange:
if b + i >= s and b + i <= t:
b_score += 1 |
class Customer:
id = 1
def __init__(self, name, address, email):
self.name = name
self.address = address
self.email = email
self.id = Customer.id
Customer.id += 1
def __repr__(self):
return f"Customer <{self.id}> {self.name}; Address: {self.address}; Email: {self.email}"
@staticmethod
def get_next_id():
return Customer.id
| class Customer:
id = 1
def __init__(self, name, address, email):
self.name = name
self.address = address
self.email = email
self.id = Customer.id
Customer.id += 1
def __repr__(self):
return f'Customer <{self.id}> {self.name}; Address: {self.address}; Email: {self.email}'
@staticmethod
def get_next_id():
return Customer.id |
SECRET_KEY = "abc"
FILEUPLOAD_ALLOWED_EXTENSIONS = ["png"]
# FILEUPLOAD_PREFIX = "/cool/upload"
# FILEUPLOAD_LOCALSTORAGE_IMG_FOLDER = "images/boring/"
FILEUPLOAD_RANDOM_FILE_APPENDIX = True
FILEUPLOAD_CONVERT_TO_SNAKE_CASE = True
| secret_key = 'abc'
fileupload_allowed_extensions = ['png']
fileupload_random_file_appendix = True
fileupload_convert_to_snake_case = True |
# 6. Math Power
def math_power(n, p):
power_output = n ** p
print(power_output)
number = float(input())
power = float(input())
math_power(number, power) | def math_power(n, p):
power_output = n ** p
print(power_output)
number = float(input())
power = float(input())
math_power(number, power) |
# https://atcoder.jp/contests/math-and-algorithm/tasks/math_and_algorithm_bj
n = int(input())
xx = [0] * n
yy = [0] * n
for i in range(n):
xx[i], yy[i] = map(int, input().split())
xx.sort()
yy.sort()
ax = 0
ay = 0
cx = 0
cy = 0
for i in range(n):
ax += xx[i] * i - cx
cx += xx[i]
ay += yy[i] * i - cy
cy += yy[i]
print(ax + ay) | n = int(input())
xx = [0] * n
yy = [0] * n
for i in range(n):
(xx[i], yy[i]) = map(int, input().split())
xx.sort()
yy.sort()
ax = 0
ay = 0
cx = 0
cy = 0
for i in range(n):
ax += xx[i] * i - cx
cx += xx[i]
ay += yy[i] * i - cy
cy += yy[i]
print(ax + ay) |
_version_major = 0
_version_minor = 1
_version_micro = 0
__version__ = "{0:d}.{1:d}.{2:d}".format(
_version_major, _version_minor, _version_micro)
| _version_major = 0
_version_minor = 1
_version_micro = 0
__version__ = '{0:d}.{1:d}.{2:d}'.format(_version_major, _version_minor, _version_micro) |
def troca(i,j,lista):
if (i >= 0 and j >= 0) and (i <= (len(lista) - 1) and j <= (len(lista) - 1)):
aux = lista[i]
lista[i] = lista[j]
lista[j] = aux
return lista
def main():
n = int(input())
lista = []
for k in range(n):
lista.append(int(input()))
i = int(input())
j = int(input())
lista = troca(i,j,lista)
for h in lista:
print(h)
main() | def troca(i, j, lista):
if (i >= 0 and j >= 0) and (i <= len(lista) - 1 and j <= len(lista) - 1):
aux = lista[i]
lista[i] = lista[j]
lista[j] = aux
return lista
def main():
n = int(input())
lista = []
for k in range(n):
lista.append(int(input()))
i = int(input())
j = int(input())
lista = troca(i, j, lista)
for h in lista:
print(h)
main() |
# test
def addTwoNumbers(a, b):
sum = a + b
return sum
def addList(l1):
sum = 0
for i in l1:
sum += i
return sum
add = lambda x, y : x + y
num1 = 1
num2 = 2
print("The sum is ", addTwoNumbers(num1, num2))
numlist = (1, 2, 3)
print(add(10, 20))
print("The sum is ", addList(numlist))
for i in range(16, 11, -1):
print(i)
print([x for x in range(16) if x > 2])
x = ('apple', 'banana', 'cherry')
y = enumerate(x)
print(list(y))
dict1 = {i: i**2 for i in range(1, 11)}
print(dict1)
txt = "The rain in Spain stays mainly in the plain"
x = "ain" in txt
print(x)
def finite_sequence():
num = 0
while num < 10000:
yield num
num += 1
def tupletest():
return 1, 2
x,y = tupletest()
print(tupletest(), x, y)
| def add_two_numbers(a, b):
sum = a + b
return sum
def add_list(l1):
sum = 0
for i in l1:
sum += i
return sum
add = lambda x, y: x + y
num1 = 1
num2 = 2
print('The sum is ', add_two_numbers(num1, num2))
numlist = (1, 2, 3)
print(add(10, 20))
print('The sum is ', add_list(numlist))
for i in range(16, 11, -1):
print(i)
print([x for x in range(16) if x > 2])
x = ('apple', 'banana', 'cherry')
y = enumerate(x)
print(list(y))
dict1 = {i: i ** 2 for i in range(1, 11)}
print(dict1)
txt = 'The rain in Spain stays mainly in the plain'
x = 'ain' in txt
print(x)
def finite_sequence():
num = 0
while num < 10000:
yield num
num += 1
def tupletest():
return (1, 2)
(x, y) = tupletest()
print(tupletest(), x, y) |
#
# PySNMP MIB module MITEL-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/MITEL-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:02: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)
#
OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsUnion, SingleValueConstraint, ConstraintsIntersection, ValueSizeConstraint, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "SingleValueConstraint", "ConstraintsIntersection", "ValueSizeConstraint", "ValueRangeConstraint")
ifIndex, = mibBuilder.importSymbols("IF-MIB", "ifIndex")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
ModuleIdentity, Gauge32, Counter64, Unsigned32, Bits, NotificationType, MibIdentifier, internet, ObjectIdentity, IpAddress, enterprises, NotificationType, MibScalar, MibTable, MibTableRow, MibTableColumn, Counter32, Integer32, iso, TimeTicks = mibBuilder.importSymbols("SNMPv2-SMI", "ModuleIdentity", "Gauge32", "Counter64", "Unsigned32", "Bits", "NotificationType", "MibIdentifier", "internet", "ObjectIdentity", "IpAddress", "enterprises", "NotificationType", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Counter32", "Integer32", "iso", "TimeTicks")
TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString")
mitel = MibIdentifier((1, 3, 6, 1, 4, 1, 1027))
snmpV2 = MibIdentifier((1, 3, 6, 1, 6))
snmpDomains = MibIdentifier((1, 3, 6, 1, 6, 1))
snmpUDPDomain = MibIdentifier((1, 3, 6, 1, 6, 1, 1))
class InterfaceIndex(Integer32):
pass
class TruthValue(Integer32):
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2))
namedValues = NamedValues(("true", 1), ("false", 2))
class RowStatus(Integer32):
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6))
namedValues = NamedValues(("active", 1), ("notInService", 2), ("notReady", 3), ("createAndGo", 4), ("createAndWait", 5), ("destroy", 6))
class TimeStamp(TimeTicks):
pass
class TimeInterval(Integer32):
subtypeSpec = Integer32.subtypeSpec + ValueRangeConstraint(0, 2147483647)
mitelIdentification = MibIdentifier((1, 3, 6, 1, 4, 1, 1027, 1))
mitelExperimental = MibIdentifier((1, 3, 6, 1, 4, 1, 1027, 2))
mitelExtensions = MibIdentifier((1, 3, 6, 1, 4, 1, 1027, 3))
mitelProprietary = MibIdentifier((1, 3, 6, 1, 4, 1, 1027, 4))
mitelConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 1027, 5))
mitelIdMgmtPlatforms = MibIdentifier((1, 3, 6, 1, 4, 1, 1027, 1, 1))
mitelIdCallServers = MibIdentifier((1, 3, 6, 1, 4, 1, 1027, 1, 2))
mitelIdTerminals = MibIdentifier((1, 3, 6, 1, 4, 1, 1027, 1, 3))
mitelIdInterfaces = MibIdentifier((1, 3, 6, 1, 4, 1, 1027, 1, 4))
mitelIdCtiPlatforms = MibIdentifier((1, 3, 6, 1, 4, 1, 1027, 1, 5))
mitelIdMgmtOpsMgr = MibIdentifier((1, 3, 6, 1, 4, 1, 1027, 1, 1, 1))
mitelIdCsMc2 = MibIdentifier((1, 3, 6, 1, 4, 1, 1027, 1, 2, 1))
mitelIdCs2000Light = MibIdentifier((1, 3, 6, 1, 4, 1, 1027, 1, 2, 2))
mitelExtInterfaces = MibIdentifier((1, 3, 6, 1, 4, 1, 1027, 3, 2))
mitelPropApplications = MibIdentifier((1, 3, 6, 1, 4, 1, 1027, 4, 1))
mitelPropTransmission = MibIdentifier((1, 3, 6, 1, 4, 1, 1027, 4, 2))
mitelPropProtocols = MibIdentifier((1, 3, 6, 1, 4, 1, 1027, 4, 3))
mitelPropUtilities = MibIdentifier((1, 3, 6, 1, 4, 1, 1027, 4, 4))
mitelPropHardware = MibIdentifier((1, 3, 6, 1, 4, 1, 1027, 4, 5))
mitelPropNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 1027, 4, 6))
mitelPropReset = MibIdentifier((1, 3, 6, 1, 4, 1, 1027, 4, 7))
mitelAppCallServer = MibIdentifier((1, 3, 6, 1, 4, 1, 1027, 4, 1, 1))
mitelNotifTraps = MibIdentifier((1, 3, 6, 1, 4, 1, 1027, 4, 6, 1))
mitelConfCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 1027, 5, 1))
mitelConfGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 1027, 5, 2))
mitelGrpCommon = MibIdentifier((1, 3, 6, 1, 4, 1, 1027, 5, 2, 1))
mitelGrpOpsMgr = MibIdentifier((1, 3, 6, 1, 4, 1, 1027, 5, 2, 2))
mitelGrpCs2000 = MibIdentifier((1, 3, 6, 1, 4, 1, 1027, 5, 2, 3))
mitelConfAgents = MibIdentifier((1, 3, 6, 1, 4, 1, 1027, 5, 3))
class TDomain(ObjectIdentifier):
pass
class TAddress(OctetString):
subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(1, 255)
class MitelIfType(Integer32):
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1))
namedValues = NamedValues(("dnic", 1))
class MitelNotifyTransportType(Integer32):
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3))
namedValues = NamedValues(("mitelNotifTransV1Trap", 1), ("mitelNotifTransV2Trap", 2), ("mitelNotifTransInform", 3))
mitelIfNumber = MibScalar((1, 3, 6, 1, 4, 1, 1027, 3, 2, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: mitelIfNumber.setStatus('mandatory')
mitelIfTable = MibTable((1, 3, 6, 1, 4, 1, 1027, 3, 2, 2), )
if mibBuilder.loadTexts: mitelIfTable.setStatus('mandatory')
mitelIfTableEntry = MibTableRow((1, 3, 6, 1, 4, 1, 1027, 3, 2, 2, 1), ).setIndexNames((0, "IF-MIB", "ifIndex"))
if mibBuilder.loadTexts: mitelIfTableEntry.setStatus('mandatory')
mitelIfTblType = MibTableColumn((1, 3, 6, 1, 4, 1, 1027, 3, 2, 2, 1, 1), MitelIfType()).setMaxAccess("readonly")
if mibBuilder.loadTexts: mitelIfTblType.setStatus('mandatory')
mitelResetReason = MibScalar((1, 3, 6, 1, 4, 1, 1027, 4, 7, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("shutdown", 1), ("coldStart", 2), ("warmStart", 3)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: mitelResetReason.setStatus('mandatory')
mitelResetPlatform = MibScalar((1, 3, 6, 1, 4, 1, 1027, 4, 7, 2), TruthValue()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: mitelResetPlatform.setStatus('mandatory')
mitelResetAgent = MibScalar((1, 3, 6, 1, 4, 1, 1027, 4, 7, 3), TruthValue()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: mitelResetAgent.setStatus('mandatory')
mitelNotifCount = MibScalar((1, 3, 6, 1, 4, 1, 1027, 4, 6, 2), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: mitelNotifCount.setStatus('mandatory')
mitelNotifEnableTable = MibTable((1, 3, 6, 1, 4, 1, 1027, 4, 6, 3), )
if mibBuilder.loadTexts: mitelNotifEnableTable.setStatus('mandatory')
mitelNotifEnableTableEntry = MibTableRow((1, 3, 6, 1, 4, 1, 1027, 4, 6, 3, 1), ).setIndexNames((0, "MITEL-MIB", "mitelNotifEnblTblIndex"))
if mibBuilder.loadTexts: mitelNotifEnableTableEntry.setStatus('mandatory')
mitelNotifEnblTblIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 1027, 4, 6, 3, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: mitelNotifEnblTblIndex.setStatus('mandatory')
mitelNotifEnblTblOid = MibTableColumn((1, 3, 6, 1, 4, 1, 1027, 4, 6, 3, 1, 2), ObjectIdentifier()).setMaxAccess("readonly")
if mibBuilder.loadTexts: mitelNotifEnblTblOid.setStatus('mandatory')
mitelNotifEnblTblEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 1027, 4, 6, 3, 1, 3), TruthValue()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: mitelNotifEnblTblEnable.setStatus('mandatory')
mitelNotifEnblTblAck = MibTableColumn((1, 3, 6, 1, 4, 1, 1027, 4, 6, 3, 1, 4), TruthValue()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: mitelNotifEnblTblAck.setStatus('mandatory')
mitelNotifEnblTblOccurrences = MibTableColumn((1, 3, 6, 1, 4, 1, 1027, 4, 6, 3, 1, 5), Counter32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: mitelNotifEnblTblOccurrences.setStatus('mandatory')
mitelNotifEnblTblDescr = MibTableColumn((1, 3, 6, 1, 4, 1, 1027, 4, 6, 3, 1, 6), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: mitelNotifEnblTblDescr.setStatus('mandatory')
mitelNotifManagerTable = MibTable((1, 3, 6, 1, 4, 1, 1027, 4, 6, 4), )
if mibBuilder.loadTexts: mitelNotifManagerTable.setStatus('mandatory')
mitelNotifManagerTableEntry = MibTableRow((1, 3, 6, 1, 4, 1, 1027, 4, 6, 4, 1), ).setIndexNames((0, "MITEL-MIB", "mitelNotifMgrTblIndex"))
if mibBuilder.loadTexts: mitelNotifManagerTableEntry.setStatus('mandatory')
mitelNotifMgrTblIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 1027, 4, 6, 4, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: mitelNotifMgrTblIndex.setStatus('mandatory')
mitelNotifMgrTblStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 1027, 4, 6, 4, 1, 2), RowStatus().clone('active')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: mitelNotifMgrTblStatus.setStatus('mandatory')
mitelNotifMgrTblTransport = MibTableColumn((1, 3, 6, 1, 4, 1, 1027, 4, 6, 4, 1, 3), MitelNotifyTransportType().clone('mitelNotifTransV1Trap')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: mitelNotifMgrTblTransport.setStatus('mandatory')
mitelNotifMgrTblDomain = MibTableColumn((1, 3, 6, 1, 4, 1, 1027, 4, 6, 4, 1, 4), TDomain().clone((1, 3, 6, 1, 6, 1, 1))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: mitelNotifMgrTblDomain.setStatus('mandatory')
mitelNotifMgrTblAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 1027, 4, 6, 4, 1, 5), TAddress().clone(hexValue="c00002000489")).setMaxAccess("readwrite")
if mibBuilder.loadTexts: mitelNotifMgrTblAddress.setStatus('mandatory')
mitelNotifMgrTblTimeout = MibTableColumn((1, 3, 6, 1, 4, 1, 1027, 4, 6, 4, 1, 6), TimeInterval().clone(1000)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: mitelNotifMgrTblTimeout.setStatus('mandatory')
mitelNotifMgrTblRetries = MibTableColumn((1, 3, 6, 1, 4, 1, 1027, 4, 6, 4, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 10)).clone(3)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: mitelNotifMgrTblRetries.setStatus('mandatory')
mitelNotifMgrTblLife = MibTableColumn((1, 3, 6, 1, 4, 1, 1027, 4, 6, 4, 1, 8), TimeInterval().clone(8640000)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: mitelNotifMgrTblLife.setStatus('mandatory')
mitelNotifMgrTblCommunity = MibTableColumn((1, 3, 6, 1, 4, 1, 1027, 4, 6, 4, 1, 9), OctetString().clone('public')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: mitelNotifMgrTblCommunity.setStatus('mandatory')
mitelNotifMgrTblName = MibTableColumn((1, 3, 6, 1, 4, 1, 1027, 4, 6, 4, 1, 10), DisplayString().clone('None specified.')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: mitelNotifMgrTblName.setStatus('mandatory')
mitelNotifHistoryMax = MibScalar((1, 3, 6, 1, 4, 1, 1027, 4, 6, 5), Integer32().clone(100)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: mitelNotifHistoryMax.setStatus('mandatory')
mitelNotifHistorySize = MibScalar((1, 3, 6, 1, 4, 1, 1027, 4, 6, 6), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: mitelNotifHistorySize.setStatus('mandatory')
mitelNotifHistoryTable = MibTable((1, 3, 6, 1, 4, 1, 1027, 4, 6, 7), )
if mibBuilder.loadTexts: mitelNotifHistoryTable.setStatus('mandatory')
mitelNotifHistoryTableEntry = MibTableRow((1, 3, 6, 1, 4, 1, 1027, 4, 6, 7, 1), ).setIndexNames((0, "MITEL-MIB", "mitelNotifHistTblIndex"))
if mibBuilder.loadTexts: mitelNotifHistoryTableEntry.setStatus('mandatory')
mitelNotifHistTblIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 1027, 4, 6, 7, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: mitelNotifHistTblIndex.setStatus('mandatory')
mitelNotifHistTblId = MibTableColumn((1, 3, 6, 1, 4, 1, 1027, 4, 6, 7, 1, 2), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: mitelNotifHistTblId.setStatus('mandatory')
mitelNotifHistTblTime = MibTableColumn((1, 3, 6, 1, 4, 1, 1027, 4, 6, 7, 1, 3), TimeStamp()).setMaxAccess("readonly")
if mibBuilder.loadTexts: mitelNotifHistTblTime.setStatus('mandatory')
mitelNotifHistTblIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 1027, 4, 6, 7, 1, 4), InterfaceIndex()).setMaxAccess("readonly")
if mibBuilder.loadTexts: mitelNotifHistTblIfIndex.setStatus('mandatory')
mitelNotifHistTblConfirmed = MibTableColumn((1, 3, 6, 1, 4, 1, 1027, 4, 6, 7, 1, 5), TruthValue()).setMaxAccess("readonly")
if mibBuilder.loadTexts: mitelNotifHistTblConfirmed.setStatus('mandatory')
mitelNotifUnackTable = MibTable((1, 3, 6, 1, 4, 1, 1027, 4, 6, 8), )
if mibBuilder.loadTexts: mitelNotifUnackTable.setStatus('mandatory')
mitelNotifUnackTableEntry = MibTableRow((1, 3, 6, 1, 4, 1, 1027, 4, 6, 8, 1), ).setIndexNames((0, "MITEL-MIB", "mitelNotifUnackTblIndex"))
if mibBuilder.loadTexts: mitelNotifUnackTableEntry.setStatus('mandatory')
mitelNotifUnackTblIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 1027, 4, 6, 8, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: mitelNotifUnackTblIndex.setStatus('mandatory')
mitelNotifUnackTblStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 1027, 4, 6, 8, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 6))).clone(namedValues=NamedValues(("active", 1), ("notInService", 2), ("destory", 6)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: mitelNotifUnackTblStatus.setStatus('mandatory')
mitelNotifUnackTblHistory = MibTableColumn((1, 3, 6, 1, 4, 1, 1027, 4, 6, 8, 1, 3), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: mitelNotifUnackTblHistory.setStatus('mandatory')
mitelNotifUnackTblManager = MibTableColumn((1, 3, 6, 1, 4, 1, 1027, 4, 6, 8, 1, 4), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: mitelNotifUnackTblManager.setStatus('mandatory')
mitelNotifUnackTblRetriesLeft = MibTableColumn((1, 3, 6, 1, 4, 1, 1027, 4, 6, 8, 1, 5), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: mitelNotifUnackTblRetriesLeft.setStatus('mandatory')
mitelNotifAgentAddress = MibScalar((1, 3, 6, 1, 4, 1, 1027, 4, 6, 9), TAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: mitelNotifAgentAddress.setStatus('mandatory')
mitelTrapsCommLost = NotificationType((1, 3, 6, 1, 4, 1, 1027, 4, 6, 1) + (0,1)).setObjects(("MITEL-MIB", "mitelNotifUnackTblStatus"), ("MITEL-MIB", "mitelNotifMgrTblDomain"), ("MITEL-MIB", "mitelNotifMgrTblAddress"))
mitelTrapsReset = NotificationType((1, 3, 6, 1, 4, 1, 1027, 4, 6, 1) + (0,2)).setObjects(("MITEL-MIB", "mitelNotifUnackTblStatus"), ("MITEL-MIB", "mitelResetReason"))
mitelGrpCmnNotifBasic = MibIdentifier((1, 3, 6, 1, 4, 1, 1027, 5, 2, 1, 2))
mitelGrpCmnNotifManagers = MibIdentifier((1, 3, 6, 1, 4, 1, 1027, 5, 2, 1, 3))
mitelGrpCmnNotifHistory = MibIdentifier((1, 3, 6, 1, 4, 1, 1027, 5, 2, 1, 4))
mitelGrpCmnNotifAck = MibIdentifier((1, 3, 6, 1, 4, 1, 1027, 5, 2, 1, 5))
mitelGrpCmnInterfaces = MibIdentifier((1, 3, 6, 1, 4, 1, 1027, 5, 2, 1, 6))
mitelGrpCmnReset = MibIdentifier((1, 3, 6, 1, 4, 1, 1027, 5, 2, 1, 7))
mitelComplMitel = MibIdentifier((1, 3, 6, 1, 4, 1, 1027, 5, 1, 1))
mibBuilder.exportSymbols("MITEL-MIB", snmpUDPDomain=snmpUDPDomain, mitelNotifMgrTblLife=mitelNotifMgrTblLife, mitelNotifMgrTblStatus=mitelNotifMgrTblStatus, mitelIdInterfaces=mitelIdInterfaces, TimeStamp=TimeStamp, mitelGrpCommon=mitelGrpCommon, mitelNotifHistoryTableEntry=mitelNotifHistoryTableEntry, mitelExtInterfaces=mitelExtInterfaces, mitelGrpCmnNotifBasic=mitelGrpCmnNotifBasic, TruthValue=TruthValue, mitelPropProtocols=mitelPropProtocols, mitelNotifUnackTableEntry=mitelNotifUnackTableEntry, mitelResetReason=mitelResetReason, mitelNotifEnableTable=mitelNotifEnableTable, mitelNotifMgrTblRetries=mitelNotifMgrTblRetries, RowStatus=RowStatus, MitelNotifyTransportType=MitelNotifyTransportType, mitelNotifHistoryMax=mitelNotifHistoryMax, mitelTrapsCommLost=mitelTrapsCommLost, mitelGrpCmnInterfaces=mitelGrpCmnInterfaces, mitelNotifMgrTblDomain=mitelNotifMgrTblDomain, mitelNotifEnblTblEnable=mitelNotifEnblTblEnable, mitelResetAgent=mitelResetAgent, mitelNotifEnblTblOid=mitelNotifEnblTblOid, snmpV2=snmpV2, mitelNotifHistoryTable=mitelNotifHistoryTable, mitelConformance=mitelConformance, mitelIdMgmtOpsMgr=mitelIdMgmtOpsMgr, mitelResetPlatform=mitelResetPlatform, mitelPropTransmission=mitelPropTransmission, snmpDomains=snmpDomains, mitelPropReset=mitelPropReset, InterfaceIndex=InterfaceIndex, mitelNotifUnackTblStatus=mitelNotifUnackTblStatus, mitelPropHardware=mitelPropHardware, MitelIfType=MitelIfType, mitelGrpCmnReset=mitelGrpCmnReset, mitelGrpOpsMgr=mitelGrpOpsMgr, mitelNotifMgrTblAddress=mitelNotifMgrTblAddress, mitelNotifHistTblConfirmed=mitelNotifHistTblConfirmed, mitelIfTable=mitelIfTable, mitelNotifUnackTblRetriesLeft=mitelNotifUnackTblRetriesLeft, mitelNotifHistTblTime=mitelNotifHistTblTime, mitelNotifHistTblIndex=mitelNotifHistTblIndex, mitelPropApplications=mitelPropApplications, mitelPropNotifications=mitelPropNotifications, mitelNotifMgrTblIndex=mitelNotifMgrTblIndex, mitelConfAgents=mitelConfAgents, mitelNotifTraps=mitelNotifTraps, mitelConfGroups=mitelConfGroups, mitelIfTableEntry=mitelIfTableEntry, mitelGrpCmnNotifHistory=mitelGrpCmnNotifHistory, mitelNotifMgrTblTimeout=mitelNotifMgrTblTimeout, mitelPropUtilities=mitelPropUtilities, mitelNotifHistTblIfIndex=mitelNotifHistTblIfIndex, mitelNotifEnblTblDescr=mitelNotifEnblTblDescr, mitelIdCsMc2=mitelIdCsMc2, mitelExtensions=mitelExtensions, mitelNotifAgentAddress=mitelNotifAgentAddress, mitelNotifMgrTblTransport=mitelNotifMgrTblTransport, mitelNotifManagerTableEntry=mitelNotifManagerTableEntry, TAddress=TAddress, mitelNotifHistorySize=mitelNotifHistorySize, mitelComplMitel=mitelComplMitel, mitelNotifCount=mitelNotifCount, TDomain=TDomain, mitelIdCtiPlatforms=mitelIdCtiPlatforms, mitelIdTerminals=mitelIdTerminals, mitelGrpCmnNotifAck=mitelGrpCmnNotifAck, mitelNotifHistTblId=mitelNotifHistTblId, mitelIdCs2000Light=mitelIdCs2000Light, mitelNotifMgrTblName=mitelNotifMgrTblName, mitelNotifMgrTblCommunity=mitelNotifMgrTblCommunity, mitelConfCompliances=mitelConfCompliances, mitelIdCallServers=mitelIdCallServers, mitelNotifEnableTableEntry=mitelNotifEnableTableEntry, mitelIfNumber=mitelIfNumber, TimeInterval=TimeInterval, mitelProprietary=mitelProprietary, mitelNotifEnblTblOccurrences=mitelNotifEnblTblOccurrences, mitelNotifUnackTblManager=mitelNotifUnackTblManager, mitelNotifUnackTable=mitelNotifUnackTable, mitelIdMgmtPlatforms=mitelIdMgmtPlatforms, mitelIfTblType=mitelIfTblType, mitelNotifUnackTblIndex=mitelNotifUnackTblIndex, mitelTrapsReset=mitelTrapsReset, mitelNotifUnackTblHistory=mitelNotifUnackTblHistory, mitelNotifEnblTblIndex=mitelNotifEnblTblIndex, mitelAppCallServer=mitelAppCallServer, mitel=mitel, mitelNotifEnblTblAck=mitelNotifEnblTblAck, mitelIdentification=mitelIdentification, mitelExperimental=mitelExperimental, mitelNotifManagerTable=mitelNotifManagerTable, mitelGrpCmnNotifManagers=mitelGrpCmnNotifManagers, mitelGrpCs2000=mitelGrpCs2000)
| (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, single_value_constraint, constraints_intersection, value_size_constraint, value_range_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsUnion', 'SingleValueConstraint', 'ConstraintsIntersection', 'ValueSizeConstraint', 'ValueRangeConstraint')
(if_index,) = mibBuilder.importSymbols('IF-MIB', 'ifIndex')
(module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup')
(module_identity, gauge32, counter64, unsigned32, bits, notification_type, mib_identifier, internet, object_identity, ip_address, enterprises, notification_type, mib_scalar, mib_table, mib_table_row, mib_table_column, counter32, integer32, iso, time_ticks) = mibBuilder.importSymbols('SNMPv2-SMI', 'ModuleIdentity', 'Gauge32', 'Counter64', 'Unsigned32', 'Bits', 'NotificationType', 'MibIdentifier', 'internet', 'ObjectIdentity', 'IpAddress', 'enterprises', 'NotificationType', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'Counter32', 'Integer32', 'iso', 'TimeTicks')
(textual_convention, display_string) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'DisplayString')
mitel = mib_identifier((1, 3, 6, 1, 4, 1, 1027))
snmp_v2 = mib_identifier((1, 3, 6, 1, 6))
snmp_domains = mib_identifier((1, 3, 6, 1, 6, 1))
snmp_udp_domain = mib_identifier((1, 3, 6, 1, 6, 1, 1))
class Interfaceindex(Integer32):
pass
class Truthvalue(Integer32):
subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(1, 2))
named_values = named_values(('true', 1), ('false', 2))
class Rowstatus(Integer32):
subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(1, 2, 3, 4, 5, 6))
named_values = named_values(('active', 1), ('notInService', 2), ('notReady', 3), ('createAndGo', 4), ('createAndWait', 5), ('destroy', 6))
class Timestamp(TimeTicks):
pass
class Timeinterval(Integer32):
subtype_spec = Integer32.subtypeSpec + value_range_constraint(0, 2147483647)
mitel_identification = mib_identifier((1, 3, 6, 1, 4, 1, 1027, 1))
mitel_experimental = mib_identifier((1, 3, 6, 1, 4, 1, 1027, 2))
mitel_extensions = mib_identifier((1, 3, 6, 1, 4, 1, 1027, 3))
mitel_proprietary = mib_identifier((1, 3, 6, 1, 4, 1, 1027, 4))
mitel_conformance = mib_identifier((1, 3, 6, 1, 4, 1, 1027, 5))
mitel_id_mgmt_platforms = mib_identifier((1, 3, 6, 1, 4, 1, 1027, 1, 1))
mitel_id_call_servers = mib_identifier((1, 3, 6, 1, 4, 1, 1027, 1, 2))
mitel_id_terminals = mib_identifier((1, 3, 6, 1, 4, 1, 1027, 1, 3))
mitel_id_interfaces = mib_identifier((1, 3, 6, 1, 4, 1, 1027, 1, 4))
mitel_id_cti_platforms = mib_identifier((1, 3, 6, 1, 4, 1, 1027, 1, 5))
mitel_id_mgmt_ops_mgr = mib_identifier((1, 3, 6, 1, 4, 1, 1027, 1, 1, 1))
mitel_id_cs_mc2 = mib_identifier((1, 3, 6, 1, 4, 1, 1027, 1, 2, 1))
mitel_id_cs2000_light = mib_identifier((1, 3, 6, 1, 4, 1, 1027, 1, 2, 2))
mitel_ext_interfaces = mib_identifier((1, 3, 6, 1, 4, 1, 1027, 3, 2))
mitel_prop_applications = mib_identifier((1, 3, 6, 1, 4, 1, 1027, 4, 1))
mitel_prop_transmission = mib_identifier((1, 3, 6, 1, 4, 1, 1027, 4, 2))
mitel_prop_protocols = mib_identifier((1, 3, 6, 1, 4, 1, 1027, 4, 3))
mitel_prop_utilities = mib_identifier((1, 3, 6, 1, 4, 1, 1027, 4, 4))
mitel_prop_hardware = mib_identifier((1, 3, 6, 1, 4, 1, 1027, 4, 5))
mitel_prop_notifications = mib_identifier((1, 3, 6, 1, 4, 1, 1027, 4, 6))
mitel_prop_reset = mib_identifier((1, 3, 6, 1, 4, 1, 1027, 4, 7))
mitel_app_call_server = mib_identifier((1, 3, 6, 1, 4, 1, 1027, 4, 1, 1))
mitel_notif_traps = mib_identifier((1, 3, 6, 1, 4, 1, 1027, 4, 6, 1))
mitel_conf_compliances = mib_identifier((1, 3, 6, 1, 4, 1, 1027, 5, 1))
mitel_conf_groups = mib_identifier((1, 3, 6, 1, 4, 1, 1027, 5, 2))
mitel_grp_common = mib_identifier((1, 3, 6, 1, 4, 1, 1027, 5, 2, 1))
mitel_grp_ops_mgr = mib_identifier((1, 3, 6, 1, 4, 1, 1027, 5, 2, 2))
mitel_grp_cs2000 = mib_identifier((1, 3, 6, 1, 4, 1, 1027, 5, 2, 3))
mitel_conf_agents = mib_identifier((1, 3, 6, 1, 4, 1, 1027, 5, 3))
class Tdomain(ObjectIdentifier):
pass
class Taddress(OctetString):
subtype_spec = OctetString.subtypeSpec + value_size_constraint(1, 255)
class Miteliftype(Integer32):
subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(1))
named_values = named_values(('dnic', 1))
class Mitelnotifytransporttype(Integer32):
subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(1, 2, 3))
named_values = named_values(('mitelNotifTransV1Trap', 1), ('mitelNotifTransV2Trap', 2), ('mitelNotifTransInform', 3))
mitel_if_number = mib_scalar((1, 3, 6, 1, 4, 1, 1027, 3, 2, 1), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
mitelIfNumber.setStatus('mandatory')
mitel_if_table = mib_table((1, 3, 6, 1, 4, 1, 1027, 3, 2, 2))
if mibBuilder.loadTexts:
mitelIfTable.setStatus('mandatory')
mitel_if_table_entry = mib_table_row((1, 3, 6, 1, 4, 1, 1027, 3, 2, 2, 1)).setIndexNames((0, 'IF-MIB', 'ifIndex'))
if mibBuilder.loadTexts:
mitelIfTableEntry.setStatus('mandatory')
mitel_if_tbl_type = mib_table_column((1, 3, 6, 1, 4, 1, 1027, 3, 2, 2, 1, 1), mitel_if_type()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
mitelIfTblType.setStatus('mandatory')
mitel_reset_reason = mib_scalar((1, 3, 6, 1, 4, 1, 1027, 4, 7, 1), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('shutdown', 1), ('coldStart', 2), ('warmStart', 3)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
mitelResetReason.setStatus('mandatory')
mitel_reset_platform = mib_scalar((1, 3, 6, 1, 4, 1, 1027, 4, 7, 2), truth_value()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
mitelResetPlatform.setStatus('mandatory')
mitel_reset_agent = mib_scalar((1, 3, 6, 1, 4, 1, 1027, 4, 7, 3), truth_value()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
mitelResetAgent.setStatus('mandatory')
mitel_notif_count = mib_scalar((1, 3, 6, 1, 4, 1, 1027, 4, 6, 2), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
mitelNotifCount.setStatus('mandatory')
mitel_notif_enable_table = mib_table((1, 3, 6, 1, 4, 1, 1027, 4, 6, 3))
if mibBuilder.loadTexts:
mitelNotifEnableTable.setStatus('mandatory')
mitel_notif_enable_table_entry = mib_table_row((1, 3, 6, 1, 4, 1, 1027, 4, 6, 3, 1)).setIndexNames((0, 'MITEL-MIB', 'mitelNotifEnblTblIndex'))
if mibBuilder.loadTexts:
mitelNotifEnableTableEntry.setStatus('mandatory')
mitel_notif_enbl_tbl_index = mib_table_column((1, 3, 6, 1, 4, 1, 1027, 4, 6, 3, 1, 1), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
mitelNotifEnblTblIndex.setStatus('mandatory')
mitel_notif_enbl_tbl_oid = mib_table_column((1, 3, 6, 1, 4, 1, 1027, 4, 6, 3, 1, 2), object_identifier()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
mitelNotifEnblTblOid.setStatus('mandatory')
mitel_notif_enbl_tbl_enable = mib_table_column((1, 3, 6, 1, 4, 1, 1027, 4, 6, 3, 1, 3), truth_value()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
mitelNotifEnblTblEnable.setStatus('mandatory')
mitel_notif_enbl_tbl_ack = mib_table_column((1, 3, 6, 1, 4, 1, 1027, 4, 6, 3, 1, 4), truth_value()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
mitelNotifEnblTblAck.setStatus('mandatory')
mitel_notif_enbl_tbl_occurrences = mib_table_column((1, 3, 6, 1, 4, 1, 1027, 4, 6, 3, 1, 5), counter32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
mitelNotifEnblTblOccurrences.setStatus('mandatory')
mitel_notif_enbl_tbl_descr = mib_table_column((1, 3, 6, 1, 4, 1, 1027, 4, 6, 3, 1, 6), display_string()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
mitelNotifEnblTblDescr.setStatus('mandatory')
mitel_notif_manager_table = mib_table((1, 3, 6, 1, 4, 1, 1027, 4, 6, 4))
if mibBuilder.loadTexts:
mitelNotifManagerTable.setStatus('mandatory')
mitel_notif_manager_table_entry = mib_table_row((1, 3, 6, 1, 4, 1, 1027, 4, 6, 4, 1)).setIndexNames((0, 'MITEL-MIB', 'mitelNotifMgrTblIndex'))
if mibBuilder.loadTexts:
mitelNotifManagerTableEntry.setStatus('mandatory')
mitel_notif_mgr_tbl_index = mib_table_column((1, 3, 6, 1, 4, 1, 1027, 4, 6, 4, 1, 1), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
mitelNotifMgrTblIndex.setStatus('mandatory')
mitel_notif_mgr_tbl_status = mib_table_column((1, 3, 6, 1, 4, 1, 1027, 4, 6, 4, 1, 2), row_status().clone('active')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
mitelNotifMgrTblStatus.setStatus('mandatory')
mitel_notif_mgr_tbl_transport = mib_table_column((1, 3, 6, 1, 4, 1, 1027, 4, 6, 4, 1, 3), mitel_notify_transport_type().clone('mitelNotifTransV1Trap')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
mitelNotifMgrTblTransport.setStatus('mandatory')
mitel_notif_mgr_tbl_domain = mib_table_column((1, 3, 6, 1, 4, 1, 1027, 4, 6, 4, 1, 4), t_domain().clone((1, 3, 6, 1, 6, 1, 1))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
mitelNotifMgrTblDomain.setStatus('mandatory')
mitel_notif_mgr_tbl_address = mib_table_column((1, 3, 6, 1, 4, 1, 1027, 4, 6, 4, 1, 5), t_address().clone(hexValue='c00002000489')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
mitelNotifMgrTblAddress.setStatus('mandatory')
mitel_notif_mgr_tbl_timeout = mib_table_column((1, 3, 6, 1, 4, 1, 1027, 4, 6, 4, 1, 6), time_interval().clone(1000)).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
mitelNotifMgrTblTimeout.setStatus('mandatory')
mitel_notif_mgr_tbl_retries = mib_table_column((1, 3, 6, 1, 4, 1, 1027, 4, 6, 4, 1, 7), integer32().subtype(subtypeSpec=value_range_constraint(1, 10)).clone(3)).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
mitelNotifMgrTblRetries.setStatus('mandatory')
mitel_notif_mgr_tbl_life = mib_table_column((1, 3, 6, 1, 4, 1, 1027, 4, 6, 4, 1, 8), time_interval().clone(8640000)).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
mitelNotifMgrTblLife.setStatus('mandatory')
mitel_notif_mgr_tbl_community = mib_table_column((1, 3, 6, 1, 4, 1, 1027, 4, 6, 4, 1, 9), octet_string().clone('public')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
mitelNotifMgrTblCommunity.setStatus('mandatory')
mitel_notif_mgr_tbl_name = mib_table_column((1, 3, 6, 1, 4, 1, 1027, 4, 6, 4, 1, 10), display_string().clone('None specified.')).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
mitelNotifMgrTblName.setStatus('mandatory')
mitel_notif_history_max = mib_scalar((1, 3, 6, 1, 4, 1, 1027, 4, 6, 5), integer32().clone(100)).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
mitelNotifHistoryMax.setStatus('mandatory')
mitel_notif_history_size = mib_scalar((1, 3, 6, 1, 4, 1, 1027, 4, 6, 6), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
mitelNotifHistorySize.setStatus('mandatory')
mitel_notif_history_table = mib_table((1, 3, 6, 1, 4, 1, 1027, 4, 6, 7))
if mibBuilder.loadTexts:
mitelNotifHistoryTable.setStatus('mandatory')
mitel_notif_history_table_entry = mib_table_row((1, 3, 6, 1, 4, 1, 1027, 4, 6, 7, 1)).setIndexNames((0, 'MITEL-MIB', 'mitelNotifHistTblIndex'))
if mibBuilder.loadTexts:
mitelNotifHistoryTableEntry.setStatus('mandatory')
mitel_notif_hist_tbl_index = mib_table_column((1, 3, 6, 1, 4, 1, 1027, 4, 6, 7, 1, 1), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
mitelNotifHistTblIndex.setStatus('mandatory')
mitel_notif_hist_tbl_id = mib_table_column((1, 3, 6, 1, 4, 1, 1027, 4, 6, 7, 1, 2), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
mitelNotifHistTblId.setStatus('mandatory')
mitel_notif_hist_tbl_time = mib_table_column((1, 3, 6, 1, 4, 1, 1027, 4, 6, 7, 1, 3), time_stamp()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
mitelNotifHistTblTime.setStatus('mandatory')
mitel_notif_hist_tbl_if_index = mib_table_column((1, 3, 6, 1, 4, 1, 1027, 4, 6, 7, 1, 4), interface_index()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
mitelNotifHistTblIfIndex.setStatus('mandatory')
mitel_notif_hist_tbl_confirmed = mib_table_column((1, 3, 6, 1, 4, 1, 1027, 4, 6, 7, 1, 5), truth_value()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
mitelNotifHistTblConfirmed.setStatus('mandatory')
mitel_notif_unack_table = mib_table((1, 3, 6, 1, 4, 1, 1027, 4, 6, 8))
if mibBuilder.loadTexts:
mitelNotifUnackTable.setStatus('mandatory')
mitel_notif_unack_table_entry = mib_table_row((1, 3, 6, 1, 4, 1, 1027, 4, 6, 8, 1)).setIndexNames((0, 'MITEL-MIB', 'mitelNotifUnackTblIndex'))
if mibBuilder.loadTexts:
mitelNotifUnackTableEntry.setStatus('mandatory')
mitel_notif_unack_tbl_index = mib_table_column((1, 3, 6, 1, 4, 1, 1027, 4, 6, 8, 1, 1), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
mitelNotifUnackTblIndex.setStatus('mandatory')
mitel_notif_unack_tbl_status = mib_table_column((1, 3, 6, 1, 4, 1, 1027, 4, 6, 8, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 6))).clone(namedValues=named_values(('active', 1), ('notInService', 2), ('destory', 6)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
mitelNotifUnackTblStatus.setStatus('mandatory')
mitel_notif_unack_tbl_history = mib_table_column((1, 3, 6, 1, 4, 1, 1027, 4, 6, 8, 1, 3), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
mitelNotifUnackTblHistory.setStatus('mandatory')
mitel_notif_unack_tbl_manager = mib_table_column((1, 3, 6, 1, 4, 1, 1027, 4, 6, 8, 1, 4), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
mitelNotifUnackTblManager.setStatus('mandatory')
mitel_notif_unack_tbl_retries_left = mib_table_column((1, 3, 6, 1, 4, 1, 1027, 4, 6, 8, 1, 5), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
mitelNotifUnackTblRetriesLeft.setStatus('mandatory')
mitel_notif_agent_address = mib_scalar((1, 3, 6, 1, 4, 1, 1027, 4, 6, 9), t_address()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
mitelNotifAgentAddress.setStatus('mandatory')
mitel_traps_comm_lost = notification_type((1, 3, 6, 1, 4, 1, 1027, 4, 6, 1) + (0, 1)).setObjects(('MITEL-MIB', 'mitelNotifUnackTblStatus'), ('MITEL-MIB', 'mitelNotifMgrTblDomain'), ('MITEL-MIB', 'mitelNotifMgrTblAddress'))
mitel_traps_reset = notification_type((1, 3, 6, 1, 4, 1, 1027, 4, 6, 1) + (0, 2)).setObjects(('MITEL-MIB', 'mitelNotifUnackTblStatus'), ('MITEL-MIB', 'mitelResetReason'))
mitel_grp_cmn_notif_basic = mib_identifier((1, 3, 6, 1, 4, 1, 1027, 5, 2, 1, 2))
mitel_grp_cmn_notif_managers = mib_identifier((1, 3, 6, 1, 4, 1, 1027, 5, 2, 1, 3))
mitel_grp_cmn_notif_history = mib_identifier((1, 3, 6, 1, 4, 1, 1027, 5, 2, 1, 4))
mitel_grp_cmn_notif_ack = mib_identifier((1, 3, 6, 1, 4, 1, 1027, 5, 2, 1, 5))
mitel_grp_cmn_interfaces = mib_identifier((1, 3, 6, 1, 4, 1, 1027, 5, 2, 1, 6))
mitel_grp_cmn_reset = mib_identifier((1, 3, 6, 1, 4, 1, 1027, 5, 2, 1, 7))
mitel_compl_mitel = mib_identifier((1, 3, 6, 1, 4, 1, 1027, 5, 1, 1))
mibBuilder.exportSymbols('MITEL-MIB', snmpUDPDomain=snmpUDPDomain, mitelNotifMgrTblLife=mitelNotifMgrTblLife, mitelNotifMgrTblStatus=mitelNotifMgrTblStatus, mitelIdInterfaces=mitelIdInterfaces, TimeStamp=TimeStamp, mitelGrpCommon=mitelGrpCommon, mitelNotifHistoryTableEntry=mitelNotifHistoryTableEntry, mitelExtInterfaces=mitelExtInterfaces, mitelGrpCmnNotifBasic=mitelGrpCmnNotifBasic, TruthValue=TruthValue, mitelPropProtocols=mitelPropProtocols, mitelNotifUnackTableEntry=mitelNotifUnackTableEntry, mitelResetReason=mitelResetReason, mitelNotifEnableTable=mitelNotifEnableTable, mitelNotifMgrTblRetries=mitelNotifMgrTblRetries, RowStatus=RowStatus, MitelNotifyTransportType=MitelNotifyTransportType, mitelNotifHistoryMax=mitelNotifHistoryMax, mitelTrapsCommLost=mitelTrapsCommLost, mitelGrpCmnInterfaces=mitelGrpCmnInterfaces, mitelNotifMgrTblDomain=mitelNotifMgrTblDomain, mitelNotifEnblTblEnable=mitelNotifEnblTblEnable, mitelResetAgent=mitelResetAgent, mitelNotifEnblTblOid=mitelNotifEnblTblOid, snmpV2=snmpV2, mitelNotifHistoryTable=mitelNotifHistoryTable, mitelConformance=mitelConformance, mitelIdMgmtOpsMgr=mitelIdMgmtOpsMgr, mitelResetPlatform=mitelResetPlatform, mitelPropTransmission=mitelPropTransmission, snmpDomains=snmpDomains, mitelPropReset=mitelPropReset, InterfaceIndex=InterfaceIndex, mitelNotifUnackTblStatus=mitelNotifUnackTblStatus, mitelPropHardware=mitelPropHardware, MitelIfType=MitelIfType, mitelGrpCmnReset=mitelGrpCmnReset, mitelGrpOpsMgr=mitelGrpOpsMgr, mitelNotifMgrTblAddress=mitelNotifMgrTblAddress, mitelNotifHistTblConfirmed=mitelNotifHistTblConfirmed, mitelIfTable=mitelIfTable, mitelNotifUnackTblRetriesLeft=mitelNotifUnackTblRetriesLeft, mitelNotifHistTblTime=mitelNotifHistTblTime, mitelNotifHistTblIndex=mitelNotifHistTblIndex, mitelPropApplications=mitelPropApplications, mitelPropNotifications=mitelPropNotifications, mitelNotifMgrTblIndex=mitelNotifMgrTblIndex, mitelConfAgents=mitelConfAgents, mitelNotifTraps=mitelNotifTraps, mitelConfGroups=mitelConfGroups, mitelIfTableEntry=mitelIfTableEntry, mitelGrpCmnNotifHistory=mitelGrpCmnNotifHistory, mitelNotifMgrTblTimeout=mitelNotifMgrTblTimeout, mitelPropUtilities=mitelPropUtilities, mitelNotifHistTblIfIndex=mitelNotifHistTblIfIndex, mitelNotifEnblTblDescr=mitelNotifEnblTblDescr, mitelIdCsMc2=mitelIdCsMc2, mitelExtensions=mitelExtensions, mitelNotifAgentAddress=mitelNotifAgentAddress, mitelNotifMgrTblTransport=mitelNotifMgrTblTransport, mitelNotifManagerTableEntry=mitelNotifManagerTableEntry, TAddress=TAddress, mitelNotifHistorySize=mitelNotifHistorySize, mitelComplMitel=mitelComplMitel, mitelNotifCount=mitelNotifCount, TDomain=TDomain, mitelIdCtiPlatforms=mitelIdCtiPlatforms, mitelIdTerminals=mitelIdTerminals, mitelGrpCmnNotifAck=mitelGrpCmnNotifAck, mitelNotifHistTblId=mitelNotifHistTblId, mitelIdCs2000Light=mitelIdCs2000Light, mitelNotifMgrTblName=mitelNotifMgrTblName, mitelNotifMgrTblCommunity=mitelNotifMgrTblCommunity, mitelConfCompliances=mitelConfCompliances, mitelIdCallServers=mitelIdCallServers, mitelNotifEnableTableEntry=mitelNotifEnableTableEntry, mitelIfNumber=mitelIfNumber, TimeInterval=TimeInterval, mitelProprietary=mitelProprietary, mitelNotifEnblTblOccurrences=mitelNotifEnblTblOccurrences, mitelNotifUnackTblManager=mitelNotifUnackTblManager, mitelNotifUnackTable=mitelNotifUnackTable, mitelIdMgmtPlatforms=mitelIdMgmtPlatforms, mitelIfTblType=mitelIfTblType, mitelNotifUnackTblIndex=mitelNotifUnackTblIndex, mitelTrapsReset=mitelTrapsReset, mitelNotifUnackTblHistory=mitelNotifUnackTblHistory, mitelNotifEnblTblIndex=mitelNotifEnblTblIndex, mitelAppCallServer=mitelAppCallServer, mitel=mitel, mitelNotifEnblTblAck=mitelNotifEnblTblAck, mitelIdentification=mitelIdentification, mitelExperimental=mitelExperimental, mitelNotifManagerTable=mitelNotifManagerTable, mitelGrpCmnNotifManagers=mitelGrpCmnNotifManagers, mitelGrpCs2000=mitelGrpCs2000) |
#!/usr/bin/python3
def print_matrix_integer(matrix=[[]]):
"prints a matrix of integers"
row_len = len(matrix)
col_len = len(matrix[0])
for i in range(row_len):
for j in range(col_len):
if j != col_len - 1:
print("{:d}".format(matrix[i][j]), end=' ')
else:
print("{:d}".format(matrix[i][j]), end='')
print("")
| def print_matrix_integer(matrix=[[]]):
"""prints a matrix of integers"""
row_len = len(matrix)
col_len = len(matrix[0])
for i in range(row_len):
for j in range(col_len):
if j != col_len - 1:
print('{:d}'.format(matrix[i][j]), end=' ')
else:
print('{:d}'.format(matrix[i][j]), end='')
print('') |
def sum_of_squares(n):
total = 0
for i in range(n):
if i * i < n:
total += i * i
else:
break
return total
| def sum_of_squares(n):
total = 0
for i in range(n):
if i * i < n:
total += i * i
else:
break
return total |
_base_ = [
'../_base_/models/fcn_r50-d8.py', '../_base_/datasets/pascal_context.py',
'../_base_/default_runtime.py', '../_base_/schedules/schedule_40k.py'
]
model = dict(
decode_head=dict(num_classes=60),
auxiliary_head=dict(num_classes=60),
test_cfg=dict(mode='slide', crop_size=(480, 480), stride=(320, 320)))
optimizer = dict(type='SGD', lr=0.004, momentum=0.9, weight_decay=0.0001)
| _base_ = ['../_base_/models/fcn_r50-d8.py', '../_base_/datasets/pascal_context.py', '../_base_/default_runtime.py', '../_base_/schedules/schedule_40k.py']
model = dict(decode_head=dict(num_classes=60), auxiliary_head=dict(num_classes=60), test_cfg=dict(mode='slide', crop_size=(480, 480), stride=(320, 320)))
optimizer = dict(type='SGD', lr=0.004, momentum=0.9, weight_decay=0.0001) |
_base_ = [
'../_base_/models/irrpwc.py',
'../_base_/datasets/flyingthings3d_subset_bi_with_occ_384x768.py',
'../_base_/schedules/schedule_s_fine_half.py',
'../_base_/default_runtime.py'
]
custom_hooks = [dict(type='EMAHook')]
data = dict(
train_dataloader=dict(
samples_per_gpu=1, workers_per_gpu=5, drop_last=True),
val_dataloader=dict(samples_per_gpu=1, workers_per_gpu=5, shuffle=False),
test_dataloader=dict(samples_per_gpu=1, workers_per_gpu=5, shuffle=False))
# Train on FlyingChairsOcc and finetune on FlyingThings3D_subset
load_from = 'https://download.openmmlab.com/mmflow/irr/irrpwc_8x1_sshort_flyingchairsocc_384x448.pth' # noqa
| _base_ = ['../_base_/models/irrpwc.py', '../_base_/datasets/flyingthings3d_subset_bi_with_occ_384x768.py', '../_base_/schedules/schedule_s_fine_half.py', '../_base_/default_runtime.py']
custom_hooks = [dict(type='EMAHook')]
data = dict(train_dataloader=dict(samples_per_gpu=1, workers_per_gpu=5, drop_last=True), val_dataloader=dict(samples_per_gpu=1, workers_per_gpu=5, shuffle=False), test_dataloader=dict(samples_per_gpu=1, workers_per_gpu=5, shuffle=False))
load_from = 'https://download.openmmlab.com/mmflow/irr/irrpwc_8x1_sshort_flyingchairsocc_384x448.pth' |
class Solution:
def isAlienSorted(self, words, order):
lookup = {c: i for i, c in enumerate(order)}
for i in range(len(words) - 1):
word1 = words[i]
word2 = words[i + 1]
for j in range(min(len(word1), len(word2))):
if word1[j] != word2[j]:
if lookup[word1[j]] > lookup[word2[j]]:
return False
break
else:
if len(word1) > len(word2):
return False
return True
if __name__ == '__main__':
words = ["apap","app"]
order = "abcdefghijklmnopqrstuvwxyz"
s = Solution()
print(s.isAlienSorted(words, order)) | class Solution:
def is_alien_sorted(self, words, order):
lookup = {c: i for (i, c) in enumerate(order)}
for i in range(len(words) - 1):
word1 = words[i]
word2 = words[i + 1]
for j in range(min(len(word1), len(word2))):
if word1[j] != word2[j]:
if lookup[word1[j]] > lookup[word2[j]]:
return False
break
else:
if len(word1) > len(word2):
return False
return True
if __name__ == '__main__':
words = ['apap', 'app']
order = 'abcdefghijklmnopqrstuvwxyz'
s = solution()
print(s.isAlienSorted(words, order)) |
#!/usr/bin/python
# sorting.py
items = { "coins": 7, "pens": 3, "cups": 2,
"bags": 1, "bottles": 4, "books": 5 }
for key in sorted(items.keys()):
print ("%s: %s" % (key, items[key]))
print ("####### #######")
for key in sorted(items.keys(), reverse=True):
print ("%s: %s" % (key, items[key]))
| items = {'coins': 7, 'pens': 3, 'cups': 2, 'bags': 1, 'bottles': 4, 'books': 5}
for key in sorted(items.keys()):
print('%s: %s' % (key, items[key]))
print('####### #######')
for key in sorted(items.keys(), reverse=True):
print('%s: %s' % (key, items[key])) |
# variants
model_type = 'SepDisc'
runner = 'SepDiscRunner01'
lambda_img = 0.001
lambda_lidar = 0.001
src_acc_threshold = 0.6
tgt_acc_threshold = 0.6
img_disc = dict(type='FCDiscriminatorCE', in_dim=64)
img_opt = dict(type='Adam', lr=0.0002, weight_decay=0.001)
lidar_disc = dict(type='FCDiscriminatorCE', in_dim=64)
lidar_opt = dict(type='Adam', lr=0.0002, weight_decay=0.001)
return_fusion_feats = False
point_cloud_range = [-50, 0, -5, 50, 50, 3]
anchor_generator_ranges = [[-50, 0, -1.8, 50, 50, -1.8]]
scatter_shape = [200, 400]
voxel_size = [0.25, 0.25, 8]
src_train = 'mmda_xmuda_split/train_usa.pkl'
tgt_train = 'mmda_xmuda_split/train_singapore.pkl'
ann_val = 'mmda_xmuda_split/test_singapore.pkl'
img_feat_channels = 64
model = dict(
type=model_type,
img_backbone=dict(
type='UNetResNet34',
out_channels=img_feat_channels,
pretrained=True),
img_seg_head=dict(
type='SepDiscHead',
img_feat_dim=img_feat_channels,
seg_pts_dim=4,
num_classes=5,
lidar_fc=[64, 64],
concat_fc=[128, 64],
class_weights=[2.68678412, 4.36182969, 5.47896839, 3.89026883, 1.])
)
train_cfg = None
test_cfg = None
class_names = [
'vehicle', # car, truck, bus, trailer, cv
'pedestrian', # pedestrian
'bike', # motorcycle, bicycle
'traffic_boundary' # traffic_cone, barrier
# background
]
data_root = '/home/xyyue/xiangyu/nuscenes_unzip/'
input_modality = dict(
use_lidar=True,
use_camera=True,
use_radar=False,
use_map=False,
use_external=False)
file_client_args = dict(backend='disk')
train_pipeline = [
dict(type='LoadSegDetPointsFromFile', # 'points', 'seg_points', 'seg_label'
load_dim=5,
use_dim=5),
dict(type='LoadFrontImage'), # filter 'seg_points', 'seg_label', 'seg_pts_indices' inside front camera; 'img'
dict(type='SegDetPointsRangeFilter', point_cloud_range=point_cloud_range), # filter 'points', 'seg_points' within point_cloud_range
dict(type='MergeCat'), # merge 'seg_label', 'gt_labels_3d' (from 10 classes to 4 classes, without background)
dict(type='SegDetFormatBundle'),
dict(type='Collect3D', keys=['img', 'seg_points', 'seg_pts_indices', 'seg_label'])
]
test_pipeline = [
dict(
type='LoadSegDetPointsFromFile',
load_dim=5,
use_dim=5),
dict(type='LoadFrontImage'), # filter 'seg_points', 'seg_label', 'seg_pts_indices' inside front camera; 'img'
dict(type='SegDetPointsRangeFilter', point_cloud_range=point_cloud_range), # filter 'points', 'seg_points' within point_cloud_range
dict(type='MergeCat'), # merge 'seg_label', 'gt_labels_3d' (from 10 classes to 4 classes, without background)
dict(type='SegDetFormatBundle'),
dict(type='Collect3D', keys=['img', 'seg_points', 'seg_pts_indices', 'seg_label'])
]
# dataset
dataset_type = 'MMDAMergeCatDataset'
data = dict(
samples_per_gpu=4,
workers_per_gpu=4,
source_train=dict(
type=dataset_type,
data_root=data_root,
ann_file=data_root + src_train,
pipeline=train_pipeline,
classes=class_names,
modality=input_modality,
filter_empty_gt=False,
test_mode=False,
box_type_3d='LiDAR'),
target_train=dict(
type=dataset_type,
data_root=data_root,
ann_file=data_root + tgt_train,
pipeline=train_pipeline,
classes=class_names,
modality=input_modality,
filter_empty_gt=False,
test_mode=False,
box_type_3d='LiDAR'),
val=dict(
type=dataset_type,
data_root=data_root,
ann_file=data_root + ann_val,
pipeline=test_pipeline,
classes=class_names,
modality=input_modality,
filter_empty_gt=False,
test_mode=True,
box_type_3d='LiDAR'),
test=dict(
type=dataset_type,
data_root=data_root,
ann_file=data_root + ann_val,
pipeline=test_pipeline,
classes=class_names,
modality=input_modality,
filter_empty_gt=False,
test_mode=True,
box_type_3d='LiDAR'))
evaluation = dict(interval=100)
# shedule_2x.py
optimizer = dict(type='AdamW', lr=0.001, weight_decay=0.01)
# optimizer_config = dict(grad_clip=dict(max_norm=35, norm_type=2))
lr_config = dict(
policy='step',
warmup='linear',
warmup_iters=1000,
warmup_ratio=1.0 / 1000,
step=[12, 18])
momentum_config = None
total_epochs = 24
# default_runtime.py
checkpoint_config = dict(interval=1)
log_config = dict(
interval=50,
hooks=[
dict(type='TextLoggerHook'),
dict(type='TensorboardLoggerHook')
])
# yapf:enable
dist_params = dict(backend='nccl')
log_level = 'INFO'
work_dir = None
load_from = None
resume_from = None
workflow = [('train', 1)]
| model_type = 'SepDisc'
runner = 'SepDiscRunner01'
lambda_img = 0.001
lambda_lidar = 0.001
src_acc_threshold = 0.6
tgt_acc_threshold = 0.6
img_disc = dict(type='FCDiscriminatorCE', in_dim=64)
img_opt = dict(type='Adam', lr=0.0002, weight_decay=0.001)
lidar_disc = dict(type='FCDiscriminatorCE', in_dim=64)
lidar_opt = dict(type='Adam', lr=0.0002, weight_decay=0.001)
return_fusion_feats = False
point_cloud_range = [-50, 0, -5, 50, 50, 3]
anchor_generator_ranges = [[-50, 0, -1.8, 50, 50, -1.8]]
scatter_shape = [200, 400]
voxel_size = [0.25, 0.25, 8]
src_train = 'mmda_xmuda_split/train_usa.pkl'
tgt_train = 'mmda_xmuda_split/train_singapore.pkl'
ann_val = 'mmda_xmuda_split/test_singapore.pkl'
img_feat_channels = 64
model = dict(type=model_type, img_backbone=dict(type='UNetResNet34', out_channels=img_feat_channels, pretrained=True), img_seg_head=dict(type='SepDiscHead', img_feat_dim=img_feat_channels, seg_pts_dim=4, num_classes=5, lidar_fc=[64, 64], concat_fc=[128, 64], class_weights=[2.68678412, 4.36182969, 5.47896839, 3.89026883, 1.0]))
train_cfg = None
test_cfg = None
class_names = ['vehicle', 'pedestrian', 'bike', 'traffic_boundary']
data_root = '/home/xyyue/xiangyu/nuscenes_unzip/'
input_modality = dict(use_lidar=True, use_camera=True, use_radar=False, use_map=False, use_external=False)
file_client_args = dict(backend='disk')
train_pipeline = [dict(type='LoadSegDetPointsFromFile', load_dim=5, use_dim=5), dict(type='LoadFrontImage'), dict(type='SegDetPointsRangeFilter', point_cloud_range=point_cloud_range), dict(type='MergeCat'), dict(type='SegDetFormatBundle'), dict(type='Collect3D', keys=['img', 'seg_points', 'seg_pts_indices', 'seg_label'])]
test_pipeline = [dict(type='LoadSegDetPointsFromFile', load_dim=5, use_dim=5), dict(type='LoadFrontImage'), dict(type='SegDetPointsRangeFilter', point_cloud_range=point_cloud_range), dict(type='MergeCat'), dict(type='SegDetFormatBundle'), dict(type='Collect3D', keys=['img', 'seg_points', 'seg_pts_indices', 'seg_label'])]
dataset_type = 'MMDAMergeCatDataset'
data = dict(samples_per_gpu=4, workers_per_gpu=4, source_train=dict(type=dataset_type, data_root=data_root, ann_file=data_root + src_train, pipeline=train_pipeline, classes=class_names, modality=input_modality, filter_empty_gt=False, test_mode=False, box_type_3d='LiDAR'), target_train=dict(type=dataset_type, data_root=data_root, ann_file=data_root + tgt_train, pipeline=train_pipeline, classes=class_names, modality=input_modality, filter_empty_gt=False, test_mode=False, box_type_3d='LiDAR'), val=dict(type=dataset_type, data_root=data_root, ann_file=data_root + ann_val, pipeline=test_pipeline, classes=class_names, modality=input_modality, filter_empty_gt=False, test_mode=True, box_type_3d='LiDAR'), test=dict(type=dataset_type, data_root=data_root, ann_file=data_root + ann_val, pipeline=test_pipeline, classes=class_names, modality=input_modality, filter_empty_gt=False, test_mode=True, box_type_3d='LiDAR'))
evaluation = dict(interval=100)
optimizer = dict(type='AdamW', lr=0.001, weight_decay=0.01)
lr_config = dict(policy='step', warmup='linear', warmup_iters=1000, warmup_ratio=1.0 / 1000, step=[12, 18])
momentum_config = None
total_epochs = 24
checkpoint_config = dict(interval=1)
log_config = dict(interval=50, hooks=[dict(type='TextLoggerHook'), dict(type='TensorboardLoggerHook')])
dist_params = dict(backend='nccl')
log_level = 'INFO'
work_dir = None
load_from = None
resume_from = None
workflow = [('train', 1)] |
def debug(x):
print(x)
### Notebook Magics
# %matplotlib inline
def juptyerConfig(pd, max_columns=500, max_rows = 500, float_format = '{:,.6f}', max_info_rows = 1000, max_categories = 500):
pd.options.display.max_columns = 500
pd.options.display.max_rows = 500
pd.options.display.float_format = float_format.format
pd.options.display.max_info_rows = 1000
pd.options.display.max_categories = 500
# from IPython.core.interactiveshell import InteractiveShell
# InteractiveShell.ast_node_interactivity = "all"
def createDataFilePath(data_dir='', data_file_name=''):
return data_dir + data_file_name | def debug(x):
print(x)
def juptyer_config(pd, max_columns=500, max_rows=500, float_format='{:,.6f}', max_info_rows=1000, max_categories=500):
pd.options.display.max_columns = 500
pd.options.display.max_rows = 500
pd.options.display.float_format = float_format.format
pd.options.display.max_info_rows = 1000
pd.options.display.max_categories = 500
def create_data_file_path(data_dir='', data_file_name=''):
return data_dir + data_file_name |
n = [ 1 ] + [ 50 ] * 10 + [ 1 ]
with open('8.in', 'r') as f:
totn, m, k, op = [ int(x) for x in f.readline().split() ]
for i in range(m):
f.readline()
for i, v in enumerate(n):
with open('p%d.in' % i, 'w') as o:
o.write('%d 0 %d 2\n' % (v, k))
for j in range(v):
o.write(f.readline() + '\n')
| n = [1] + [50] * 10 + [1]
with open('8.in', 'r') as f:
(totn, m, k, op) = [int(x) for x in f.readline().split()]
for i in range(m):
f.readline()
for (i, v) in enumerate(n):
with open('p%d.in' % i, 'w') as o:
o.write('%d 0 %d 2\n' % (v, k))
for j in range(v):
o.write(f.readline() + '\n') |
# Configuration file for ipython-console.
c = get_config()
#------------------------------------------------------------------------------
# ZMQTerminalIPythonApp configuration
#------------------------------------------------------------------------------
# ZMQTerminalIPythonApp will inherit config from: TerminalIPythonApp,
# BaseIPythonApplication, Application, InteractiveShellApp, IPythonConsoleApp,
# ConnectionFileMixin
# The Logging format template
# c.ZMQTerminalIPythonApp.log_format = '[%(name)s]%(highlevel)s %(message)s'
# List of files to run at IPython startup.
# c.ZMQTerminalIPythonApp.exec_files = []
# set the stdin (ROUTER) port [default: random]
# c.ZMQTerminalIPythonApp.stdin_port = 0
# set the iopub (PUB) port [default: random]
# c.ZMQTerminalIPythonApp.iopub_port = 0
# Execute the given command string.
# c.ZMQTerminalIPythonApp.code_to_run = ''
# The name of the IPython directory. This directory is used for logging
# configuration (through profiles), history storage, etc. The default is usually
# $HOME/.ipython. This option can also be specified through the environment
# variable IPYTHONDIR.
# c.ZMQTerminalIPythonApp.ipython_dir = ''
# A file to be run
# c.ZMQTerminalIPythonApp.file_to_run = ''
# Run the module as a script.
# c.ZMQTerminalIPythonApp.module_to_run = ''
# Whether to display a banner upon starting IPython.
# c.ZMQTerminalIPythonApp.display_banner = True
# Enable GUI event loop integration with any of ('glut', 'gtk', 'gtk3', 'osx',
# 'pyglet', 'qt', 'qt5', 'tk', 'wx').
# c.ZMQTerminalIPythonApp.gui = None
# Start IPython quickly by skipping the loading of config files.
# c.ZMQTerminalIPythonApp.quick = False
# Set the log level by value or name.
# c.ZMQTerminalIPythonApp.log_level = 30
# Path to the ssh key to use for logging in to the ssh server.
# c.ZMQTerminalIPythonApp.sshkey = ''
# The SSH server to use to connect to the kernel.
# c.ZMQTerminalIPythonApp.sshserver = ''
# lines of code to run at IPython startup.
# c.ZMQTerminalIPythonApp.exec_lines = []
# Pre-load matplotlib and numpy for interactive use, selecting a particular
# matplotlib backend and loop integration.
# c.ZMQTerminalIPythonApp.pylab = None
# Path to an extra config file to load.
#
# If specified, load this config file in addition to any other IPython config.
# c.ZMQTerminalIPythonApp.extra_config_file = ''
# set the shell (ROUTER) port [default: random]
# c.ZMQTerminalIPythonApp.shell_port = 0
# The IPython profile to use.
# c.ZMQTerminalIPythonApp.profile = 'default'
# JSON file in which to store connection info [default: kernel-<pid>.json]
#
# This file will contain the IP, ports, and authentication key needed to connect
# clients to this kernel. By default, this file will be created in the security
# dir of the current profile, but can be specified by absolute path.
# c.ZMQTerminalIPythonApp.connection_file = ''
# Run the file referenced by the PYTHONSTARTUP environment variable at IPython
# startup.
# c.ZMQTerminalIPythonApp.exec_PYTHONSTARTUP = True
# Should variables loaded at startup (by startup files, exec_lines, etc.) be
# hidden from tools like %who?
# c.ZMQTerminalIPythonApp.hide_initial_ns = True
# Whether to install the default config files into the profile dir. If a new
# profile is being created, and IPython contains config files for that profile,
# then they will be staged into the new directory. Otherwise, default config
# files will be automatically generated.
# c.ZMQTerminalIPythonApp.copy_config_files = False
# Whether to overwrite existing config files when copying
# c.ZMQTerminalIPythonApp.overwrite = False
# Configure matplotlib for interactive use with the default matplotlib backend.
# c.ZMQTerminalIPythonApp.matplotlib = None
# Set to display confirmation dialog on exit. You can always use 'exit' or
# 'quit', to force a direct exit without any confirmation.
# c.ZMQTerminalIPythonApp.confirm_exit = True
# If a command or file is given via the command-line, e.g. 'ipython foo.py',
# start an interactive shell after executing the file or command.
# c.ZMQTerminalIPythonApp.force_interact = False
#
# c.ZMQTerminalIPythonApp.transport = 'tcp'
# set the control (ROUTER) port [default: random]
# c.ZMQTerminalIPythonApp.control_port = 0
# dotted module name of an IPython extension to load.
# c.ZMQTerminalIPythonApp.extra_extension = ''
# Set the kernel's IP address [default localhost]. If the IP address is
# something other than localhost, then Consoles on other machines will be able
# to connect to the Kernel, so be careful!
# c.ZMQTerminalIPythonApp.ip = ''
# If true, IPython will populate the user namespace with numpy, pylab, etc. and
# an ``import *`` is done from numpy and pylab, when using pylab mode.
#
# When False, pylab mode should not import any names into the user namespace.
# c.ZMQTerminalIPythonApp.pylab_import_all = True
# set the heartbeat port [default: random]
# c.ZMQTerminalIPythonApp.hb_port = 0
# The date format used by logging formatters for %(asctime)s
# c.ZMQTerminalIPythonApp.log_datefmt = '%Y-%m-%d %H:%M:%S'
# The name of the default kernel to start.
# c.ZMQTerminalIPythonApp.kernel_name = 'python'
# Create a massive crash report when IPython encounters what may be an internal
# error. The default is to append a short message to the usual traceback
# c.ZMQTerminalIPythonApp.verbose_crash = False
# A list of dotted module names of IPython extensions to load.
# c.ZMQTerminalIPythonApp.extensions = []
# Connect to an already running kernel
# c.ZMQTerminalIPythonApp.existing = ''
# Suppress warning messages about legacy config files
# c.ZMQTerminalIPythonApp.ignore_old_config = False
#------------------------------------------------------------------------------
# ZMQTerminalInteractiveShell configuration
#------------------------------------------------------------------------------
# A subclass of TerminalInteractiveShell that uses the 0MQ kernel
# ZMQTerminalInteractiveShell will inherit config from:
# TerminalInteractiveShell, InteractiveShell
# Set the editor used by IPython (default to $EDITOR/vi/notepad).
# c.ZMQTerminalInteractiveShell.editor = 'vi'
# 'all', 'last', 'last_expr' or 'none', specifying which nodes should be run
# interactively (displaying output from expressions).
# c.ZMQTerminalInteractiveShell.ast_node_interactivity = 'last_expr'
# Set the color scheme (NoColor, Linux, or LightBG).
# c.ZMQTerminalInteractiveShell.colors = 'Linux'
# Autoindent IPython code entered interactively.
# c.ZMQTerminalInteractiveShell.autoindent = True
# Whether to include output from clients other than this one sharing the same
# kernel.
#
# Outputs are not displayed until enter is pressed.
# c.ZMQTerminalInteractiveShell.include_other_output = False
# A list of ast.NodeTransformer subclass instances, which will be applied to
# user input before code is run.
# c.ZMQTerminalInteractiveShell.ast_transformers = []
#
# c.ZMQTerminalInteractiveShell.readline_parse_and_bind = ['tab: complete', '"\\C-l": clear-screen', 'set show-all-if-ambiguous on', '"\\C-o": tab-insert', '"\\C-r": reverse-search-history', '"\\C-s": forward-search-history', '"\\C-p": history-search-backward', '"\\C-n": history-search-forward', '"\\e[A": history-search-backward', '"\\e[B": history-search-forward', '"\\C-k": kill-line', '"\\C-u": unix-line-discard']
# Enable deep (recursive) reloading by default. IPython can use the deep_reload
# module which reloads changes in modules recursively (it replaces the reload()
# function, so you don't need to change anything to use it). deep_reload()
# forces a full reload of modules whose code may have changed, which the default
# reload() function does not. When deep_reload is off, IPython will use the
# normal reload(), but deep_reload will still be available as dreload().
# c.ZMQTerminalInteractiveShell.deep_reload = False
# Save multi-line entries as one entry in readline history
# c.ZMQTerminalInteractiveShell.multiline_history = True
# Callable object called via 'callable' image handler with one argument, `data`,
# which is `msg["content"]["data"]` where `msg` is the message from iopub
# channel. For exmaple, you can find base64 encoded PNG data as
# `data['image/png']`.
# c.ZMQTerminalInteractiveShell.callable_image_handler = None
#
# c.ZMQTerminalInteractiveShell.separate_out2 = ''
# Don't call post-execute functions that have failed in the past.
# c.ZMQTerminalInteractiveShell.disable_failing_post_execute = False
# Start logging to the given file in append mode.
# c.ZMQTerminalInteractiveShell.logappend = ''
#
# c.ZMQTerminalInteractiveShell.separate_in = '\n'
#
# c.ZMQTerminalInteractiveShell.readline_use = True
# Make IPython automatically call any callable object even if you didn't type
# explicit parentheses. For example, 'str 43' becomes 'str(43)' automatically.
# The value can be '0' to disable the feature, '1' for 'smart' autocall, where
# it is not applied if there are no more arguments on the line, and '2' for
# 'full' autocall, where all callable objects are automatically called (even if
# no arguments are present).
# c.ZMQTerminalInteractiveShell.autocall = 0
# Enable auto setting the terminal title.
# c.ZMQTerminalInteractiveShell.term_title = False
# Automatically call the pdb debugger after every exception.
# c.ZMQTerminalInteractiveShell.pdb = False
# Deprecated, use PromptManager.in_template
# c.ZMQTerminalInteractiveShell.prompt_in1 = 'In [\\#]: '
# The part of the banner to be printed after the profile
# c.ZMQTerminalInteractiveShell.banner2 = ''
#
# c.ZMQTerminalInteractiveShell.wildcards_case_sensitive = True
#
# c.ZMQTerminalInteractiveShell.readline_remove_delims = '-/~'
# Deprecated, use PromptManager.out_template
# c.ZMQTerminalInteractiveShell.prompt_out = 'Out[\\#]: '
#
# c.ZMQTerminalInteractiveShell.xmode = 'Context'
# Use colors for displaying information about objects. Because this information
# is passed through a pager (like 'less'), and some pagers get confused with
# color codes, this capability can be turned off.
# c.ZMQTerminalInteractiveShell.color_info = True
# Command to invoke an image viewer program when you are using 'stream' image
# handler. This option is a list of string where the first element is the
# command itself and reminders are the options for the command. Raw image data
# is given as STDIN to the program.
# c.ZMQTerminalInteractiveShell.stream_image_handler = []
# Set the size of the output cache. The default is 1000, you can change it
# permanently in your config file. Setting it to 0 completely disables the
# caching system, and the minimum value accepted is 20 (if you provide a value
# less than 20, it is reset to 0 and a warning is issued). This limit is
# defined because otherwise you'll spend more time re-flushing a too small cache
# than working
# c.ZMQTerminalInteractiveShell.cache_size = 1000
#
# c.ZMQTerminalInteractiveShell.ipython_dir = ''
# Command to invoke an image viewer program when you are using 'tempfile' image
# handler. This option is a list of string where the first element is the
# command itself and reminders are the options for the command. You can use
# {file} and {format} in the string to represent the location of the generated
# image file and image format.
# c.ZMQTerminalInteractiveShell.tempfile_image_handler = []
# Deprecated, use PromptManager.in2_template
# c.ZMQTerminalInteractiveShell.prompt_in2 = ' .\\D.: '
# Enable magic commands to be called without the leading %.
# c.ZMQTerminalInteractiveShell.automagic = True
#
# c.ZMQTerminalInteractiveShell.separate_out = ''
# Timeout for giving up on a kernel (in seconds).
#
# On first connect and restart, the console tests whether the kernel is running
# and responsive by sending kernel_info_requests. This sets the timeout in
# seconds for how long the kernel can take before being presumed dead.
# c.ZMQTerminalInteractiveShell.kernel_timeout = 60
# Deprecated, use PromptManager.justify
# c.ZMQTerminalInteractiveShell.prompts_pad_left = True
# The shell program to be used for paging.
# c.ZMQTerminalInteractiveShell.pager = 'less'
# The name of the logfile to use.
# c.ZMQTerminalInteractiveShell.logfile = ''
# If True, anything that would be passed to the pager will be displayed as
# regular output instead.
# c.ZMQTerminalInteractiveShell.display_page = False
# auto editing of files with syntax errors.
# c.ZMQTerminalInteractiveShell.autoedit_syntax = False
# Handler for image type output. This is useful, for example, when connecting
# to the kernel in which pylab inline backend is activated. There are four
# handlers defined. 'PIL': Use Python Imaging Library to popup image; 'stream':
# Use an external program to show the image. Image will be fed into the STDIN
# of the program. You will need to configure `stream_image_handler`;
# 'tempfile': Use an external program to show the image. Image will be saved in
# a temporally file and the program is called with the temporally file. You
# will need to configure `tempfile_image_handler`; 'callable': You can set any
# Python callable which is called with the image data. You will need to
# configure `callable_image_handler`.
# c.ZMQTerminalInteractiveShell.image_handler = None
# Show rewritten input, e.g. for autocall.
# c.ZMQTerminalInteractiveShell.show_rewritten_input = True
# The part of the banner to be printed before the profile
# c.ZMQTerminalInteractiveShell.banner1 = 'Python 3.4.0 (default, Apr 11 2014, 13:05:18) \nType "copyright", "credits" or "license" for more information.\n\nIPython 3.0.0-rc1 -- An enhanced Interactive Python.\n? -> Introduction and overview of IPython\'s features.\n%quickref -> Quick reference.\nhelp -> Python\'s own help system.\nobject? -> Details about \'object\', use \'object??\' for extra details.\n'
# Set to confirm when you try to exit IPython with an EOF (Control-D in Unix,
# Control-Z/Enter in Windows). By typing 'exit' or 'quit', you can force a
# direct exit without any confirmation.
# c.ZMQTerminalInteractiveShell.confirm_exit = True
# Preferred object representation MIME type in order. First matched MIME type
# will be used.
# c.ZMQTerminalInteractiveShell.mime_preference = ['image/png', 'image/jpeg', 'image/svg+xml']
#
# c.ZMQTerminalInteractiveShell.history_length = 10000
#
# c.ZMQTerminalInteractiveShell.object_info_string_level = 0
#
# c.ZMQTerminalInteractiveShell.debug = False
# Start logging to the default log file.
# c.ZMQTerminalInteractiveShell.logstart = False
# Number of lines of your screen, used to control printing of very long strings.
# Strings longer than this number of lines will be sent through a pager instead
# of directly printed. The default value for this is 0, which means IPython
# will auto-detect your screen size every time it needs to print certain
# potentially long strings (this doesn't change the behavior of the 'print'
# keyword, it's only triggered internally). If for some reason this isn't
# working well (it needs curses support), specify it yourself. Otherwise don't
# change the default.
# c.ZMQTerminalInteractiveShell.screen_length = 0
# Prefix to add to outputs coming from clients other than this one.
#
# Only relevant if include_other_output is True.
# c.ZMQTerminalInteractiveShell.other_output_prefix = '[remote] '
#
# c.ZMQTerminalInteractiveShell.quiet = False
#------------------------------------------------------------------------------
# KernelManager configuration
#------------------------------------------------------------------------------
# Manages a single kernel in a subprocess on this host.
#
# This version starts kernels with Popen.
# KernelManager will inherit config from: ConnectionFileMixin
#
# c.KernelManager.transport = 'tcp'
# set the shell (ROUTER) port [default: random]
# c.KernelManager.shell_port = 0
# Set the kernel's IP address [default localhost]. If the IP address is
# something other than localhost, then Consoles on other machines will be able
# to connect to the Kernel, so be careful!
# c.KernelManager.ip = ''
# set the stdin (ROUTER) port [default: random]
# c.KernelManager.stdin_port = 0
# JSON file in which to store connection info [default: kernel-<pid>.json]
#
# This file will contain the IP, ports, and authentication key needed to connect
# clients to this kernel. By default, this file will be created in the security
# dir of the current profile, but can be specified by absolute path.
# c.KernelManager.connection_file = ''
# set the heartbeat port [default: random]
# c.KernelManager.hb_port = 0
# set the iopub (PUB) port [default: random]
# c.KernelManager.iopub_port = 0
# set the control (ROUTER) port [default: random]
# c.KernelManager.control_port = 0
# Should we autorestart the kernel if it dies.
# c.KernelManager.autorestart = False
# DEPRECATED: Use kernel_name instead.
#
# The Popen Command to launch the kernel. Override this if you have a custom
# kernel. If kernel_cmd is specified in a configuration file, IPython does not
# pass any arguments to the kernel, because it cannot make any assumptions about
# the arguments that the kernel understands. In particular, this means that the
# kernel does not receive the option --debug if it given on the IPython command
# line.
# c.KernelManager.kernel_cmd = []
#------------------------------------------------------------------------------
# ProfileDir configuration
#------------------------------------------------------------------------------
# An object to manage the profile directory and its resources.
#
# The profile directory is used by all IPython applications, to manage
# configuration, logging and security.
#
# This object knows how to find, create and manage these directories. This
# should be used by any code that wants to handle profiles.
# Set the profile location directly. This overrides the logic used by the
# `profile` option.
# c.ProfileDir.location = ''
#------------------------------------------------------------------------------
# Session configuration
#------------------------------------------------------------------------------
# Object for handling serialization and sending of messages.
#
# The Session object handles building messages and sending them with ZMQ sockets
# or ZMQStream objects. Objects can communicate with each other over the
# network via Session objects, and only need to work with the dict-based IPython
# message spec. The Session will handle serialization/deserialization, security,
# and metadata.
#
# Sessions support configurable serialization via packer/unpacker traits, and
# signing with HMAC digests via the key/keyfile traits.
#
# Parameters ----------
#
# debug : bool
# whether to trigger extra debugging statements
# packer/unpacker : str : 'json', 'pickle' or import_string
# importstrings for methods to serialize message parts. If just
# 'json' or 'pickle', predefined JSON and pickle packers will be used.
# Otherwise, the entire importstring must be used.
#
# The functions must accept at least valid JSON input, and output *bytes*.
#
# For example, to use msgpack:
# packer = 'msgpack.packb', unpacker='msgpack.unpackb'
# pack/unpack : callables
# You can also set the pack/unpack callables for serialization directly.
# session : bytes
# the ID of this Session object. The default is to generate a new UUID.
# username : unicode
# username added to message headers. The default is to ask the OS.
# key : bytes
# The key used to initialize an HMAC signature. If unset, messages
# will not be signed or checked.
# keyfile : filepath
# The file containing a key. If this is set, `key` will be initialized
# to the contents of the file.
# The UUID identifying this session.
# c.Session.session = ''
# Threshold (in bytes) beyond which an object's buffer should be extracted to
# avoid pickling.
# c.Session.buffer_threshold = 1024
# The maximum number of items for a container to be introspected for custom
# serialization. Containers larger than this are pickled outright.
# c.Session.item_threshold = 64
# The name of the unpacker for unserializing messages. Only used with custom
# functions for `packer`.
# c.Session.unpacker = 'json'
# path to file containing execution key.
# c.Session.keyfile = ''
# Metadata dictionary, which serves as the default top-level metadata dict for
# each message.
# c.Session.metadata = {}
# Debug output in the Session
# c.Session.debug = False
# The digest scheme used to construct the message signatures. Must have the form
# 'hmac-HASH'.
# c.Session.signature_scheme = 'hmac-sha256'
# The name of the packer for serializing messages. Should be one of 'json',
# 'pickle', or an import name for a custom callable serializer.
# c.Session.packer = 'json'
# Username for the Session. Default is your system username.
# c.Session.username = 'vagrant'
# The maximum number of digests to remember.
#
# The digest history will be culled when it exceeds this value.
# c.Session.digest_history_size = 65536
# execution key, for extra authentication.
# c.Session.key = b''
# Threshold (in bytes) beyond which a buffer should be sent without copying.
# c.Session.copy_threshold = 65536
| c = get_config() |
def fib(n):
'''Takes in a number n, and returns the nth fibonacci number, starting with: 1, 1, 2, 3, 5,...'''
if n <= 1:
return n
else:
return fib(n - 1) + fib(n - 2)
| def fib(n):
"""Takes in a number n, and returns the nth fibonacci number, starting with: 1, 1, 2, 3, 5,..."""
if n <= 1:
return n
else:
return fib(n - 1) + fib(n - 2) |
class Column(object):
def __init__(self, name, dataType):
self._number = 0
self._name = name
self._dataType = dataType
self._length = None
self._default = None
self._notNull = False
self._unique = False
self._constraint = None
self._check = []
self._primaryKey = False
self._foreignKey = None
self._autoincrement = False
# TODO FOREIGN KEY implementation
# {'refTable':None,'refColumn':None} {'Referenced table': None}
def __str__(self):
return self._name
@property
def name(self):
return self._name
@name.setter
def name(self, name):
self._name = name
@property
def dataType(self):
return self._dataType
@dataType.setter
def dataType(self, dataType):
self._dataType = dataType
@property
def length(self):
return self._length
@length.setter
def length(self, length):
self._length = length
@property
def notNull(self):
return self._notNull
@notNull.setter
def notNull(self, notNull):
self._notNull = notNull
@property
def primaryKey(self):
return self._primaryKey
@primaryKey.setter
def primaryKey(self, primaryKey):
self._primaryKey = primaryKey
@property
def number(self):
return self._number
@number.setter
def number(self, number):
self._number = number
@property
def foreignKey(self):
return self._foreignKey
@foreignKey.setter
def foreignKey(self, foreignKey):
self._foreignKey = foreignKey
@property
def unique(self):
return self._unique
@unique.setter
def unique(self, unique):
self._unique = unique
@property
def constraint(self):
return self._constraint
@constraint.setter
def constraint(self, constraint):
self._constraint = constraint
@property
def default(self):
return self._default
@default.setter
def default(self, default):
self._default = default
@property
def autoincrement(self):
return self._autoincrement
@autoincrement.setter
def autoincrement(self, autoincrement):
self._autoincrement = autoincrement
@property
def check(self):
return self._check
@check.setter
def check(self, check):
self._check = check
| class Column(object):
def __init__(self, name, dataType):
self._number = 0
self._name = name
self._dataType = dataType
self._length = None
self._default = None
self._notNull = False
self._unique = False
self._constraint = None
self._check = []
self._primaryKey = False
self._foreignKey = None
self._autoincrement = False
def __str__(self):
return self._name
@property
def name(self):
return self._name
@name.setter
def name(self, name):
self._name = name
@property
def data_type(self):
return self._dataType
@dataType.setter
def data_type(self, dataType):
self._dataType = dataType
@property
def length(self):
return self._length
@length.setter
def length(self, length):
self._length = length
@property
def not_null(self):
return self._notNull
@notNull.setter
def not_null(self, notNull):
self._notNull = notNull
@property
def primary_key(self):
return self._primaryKey
@primaryKey.setter
def primary_key(self, primaryKey):
self._primaryKey = primaryKey
@property
def number(self):
return self._number
@number.setter
def number(self, number):
self._number = number
@property
def foreign_key(self):
return self._foreignKey
@foreignKey.setter
def foreign_key(self, foreignKey):
self._foreignKey = foreignKey
@property
def unique(self):
return self._unique
@unique.setter
def unique(self, unique):
self._unique = unique
@property
def constraint(self):
return self._constraint
@constraint.setter
def constraint(self, constraint):
self._constraint = constraint
@property
def default(self):
return self._default
@default.setter
def default(self, default):
self._default = default
@property
def autoincrement(self):
return self._autoincrement
@autoincrement.setter
def autoincrement(self, autoincrement):
self._autoincrement = autoincrement
@property
def check(self):
return self._check
@check.setter
def check(self, check):
self._check = check |
# Definisikan class Karyawan
class Karyawan:
def __init__(self, nama, usia, pendapatan, insentif_lembur):
self.nama = nama
self.usia = usia
self.pendapatan = pendapatan
self.pendapatan_tambahan = 0
self.insentif_lembur = insentif_lembur
def lembur(self):
self.pendapatan_tambahan += self.insentif_lembur
def tambahan_proyek(self, jumlah_tambahan):
self.pendapatan_tambahan += jumlah_tambahan
def total_pendapatan(self):
return self.pendapatan + self.pendapatan_tambahan
# Definisikan class Perusahaan
class Perusahaan:
def __init__(self, nama, alamat, nomor_telepon):
self.nama = nama
self.alamat = alamat
self.nomor_telepon = nomor_telepon
self.list_karyawan = []
def aktifkan_karyawan(self, karyawan):
self.list_karyawan.append(karyawan)
def nonaktifkan_karyawan(self, nama_karyawan):
karyawan_nonaktif = None
for karyawan in self.list_karyawan:
if karyawan.nama == nama_karyawan:
karyawan_nonaktif = karyawan
break
if karyawan_nonaktif is not None:
self.list_karyawan.remove(karyawan_nonaktif) | class Karyawan:
def __init__(self, nama, usia, pendapatan, insentif_lembur):
self.nama = nama
self.usia = usia
self.pendapatan = pendapatan
self.pendapatan_tambahan = 0
self.insentif_lembur = insentif_lembur
def lembur(self):
self.pendapatan_tambahan += self.insentif_lembur
def tambahan_proyek(self, jumlah_tambahan):
self.pendapatan_tambahan += jumlah_tambahan
def total_pendapatan(self):
return self.pendapatan + self.pendapatan_tambahan
class Perusahaan:
def __init__(self, nama, alamat, nomor_telepon):
self.nama = nama
self.alamat = alamat
self.nomor_telepon = nomor_telepon
self.list_karyawan = []
def aktifkan_karyawan(self, karyawan):
self.list_karyawan.append(karyawan)
def nonaktifkan_karyawan(self, nama_karyawan):
karyawan_nonaktif = None
for karyawan in self.list_karyawan:
if karyawan.nama == nama_karyawan:
karyawan_nonaktif = karyawan
break
if karyawan_nonaktif is not None:
self.list_karyawan.remove(karyawan_nonaktif) |
def permutations(arr):
arr1 = arr.copy()
print(" ".join(arr1), end=" ")
count = len(arr1)
for x in range(len(arr)):
tmp = []
for i in arr:
for k in arr1:
if i not in k:
tmp.append(k + i)
count += 1
print(" ".join(tmp), end=" ")
arr1 = tmp
arr = input().split()
permutations(arr)
| def permutations(arr):
arr1 = arr.copy()
print(' '.join(arr1), end=' ')
count = len(arr1)
for x in range(len(arr)):
tmp = []
for i in arr:
for k in arr1:
if i not in k:
tmp.append(k + i)
count += 1
print(' '.join(tmp), end=' ')
arr1 = tmp
arr = input().split()
permutations(arr) |
class AvailableCashError(Exception):
def __init__(self, available_amount, requested_amount):
error_message = (
'There is not enough available cash in the account. ' +
'Amount available is {available_amount}, amount requested is {requested_amount}. ' +
'\nPlease add funds or reduce the requested amount.'
).format(available_amount=available_amount, requested_amount=requested_amount)
super().__init__(error_message)
class InvalidAmountError(Exception):
def __init__(self, amount, denomination):
error_message = (
'The amount of {amount} is not in the denomination of {denomination}.'
).format(amount=amount, denomination=denomination)
super().__init__(error_message)
class UnevenDivisionError(Exception):
def __init__(self, numerator, denominator):
error_message = (
'The provided amount of {numerator} is not evenly divisable by {denominator}'
).format(numerator=numerator, denominator=denominator)
super().__init__(error_message)
class AvailableLoansError(Exception):
def __init__(self):
error_message = ('There are no notes available that match the provided criteria. ' +
' Either specify an alternative filter, or wait until additional ' +
' notes have been listed on the market.')
super().__init__(error_message)
| class Availablecasherror(Exception):
def __init__(self, available_amount, requested_amount):
error_message = ('There is not enough available cash in the account. ' + 'Amount available is {available_amount}, amount requested is {requested_amount}. ' + '\nPlease add funds or reduce the requested amount.').format(available_amount=available_amount, requested_amount=requested_amount)
super().__init__(error_message)
class Invalidamounterror(Exception):
def __init__(self, amount, denomination):
error_message = 'The amount of {amount} is not in the denomination of {denomination}.'.format(amount=amount, denomination=denomination)
super().__init__(error_message)
class Unevendivisionerror(Exception):
def __init__(self, numerator, denominator):
error_message = 'The provided amount of {numerator} is not evenly divisable by {denominator}'.format(numerator=numerator, denominator=denominator)
super().__init__(error_message)
class Availableloanserror(Exception):
def __init__(self):
error_message = 'There are no notes available that match the provided criteria. ' + ' Either specify an alternative filter, or wait until additional ' + ' notes have been listed on the market.'
super().__init__(error_message) |
# --------------
##File path for the file
file_path
#Code starts here
def read_file(path):
f=open(path,'r')
sentence=f.readline()
f.close()
return sentence
sample_message=read_file(file_path)
print(sample_message)
# --------------
#Code starts here
file_path_1
file_path_2
def fuse_msg(message_a,message_b):
a=int(message_a)
b=int(message_b)
quotient=b // a
return str(quotient)
message_1=read_file(file_path_1)
message_2=read_file(file_path_2)
print(message_1)
print(message_2)
secret_msg_1=fuse_msg(message_1,message_2)
print(secret_msg_1)
# --------------
#Code starts here
file_path_3
def substitute_msg(message_c):
if message_c == 'Red':
sub='Army General'
elif message_c == 'Green':
sub='Data Scientist'
else:
sub='Marine Biologist'
return sub
message_3 = read_file(file_path_3)
print(message_3)
secret_msg_2=substitute_msg(message_3)
print(secret_msg_2)
# --------------
# File path for message 4 and message 5
file_path_4
file_path_5
#Code starts here
def compare_msg(message_d,message_e):
a_list = message_d.split()
b_list = message_e.split()
c_list = [x for x in a_list if x not in b_list]
final_msg = " ".join(c_list)
return final_msg
message_4=read_file(file_path_4)
message_5=read_file(file_path_5)
print(message_4)
print(message_5)
secret_msg_3=compare_msg(message_4,message_5)
print(secret_msg_3)
# --------------
#Code starts here
file_path_6
def extract_msg(message_f):
a_list = message_f.split()
even_word = lambda x: len(x) % 2 == 0
b_list = filter(even_word,a_list)
final_msg = " ".join(b_list)
return final_msg
message_6 = read_file(file_path_6)
print(message_6)
secret_msg_4 = extract_msg(message_6)
print(secret_msg_4)
# --------------
#Secret message parts in the correct order
message_parts=[secret_msg_3, secret_msg_1, secret_msg_4, secret_msg_2]
final_path= user_data_dir + '/secret_message.txt'
#Code starts here
def write_file(secret_msg,path):
fopen = open(path,'a+')
fopen.write(secret_msg)
fopen.close()
secret_msg = " ".join(message_parts)
print(secret_msg)
write_file(secret_msg,final_path)
| file_path
def read_file(path):
f = open(path, 'r')
sentence = f.readline()
f.close()
return sentence
sample_message = read_file(file_path)
print(sample_message)
file_path_1
file_path_2
def fuse_msg(message_a, message_b):
a = int(message_a)
b = int(message_b)
quotient = b // a
return str(quotient)
message_1 = read_file(file_path_1)
message_2 = read_file(file_path_2)
print(message_1)
print(message_2)
secret_msg_1 = fuse_msg(message_1, message_2)
print(secret_msg_1)
file_path_3
def substitute_msg(message_c):
if message_c == 'Red':
sub = 'Army General'
elif message_c == 'Green':
sub = 'Data Scientist'
else:
sub = 'Marine Biologist'
return sub
message_3 = read_file(file_path_3)
print(message_3)
secret_msg_2 = substitute_msg(message_3)
print(secret_msg_2)
file_path_4
file_path_5
def compare_msg(message_d, message_e):
a_list = message_d.split()
b_list = message_e.split()
c_list = [x for x in a_list if x not in b_list]
final_msg = ' '.join(c_list)
return final_msg
message_4 = read_file(file_path_4)
message_5 = read_file(file_path_5)
print(message_4)
print(message_5)
secret_msg_3 = compare_msg(message_4, message_5)
print(secret_msg_3)
file_path_6
def extract_msg(message_f):
a_list = message_f.split()
even_word = lambda x: len(x) % 2 == 0
b_list = filter(even_word, a_list)
final_msg = ' '.join(b_list)
return final_msg
message_6 = read_file(file_path_6)
print(message_6)
secret_msg_4 = extract_msg(message_6)
print(secret_msg_4)
message_parts = [secret_msg_3, secret_msg_1, secret_msg_4, secret_msg_2]
final_path = user_data_dir + '/secret_message.txt'
def write_file(secret_msg, path):
fopen = open(path, 'a+')
fopen.write(secret_msg)
fopen.close()
secret_msg = ' '.join(message_parts)
print(secret_msg)
write_file(secret_msg, final_path) |
#
# Copyright SAS Institute
#
# Licensed under the Apache License, Version 2.0 (the License);
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
class SASConfigNotFoundError(Exception):
def __init__(self, path: str):
self.path = path
def __str__(self):
return 'Configuration path {} does not exist.'.format(self.path)
class SASConfigNotValidError(Exception):
def __init__(self, defn: str, msg: str=None):
self.defn = defn if defn else 'N/A'
self.msg = msg
def __str__(self):
return 'Configuration definition {} is not valid. {}'.format(self.defn, self.msg)
class SASIONotSupportedError(Exception):
def __init__(self, method: str, alts: list=None):
self.method = method
self.alts = alts
def __str__(self):
if self.alts is not None:
alt_text = 'Try the following: {}'.format(', '.join(self.alts))
else:
alt_text = ''
return 'Cannot use {} I/O module on Windows. {}'.format(self.method, alt_text)
class SASHTTPauthenticateError(Exception):
def __init__(self, msg: str):
self.msg = msg
def __str__(self):
return 'Failure in GET AuthToken.\n {}'.format(self.msg)
class SASHTTPconnectionError(Exception):
def __init__(self, msg: str):
self.msg = msg
def __str__(self):
return 'Failure in GET Connection.\n {}'.format(self.msg)
class SASHTTPsubmissionError(Exception):
def __init__(self, msg: str):
self.msg = msg
def __str__(self):
return 'Failure in submit().\n {}'.format(self.msg)
| class Sasconfignotfounderror(Exception):
def __init__(self, path: str):
self.path = path
def __str__(self):
return 'Configuration path {} does not exist.'.format(self.path)
class Sasconfignotvaliderror(Exception):
def __init__(self, defn: str, msg: str=None):
self.defn = defn if defn else 'N/A'
self.msg = msg
def __str__(self):
return 'Configuration definition {} is not valid. {}'.format(self.defn, self.msg)
class Sasionotsupportederror(Exception):
def __init__(self, method: str, alts: list=None):
self.method = method
self.alts = alts
def __str__(self):
if self.alts is not None:
alt_text = 'Try the following: {}'.format(', '.join(self.alts))
else:
alt_text = ''
return 'Cannot use {} I/O module on Windows. {}'.format(self.method, alt_text)
class Sashttpauthenticateerror(Exception):
def __init__(self, msg: str):
self.msg = msg
def __str__(self):
return 'Failure in GET AuthToken.\n {}'.format(self.msg)
class Sashttpconnectionerror(Exception):
def __init__(self, msg: str):
self.msg = msg
def __str__(self):
return 'Failure in GET Connection.\n {}'.format(self.msg)
class Sashttpsubmissionerror(Exception):
def __init__(self, msg: str):
self.msg = msg
def __str__(self):
return 'Failure in submit().\n {}'.format(self.msg) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
## Onera M6 configuration module for geoGen
#
# Adrien Crovato
def getParams():
p = {}
# Wing parameters (nP planforms for half-wing)
p['airfPath'] = '../airfoils' # path pointing the airfoils directory (relative to this config file)
p['airfName'] = ['oneraM6.dat', 'oneraM6.dat'] # names of file containing airfoil (Selig formatted) data (size: nP+1)
p['span'] = [1.196] # span of each planform (size: nP)
p['taper'] = [0.562] # taper of each planform (size: nP)
p['sweep'] = [30] # leading edge sweep of each planform (size: nP)
p['dihedral'] = [0] # dihedral angle of each planform (size: nP)
p['twist'] = [0, 0] # twist angle of each airfoil (size: nP+1)
p['rootChord'] = 0.8059 # root chord
p['offset'] = [0., 0.] # x and z offset at the leading edge root
p['coWingtip'] = True # cut-off wingtip (not supported yet)
# Sphere
p['domType'] = 'sphere' # domain type ('sphere' or 'box')
p['rSphere'] = 50*p['rootChord']
return p
| def get_params():
p = {}
p['airfPath'] = '../airfoils'
p['airfName'] = ['oneraM6.dat', 'oneraM6.dat']
p['span'] = [1.196]
p['taper'] = [0.562]
p['sweep'] = [30]
p['dihedral'] = [0]
p['twist'] = [0, 0]
p['rootChord'] = 0.8059
p['offset'] = [0.0, 0.0]
p['coWingtip'] = True
p['domType'] = 'sphere'
p['rSphere'] = 50 * p['rootChord']
return p |
# A function is a block of organized, reusable code that is used to perform a single, related action.
# Define a function.
def fun():
print("What's a Funtion ?")
# Functions with Arguments.
def funArg(arg1,arg2):
print(arg1," ",arg2)
# return(arg1," ",arg2)
#Functions that returns a value
def funX(a):
return a+a
# Calling the Function.
fun()
funArg(50,50)
print(funArg(50,50))
print(funX(50))
| def fun():
print("What's a Funtion ?")
def fun_arg(arg1, arg2):
print(arg1, ' ', arg2)
def fun_x(a):
return a + a
fun()
fun_arg(50, 50)
print(fun_arg(50, 50))
print(fun_x(50)) |
# Frames Per Second
FPS = 60
# SCREEN
SCREEN_COLUMNS_NUMBER = 6
SCREEN_ROWS_NUMBER = 7
SCREEN_COLUMN_SIZE = 96
SCREEN_ROW_SIZE = 96
SCREEN_WIDTH = SCREEN_COLUMNS_NUMBER * SCREEN_COLUMN_SIZE
SCREEN_HEIGHT = SCREEN_ROWS_NUMBER * SCREEN_ROW_SIZE
# Colors for display.
COLOR_WHITE = (255, 255, 255)
COLOR_BLACK = (0, 0, 0)
COLOR_GREEN = (0, 128, 0)
COLOR_BLUE = (0, 0, 128)
COLOR_RED = (255, 0, 0)
COLOR_GRAY = (224, 224, 224)
COLOR_BROWN = (160, 82, 45)
PLAYER_INDEX = 21
BOTS_MAX_4ROWS = 5
BOTS_MAX_ALL_ROAD = 10
COUNT_LOCK = 10
| fps = 60
screen_columns_number = 6
screen_rows_number = 7
screen_column_size = 96
screen_row_size = 96
screen_width = SCREEN_COLUMNS_NUMBER * SCREEN_COLUMN_SIZE
screen_height = SCREEN_ROWS_NUMBER * SCREEN_ROW_SIZE
color_white = (255, 255, 255)
color_black = (0, 0, 0)
color_green = (0, 128, 0)
color_blue = (0, 0, 128)
color_red = (255, 0, 0)
color_gray = (224, 224, 224)
color_brown = (160, 82, 45)
player_index = 21
bots_max_4_rows = 5
bots_max_all_road = 10
count_lock = 10 |
class Linked_List():
def __init__(self, head):
self.head = head
class Node():
def __init__(self, data):
self.data = data
self.next = None
# O(N) space and O(N) time
def partition_linked_list(linked_list, partition):
less_than = []
greater_than_or_equal = []
next_one = linked_list.head
while next_one is not None:
if next_one.data < partition:
less_than.append(next_one.data)
else:
greater_than_or_equal.append(next_one.data)
next_one = next_one.next
next_one = linked_list.head
while next_one is not None:
if len(less_than) > 0:
next_one.data = less_than.pop()
else:
next_one.data = greater_than_or_equal.pop()
next_one = next_one.next
return linked_list | class Linked_List:
def __init__(self, head):
self.head = head
class Node:
def __init__(self, data):
self.data = data
self.next = None
def partition_linked_list(linked_list, partition):
less_than = []
greater_than_or_equal = []
next_one = linked_list.head
while next_one is not None:
if next_one.data < partition:
less_than.append(next_one.data)
else:
greater_than_or_equal.append(next_one.data)
next_one = next_one.next
next_one = linked_list.head
while next_one is not None:
if len(less_than) > 0:
next_one.data = less_than.pop()
else:
next_one.data = greater_than_or_equal.pop()
next_one = next_one.next
return linked_list |
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# External libraries
# Markdown
'markdownx',
# Bootstrap
'bootstrap4',
# Our apps
'apps.blocks',
'apps.bot',
'apps.custom_admin',
'apps.lp',
'apps.results',
'apps.services',
'apps.tags',
'apps.quiz',
'apps.lms',
'apps.social',
'apps.users',
'apps.course',
'apps.lesson',
]
| installed_apps = ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'markdownx', 'bootstrap4', 'apps.blocks', 'apps.bot', 'apps.custom_admin', 'apps.lp', 'apps.results', 'apps.services', 'apps.tags', 'apps.quiz', 'apps.lms', 'apps.social', 'apps.users', 'apps.course', 'apps.lesson'] |
class Sorting:
@staticmethod
def insertion_sort(arr):
for i in range(1, len(arr)):
curr = arr[i]
j = i - 1
while j >= 0 and curr < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = curr
return arr
if __name__ == "__main__":
obj = Sorting()
print(obj.insertion_sort([3, 2, 5, 7, 6]))
| class Sorting:
@staticmethod
def insertion_sort(arr):
for i in range(1, len(arr)):
curr = arr[i]
j = i - 1
while j >= 0 and curr < arr[j]:
arr[j + 1] = arr[j]
j -= 1
arr[j + 1] = curr
return arr
if __name__ == '__main__':
obj = sorting()
print(obj.insertion_sort([3, 2, 5, 7, 6])) |
HERO = {'B': 'Batman', 'J': 'Joker', 'R': 'Robin'}
OUTPUT = '{}: {}'.format
class BatmanQuotes(object):
@staticmethod
def get_quote(quotes, hero):
for i, a in enumerate(hero):
if i == 0:
hero = HERO[a]
elif a.isdigit():
quotes = quotes[int(a)]
break
return OUTPUT(hero, quotes)
| hero = {'B': 'Batman', 'J': 'Joker', 'R': 'Robin'}
output = '{}: {}'.format
class Batmanquotes(object):
@staticmethod
def get_quote(quotes, hero):
for (i, a) in enumerate(hero):
if i == 0:
hero = HERO[a]
elif a.isdigit():
quotes = quotes[int(a)]
break
return output(hero, quotes) |
numBlanks = 0
golden = ["Emptiness", "fear", "mountain"]
newLines = []
with open('fill-blanks.txt', 'r') as f:
for line in f:
if '...' in line:
blank = input("Fill the blank in " + line)
if blank == golden[numBlanks]:
newLine = line.replace("...", blank)
else:
newLine = line
numBlanks += 1
else:
newLine = line
newLines.append(newLine)
print(newLines)
| num_blanks = 0
golden = ['Emptiness', 'fear', 'mountain']
new_lines = []
with open('fill-blanks.txt', 'r') as f:
for line in f:
if '...' in line:
blank = input('Fill the blank in ' + line)
if blank == golden[numBlanks]:
new_line = line.replace('...', blank)
else:
new_line = line
num_blanks += 1
else:
new_line = line
newLines.append(newLine)
print(newLines) |
array = [116, 176382, 94, 325, 3476, 4, 2542, 9, 21, 56, 322, 322]
print(array)
SENTINEL = 10**12
def merge(array, left, mid, right):
L = array[left:mid]
R = array[mid:right]
L.append(SENTINEL)
R.append(SENTINEL)
i = j = 0
for k in range(left, right):
if L[i] <= R[j]:
array[k] = L[i]
i += 1
else:
array[k] = R[j]
j += 1
def mergeSort(array, left, right):
if (left + 1 < right):
mid = (left + right) // 2
mergeSort(array, left, mid)
mergeSort(array, mid, right)
merge(array, left, mid, right)
mergeSort(array, 0, len(array))
print(array)
| array = [116, 176382, 94, 325, 3476, 4, 2542, 9, 21, 56, 322, 322]
print(array)
sentinel = 10 ** 12
def merge(array, left, mid, right):
l = array[left:mid]
r = array[mid:right]
L.append(SENTINEL)
R.append(SENTINEL)
i = j = 0
for k in range(left, right):
if L[i] <= R[j]:
array[k] = L[i]
i += 1
else:
array[k] = R[j]
j += 1
def merge_sort(array, left, right):
if left + 1 < right:
mid = (left + right) // 2
merge_sort(array, left, mid)
merge_sort(array, mid, right)
merge(array, left, mid, right)
merge_sort(array, 0, len(array))
print(array) |
ACTIONS = ["Attribution", "CommericalUse", "DerivativeWorks", "Distribution", "Notice", "Reproduction", "ShareAlike", "Sharing", "SourceCode", "acceptTracking", "adHocShare", "aggregate", "annotate", "anonymize", "append", "appendTo", "archive", "attachPolicy", "attachSource", "attribute", "commercialize", "compensate", "concurrentUse", "copy", "delete", "derive", "digitize", "display", "distribute", "ensureExclusivity", "execute", "export", "extract", "extractChar", "extractPage", "extractWord", "give", "grantUse", "include", "index", "inform", "install", "lease", "lend", "license", "modify", "move", "nextPolicy", "obtainConsent", "pay", "play", "present", "preview", "print", "read", "reproduce", "reviewPolicy", "secondaryUse", "sell", "share", "stream", "synchronize", "textToSpeech", "transfer", "transform", "translate", "uninstall", "use", "watermark", "write", "writeTo"]
ATTRIBUTION = "Attribution"
COMMERCIALUSE = "CommericalUse"
DERIVATIVE_WORKS = "DerivativeWorks"
DISTRIBUTION = "Distribution"
NOTICE = "Notice"
REPRODUCTION = "Reproduction"
SHARE_ALIKE = "ShareAlike"
SHARING = "Sharing"
SOURCECODE = "SourceCode"
ACCEPTTRACKING = "acceptTracking"
AGGREGATE = "aggregate"
ANNOTATE = "annotate"
ANONYMIZE = "anonymize"
ARCHIVE = "archive"
ATTRIBUTE = "attribute"
COMPENSATE = "compensate"
CONCURRENTUSE = "concurrentUse"
DELETE = "delete"
DERIVE = "derive"
DIGITIZE = "digitize"
DISPLAY = "display"
DISTRIBUTE = "distribute"
ENSUREEXCLUSIVITY = "ensureExclusivity"
EXECUTE = "execute"
EXTRACT = "extract"
GIVE = "give"
GRANTUSE = "grantUse"
INCLUDE = "include"
INDEX = "index"
INFORM = "inform"
INSTALL = "install"
MODIFY = "modify"
MOVE = "move"
NEXTPOLICY = "nextPolicy"
OBTAINCONSENT = "obtainConsent"
PLAY = "play"
PRESENT = "present"
PRINT = "print"
READ = "read"
REPRODUCE = "reproduce"
REVIEWPOLICY = "reviewPolicy"
SELL = "sell"
STREAM = "stream"
SYNCHRONIZE = "synchronize"
TEXTTOSPEECH = "textToSpeech"
TRANSFER = "transfer"
TRANSFORM = "transform"
TRANSLATE = "translate"
UNINSTALL = "uninstall"
WATERMARK = "watermark"
USE = "use"
ARBRE_DERIVE = {
DERIVE: {
PRINT: {},
PLAY: {
DISPLAY: {}
}
}
}
ARBRE = {
USE: {
REPRODUCE: {
REPRODUCTION: {
CONCURRENTUSE: {},
DIGITIZE: {}
}
},
MOVE: {
DELETE: {}
},
SHARING: {
DERIVE: {
PRINT: {},
PLAY: {
DISPLAY: {}
}
}
},
DERIVATIVE_WORKS: {
DERIVE: {
PRINT: {},
PLAY: {
DISPLAY: {}
}
},
SHARE_ALIKE: {}
},
DISTRIBUTION: {
DISTRIBUTE: {},
PRESENT: {},
STREAM: {},
TEXTTOSPEECH: {}
},
MODIFY: {
ANONYMIZE: {},
TRANSFORM: {}
},
COMMERCIALUSE: {},
NOTICE: {},
SOURCECODE: {},
ACCEPTTRACKING: {},
AGGREGATE: {},
ANNOTATE: {},
ARCHIVE: {},
ATTRIBUTE: {},
ATTRIBUTION: {},
COMPENSATE: {},
ENSUREEXCLUSIVITY: {},
EXECUTE: {},
EXTRACT: {},
GRANTUSE: {},
INCLUDE: {},
INDEX: {},
INFORM: {},
INSTALL: {},
NEXTPOLICY: {},
OBTAINCONSENT: {},
READ: {},
REVIEWPOLICY: {},
SYNCHRONIZE: {},
TRANSFORM: {},
TRANSLATE: {},
UNINSTALL: {},
WATERMARK: {},
TRANSFER: {
GIVE: {},
SELL: {}
}
}
}
| actions = ['Attribution', 'CommericalUse', 'DerivativeWorks', 'Distribution', 'Notice', 'Reproduction', 'ShareAlike', 'Sharing', 'SourceCode', 'acceptTracking', 'adHocShare', 'aggregate', 'annotate', 'anonymize', 'append', 'appendTo', 'archive', 'attachPolicy', 'attachSource', 'attribute', 'commercialize', 'compensate', 'concurrentUse', 'copy', 'delete', 'derive', 'digitize', 'display', 'distribute', 'ensureExclusivity', 'execute', 'export', 'extract', 'extractChar', 'extractPage', 'extractWord', 'give', 'grantUse', 'include', 'index', 'inform', 'install', 'lease', 'lend', 'license', 'modify', 'move', 'nextPolicy', 'obtainConsent', 'pay', 'play', 'present', 'preview', 'print', 'read', 'reproduce', 'reviewPolicy', 'secondaryUse', 'sell', 'share', 'stream', 'synchronize', 'textToSpeech', 'transfer', 'transform', 'translate', 'uninstall', 'use', 'watermark', 'write', 'writeTo']
attribution = 'Attribution'
commercialuse = 'CommericalUse'
derivative_works = 'DerivativeWorks'
distribution = 'Distribution'
notice = 'Notice'
reproduction = 'Reproduction'
share_alike = 'ShareAlike'
sharing = 'Sharing'
sourcecode = 'SourceCode'
accepttracking = 'acceptTracking'
aggregate = 'aggregate'
annotate = 'annotate'
anonymize = 'anonymize'
archive = 'archive'
attribute = 'attribute'
compensate = 'compensate'
concurrentuse = 'concurrentUse'
delete = 'delete'
derive = 'derive'
digitize = 'digitize'
display = 'display'
distribute = 'distribute'
ensureexclusivity = 'ensureExclusivity'
execute = 'execute'
extract = 'extract'
give = 'give'
grantuse = 'grantUse'
include = 'include'
index = 'index'
inform = 'inform'
install = 'install'
modify = 'modify'
move = 'move'
nextpolicy = 'nextPolicy'
obtainconsent = 'obtainConsent'
play = 'play'
present = 'present'
print = 'print'
read = 'read'
reproduce = 'reproduce'
reviewpolicy = 'reviewPolicy'
sell = 'sell'
stream = 'stream'
synchronize = 'synchronize'
texttospeech = 'textToSpeech'
transfer = 'transfer'
transform = 'transform'
translate = 'translate'
uninstall = 'uninstall'
watermark = 'watermark'
use = 'use'
arbre_derive = {DERIVE: {PRINT: {}, PLAY: {DISPLAY: {}}}}
arbre = {USE: {REPRODUCE: {REPRODUCTION: {CONCURRENTUSE: {}, DIGITIZE: {}}}, MOVE: {DELETE: {}}, SHARING: {DERIVE: {PRINT: {}, PLAY: {DISPLAY: {}}}}, DERIVATIVE_WORKS: {DERIVE: {PRINT: {}, PLAY: {DISPLAY: {}}}, SHARE_ALIKE: {}}, DISTRIBUTION: {DISTRIBUTE: {}, PRESENT: {}, STREAM: {}, TEXTTOSPEECH: {}}, MODIFY: {ANONYMIZE: {}, TRANSFORM: {}}, COMMERCIALUSE: {}, NOTICE: {}, SOURCECODE: {}, ACCEPTTRACKING: {}, AGGREGATE: {}, ANNOTATE: {}, ARCHIVE: {}, ATTRIBUTE: {}, ATTRIBUTION: {}, COMPENSATE: {}, ENSUREEXCLUSIVITY: {}, EXECUTE: {}, EXTRACT: {}, GRANTUSE: {}, INCLUDE: {}, INDEX: {}, INFORM: {}, INSTALL: {}, NEXTPOLICY: {}, OBTAINCONSENT: {}, READ: {}, REVIEWPOLICY: {}, SYNCHRONIZE: {}, TRANSFORM: {}, TRANSLATE: {}, UNINSTALL: {}, WATERMARK: {}, TRANSFER: {GIVE: {}, SELL: {}}}} |
_base_ = [
'../_base_/models/regnet/regnetx_400mf.py',
'../_base_/datasets/imagenet_bs32.py',
'../_base_/schedules/imagenet_bs1024_coslr.py',
'../_base_/default_runtime.py'
]
# Precise BN hook will update the bn stats, so this hook should be executed
# before CheckpointHook, which has priority of 'NORMAL'. So set the
# priority of PreciseBNHook to 'ABOVE_NORMAL' here.
custom_hooks = [
dict(
type='PreciseBNHook',
num_samples=8192,
interval=1,
priority='ABOVE_NORMAL')
]
# sgd with nesterov, base ls is 0.8 for batch_size 1024,
# 0.4 for batch_size 512 and 0.2 for batch_size 256 when training ImageNet1k
optimizer = dict(lr=0.8, nesterov=True)
# dataset settings
dataset_type = 'ImageNet'
# normalization params, in order of BGR
NORM_MEAN = [103.53, 116.28, 123.675]
NORM_STD = [57.375, 57.12, 58.395]
# lighting params, in order of RGB, from repo. pycls
EIGVAL = [0.2175, 0.0188, 0.0045]
EIGVEC = [[-0.5675, 0.7192, 0.4009], [-0.5808, -0.0045, -0.814],
[-0.5836, -0.6948, 0.4203]]
train_pipeline = [
dict(type='LoadImageFromFile'),
dict(type='RandomResizedCrop', size=224),
dict(type='RandomFlip', flip_prob=0.5, direction='horizontal'),
dict(
type='Lighting',
eigval=EIGVAL,
eigvec=EIGVEC,
alphastd=25.5, # because the value range of images is [0,255]
to_rgb=True
), # BGR image from cv2 in LoadImageFromFile, convert to RGB here
dict(type='Normalize', mean=NORM_MEAN, std=NORM_STD,
to_rgb=True), # RGB2BGR
dict(type='ImageToTensor', keys=['img']),
dict(type='ToTensor', keys=['gt_label']),
dict(type='Collect', keys=['img', 'gt_label'])
]
test_pipeline = [
dict(type='LoadImageFromFile'),
dict(type='Resize', size=(256, -1)),
dict(type='CenterCrop', crop_size=224),
dict(type='Normalize', mean=NORM_MEAN, std=NORM_STD, to_rgb=False),
dict(type='ImageToTensor', keys=['img']),
dict(type='Collect', keys=['img'])
]
data = dict(
samples_per_gpu=128,
workers_per_gpu=8,
train=dict(
type=dataset_type,
data_prefix='data/imagenet/train',
pipeline=train_pipeline),
val=dict(
type=dataset_type,
data_prefix='data/imagenet/val',
ann_file='data/imagenet/meta/val.txt',
pipeline=test_pipeline),
test=dict(
# replace `data/val` with `data/test` for standard test
type=dataset_type,
data_prefix='data/imagenet/val',
ann_file='data/imagenet/meta/val.txt',
pipeline=test_pipeline))
| _base_ = ['../_base_/models/regnet/regnetx_400mf.py', '../_base_/datasets/imagenet_bs32.py', '../_base_/schedules/imagenet_bs1024_coslr.py', '../_base_/default_runtime.py']
custom_hooks = [dict(type='PreciseBNHook', num_samples=8192, interval=1, priority='ABOVE_NORMAL')]
optimizer = dict(lr=0.8, nesterov=True)
dataset_type = 'ImageNet'
norm_mean = [103.53, 116.28, 123.675]
norm_std = [57.375, 57.12, 58.395]
eigval = [0.2175, 0.0188, 0.0045]
eigvec = [[-0.5675, 0.7192, 0.4009], [-0.5808, -0.0045, -0.814], [-0.5836, -0.6948, 0.4203]]
train_pipeline = [dict(type='LoadImageFromFile'), dict(type='RandomResizedCrop', size=224), dict(type='RandomFlip', flip_prob=0.5, direction='horizontal'), dict(type='Lighting', eigval=EIGVAL, eigvec=EIGVEC, alphastd=25.5, to_rgb=True), dict(type='Normalize', mean=NORM_MEAN, std=NORM_STD, to_rgb=True), dict(type='ImageToTensor', keys=['img']), dict(type='ToTensor', keys=['gt_label']), dict(type='Collect', keys=['img', 'gt_label'])]
test_pipeline = [dict(type='LoadImageFromFile'), dict(type='Resize', size=(256, -1)), dict(type='CenterCrop', crop_size=224), dict(type='Normalize', mean=NORM_MEAN, std=NORM_STD, to_rgb=False), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img'])]
data = dict(samples_per_gpu=128, workers_per_gpu=8, train=dict(type=dataset_type, data_prefix='data/imagenet/train', pipeline=train_pipeline), val=dict(type=dataset_type, data_prefix='data/imagenet/val', ann_file='data/imagenet/meta/val.txt', pipeline=test_pipeline), test=dict(type=dataset_type, data_prefix='data/imagenet/val', ann_file='data/imagenet/meta/val.txt', pipeline=test_pipeline)) |
###########################################################################
#
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
###########################################################################
conversionStatus_Schema = [[{
'name': 'childDirectedTreatment',
'type': 'BOOLEAN',
'mode': 'NULLABLE'
}, {
'name':
'customVariables',
'type':
'RECORD',
'mode':
'REPEATED',
'fields': [{
'description': '',
'name': 'kind',
'type': 'STRING',
'mode': 'NULLABLE'
}, {
'description':
'U1, U10, U100, U11, U12, U13, U14, U15, U16, U17, U18, U19, U2, '
'U20, U21, U22, U23, U24, U25, U26, U27, U28, U29, U3, U30, U31, '
'U32, U33, U34, U35, U36, U37, U38, U39, U4, U40, U41, U42, U43, '
'U44, U45, U46, U47, U48, U49, U5, U50, U51, U52, U53, U54, U55, '
'U56, U57, U58, U59, U6, U60, U61, U62, U63, U64, U65, U66, U67, '
'U68, U69, U7, U70, U71, U72, U73, U74, U75, U76, U77, U78, U79, '
'U8, U80, U81, U82, U83, U84, U85, U86, U87, U88, U89, U9, U90, '
'U91, U92, U93, U94, U95, U96, U97, U98, U99',
'name':
'type',
'type':
'STRING',
'mode':
'NULLABLE'
}, {
'description': '',
'name': 'value',
'type': 'STRING',
'mode': 'NULLABLE'
}]
}, {
'description': '',
'name': 'encryptedUserId',
'type': 'STRING',
'mode': 'NULLABLE'
}, {
'name': 'encryptedUserIdCandidates',
'type': 'STRING',
'mode': 'REPEATED'
}, {
'description': '',
'name': 'floodlightActivityId',
'type': 'INT64',
'mode': 'NULLABLE'
}, {
'description': '',
'name': 'floodlightConfigurationId',
'type': 'INT64',
'mode': 'NULLABLE'
}, {
'description': '',
'name': 'gclid',
'type': 'STRING',
'mode': 'NULLABLE'
}, {
'description': '',
'name': 'kind',
'type': 'STRING',
'mode': 'NULLABLE'
}, {
'name': 'limitAdTracking',
'type': 'BOOLEAN',
'mode': 'NULLABLE'
}, {
'description': '',
'name': 'mobileDeviceId',
'type': 'STRING',
'mode': 'NULLABLE'
}, {
'name': 'nonPersonalizedAd',
'type': 'BOOLEAN',
'mode': 'NULLABLE'
}, {
'description': '',
'name': 'ordinal',
'type': 'STRING',
'mode': 'NULLABLE'
}, {
'description': '',
'name': 'quantity',
'type': 'INT64',
'mode': 'NULLABLE'
}, {
'description': '',
'name': 'timestampMicros',
'type': 'INT64',
'mode': 'NULLABLE'
}, {
'name': 'treatmentForUnderage',
'type': 'BOOLEAN',
'mode': 'NULLABLE'
}, {
'description': '',
'name': 'value',
'type': 'FLOAT64',
'mode': 'NULLABLE'
}], {
'name':
'errors',
'type':
'RECORD',
'mode':
'REPEATED',
'fields': [{
'description':
'INTERNAL, INVALID_ARGUMENT, NOT_FOUND, PERMISSION_DENIED',
'name':
'code',
'type':
'STRING',
'mode':
'NULLABLE'
}, {
'description': '',
'name': 'kind',
'type': 'STRING',
'mode': 'NULLABLE'
}, {
'description': '',
'name': 'message',
'type': 'STRING',
'mode': 'NULLABLE'
}]
}, {
'description': '',
'name': 'kind',
'type': 'STRING',
'mode': 'NULLABLE'
}]
| conversion_status__schema = [[{'name': 'childDirectedTreatment', 'type': 'BOOLEAN', 'mode': 'NULLABLE'}, {'name': 'customVariables', 'type': 'RECORD', 'mode': 'REPEATED', 'fields': [{'description': '', 'name': 'kind', 'type': 'STRING', 'mode': 'NULLABLE'}, {'description': 'U1, U10, U100, U11, U12, U13, U14, U15, U16, U17, U18, U19, U2, U20, U21, U22, U23, U24, U25, U26, U27, U28, U29, U3, U30, U31, U32, U33, U34, U35, U36, U37, U38, U39, U4, U40, U41, U42, U43, U44, U45, U46, U47, U48, U49, U5, U50, U51, U52, U53, U54, U55, U56, U57, U58, U59, U6, U60, U61, U62, U63, U64, U65, U66, U67, U68, U69, U7, U70, U71, U72, U73, U74, U75, U76, U77, U78, U79, U8, U80, U81, U82, U83, U84, U85, U86, U87, U88, U89, U9, U90, U91, U92, U93, U94, U95, U96, U97, U98, U99', 'name': 'type', 'type': 'STRING', 'mode': 'NULLABLE'}, {'description': '', 'name': 'value', 'type': 'STRING', 'mode': 'NULLABLE'}]}, {'description': '', 'name': 'encryptedUserId', 'type': 'STRING', 'mode': 'NULLABLE'}, {'name': 'encryptedUserIdCandidates', 'type': 'STRING', 'mode': 'REPEATED'}, {'description': '', 'name': 'floodlightActivityId', 'type': 'INT64', 'mode': 'NULLABLE'}, {'description': '', 'name': 'floodlightConfigurationId', 'type': 'INT64', 'mode': 'NULLABLE'}, {'description': '', 'name': 'gclid', 'type': 'STRING', 'mode': 'NULLABLE'}, {'description': '', 'name': 'kind', 'type': 'STRING', 'mode': 'NULLABLE'}, {'name': 'limitAdTracking', 'type': 'BOOLEAN', 'mode': 'NULLABLE'}, {'description': '', 'name': 'mobileDeviceId', 'type': 'STRING', 'mode': 'NULLABLE'}, {'name': 'nonPersonalizedAd', 'type': 'BOOLEAN', 'mode': 'NULLABLE'}, {'description': '', 'name': 'ordinal', 'type': 'STRING', 'mode': 'NULLABLE'}, {'description': '', 'name': 'quantity', 'type': 'INT64', 'mode': 'NULLABLE'}, {'description': '', 'name': 'timestampMicros', 'type': 'INT64', 'mode': 'NULLABLE'}, {'name': 'treatmentForUnderage', 'type': 'BOOLEAN', 'mode': 'NULLABLE'}, {'description': '', 'name': 'value', 'type': 'FLOAT64', 'mode': 'NULLABLE'}], {'name': 'errors', 'type': 'RECORD', 'mode': 'REPEATED', 'fields': [{'description': 'INTERNAL, INVALID_ARGUMENT, NOT_FOUND, PERMISSION_DENIED', 'name': 'code', 'type': 'STRING', 'mode': 'NULLABLE'}, {'description': '', 'name': 'kind', 'type': 'STRING', 'mode': 'NULLABLE'}, {'description': '', 'name': 'message', 'type': 'STRING', 'mode': 'NULLABLE'}]}, {'description': '', 'name': 'kind', 'type': 'STRING', 'mode': 'NULLABLE'}] |
with open("input") as file:
lines = [line.split(" ") for line in file.read().strip().split("\n")]
register_names = set([line[0] for line in lines])
registers = {}
for name in register_names:
registers[name] = 0
operations = {
"dec": lambda r,v: r-v,
"inc": lambda r,v: r+v }
comparisons = {
">": lambda a,b: a > b,
">=": lambda a,b: a >= b,
"<": lambda a,b: a < b,
"<=": lambda a,b: a <= b,
"==": lambda a,b: a == b,
"!=": lambda a,b: a != b }
for line in lines:
if comparisons[line[5]](registers[line[4]],int(line[6])):
registers[line[0]] = operations[line[1]](registers[line[0]],int(line[2]))
print(max(registers.values()))
| with open('input') as file:
lines = [line.split(' ') for line in file.read().strip().split('\n')]
register_names = set([line[0] for line in lines])
registers = {}
for name in register_names:
registers[name] = 0
operations = {'dec': lambda r, v: r - v, 'inc': lambda r, v: r + v}
comparisons = {'>': lambda a, b: a > b, '>=': lambda a, b: a >= b, '<': lambda a, b: a < b, '<=': lambda a, b: a <= b, '==': lambda a, b: a == b, '!=': lambda a, b: a != b}
for line in lines:
if comparisons[line[5]](registers[line[4]], int(line[6])):
registers[line[0]] = operations[line[1]](registers[line[0]], int(line[2]))
print(max(registers.values())) |
# Source: https://github.com/kenshohara/3D-ResNets-PyTorch/blob/master/mean.py
def get_mean(norm_value=255, dataset='activitynet'):
# Below values are in RGB order
assert dataset in ['activitynet', 'kinetics', 'ucf101']
if dataset == 'activitynet':
return [114.7748/norm_value, 107.7354/norm_value, 99.4750/norm_value]
elif dataset == 'kinetics':
# Kinetics (10 videos for each class)
return [110.63666788/norm_value, 103.16065604/norm_value, 96.29023126/norm_value]
elif dataset == 'ucf101':
return [101.00131/norm_value, 97.3644226/norm_value, 89.42114168/norm_value]
def get_std(norm_value=255):
# Kinetics (10 videos for each class)
return [38.7568578/norm_value, 37.88248729/norm_value, 40.02898126/norm_value] | def get_mean(norm_value=255, dataset='activitynet'):
assert dataset in ['activitynet', 'kinetics', 'ucf101']
if dataset == 'activitynet':
return [114.7748 / norm_value, 107.7354 / norm_value, 99.475 / norm_value]
elif dataset == 'kinetics':
return [110.63666788 / norm_value, 103.16065604 / norm_value, 96.29023126 / norm_value]
elif dataset == 'ucf101':
return [101.00131 / norm_value, 97.3644226 / norm_value, 89.42114168 / norm_value]
def get_std(norm_value=255):
return [38.7568578 / norm_value, 37.88248729 / norm_value, 40.02898126 / norm_value] |
# AUTOGENERATED BY NBDEV! DO NOT EDIT!
__all__ = ["index", "modules", "custom_doc_links", "git_url"]
index = {"say_hello": "00_core.ipynb",
"say_bye": "00_core.ipynb",
"optimize_bayes_param": "01_bayes_opt.ipynb",
"ReadTabBatchIdentity": "02_tab_ae.ipynb",
"TabularPandasIdentity": "02_tab_ae.ipynb",
"TabDataLoaderIdentity": "02_tab_ae.ipynb",
"RecreatedLoss": "02_tab_ae.ipynb",
"BatchSwapNoise": "02_tab_ae.ipynb",
"TabularAE": "02_tab_ae.ipynb",
"HyperparamsGenerator": "03_param_finetune.ipynb",
"XgboostParamGenerator": "03_param_finetune.ipynb",
"LgbmParamGenerator": "03_param_finetune.ipynb",
"CatParamGenerator": "03_param_finetune.ipynb",
"RFParamGenerator": "03_param_finetune.ipynb",
"ModelIterator": "04_model_zoo.ipynb"}
modules = ["core.py",
"bayes_opt.py",
"tab_ae.py",
"params.py",
"model_iterator.py"]
doc_url = "https://DavidykZhao.github.io/Yikai_helper_funcs/"
git_url = "https://github.com/DavidykZhao/Yikai_helper_funcs/tree/master/"
def custom_doc_links(name): return None
| __all__ = ['index', 'modules', 'custom_doc_links', 'git_url']
index = {'say_hello': '00_core.ipynb', 'say_bye': '00_core.ipynb', 'optimize_bayes_param': '01_bayes_opt.ipynb', 'ReadTabBatchIdentity': '02_tab_ae.ipynb', 'TabularPandasIdentity': '02_tab_ae.ipynb', 'TabDataLoaderIdentity': '02_tab_ae.ipynb', 'RecreatedLoss': '02_tab_ae.ipynb', 'BatchSwapNoise': '02_tab_ae.ipynb', 'TabularAE': '02_tab_ae.ipynb', 'HyperparamsGenerator': '03_param_finetune.ipynb', 'XgboostParamGenerator': '03_param_finetune.ipynb', 'LgbmParamGenerator': '03_param_finetune.ipynb', 'CatParamGenerator': '03_param_finetune.ipynb', 'RFParamGenerator': '03_param_finetune.ipynb', 'ModelIterator': '04_model_zoo.ipynb'}
modules = ['core.py', 'bayes_opt.py', 'tab_ae.py', 'params.py', 'model_iterator.py']
doc_url = 'https://DavidykZhao.github.io/Yikai_helper_funcs/'
git_url = 'https://github.com/DavidykZhao/Yikai_helper_funcs/tree/master/'
def custom_doc_links(name):
return None |
list_of_numbers_as_strings = input().split(", ")
for index in range(len(list_of_numbers_as_strings)):
number = int(list_of_numbers_as_strings[index])
if number == 0:
list_of_numbers_as_strings.remove(str(0))
list_of_numbers_as_strings.append(str(0))
print(list_of_numbers_as_strings)
| list_of_numbers_as_strings = input().split(', ')
for index in range(len(list_of_numbers_as_strings)):
number = int(list_of_numbers_as_strings[index])
if number == 0:
list_of_numbers_as_strings.remove(str(0))
list_of_numbers_as_strings.append(str(0))
print(list_of_numbers_as_strings) |
##Config file for lifetime_spyrelet.py in spyre/spyre/spyrelet/
# Device List
devices = {
'vna':[
'lantz.drivers.VNA_Keysight.E5071B',
['TCPIP0::A-E5071B-03400::inst0::INSTR'],
{}
],
'source':[
'lantz.drivers.mwsource.SynthNVPro',
['ASRL16::INSTR'],
{}
]
}
# Experiment List
spyrelets = {
'freqSweep_Keysight':[
'spyre.spyrelets.freqSweep_VNA_Keysight_spyrelet.Sweep',
{'vna': 'vna','source': 'source'},
{}
],
} | devices = {'vna': ['lantz.drivers.VNA_Keysight.E5071B', ['TCPIP0::A-E5071B-03400::inst0::INSTR'], {}], 'source': ['lantz.drivers.mwsource.SynthNVPro', ['ASRL16::INSTR'], {}]}
spyrelets = {'freqSweep_Keysight': ['spyre.spyrelets.freqSweep_VNA_Keysight_spyrelet.Sweep', {'vna': 'vna', 'source': 'source'}, {}]} |
height = int(input())
for i in range(1, height + 1):
for j in range(1,i+1):
if(i == height or j == 1 or i == j):
print(i,end=" ")
else:
print(end=" ")
print()
# Sample Input :- 5
# Output :-
# 1
# 2 2
# 3 3
# 4 4
# 5 5 5 5 5
| height = int(input())
for i in range(1, height + 1):
for j in range(1, i + 1):
if i == height or j == 1 or i == j:
print(i, end=' ')
else:
print(end=' ')
print() |
# -*- coding:utf-8-*-
name = ["gyj","dzj","why","zz","wwb","zke","ljx","syb","yxd"]
print(name)
name.reverse()
print(name)
print(len(name))
| name = ['gyj', 'dzj', 'why', 'zz', 'wwb', 'zke', 'ljx', 'syb', 'yxd']
print(name)
name.reverse()
print(name)
print(len(name)) |
def flatten(seq):
r = []
for x in seq:
if type(x) == list:
r += flatten(x)
else:
r.append(x)
return r
seq = [1,[2,3],4]
seq = [1,[2,[5,6],3],4]
print(seq, '-->', flatten(seq))
| def flatten(seq):
r = []
for x in seq:
if type(x) == list:
r += flatten(x)
else:
r.append(x)
return r
seq = [1, [2, 3], 4]
seq = [1, [2, [5, 6], 3], 4]
print(seq, '-->', flatten(seq)) |
# parsetab.py
# This file is automatically generated. Do not edit.
_tabversion = '3.10'
_lr_method = 'LALR'
_lr_signature = 'nonassocLESSMOREEQUALSTOMOREEQUALLESSEQUALNOTEQUALleftPLUSMINUSleftTIMESDIVIDEleftANDORrightUMINUSINT FLOAT PLUS MINUS TIMES DIVIDE EQUALS LPAREN RPAREN LCURLBRACKET RCURLBRACKET ID COMMENT STRING ASSIGN SEMICOLON COMMA POINT NOT EQUALSTO MORE LESS MOREEQUAL LESSEQUAL NOTEQUAL AND OR INCREMENT DECREMENT BREAK CASE CHAN CONST CONTINUE DEFAULT DEFER ELSE FALLTHROUGH FOR FUNC GO GOTO IF IMPORT INTERFACE MAP PACKAGE RANGE RETURN SELECT STRUCT SWITCH TYPE VAR MAIN FMT PRINT SCAN TRUE FALSEstatement : PACKAGE MAIN IMPORT STRING FUNC MAIN LPAREN RPAREN LCURLBRACKET list RCURLBRACKET\n | PACKAGE MAIN IMPORT STRING FUNC MAIN LPAREN RPAREN LCURLBRACKET RCURLBRACKETlist : inst\n | inst listassignment : ID ASSIGN expressionAR\n | ID ASSIGN expressionBo\n | ID EQUALS expressionAR\n | ID EQUALS expressionBo\n | ID INCREMENT\n | ID DECREMENTinst : FOR expressionBo LCURLBRACKET list RCURLBRACKET\n | FOR assignment SEMICOLON expressionBo SEMICOLON assignment LCURLBRACKET list RCURLBRACKETinst : assignment SEMICOLONinst : IF expressionBo LCURLBRACKET list RCURLBRACKET ELSE LCURLBRACKET list RCURLBRACKET\n | IF expressionBo LCURLBRACKET list RCURLBRACKETlistID : expressionAR\n | expressionBo\n | expressionBo COMMA listID\n | expressionAR COMMA listIDIDlist : ID\n | ID COMMA IDlistinst : FMT POINT PRINT LPAREN listID RPAREN SEMICOLON\n | FMT POINT SCAN LPAREN IDlist RPAREN SEMICOLON\n | FMT POINT PRINT LPAREN RPAREN SEMICOLON\n | FMT POINT SCAN LPAREN RPAREN SEMICOLONexpressionAR : expressionAR PLUS expressionAR\n | expressionAR MINUS expressionAR\n | expressionAR TIMES expressionAR\n | expressionAR DIVIDE expressionAR\n | IDexpressionAR : INTexpressionAR : MINUS expressionAR %prec UMINUSexpressionAR : FLOATexpressionAR : LPAREN expressionAR RPARENexpressionBo : expressionAR MORE expressionAR\n | expressionAR LESS expressionAR\n | expressionAR MOREEQUAL expressionAR\n | expressionAR LESSEQUAL expressionAR\n | expressionBo NOTEQUAL expressionBo\n | expressionAR NOTEQUAL expressionAR\n | expressionBo EQUALSTO expressionBo\n | expressionAR EQUALSTO expressionAR\n | expressionBo AND expressionBo\n | expressionBo OR expressionBoexpressionBo : NOT expressionBo %prec UMINUSexpressionBo : TRUE\n | FALSEexpressionBo : LPAREN expressionBo RPAREN'
_lr_action_items = {'PACKAGE':([0,],[2,]),'$end':([1,12,19,],[0,-2,-1,]),'MAIN':([2,6,],[3,7,]),'IMPORT':([3,],[4,]),'STRING':([4,],[5,]),'FUNC':([5,],[6,]),'LPAREN':([7,14,16,24,27,29,36,37,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,60,62,63,66,89,106,107,],[8,27,27,27,27,60,66,66,27,27,27,27,27,60,60,60,60,60,60,60,60,60,60,60,89,90,66,66,66,66,]),'RPAREN':([8,25,26,30,31,34,56,57,58,59,70,71,72,73,75,76,77,78,79,80,81,82,83,84,85,86,87,89,90,91,95,97,98,99,101,114,115,117,],[9,-46,-47,-31,-33,-30,-45,85,86,-32,-39,-41,-43,-44,-35,-36,-37,-38,-40,-42,-26,-27,-28,-29,-48,-34,86,96,100,86,104,-16,-17,108,-20,-19,-18,-21,]),'LCURLBRACKET':([9,21,25,26,30,31,33,34,38,39,56,59,64,65,67,68,70,71,72,73,75,76,77,78,79,80,81,82,83,84,85,86,102,103,],[10,40,-46,-47,-31,-33,61,-30,-9,-10,-45,-32,-5,-6,-7,-8,-39,-41,-43,-44,-35,-36,-37,-38,-40,-42,-26,-27,-28,-29,-48,-34,111,112,]),'RCURLBRACKET':([10,11,13,20,32,69,88,92,94,105,109,113,116,118,119,120,121,],[12,19,-3,-4,-13,92,94,-11,-15,-24,-25,-22,-23,120,121,-12,-14,]),'FOR':([10,13,32,40,61,92,94,105,109,111,112,113,116,120,121,],[14,14,-13,14,14,-11,-15,-24,-25,14,14,-22,-23,-12,-14,]),'IF':([10,13,32,40,61,92,94,105,109,111,112,113,116,120,121,],[16,16,-13,16,16,-11,-15,-24,-25,16,16,-22,-23,-12,-14,]),'FMT':([10,13,32,40,61,92,94,105,109,111,112,113,116,120,121,],[17,17,-13,17,17,-11,-15,-24,-25,17,17,-22,-23,-12,-14,]),'ID':([10,13,14,16,24,27,29,32,36,37,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,60,61,66,89,90,92,93,94,105,106,107,109,110,111,112,113,116,120,121,],[18,18,28,34,34,34,34,-13,34,34,18,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,34,18,34,34,101,-11,18,-15,-24,34,34,-25,101,18,18,-22,-23,-12,-14,]),'NOT':([14,16,24,27,36,37,41,42,43,44,45,66,89,106,107,],[24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,]),'TRUE':([14,16,24,27,36,37,41,42,43,44,45,66,89,106,107,],[25,25,25,25,25,25,25,25,25,25,25,25,25,25,25,]),'FALSE':([14,16,24,27,36,37,41,42,43,44,45,66,89,106,107,],[26,26,26,26,26,26,26,26,26,26,26,26,26,26,26,]),'INT':([14,16,24,27,29,36,37,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,60,66,89,106,107,],[30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,]),'MINUS':([14,16,23,24,27,28,29,30,31,34,36,37,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,58,59,60,64,66,67,75,76,77,78,79,80,81,82,83,84,86,87,89,91,97,106,107,],[29,29,53,29,29,-30,29,-31,-33,-30,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,29,53,-32,29,53,29,53,53,53,53,53,53,53,-26,-27,-28,-29,-34,53,29,53,53,29,29,]),'FLOAT':([14,16,24,27,29,36,37,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,60,66,89,106,107,],[31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,31,]),'SEMICOLON':([15,22,25,26,30,31,34,38,39,56,59,64,65,67,68,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,96,100,104,108,],[32,45,-46,-47,-31,-33,-30,-9,-10,-45,-32,-5,-6,-7,-8,-39,-41,-43,-44,93,-35,-36,-37,-38,-40,-42,-26,-27,-28,-29,-48,-34,105,109,113,116,]),'POINT':([17,],[35,]),'ASSIGN':([18,28,],[36,36,]),'EQUALS':([18,28,],[37,37,]),'INCREMENT':([18,28,],[38,38,]),'DECREMENT':([18,28,],[39,39,]),'NOTEQUAL':([21,23,25,26,28,30,31,33,34,56,57,58,59,64,65,67,68,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,91,97,98,],[41,50,-46,-47,-30,-31,-33,41,-30,-45,41,50,-32,50,41,50,41,None,None,-43,-44,41,-35,-36,-37,-38,-40,-42,-26,-27,-28,-29,-48,-34,50,50,41,]),'EQUALSTO':([21,23,25,26,28,30,31,33,34,56,57,58,59,64,65,67,68,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,91,97,98,],[42,51,-46,-47,-30,-31,-33,42,-30,-45,42,51,-32,51,42,51,42,None,None,-43,-44,42,-35,-36,-37,-38,-40,-42,-26,-27,-28,-29,-48,-34,51,51,42,]),'AND':([21,25,26,30,31,33,34,56,57,59,65,68,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,98,],[43,-46,-47,-31,-33,43,-30,-45,43,-32,43,43,43,43,-43,-44,43,-35,-36,-37,-38,-40,-42,-26,-27,-28,-29,-48,-34,43,]),'OR':([21,25,26,30,31,33,34,56,57,59,65,68,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,98,],[44,-46,-47,-31,-33,44,-30,-45,44,-32,44,44,44,44,-43,-44,44,-35,-36,-37,-38,-40,-42,-26,-27,-28,-29,-48,-34,44,]),'MORE':([23,28,30,31,34,58,59,64,67,81,82,83,84,86,91,97,],[46,-30,-31,-33,-30,46,-32,46,46,-26,-27,-28,-29,-34,46,46,]),'LESS':([23,28,30,31,34,58,59,64,67,81,82,83,84,86,91,97,],[47,-30,-31,-33,-30,47,-32,47,47,-26,-27,-28,-29,-34,47,47,]),'MOREEQUAL':([23,28,30,31,34,58,59,64,67,81,82,83,84,86,91,97,],[48,-30,-31,-33,-30,48,-32,48,48,-26,-27,-28,-29,-34,48,48,]),'LESSEQUAL':([23,28,30,31,34,58,59,64,67,81,82,83,84,86,91,97,],[49,-30,-31,-33,-30,49,-32,49,49,-26,-27,-28,-29,-34,49,49,]),'PLUS':([23,28,30,31,34,58,59,64,67,75,76,77,78,79,80,81,82,83,84,86,87,91,97,],[52,-30,-31,-33,-30,52,-32,52,52,52,52,52,52,52,52,-26,-27,-28,-29,-34,52,52,52,]),'TIMES':([23,28,30,31,34,58,59,64,67,75,76,77,78,79,80,81,82,83,84,86,87,91,97,],[54,-30,-31,-33,-30,54,-32,54,54,54,54,54,54,54,54,54,54,-28,-29,-34,54,54,54,]),'DIVIDE':([23,28,30,31,34,58,59,64,67,75,76,77,78,79,80,81,82,83,84,86,87,91,97,],[55,-30,-31,-33,-30,55,-32,55,55,55,55,55,55,55,55,55,55,-28,-29,-34,55,55,55,]),'COMMA':([25,26,30,31,34,56,59,70,71,72,73,75,76,77,78,79,80,81,82,83,84,85,86,97,98,101,],[-46,-47,-31,-33,-30,-45,-32,-39,-41,-43,-44,-35,-36,-37,-38,-40,-42,-26,-27,-28,-29,-48,-34,106,107,110,]),'PRINT':([35,],[62,]),'SCAN':([35,],[63,]),'ELSE':([94,],[103,]),}
_lr_action = {}
for _k, _v in _lr_action_items.items():
for _x,_y in zip(_v[0],_v[1]):
if not _x in _lr_action: _lr_action[_x] = {}
_lr_action[_x][_k] = _y
del _lr_action_items
_lr_goto_items = {'statement':([0,],[1,]),'list':([10,13,40,61,111,112,],[11,20,69,88,118,119,]),'inst':([10,13,40,61,111,112,],[13,13,13,13,13,13,]),'assignment':([10,13,14,40,61,93,111,112,],[15,15,22,15,15,102,15,15,]),'expressionBo':([14,16,24,27,36,37,41,42,43,44,45,66,89,106,107,],[21,33,56,57,65,68,70,71,72,73,74,57,98,98,98,]),'expressionAR':([14,16,24,27,29,36,37,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,60,66,89,106,107,],[23,23,23,58,59,64,67,23,23,23,23,23,75,76,77,78,79,80,81,82,83,84,87,91,97,97,97,]),'listID':([89,106,107,],[95,114,115,]),'IDlist':([90,110,],[99,117,]),}
_lr_goto = {}
for _k, _v in _lr_goto_items.items():
for _x, _y in zip(_v[0], _v[1]):
if not _x in _lr_goto: _lr_goto[_x] = {}
_lr_goto[_x][_k] = _y
del _lr_goto_items
_lr_productions = [
("S' -> statement","S'",1,None,None,None),
('statement -> PACKAGE MAIN IMPORT STRING FUNC MAIN LPAREN RPAREN LCURLBRACKET list RCURLBRACKET','statement',11,'p_statement_expr','plintax.py',17),
('statement -> PACKAGE MAIN IMPORT STRING FUNC MAIN LPAREN RPAREN LCURLBRACKET RCURLBRACKET','statement',10,'p_statement_expr','plintax.py',18),
('list -> inst','list',1,'p_list','plintax.py',26),
('list -> inst list','list',2,'p_list','plintax.py',27),
('assignment -> ID ASSIGN expressionAR','assignment',3,'p_assignment','plintax.py',34),
('assignment -> ID ASSIGN expressionBo','assignment',3,'p_assignment','plintax.py',35),
('assignment -> ID EQUALS expressionAR','assignment',3,'p_assignment','plintax.py',36),
('assignment -> ID EQUALS expressionBo','assignment',3,'p_assignment','plintax.py',37),
('assignment -> ID INCREMENT','assignment',2,'p_assignment','plintax.py',38),
('assignment -> ID DECREMENT','assignment',2,'p_assignment','plintax.py',39),
('inst -> FOR expressionBo LCURLBRACKET list RCURLBRACKET','inst',5,'p_inst_For','plintax.py',53),
('inst -> FOR assignment SEMICOLON expressionBo SEMICOLON assignment LCURLBRACKET list RCURLBRACKET','inst',9,'p_inst_For','plintax.py',54),
('inst -> assignment SEMICOLON','inst',2,'p_inst_assignment','plintax.py',62),
('inst -> IF expressionBo LCURLBRACKET list RCURLBRACKET ELSE LCURLBRACKET list RCURLBRACKET','inst',9,'p_inst_If','plintax.py',67),
('inst -> IF expressionBo LCURLBRACKET list RCURLBRACKET','inst',5,'p_inst_If','plintax.py',68),
('listID -> expressionAR','listID',1,'p_listID','plintax.py',75),
('listID -> expressionBo','listID',1,'p_listID','plintax.py',76),
('listID -> expressionBo COMMA listID','listID',3,'p_listID','plintax.py',77),
('listID -> expressionAR COMMA listID','listID',3,'p_listID','plintax.py',78),
('IDlist -> ID','IDlist',1,'p_IDlist','plintax.py',85),
('IDlist -> ID COMMA IDlist','IDlist',3,'p_IDlist','plintax.py',86),
('inst -> FMT POINT PRINT LPAREN listID RPAREN SEMICOLON','inst',7,'p_inst_func','plintax.py',102),
('inst -> FMT POINT SCAN LPAREN IDlist RPAREN SEMICOLON','inst',7,'p_inst_func','plintax.py',103),
('inst -> FMT POINT PRINT LPAREN RPAREN SEMICOLON','inst',6,'p_inst_func','plintax.py',104),
('inst -> FMT POINT SCAN LPAREN RPAREN SEMICOLON','inst',6,'p_inst_func','plintax.py',105),
('expressionAR -> expressionAR PLUS expressionAR','expressionAR',3,'p_expressionAR_binop','plintax.py',115),
('expressionAR -> expressionAR MINUS expressionAR','expressionAR',3,'p_expressionAR_binop','plintax.py',116),
('expressionAR -> expressionAR TIMES expressionAR','expressionAR',3,'p_expressionAR_binop','plintax.py',117),
('expressionAR -> expressionAR DIVIDE expressionAR','expressionAR',3,'p_expressionAR_binop','plintax.py',118),
('expressionAR -> ID','expressionAR',1,'p_expressionAR_binop','plintax.py',119),
('expressionAR -> INT','expressionAR',1,'p_expressionAR_int','plintax.py',134),
('expressionAR -> MINUS expressionAR','expressionAR',2,'p_expressionAR_inverse','plintax.py',139),
('expressionAR -> FLOAT','expressionAR',1,'p_expressionAR_float','plintax.py',144),
('expressionAR -> LPAREN expressionAR RPAREN','expressionAR',3,'p_expressionAR_group','plintax.py',149),
('expressionBo -> expressionAR MORE expressionAR','expressionBo',3,'p_expressionBo_binop','plintax.py',156),
('expressionBo -> expressionAR LESS expressionAR','expressionBo',3,'p_expressionBo_binop','plintax.py',157),
('expressionBo -> expressionAR MOREEQUAL expressionAR','expressionBo',3,'p_expressionBo_binop','plintax.py',158),
('expressionBo -> expressionAR LESSEQUAL expressionAR','expressionBo',3,'p_expressionBo_binop','plintax.py',159),
('expressionBo -> expressionBo NOTEQUAL expressionBo','expressionBo',3,'p_expressionBo_binop','plintax.py',160),
('expressionBo -> expressionAR NOTEQUAL expressionAR','expressionBo',3,'p_expressionBo_binop','plintax.py',161),
('expressionBo -> expressionBo EQUALSTO expressionBo','expressionBo',3,'p_expressionBo_binop','plintax.py',162),
('expressionBo -> expressionAR EQUALSTO expressionAR','expressionBo',3,'p_expressionBo_binop','plintax.py',163),
('expressionBo -> expressionBo AND expressionBo','expressionBo',3,'p_expressionBo_binop','plintax.py',164),
('expressionBo -> expressionBo OR expressionBo','expressionBo',3,'p_expressionBo_binop','plintax.py',165),
('expressionBo -> NOT expressionBo','expressionBo',2,'p_expressionBo_inverse','plintax.py',186),
('expressionBo -> TRUE','expressionBo',1,'p_expressionBo_int','plintax.py',192),
('expressionBo -> FALSE','expressionBo',1,'p_expressionBo_int','plintax.py',193),
('expressionBo -> LPAREN expressionBo RPAREN','expressionBo',3,'p_expressionBo_group','plintax.py',201),
]
| _tabversion = '3.10'
_lr_method = 'LALR'
_lr_signature = 'nonassocLESSMOREEQUALSTOMOREEQUALLESSEQUALNOTEQUALleftPLUSMINUSleftTIMESDIVIDEleftANDORrightUMINUSINT FLOAT PLUS MINUS TIMES DIVIDE EQUALS LPAREN RPAREN LCURLBRACKET RCURLBRACKET ID COMMENT STRING ASSIGN SEMICOLON COMMA POINT NOT EQUALSTO MORE LESS MOREEQUAL LESSEQUAL NOTEQUAL AND OR INCREMENT DECREMENT BREAK CASE CHAN CONST CONTINUE DEFAULT DEFER ELSE FALLTHROUGH FOR FUNC GO GOTO IF IMPORT INTERFACE MAP PACKAGE RANGE RETURN SELECT STRUCT SWITCH TYPE VAR MAIN FMT PRINT SCAN TRUE FALSEstatement : PACKAGE MAIN IMPORT STRING FUNC MAIN LPAREN RPAREN LCURLBRACKET list RCURLBRACKET\n | PACKAGE MAIN IMPORT STRING FUNC MAIN LPAREN RPAREN LCURLBRACKET RCURLBRACKETlist : inst\n | inst listassignment : ID ASSIGN expressionAR\n | ID ASSIGN expressionBo\n | ID EQUALS expressionAR\n | ID EQUALS expressionBo\n | ID INCREMENT\n | ID DECREMENTinst : FOR expressionBo LCURLBRACKET list RCURLBRACKET\n | FOR assignment SEMICOLON expressionBo SEMICOLON assignment LCURLBRACKET list RCURLBRACKETinst : assignment SEMICOLONinst : IF expressionBo LCURLBRACKET list RCURLBRACKET ELSE LCURLBRACKET list RCURLBRACKET\n | IF expressionBo LCURLBRACKET list RCURLBRACKETlistID : expressionAR\n | expressionBo\n | expressionBo COMMA listID\n | expressionAR COMMA listIDIDlist : ID\n | ID COMMA IDlistinst : FMT POINT PRINT LPAREN listID RPAREN SEMICOLON\n | FMT POINT SCAN LPAREN IDlist RPAREN SEMICOLON\n | FMT POINT PRINT LPAREN RPAREN SEMICOLON\n | FMT POINT SCAN LPAREN RPAREN SEMICOLONexpressionAR : expressionAR PLUS expressionAR\n | expressionAR MINUS expressionAR\n | expressionAR TIMES expressionAR\n | expressionAR DIVIDE expressionAR\n | IDexpressionAR : INTexpressionAR : MINUS expressionAR %prec UMINUSexpressionAR : FLOATexpressionAR : LPAREN expressionAR RPARENexpressionBo : expressionAR MORE expressionAR\n | expressionAR LESS expressionAR\n | expressionAR MOREEQUAL expressionAR\n | expressionAR LESSEQUAL expressionAR\n | expressionBo NOTEQUAL expressionBo\n | expressionAR NOTEQUAL expressionAR\n | expressionBo EQUALSTO expressionBo\n | expressionAR EQUALSTO expressionAR\n | expressionBo AND expressionBo\n | expressionBo OR expressionBoexpressionBo : NOT expressionBo %prec UMINUSexpressionBo : TRUE\n | FALSEexpressionBo : LPAREN expressionBo RPAREN'
_lr_action_items = {'PACKAGE': ([0], [2]), '$end': ([1, 12, 19], [0, -2, -1]), 'MAIN': ([2, 6], [3, 7]), 'IMPORT': ([3], [4]), 'STRING': ([4], [5]), 'FUNC': ([5], [6]), 'LPAREN': ([7, 14, 16, 24, 27, 29, 36, 37, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 60, 62, 63, 66, 89, 106, 107], [8, 27, 27, 27, 27, 60, 66, 66, 27, 27, 27, 27, 27, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 60, 89, 90, 66, 66, 66, 66]), 'RPAREN': ([8, 25, 26, 30, 31, 34, 56, 57, 58, 59, 70, 71, 72, 73, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 89, 90, 91, 95, 97, 98, 99, 101, 114, 115, 117], [9, -46, -47, -31, -33, -30, -45, 85, 86, -32, -39, -41, -43, -44, -35, -36, -37, -38, -40, -42, -26, -27, -28, -29, -48, -34, 86, 96, 100, 86, 104, -16, -17, 108, -20, -19, -18, -21]), 'LCURLBRACKET': ([9, 21, 25, 26, 30, 31, 33, 34, 38, 39, 56, 59, 64, 65, 67, 68, 70, 71, 72, 73, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 102, 103], [10, 40, -46, -47, -31, -33, 61, -30, -9, -10, -45, -32, -5, -6, -7, -8, -39, -41, -43, -44, -35, -36, -37, -38, -40, -42, -26, -27, -28, -29, -48, -34, 111, 112]), 'RCURLBRACKET': ([10, 11, 13, 20, 32, 69, 88, 92, 94, 105, 109, 113, 116, 118, 119, 120, 121], [12, 19, -3, -4, -13, 92, 94, -11, -15, -24, -25, -22, -23, 120, 121, -12, -14]), 'FOR': ([10, 13, 32, 40, 61, 92, 94, 105, 109, 111, 112, 113, 116, 120, 121], [14, 14, -13, 14, 14, -11, -15, -24, -25, 14, 14, -22, -23, -12, -14]), 'IF': ([10, 13, 32, 40, 61, 92, 94, 105, 109, 111, 112, 113, 116, 120, 121], [16, 16, -13, 16, 16, -11, -15, -24, -25, 16, 16, -22, -23, -12, -14]), 'FMT': ([10, 13, 32, 40, 61, 92, 94, 105, 109, 111, 112, 113, 116, 120, 121], [17, 17, -13, 17, 17, -11, -15, -24, -25, 17, 17, -22, -23, -12, -14]), 'ID': ([10, 13, 14, 16, 24, 27, 29, 32, 36, 37, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 60, 61, 66, 89, 90, 92, 93, 94, 105, 106, 107, 109, 110, 111, 112, 113, 116, 120, 121], [18, 18, 28, 34, 34, 34, 34, -13, 34, 34, 18, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 34, 18, 34, 34, 101, -11, 18, -15, -24, 34, 34, -25, 101, 18, 18, -22, -23, -12, -14]), 'NOT': ([14, 16, 24, 27, 36, 37, 41, 42, 43, 44, 45, 66, 89, 106, 107], [24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24]), 'TRUE': ([14, 16, 24, 27, 36, 37, 41, 42, 43, 44, 45, 66, 89, 106, 107], [25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25]), 'FALSE': ([14, 16, 24, 27, 36, 37, 41, 42, 43, 44, 45, 66, 89, 106, 107], [26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26]), 'INT': ([14, 16, 24, 27, 29, 36, 37, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 60, 66, 89, 106, 107], [30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30]), 'MINUS': ([14, 16, 23, 24, 27, 28, 29, 30, 31, 34, 36, 37, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 58, 59, 60, 64, 66, 67, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 86, 87, 89, 91, 97, 106, 107], [29, 29, 53, 29, 29, -30, 29, -31, -33, -30, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 53, -32, 29, 53, 29, 53, 53, 53, 53, 53, 53, 53, -26, -27, -28, -29, -34, 53, 29, 53, 53, 29, 29]), 'FLOAT': ([14, 16, 24, 27, 29, 36, 37, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 60, 66, 89, 106, 107], [31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31]), 'SEMICOLON': ([15, 22, 25, 26, 30, 31, 34, 38, 39, 56, 59, 64, 65, 67, 68, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 96, 100, 104, 108], [32, 45, -46, -47, -31, -33, -30, -9, -10, -45, -32, -5, -6, -7, -8, -39, -41, -43, -44, 93, -35, -36, -37, -38, -40, -42, -26, -27, -28, -29, -48, -34, 105, 109, 113, 116]), 'POINT': ([17], [35]), 'ASSIGN': ([18, 28], [36, 36]), 'EQUALS': ([18, 28], [37, 37]), 'INCREMENT': ([18, 28], [38, 38]), 'DECREMENT': ([18, 28], [39, 39]), 'NOTEQUAL': ([21, 23, 25, 26, 28, 30, 31, 33, 34, 56, 57, 58, 59, 64, 65, 67, 68, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 91, 97, 98], [41, 50, -46, -47, -30, -31, -33, 41, -30, -45, 41, 50, -32, 50, 41, 50, 41, None, None, -43, -44, 41, -35, -36, -37, -38, -40, -42, -26, -27, -28, -29, -48, -34, 50, 50, 41]), 'EQUALSTO': ([21, 23, 25, 26, 28, 30, 31, 33, 34, 56, 57, 58, 59, 64, 65, 67, 68, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 91, 97, 98], [42, 51, -46, -47, -30, -31, -33, 42, -30, -45, 42, 51, -32, 51, 42, 51, 42, None, None, -43, -44, 42, -35, -36, -37, -38, -40, -42, -26, -27, -28, -29, -48, -34, 51, 51, 42]), 'AND': ([21, 25, 26, 30, 31, 33, 34, 56, 57, 59, 65, 68, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 98], [43, -46, -47, -31, -33, 43, -30, -45, 43, -32, 43, 43, 43, 43, -43, -44, 43, -35, -36, -37, -38, -40, -42, -26, -27, -28, -29, -48, -34, 43]), 'OR': ([21, 25, 26, 30, 31, 33, 34, 56, 57, 59, 65, 68, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 98], [44, -46, -47, -31, -33, 44, -30, -45, 44, -32, 44, 44, 44, 44, -43, -44, 44, -35, -36, -37, -38, -40, -42, -26, -27, -28, -29, -48, -34, 44]), 'MORE': ([23, 28, 30, 31, 34, 58, 59, 64, 67, 81, 82, 83, 84, 86, 91, 97], [46, -30, -31, -33, -30, 46, -32, 46, 46, -26, -27, -28, -29, -34, 46, 46]), 'LESS': ([23, 28, 30, 31, 34, 58, 59, 64, 67, 81, 82, 83, 84, 86, 91, 97], [47, -30, -31, -33, -30, 47, -32, 47, 47, -26, -27, -28, -29, -34, 47, 47]), 'MOREEQUAL': ([23, 28, 30, 31, 34, 58, 59, 64, 67, 81, 82, 83, 84, 86, 91, 97], [48, -30, -31, -33, -30, 48, -32, 48, 48, -26, -27, -28, -29, -34, 48, 48]), 'LESSEQUAL': ([23, 28, 30, 31, 34, 58, 59, 64, 67, 81, 82, 83, 84, 86, 91, 97], [49, -30, -31, -33, -30, 49, -32, 49, 49, -26, -27, -28, -29, -34, 49, 49]), 'PLUS': ([23, 28, 30, 31, 34, 58, 59, 64, 67, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 86, 87, 91, 97], [52, -30, -31, -33, -30, 52, -32, 52, 52, 52, 52, 52, 52, 52, 52, -26, -27, -28, -29, -34, 52, 52, 52]), 'TIMES': ([23, 28, 30, 31, 34, 58, 59, 64, 67, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 86, 87, 91, 97], [54, -30, -31, -33, -30, 54, -32, 54, 54, 54, 54, 54, 54, 54, 54, 54, 54, -28, -29, -34, 54, 54, 54]), 'DIVIDE': ([23, 28, 30, 31, 34, 58, 59, 64, 67, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 86, 87, 91, 97], [55, -30, -31, -33, -30, 55, -32, 55, 55, 55, 55, 55, 55, 55, 55, 55, 55, -28, -29, -34, 55, 55, 55]), 'COMMA': ([25, 26, 30, 31, 34, 56, 59, 70, 71, 72, 73, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 97, 98, 101], [-46, -47, -31, -33, -30, -45, -32, -39, -41, -43, -44, -35, -36, -37, -38, -40, -42, -26, -27, -28, -29, -48, -34, 106, 107, 110]), 'PRINT': ([35], [62]), 'SCAN': ([35], [63]), 'ELSE': ([94], [103])}
_lr_action = {}
for (_k, _v) in _lr_action_items.items():
for (_x, _y) in zip(_v[0], _v[1]):
if not _x in _lr_action:
_lr_action[_x] = {}
_lr_action[_x][_k] = _y
del _lr_action_items
_lr_goto_items = {'statement': ([0], [1]), 'list': ([10, 13, 40, 61, 111, 112], [11, 20, 69, 88, 118, 119]), 'inst': ([10, 13, 40, 61, 111, 112], [13, 13, 13, 13, 13, 13]), 'assignment': ([10, 13, 14, 40, 61, 93, 111, 112], [15, 15, 22, 15, 15, 102, 15, 15]), 'expressionBo': ([14, 16, 24, 27, 36, 37, 41, 42, 43, 44, 45, 66, 89, 106, 107], [21, 33, 56, 57, 65, 68, 70, 71, 72, 73, 74, 57, 98, 98, 98]), 'expressionAR': ([14, 16, 24, 27, 29, 36, 37, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 60, 66, 89, 106, 107], [23, 23, 23, 58, 59, 64, 67, 23, 23, 23, 23, 23, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 87, 91, 97, 97, 97]), 'listID': ([89, 106, 107], [95, 114, 115]), 'IDlist': ([90, 110], [99, 117])}
_lr_goto = {}
for (_k, _v) in _lr_goto_items.items():
for (_x, _y) in zip(_v[0], _v[1]):
if not _x in _lr_goto:
_lr_goto[_x] = {}
_lr_goto[_x][_k] = _y
del _lr_goto_items
_lr_productions = [("S' -> statement", "S'", 1, None, None, None), ('statement -> PACKAGE MAIN IMPORT STRING FUNC MAIN LPAREN RPAREN LCURLBRACKET list RCURLBRACKET', 'statement', 11, 'p_statement_expr', 'plintax.py', 17), ('statement -> PACKAGE MAIN IMPORT STRING FUNC MAIN LPAREN RPAREN LCURLBRACKET RCURLBRACKET', 'statement', 10, 'p_statement_expr', 'plintax.py', 18), ('list -> inst', 'list', 1, 'p_list', 'plintax.py', 26), ('list -> inst list', 'list', 2, 'p_list', 'plintax.py', 27), ('assignment -> ID ASSIGN expressionAR', 'assignment', 3, 'p_assignment', 'plintax.py', 34), ('assignment -> ID ASSIGN expressionBo', 'assignment', 3, 'p_assignment', 'plintax.py', 35), ('assignment -> ID EQUALS expressionAR', 'assignment', 3, 'p_assignment', 'plintax.py', 36), ('assignment -> ID EQUALS expressionBo', 'assignment', 3, 'p_assignment', 'plintax.py', 37), ('assignment -> ID INCREMENT', 'assignment', 2, 'p_assignment', 'plintax.py', 38), ('assignment -> ID DECREMENT', 'assignment', 2, 'p_assignment', 'plintax.py', 39), ('inst -> FOR expressionBo LCURLBRACKET list RCURLBRACKET', 'inst', 5, 'p_inst_For', 'plintax.py', 53), ('inst -> FOR assignment SEMICOLON expressionBo SEMICOLON assignment LCURLBRACKET list RCURLBRACKET', 'inst', 9, 'p_inst_For', 'plintax.py', 54), ('inst -> assignment SEMICOLON', 'inst', 2, 'p_inst_assignment', 'plintax.py', 62), ('inst -> IF expressionBo LCURLBRACKET list RCURLBRACKET ELSE LCURLBRACKET list RCURLBRACKET', 'inst', 9, 'p_inst_If', 'plintax.py', 67), ('inst -> IF expressionBo LCURLBRACKET list RCURLBRACKET', 'inst', 5, 'p_inst_If', 'plintax.py', 68), ('listID -> expressionAR', 'listID', 1, 'p_listID', 'plintax.py', 75), ('listID -> expressionBo', 'listID', 1, 'p_listID', 'plintax.py', 76), ('listID -> expressionBo COMMA listID', 'listID', 3, 'p_listID', 'plintax.py', 77), ('listID -> expressionAR COMMA listID', 'listID', 3, 'p_listID', 'plintax.py', 78), ('IDlist -> ID', 'IDlist', 1, 'p_IDlist', 'plintax.py', 85), ('IDlist -> ID COMMA IDlist', 'IDlist', 3, 'p_IDlist', 'plintax.py', 86), ('inst -> FMT POINT PRINT LPAREN listID RPAREN SEMICOLON', 'inst', 7, 'p_inst_func', 'plintax.py', 102), ('inst -> FMT POINT SCAN LPAREN IDlist RPAREN SEMICOLON', 'inst', 7, 'p_inst_func', 'plintax.py', 103), ('inst -> FMT POINT PRINT LPAREN RPAREN SEMICOLON', 'inst', 6, 'p_inst_func', 'plintax.py', 104), ('inst -> FMT POINT SCAN LPAREN RPAREN SEMICOLON', 'inst', 6, 'p_inst_func', 'plintax.py', 105), ('expressionAR -> expressionAR PLUS expressionAR', 'expressionAR', 3, 'p_expressionAR_binop', 'plintax.py', 115), ('expressionAR -> expressionAR MINUS expressionAR', 'expressionAR', 3, 'p_expressionAR_binop', 'plintax.py', 116), ('expressionAR -> expressionAR TIMES expressionAR', 'expressionAR', 3, 'p_expressionAR_binop', 'plintax.py', 117), ('expressionAR -> expressionAR DIVIDE expressionAR', 'expressionAR', 3, 'p_expressionAR_binop', 'plintax.py', 118), ('expressionAR -> ID', 'expressionAR', 1, 'p_expressionAR_binop', 'plintax.py', 119), ('expressionAR -> INT', 'expressionAR', 1, 'p_expressionAR_int', 'plintax.py', 134), ('expressionAR -> MINUS expressionAR', 'expressionAR', 2, 'p_expressionAR_inverse', 'plintax.py', 139), ('expressionAR -> FLOAT', 'expressionAR', 1, 'p_expressionAR_float', 'plintax.py', 144), ('expressionAR -> LPAREN expressionAR RPAREN', 'expressionAR', 3, 'p_expressionAR_group', 'plintax.py', 149), ('expressionBo -> expressionAR MORE expressionAR', 'expressionBo', 3, 'p_expressionBo_binop', 'plintax.py', 156), ('expressionBo -> expressionAR LESS expressionAR', 'expressionBo', 3, 'p_expressionBo_binop', 'plintax.py', 157), ('expressionBo -> expressionAR MOREEQUAL expressionAR', 'expressionBo', 3, 'p_expressionBo_binop', 'plintax.py', 158), ('expressionBo -> expressionAR LESSEQUAL expressionAR', 'expressionBo', 3, 'p_expressionBo_binop', 'plintax.py', 159), ('expressionBo -> expressionBo NOTEQUAL expressionBo', 'expressionBo', 3, 'p_expressionBo_binop', 'plintax.py', 160), ('expressionBo -> expressionAR NOTEQUAL expressionAR', 'expressionBo', 3, 'p_expressionBo_binop', 'plintax.py', 161), ('expressionBo -> expressionBo EQUALSTO expressionBo', 'expressionBo', 3, 'p_expressionBo_binop', 'plintax.py', 162), ('expressionBo -> expressionAR EQUALSTO expressionAR', 'expressionBo', 3, 'p_expressionBo_binop', 'plintax.py', 163), ('expressionBo -> expressionBo AND expressionBo', 'expressionBo', 3, 'p_expressionBo_binop', 'plintax.py', 164), ('expressionBo -> expressionBo OR expressionBo', 'expressionBo', 3, 'p_expressionBo_binop', 'plintax.py', 165), ('expressionBo -> NOT expressionBo', 'expressionBo', 2, 'p_expressionBo_inverse', 'plintax.py', 186), ('expressionBo -> TRUE', 'expressionBo', 1, 'p_expressionBo_int', 'plintax.py', 192), ('expressionBo -> FALSE', 'expressionBo', 1, 'p_expressionBo_int', 'plintax.py', 193), ('expressionBo -> LPAREN expressionBo RPAREN', 'expressionBo', 3, 'p_expressionBo_group', 'plintax.py', 201)] |
class Level:
def __init__(self, current_level=1, current_xp=0, level_up_base=30, level_up_factor=30):
#Original (self, current_level=1, current_xp=0, level_up_base=200, level_up_factor=150)
self.current_level = current_level
self.current_xp = current_xp
self.level_up_base = level_up_base
self.level_up_factor = level_up_factor
@property
def experience_to_next_level(self):
return self.level_up_base + self.current_level * self.level_up_factor
def add_xp(self, xp):
self.current_xp += xp
if self.current_xp > self.experience_to_next_level:
self.current_xp -= self.experience_to_next_level
self.current_level += 1
return True
else:
return False
| class Level:
def __init__(self, current_level=1, current_xp=0, level_up_base=30, level_up_factor=30):
self.current_level = current_level
self.current_xp = current_xp
self.level_up_base = level_up_base
self.level_up_factor = level_up_factor
@property
def experience_to_next_level(self):
return self.level_up_base + self.current_level * self.level_up_factor
def add_xp(self, xp):
self.current_xp += xp
if self.current_xp > self.experience_to_next_level:
self.current_xp -= self.experience_to_next_level
self.current_level += 1
return True
else:
return False |
version = 1
disable_existing_loggers = False
loggers = {
'sanic.root': {
'level': 'DEBUG',
'handlers': ['console', 'root_file'],
'propagate': True
},
'sanic.error': {
'level': 'ERROR',
'handlers': ['error_file'],
'propagate': True
},
'sanic.access': {
'level': 'INFO',
'handlers': ['access_file'],
'propagate': True
}
}
handlers = {
'console': {
'class': 'logging.StreamHandler',
'level': 'DEBUG',
'formatter': 'generic'
},
'root_file': {
'class': 'logging.handlers.RotatingFileHandler',
'level': 'INFO',
'formatter': 'generic',
'encoding': 'utf-8',
'filename': './runtime/log/root.log',
'maxBytes': 2000000,
'backupCount': 5
},
'error_file': {
'class': 'logging.handlers.RotatingFileHandler',
'level': 'ERROR',
'formatter': 'generic',
'encoding': 'utf-8',
'filename': './runtime/log/error.log',
'maxBytes': 2000000,
'backupCount': 5
},
'access_file': {
'class': 'logging.handlers.RotatingFileHandler',
'level': 'INFO',
'formatter': 'access',
'encoding': 'utf-8',
'filename': './runtime/log/access.log',
'maxBytes': 2000000,
'backupCount': 5
}
}
formatters = {
'generic': {
'format': '%(asctime)s %(levelname)s %(name)s:%(lineno)d | %(message)s'
},
'access': {
'format': '%(asctime)s - %(levelname)s - %(name)s:%(lineno)d %(byte)d | %(request)s'
}
}
| version = 1
disable_existing_loggers = False
loggers = {'sanic.root': {'level': 'DEBUG', 'handlers': ['console', 'root_file'], 'propagate': True}, 'sanic.error': {'level': 'ERROR', 'handlers': ['error_file'], 'propagate': True}, 'sanic.access': {'level': 'INFO', 'handlers': ['access_file'], 'propagate': True}}
handlers = {'console': {'class': 'logging.StreamHandler', 'level': 'DEBUG', 'formatter': 'generic'}, 'root_file': {'class': 'logging.handlers.RotatingFileHandler', 'level': 'INFO', 'formatter': 'generic', 'encoding': 'utf-8', 'filename': './runtime/log/root.log', 'maxBytes': 2000000, 'backupCount': 5}, 'error_file': {'class': 'logging.handlers.RotatingFileHandler', 'level': 'ERROR', 'formatter': 'generic', 'encoding': 'utf-8', 'filename': './runtime/log/error.log', 'maxBytes': 2000000, 'backupCount': 5}, 'access_file': {'class': 'logging.handlers.RotatingFileHandler', 'level': 'INFO', 'formatter': 'access', 'encoding': 'utf-8', 'filename': './runtime/log/access.log', 'maxBytes': 2000000, 'backupCount': 5}}
formatters = {'generic': {'format': '%(asctime)s %(levelname)s %(name)s:%(lineno)d | %(message)s'}, 'access': {'format': '%(asctime)s - %(levelname)s - %(name)s:%(lineno)d %(byte)d | %(request)s'}} |
#Printing Stars in 'C' Shape !
'''
****
*
*
*
*
*
****
'''
for row in range(7):
for col in range(5):
if (col==0 and (row!=0 and row!=6)) or (row==0 or row==6) and (col>0):
print('*',end='')
else:
print(end=' ')
print() | """
****
*
*
*
*
*
****
"""
for row in range(7):
for col in range(5):
if col == 0 and (row != 0 and row != 6) or ((row == 0 or row == 6) and col > 0):
print('*', end='')
else:
print(end=' ')
print() |
def Main():
a = 1
b = 2
c = 3
e = 4
d = a + b - c * e
return d
| def main():
a = 1
b = 2
c = 3
e = 4
d = a + b - c * e
return d |
# Parameters:
# MON_PERIOD : Number of seconds the temperature is read.
# MON_INTERVAL : Number of seconds the temperature is checked.
# TEMP_HIGH : Value in Celsius degree on that a warning e-mail is sent if temperature is above it.
# TEMP_CRITICAL : Value in Celsius degree on that the device is shutted down to protect it.
MON_PERIOD = 1
MON_INTERVAL = 600
TEMP_HIGH = 85.0
TEMP_CRITICAL = 90.0
| mon_period = 1
mon_interval = 600
temp_high = 85.0
temp_critical = 90.0 |
material = []
for i in range(int(input())):
material.append(int(input()))
srted = sorted(material)
if srted == material:
print("YES")
else:
print("NO") | material = []
for i in range(int(input())):
material.append(int(input()))
srted = sorted(material)
if srted == material:
print('YES')
else:
print('NO') |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.