content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
class ListNode:
def __init__(self, value, prev=None, next=None):
self.value = value
self.prev = prev
self.next = next
def insert_after(self, value):
pass
def insert_before(self, value):
pass
def delete(self):
pass
class DoublyLinkedList:
def __init__(self, node=None):
self.head = node
self.tail = node
def add_to_head(self, value):
pass
def remove_from_head(self):
pass
def add_to_tail(self, value):
pass
def remove_from_tail(self):
pass
def move_to_front(self, node):
pass
def move_to_end(self, node):
pass
def delete(self, node):
pass
| class Listnode:
def __init__(self, value, prev=None, next=None):
self.value = value
self.prev = prev
self.next = next
def insert_after(self, value):
pass
def insert_before(self, value):
pass
def delete(self):
pass
class Doublylinkedlist:
def __init__(self, node=None):
self.head = node
self.tail = node
def add_to_head(self, value):
pass
def remove_from_head(self):
pass
def add_to_tail(self, value):
pass
def remove_from_tail(self):
pass
def move_to_front(self, node):
pass
def move_to_end(self, node):
pass
def delete(self, node):
pass |
"""Class for converter models."""
class InverterModels:
"""
SwitcInverter class.
Attributes:
():
"""
def ODE_model_single_phase_EMT(self,y,t,signals,grid,sim):
"""ODE model of inverter branch."""
self.ia,dummy = y # unpack current values of y
Vdc = 100.0 #Get DC link voltage
control_signal = self.control_signal_calc(signals,t)
self.vta = self.vt_calc(Vdc,control_signal)
self.va = self.va_calc(t,grid,sim.use_grid)
dia = (1/self.Lf)*(-self.Rf*self.ia -self.va + self.vta)
result = [dia,dummy]
return np.array(result)
def ODE_model_single_phase_dynamicphasor(self,y,t,signals,grid,sim):
"""Dynamic phasor."""
iaR,iaI = y # unpack current values of y
Vdc = 100.0 #Get DC link voltage
winv = 2*math.pi*60
self.ia = iaR + 1j*iaI
self.vta = self.half_bridge_phasor(Vdc,1.0+1j*0.0)
diaR = (1/self.Lf)*(-self.Rf*self.ia.real - self.Rload*self.ia.real + self.vta.real) + (winv)*self.ia.imag
diaI = (1/self.Lf)*(-self.Rf*self.ia.imag - self.Rload*self.ia.imag + self.vta.imag) - (winv)*self.ia.real
result = [diaR,diaI]
return np.array(result)
def single_phase_half_bridge_switching(self,Vdc,S1):
"""Simulates a bridge in inverter"""
self.update_Vdc(Vdc)
S11 = self.calc_primary(S1)
S12 = self.calc_complimentary(S1)
assert S11+S12 == 1, 'S11 and S12 switches cannot be both ON or OFF at the same time in ideal half bridge.'
#print('S11:{},S12:{}'.format(S11,S12))
Van = (S11 - S12)*(self.Vdc/2)
#print('Van:{}'.format(Van))
return Van
def single_phase_full_bridge_switching(self,Vdc,S1,S2):
"""Simulates a bridge in inverter"""
self.update_Vdc(Vdc)
S11 = self.calc_primary(S1)
S12 = self.calc_complimentary(S1)
S21 = calc_primary(S2)
S22 = calc_complimentary(S2)
assert S11+S12 == 1, 'S11 and S12 switches cannot be both ON or OFF at the same time in full bridge.'
assert S21+S22 == 1, 'S21 and S22 switches cannot be both ON or OFF at the same time in full bridge.'
Van = (S11 - S12)*(self.Vdc/2) - (S21 - S22)*(self.Vdc/2)
#print('Van:{}'.format(Van))
return Van
def three_phase_full_bridge_switching(Vdc,S1,S2,S3):
"""Simulates a bridge in inverter"""
S11 = calc_primary(S1)
S12 = calc_complimentary(S1)
S21 = calc_primary(S2)
S22 = calc_complimentary(S2)
S31 = calc_primary(S3)
S32 = calc_complimentary(S3)
assert S11+S12 == 1, 'S11 and S12 switches cannot be both ON or OFF at the same time in ideal half bridge.'
assert S21+S22 == 1, 'S21 and S22 switches cannot be both ON or OFF at the same time in ideal half bridge.'
assert S31+S32 == 1, 'S31 and S32 switches cannot be both ON or OFF at the same time in ideal half bridge.'
print('S1:{},S2:{},S3:{}'.format(S11,S21,S31))
Vno = (self.Vdc/6)*(2*S11+2*S21+2*S31-3)
Van = (self.Vdc/2)*(S11-S12)-Vno
Vbn = (self.Vdc/2)*(S21-S22)-Vno
Vcn = (self.Vdc/2)*(S31-S32)-Vno
#Van = (2*S11 - S21 - S31)*(Vdc/3)
#Vbn = (2*S21 - S11 - S31)*(Vdc/3)
#Vcn = (2*S31 - S21 - S11)*(Vdc/3)
print('Vno:{},Van+Vbn+Vcn:{}'.format(Vno,Van+Vbn+Vcn))
print('Van:{},Vbn:{},Vcn:{}'.format(Van,Vbn,Vcn))
print('Vab:{},Vbc:{},Vca:{}'.format(Van-Vbn,Vbn-Vcn,Vcn-Van))
return Van,Vbn,Vcn
def single_phase_half_bridge_average(self,Vdc,m):
"""Simulates a bridge in inverter"""
self.update_Vdc(Vdc)
assert m>=-1 and m <= 1, 'duty cycle should be between 0 and 1.'
Van = m*(self.Vdc/2)
return Van
def single_phase_full_bridge_average(self,Vdc,m):
"""Simulates a bridge in inverter"""
self.update_Vdc(Vdc)
assert m>=-1 and m <= 1, 'duty cycle should be between 0 and 1.'
Van = m*(self.Vdc)
return Van
def single_phase_half_bridge_phasor(self,Vdc,m):
"""Simulates a bridge in inverter"""
self.update_Vdc(Vdc)
assert isinstance(m,complex), 'duty cycle should be complex phasor.'
Van = m*(self.Vdc/2)
return Van
def single_phase_full_bridge_phasor(self,Vdc,m):
"""Simulates a bridge in inverter"""
self.update_Vdc(Vdc)
assert isinstance(m,complex), 'duty cycle should be complex phasor.'
Van = m*(self.Vdc)
return Van | """Class for converter models."""
class Invertermodels:
"""
SwitcInverter class.
Attributes:
():
"""
def ode_model_single_phase_emt(self, y, t, signals, grid, sim):
"""ODE model of inverter branch."""
(self.ia, dummy) = y
vdc = 100.0
control_signal = self.control_signal_calc(signals, t)
self.vta = self.vt_calc(Vdc, control_signal)
self.va = self.va_calc(t, grid, sim.use_grid)
dia = 1 / self.Lf * (-self.Rf * self.ia - self.va + self.vta)
result = [dia, dummy]
return np.array(result)
def ode_model_single_phase_dynamicphasor(self, y, t, signals, grid, sim):
"""Dynamic phasor."""
(ia_r, ia_i) = y
vdc = 100.0
winv = 2 * math.pi * 60
self.ia = iaR + 1j * iaI
self.vta = self.half_bridge_phasor(Vdc, 1.0 + 1j * 0.0)
dia_r = 1 / self.Lf * (-self.Rf * self.ia.real - self.Rload * self.ia.real + self.vta.real) + winv * self.ia.imag
dia_i = 1 / self.Lf * (-self.Rf * self.ia.imag - self.Rload * self.ia.imag + self.vta.imag) - winv * self.ia.real
result = [diaR, diaI]
return np.array(result)
def single_phase_half_bridge_switching(self, Vdc, S1):
"""Simulates a bridge in inverter"""
self.update_Vdc(Vdc)
s11 = self.calc_primary(S1)
s12 = self.calc_complimentary(S1)
assert S11 + S12 == 1, 'S11 and S12 switches cannot be both ON or OFF at the same time in ideal half bridge.'
van = (S11 - S12) * (self.Vdc / 2)
return Van
def single_phase_full_bridge_switching(self, Vdc, S1, S2):
"""Simulates a bridge in inverter"""
self.update_Vdc(Vdc)
s11 = self.calc_primary(S1)
s12 = self.calc_complimentary(S1)
s21 = calc_primary(S2)
s22 = calc_complimentary(S2)
assert S11 + S12 == 1, 'S11 and S12 switches cannot be both ON or OFF at the same time in full bridge.'
assert S21 + S22 == 1, 'S21 and S22 switches cannot be both ON or OFF at the same time in full bridge.'
van = (S11 - S12) * (self.Vdc / 2) - (S21 - S22) * (self.Vdc / 2)
return Van
def three_phase_full_bridge_switching(Vdc, S1, S2, S3):
"""Simulates a bridge in inverter"""
s11 = calc_primary(S1)
s12 = calc_complimentary(S1)
s21 = calc_primary(S2)
s22 = calc_complimentary(S2)
s31 = calc_primary(S3)
s32 = calc_complimentary(S3)
assert S11 + S12 == 1, 'S11 and S12 switches cannot be both ON or OFF at the same time in ideal half bridge.'
assert S21 + S22 == 1, 'S21 and S22 switches cannot be both ON or OFF at the same time in ideal half bridge.'
assert S31 + S32 == 1, 'S31 and S32 switches cannot be both ON or OFF at the same time in ideal half bridge.'
print('S1:{},S2:{},S3:{}'.format(S11, S21, S31))
vno = self.Vdc / 6 * (2 * S11 + 2 * S21 + 2 * S31 - 3)
van = self.Vdc / 2 * (S11 - S12) - Vno
vbn = self.Vdc / 2 * (S21 - S22) - Vno
vcn = self.Vdc / 2 * (S31 - S32) - Vno
print('Vno:{},Van+Vbn+Vcn:{}'.format(Vno, Van + Vbn + Vcn))
print('Van:{},Vbn:{},Vcn:{}'.format(Van, Vbn, Vcn))
print('Vab:{},Vbc:{},Vca:{}'.format(Van - Vbn, Vbn - Vcn, Vcn - Van))
return (Van, Vbn, Vcn)
def single_phase_half_bridge_average(self, Vdc, m):
"""Simulates a bridge in inverter"""
self.update_Vdc(Vdc)
assert m >= -1 and m <= 1, 'duty cycle should be between 0 and 1.'
van = m * (self.Vdc / 2)
return Van
def single_phase_full_bridge_average(self, Vdc, m):
"""Simulates a bridge in inverter"""
self.update_Vdc(Vdc)
assert m >= -1 and m <= 1, 'duty cycle should be between 0 and 1.'
van = m * self.Vdc
return Van
def single_phase_half_bridge_phasor(self, Vdc, m):
"""Simulates a bridge in inverter"""
self.update_Vdc(Vdc)
assert isinstance(m, complex), 'duty cycle should be complex phasor.'
van = m * (self.Vdc / 2)
return Van
def single_phase_full_bridge_phasor(self, Vdc, m):
"""Simulates a bridge in inverter"""
self.update_Vdc(Vdc)
assert isinstance(m, complex), 'duty cycle should be complex phasor.'
van = m * self.Vdc
return Van |
def count(start=0, step=1):
while True:
yield start
start += step
def cycle(p):
try:
len(p)
except TypeError:
# len() is not defined for this type. Assume it is
# a finite iterable so we must cache the elements.
cache = []
for i in p:
yield i
cache.append(i)
p = cache
while p:
yield from p
def repeat(el, n=None):
if n is None:
while True:
yield el
else:
for i in range(n):
yield el
def chain(*p):
for i in p:
yield from i
def islice(p, start, stop=(), step=1):
if stop == ():
stop = start
start = 0
# TODO: optimizing or breaking semantics?
if start >= stop:
return
it = iter(p)
for i in range(start):
next(it)
while True:
yield next(it)
for i in range(step - 1):
next(it)
start += step
if start >= stop:
return
def tee(iterable, n=2):
return [iter(iterable)] * n
def starmap(function, iterable):
for args in iterable:
yield function(*args)
def accumulate(iterable, func=lambda x, y: x + y):
it = iter(iterable)
try:
acc = next(it)
except StopIteration:
return
yield acc
for element in it:
acc = func(acc, element)
yield acc
| def count(start=0, step=1):
while True:
yield start
start += step
def cycle(p):
try:
len(p)
except TypeError:
cache = []
for i in p:
yield i
cache.append(i)
p = cache
while p:
yield from p
def repeat(el, n=None):
if n is None:
while True:
yield el
else:
for i in range(n):
yield el
def chain(*p):
for i in p:
yield from i
def islice(p, start, stop=(), step=1):
if stop == ():
stop = start
start = 0
if start >= stop:
return
it = iter(p)
for i in range(start):
next(it)
while True:
yield next(it)
for i in range(step - 1):
next(it)
start += step
if start >= stop:
return
def tee(iterable, n=2):
return [iter(iterable)] * n
def starmap(function, iterable):
for args in iterable:
yield function(*args)
def accumulate(iterable, func=lambda x, y: x + y):
it = iter(iterable)
try:
acc = next(it)
except StopIteration:
return
yield acc
for element in it:
acc = func(acc, element)
yield acc |
'''
Assembling your data
Here, three DataFrames have been pre-loaded: g1800s, g1900s, and g2000s. These contain the Gapminder life expectancy data for, respectively, the 19th century, the 20th century, and the 21st century.
Your task in this exercise is to concatenate them into a single DataFrame called gapminder. This is a row-wise concatenation, similar to how you concatenated the monthly Uber datasets in Chapter 3.
INSTRUCTIONS
100XP
-Use pd.concat() to concatenate g1800s, g1900s, and g2000s into one DataFrame called gapminder. Make sure you pass DataFrames to pd.concat() in the form of a list.
-Print the shape and the head of the concatenated DataFrame.
'''
# Concatenate the DataFrames row-wise
gapminder = pd.concat([g1800s, g1900s, g2000s])
# Print the shape of gapminder
print(gapminder.shape)
# Print the head of gapminder
print(gapminder.head())
| """
Assembling your data
Here, three DataFrames have been pre-loaded: g1800s, g1900s, and g2000s. These contain the Gapminder life expectancy data for, respectively, the 19th century, the 20th century, and the 21st century.
Your task in this exercise is to concatenate them into a single DataFrame called gapminder. This is a row-wise concatenation, similar to how you concatenated the monthly Uber datasets in Chapter 3.
INSTRUCTIONS
100XP
-Use pd.concat() to concatenate g1800s, g1900s, and g2000s into one DataFrame called gapminder. Make sure you pass DataFrames to pd.concat() in the form of a list.
-Print the shape and the head of the concatenated DataFrame.
"""
gapminder = pd.concat([g1800s, g1900s, g2000s])
print(gapminder.shape)
print(gapminder.head()) |
class MinStack(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.data = []
def push(self, x):
"""
:type x: int
:rtype: void
"""
self.data.append(x)
def pop(self):
"""
:rtype: void
"""
if len(self.data)>0:
self.data.pop()
def top(self):
"""
:rtype: int
"""
if len(self.data)>0:
return self.data[-1]
def getMin(self):
"""
:rtype: int
"""
if len(self.data)>0:
return min(self.data)
# enteries = []
# while len(self.data) > 0:
# enteries.append(self.top())
# self.pop()
# if len(enteries)>0:
# ans = min(enteries)
# else:
# ans = None
# for et in reversed(enteries):
# self.push(et)
# return ans
| class Minstack(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.data = []
def push(self, x):
"""
:type x: int
:rtype: void
"""
self.data.append(x)
def pop(self):
"""
:rtype: void
"""
if len(self.data) > 0:
self.data.pop()
def top(self):
"""
:rtype: int
"""
if len(self.data) > 0:
return self.data[-1]
def get_min(self):
"""
:rtype: int
"""
if len(self.data) > 0:
return min(self.data) |
description = 'collimator setup'
group = 'lowlevel'
devices = dict(
tof_io = device('nicos.devices.generic.ManualSwitch',
description = 'ToF',
states = [1, 2, 3],
lowlevel = True,
),
L = device('nicos.devices.generic.Switcher',
description = 'Distance',
moveable = 'tof_io',
mapping = {
10: 1,
13: 2,
17: 3,
},
unit = 'm',
precision = 0,
),
collimator_io = device('nicos.devices.generic.ManualSwitch',
description = 'Collimator',
states = [1, 2, 3, 4, 5, 6],
lowlevel = True,
),
pinhole = device('nicos.devices.generic.Switcher',
description = 'Hole diameter',
moveable = 'collimator_io',
mapping = {
6.2: 1,
3: 2,
0.85: 3,
1.5: 4,
2.5: 5,
},
unit = 'mm',
precision = 0,
),
collimator = device('nicos_mlz.antares.devices.collimator.CollimatorLoverD',
description = 'Collimator ratio (L/D)',
l = 'L',
d = 'pinhole',
unit = 'L/D',
fmtstr = '%.2f',
),
)
| description = 'collimator setup'
group = 'lowlevel'
devices = dict(tof_io=device('nicos.devices.generic.ManualSwitch', description='ToF', states=[1, 2, 3], lowlevel=True), L=device('nicos.devices.generic.Switcher', description='Distance', moveable='tof_io', mapping={10: 1, 13: 2, 17: 3}, unit='m', precision=0), collimator_io=device('nicos.devices.generic.ManualSwitch', description='Collimator', states=[1, 2, 3, 4, 5, 6], lowlevel=True), pinhole=device('nicos.devices.generic.Switcher', description='Hole diameter', moveable='collimator_io', mapping={6.2: 1, 3: 2, 0.85: 3, 1.5: 4, 2.5: 5}, unit='mm', precision=0), collimator=device('nicos_mlz.antares.devices.collimator.CollimatorLoverD', description='Collimator ratio (L/D)', l='L', d='pinhole', unit='L/D', fmtstr='%.2f')) |
inf = 2**33
DEBUG = 0
def bellmanFord(graph, cost, loop, start):
parent = [-1] * len(graph)
cost[start] = 0
for i in range(len(graph) - 1):
for u in range(len(graph)):
for v, c in graph[u]:
if (cost[u] + c < cost[v] and cost[u] != inf):
parent[v] = u
cost[v] = cost[u] + c
if (DEBUG): print("parent", parent)
for u in range(len(graph)):
for v, c in graph[u]:
if (cost[u] + c < cost[v] and cost[v] != inf):
#loop[u], loop[v] = 1, 1
#loop[v] = 1
start, end, done = v, u, 0
loop[end] = 1
while (end != start and done < len(graph)):
end = parent[end]
loop[end] = 1
done += 1
loop[end] = 1
return(0)
case = 1
while (True):
try:
line = list(map(int, input().split()))
except:
break
junctions, costs = line[0], line[1:]
if (junctions == 0):
trash = input()
trash = input()
print("Set #", case, sep='')
case += 1
continue
graph = [[] for i in range(junctions)]
roads = int(input())
for i in range(roads):
u, v = map(int, input().split())
u, v = u - 1, v - 1
graph[u] += [[v, (costs[v] - costs[u])**3]]
if (DEBUG): print(graph)
cost, loop = [inf] * junctions, [0] * junctions
bellmanFord(graph, cost, loop, 0)
if (DEBUG): print(cost)
if (DEBUG): print(loop)
queries = int(input())
print("Set #", case, sep='')
for i in range(queries):
query = int(input())
query -= 1
if (cost[query] < 3 or loop[query] or cost[query] == inf):
print("?")
else:
print(cost[query])
case += 1 | inf = 2 ** 33
debug = 0
def bellman_ford(graph, cost, loop, start):
parent = [-1] * len(graph)
cost[start] = 0
for i in range(len(graph) - 1):
for u in range(len(graph)):
for (v, c) in graph[u]:
if cost[u] + c < cost[v] and cost[u] != inf:
parent[v] = u
cost[v] = cost[u] + c
if DEBUG:
print('parent', parent)
for u in range(len(graph)):
for (v, c) in graph[u]:
if cost[u] + c < cost[v] and cost[v] != inf:
(start, end, done) = (v, u, 0)
loop[end] = 1
while end != start and done < len(graph):
end = parent[end]
loop[end] = 1
done += 1
loop[end] = 1
return 0
case = 1
while True:
try:
line = list(map(int, input().split()))
except:
break
(junctions, costs) = (line[0], line[1:])
if junctions == 0:
trash = input()
trash = input()
print('Set #', case, sep='')
case += 1
continue
graph = [[] for i in range(junctions)]
roads = int(input())
for i in range(roads):
(u, v) = map(int, input().split())
(u, v) = (u - 1, v - 1)
graph[u] += [[v, (costs[v] - costs[u]) ** 3]]
if DEBUG:
print(graph)
(cost, loop) = ([inf] * junctions, [0] * junctions)
bellman_ford(graph, cost, loop, 0)
if DEBUG:
print(cost)
if DEBUG:
print(loop)
queries = int(input())
print('Set #', case, sep='')
for i in range(queries):
query = int(input())
query -= 1
if cost[query] < 3 or loop[query] or cost[query] == inf:
print('?')
else:
print(cost[query])
case += 1 |
def chop(t):
del t[0], t[-1]
return None
def middle(t):
return t[1:-1]
letters = ['a', 'b', 'c', 'd', 'e']
print(middle(letters))
| def chop(t):
del t[0], t[-1]
return None
def middle(t):
return t[1:-1]
letters = ['a', 'b', 'c', 'd', 'e']
print(middle(letters)) |
"""Build extension to generate j2cl-compatible protocol buffers.
Usage:
j2cl_proto: generates a j2cl-compatible java_library for an existing
proto_library.
Example usage:
load("//java/com/google/protobuf/contrib/j2cl:j2cl_proto.bzl", "j2cl_proto_library")
proto_library(
name = "accessor",
srcs = ["accessor.proto"],
)
j2cl_proto_library(
name = "accessor_j2cl_proto",
dep = ":accessor",
)
"""
# Blessed by J2CL team. This is needed for J2CL provider and J2CL provider API is
# only avaiable for proto. Other should never depend on J2CL internals.
load(
"@com_google_j2cl//build_defs/internal_do_not_use:j2cl_common.bzl",
"J2CL_TOOLCHAIN_ATTRS",
"J2clInfo",
"j2cl_common",
)
load(
"//java/com/google/protobuf/contrib/immutablejs:immutable_js_proto_library.bzl",
"ImmutableJspbInfo",
"immutable_js_proto_library_aspect",
)
load(":j2cl_proto_provider.bzl", "J2clProtoInfo")
def _unarchived_jar_path(path):
"""Get the path of the unarchived directory.
Args:
path: The path to the archive file.
Returns:
The path to the directory that this file will expand to.
"""
if not path.endswith(".srcjar"):
fail("Path %s doesn't end in \".srcjar\"" % path)
return path[0:-7]
def _j2cl_proto_library_aspect_impl(target, ctx):
artifact_suffix = "-j2cl"
srcs = target[ProtoInfo].direct_sources
transitive_srcs = target[ProtoInfo].transitive_sources
deps = [target[ImmutableJspbInfo].js]
deps += [dep[J2clProtoInfo]._private_.j2cl_info for dep in ctx.rule.attr.deps]
transitive_runfiles = [target[ImmutableJspbInfo]._private_.runfiles]
transitive_runfiles += [dep[J2clProtoInfo]._private_.runfiles for dep in ctx.rule.attr.deps]
jar_archive = None
if srcs:
jar_archive = ctx.actions.declare_file(ctx.label.name + artifact_suffix + ".srcjar")
protoc_command_template = """
set -e -o pipefail
rm -rf {dir}
mkdir -p {dir}
{protoc} --plugin=protoc-gen-j2cl_protobuf={protoc_plugin} \
--proto_path=. \
--proto_path={genfiles} \
--j2cl_protobuf_out={dir} \
{proto_sources}
java_files=$(find {dir} -name '*.java')
chmod -R 664 $java_files
{java_format} -i $java_files
{jar} -cf {jar_file} -C {dir} .
"""
protoc_command = protoc_command_template.format(
dir = _unarchived_jar_path(jar_archive.path),
protoc = ctx.executable._protocol_compiler.path,
protoc_plugin = ctx.executable._protoc_gen_j2cl.path,
genfiles = ctx.configuration.genfiles_dir.path,
proto_sources = " ".join([s.path for s in srcs]),
jar = ctx.executable._jar.path,
jar_file = jar_archive.path,
java_format = ctx.executable._google_java_formatter.path,
)
resolved_tools, resolved_command, input_manifest = ctx.resolve_command(
command = protoc_command,
tools = [
ctx.attr._protocol_compiler,
ctx.attr._protoc_gen_j2cl,
ctx.attr._jar,
ctx.attr._google_java_formatter,
],
)
ctx.actions.run_shell(
command = resolved_command,
inputs = transitive_srcs,
tools = resolved_tools,
outputs = [jar_archive],
input_manifests = input_manifest,
progress_message = "Generating J2CL proto files",
)
runtime_deps = [d[J2clInfo] for d in ctx.attr._j2cl_proto_implicit_deps]
transitive_runfiles += [
d[DefaultInfo].default_runfiles.files
for d in ctx.attr._j2cl_proto_implicit_deps
]
j2cl_provider = j2cl_common.compile(
ctx,
srcs = [jar_archive],
deps = deps + runtime_deps,
artifact_suffix = artifact_suffix,
)
else:
# Considers deps as exports in no srcs case.
j2cl_provider = j2cl_common.compile(
ctx,
exports = deps,
artifact_suffix = artifact_suffix,
)
js = j2cl_common.get_jsinfo_provider(j2cl_provider)
return J2clProtoInfo(
_private_ = struct(
j2cl_info = j2cl_provider,
srcjar = jar_archive,
runfiles = depset(js.srcs, transitive = transitive_runfiles),
),
js = js,
)
_j2cl_proto_library_aspect = aspect(
implementation = _j2cl_proto_library_aspect_impl,
required_aspect_providers = [ImmutableJspbInfo],
attr_aspects = ["deps"],
provides = [J2clProtoInfo],
attrs = dict(J2CL_TOOLCHAIN_ATTRS, **{
"_j2cl_proto_implicit_deps": attr.label_list(
default = [
Label("//third_party:gwt-jsinterop-annotations-j2cl"),
Label("//third_party:jsinterop-base-j2cl"),
Label("//third_party:j2cl_proto_runtime"),
],
),
"_protocol_compiler": attr.label(
executable = True,
cfg = "host",
default = Label("//third_party:protocol_compiler"),
),
"_protoc_gen_j2cl": attr.label(
executable = True,
cfg = "host",
default = Label("//java/com/google/protobuf/contrib/j2cl/internal_do_not_use:J2CLProtobufCompiler"),
),
"_jar": attr.label(
executable = True,
cfg = "host",
default = Label("@bazel_tools//tools/jdk:jar"),
),
"_google_java_formatter": attr.label(
cfg = "host",
executable = True,
default = Label("//third_party:google_java_format"),
allow_files = True,
),
}),
fragments = ["java", "js"],
)
def _j2cl_proto_library_rule_impl(ctx):
if len(ctx.attr.deps) != 1:
fail("Only one deps entry allowed")
j2cl_proto_info = ctx.attr.deps[0][J2clProtoInfo]
output = []
srcjar = j2cl_proto_info._private_.srcjar
if srcjar:
output = ctx.actions.declare_directory(ctx.label.name + "_for_testing_do_not_use")
ctx.actions.run_shell(
inputs = [srcjar],
outputs = [output],
command = (
"mkdir -p %s && " % output.path +
"%s x %s -d %s" % (ctx.executable._zip.path, srcjar.path, output.path)
),
tools = [ctx.executable._zip],
)
output = [output]
# This is a workaround to b/35847804 to make sure the zip ends up in the runfiles.
# We are doing this transitively since we need to workaround the issue for the files generated
# by the aspect as well.
runfiles = j2cl_proto_info._private_.runfiles
return j2cl_common.create_js_lib_struct(
j2cl_info = j2cl_proto_info._private_.j2cl_info,
extra_providers = [
DefaultInfo(runfiles = ctx.runfiles(transitive_files = runfiles)),
OutputGroupInfo(for_testing_do_not_use = output),
],
)
# WARNING:
# This rule should really be private since it intoduces a new proto runtime
# to the repo and using this will cause diamond dependency problems.
# Use regular j2cl_proto_library rule with the blaze flag
# (--define j2cl_proto=interop).
new_j2cl_proto_library = rule(
implementation = _j2cl_proto_library_rule_impl,
attrs = {
"deps": attr.label_list(
providers = [ProtoInfo],
aspects = [immutable_js_proto_library_aspect, _j2cl_proto_library_aspect],
),
"_zip": attr.label(
cfg = "host",
executable = True,
default = Label("@bazel_tools//tools/zip:zipper"),
),
},
fragments = ["js"],
)
| """Build extension to generate j2cl-compatible protocol buffers.
Usage:
j2cl_proto: generates a j2cl-compatible java_library for an existing
proto_library.
Example usage:
load("//java/com/google/protobuf/contrib/j2cl:j2cl_proto.bzl", "j2cl_proto_library")
proto_library(
name = "accessor",
srcs = ["accessor.proto"],
)
j2cl_proto_library(
name = "accessor_j2cl_proto",
dep = ":accessor",
)
"""
load('@com_google_j2cl//build_defs/internal_do_not_use:j2cl_common.bzl', 'J2CL_TOOLCHAIN_ATTRS', 'J2clInfo', 'j2cl_common')
load('//java/com/google/protobuf/contrib/immutablejs:immutable_js_proto_library.bzl', 'ImmutableJspbInfo', 'immutable_js_proto_library_aspect')
load(':j2cl_proto_provider.bzl', 'J2clProtoInfo')
def _unarchived_jar_path(path):
"""Get the path of the unarchived directory.
Args:
path: The path to the archive file.
Returns:
The path to the directory that this file will expand to.
"""
if not path.endswith('.srcjar'):
fail('Path %s doesn\'t end in ".srcjar"' % path)
return path[0:-7]
def _j2cl_proto_library_aspect_impl(target, ctx):
artifact_suffix = '-j2cl'
srcs = target[ProtoInfo].direct_sources
transitive_srcs = target[ProtoInfo].transitive_sources
deps = [target[ImmutableJspbInfo].js]
deps += [dep[J2clProtoInfo]._private_.j2cl_info for dep in ctx.rule.attr.deps]
transitive_runfiles = [target[ImmutableJspbInfo]._private_.runfiles]
transitive_runfiles += [dep[J2clProtoInfo]._private_.runfiles for dep in ctx.rule.attr.deps]
jar_archive = None
if srcs:
jar_archive = ctx.actions.declare_file(ctx.label.name + artifact_suffix + '.srcjar')
protoc_command_template = "\n set -e -o pipefail\n\n rm -rf {dir}\n mkdir -p {dir}\n\n {protoc} --plugin=protoc-gen-j2cl_protobuf={protoc_plugin} --proto_path=. --proto_path={genfiles} --j2cl_protobuf_out={dir} {proto_sources}\n java_files=$(find {dir} -name '*.java')\n chmod -R 664 $java_files\n {java_format} -i $java_files\n {jar} -cf {jar_file} -C {dir} .\n "
protoc_command = protoc_command_template.format(dir=_unarchived_jar_path(jar_archive.path), protoc=ctx.executable._protocol_compiler.path, protoc_plugin=ctx.executable._protoc_gen_j2cl.path, genfiles=ctx.configuration.genfiles_dir.path, proto_sources=' '.join([s.path for s in srcs]), jar=ctx.executable._jar.path, jar_file=jar_archive.path, java_format=ctx.executable._google_java_formatter.path)
(resolved_tools, resolved_command, input_manifest) = ctx.resolve_command(command=protoc_command, tools=[ctx.attr._protocol_compiler, ctx.attr._protoc_gen_j2cl, ctx.attr._jar, ctx.attr._google_java_formatter])
ctx.actions.run_shell(command=resolved_command, inputs=transitive_srcs, tools=resolved_tools, outputs=[jar_archive], input_manifests=input_manifest, progress_message='Generating J2CL proto files')
runtime_deps = [d[J2clInfo] for d in ctx.attr._j2cl_proto_implicit_deps]
transitive_runfiles += [d[DefaultInfo].default_runfiles.files for d in ctx.attr._j2cl_proto_implicit_deps]
j2cl_provider = j2cl_common.compile(ctx, srcs=[jar_archive], deps=deps + runtime_deps, artifact_suffix=artifact_suffix)
else:
j2cl_provider = j2cl_common.compile(ctx, exports=deps, artifact_suffix=artifact_suffix)
js = j2cl_common.get_jsinfo_provider(j2cl_provider)
return j2cl_proto_info(_private_=struct(j2cl_info=j2cl_provider, srcjar=jar_archive, runfiles=depset(js.srcs, transitive=transitive_runfiles)), js=js)
_j2cl_proto_library_aspect = aspect(implementation=_j2cl_proto_library_aspect_impl, required_aspect_providers=[ImmutableJspbInfo], attr_aspects=['deps'], provides=[J2clProtoInfo], attrs=dict(J2CL_TOOLCHAIN_ATTRS, **{'_j2cl_proto_implicit_deps': attr.label_list(default=[label('//third_party:gwt-jsinterop-annotations-j2cl'), label('//third_party:jsinterop-base-j2cl'), label('//third_party:j2cl_proto_runtime')]), '_protocol_compiler': attr.label(executable=True, cfg='host', default=label('//third_party:protocol_compiler')), '_protoc_gen_j2cl': attr.label(executable=True, cfg='host', default=label('//java/com/google/protobuf/contrib/j2cl/internal_do_not_use:J2CLProtobufCompiler')), '_jar': attr.label(executable=True, cfg='host', default=label('@bazel_tools//tools/jdk:jar')), '_google_java_formatter': attr.label(cfg='host', executable=True, default=label('//third_party:google_java_format'), allow_files=True)}), fragments=['java', 'js'])
def _j2cl_proto_library_rule_impl(ctx):
if len(ctx.attr.deps) != 1:
fail('Only one deps entry allowed')
j2cl_proto_info = ctx.attr.deps[0][J2clProtoInfo]
output = []
srcjar = j2cl_proto_info._private_.srcjar
if srcjar:
output = ctx.actions.declare_directory(ctx.label.name + '_for_testing_do_not_use')
ctx.actions.run_shell(inputs=[srcjar], outputs=[output], command='mkdir -p %s && ' % output.path + '%s x %s -d %s' % (ctx.executable._zip.path, srcjar.path, output.path), tools=[ctx.executable._zip])
output = [output]
runfiles = j2cl_proto_info._private_.runfiles
return j2cl_common.create_js_lib_struct(j2cl_info=j2cl_proto_info._private_.j2cl_info, extra_providers=[default_info(runfiles=ctx.runfiles(transitive_files=runfiles)), output_group_info(for_testing_do_not_use=output)])
new_j2cl_proto_library = rule(implementation=_j2cl_proto_library_rule_impl, attrs={'deps': attr.label_list(providers=[ProtoInfo], aspects=[immutable_js_proto_library_aspect, _j2cl_proto_library_aspect]), '_zip': attr.label(cfg='host', executable=True, default=label('@bazel_tools//tools/zip:zipper'))}, fragments=['js']) |
# Day 20: http://adventofcode.com/2016/day/20
inp = [(5, 8), (0, 2), (4, 7)]
def allowed(blocked, n):
rng, *blocked = sorted([*r] for r in blocked)
for cur in blocked:
if cur[0] > n:
break
elif cur[0] > rng[-1] + 1:
yield from range(rng[-1] + 1, cur[0])
rng = cur
else:
rng[-1] = max(rng[-1], cur[-1])
yield from range(rng[-1] + 1, n + 1)
if __name__ == '__main__':
ips = list(allowed(inp, 9))
print('There are', len(ips), 'allowed IPs:')
for i, x in enumerate(ips, start=1):
print(f'{i}) {x}')
| inp = [(5, 8), (0, 2), (4, 7)]
def allowed(blocked, n):
(rng, *blocked) = sorted(([*r] for r in blocked))
for cur in blocked:
if cur[0] > n:
break
elif cur[0] > rng[-1] + 1:
yield from range(rng[-1] + 1, cur[0])
rng = cur
else:
rng[-1] = max(rng[-1], cur[-1])
yield from range(rng[-1] + 1, n + 1)
if __name__ == '__main__':
ips = list(allowed(inp, 9))
print('There are', len(ips), 'allowed IPs:')
for (i, x) in enumerate(ips, start=1):
print(f'{i}) {x}') |
'''
Given a string s consisting of some words separated by some number of spaces, return the length of the last word in the string.
A word is a maximal substring consisting of non-space characters only.
Example 1:
Input: s = "Hello World"
Output: 5
Explanation: The last word is "World" with length 5.
Example 2:
Input: s = " fly me to the moon "
Output: 4
Explanation: The last word is "moon" with length 4.
Example 3:
Input: s = "luffy is still joyboy"
Output: 6
Explanation: The last word is "joyboy" with length 6.
Constraints:
1 <= s.length <= 104
s consists of only English letters and spaces ' '.
There will be at least one word in s.
'''
class Solution:
def lengthOfLastWord(self, s: str) -> int:
return len(list(s.strip().split(' '))[-1]) | """
Given a string s consisting of some words separated by some number of spaces, return the length of the last word in the string.
A word is a maximal substring consisting of non-space characters only.
Example 1:
Input: s = "Hello World"
Output: 5
Explanation: The last word is "World" with length 5.
Example 2:
Input: s = " fly me to the moon "
Output: 4
Explanation: The last word is "moon" with length 4.
Example 3:
Input: s = "luffy is still joyboy"
Output: 6
Explanation: The last word is "joyboy" with length 6.
Constraints:
1 <= s.length <= 104
s consists of only English letters and spaces ' '.
There will be at least one word in s.
"""
class Solution:
def length_of_last_word(self, s: str) -> int:
return len(list(s.strip().split(' '))[-1]) |
test = { 'name': 'q5_2',
'points': 1,
'suites': [ { 'cases': [ { 'code': '>>> # Hint: If you are getting 47 as your answer, you might be computing the biggest change rather than biggest decrease!;\n'
'>>> biggest_decrease != 47\n'
'True',
'hidden': False,
'locked': False},
{'code': '>>> # Hint: biggest decrease is above 30, but not 47;\n>>> 30 <= biggest_decrease < 47\nTrue', 'hidden': False, 'locked': False}],
'scored': True,
'setup': '',
'teardown': '',
'type': 'doctest'}]}
| test = {'name': 'q5_2', 'points': 1, 'suites': [{'cases': [{'code': '>>> # Hint: If you are getting 47 as your answer, you might be computing the biggest change rather than biggest decrease!;\n>>> biggest_decrease != 47\nTrue', 'hidden': False, 'locked': False}, {'code': '>>> # Hint: biggest decrease is above 30, but not 47;\n>>> 30 <= biggest_decrease < 47\nTrue', 'hidden': False, 'locked': False}], 'scored': True, 'setup': '', 'teardown': '', 'type': 'doctest'}]} |
def best_sum_tab(n, a):
table = [None for i in range(n + 1)]
table[0] = []
for i in range(n + 1):
if table[i] is not None:
for j in a:
if (i + j) < len(table):
temp = table[i] + [j]
if table[i + j] is None:
table[i + j] = temp
elif len(temp) < len(table[i + j]):
table[i + j] = temp
return table[n]
if __name__ == "__main__":
print(best_sum_tab(7, [5, 3, 4, 7]))
print(best_sum_tab(8, [2, 3, 5]))
print(best_sum_tab(8, [1, 4, 5]))
print(best_sum_tab(100, [1, 2, 5, 25]))
| def best_sum_tab(n, a):
table = [None for i in range(n + 1)]
table[0] = []
for i in range(n + 1):
if table[i] is not None:
for j in a:
if i + j < len(table):
temp = table[i] + [j]
if table[i + j] is None:
table[i + j] = temp
elif len(temp) < len(table[i + j]):
table[i + j] = temp
return table[n]
if __name__ == '__main__':
print(best_sum_tab(7, [5, 3, 4, 7]))
print(best_sum_tab(8, [2, 3, 5]))
print(best_sum_tab(8, [1, 4, 5]))
print(best_sum_tab(100, [1, 2, 5, 25])) |
if opt.save_every > 0 and num_updates % opt.save_every == -1 % opt.save_every:
valid_loss = self.eval(self.valid_data)
valid_ppl = math.exp(min(valid_loss, 100))
print('Validation perplexity: %g' % valid_ppl)
ep = float(epoch) - 1. + ((float(i) + 1.) / n_samples)
self.save(ep, valid_ppl, batch_order=batch_order, iteration=i) | if opt.save_every > 0 and num_updates % opt.save_every == -1 % opt.save_every:
valid_loss = self.eval(self.valid_data)
valid_ppl = math.exp(min(valid_loss, 100))
print('Validation perplexity: %g' % valid_ppl)
ep = float(epoch) - 1.0 + (float(i) + 1.0) / n_samples
self.save(ep, valid_ppl, batch_order=batch_order, iteration=i) |
FEATURES = set(
[
"five_prime_utr",
"three_prime_utr",
"CDS",
"exon",
"intron",
"start_codon",
"stop_codon",
"ncRNA",
]
)
NON_CODING_BIOTYPES = set(
[
"Mt_rRNA",
"Mt_tRNA",
"miRNA",
"misc_RNA",
"rRNA",
"scRNA",
"snRNA",
"snoRNA",
"ribozyme",
"sRNA",
"scaRNA",
"lncRNA",
"ncRNA",
"Mt_tRNA_pseudogene",
"tRNA_pseudogene",
"snoRNA_pseudogene",
"snRNA_pseudogene",
"scRNA_pseudogene",
"rRNA_pseudogene",
"misc_RNA_pseudogene",
"miRNA_pseudogene",
"non_coding",
"known_ncrna ",
"lincRNA ",
"macro_lncRNA ",
"3prime_overlapping_ncRNA",
"vault_RNA",
"vaultRNA",
"bidirectional_promoter_lncRNA",
]
)
| features = set(['five_prime_utr', 'three_prime_utr', 'CDS', 'exon', 'intron', 'start_codon', 'stop_codon', 'ncRNA'])
non_coding_biotypes = set(['Mt_rRNA', 'Mt_tRNA', 'miRNA', 'misc_RNA', 'rRNA', 'scRNA', 'snRNA', 'snoRNA', 'ribozyme', 'sRNA', 'scaRNA', 'lncRNA', 'ncRNA', 'Mt_tRNA_pseudogene', 'tRNA_pseudogene', 'snoRNA_pseudogene', 'snRNA_pseudogene', 'scRNA_pseudogene', 'rRNA_pseudogene', 'misc_RNA_pseudogene', 'miRNA_pseudogene', 'non_coding', 'known_ncrna ', 'lincRNA ', 'macro_lncRNA ', '3prime_overlapping_ncRNA', 'vault_RNA', 'vaultRNA', 'bidirectional_promoter_lncRNA']) |
# Runtime: 20 ms
# Beats 100% of Python submissions
class Solution(object):
def checkRecord(self, s):
"""
:type s: str
:rtype: bool
"""
if s.count("LLL") > 0:
return False
if s.count("A") > 2:
return False
return True
# A more worked out solution is:
# class Solution(object):
# def checkRecord(self, s):
# """
# :type s: str
# :rtype: bool
# """
# a_count = 0
# cons_p_count = 0
# for day in s:
# if day == 'A':
# a_count +=1
# if day == 'L':
# cons_p_count += 1
# else:
# cons_p_count = 0
# if a_count > 1:
# return False
# if cons_p_count > 2:
# return False
# return True | class Solution(object):
def check_record(self, s):
"""
:type s: str
:rtype: bool
"""
if s.count('LLL') > 0:
return False
if s.count('A') > 2:
return False
return True |
#Donald Hobson
#A program to make big letters out of small ones
#storeage of pattern to make large letters.
largeLetter=[[" A ",
" A A ",
" AAA ",
"A A",
"A A",],
["BBBB ",
"B B",
"BBBBB",
"B B",
"BBBB "],[
" cccc",
"c ",
"c ",
"c ",
" cccc",],[
"DDDD ",
"D D",
"D D",
"D D",
"DDDD "],[
"EEEEE",
"E ",
"EEEE ",
"E ",
"EEEEE"],[
"FFFFF",
"F ",
"FFFF ",
"F ",
"F "],[
" GGG ",
"G ",
"G GG",
"G G",
" GGG "],[
"H H",
"H H",
"HHHHH",
"H H",
"H H"],[
"IIIII",
" I ",
" I ",
" I ",
"IIIII"],[
" JJJJ",
" J ",
" J ",
" J ",
"JJJ "],[
"K K",
"K KK ",
"KK ",
"K KK ",
"K K"],[
"L ",
"L ",
"L ",
"L ",
"LLLLL"],[
"M M",
"MM MM",
"M M M",
"M M",
"M M"],[
"N N",
"NN N",
"N N N",
"N NN",
"N N"],[
" OOO ",
"O O",
"O O",
"O O",
" OOO "],[
"PPPP ",
"P P",
"PPPP ",
"P ",
"P "],[
" QQ ",
"Q Q ",
"Q QQ ",
"Q Q ",
" QQ Q"],[
"RRRR ",
"R R",
"RRRR ",
"R R ",
"R R"],[
" SSSS",
"S ",
" SSS ",
" S",
"SSSS "],[
"TTTTT",
" T ",
" T ",
" T ",
" T "],[
"U U",
"U U",
"U U",
"U U",
" UUU "],[
"V V",
"V V",
" V V ",
" V V ",
" V "],[
"W W",
"W W",
"W W",
"W W W",
" W W "],[
"X X",
" X X ",
" X ",
" X X ",
"X X"],[
"Y Y",
" Y Y ",
" Y ",
" Y ",
" Y "],[
"ZZZZZ",
" Z ",
" Z ",
" Z ",
"ZZZZZ"]]
# Outer loop, For repeating whle process
while True:
largeText=input("Large Text>").upper()
while True:
method=input("Calital \"C\" , Lowercase \"L\" or Subtext \"S\" >").upper()
if method=="C"or method=="L":
break
if method=="S":
subtext=""
while len(subtext)==0:
subtext=input("Subtext is >")
positionInSubtext=0
subtextLength=len(subtext)
break
largeTextSections=[]
print()
while len(largeText)>19:
largeTextSections.append(largeText[:19])
largeText=largeText[19:]
if len(largeText)>0:
largeTextSections.append(largeText)
for section in largeTextSections:
for i in range(5):
string=""
for line in section:
if line==" ":
string+=" "*5
else:
if method=="S":
for character in range (5):
newstr=largeLetter[ord(line)-65][i]
if largeLetter[ord(line)-65][i][character]==" ":
string+=" "
else:
string+=subtext[positionInSubtext]
positionInSubtext=(positionInSubtext+1)%subtextLength
elif method=="L":
string+=largeLetter[ord(line)-65][i].lower()
else:
string+=largeLetter[ord(line)-65][i]
string+=" "
print(string)
print("\n")
if input("Do you wish to exit \"Y\"/\"N\" >").upper() =="Y":
break
| large_letter = [[' A ', ' A A ', ' AAA ', 'A A', 'A A'], ['BBBB ', 'B B', 'BBBBB', 'B B', 'BBBB '], [' cccc', 'c ', 'c ', 'c ', ' cccc'], ['DDDD ', 'D D', 'D D', 'D D', 'DDDD '], ['EEEEE', 'E ', 'EEEE ', 'E ', 'EEEEE'], ['FFFFF', 'F ', 'FFFF ', 'F ', 'F '], [' GGG ', 'G ', 'G GG', 'G G', ' GGG '], ['H H', 'H H', 'HHHHH', 'H H', 'H H'], ['IIIII', ' I ', ' I ', ' I ', 'IIIII'], [' JJJJ', ' J ', ' J ', ' J ', 'JJJ '], ['K K', 'K KK ', 'KK ', 'K KK ', 'K K'], ['L ', 'L ', 'L ', 'L ', 'LLLLL'], ['M M', 'MM MM', 'M M M', 'M M', 'M M'], ['N N', 'NN N', 'N N N', 'N NN', 'N N'], [' OOO ', 'O O', 'O O', 'O O', ' OOO '], ['PPPP ', 'P P', 'PPPP ', 'P ', 'P '], [' QQ ', 'Q Q ', 'Q QQ ', 'Q Q ', ' QQ Q'], ['RRRR ', 'R R', 'RRRR ', 'R R ', 'R R'], [' SSSS', 'S ', ' SSS ', ' S', 'SSSS '], ['TTTTT', ' T ', ' T ', ' T ', ' T '], ['U U', 'U U', 'U U', 'U U', ' UUU '], ['V V', 'V V', ' V V ', ' V V ', ' V '], ['W W', 'W W', 'W W', 'W W W', ' W W '], ['X X', ' X X ', ' X ', ' X X ', 'X X'], ['Y Y', ' Y Y ', ' Y ', ' Y ', ' Y '], ['ZZZZZ', ' Z ', ' Z ', ' Z ', 'ZZZZZ']]
while True:
large_text = input('Large Text>').upper()
while True:
method = input('Calital "C" , Lowercase "L" or Subtext "S" >').upper()
if method == 'C' or method == 'L':
break
if method == 'S':
subtext = ''
while len(subtext) == 0:
subtext = input('Subtext is >')
position_in_subtext = 0
subtext_length = len(subtext)
break
large_text_sections = []
print()
while len(largeText) > 19:
largeTextSections.append(largeText[:19])
large_text = largeText[19:]
if len(largeText) > 0:
largeTextSections.append(largeText)
for section in largeTextSections:
for i in range(5):
string = ''
for line in section:
if line == ' ':
string += ' ' * 5
else:
if method == 'S':
for character in range(5):
newstr = largeLetter[ord(line) - 65][i]
if largeLetter[ord(line) - 65][i][character] == ' ':
string += ' '
else:
string += subtext[positionInSubtext]
position_in_subtext = (positionInSubtext + 1) % subtextLength
elif method == 'L':
string += largeLetter[ord(line) - 65][i].lower()
else:
string += largeLetter[ord(line) - 65][i]
string += ' '
print(string)
print('\n')
if input('Do you wish to exit "Y"/"N" >').upper() == 'Y':
break |
EGAUGE_API_URLS = {
'stored' : 'http://%s.egaug.es/cgi-bin/egauge-show',
'instantaneous' : 'http://%s.egaug.es/cgi-bin/egauge',
}
| egauge_api_urls = {'stored': 'http://%s.egaug.es/cgi-bin/egauge-show', 'instantaneous': 'http://%s.egaug.es/cgi-bin/egauge'} |
t = int(input())
for i in range(t):
n=int(input())
l=0
h=100000
while l<=h:
mid =(l+h)//2
r= (mid*(mid+1))//2
if r>n:
h=mid - 1
else:
ht=mid
l=mid+1
print(ht)
| t = int(input())
for i in range(t):
n = int(input())
l = 0
h = 100000
while l <= h:
mid = (l + h) // 2
r = mid * (mid + 1) // 2
if r > n:
h = mid - 1
else:
ht = mid
l = mid + 1
print(ht) |
"""
Hello world application.
Mostly just to test the Python setup on current computer.
"""
MESSSAGE = "Hello World"
print(MESSSAGE)
| """
Hello world application.
Mostly just to test the Python setup on current computer.
"""
messsage = 'Hello World'
print(MESSSAGE) |
class Solution:
def singleNumber(self, nums: List[int]) -> List[int]:
dict_val = {}
result1 = []
result2 = []
for val in nums:
dict_val[val] = dict_val.get(val, 0) + 1
if dict_val[val] > 1:
result1.append(val)
else:
result2.append(val)
return set(result2)-set(result1)
class Solution:
def singleNumber(self, nums: List[int]) -> List[int]:
dict_val = {}
result1 = []
result2 = []
for val in nums:
dict_val[val] = dict_val.get(val, 0) + 1
return [k for k, v in sorted(dict_val.items(), key=lambda item: item[1])][:2]
| class Solution:
def single_number(self, nums: List[int]) -> List[int]:
dict_val = {}
result1 = []
result2 = []
for val in nums:
dict_val[val] = dict_val.get(val, 0) + 1
if dict_val[val] > 1:
result1.append(val)
else:
result2.append(val)
return set(result2) - set(result1)
class Solution:
def single_number(self, nums: List[int]) -> List[int]:
dict_val = {}
result1 = []
result2 = []
for val in nums:
dict_val[val] = dict_val.get(val, 0) + 1
return [k for (k, v) in sorted(dict_val.items(), key=lambda item: item[1])][:2] |
# (c) 2012-2019, Ansible by Red Hat
#
# This file is part of Ansible Galaxy
#
# Ansible Galaxy is free software: you can redistribute it and/or modify
# it under the terms of the Apache License as published by
# the Apache Software Foundation, either version 2 of the License, or
# (at your option) any later version.
#
# Ansible Galaxy is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# Apache License for more details.
#
# You should have received a copy of the Apache License
# along with Galaxy. If not, see <http://www.apache.org/licenses/>.
SURVEY_FIElDS = (
'docs',
'ease_of_use',
'does_what_it_says',
'works_as_is',
'used_in_production',
)
def calculate_survey_score(surveys):
'''
:var surveys: queryset container all of the surveys for a collection or a
repository
'''
score = 0
answer_count = 0
survey_score = 0.0
for survey in surveys:
for k in SURVEY_FIElDS:
data = getattr(survey, k)
if data is not None:
answer_count += 1
survey_score += (data - 1) / 4
# Average and convert to 0-5 scale
score = (survey_score / answer_count) * 5
return score
| survey_fi_el_ds = ('docs', 'ease_of_use', 'does_what_it_says', 'works_as_is', 'used_in_production')
def calculate_survey_score(surveys):
"""
:var surveys: queryset container all of the surveys for a collection or a
repository
"""
score = 0
answer_count = 0
survey_score = 0.0
for survey in surveys:
for k in SURVEY_FIElDS:
data = getattr(survey, k)
if data is not None:
answer_count += 1
survey_score += (data - 1) / 4
score = survey_score / answer_count * 5
return score |
__author__ = 'arid6405'
class SfcsmError(Exception):
def __init__(self, status, message):
self.status = status
self.message = message
def __str__(self):
return "Error {}: {} ".format(self.status, self.message) | __author__ = 'arid6405'
class Sfcsmerror(Exception):
def __init__(self, status, message):
self.status = status
self.message = message
def __str__(self):
return 'Error {}: {} '.format(self.status, self.message) |
"""
The core calculation, ``work_hours+hol_hours- 13*7.4``,
translates as 'the total number of hours minus the number
of mandatory leave days times by the number of hours in the
average working day, which is :math:`\\frac{37}{5}=7.4`, which
altogether gives the total number of hours available to be worked.
Dividing this number by 37 gives the number of weeks in the year
that can be worked, which is a key figure in working out space requirements.
"""
def definition():
"""
Calculates the number of weeks actually workable, accounting for
universal mandatory leave (bank holidays and efficiency days).
"""
sql = """
SELECT *, (work_hours+hol_hours- 13*7.4)/37 as open_weeks
FROM staff_con_type_hours
"""
return sql | """
The core calculation, ``work_hours+hol_hours- 13*7.4``,
translates as 'the total number of hours minus the number
of mandatory leave days times by the number of hours in the
average working day, which is :math:`\\frac{37}{5}=7.4`, which
altogether gives the total number of hours available to be worked.
Dividing this number by 37 gives the number of weeks in the year
that can be worked, which is a key figure in working out space requirements.
"""
def definition():
"""
Calculates the number of weeks actually workable, accounting for
universal mandatory leave (bank holidays and efficiency days).
"""
sql = '\nSELECT *, (work_hours+hol_hours- 13*7.4)/37 as open_weeks\nFROM staff_con_type_hours\n'
return sql |
def decode(s):
dec = dict()
def dec_pos(x,e):
for i in range(x+1):
e=dec[e]
return e
for i in range(32,127):
dec[encode(chr(i))] = chr(i)
a=''
for index,value in enumerate(s):
a+=dec_pos(index,value)
return a | def decode(s):
dec = dict()
def dec_pos(x, e):
for i in range(x + 1):
e = dec[e]
return e
for i in range(32, 127):
dec[encode(chr(i))] = chr(i)
a = ''
for (index, value) in enumerate(s):
a += dec_pos(index, value)
return a |
print("---------- numero de discos ----------")
def hanoi(n, source, helper, target):
if n > 0:
# move tower of size n - 1 to helper:
hanoi(n - 1, source, target, helper)
print(source, helper, target)
# move disk from source peg to target peg
if source:
target.append(source.pop())
print(source, helper, target)
# move tower of size n-1 from helper to target
hanoi(n - 1, helper, source, target)
print(source, helper, target)
source = [5, 4, 3, 2, 1]
target = []
helper = []
hanoi(len(source), source, helper, target)
print(source, helper, target)
| print('---------- numero de discos ----------')
def hanoi(n, source, helper, target):
if n > 0:
hanoi(n - 1, source, target, helper)
print(source, helper, target)
if source:
target.append(source.pop())
print(source, helper, target)
hanoi(n - 1, helper, source, target)
print(source, helper, target)
source = [5, 4, 3, 2, 1]
target = []
helper = []
hanoi(len(source), source, helper, target)
print(source, helper, target) |
class Solution(object):
def rangeBitwiseAnd(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
k = 0
while n != m:
n >>= 1
m >>= 1
k += 1
return n << k
| class Solution(object):
def range_bitwise_and(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
k = 0
while n != m:
n >>= 1
m >>= 1
k += 1
return n << k |
__author__ = 'schlitzer'
__all__ = [
'AdminError',
'AlreadyAuthenticatedError',
'AuthenticationError',
'BaseError',
'CredentialError',
'DuplicateResource',
'FlowError',
'InvalidBody',
'InvalidFields',
'InvalidName',
'InvalidPaginationLimit',
'InvalidParameterValue',
'InvalidSelectors',
'InvalidSortCriteria',
'InvalidUUID',
'ModelError',
'MongoConnError',
'PeerReceiverCredentialError',
'PermError',
'ResourceNotFound',
'ResourceInUse',
'SessionError',
'SessionCredentialError',
'StaticPathDisabledError',
'ValidationError'
]
class BaseError(Exception):
def __init__(self, status, code, msg):
super().__init__()
self.status = status
self.msg = msg
self.code = code
self.err_rsp = {'errors': [{
"id": self.code,
"details": self.msg,
"title": self.msg
}]}
class AAError(BaseError):
def __init__(self, status=403, code=1000, msg=None):
super().__init__(status, code, msg)
class ModelError(BaseError):
def __init__(self, status=None, code=2000, msg=None):
super().__init__(status, code, msg)
class ValidationError(BaseError):
def __init__(self, status=None, code=3000, msg=None):
super().__init__(status, code, msg)
class FeatureError(BaseError):
def __init__(self, status=None, code=4000, msg=None):
super().__init__(status, code, msg)
class BackEndError(BaseError):
def __init__(self, status=None, code=5000, msg=None):
super().__init__(status, code, msg)
class AuthenticationError(ModelError):
def __init__(self):
super().__init__(
status=403,
code=1001,
msg="Invalid username or Password"
)
class CredentialError(ModelError):
def __init__(self):
super().__init__(
status=401,
code=1002,
msg="Invalid Credentials"
)
class AlreadyAuthenticatedError(ModelError):
def __init__(self):
super().__init__(
status=403,
code=1003,
msg="Already authenticated"
)
class SessionError(ModelError):
def __init__(self):
super().__init__(
status=403,
code=1004,
msg="Invalid or expired session"
)
class PermError(ModelError):
def __init__(self, msg):
super().__init__(
status=403,
code=1005,
msg=msg
)
class SessionCredentialError(ModelError):
def __init__(self):
super().__init__(
status=403,
code=1006,
msg="Neither valid Session or Credentials available"
)
class AdminError(ModelError):
def __init__(self):
super().__init__(
status=403,
code=1007,
msg="Root admin privilege needed for this resource"
)
class PeerReceiverCredentialError(ModelError):
def __init__(self):
super().__init__(
status=403,
code=1008,
msg="Receiver credentials needed for this resource"
)
class ResourceNotFound(ModelError):
def __init__(self, resource):
super().__init__(
status=404,
code=2001,
msg="Resource not found: {0}".format(resource)
)
class DuplicateResource(ModelError):
def __init__(self, resource):
super().__init__(
status=400,
code=2002,
msg="Duplicate Resource: {0}".format(resource)
)
class InvalidBody(ValidationError):
def __init__(self, err):
super().__init__(
status=400,
code=3001,
msg="Invalid post body: {0}".format(err)
)
class InvalidFields(ValidationError):
def __init__(self, err):
super().__init__(
status=400,
code=3003,
msg="Invalid field selection: {0}".format(err)
)
class InvalidSelectors(ValidationError):
def __init__(self, err):
super().__init__(
status=400,
code=3004,
msg="Invalid selection: {0}".format(err)
)
class InvalidPaginationLimit(ValidationError):
def __init__(self, err):
super().__init__(
status=400,
code=3005,
msg="Invalid pagination limit, has to be one of: {0}".format(err)
)
class InvalidSortCriteria(ValidationError):
def __init__(self, err):
super().__init__(
status=400,
code=3006,
msg="Invalid sort criteria: {0}".format(err)
)
class InvalidParameterValue(ValidationError):
def __init__(self, err):
super().__init__(
status=400,
code=3007,
msg="Invalid parameter value: {0}".format(err)
)
class InvalidUUID(ValidationError):
def __init__(self, err):
super().__init__(
status=400,
code=3008,
msg="Invalid uuid: {0}".format(err)
)
class InvalidName(ValidationError):
def __init__(self, err):
super().__init__(
status=400,
code=3009,
msg="Invalid Name: {0}".format(err)
)
class ResourceInUse(ValidationError):
def __init__(self, err):
super().__init__(
status=400,
code=3010,
msg="Resource is still used: {0}".format(err)
)
class FlowError(ValidationError):
def __init__(self, err):
super().__init__(
status=400,
code=3011,
msg="Flow Error: {0}".format(err)
)
class StaticPathDisabledError(FeatureError):
def __init__(self):
super().__init__(
status=400,
code=4002,
msg="Static path feature is disabled"
)
class MongoConnError(BackEndError):
def __init__(self, err):
super().__init__(
status=500,
code=5001,
msg="MongoDB connection error: {0}".format(err)
)
class RedisConnError(BackEndError):
def __init__(self, err):
super().__init__(
status=500,
code=5002,
msg="Redis connection error: {0}".format(err)
)
| __author__ = 'schlitzer'
__all__ = ['AdminError', 'AlreadyAuthenticatedError', 'AuthenticationError', 'BaseError', 'CredentialError', 'DuplicateResource', 'FlowError', 'InvalidBody', 'InvalidFields', 'InvalidName', 'InvalidPaginationLimit', 'InvalidParameterValue', 'InvalidSelectors', 'InvalidSortCriteria', 'InvalidUUID', 'ModelError', 'MongoConnError', 'PeerReceiverCredentialError', 'PermError', 'ResourceNotFound', 'ResourceInUse', 'SessionError', 'SessionCredentialError', 'StaticPathDisabledError', 'ValidationError']
class Baseerror(Exception):
def __init__(self, status, code, msg):
super().__init__()
self.status = status
self.msg = msg
self.code = code
self.err_rsp = {'errors': [{'id': self.code, 'details': self.msg, 'title': self.msg}]}
class Aaerror(BaseError):
def __init__(self, status=403, code=1000, msg=None):
super().__init__(status, code, msg)
class Modelerror(BaseError):
def __init__(self, status=None, code=2000, msg=None):
super().__init__(status, code, msg)
class Validationerror(BaseError):
def __init__(self, status=None, code=3000, msg=None):
super().__init__(status, code, msg)
class Featureerror(BaseError):
def __init__(self, status=None, code=4000, msg=None):
super().__init__(status, code, msg)
class Backenderror(BaseError):
def __init__(self, status=None, code=5000, msg=None):
super().__init__(status, code, msg)
class Authenticationerror(ModelError):
def __init__(self):
super().__init__(status=403, code=1001, msg='Invalid username or Password')
class Credentialerror(ModelError):
def __init__(self):
super().__init__(status=401, code=1002, msg='Invalid Credentials')
class Alreadyauthenticatederror(ModelError):
def __init__(self):
super().__init__(status=403, code=1003, msg='Already authenticated')
class Sessionerror(ModelError):
def __init__(self):
super().__init__(status=403, code=1004, msg='Invalid or expired session')
class Permerror(ModelError):
def __init__(self, msg):
super().__init__(status=403, code=1005, msg=msg)
class Sessioncredentialerror(ModelError):
def __init__(self):
super().__init__(status=403, code=1006, msg='Neither valid Session or Credentials available')
class Adminerror(ModelError):
def __init__(self):
super().__init__(status=403, code=1007, msg='Root admin privilege needed for this resource')
class Peerreceivercredentialerror(ModelError):
def __init__(self):
super().__init__(status=403, code=1008, msg='Receiver credentials needed for this resource')
class Resourcenotfound(ModelError):
def __init__(self, resource):
super().__init__(status=404, code=2001, msg='Resource not found: {0}'.format(resource))
class Duplicateresource(ModelError):
def __init__(self, resource):
super().__init__(status=400, code=2002, msg='Duplicate Resource: {0}'.format(resource))
class Invalidbody(ValidationError):
def __init__(self, err):
super().__init__(status=400, code=3001, msg='Invalid post body: {0}'.format(err))
class Invalidfields(ValidationError):
def __init__(self, err):
super().__init__(status=400, code=3003, msg='Invalid field selection: {0}'.format(err))
class Invalidselectors(ValidationError):
def __init__(self, err):
super().__init__(status=400, code=3004, msg='Invalid selection: {0}'.format(err))
class Invalidpaginationlimit(ValidationError):
def __init__(self, err):
super().__init__(status=400, code=3005, msg='Invalid pagination limit, has to be one of: {0}'.format(err))
class Invalidsortcriteria(ValidationError):
def __init__(self, err):
super().__init__(status=400, code=3006, msg='Invalid sort criteria: {0}'.format(err))
class Invalidparametervalue(ValidationError):
def __init__(self, err):
super().__init__(status=400, code=3007, msg='Invalid parameter value: {0}'.format(err))
class Invaliduuid(ValidationError):
def __init__(self, err):
super().__init__(status=400, code=3008, msg='Invalid uuid: {0}'.format(err))
class Invalidname(ValidationError):
def __init__(self, err):
super().__init__(status=400, code=3009, msg='Invalid Name: {0}'.format(err))
class Resourceinuse(ValidationError):
def __init__(self, err):
super().__init__(status=400, code=3010, msg='Resource is still used: {0}'.format(err))
class Flowerror(ValidationError):
def __init__(self, err):
super().__init__(status=400, code=3011, msg='Flow Error: {0}'.format(err))
class Staticpathdisablederror(FeatureError):
def __init__(self):
super().__init__(status=400, code=4002, msg='Static path feature is disabled')
class Mongoconnerror(BackEndError):
def __init__(self, err):
super().__init__(status=500, code=5001, msg='MongoDB connection error: {0}'.format(err))
class Redisconnerror(BackEndError):
def __init__(self, err):
super().__init__(status=500, code=5002, msg='Redis connection error: {0}'.format(err)) |
class Solution:
def twoSum(self, nums: [int], target: int) -> [int]:
d = {int: int}
for i in range(len(nums)):
if target - nums[i] in d:
return [d[target-nums[i]], i]
else:
d[nums[i]] = i
return []
if __name__ == "__main__":
solution = Solution()
print(solution.twoSum([2, 7, 11, 15], 9)) | class Solution:
def two_sum(self, nums: [int], target: int) -> [int]:
d = {int: int}
for i in range(len(nums)):
if target - nums[i] in d:
return [d[target - nums[i]], i]
else:
d[nums[i]] = i
return []
if __name__ == '__main__':
solution = solution()
print(solution.twoSum([2, 7, 11, 15], 9)) |
#
# PySNMP MIB module HH3C-VSI-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HH3C-VSI-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:15:32 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, ConstraintsIntersection, ValueSizeConstraint, SingleValueConstraint, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "ConstraintsIntersection", "ValueSizeConstraint", "SingleValueConstraint", "ValueRangeConstraint")
hh3cCommon, = mibBuilder.importSymbols("HH3C-OID-MIB", "hh3cCommon")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
MibIdentifier, NotificationType, ObjectIdentity, Unsigned32, Bits, IpAddress, Counter64, iso, MibScalar, MibTable, MibTableRow, MibTableColumn, Counter32, Gauge32, ModuleIdentity, TimeTicks, Integer32 = mibBuilder.importSymbols("SNMPv2-SMI", "MibIdentifier", "NotificationType", "ObjectIdentity", "Unsigned32", "Bits", "IpAddress", "Counter64", "iso", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Counter32", "Gauge32", "ModuleIdentity", "TimeTicks", "Integer32")
RowStatus, DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "RowStatus", "DisplayString", "TextualConvention")
hh3cVsi = ModuleIdentity((1, 3, 6, 1, 4, 1, 25506, 2, 105))
hh3cVsi.setRevisions(('2009-08-08 10:00',))
if mibBuilder.loadTexts: hh3cVsi.setLastUpdated('200908081000Z')
if mibBuilder.loadTexts: hh3cVsi.setOrganization('Hangzhou H3C Tech. Co., Ltd.')
hh3cVsiObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 25506, 2, 105, 1))
hh3cVsiScalarGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 25506, 2, 105, 1, 1))
hh3cVsiNextAvailableVsiIndex = MibScalar((1, 3, 6, 1, 4, 1, 25506, 2, 105, 1, 1, 1), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hh3cVsiNextAvailableVsiIndex.setStatus('current')
hh3cVsiTable = MibTable((1, 3, 6, 1, 4, 1, 25506, 2, 105, 1, 2), )
if mibBuilder.loadTexts: hh3cVsiTable.setStatus('current')
hh3cVsiEntry = MibTableRow((1, 3, 6, 1, 4, 1, 25506, 2, 105, 1, 2, 1), ).setIndexNames((0, "HH3C-VSI-MIB", "hh3cVsiIndex"))
if mibBuilder.loadTexts: hh3cVsiEntry.setStatus('current')
hh3cVsiIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 105, 1, 2, 1, 1), Unsigned32())
if mibBuilder.loadTexts: hh3cVsiIndex.setStatus('current')
hh3cVsiName = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 105, 1, 2, 1, 2), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 31))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hh3cVsiName.setStatus('current')
hh3cVsiMode = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 105, 1, 2, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("martini", 1), ("minm", 2), ("martiniAndMinm", 3), ("kompella", 4), ("kompellaAndMinm", 5)))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hh3cVsiMode.setStatus('current')
hh3cMinmIsid = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 105, 1, 2, 1, 4), Integer32()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hh3cMinmIsid.setStatus('current')
hh3cVsiId = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 105, 1, 2, 1, 5), Unsigned32()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hh3cVsiId.setStatus('current')
hh3cVsiTransMode = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 105, 1, 2, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("vlan", 1), ("ethernet", 2)))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hh3cVsiTransMode.setStatus('current')
hh3cVsiEnableHubSpoke = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 105, 1, 2, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("disable", 1), ("enable", 2)))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hh3cVsiEnableHubSpoke.setStatus('current')
hh3cVsiAdminState = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 105, 1, 2, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("adminUp", 1), ("adminDown", 2)))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hh3cVsiAdminState.setStatus('current')
hh3cVsiRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 105, 1, 2, 1, 9), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hh3cVsiRowStatus.setStatus('current')
hh3cVsiXconnectTable = MibTable((1, 3, 6, 1, 4, 1, 25506, 2, 105, 1, 3), )
if mibBuilder.loadTexts: hh3cVsiXconnectTable.setStatus('current')
hh3cVsiXconnectEntry = MibTableRow((1, 3, 6, 1, 4, 1, 25506, 2, 105, 1, 3, 1), ).setIndexNames((0, "HH3C-VSI-MIB", "hh3cVsiXconnectIfIndex"), (0, "HH3C-VSI-MIB", "hh3cVsiXconnectEvcSrvInstId"))
if mibBuilder.loadTexts: hh3cVsiXconnectEntry.setStatus('current')
hh3cVsiXconnectIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 105, 1, 3, 1, 1), Unsigned32())
if mibBuilder.loadTexts: hh3cVsiXconnectIfIndex.setStatus('current')
hh3cVsiXconnectEvcSrvInstId = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 105, 1, 3, 1, 2), Unsigned32())
if mibBuilder.loadTexts: hh3cVsiXconnectEvcSrvInstId.setStatus('current')
hh3cVsiXconnectVsiName = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 105, 1, 3, 1, 3), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 31))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hh3cVsiXconnectVsiName.setStatus('current')
hh3cVsiXconnectAccessMode = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 105, 1, 3, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("vlan", 1), ("ethernet", 2)))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hh3cVsiXconnectAccessMode.setStatus('current')
hh3cVsiXconnectHubSpoke = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 105, 1, 3, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("none", 1), ("hub", 2), ("spoke", 3)))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hh3cVsiXconnectHubSpoke.setStatus('current')
hh3cVsiXconnectRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 25506, 2, 105, 1, 3, 1, 6), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hh3cVsiXconnectRowStatus.setStatus('current')
mibBuilder.exportSymbols("HH3C-VSI-MIB", hh3cVsiMode=hh3cVsiMode, hh3cMinmIsid=hh3cMinmIsid, hh3cVsi=hh3cVsi, hh3cVsiXconnectAccessMode=hh3cVsiXconnectAccessMode, hh3cVsiXconnectRowStatus=hh3cVsiXconnectRowStatus, hh3cVsiXconnectHubSpoke=hh3cVsiXconnectHubSpoke, hh3cVsiEntry=hh3cVsiEntry, hh3cVsiObjects=hh3cVsiObjects, hh3cVsiNextAvailableVsiIndex=hh3cVsiNextAvailableVsiIndex, hh3cVsiTransMode=hh3cVsiTransMode, hh3cVsiXconnectVsiName=hh3cVsiXconnectVsiName, hh3cVsiAdminState=hh3cVsiAdminState, hh3cVsiIndex=hh3cVsiIndex, hh3cVsiScalarGroup=hh3cVsiScalarGroup, hh3cVsiId=hh3cVsiId, hh3cVsiRowStatus=hh3cVsiRowStatus, PYSNMP_MODULE_ID=hh3cVsi, hh3cVsiName=hh3cVsiName, hh3cVsiEnableHubSpoke=hh3cVsiEnableHubSpoke, hh3cVsiTable=hh3cVsiTable, hh3cVsiXconnectEntry=hh3cVsiXconnectEntry, hh3cVsiXconnectEvcSrvInstId=hh3cVsiXconnectEvcSrvInstId, hh3cVsiXconnectIfIndex=hh3cVsiXconnectIfIndex, hh3cVsiXconnectTable=hh3cVsiXconnectTable)
| (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, constraints_intersection, value_size_constraint, single_value_constraint, value_range_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsUnion', 'ConstraintsIntersection', 'ValueSizeConstraint', 'SingleValueConstraint', 'ValueRangeConstraint')
(hh3c_common,) = mibBuilder.importSymbols('HH3C-OID-MIB', 'hh3cCommon')
(module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup')
(mib_identifier, notification_type, object_identity, unsigned32, bits, ip_address, counter64, iso, mib_scalar, mib_table, mib_table_row, mib_table_column, counter32, gauge32, module_identity, time_ticks, integer32) = mibBuilder.importSymbols('SNMPv2-SMI', 'MibIdentifier', 'NotificationType', 'ObjectIdentity', 'Unsigned32', 'Bits', 'IpAddress', 'Counter64', 'iso', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'Counter32', 'Gauge32', 'ModuleIdentity', 'TimeTicks', 'Integer32')
(row_status, display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'RowStatus', 'DisplayString', 'TextualConvention')
hh3c_vsi = module_identity((1, 3, 6, 1, 4, 1, 25506, 2, 105))
hh3cVsi.setRevisions(('2009-08-08 10:00',))
if mibBuilder.loadTexts:
hh3cVsi.setLastUpdated('200908081000Z')
if mibBuilder.loadTexts:
hh3cVsi.setOrganization('Hangzhou H3C Tech. Co., Ltd.')
hh3c_vsi_objects = mib_identifier((1, 3, 6, 1, 4, 1, 25506, 2, 105, 1))
hh3c_vsi_scalar_group = mib_identifier((1, 3, 6, 1, 4, 1, 25506, 2, 105, 1, 1))
hh3c_vsi_next_available_vsi_index = mib_scalar((1, 3, 6, 1, 4, 1, 25506, 2, 105, 1, 1, 1), unsigned32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
hh3cVsiNextAvailableVsiIndex.setStatus('current')
hh3c_vsi_table = mib_table((1, 3, 6, 1, 4, 1, 25506, 2, 105, 1, 2))
if mibBuilder.loadTexts:
hh3cVsiTable.setStatus('current')
hh3c_vsi_entry = mib_table_row((1, 3, 6, 1, 4, 1, 25506, 2, 105, 1, 2, 1)).setIndexNames((0, 'HH3C-VSI-MIB', 'hh3cVsiIndex'))
if mibBuilder.loadTexts:
hh3cVsiEntry.setStatus('current')
hh3c_vsi_index = mib_table_column((1, 3, 6, 1, 4, 1, 25506, 2, 105, 1, 2, 1, 1), unsigned32())
if mibBuilder.loadTexts:
hh3cVsiIndex.setStatus('current')
hh3c_vsi_name = mib_table_column((1, 3, 6, 1, 4, 1, 25506, 2, 105, 1, 2, 1, 2), octet_string().subtype(subtypeSpec=value_size_constraint(1, 31))).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
hh3cVsiName.setStatus('current')
hh3c_vsi_mode = mib_table_column((1, 3, 6, 1, 4, 1, 25506, 2, 105, 1, 2, 1, 3), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4, 5))).clone(namedValues=named_values(('martini', 1), ('minm', 2), ('martiniAndMinm', 3), ('kompella', 4), ('kompellaAndMinm', 5)))).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
hh3cVsiMode.setStatus('current')
hh3c_minm_isid = mib_table_column((1, 3, 6, 1, 4, 1, 25506, 2, 105, 1, 2, 1, 4), integer32()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
hh3cMinmIsid.setStatus('current')
hh3c_vsi_id = mib_table_column((1, 3, 6, 1, 4, 1, 25506, 2, 105, 1, 2, 1, 5), unsigned32()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
hh3cVsiId.setStatus('current')
hh3c_vsi_trans_mode = mib_table_column((1, 3, 6, 1, 4, 1, 25506, 2, 105, 1, 2, 1, 6), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('vlan', 1), ('ethernet', 2)))).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
hh3cVsiTransMode.setStatus('current')
hh3c_vsi_enable_hub_spoke = mib_table_column((1, 3, 6, 1, 4, 1, 25506, 2, 105, 1, 2, 1, 7), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('disable', 1), ('enable', 2)))).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
hh3cVsiEnableHubSpoke.setStatus('current')
hh3c_vsi_admin_state = mib_table_column((1, 3, 6, 1, 4, 1, 25506, 2, 105, 1, 2, 1, 8), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('adminUp', 1), ('adminDown', 2)))).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
hh3cVsiAdminState.setStatus('current')
hh3c_vsi_row_status = mib_table_column((1, 3, 6, 1, 4, 1, 25506, 2, 105, 1, 2, 1, 9), row_status()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
hh3cVsiRowStatus.setStatus('current')
hh3c_vsi_xconnect_table = mib_table((1, 3, 6, 1, 4, 1, 25506, 2, 105, 1, 3))
if mibBuilder.loadTexts:
hh3cVsiXconnectTable.setStatus('current')
hh3c_vsi_xconnect_entry = mib_table_row((1, 3, 6, 1, 4, 1, 25506, 2, 105, 1, 3, 1)).setIndexNames((0, 'HH3C-VSI-MIB', 'hh3cVsiXconnectIfIndex'), (0, 'HH3C-VSI-MIB', 'hh3cVsiXconnectEvcSrvInstId'))
if mibBuilder.loadTexts:
hh3cVsiXconnectEntry.setStatus('current')
hh3c_vsi_xconnect_if_index = mib_table_column((1, 3, 6, 1, 4, 1, 25506, 2, 105, 1, 3, 1, 1), unsigned32())
if mibBuilder.loadTexts:
hh3cVsiXconnectIfIndex.setStatus('current')
hh3c_vsi_xconnect_evc_srv_inst_id = mib_table_column((1, 3, 6, 1, 4, 1, 25506, 2, 105, 1, 3, 1, 2), unsigned32())
if mibBuilder.loadTexts:
hh3cVsiXconnectEvcSrvInstId.setStatus('current')
hh3c_vsi_xconnect_vsi_name = mib_table_column((1, 3, 6, 1, 4, 1, 25506, 2, 105, 1, 3, 1, 3), octet_string().subtype(subtypeSpec=value_size_constraint(1, 31))).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
hh3cVsiXconnectVsiName.setStatus('current')
hh3c_vsi_xconnect_access_mode = mib_table_column((1, 3, 6, 1, 4, 1, 25506, 2, 105, 1, 3, 1, 4), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('vlan', 1), ('ethernet', 2)))).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
hh3cVsiXconnectAccessMode.setStatus('current')
hh3c_vsi_xconnect_hub_spoke = mib_table_column((1, 3, 6, 1, 4, 1, 25506, 2, 105, 1, 3, 1, 5), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('none', 1), ('hub', 2), ('spoke', 3)))).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
hh3cVsiXconnectHubSpoke.setStatus('current')
hh3c_vsi_xconnect_row_status = mib_table_column((1, 3, 6, 1, 4, 1, 25506, 2, 105, 1, 3, 1, 6), row_status()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
hh3cVsiXconnectRowStatus.setStatus('current')
mibBuilder.exportSymbols('HH3C-VSI-MIB', hh3cVsiMode=hh3cVsiMode, hh3cMinmIsid=hh3cMinmIsid, hh3cVsi=hh3cVsi, hh3cVsiXconnectAccessMode=hh3cVsiXconnectAccessMode, hh3cVsiXconnectRowStatus=hh3cVsiXconnectRowStatus, hh3cVsiXconnectHubSpoke=hh3cVsiXconnectHubSpoke, hh3cVsiEntry=hh3cVsiEntry, hh3cVsiObjects=hh3cVsiObjects, hh3cVsiNextAvailableVsiIndex=hh3cVsiNextAvailableVsiIndex, hh3cVsiTransMode=hh3cVsiTransMode, hh3cVsiXconnectVsiName=hh3cVsiXconnectVsiName, hh3cVsiAdminState=hh3cVsiAdminState, hh3cVsiIndex=hh3cVsiIndex, hh3cVsiScalarGroup=hh3cVsiScalarGroup, hh3cVsiId=hh3cVsiId, hh3cVsiRowStatus=hh3cVsiRowStatus, PYSNMP_MODULE_ID=hh3cVsi, hh3cVsiName=hh3cVsiName, hh3cVsiEnableHubSpoke=hh3cVsiEnableHubSpoke, hh3cVsiTable=hh3cVsiTable, hh3cVsiXconnectEntry=hh3cVsiXconnectEntry, hh3cVsiXconnectEvcSrvInstId=hh3cVsiXconnectEvcSrvInstId, hh3cVsiXconnectIfIndex=hh3cVsiXconnectIfIndex, hh3cVsiXconnectTable=hh3cVsiXconnectTable) |
class RemoveStoryboard(ControllableStoryboardAction):
"""
A trigger action that removes a System.Windows.Media.Animation.Storyboard.
RemoveStoryboard()
"""
| class Removestoryboard(ControllableStoryboardAction):
"""
A trigger action that removes a System.Windows.Media.Animation.Storyboard.
RemoveStoryboard()
""" |
vals = [0,10,-30,173247,123,19892122]
formats = ['%o','%020o', '%-20o', '%#o', '+%o', '+%#o']
for val in vals:
for fmt in formats:
print(fmt+":", fmt % val)
| vals = [0, 10, -30, 173247, 123, 19892122]
formats = ['%o', '%020o', '%-20o', '%#o', '+%o', '+%#o']
for val in vals:
for fmt in formats:
print(fmt + ':', fmt % val) |
class RoutedCommand(object,ICommand):
"""
Defines a command that implements System.Windows.Input.ICommand and is routed through the element tree.
RoutedCommand()
RoutedCommand(name: str,ownerType: Type)
RoutedCommand(name: str,ownerType: Type,inputGestures: InputGestureCollection)
"""
def CanExecute(self,parameter,target):
"""
CanExecute(self: RoutedCommand,parameter: object,target: IInputElement) -> bool
Determines whether this System.Windows.Input.RoutedCommand can execute in its
current state.
parameter: A user defined data type.
target: The command target.
Returns: true if the command can execute on the current command target; otherwise,false.
"""
pass
def Execute(self,parameter,target):
"""
Execute(self: RoutedCommand,parameter: object,target: IInputElement)
Executes the System.Windows.Input.RoutedCommand on the current command target.
parameter: User defined parameter to be passed to the handler.
target: Element at which to begin looking for command handlers.
"""
pass
def __init__(self,*args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
@staticmethod
def __new__(self,name=None,ownerType=None,inputGestures=None):
"""
__new__(cls: type)
__new__(cls: type,name: str,ownerType: Type)
__new__(cls: type,name: str,ownerType: Type,inputGestures: InputGestureCollection)
"""
pass
def __repr__(self,*args):
""" __repr__(self: object) -> str """
pass
InputGestures=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the collection of System.Windows.Input.InputGesture objects that are associated with this command.
Get: InputGestures(self: RoutedCommand) -> InputGestureCollection
"""
Name=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the name of the command.
Get: Name(self: RoutedCommand) -> str
"""
OwnerType=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the type that is registered with the command.
Get: OwnerType(self: RoutedCommand) -> Type
"""
CanExecuteChanged=None
| class Routedcommand(object, ICommand):
"""
Defines a command that implements System.Windows.Input.ICommand and is routed through the element tree.
RoutedCommand()
RoutedCommand(name: str,ownerType: Type)
RoutedCommand(name: str,ownerType: Type,inputGestures: InputGestureCollection)
"""
def can_execute(self, parameter, target):
"""
CanExecute(self: RoutedCommand,parameter: object,target: IInputElement) -> bool
Determines whether this System.Windows.Input.RoutedCommand can execute in its
current state.
parameter: A user defined data type.
target: The command target.
Returns: true if the command can execute on the current command target; otherwise,false.
"""
pass
def execute(self, parameter, target):
"""
Execute(self: RoutedCommand,parameter: object,target: IInputElement)
Executes the System.Windows.Input.RoutedCommand on the current command target.
parameter: User defined parameter to be passed to the handler.
target: Element at which to begin looking for command handlers.
"""
pass
def __init__(self, *args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
@staticmethod
def __new__(self, name=None, ownerType=None, inputGestures=None):
"""
__new__(cls: type)
__new__(cls: type,name: str,ownerType: Type)
__new__(cls: type,name: str,ownerType: Type,inputGestures: InputGestureCollection)
"""
pass
def __repr__(self, *args):
""" __repr__(self: object) -> str """
pass
input_gestures = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Gets the collection of System.Windows.Input.InputGesture objects that are associated with this command.\n\n\n\nGet: InputGestures(self: RoutedCommand) -> InputGestureCollection\n\n\n\n'
name = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Gets the name of the command.\n\n\n\nGet: Name(self: RoutedCommand) -> str\n\n\n\n'
owner_type = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Gets the type that is registered with the command.\n\n\n\nGet: OwnerType(self: RoutedCommand) -> Type\n\n\n\n'
can_execute_changed = None |
# File: gcloudcomputeengine_consts.py
#
# Copyright (c) 2021 Splunk Inc.
#
# Licensed under Apache 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt)
# Define your constants here
COMPUTE = 'compute'
COMPUTE_VERSION = 'v1'
# Error message handling constants
ERR_CODE_MSG = "Error code unavailable"
ERR_MSG_UNAVAILABLE = "Error message unavailable. Please check the asset configuration and|or action parameters"
PARSE_ERR_MSG = "Unable to parse the error message. Please check the asset configuration and|or action parameters"
| compute = 'compute'
compute_version = 'v1'
err_code_msg = 'Error code unavailable'
err_msg_unavailable = 'Error message unavailable. Please check the asset configuration and|or action parameters'
parse_err_msg = 'Unable to parse the error message. Please check the asset configuration and|or action parameters' |
#!/usr/bin/env python3
def byterize(obj):
objdict = obj.__dict__['fields']
def do_encode(dictio, key):
if isinstance(dictio[key], str) and len(dictio[key]) > 0 and key not in ['SecondaryAddr']:
dictio[key] = dictio[key].encode('latin-1')
elif hasattr(dictio[key], '__dict__'):
subdictio = dictio[key].__dict__['fields']
for subkey in subdictio:
do_encode(subdictio, subkey)
for field in objdict:
do_encode(objdict, field)
return obj
def justify(astring, indent = 35, break_every = 100):
str_indent = ('\n' + ' ' * indent)
splitted = astring.split('\n')
longests = [(n, s) for n, s in enumerate(splitted) if len(s) >= break_every]
for longest in longests:
lines = []
for i in range(0, len(longest[1]), break_every):
lines.append(longest[1][i : i + break_every])
splitted[longest[0]] = str_indent.join(lines)
if len(splitted) > 1:
justy = str_indent.join(splitted)
else:
justy = str_indent + str_indent.join(splitted)
return justy
class ShellStyle(object):
def style(self, s, style):
return style + s + '\033[0m'
def green(self, s):
return self.style(s, '\033[92m')
def blue(self, s):
return self.style(s, '\033[94m')
def yellow(self, s):
return self.style(s, '\033[93m')
def red(self, s):
return self.style(s, '\033[91m')
def magenta(self, s):
return self.style(s, '\033[95m')
def cyan(self, s):
return self.style(s, '\033[96m')
def white(self, s):
return self.style(s, '\033[97m')
def bold(self, s):
return self.style(s, '\033[1m')
def underline(self, s):
return self.style(s, '\033[4m')
def shell_message(nshell):
shelldict = {0: ShellStyle().yellow("Client generating RPC Bind Request..."),
1: ShellStyle().yellow("Client sending RPC Bind Request...") + ShellStyle().red("\t\t\t\t===============>"),
2: ShellStyle().red("===============>\t\t") + ShellStyle().yellow("Server received RPC Bind Request !!!"),
3: ShellStyle().yellow("\t\t\t\tServer parsing RPC Bind Request..."),
4: ShellStyle().yellow("\t\t\t\tServer generating RPC Bind Response..."),
5: ShellStyle().red("<===============\t\t") + ShellStyle().yellow("Server sending RPC Bind Response..."),
6: ShellStyle().green("\t\t\t\tRPC Bind acknowledged !!!\n"),
7: ShellStyle().yellow("Client received RPC Bind Response !!!") + ShellStyle().red("\t\t\t\t<==============="),
8: ShellStyle().green("RPC Bind acknowledged !!!\n"),
9: ShellStyle().blue("Client generating Activation Request dictionary..."),
10: ShellStyle().blue("Client generating Activation Request data..."),
11: ShellStyle().blue("Client generating RPC Activation Request..."),
12: ShellStyle().blue("Client sending RPC Activation Request...") + ShellStyle().red("\t\t\t===============>"),
13: ShellStyle().red("===============>\t\t") + ShellStyle().blue("Server received RPC Activation Request !!!"),
14: ShellStyle().blue("\t\t\t\tServer parsing RPC Activation Request..."),
15: ShellStyle().blue("\t\t\t\tServer processing KMS Activation Request..."),
16: ShellStyle().blue("\t\t\t\tServer processing KMS Activation Response..."),
17: ShellStyle().blue("\t\t\t\tServer generating RPC Activation Response..."),
18: ShellStyle().red("<===============\t\t") + ShellStyle().blue("Server sending RPC Activation Response..."),
19: ShellStyle().green("\t\t\t\tServer responded, now in Stand by...\n"),
20: ShellStyle().blue("Client received Response !!!") + ShellStyle().red("\t\t\t\t\t<==============="),
21: ShellStyle().green("Activation Done !!!"),
-1: ShellStyle().red("\t\t\t\t\t\t\t\tServer receiving"),
-2: ShellStyle().red("Client sending"),
-3: ShellStyle().red("Client receiving"),
-4: ShellStyle().red("\t\t\t\t\t\t\t\tServer sending")
}
if isinstance(nshell, list):
for n in nshell:
print(shelldict[n])
else:
print(shelldict[nshell])
| def byterize(obj):
objdict = obj.__dict__['fields']
def do_encode(dictio, key):
if isinstance(dictio[key], str) and len(dictio[key]) > 0 and (key not in ['SecondaryAddr']):
dictio[key] = dictio[key].encode('latin-1')
elif hasattr(dictio[key], '__dict__'):
subdictio = dictio[key].__dict__['fields']
for subkey in subdictio:
do_encode(subdictio, subkey)
for field in objdict:
do_encode(objdict, field)
return obj
def justify(astring, indent=35, break_every=100):
str_indent = '\n' + ' ' * indent
splitted = astring.split('\n')
longests = [(n, s) for (n, s) in enumerate(splitted) if len(s) >= break_every]
for longest in longests:
lines = []
for i in range(0, len(longest[1]), break_every):
lines.append(longest[1][i:i + break_every])
splitted[longest[0]] = str_indent.join(lines)
if len(splitted) > 1:
justy = str_indent.join(splitted)
else:
justy = str_indent + str_indent.join(splitted)
return justy
class Shellstyle(object):
def style(self, s, style):
return style + s + '\x1b[0m'
def green(self, s):
return self.style(s, '\x1b[92m')
def blue(self, s):
return self.style(s, '\x1b[94m')
def yellow(self, s):
return self.style(s, '\x1b[93m')
def red(self, s):
return self.style(s, '\x1b[91m')
def magenta(self, s):
return self.style(s, '\x1b[95m')
def cyan(self, s):
return self.style(s, '\x1b[96m')
def white(self, s):
return self.style(s, '\x1b[97m')
def bold(self, s):
return self.style(s, '\x1b[1m')
def underline(self, s):
return self.style(s, '\x1b[4m')
def shell_message(nshell):
shelldict = {0: shell_style().yellow('Client generating RPC Bind Request...'), 1: shell_style().yellow('Client sending RPC Bind Request...') + shell_style().red('\t\t\t\t===============>'), 2: shell_style().red('===============>\t\t') + shell_style().yellow('Server received RPC Bind Request !!!'), 3: shell_style().yellow('\t\t\t\tServer parsing RPC Bind Request...'), 4: shell_style().yellow('\t\t\t\tServer generating RPC Bind Response...'), 5: shell_style().red('<===============\t\t') + shell_style().yellow('Server sending RPC Bind Response...'), 6: shell_style().green('\t\t\t\tRPC Bind acknowledged !!!\n'), 7: shell_style().yellow('Client received RPC Bind Response !!!') + shell_style().red('\t\t\t\t<==============='), 8: shell_style().green('RPC Bind acknowledged !!!\n'), 9: shell_style().blue('Client generating Activation Request dictionary...'), 10: shell_style().blue('Client generating Activation Request data...'), 11: shell_style().blue('Client generating RPC Activation Request...'), 12: shell_style().blue('Client sending RPC Activation Request...') + shell_style().red('\t\t\t===============>'), 13: shell_style().red('===============>\t\t') + shell_style().blue('Server received RPC Activation Request !!!'), 14: shell_style().blue('\t\t\t\tServer parsing RPC Activation Request...'), 15: shell_style().blue('\t\t\t\tServer processing KMS Activation Request...'), 16: shell_style().blue('\t\t\t\tServer processing KMS Activation Response...'), 17: shell_style().blue('\t\t\t\tServer generating RPC Activation Response...'), 18: shell_style().red('<===============\t\t') + shell_style().blue('Server sending RPC Activation Response...'), 19: shell_style().green('\t\t\t\tServer responded, now in Stand by...\n'), 20: shell_style().blue('Client received Response !!!') + shell_style().red('\t\t\t\t\t<==============='), 21: shell_style().green('Activation Done !!!'), -1: shell_style().red('\t\t\t\t\t\t\t\tServer receiving'), -2: shell_style().red('Client sending'), -3: shell_style().red('Client receiving'), -4: shell_style().red('\t\t\t\t\t\t\t\tServer sending')}
if isinstance(nshell, list):
for n in nshell:
print(shelldict[n])
else:
print(shelldict[nshell]) |
"""Settings for the kytos/storehouse NApp."""
# Path to serialize the objects, this is relative to a venv, if a venv exists.
CUSTOM_DESTINATION_PATH = "/var/tmp/kytos/storehouse"
| """Settings for the kytos/storehouse NApp."""
custom_destination_path = '/var/tmp/kytos/storehouse' |
class DaftException(Exception):
def __init__(self, reason):
self.reason = reason
def __str__(self):
return "Error: " + self.reason
| class Daftexception(Exception):
def __init__(self, reason):
self.reason = reason
def __str__(self):
return 'Error: ' + self.reason |
class Solution:
def transformArray(self, arr: List[int]) -> List[int]:
na = arr[:]
stable = False
while not stable:
stable = True
for i in range(1, len(arr) - 1):
if arr[i] < arr[i-1] and arr[i] < arr[i+1]:
na[i] = arr[i] + 1
stable = False
elif arr[i] > arr[i-1] and arr[i] > arr[i+1]:
na[i] = arr[i] - 1
stable = False
else:
na[i] = arr[i]
arr = na[:]
return arr
| class Solution:
def transform_array(self, arr: List[int]) -> List[int]:
na = arr[:]
stable = False
while not stable:
stable = True
for i in range(1, len(arr) - 1):
if arr[i] < arr[i - 1] and arr[i] < arr[i + 1]:
na[i] = arr[i] + 1
stable = False
elif arr[i] > arr[i - 1] and arr[i] > arr[i + 1]:
na[i] = arr[i] - 1
stable = False
else:
na[i] = arr[i]
arr = na[:]
return arr |
try:
p=8778
b=56434
#f = open("ab.txt")
p = b/0
f = open("ab.txt")
for line in f:
print(line)
except FileNotFoundError as e:
print( e.filename)
except Exception as e:
print(e)
except ZeroDivisionError as e:
print(e)
#except (FileNotFoundError , ZeroDivisionError):
#print("file not found")
#except ZeroDivisionError:
#print("zero division error")
#i = 0/0
#we made some changes
| try:
p = 8778
b = 56434
p = b / 0
f = open('ab.txt')
for line in f:
print(line)
except FileNotFoundError as e:
print(e.filename)
except Exception as e:
print(e)
except ZeroDivisionError as e:
print(e) |
# ***************************************************************************************
# ***************************************************************************************
#
# Name : errors.py
# Author : Paul Robson (paul@robsons.org.uk)
# Date : 9th December 2018
# Purpose : Error classes
#
# ***************************************************************************************
# ***************************************************************************************
# ***************************************************************************************
# Compiler Error
# ***************************************************************************************
class CompilerException(Exception):
def __init__(self,message):
self.message = message
def get(self):
return "{0} ({1}:{2})".format(self.message,CompilerException.FILENAME,CompilerException.LINENUMBER)
CompilerException.FILENAME = "test"
CompilerException.LINENUMBER = 42
if __name__ == "__main__":
ex = CompilerException("Division by 42 error")
print(ex.get())
raise ex
| class Compilerexception(Exception):
def __init__(self, message):
self.message = message
def get(self):
return '{0} ({1}:{2})'.format(self.message, CompilerException.FILENAME, CompilerException.LINENUMBER)
CompilerException.FILENAME = 'test'
CompilerException.LINENUMBER = 42
if __name__ == '__main__':
ex = compiler_exception('Division by 42 error')
print(ex.get())
raise ex |
"""Unit tests for image_uploader.bzl."""
load(
"//skylark:integration_tests.bzl",
"SutComponentInfo"
)
load(
":image_uploader.bzl",
"image_uploader_sut_component",
)
load("//skylark:unittest.bzl", "asserts", "unittest")
load("//skylark:toolchains.bzl", "toolchain_container_images")
# image_uploader_sut_component_basic_test tests the image_uploader_sut_component
# rule and makes sure that it converts correctly into an underlying
# sut_component by examining the SutComponentInfo output of the rule.
def _image_uploader_sut_component_basic_test_impl(ctx):
env = unittest.begin(ctx)
provider = ctx.attr.dep[SutComponentInfo]
asserts.set_equals(
env,
depset([
"name: \"" + ctx.attr.rule_name + "_prepare\" " +
"setups {" +
"file: \"skylark/image_uploader/generate_image_name.sh\" " +
"timeout_seconds: 3 " +
"args: \"--registry\" args: \"" + ctx.attr.registry + "\" " +
"args: \"--repository\" args: \"" + ctx.attr.repository + "\" " +
"output_properties {key: \"image\"}" +
"} " +
"teardowns {" +
"file: \"skylark/image_uploader/delete_image.sh\" " +
"timeout_seconds: 60 " +
"args: \"{image}\"" +
"} " +
"docker_image: \"" + toolchain_container_images()["rbe-integration-test"] + "\" " +
"num_requested_ports: 0",
"name: \"" + ctx.attr.rule_name + "\" " +
"setups {" +
"file: \"skylark/image_uploader/create_and_upload_image.sh\" " +
"timeout_seconds: 600 " +
"args: \"--base_image\" args: \"" + ctx.attr.base_image + "\" " +
"args: \"--directory\" args: \"" + ctx.attr.directory + "\" " +
"".join(["args: \"--file\" args: \"%s\" " % f for f in ctx.attr.files]) +
"args: \"--new_image\" args: \"{prep#image}\" " +
"output_properties {key: \"image\"}" +
"} " +
"docker_image: \"" + toolchain_container_images()["rbe-integration-test"] + "\" " +
"sut_component_alias {" +
"target: \"" + ctx.attr.rule_name + "_prepare\" " +
"local_alias: \"prep\"" +
"} " +
"num_requested_ports: 1"
]),
provider.sut_protos)
asserts.set_equals(
env,
depset([ctx.file.prepare, ctx.file.setup]),
provider.setups)
asserts.set_equals(
env,
depset([ctx.file.teardown]),
provider.teardowns)
asserts.set_equals(env,
depset(ctx.files.data),
provider.data)
unittest.end(env)
image_uploader_sut_component_basic_test = unittest.make(
_image_uploader_sut_component_basic_test_impl,
attrs={"dep": attr.label(),
"rule_name" : attr.string(),
"prepare": attr.label(allow_single_file = True),
"setup": attr.label(allow_single_file = True),
"teardown": attr.label(allow_single_file = True),
"base_image": attr.string(),
"directory": attr.string(),
"data": attr.label_list(allow_files = True),
"files": attr.string_list(),
"registry": attr.string(),
"repository": attr.string()}
)
def test_image_uploader_sut_component_basic():
"""Generates a basic image_uploader_sut_component."""
base_image = "gcr.io/base_project/img"
directory = "/path/to/dir/in/container/"
registry = "gcr.io"
repository = "new_project/prefix_of_new_image"
image_uploader_sut_component(
name = "image_uploader_sut_component_basic_subject",
base_image = base_image,
directory = directory,
files = [
"testdata/file1.txt",
"testdata/file2.txt",
],
registry = registry,
repository = repository
)
image_uploader_sut_component_basic_test(
name = "image_uploader_sut_component_basic",
dep = "image_uploader_sut_component_basic_subject",
rule_name = "//skylark/image_uploader:image_uploader_sut_component_basic_subject",
prepare = "generate_image_name.sh",
setup = "create_and_upload_image.sh",
teardown = "delete_image.sh",
base_image = base_image,
directory = directory,
data = [
"testdata/file1.txt",
"testdata/file2.txt",
],
files = [
"skylark/image_uploader/testdata/file1.txt",
"skylark/image_uploader/testdata/file2.txt",
],
registry = registry,
repository = repository)
def image_uploader_sut_component_test_suite():
test_image_uploader_sut_component_basic()
native.test_suite(
name = "image_uploader_sut_component_test",
tests = [
"image_uploader_sut_component_basic",
],
)
| """Unit tests for image_uploader.bzl."""
load('//skylark:integration_tests.bzl', 'SutComponentInfo')
load(':image_uploader.bzl', 'image_uploader_sut_component')
load('//skylark:unittest.bzl', 'asserts', 'unittest')
load('//skylark:toolchains.bzl', 'toolchain_container_images')
def _image_uploader_sut_component_basic_test_impl(ctx):
env = unittest.begin(ctx)
provider = ctx.attr.dep[SutComponentInfo]
asserts.set_equals(env, depset(['name: "' + ctx.attr.rule_name + '_prepare" ' + 'setups {' + 'file: "skylark/image_uploader/generate_image_name.sh" ' + 'timeout_seconds: 3 ' + 'args: "--registry" args: "' + ctx.attr.registry + '" ' + 'args: "--repository" args: "' + ctx.attr.repository + '" ' + 'output_properties {key: "image"}' + '} ' + 'teardowns {' + 'file: "skylark/image_uploader/delete_image.sh" ' + 'timeout_seconds: 60 ' + 'args: "{image}"' + '} ' + 'docker_image: "' + toolchain_container_images()['rbe-integration-test'] + '" ' + 'num_requested_ports: 0', 'name: "' + ctx.attr.rule_name + '" ' + 'setups {' + 'file: "skylark/image_uploader/create_and_upload_image.sh" ' + 'timeout_seconds: 600 ' + 'args: "--base_image" args: "' + ctx.attr.base_image + '" ' + 'args: "--directory" args: "' + ctx.attr.directory + '" ' + ''.join(['args: "--file" args: "%s" ' % f for f in ctx.attr.files]) + 'args: "--new_image" args: "{prep#image}" ' + 'output_properties {key: "image"}' + '} ' + 'docker_image: "' + toolchain_container_images()['rbe-integration-test'] + '" ' + 'sut_component_alias {' + 'target: "' + ctx.attr.rule_name + '_prepare" ' + 'local_alias: "prep"' + '} ' + 'num_requested_ports: 1']), provider.sut_protos)
asserts.set_equals(env, depset([ctx.file.prepare, ctx.file.setup]), provider.setups)
asserts.set_equals(env, depset([ctx.file.teardown]), provider.teardowns)
asserts.set_equals(env, depset(ctx.files.data), provider.data)
unittest.end(env)
image_uploader_sut_component_basic_test = unittest.make(_image_uploader_sut_component_basic_test_impl, attrs={'dep': attr.label(), 'rule_name': attr.string(), 'prepare': attr.label(allow_single_file=True), 'setup': attr.label(allow_single_file=True), 'teardown': attr.label(allow_single_file=True), 'base_image': attr.string(), 'directory': attr.string(), 'data': attr.label_list(allow_files=True), 'files': attr.string_list(), 'registry': attr.string(), 'repository': attr.string()})
def test_image_uploader_sut_component_basic():
"""Generates a basic image_uploader_sut_component."""
base_image = 'gcr.io/base_project/img'
directory = '/path/to/dir/in/container/'
registry = 'gcr.io'
repository = 'new_project/prefix_of_new_image'
image_uploader_sut_component(name='image_uploader_sut_component_basic_subject', base_image=base_image, directory=directory, files=['testdata/file1.txt', 'testdata/file2.txt'], registry=registry, repository=repository)
image_uploader_sut_component_basic_test(name='image_uploader_sut_component_basic', dep='image_uploader_sut_component_basic_subject', rule_name='//skylark/image_uploader:image_uploader_sut_component_basic_subject', prepare='generate_image_name.sh', setup='create_and_upload_image.sh', teardown='delete_image.sh', base_image=base_image, directory=directory, data=['testdata/file1.txt', 'testdata/file2.txt'], files=['skylark/image_uploader/testdata/file1.txt', 'skylark/image_uploader/testdata/file2.txt'], registry=registry, repository=repository)
def image_uploader_sut_component_test_suite():
test_image_uploader_sut_component_basic()
native.test_suite(name='image_uploader_sut_component_test', tests=['image_uploader_sut_component_basic']) |
def get_options_ratio(options, total):
return options / total
def get_faculty_rating(get_options_ratio):
if get_options_ratio > .9 and get_options_ratio < 1:
return "Excellent"
if get_options_ratio > .8 and get_options_ratio < .9:
return "Very Good"
if get_options_ratio > .7 and get_options_ratio < .8:
return "Good"
if get_options_ratio > .6 and get_options_ratio < .7:
return "Needs Improvement"
if get_options_ratio > 0 and get_options_ratio < .6:
return "Unacceptable" | def get_options_ratio(options, total):
return options / total
def get_faculty_rating(get_options_ratio):
if get_options_ratio > 0.9 and get_options_ratio < 1:
return 'Excellent'
if get_options_ratio > 0.8 and get_options_ratio < 0.9:
return 'Very Good'
if get_options_ratio > 0.7 and get_options_ratio < 0.8:
return 'Good'
if get_options_ratio > 0.6 and get_options_ratio < 0.7:
return 'Needs Improvement'
if get_options_ratio > 0 and get_options_ratio < 0.6:
return 'Unacceptable' |
"""Exceptions and Error Handling"""
def assert_(condition, message='', exception_type=AssertionError):
"""Like assert, but with arbitrary exception types."""
if not condition:
raise exception_type(message)
# ------ VALUE ERRORS ------
class ShapeError(ValueError):
pass
class FrequencyValueError(ValueError):
pass
class DeviceError(ValueError):
pass
class NotSetError(ValueError):
pass
# ------ TYPE ERRORS ------
class NotTorchModuleError(TypeError):
pass
class FrequencyTypeError(TypeError):
pass
class DTypeError(TypeError):
pass
# ------ LOOKUP ERRORS ------
class ClassNotFoundError(LookupError):
pass
# ------ NOT-IMPLEMENTED ERRORS ------
class NotUnwrappableError(NotImplementedError):
pass | """Exceptions and Error Handling"""
def assert_(condition, message='', exception_type=AssertionError):
"""Like assert, but with arbitrary exception types."""
if not condition:
raise exception_type(message)
class Shapeerror(ValueError):
pass
class Frequencyvalueerror(ValueError):
pass
class Deviceerror(ValueError):
pass
class Notseterror(ValueError):
pass
class Nottorchmoduleerror(TypeError):
pass
class Frequencytypeerror(TypeError):
pass
class Dtypeerror(TypeError):
pass
class Classnotfounderror(LookupError):
pass
class Notunwrappableerror(NotImplementedError):
pass |
'''
Given a word, you need to judge whether the usage of capitals in it is right or not.
We define the usage of capitals in a word to be right when one of the following cases holds:
All letters in this word are capitals, like "USA".
All letters in this word are not capitals, like "leetcode".
Only the first letter in this word is capital, like "Google".
Otherwise, we define that this word doesn't use capitals in a right way.
'''
class Solution:
def detectCapitalUse(self, word: str) -> bool:
s = word
all_caps = True
all_low = True
for i in range(len(s)):
if s[i].isupper() == False:
all_caps = False
break
for i in range(len(s)):
if s[i].islower() == False:
all_low = False
break
first_letter_cap = s[0].isupper()
the_rest = s[1:]
for i in range(len(the_rest)):
if the_rest[i].isupper():
first_letter_cap = False
break
if all_caps or all_low or first_letter_cap:
return True
return False
| """
Given a word, you need to judge whether the usage of capitals in it is right or not.
We define the usage of capitals in a word to be right when one of the following cases holds:
All letters in this word are capitals, like "USA".
All letters in this word are not capitals, like "leetcode".
Only the first letter in this word is capital, like "Google".
Otherwise, we define that this word doesn't use capitals in a right way.
"""
class Solution:
def detect_capital_use(self, word: str) -> bool:
s = word
all_caps = True
all_low = True
for i in range(len(s)):
if s[i].isupper() == False:
all_caps = False
break
for i in range(len(s)):
if s[i].islower() == False:
all_low = False
break
first_letter_cap = s[0].isupper()
the_rest = s[1:]
for i in range(len(the_rest)):
if the_rest[i].isupper():
first_letter_cap = False
break
if all_caps or all_low or first_letter_cap:
return True
return False |
# See readme.md for instructions on running this code.
class HelpHandler(object):
def usage(self):
return '''
This plugin will give info about Zulip to
any user that types a message saying "help".
This is example code; ideally, you would flesh
this out for more useful help pertaining to
your Zulip instance.
'''
def triage_message(self, message):
# return True if we think the message may be of interest
original_content = message['content']
if message['type'] != 'stream':
return True
if original_content.lower().strip() != 'help':
return False
return True
def handle_message(self, message, client):
help_content = '''
Info on Zulip can be found here:
https://github.com/zulip/zulip
'''.strip()
client.send_message(dict(
type='stream',
to=message['display_recipient'],
subject=message['subject'],
content=help_content,
))
handler_class = HelpHandler
| class Helphandler(object):
def usage(self):
return '\n This plugin will give info about Zulip to\n any user that types a message saying "help".\n\n This is example code; ideally, you would flesh\n this out for more useful help pertaining to\n your Zulip instance.\n '
def triage_message(self, message):
original_content = message['content']
if message['type'] != 'stream':
return True
if original_content.lower().strip() != 'help':
return False
return True
def handle_message(self, message, client):
help_content = '\n Info on Zulip can be found here:\n https://github.com/zulip/zulip\n '.strip()
client.send_message(dict(type='stream', to=message['display_recipient'], subject=message['subject'], content=help_content))
handler_class = HelpHandler |
'''
Given a string S, return the "reversed" string where all characters that are not a letter stay in the same place, and all letters reverse their positions.
Example 1:
Input: "ab-cd"
Output: "dc-ba"
Example 2:
Input: "a-bC-dEf-ghIj"
Output: "j-Ih-gfE-dCba"
Example 3:
Input: "Test1ng-Leet=code-Q!"
Output: "Qedo1ct-eeLg=ntse-T!"
Note:
S.length <= 100
33 <= S[i].ASCIIcode <= 122
S doesn't contain \ or "
'''
def reverseOnlyLetters(S):
l = ""
r = [None]*len(S)
# add not letters
for i, char in enumerate(S):
if char.isalpha():
l+=char
else:
r[i] = char
# print(l, r)
# add leters
j=len(l)-1
for i in range(len(r)):
if r[i] == None:
r[i] = l[j]
j-=1
# print("".join(r))
return("".join(r))
def reverseOnlyLetters2(S):
r = ['']*len(S)
i, j = len(S)-1, 0
while i >=0 and j < len(S):
if S[i].isalpha():
r[j] = S[i]
else:
while not S[j].isalpha():
j+=1
if j >=len(S):
j-=1
break
if j < len(S):
r[j] = S[i]
i-=1
j+=1
print("".join(r))
return "".join(r)
reverseOnlyLetters("21-a_bc1=")
| """
Given a string S, return the "reversed" string where all characters that are not a letter stay in the same place, and all letters reverse their positions.
Example 1:
Input: "ab-cd"
Output: "dc-ba"
Example 2:
Input: "a-bC-dEf-ghIj"
Output: "j-Ih-gfE-dCba"
Example 3:
Input: "Test1ng-Leet=code-Q!"
Output: "Qedo1ct-eeLg=ntse-T!"
Note:
S.length <= 100
33 <= S[i].ASCIIcode <= 122
S doesn't contain \\ or "
"""
def reverse_only_letters(S):
l = ''
r = [None] * len(S)
for (i, char) in enumerate(S):
if char.isalpha():
l += char
else:
r[i] = char
j = len(l) - 1
for i in range(len(r)):
if r[i] == None:
r[i] = l[j]
j -= 1
return ''.join(r)
def reverse_only_letters2(S):
r = [''] * len(S)
(i, j) = (len(S) - 1, 0)
while i >= 0 and j < len(S):
if S[i].isalpha():
r[j] = S[i]
else:
while not S[j].isalpha():
j += 1
if j >= len(S):
j -= 1
break
if j < len(S):
r[j] = S[i]
i -= 1
j += 1
print(''.join(r))
return ''.join(r)
reverse_only_letters('21-a_bc1=') |
"""Top-level package for Railyard."""
__author__ = """Konstantin Taletskiy"""
__email__ = 'konstantin@taletskiy.com'
__version__ = '0.1.0'
| """Top-level package for Railyard."""
__author__ = 'Konstantin Taletskiy'
__email__ = 'konstantin@taletskiy.com'
__version__ = '0.1.0' |
#
# PySNMP MIB module NMS-EPON-ONU-SERIAL-PORT (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NMS-EPON-ONU-SERIAL-PORT
# Produced by pysmi-0.3.4 at Mon Apr 29 20:12:14 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")
ConstraintsIntersection, ValueSizeConstraint, ConstraintsUnion, ValueRangeConstraint, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ValueSizeConstraint", "ConstraintsUnion", "ValueRangeConstraint", "SingleValueConstraint")
nmsEPONGroup, = mibBuilder.importSymbols("NMS-SMI", "nmsEPONGroup")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
iso, MibScalar, MibTable, MibTableRow, MibTableColumn, ModuleIdentity, Integer32, ObjectIdentity, IpAddress, Counter32, MibIdentifier, Bits, Unsigned32, TimeTicks, Counter64, NotificationType, Gauge32 = mibBuilder.importSymbols("SNMPv2-SMI", "iso", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ModuleIdentity", "Integer32", "ObjectIdentity", "IpAddress", "Counter32", "MibIdentifier", "Bits", "Unsigned32", "TimeTicks", "Counter64", "NotificationType", "Gauge32")
DisplayString, RowStatus, MacAddress, TruthValue, PhysAddress, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "RowStatus", "MacAddress", "TruthValue", "PhysAddress", "TextualConvention")
nmsEponOnuSerialPort = MibIdentifier((1, 3, 6, 1, 4, 1, 11606, 10, 101, 27))
nmsEponOnuSerialPortTable = MibTable((1, 3, 6, 1, 4, 1, 11606, 10, 101, 27, 1), )
if mibBuilder.loadTexts: nmsEponOnuSerialPortTable.setStatus('mandatory')
nmsEponOnuSerialPortEntry = MibTableRow((1, 3, 6, 1, 4, 1, 11606, 10, 101, 27, 1, 1), ).setIndexNames((0, "NMS-EPON-ONU-SERIAL-PORT", "llidIfIndex"), (0, "NMS-EPON-ONU-SERIAL-PORT", "onuSerialPortSeqNo"))
if mibBuilder.loadTexts: nmsEponOnuSerialPortEntry.setStatus('mandatory')
llidIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 11606, 10, 101, 27, 1, 1, 1), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: llidIfIndex.setStatus('mandatory')
onuSerialPortSeqNo = MibTableColumn((1, 3, 6, 1, 4, 1, 11606, 10, 101, 27, 1, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(224, 239))).setMaxAccess("readonly")
if mibBuilder.loadTexts: onuSerialPortSeqNo.setStatus('mandatory')
onuSerialPortSpeed = MibTableColumn((1, 3, 6, 1, 4, 1, 11606, 10, 101, 27, 1, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(300, 115200))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: onuSerialPortSpeed.setStatus('mandatory')
onuSerialPortDataBits = MibTableColumn((1, 3, 6, 1, 4, 1, 11606, 10, 101, 27, 1, 1, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(5, 8))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: onuSerialPortDataBits.setStatus('mandatory')
onuSerialPortHaltBits = MibTableColumn((1, 3, 6, 1, 4, 1, 11606, 10, 101, 27, 1, 1, 5), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 2))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: onuSerialPortHaltBits.setStatus('mandatory')
onuSerialPortParity = MibTableColumn((1, 3, 6, 1, 4, 1, 11606, 10, 101, 27, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("none", 0), ("odd", 1), ("even", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: onuSerialPortParity.setStatus('mandatory')
onuSerialPortFlowControl = MibTableColumn((1, 3, 6, 1, 4, 1, 11606, 10, 101, 27, 1, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("none", 0), ("software", 1), ("hardware", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: onuSerialPortFlowControl.setStatus('mandatory')
onuSerialPortPropRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 11606, 10, 101, 27, 1, 1, 8), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: onuSerialPortPropRowStatus.setStatus('mandatory')
onuSerialPortDataReadInterval = MibTableColumn((1, 3, 6, 1, 4, 1, 11606, 10, 101, 27, 1, 1, 9), Integer32().subtype(subtypeSpec=ValueRangeConstraint(10, 100000))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: onuSerialPortDataReadInterval.setStatus('mandatory')
onuSerialPortDataReadBytes = MibTableColumn((1, 3, 6, 1, 4, 1, 11606, 10, 101, 27, 1, 1, 10), Integer32().subtype(subtypeSpec=ValueRangeConstraint(10, 1000))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: onuSerialPortDataReadBytes.setStatus('mandatory')
onuSerialPortBufferRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 11606, 10, 101, 27, 1, 1, 11), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: onuSerialPortBufferRowStatus.setStatus('mandatory')
onuSerialPortKeepaliveMode = MibTableColumn((1, 3, 6, 1, 4, 1, 11606, 10, 101, 27, 1, 1, 12), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disable", 0), ("enable", 1)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: onuSerialPortKeepaliveMode.setStatus('mandatory')
onuSerialPortKeepaliveIdle = MibTableColumn((1, 3, 6, 1, 4, 1, 11606, 10, 101, 27, 1, 1, 13), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 10000))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: onuSerialPortKeepaliveIdle.setStatus('mandatory')
onuSerialPortKeepaliveTimeout = MibTableColumn((1, 3, 6, 1, 4, 1, 11606, 10, 101, 27, 1, 1, 14), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 10000))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: onuSerialPortKeepaliveTimeout.setStatus('mandatory')
onuSerialPortKeepaliveProbeCount = MibTableColumn((1, 3, 6, 1, 4, 1, 11606, 10, 101, 27, 1, 1, 15), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 1000))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: onuSerialPortKeepaliveProbeCount.setStatus('mandatory')
onuSerialPortKeepaliveRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 11606, 10, 101, 27, 1, 1, 16), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: onuSerialPortKeepaliveRowStatus.setStatus('mandatory')
onuSerialPortLoopback = MibTableColumn((1, 3, 6, 1, 4, 1, 11606, 10, 101, 27, 1, 1, 17), TruthValue()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: onuSerialPortLoopback.setStatus('mandatory')
mibBuilder.exportSymbols("NMS-EPON-ONU-SERIAL-PORT", onuSerialPortDataReadInterval=onuSerialPortDataReadInterval, onuSerialPortDataReadBytes=onuSerialPortDataReadBytes, nmsEponOnuSerialPortEntry=nmsEponOnuSerialPortEntry, onuSerialPortHaltBits=onuSerialPortHaltBits, onuSerialPortBufferRowStatus=onuSerialPortBufferRowStatus, onuSerialPortDataBits=onuSerialPortDataBits, onuSerialPortSeqNo=onuSerialPortSeqNo, onuSerialPortLoopback=onuSerialPortLoopback, onuSerialPortKeepaliveTimeout=onuSerialPortKeepaliveTimeout, onuSerialPortKeepaliveMode=onuSerialPortKeepaliveMode, onuSerialPortParity=onuSerialPortParity, onuSerialPortPropRowStatus=onuSerialPortPropRowStatus, onuSerialPortKeepaliveProbeCount=onuSerialPortKeepaliveProbeCount, onuSerialPortKeepaliveIdle=onuSerialPortKeepaliveIdle, onuSerialPortSpeed=onuSerialPortSpeed, nmsEponOnuSerialPort=nmsEponOnuSerialPort, onuSerialPortFlowControl=onuSerialPortFlowControl, llidIfIndex=llidIfIndex, onuSerialPortKeepaliveRowStatus=onuSerialPortKeepaliveRowStatus, nmsEponOnuSerialPortTable=nmsEponOnuSerialPortTable)
| (octet_string, object_identifier, integer) = mibBuilder.importSymbols('ASN1', 'OctetString', 'ObjectIdentifier', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_intersection, value_size_constraint, constraints_union, value_range_constraint, single_value_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsIntersection', 'ValueSizeConstraint', 'ConstraintsUnion', 'ValueRangeConstraint', 'SingleValueConstraint')
(nms_epon_group,) = mibBuilder.importSymbols('NMS-SMI', 'nmsEPONGroup')
(module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup')
(iso, mib_scalar, mib_table, mib_table_row, mib_table_column, module_identity, integer32, object_identity, ip_address, counter32, mib_identifier, bits, unsigned32, time_ticks, counter64, notification_type, gauge32) = mibBuilder.importSymbols('SNMPv2-SMI', 'iso', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'ModuleIdentity', 'Integer32', 'ObjectIdentity', 'IpAddress', 'Counter32', 'MibIdentifier', 'Bits', 'Unsigned32', 'TimeTicks', 'Counter64', 'NotificationType', 'Gauge32')
(display_string, row_status, mac_address, truth_value, phys_address, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'RowStatus', 'MacAddress', 'TruthValue', 'PhysAddress', 'TextualConvention')
nms_epon_onu_serial_port = mib_identifier((1, 3, 6, 1, 4, 1, 11606, 10, 101, 27))
nms_epon_onu_serial_port_table = mib_table((1, 3, 6, 1, 4, 1, 11606, 10, 101, 27, 1))
if mibBuilder.loadTexts:
nmsEponOnuSerialPortTable.setStatus('mandatory')
nms_epon_onu_serial_port_entry = mib_table_row((1, 3, 6, 1, 4, 1, 11606, 10, 101, 27, 1, 1)).setIndexNames((0, 'NMS-EPON-ONU-SERIAL-PORT', 'llidIfIndex'), (0, 'NMS-EPON-ONU-SERIAL-PORT', 'onuSerialPortSeqNo'))
if mibBuilder.loadTexts:
nmsEponOnuSerialPortEntry.setStatus('mandatory')
llid_if_index = mib_table_column((1, 3, 6, 1, 4, 1, 11606, 10, 101, 27, 1, 1, 1), integer32()).setMaxAccess('readonly')
if mibBuilder.loadTexts:
llidIfIndex.setStatus('mandatory')
onu_serial_port_seq_no = mib_table_column((1, 3, 6, 1, 4, 1, 11606, 10, 101, 27, 1, 1, 2), integer32().subtype(subtypeSpec=value_range_constraint(224, 239))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
onuSerialPortSeqNo.setStatus('mandatory')
onu_serial_port_speed = mib_table_column((1, 3, 6, 1, 4, 1, 11606, 10, 101, 27, 1, 1, 3), integer32().subtype(subtypeSpec=value_range_constraint(300, 115200))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
onuSerialPortSpeed.setStatus('mandatory')
onu_serial_port_data_bits = mib_table_column((1, 3, 6, 1, 4, 1, 11606, 10, 101, 27, 1, 1, 4), integer32().subtype(subtypeSpec=value_range_constraint(5, 8))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
onuSerialPortDataBits.setStatus('mandatory')
onu_serial_port_halt_bits = mib_table_column((1, 3, 6, 1, 4, 1, 11606, 10, 101, 27, 1, 1, 5), integer32().subtype(subtypeSpec=value_range_constraint(1, 2))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
onuSerialPortHaltBits.setStatus('mandatory')
onu_serial_port_parity = mib_table_column((1, 3, 6, 1, 4, 1, 11606, 10, 101, 27, 1, 1, 6), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1, 2))).clone(namedValues=named_values(('none', 0), ('odd', 1), ('even', 2)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
onuSerialPortParity.setStatus('mandatory')
onu_serial_port_flow_control = mib_table_column((1, 3, 6, 1, 4, 1, 11606, 10, 101, 27, 1, 1, 7), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1, 2))).clone(namedValues=named_values(('none', 0), ('software', 1), ('hardware', 2)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
onuSerialPortFlowControl.setStatus('mandatory')
onu_serial_port_prop_row_status = mib_table_column((1, 3, 6, 1, 4, 1, 11606, 10, 101, 27, 1, 1, 8), row_status()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
onuSerialPortPropRowStatus.setStatus('mandatory')
onu_serial_port_data_read_interval = mib_table_column((1, 3, 6, 1, 4, 1, 11606, 10, 101, 27, 1, 1, 9), integer32().subtype(subtypeSpec=value_range_constraint(10, 100000))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
onuSerialPortDataReadInterval.setStatus('mandatory')
onu_serial_port_data_read_bytes = mib_table_column((1, 3, 6, 1, 4, 1, 11606, 10, 101, 27, 1, 1, 10), integer32().subtype(subtypeSpec=value_range_constraint(10, 1000))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
onuSerialPortDataReadBytes.setStatus('mandatory')
onu_serial_port_buffer_row_status = mib_table_column((1, 3, 6, 1, 4, 1, 11606, 10, 101, 27, 1, 1, 11), row_status()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
onuSerialPortBufferRowStatus.setStatus('mandatory')
onu_serial_port_keepalive_mode = mib_table_column((1, 3, 6, 1, 4, 1, 11606, 10, 101, 27, 1, 1, 12), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1))).clone(namedValues=named_values(('disable', 0), ('enable', 1)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
onuSerialPortKeepaliveMode.setStatus('mandatory')
onu_serial_port_keepalive_idle = mib_table_column((1, 3, 6, 1, 4, 1, 11606, 10, 101, 27, 1, 1, 13), integer32().subtype(subtypeSpec=value_range_constraint(1, 10000))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
onuSerialPortKeepaliveIdle.setStatus('mandatory')
onu_serial_port_keepalive_timeout = mib_table_column((1, 3, 6, 1, 4, 1, 11606, 10, 101, 27, 1, 1, 14), integer32().subtype(subtypeSpec=value_range_constraint(1, 10000))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
onuSerialPortKeepaliveTimeout.setStatus('mandatory')
onu_serial_port_keepalive_probe_count = mib_table_column((1, 3, 6, 1, 4, 1, 11606, 10, 101, 27, 1, 1, 15), integer32().subtype(subtypeSpec=value_range_constraint(1, 1000))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
onuSerialPortKeepaliveProbeCount.setStatus('mandatory')
onu_serial_port_keepalive_row_status = mib_table_column((1, 3, 6, 1, 4, 1, 11606, 10, 101, 27, 1, 1, 16), row_status()).setMaxAccess('readcreate')
if mibBuilder.loadTexts:
onuSerialPortKeepaliveRowStatus.setStatus('mandatory')
onu_serial_port_loopback = mib_table_column((1, 3, 6, 1, 4, 1, 11606, 10, 101, 27, 1, 1, 17), truth_value()).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
onuSerialPortLoopback.setStatus('mandatory')
mibBuilder.exportSymbols('NMS-EPON-ONU-SERIAL-PORT', onuSerialPortDataReadInterval=onuSerialPortDataReadInterval, onuSerialPortDataReadBytes=onuSerialPortDataReadBytes, nmsEponOnuSerialPortEntry=nmsEponOnuSerialPortEntry, onuSerialPortHaltBits=onuSerialPortHaltBits, onuSerialPortBufferRowStatus=onuSerialPortBufferRowStatus, onuSerialPortDataBits=onuSerialPortDataBits, onuSerialPortSeqNo=onuSerialPortSeqNo, onuSerialPortLoopback=onuSerialPortLoopback, onuSerialPortKeepaliveTimeout=onuSerialPortKeepaliveTimeout, onuSerialPortKeepaliveMode=onuSerialPortKeepaliveMode, onuSerialPortParity=onuSerialPortParity, onuSerialPortPropRowStatus=onuSerialPortPropRowStatus, onuSerialPortKeepaliveProbeCount=onuSerialPortKeepaliveProbeCount, onuSerialPortKeepaliveIdle=onuSerialPortKeepaliveIdle, onuSerialPortSpeed=onuSerialPortSpeed, nmsEponOnuSerialPort=nmsEponOnuSerialPort, onuSerialPortFlowControl=onuSerialPortFlowControl, llidIfIndex=llidIfIndex, onuSerialPortKeepaliveRowStatus=onuSerialPortKeepaliveRowStatus, nmsEponOnuSerialPortTable=nmsEponOnuSerialPortTable) |
# A simple color module I wrote for my projects
# Feel free to copy this script and use it for your own projects!
class Color:
purple = '\033[95m'
blue = '\033[94m'
green = '\033[92m'
yellow = '\033[93m'
red = '\033[91m'
white = '\033[0m'
class textType:
bold = '\033[1m'
underline = '\033[4m'
| class Color:
purple = '\x1b[95m'
blue = '\x1b[94m'
green = '\x1b[92m'
yellow = '\x1b[93m'
red = '\x1b[91m'
white = '\x1b[0m'
class Texttype:
bold = '\x1b[1m'
underline = '\x1b[4m' |
# LC 1268
class TrieNode:
def __init__(self):
self.next = dict()
self.words = list()
class Trie:
def __init__(self):
self.root = TrieNode()
def insert(self, word):
node = self.root
for char in word:
# node = node.next.setdefault(char, TrieNode())
if char not in node.next:
node.next[char] = TrieNode()
node = node.next[char]
if len(node.words) < 3:
node.words.append(word)
def getSuggestionsFor(self, word):
ans = []
node = self.root
for char in word:
if node:
node = node.next.get(char, None)
if node:
ans.append(node.words)
else:
ans.append([])
return ans
class Solution:
def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:
products.sort()
trie = Trie()
for word in products:
trie.insert(word)
return trie.getSuggestionsFor(searchWord)
| class Trienode:
def __init__(self):
self.next = dict()
self.words = list()
class Trie:
def __init__(self):
self.root = trie_node()
def insert(self, word):
node = self.root
for char in word:
if char not in node.next:
node.next[char] = trie_node()
node = node.next[char]
if len(node.words) < 3:
node.words.append(word)
def get_suggestions_for(self, word):
ans = []
node = self.root
for char in word:
if node:
node = node.next.get(char, None)
if node:
ans.append(node.words)
else:
ans.append([])
return ans
class Solution:
def suggested_products(self, products: List[str], searchWord: str) -> List[List[str]]:
products.sort()
trie = trie()
for word in products:
trie.insert(word)
return trie.getSuggestionsFor(searchWord) |
x = int(input())
y = int(input())
print(y % x)
| x = int(input())
y = int(input())
print(y % x) |
class OutputBase:
def __init__(self):
self.output_buffer = []
def __call__(self, obj):
self.write(obj)
def write(self, obj):
pass
def clear(self):
self.output_buffer = []
| class Outputbase:
def __init__(self):
self.output_buffer = []
def __call__(self, obj):
self.write(obj)
def write(self, obj):
pass
def clear(self):
self.output_buffer = [] |
#!/usr/bin/python
# https://po.kattis.com/problems/vandrarhem
class Bed(object):
def __init__(self, price, available_beds):
""" Constructor for Bed """
self.price = int(price)
self.available_beds = int(available_beds)
def is_full(self):
""" Checks if there is a bed of this type available """
return self.available_beds == 0
def book(self):
""" Books a bed of this type """
if not self.is_full():
self.available_beds -= 1
def main():
with open("infile.txt") as f:
infile = f.read().splitlines()
firstline = infile.pop(0)
attendees = int(firstline.split(" ")[0])
bedtype_count = int(firstline.split(" ")[1])
# The total cost for booking a bed for every attendee
total_cost = 0
bedtypes = []
for i in range(bedtype_count):
line = infile[i]
tokens = line.split(" ")
price = tokens[0]
available = tokens[1]
bedtypes.append(Bed(price, available))
# Sort the bedtypes by their price
bedtypes.sort(key=lambda bed: bed.price)
bed_type_counter = 0
# Book a bed for every attendee
while attendees > 0:
current_bed_type = bedtypes[bed_type_counter]
current_bed_price = current_bed_type.price
if current_bed_type.available_beds == 0:
bed_type_counter += 1
continue
else:
current_bed_type.book()
total_cost += current_bed_price
attendees -= 1
print(total_cost)
if __name__ == '__main__':
main()
| class Bed(object):
def __init__(self, price, available_beds):
""" Constructor for Bed """
self.price = int(price)
self.available_beds = int(available_beds)
def is_full(self):
""" Checks if there is a bed of this type available """
return self.available_beds == 0
def book(self):
""" Books a bed of this type """
if not self.is_full():
self.available_beds -= 1
def main():
with open('infile.txt') as f:
infile = f.read().splitlines()
firstline = infile.pop(0)
attendees = int(firstline.split(' ')[0])
bedtype_count = int(firstline.split(' ')[1])
total_cost = 0
bedtypes = []
for i in range(bedtype_count):
line = infile[i]
tokens = line.split(' ')
price = tokens[0]
available = tokens[1]
bedtypes.append(bed(price, available))
bedtypes.sort(key=lambda bed: bed.price)
bed_type_counter = 0
while attendees > 0:
current_bed_type = bedtypes[bed_type_counter]
current_bed_price = current_bed_type.price
if current_bed_type.available_beds == 0:
bed_type_counter += 1
continue
else:
current_bed_type.book()
total_cost += current_bed_price
attendees -= 1
print(total_cost)
if __name__ == '__main__':
main() |
DEBUG = False
# if False, "0" will be used
ENABLE_STRING_SEEDING = True
# use headless evaluator
HEADLESS = False
# === Emulator ===
DEVICE_NUM = 1
AVD_BOOT_DELAY = 30
AVD_SERIES = "api19_"
EVAL_TIMEOUT = 120
# if run on Mac OS, use "gtimeout"
TIMEOUT_CMD = "timeout"
# === Env. Paths ===
# path should end with a '/'
ANDROID_HOME = '/home/shadeimi/Software/android-sdk-linux/'
# the path of sapienz folder
WORKING_DIR = '/home/shadeimi/Software/eclipseWorkspace/sapienz/'
# === GA parameters ===
SEQUENCE_LENGTH_MIN = 20
SEQUENCE_LENGTH_MAX = 500
SUITE_SIZE = 5
POPULATION_SIZE = 50
OFFSPRING_SIZE = 50
GENERATION = 100
# Crossover probability
CXPB = 0.7
# Mutation probability
MUTPB = 0.3
# === Only for main_multi ===
# start from the ith apk
APK_OFFSET = 0
APK_DIR = ""
REPEATED_RESULTS_DIR = ""
REPEATED_RUNS = 20
# === MOTIFCORE script ===
# for initial population
MOTIFCORE_SCRIPT_PATH = '/mnt/sdcard/motifcore.script'
# header for evolved scripts
MOTIFCORE_SCRIPT_HEADER = 'type= raw events\ncount= -1\nspeed= 1.0\nstart data >>\n'
| debug = False
enable_string_seeding = True
headless = False
device_num = 1
avd_boot_delay = 30
avd_series = 'api19_'
eval_timeout = 120
timeout_cmd = 'timeout'
android_home = '/home/shadeimi/Software/android-sdk-linux/'
working_dir = '/home/shadeimi/Software/eclipseWorkspace/sapienz/'
sequence_length_min = 20
sequence_length_max = 500
suite_size = 5
population_size = 50
offspring_size = 50
generation = 100
cxpb = 0.7
mutpb = 0.3
apk_offset = 0
apk_dir = ''
repeated_results_dir = ''
repeated_runs = 20
motifcore_script_path = '/mnt/sdcard/motifcore.script'
motifcore_script_header = 'type= raw events\ncount= -1\nspeed= 1.0\nstart data >>\n' |
""" Remove metainfo files in folders, only if they're associated with torrents registered in Transmission.
Usage:
clutchless prune folder [--dry-run] <metainfo> ...
Arguments:
<metainfo> ... Folders to search for metainfo files to remove.
Options:
--dry-run Doesn't delete any files, only outputs what would be done.
"""
| """ Remove metainfo files in folders, only if they're associated with torrents registered in Transmission.
Usage:
clutchless prune folder [--dry-run] <metainfo> ...
Arguments:
<metainfo> ... Folders to search for metainfo files to remove.
Options:
--dry-run Doesn't delete any files, only outputs what would be done.
""" |
class InvalidDataFrameException(Exception):
pass
class InvalidCheckTypeException(Exception):
pass
| class Invaliddataframeexception(Exception):
pass
class Invalidchecktypeexception(Exception):
pass |
#!/usr/bin/python
# vim: set ts=4:
# vim: set shiftwidth=4:
# vim: set expandtab:
#-------------------------------------------------------------------------------
#---> Elections supported
#-------------------------------------------------------------------------------
# election id - base_url - election type - year - has special polling stations tuples for each election
elections = [
('20150920', 'http://ekloges.ypes.gr/current', 'v', 2015, True),
('20150125', 'http://ekloges-prev.singularlogic.eu/v2015a', 'v', 2015, True),
('20150705', 'http://ekloges-prev.singularlogic.eu/r2015', 'e', 2015, True),
('20140525', 'http://ekloges-prev.singularlogic.eu/may2014', 'e', 2014, False),
('20120617', 'http://ekloges-prev.singularlogic.eu/v2012b', 'v', 2012, True),
('20120506', 'http://ekloges-prev.singularlogic.eu/v2012a', 'v', 2012, True)]
# chosen election
_ELECTION = 5
election_str = elections[_ELECTION][0]
base_url = elections[_ELECTION][1]
election_type = elections[_ELECTION][2]
year = elections[_ELECTION][3]
has_special = elections[_ELECTION][4]
#-------------------------------------------------------------------------------
#---> Json files urls
#-------------------------------------------------------------------------------
def get_url(lvl, idx, dynamic):
content_type = 'dyn' if dynamic else 'stat'
if year > 2012:
first_part = '{0}/{1}/{2}'.format(base_url, content_type, election_type)
else:
first_part = '{0}/{1}'.format(base_url, content_type)
if lvl == 'epik' or lvl == 'top':
return '{0}/{1}'.format(first_part, 'statics.js')
elif lvl == 'ep' or lvl == 'district':
return '{0}/ep_{1}.js'.format(first_part, idx)
elif lvl == 'den' or lvl == 'munical_unit':
return '{0}/den_{1}.js'.format(first_part, idx)
elif lvl == 'special':
return '{0}/special_{1}.js'.format(first_part, idx)
elif lvl == 'tm' or lvl == 'pstation':
if year > 2012:
return '{0}/{1}/tm_{2}.js'.format(first_part, int(idx / 10000), idx)
else:
return '{0}/tm_{1}.js'.format(first_part, idx)
else:
raise Exception
#-------------------------------------------------------------------------------
#---> Top level file structure
#-------------------------------------------------------------------------------
if election_type == 'v' and year >= 2015:
lvl_labels = ['epik', 'snom', 'ep', 'dhm', 'den']
lvl_structs = [['id', 'name', 'pstation_cnt', 'population'],
['id', 'name', 'pstation_cnt'],
['id', 'name', 'pstation_cnt', 'alt_id', 'mps', 'unknown'],
['id', 'name', 'pstation_cnt', 'upper_id'],
['id', 'name', 'pstation_cnt', 'upper_id']]
parties_label = 'party'
parties_struct = ['id', 'alt_id', 'name', 'colour', 'in_parliament']
elif election_type == 'v' and year >= 2012:
lvl_labels = ['epik', 'ep', 'dhm', 'den']
lvl_structs = [['id', 'name', 'pstation_cnt', 'population'],
['id', 'name', 'pstation_cnt', 'alt_id', 'mps'],
['id', 'name', 'pstation_cnt', 'upper_id'],
['id', 'name', 'pstation_cnt', 'upper_id']]
parties_label = 'party'
parties_struct = ['id', 'alt_id', 'name', 'colour']
elif election_type == 'e':
lvl_labels = ['epik', 'snom', 'ep', 'dhm', 'den']
lvl_structs = [['id', 'name', 'pstation_cnt', 'population', 'mps', 'unknown'],
['id', 'upper_id', 'name', 'pstation_cnt'],
['id', 'name', 'pstation_cnt', 'alt_id', 'upper_id'],
['id', 'name', 'pstation_cnt', 'upper_id'],
['id', 'name', 'pstation_cnt', 'upper_id']]
parties_label = 'party'
parties_struct = ['id', 'alt_id', 'name', 'colour', 'in_parliament']
#-------------------------------------------------------------------------------
#---> Translations
#-------------------------------------------------------------------------------
translations = dict([
('NumTm', 'pstation_cnt'),
('Gramenoi', 'registered'),
('Egkyra', 'valid'),
('Akyra', 'invalid'),
('Leyka', 'blank')])
#-------------------------------------------------------------------------------
#---> Top level access helpers
#-------------------------------------------------------------------------------
def get(data_lst, lvl, field):
structure = lvl_structs[lvl_labels.index(lvl)]
try:
idx = structure.index(field)
except:
if field == 'upper_id':
return -1
else:
raise ValueError
return data_lst[idx]
def get_parties_list(data):
return data[parties_label]
def get_party_field(data_lst, field):
idx = parties_struct.index(field)
return data_lst[idx]
def has_special_list():
if election_str == '20120506':
return False
return True
| elections = [('20150920', 'http://ekloges.ypes.gr/current', 'v', 2015, True), ('20150125', 'http://ekloges-prev.singularlogic.eu/v2015a', 'v', 2015, True), ('20150705', 'http://ekloges-prev.singularlogic.eu/r2015', 'e', 2015, True), ('20140525', 'http://ekloges-prev.singularlogic.eu/may2014', 'e', 2014, False), ('20120617', 'http://ekloges-prev.singularlogic.eu/v2012b', 'v', 2012, True), ('20120506', 'http://ekloges-prev.singularlogic.eu/v2012a', 'v', 2012, True)]
_election = 5
election_str = elections[_ELECTION][0]
base_url = elections[_ELECTION][1]
election_type = elections[_ELECTION][2]
year = elections[_ELECTION][3]
has_special = elections[_ELECTION][4]
def get_url(lvl, idx, dynamic):
content_type = 'dyn' if dynamic else 'stat'
if year > 2012:
first_part = '{0}/{1}/{2}'.format(base_url, content_type, election_type)
else:
first_part = '{0}/{1}'.format(base_url, content_type)
if lvl == 'epik' or lvl == 'top':
return '{0}/{1}'.format(first_part, 'statics.js')
elif lvl == 'ep' or lvl == 'district':
return '{0}/ep_{1}.js'.format(first_part, idx)
elif lvl == 'den' or lvl == 'munical_unit':
return '{0}/den_{1}.js'.format(first_part, idx)
elif lvl == 'special':
return '{0}/special_{1}.js'.format(first_part, idx)
elif lvl == 'tm' or lvl == 'pstation':
if year > 2012:
return '{0}/{1}/tm_{2}.js'.format(first_part, int(idx / 10000), idx)
else:
return '{0}/tm_{1}.js'.format(first_part, idx)
else:
raise Exception
if election_type == 'v' and year >= 2015:
lvl_labels = ['epik', 'snom', 'ep', 'dhm', 'den']
lvl_structs = [['id', 'name', 'pstation_cnt', 'population'], ['id', 'name', 'pstation_cnt'], ['id', 'name', 'pstation_cnt', 'alt_id', 'mps', 'unknown'], ['id', 'name', 'pstation_cnt', 'upper_id'], ['id', 'name', 'pstation_cnt', 'upper_id']]
parties_label = 'party'
parties_struct = ['id', 'alt_id', 'name', 'colour', 'in_parliament']
elif election_type == 'v' and year >= 2012:
lvl_labels = ['epik', 'ep', 'dhm', 'den']
lvl_structs = [['id', 'name', 'pstation_cnt', 'population'], ['id', 'name', 'pstation_cnt', 'alt_id', 'mps'], ['id', 'name', 'pstation_cnt', 'upper_id'], ['id', 'name', 'pstation_cnt', 'upper_id']]
parties_label = 'party'
parties_struct = ['id', 'alt_id', 'name', 'colour']
elif election_type == 'e':
lvl_labels = ['epik', 'snom', 'ep', 'dhm', 'den']
lvl_structs = [['id', 'name', 'pstation_cnt', 'population', 'mps', 'unknown'], ['id', 'upper_id', 'name', 'pstation_cnt'], ['id', 'name', 'pstation_cnt', 'alt_id', 'upper_id'], ['id', 'name', 'pstation_cnt', 'upper_id'], ['id', 'name', 'pstation_cnt', 'upper_id']]
parties_label = 'party'
parties_struct = ['id', 'alt_id', 'name', 'colour', 'in_parliament']
translations = dict([('NumTm', 'pstation_cnt'), ('Gramenoi', 'registered'), ('Egkyra', 'valid'), ('Akyra', 'invalid'), ('Leyka', 'blank')])
def get(data_lst, lvl, field):
structure = lvl_structs[lvl_labels.index(lvl)]
try:
idx = structure.index(field)
except:
if field == 'upper_id':
return -1
else:
raise ValueError
return data_lst[idx]
def get_parties_list(data):
return data[parties_label]
def get_party_field(data_lst, field):
idx = parties_struct.index(field)
return data_lst[idx]
def has_special_list():
if election_str == '20120506':
return False
return True |
def ortho_locs(row, col):
offsets = [(-1,0), (0,-1), (0,1), (1,0)]
for row_offset, col_offset in offsets:
yield row + row_offset, col + col_offset
def adj_locs(row, col):
offsets = [(-1,-1), (-1,0), (-1,1), (0,-1), (0,1), (1,-1), (1,0), (1,1)]
for row_offset, col_offset in offsets:
yield row + row_offset, col + col_offset
class Grid:
def __init__(self, grid):
self.grid = grid
self.rows = len(grid)
self.cols = len(grid[0])
def __getitem__(self, row):
return self.grid[row]
def __iter__(self):
return self.grid.__iter__()
def valid_loc(self, row, col):
return row >= 0 and row < self.rows and col >= 0 and col < self.cols
def ortho_locs(self, row, col):
for ortho_row, ortho_col in ortho_locs(row, col):
if self.valid_loc(ortho_row, ortho_col):
yield ortho_row, ortho_col
def adj_locs(self, row, col):
for adj_row, adj_col in adj_locs(row, col):
if self.valid_loc(adj_row, adj_col):
yield adj_row, adj_col
def make_mirror(self, value):
return [[value for _ in row] for row in self.grid]
def build_grid(rows, cols, value):
return Grid([[value for _ in range(cols)] for _ in range(rows)])
def print_grid(grid, formatter=lambda v: v):
for row in grid:
for col in row:
print(formatter(col), end="")
print("")
| def ortho_locs(row, col):
offsets = [(-1, 0), (0, -1), (0, 1), (1, 0)]
for (row_offset, col_offset) in offsets:
yield (row + row_offset, col + col_offset)
def adj_locs(row, col):
offsets = [(-1, -1), (-1, 0), (-1, 1), (0, -1), (0, 1), (1, -1), (1, 0), (1, 1)]
for (row_offset, col_offset) in offsets:
yield (row + row_offset, col + col_offset)
class Grid:
def __init__(self, grid):
self.grid = grid
self.rows = len(grid)
self.cols = len(grid[0])
def __getitem__(self, row):
return self.grid[row]
def __iter__(self):
return self.grid.__iter__()
def valid_loc(self, row, col):
return row >= 0 and row < self.rows and (col >= 0) and (col < self.cols)
def ortho_locs(self, row, col):
for (ortho_row, ortho_col) in ortho_locs(row, col):
if self.valid_loc(ortho_row, ortho_col):
yield (ortho_row, ortho_col)
def adj_locs(self, row, col):
for (adj_row, adj_col) in adj_locs(row, col):
if self.valid_loc(adj_row, adj_col):
yield (adj_row, adj_col)
def make_mirror(self, value):
return [[value for _ in row] for row in self.grid]
def build_grid(rows, cols, value):
return grid([[value for _ in range(cols)] for _ in range(rows)])
def print_grid(grid, formatter=lambda v: v):
for row in grid:
for col in row:
print(formatter(col), end='')
print('') |
def GetByTitle(type, title):
type = type.upper()
if type != 'ANIME' and type != 'MANGA':
return False
variables = {
'type' : type,
'search' : title
}
return variables | def get_by_title(type, title):
type = type.upper()
if type != 'ANIME' and type != 'MANGA':
return False
variables = {'type': type, 'search': title}
return variables |
class BaseModel(object):
@classmethod
def connect(cls):
"""
Args:
None
Returns:
None
"""
raise NotImplementedError('model.connect not implemented!')
@classmethod
def create(cls, data):
"""
Args:
data(dict)
Returns:
model_vo(object)
"""
raise NotImplementedError('model.create not implemented!')
def update(self, data):
"""
Args:
data(dict)
Returns:
model_vo(object)
"""
raise NotImplementedError('model.update not implemented!')
def delete(self):
"""
Args:
None
Returns:
None
"""
raise NotImplementedError('model.delete not implemented!')
def terminate(self):
"""
Args:
None
Returns:
None
"""
raise NotImplementedError('model.terminate not implemented!')
@classmethod
def get(cls, **conditions):
"""
Args:
conditions(kwargs)
- key(str) : value(any)
Returns:
model_vo(object)
"""
raise NotImplementedError('model.get not implemented!')
@classmethod
def filter(cls, **conditions):
"""
Args:
conditions(kwargs)
- key(str) : value(any)
Returns:
model_vos(list)
"""
raise NotImplementedError('model.filter not implemented!')
def to_dict(self):
"""
Args:
None
Returns:
model_data(dict)
"""
raise NotImplementedError('model.to_dict not implemented!')
@classmethod
def query(cls, **query):
"""
Args:
query(kwargs)
- filter(list)
[
{
'key' : 'field(str)',
'value' : 'value(any or list)',
'operator' : 'lt | lte | gt | gte | eq | not | exists |
contain | not_contain | in | not_in | not_contain_in | match | regex | regex_in'
},
...
]
- filter_or(list)
[
{
'key' : 'field(str)',
'value' : 'value(any or list)',
'operator' : 'lt | lte | gt | gte | eq | not | exists |
contain | not_contain | in | not_in | not_contain_in | match | regex | regex_in'
},
...
]
- sort(dict)
{
'key' : 'field(str)',
'desc' : True | False
}
- page(dict)
{
'start': (int),
'limit' : (int)
}
- distinct(str): 'field'
- only(list): ['field1', 'field2', '...']
- exclude(list): ['field1', 'field2', '...']
- minimal(bool)
- count_only(bool)
Returns:
model_vos(list)
total_count(int)
"""
raise NotImplementedError('model.query not implemented!')
@classmethod
def stat(cls, **query):
"""
Args:
query(kwargs)
- filter(list)
[
{
'key' : 'field(str)',
'value' : 'value(any or list)',
'operator' : 'lt | lte | gt | gte | eq | not | exists |
contain | not_contain | in | not_in | not_contain_in | match | regex | regex_in
datetime_lt | datetime_lte | datetime_gt | datetime_gte | timediff_lt | timediff_lte
timediff_gt | timediff_gte'
},
...
]
- filter_or(list)
[
{
'key' : 'field(str)',
'value' : 'value(any or list)',
'operator' : 'lt | lte | gt | gte | eq | not | exists |
contain | not_contain | in | not_in | not_contain_in | match | regex | regex_in
datetime_lt | datetime_lte | datetime_gt | datetime_gte | timediff_lt | timediff_lte
timediff_gt | timediff_gte'
},
...
]
- aggregate(dict)
{
'unwind': [
{
'path': 'key path(str)'
}
],
'group': {
'keys': [
{
'key': 'field(str)',
'name': 'alias name(str)'
},
...
],
'fields': [
{
'key': 'field(str)',
'name': 'alias name(str)',
'operator': 'count | sum | avg | max | min | size | add_to_set | merge_objects'
},
...
]
}
'count': {
'name': 'alias name(str)'
}
}
- sort(dict)
{
'name' : 'field(str)',
'desc' : True | False
}
- page(dict)
{
'start': (int),
'limit' : (int)
}
Returns:
values(list)
"""
raise NotImplementedError('model.stat not implemented!')
| class Basemodel(object):
@classmethod
def connect(cls):
"""
Args:
None
Returns:
None
"""
raise not_implemented_error('model.connect not implemented!')
@classmethod
def create(cls, data):
"""
Args:
data(dict)
Returns:
model_vo(object)
"""
raise not_implemented_error('model.create not implemented!')
def update(self, data):
"""
Args:
data(dict)
Returns:
model_vo(object)
"""
raise not_implemented_error('model.update not implemented!')
def delete(self):
"""
Args:
None
Returns:
None
"""
raise not_implemented_error('model.delete not implemented!')
def terminate(self):
"""
Args:
None
Returns:
None
"""
raise not_implemented_error('model.terminate not implemented!')
@classmethod
def get(cls, **conditions):
"""
Args:
conditions(kwargs)
- key(str) : value(any)
Returns:
model_vo(object)
"""
raise not_implemented_error('model.get not implemented!')
@classmethod
def filter(cls, **conditions):
"""
Args:
conditions(kwargs)
- key(str) : value(any)
Returns:
model_vos(list)
"""
raise not_implemented_error('model.filter not implemented!')
def to_dict(self):
"""
Args:
None
Returns:
model_data(dict)
"""
raise not_implemented_error('model.to_dict not implemented!')
@classmethod
def query(cls, **query):
"""
Args:
query(kwargs)
- filter(list)
[
{
'key' : 'field(str)',
'value' : 'value(any or list)',
'operator' : 'lt | lte | gt | gte | eq | not | exists |
contain | not_contain | in | not_in | not_contain_in | match | regex | regex_in'
},
...
]
- filter_or(list)
[
{
'key' : 'field(str)',
'value' : 'value(any or list)',
'operator' : 'lt | lte | gt | gte | eq | not | exists |
contain | not_contain | in | not_in | not_contain_in | match | regex | regex_in'
},
...
]
- sort(dict)
{
'key' : 'field(str)',
'desc' : True | False
}
- page(dict)
{
'start': (int),
'limit' : (int)
}
- distinct(str): 'field'
- only(list): ['field1', 'field2', '...']
- exclude(list): ['field1', 'field2', '...']
- minimal(bool)
- count_only(bool)
Returns:
model_vos(list)
total_count(int)
"""
raise not_implemented_error('model.query not implemented!')
@classmethod
def stat(cls, **query):
"""
Args:
query(kwargs)
- filter(list)
[
{
'key' : 'field(str)',
'value' : 'value(any or list)',
'operator' : 'lt | lte | gt | gte | eq | not | exists |
contain | not_contain | in | not_in | not_contain_in | match | regex | regex_in
datetime_lt | datetime_lte | datetime_gt | datetime_gte | timediff_lt | timediff_lte
timediff_gt | timediff_gte'
},
...
]
- filter_or(list)
[
{
'key' : 'field(str)',
'value' : 'value(any or list)',
'operator' : 'lt | lte | gt | gte | eq | not | exists |
contain | not_contain | in | not_in | not_contain_in | match | regex | regex_in
datetime_lt | datetime_lte | datetime_gt | datetime_gte | timediff_lt | timediff_lte
timediff_gt | timediff_gte'
},
...
]
- aggregate(dict)
{
'unwind': [
{
'path': 'key path(str)'
}
],
'group': {
'keys': [
{
'key': 'field(str)',
'name': 'alias name(str)'
},
...
],
'fields': [
{
'key': 'field(str)',
'name': 'alias name(str)',
'operator': 'count | sum | avg | max | min | size | add_to_set | merge_objects'
},
...
]
}
'count': {
'name': 'alias name(str)'
}
}
- sort(dict)
{
'name' : 'field(str)',
'desc' : True | False
}
- page(dict)
{
'start': (int),
'limit' : (int)
}
Returns:
values(list)
"""
raise not_implemented_error('model.stat not implemented!') |
def queryValue(cur, sql, fields=None, error=None) :
row = queryRow(cur, sql, fields, error);
if row is None : return None
return row[0]
def queryRow(cur, sql, fields=None, error=None) :
row = doQuery(cur, sql, fields)
try:
row = cur.fetchone()
return row
except Exception as e:
if error:
print(error, e)
else :
print(e)
return None
def doQuery(cur, sql, fields=None) :
row = cur.execute(sql, fields)
return row
| def query_value(cur, sql, fields=None, error=None):
row = query_row(cur, sql, fields, error)
if row is None:
return None
return row[0]
def query_row(cur, sql, fields=None, error=None):
row = do_query(cur, sql, fields)
try:
row = cur.fetchone()
return row
except Exception as e:
if error:
print(error, e)
else:
print(e)
return None
def do_query(cur, sql, fields=None):
row = cur.execute(sql, fields)
return row |
HEADERS_FOR_HTTP_GET = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'
}
AGE_CATEGORIES = [
'JM10', 'JW10',
'JM11-14', 'JW11-14',
'JM15-17', 'JW15-17',
'SM18-19', 'SW18-19',
'SM20-24', 'SW20-24',
'SM25-29', 'SW25-29',
'SM30-34', 'SW30-34',
'VM35-39', 'VW35-39',
'VM40-44', 'VW40-44',
'VM45-49', 'VW45-49',
'VM50-54', 'VW50-54',
'VM55-59', 'VW55-59',
'VM60-64', 'VW60-64',
'VM65-69', 'VW65-69',
'VM70-74', 'VW70-74',
'VM75-79', 'VW75-79',
'VM---', 'VW---'
] | headers_for_http_get = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}
age_categories = ['JM10', 'JW10', 'JM11-14', 'JW11-14', 'JM15-17', 'JW15-17', 'SM18-19', 'SW18-19', 'SM20-24', 'SW20-24', 'SM25-29', 'SW25-29', 'SM30-34', 'SW30-34', 'VM35-39', 'VW35-39', 'VM40-44', 'VW40-44', 'VM45-49', 'VW45-49', 'VM50-54', 'VW50-54', 'VM55-59', 'VW55-59', 'VM60-64', 'VW60-64', 'VM65-69', 'VW65-69', 'VM70-74', 'VW70-74', 'VM75-79', 'VW75-79', 'VM---', 'VW---'] |
#
# PySNMP MIB module MICOM-IFDNA-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/MICOM-IFDNA-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:02:03 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "OctetString", "Integer")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsUnion, SingleValueConstraint, ValueRangeConstraint, ValueSizeConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "SingleValueConstraint", "ValueRangeConstraint", "ValueSizeConstraint", "ConstraintsIntersection")
micom_oscar, = mibBuilder.importSymbols("MICOM-OSCAR-MIB", "micom-oscar")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
Counter64, NotificationType, iso, Bits, Counter32, MibScalar, MibTable, MibTableRow, MibTableColumn, ObjectIdentity, IpAddress, Unsigned32, TimeTicks, Integer32, MibIdentifier, Gauge32, ModuleIdentity = mibBuilder.importSymbols("SNMPv2-SMI", "Counter64", "NotificationType", "iso", "Bits", "Counter32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ObjectIdentity", "IpAddress", "Unsigned32", "TimeTicks", "Integer32", "MibIdentifier", "Gauge32", "ModuleIdentity")
TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString")
micom_ifdna = MibIdentifier((1, 3, 6, 1, 4, 1, 335, 1, 4, 18)).setLabel("micom-ifdna")
ifDna = MibIdentifier((1, 3, 6, 1, 4, 1, 335, 1, 4, 18, 1))
ifNvDna = MibIdentifier((1, 3, 6, 1, 4, 1, 335, 1, 4, 18, 2))
mcmIfDnaTable = MibTable((1, 3, 6, 1, 4, 1, 335, 1, 4, 18, 1, 1), )
if mibBuilder.loadTexts: mcmIfDnaTable.setStatus('mandatory')
mcmIfDnaEntry = MibTableRow((1, 3, 6, 1, 4, 1, 335, 1, 4, 18, 1, 1, 1), ).setIndexNames((0, "MICOM-IFDNA-MIB", "mcmIfDnaIfIndex"), (0, "MICOM-IFDNA-MIB", "mcmIfDnaType"))
if mibBuilder.loadTexts: mcmIfDnaEntry.setStatus('mandatory')
mcmIfDnaIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 335, 1, 4, 18, 1, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: mcmIfDnaIfIndex.setStatus('mandatory')
mcmIfDnaType = MibTableColumn((1, 3, 6, 1, 4, 1, 335, 1, 4, 18, 1, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("provisioned", 1), ("learnt", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: mcmIfDnaType.setStatus('mandatory')
mcmIfDNADigits = MibTableColumn((1, 3, 6, 1, 4, 1, 335, 1, 4, 18, 1, 1, 1, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 34))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: mcmIfDNADigits.setStatus('mandatory')
mcmIfDnaStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 335, 1, 4, 18, 1, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("valid", 1), ("active", 2), ("invalid", 3)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: mcmIfDnaStatus.setStatus('mandatory')
nvmIfDnaTable = MibTable((1, 3, 6, 1, 4, 1, 335, 1, 4, 18, 2, 1), )
if mibBuilder.loadTexts: nvmIfDnaTable.setStatus('mandatory')
nvmIfDnaEntry = MibTableRow((1, 3, 6, 1, 4, 1, 335, 1, 4, 18, 2, 1, 1), ).setIndexNames((0, "MICOM-IFDNA-MIB", "nvmIfDnaIfIndex"), (0, "MICOM-IFDNA-MIB", "nvmIfDnaType"))
if mibBuilder.loadTexts: nvmIfDnaEntry.setStatus('mandatory')
nvmIfDnaIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 335, 1, 4, 18, 2, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 255))).setMaxAccess("readonly")
if mibBuilder.loadTexts: nvmIfDnaIfIndex.setStatus('mandatory')
nvmIfDnaType = MibTableColumn((1, 3, 6, 1, 4, 1, 335, 1, 4, 18, 2, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("provisioned", 1), ("learnt", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: nvmIfDnaType.setStatus('mandatory')
nvmIfDNADigits = MibTableColumn((1, 3, 6, 1, 4, 1, 335, 1, 4, 18, 2, 1, 1, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 34))).setMaxAccess("readonly")
if mibBuilder.loadTexts: nvmIfDNADigits.setStatus('mandatory')
nvmIfDnaStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 335, 1, 4, 18, 2, 1, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("valid", 1), ("active", 2), ("invalid", 3)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: nvmIfDnaStatus.setStatus('mandatory')
mibBuilder.exportSymbols("MICOM-IFDNA-MIB", nvmIfDnaStatus=nvmIfDnaStatus, mcmIfDnaType=mcmIfDnaType, mcmIfDnaTable=mcmIfDnaTable, mcmIfDnaEntry=mcmIfDnaEntry, micom_ifdna=micom_ifdna, mcmIfDnaIfIndex=mcmIfDnaIfIndex, ifNvDna=ifNvDna, mcmIfDnaStatus=mcmIfDnaStatus, nvmIfDnaTable=nvmIfDnaTable, nvmIfDnaEntry=nvmIfDnaEntry, ifDna=ifDna, nvmIfDnaType=nvmIfDnaType, nvmIfDNADigits=nvmIfDNADigits, mcmIfDNADigits=mcmIfDNADigits, nvmIfDnaIfIndex=nvmIfDnaIfIndex)
| (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(constraints_union, single_value_constraint, value_range_constraint, value_size_constraint, constraints_intersection) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsUnion', 'SingleValueConstraint', 'ValueRangeConstraint', 'ValueSizeConstraint', 'ConstraintsIntersection')
(micom_oscar,) = mibBuilder.importSymbols('MICOM-OSCAR-MIB', 'micom-oscar')
(notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance')
(counter64, notification_type, iso, bits, counter32, mib_scalar, mib_table, mib_table_row, mib_table_column, object_identity, ip_address, unsigned32, time_ticks, integer32, mib_identifier, gauge32, module_identity) = mibBuilder.importSymbols('SNMPv2-SMI', 'Counter64', 'NotificationType', 'iso', 'Bits', 'Counter32', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'ObjectIdentity', 'IpAddress', 'Unsigned32', 'TimeTicks', 'Integer32', 'MibIdentifier', 'Gauge32', 'ModuleIdentity')
(textual_convention, display_string) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'DisplayString')
micom_ifdna = mib_identifier((1, 3, 6, 1, 4, 1, 335, 1, 4, 18)).setLabel('micom-ifdna')
if_dna = mib_identifier((1, 3, 6, 1, 4, 1, 335, 1, 4, 18, 1))
if_nv_dna = mib_identifier((1, 3, 6, 1, 4, 1, 335, 1, 4, 18, 2))
mcm_if_dna_table = mib_table((1, 3, 6, 1, 4, 1, 335, 1, 4, 18, 1, 1))
if mibBuilder.loadTexts:
mcmIfDnaTable.setStatus('mandatory')
mcm_if_dna_entry = mib_table_row((1, 3, 6, 1, 4, 1, 335, 1, 4, 18, 1, 1, 1)).setIndexNames((0, 'MICOM-IFDNA-MIB', 'mcmIfDnaIfIndex'), (0, 'MICOM-IFDNA-MIB', 'mcmIfDnaType'))
if mibBuilder.loadTexts:
mcmIfDnaEntry.setStatus('mandatory')
mcm_if_dna_if_index = mib_table_column((1, 3, 6, 1, 4, 1, 335, 1, 4, 18, 1, 1, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(1, 255))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
mcmIfDnaIfIndex.setStatus('mandatory')
mcm_if_dna_type = mib_table_column((1, 3, 6, 1, 4, 1, 335, 1, 4, 18, 1, 1, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('provisioned', 1), ('learnt', 2)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
mcmIfDnaType.setStatus('mandatory')
mcm_if_dna_digits = mib_table_column((1, 3, 6, 1, 4, 1, 335, 1, 4, 18, 1, 1, 1, 3), display_string().subtype(subtypeSpec=value_size_constraint(1, 34))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
mcmIfDNADigits.setStatus('mandatory')
mcm_if_dna_status = mib_table_column((1, 3, 6, 1, 4, 1, 335, 1, 4, 18, 1, 1, 1, 4), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('valid', 1), ('active', 2), ('invalid', 3)))).setMaxAccess('readwrite')
if mibBuilder.loadTexts:
mcmIfDnaStatus.setStatus('mandatory')
nvm_if_dna_table = mib_table((1, 3, 6, 1, 4, 1, 335, 1, 4, 18, 2, 1))
if mibBuilder.loadTexts:
nvmIfDnaTable.setStatus('mandatory')
nvm_if_dna_entry = mib_table_row((1, 3, 6, 1, 4, 1, 335, 1, 4, 18, 2, 1, 1)).setIndexNames((0, 'MICOM-IFDNA-MIB', 'nvmIfDnaIfIndex'), (0, 'MICOM-IFDNA-MIB', 'nvmIfDnaType'))
if mibBuilder.loadTexts:
nvmIfDnaEntry.setStatus('mandatory')
nvm_if_dna_if_index = mib_table_column((1, 3, 6, 1, 4, 1, 335, 1, 4, 18, 2, 1, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(1, 255))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
nvmIfDnaIfIndex.setStatus('mandatory')
nvm_if_dna_type = mib_table_column((1, 3, 6, 1, 4, 1, 335, 1, 4, 18, 2, 1, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('provisioned', 1), ('learnt', 2)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
nvmIfDnaType.setStatus('mandatory')
nvm_if_dna_digits = mib_table_column((1, 3, 6, 1, 4, 1, 335, 1, 4, 18, 2, 1, 1, 3), display_string().subtype(subtypeSpec=value_size_constraint(1, 34))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
nvmIfDNADigits.setStatus('mandatory')
nvm_if_dna_status = mib_table_column((1, 3, 6, 1, 4, 1, 335, 1, 4, 18, 2, 1, 1, 4), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('valid', 1), ('active', 2), ('invalid', 3)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
nvmIfDnaStatus.setStatus('mandatory')
mibBuilder.exportSymbols('MICOM-IFDNA-MIB', nvmIfDnaStatus=nvmIfDnaStatus, mcmIfDnaType=mcmIfDnaType, mcmIfDnaTable=mcmIfDnaTable, mcmIfDnaEntry=mcmIfDnaEntry, micom_ifdna=micom_ifdna, mcmIfDnaIfIndex=mcmIfDnaIfIndex, ifNvDna=ifNvDna, mcmIfDnaStatus=mcmIfDnaStatus, nvmIfDnaTable=nvmIfDnaTable, nvmIfDnaEntry=nvmIfDnaEntry, ifDna=ifDna, nvmIfDnaType=nvmIfDnaType, nvmIfDNADigits=nvmIfDNADigits, mcmIfDNADigits=mcmIfDNADigits, nvmIfDnaIfIndex=nvmIfDnaIfIndex) |
a = 5
b = 3
def timeit_1():
print(a + b)
c = 8
def timeit_2():
print(a + b + c)
| a = 5
b = 3
def timeit_1():
print(a + b)
c = 8
def timeit_2():
print(a + b + c) |
def some_but_not_all(seq, pred):
has = [False,False]
for it in seq:
has[bool(pred(it))] = True
# exit as fast as possible
if all(has):
return True
# sequennce is scanned with only True or False predictions.
return False | def some_but_not_all(seq, pred):
has = [False, False]
for it in seq:
has[bool(pred(it))] = True
if all(has):
return True
return False |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
''' A short description of this file
A slightly longer description of this file
can be found under the shorter desription.
'''
def get_code():
''' Get mysterious code... '''
return '100111011111101010110110101100'
| """ A short description of this file
A slightly longer description of this file
can be found under the shorter desription.
"""
def get_code():
""" Get mysterious code... """
return '100111011111101010110110101100' |
class StdoutMock():
def __init__(self, *args, **kwargs):
self.content = ''
def write(self, content):
self.content += content
def read(self):
return self.content
def __str__(self):
return self.read()
| class Stdoutmock:
def __init__(self, *args, **kwargs):
self.content = ''
def write(self, content):
self.content += content
def read(self):
return self.content
def __str__(self):
return self.read() |
"""
uci_bootcamp_2021/examples/functions.py
examples on how to use functions
"""
def y(x, slope, initial_offset):
"""
This is a docstring. it is a piece of living documentation that is attached to the function.
Note: different companies have different styles for docstrings, and this one doesn't fit any of them!
this is just a small example of how to write a function in python, using simple math for demonstration.
"""
return slope * x + initial_offset
def y(x: float, slope: float, initial_offset: float = 0) -> float:
"""Same function as above, but this time with type annotations!"""
return slope * x + initial_offset
| """
uci_bootcamp_2021/examples/functions.py
examples on how to use functions
"""
def y(x, slope, initial_offset):
"""
This is a docstring. it is a piece of living documentation that is attached to the function.
Note: different companies have different styles for docstrings, and this one doesn't fit any of them!
this is just a small example of how to write a function in python, using simple math for demonstration.
"""
return slope * x + initial_offset
def y(x: float, slope: float, initial_offset: float=0) -> float:
"""Same function as above, but this time with type annotations!"""
return slope * x + initial_offset |
def flatten(list):
final = []
for item in list:
final += item
return final
def flattenN(list):
if type(list[0]) != type([]):
return list
return flattenN(flatten(list))
list = [[[1,2],[3,4]],[[3,4],["hello","there"]]]
result = flattenN(list)
print(result)
| def flatten(list):
final = []
for item in list:
final += item
return final
def flatten_n(list):
if type(list[0]) != type([]):
return list
return flatten_n(flatten(list))
list = [[[1, 2], [3, 4]], [[3, 4], ['hello', 'there']]]
result = flatten_n(list)
print(result) |
def imp_notas(quantidade, valor):
return '{:.0f} nota(s) de R$ {:.2f}'.format(quantidade, valor)
def imp_moedas(quantidade, valor):
return '{:.0f} moeda(s) de R$ {:.2f}'.format(quantidade, valor)
numero = float(input())
numero += 0.0001
if numero >= 0 or numero <= 1000000.00:
notas = [100.00, 50.00, 20.00, 10.00, 5.00, 2.00]
moedas = [1.00, 0.50, 0.25, 0.10, 0.05, 0.01]
dcp_notas = []
dcp_moedas = []
for nota in notas:
dcp_notas.append( (numero // nota) )
numero = numero - ( ( numero // nota ) * nota )
for moeda in moedas:
dcp_moedas.append( (numero // moeda) )
numero = numero - ( ( numero // moeda ) * moeda )
print('NOTAS:')
for i in range(6):
print(imp_notas(dcp_notas[i], notas[i]))
print('MOEDAS:')
for i in range(6):
print(imp_moedas(dcp_moedas[i], moedas[i]))
| def imp_notas(quantidade, valor):
return '{:.0f} nota(s) de R$ {:.2f}'.format(quantidade, valor)
def imp_moedas(quantidade, valor):
return '{:.0f} moeda(s) de R$ {:.2f}'.format(quantidade, valor)
numero = float(input())
numero += 0.0001
if numero >= 0 or numero <= 1000000.0:
notas = [100.0, 50.0, 20.0, 10.0, 5.0, 2.0]
moedas = [1.0, 0.5, 0.25, 0.1, 0.05, 0.01]
dcp_notas = []
dcp_moedas = []
for nota in notas:
dcp_notas.append(numero // nota)
numero = numero - numero // nota * nota
for moeda in moedas:
dcp_moedas.append(numero // moeda)
numero = numero - numero // moeda * moeda
print('NOTAS:')
for i in range(6):
print(imp_notas(dcp_notas[i], notas[i]))
print('MOEDAS:')
for i in range(6):
print(imp_moedas(dcp_moedas[i], moedas[i])) |
class Wizard:
def __init__(self, app):
self.app = app
def skip_wizard(self):
driver = self.app.driver
driver.find_element_by_class_name("skip").click()
| class Wizard:
def __init__(self, app):
self.app = app
def skip_wizard(self):
driver = self.app.driver
driver.find_element_by_class_name('skip').click() |
def linked_sort(a_to_sort, a_linked, key=str):
res = sorted(zip(a_to_sort, a_linked), key=key)
for i in range(len(a_to_sort)):
a_to_sort[i], a_linked[i] = res[i]
return a_to_sort | def linked_sort(a_to_sort, a_linked, key=str):
res = sorted(zip(a_to_sort, a_linked), key=key)
for i in range(len(a_to_sort)):
(a_to_sort[i], a_linked[i]) = res[i]
return a_to_sort |
# -*- coding: utf-8 -*-
# :copyright: (c) 2011 - 2015 by Arezqui Belaid.
# :license: MPL 2.0, see COPYING for more details.
__version__ = '1.0.3'
__author__ = "Arezqui Belaid"
__contact__ = "info@star2billing.com"
__homepage__ = "http://www.star2billing.org"
__docformat__ = "restructuredtext"
| __version__ = '1.0.3'
__author__ = 'Arezqui Belaid'
__contact__ = 'info@star2billing.com'
__homepage__ = 'http://www.star2billing.org'
__docformat__ = 'restructuredtext' |
def print_stats(num_broke, num_profitors, sample_size, profits, loses, type):
broke_percent = (num_broke / sample_size) * 100
profit_percent = (num_profitors / sample_size) * 100
try:
survive_profit_percent = (num_profitors / (sample_size - num_broke)) * 100
except ZeroDivisionError:
survive_profit_percent = 0
try:
avg_profit = sum(profits) / len(profits)
except ZeroDivisionError:
avg_profit = 0
try:
avg_loses = sum(loses) / len(loses)
except ZeroDivisionError:
avg_loses = 0
print(f'\n{type} Percentage Broke: {broke_percent}%')
print(f'{type} Percentage Profited: {profit_percent}%')
print(f'{type} Percentage Survivors Profited: {survive_profit_percent}%')
print(f'{type} Avergage Profit: {avg_profit}')
print(f'{type} Avergage Loses: {avg_loses}')
print(f' {type} Expected Profit: {avg_profit * (profit_percent/ 100)}')
print(f' {type} Expected Loss: {avg_loses * (1 - (profit_percent / 100))}')
| def print_stats(num_broke, num_profitors, sample_size, profits, loses, type):
broke_percent = num_broke / sample_size * 100
profit_percent = num_profitors / sample_size * 100
try:
survive_profit_percent = num_profitors / (sample_size - num_broke) * 100
except ZeroDivisionError:
survive_profit_percent = 0
try:
avg_profit = sum(profits) / len(profits)
except ZeroDivisionError:
avg_profit = 0
try:
avg_loses = sum(loses) / len(loses)
except ZeroDivisionError:
avg_loses = 0
print(f'\n{type} Percentage Broke: {broke_percent}%')
print(f'{type} Percentage Profited: {profit_percent}%')
print(f'{type} Percentage Survivors Profited: {survive_profit_percent}%')
print(f'{type} Avergage Profit: {avg_profit}')
print(f'{type} Avergage Loses: {avg_loses}')
print(f' {type} Expected Profit: {avg_profit * (profit_percent / 100)}')
print(f' {type} Expected Loss: {avg_loses * (1 - profit_percent / 100)}') |
class Similarity:
def __init__(self, path, score):
self.path = path
self.score = score
@classmethod
def from_dict(cls, adict):
return cls(
path=adict['path'],
score=adict['score'],
)
def to_dict(self):
return {
'path': self.path,
'score': self.score
}
def __eq__(self, other):
return self.to_dict() == other.to_dict()
| class Similarity:
def __init__(self, path, score):
self.path = path
self.score = score
@classmethod
def from_dict(cls, adict):
return cls(path=adict['path'], score=adict['score'])
def to_dict(self):
return {'path': self.path, 'score': self.score}
def __eq__(self, other):
return self.to_dict() == other.to_dict() |
EFFICIENTDET = {
'efficientdet-d0': {'input_size': 512,
'backbone': 'B0',
'W_bifpn': 64,
'D_bifpn': 2,
'D_class': 3},
'efficientdet-d1': {'input_size': 640,
'backbone': 'B1',
'W_bifpn': 88,
'D_bifpn': 3,
'D_class': 3},
'efficientdet-d2': {'input_size': 768,
'backbone': 'B2',
'W_bifpn': 112,
'D_bifpn': 4,
'D_class': 3},
'efficientdet-d3': {'input_size': 896,
'backbone': 'B3',
'W_bifpn': 160,
'D_bifpn': 5,
'D_class': 4},
'efficientdet-d4': {'input_size': 1024,
'backbone': 'B4',
'W_bifpn': 224,
'D_bifpn': 6,
'D_class': 4},
'efficientdet-d5': {'input_size': 1280,
'backbone': 'B5',
'W_bifpn': 288,
'D_bifpn': 7,
'D_class': 4},
'efficientdet-d6': {'input_size': 1408,
'backbone': 'B6',
'W_bifpn': 384,
'D_bifpn': 8,
'D_class': 5},
'efficientdet-d7': {'input_size': 1636,
'backbone': 'B6',
'W_bifpn': 384,
'D_bifpn': 8,
'D_class': 5},
} | efficientdet = {'efficientdet-d0': {'input_size': 512, 'backbone': 'B0', 'W_bifpn': 64, 'D_bifpn': 2, 'D_class': 3}, 'efficientdet-d1': {'input_size': 640, 'backbone': 'B1', 'W_bifpn': 88, 'D_bifpn': 3, 'D_class': 3}, 'efficientdet-d2': {'input_size': 768, 'backbone': 'B2', 'W_bifpn': 112, 'D_bifpn': 4, 'D_class': 3}, 'efficientdet-d3': {'input_size': 896, 'backbone': 'B3', 'W_bifpn': 160, 'D_bifpn': 5, 'D_class': 4}, 'efficientdet-d4': {'input_size': 1024, 'backbone': 'B4', 'W_bifpn': 224, 'D_bifpn': 6, 'D_class': 4}, 'efficientdet-d5': {'input_size': 1280, 'backbone': 'B5', 'W_bifpn': 288, 'D_bifpn': 7, 'D_class': 4}, 'efficientdet-d6': {'input_size': 1408, 'backbone': 'B6', 'W_bifpn': 384, 'D_bifpn': 8, 'D_class': 5}, 'efficientdet-d7': {'input_size': 1636, 'backbone': 'B6', 'W_bifpn': 384, 'D_bifpn': 8, 'D_class': 5}} |
month = int(input("Enter month: "))
year = int(input("Enter year: "))
if month == 1:
monthName = "January"
numberOfDaysInMonth = 31
elif month == 2:
monthName = "February"
if year % 400 == 0 or (year % 4 == 0 and year % 100 != 0):
numberOfDaysInMonth = 29
else:
numberOfDaysInMonth = 28
elif month == 3:
monthName = "March"
numberOfDaysInMonth = 31
elif month == 4:
monthName = "April"
numberOfDaysInMonth = 30
elif month == 5:
monthName = "May"
numberOfDaysInMonth = 31
elif month == 6:
monthName = "June"
numberOfDaysInMonth = 30
elif month == 7:
monthName = "July"
numberOfDaysInMonth = 31
elif month == 8:
monthName = "August"
numberOfDaysInMonth = 31
elif month == 9:
monthName = "September"
numberOfDaysInMonth = 30
elif month == 10:
monthName = "October"
numberOfDaysInMonth = 31
elif month == 11:
monthName = "November"
numberOfDaysInMonth = 30
else:
monthName = "December"
numberOfDaysInMonth = 31
print(monthName, year, "has", numberOfDaysInMonth, "days")
| month = int(input('Enter month: '))
year = int(input('Enter year: '))
if month == 1:
month_name = 'January'
number_of_days_in_month = 31
elif month == 2:
month_name = 'February'
if year % 400 == 0 or (year % 4 == 0 and year % 100 != 0):
number_of_days_in_month = 29
else:
number_of_days_in_month = 28
elif month == 3:
month_name = 'March'
number_of_days_in_month = 31
elif month == 4:
month_name = 'April'
number_of_days_in_month = 30
elif month == 5:
month_name = 'May'
number_of_days_in_month = 31
elif month == 6:
month_name = 'June'
number_of_days_in_month = 30
elif month == 7:
month_name = 'July'
number_of_days_in_month = 31
elif month == 8:
month_name = 'August'
number_of_days_in_month = 31
elif month == 9:
month_name = 'September'
number_of_days_in_month = 30
elif month == 10:
month_name = 'October'
number_of_days_in_month = 31
elif month == 11:
month_name = 'November'
number_of_days_in_month = 30
else:
month_name = 'December'
number_of_days_in_month = 31
print(monthName, year, 'has', numberOfDaysInMonth, 'days') |
# Problem: Given as an input two strings, X = x_{1} x_{2}... x_{m}, and Y = y_{1} y_{2}... y_{m}, output the alignment of the strings, character by character,
# so that the net penalty is minimised.
gap_penalty = 3 # cost of gap
mismatch_penalty = 2 # cost of mismatch
memoScore = {}
memoSequence = {}
def sequenceAlignment(seq1, seq2):
if (seq1,seq2) in memoScore:return memoScore[(seq1,seq2)] # memoization
if seq1 == "" and seq2 == "" : # base case
memoSequence[(seq1,seq2)] = ["",""]
return 0
elif seq1 == "" or seq2== "" :
maxim = max(len(seq1),len(seq2))
memoSequence[(seq1,seq2)] = [seq1.ljust(maxim,"_"), seq2.ljust(maxim,"_")]
return gap_penalty*maxim
penalty = 0 if seq1[0] == seq2[0] else mismatch_penalty
nogap = sequenceAlignment( seq1[1:],seq2[1:] ) + penalty # cost of match/mistmatch
seq1gap = sequenceAlignment( seq1,seq2[1:] ) + gap_penalty # cost of gap in sequence 1
seq2gap = sequenceAlignment( seq1[1:],seq2 ) + gap_penalty # cost of gap in sequence 2
if seq1gap < nogap and seq1gap <= seq2gap:
result = seq1gap
newSeq1 = "_" + memoSequence[(seq1,seq2[1:])][0]
newSeq2 = seq2[0] + memoSequence[(seq1,seq2[1:])][1]
elif seq2gap < nogap and seq2gap <= seq1gap:
result = seq2gap
newSeq1 = seq1[0] + memoSequence[(seq1[1:],seq2)][0]
newSeq2 = "_" + memoSequence[(seq1[1:],seq2)][1]
else:
result = nogap
newSeq1 = seq1[0] + memoSequence[(seq1[1:],seq2[1:])][0]
newSeq2 = seq2[0] + memoSequence[(seq1[1:],seq2[1:])][1]
memoScore[(seq1,seq2)] = result
memoSequence[(seq1,seq2)] = [newSeq1,newSeq2]
return result
# Testing
sequence1 = "AGGGCT"
sequence2 = "AGGCA"
sequenceAlignment(sequence1,sequence2)
finalsequence = memoSequence[(sequence1,sequence2)]
print("First sequence : ", finalsequence[0])
print("Second sequence : ", finalsequence[1])
print("Min penalty : ",memoScore[(sequence1,sequence2)] )
| gap_penalty = 3
mismatch_penalty = 2
memo_score = {}
memo_sequence = {}
def sequence_alignment(seq1, seq2):
if (seq1, seq2) in memoScore:
return memoScore[seq1, seq2]
if seq1 == '' and seq2 == '':
memoSequence[seq1, seq2] = ['', '']
return 0
elif seq1 == '' or seq2 == '':
maxim = max(len(seq1), len(seq2))
memoSequence[seq1, seq2] = [seq1.ljust(maxim, '_'), seq2.ljust(maxim, '_')]
return gap_penalty * maxim
penalty = 0 if seq1[0] == seq2[0] else mismatch_penalty
nogap = sequence_alignment(seq1[1:], seq2[1:]) + penalty
seq1gap = sequence_alignment(seq1, seq2[1:]) + gap_penalty
seq2gap = sequence_alignment(seq1[1:], seq2) + gap_penalty
if seq1gap < nogap and seq1gap <= seq2gap:
result = seq1gap
new_seq1 = '_' + memoSequence[seq1, seq2[1:]][0]
new_seq2 = seq2[0] + memoSequence[seq1, seq2[1:]][1]
elif seq2gap < nogap and seq2gap <= seq1gap:
result = seq2gap
new_seq1 = seq1[0] + memoSequence[seq1[1:], seq2][0]
new_seq2 = '_' + memoSequence[seq1[1:], seq2][1]
else:
result = nogap
new_seq1 = seq1[0] + memoSequence[seq1[1:], seq2[1:]][0]
new_seq2 = seq2[0] + memoSequence[seq1[1:], seq2[1:]][1]
memoScore[seq1, seq2] = result
memoSequence[seq1, seq2] = [newSeq1, newSeq2]
return result
sequence1 = 'AGGGCT'
sequence2 = 'AGGCA'
sequence_alignment(sequence1, sequence2)
finalsequence = memoSequence[sequence1, sequence2]
print('First sequence : ', finalsequence[0])
print('Second sequence : ', finalsequence[1])
print('Min penalty : ', memoScore[sequence1, sequence2]) |
A = int(input())
B = set("aeiou")
for i in range(A):
S = input()
count = 0
for j in range(len(S)):
if S[j] in B:
count += 1
print(count)
| a = int(input())
b = set('aeiou')
for i in range(A):
s = input()
count = 0
for j in range(len(S)):
if S[j] in B:
count += 1
print(count) |
# Configuration for running the Avalon Music Server under Gunicorn
# http://docs.gunicorn.org
# Note that this configuration omits a bunch of features that Gunicorn
# has (such as running as a daemon, changing users, error and access
# logging) because it is designed to be used when running Gunicorn
# with supervisord and a separate public facing web server (such as
# Nginx).
# Bind the server to an address only accessible locally. We'll be
# running Nginx which will proxy to Gunicorn and act as the public-
# facing web server.
bind = 'localhost:8000'
# Use three workers in addition to the master process. Since the Avalon
# Music Server is largely CPU bound, you can increase the number of
# request that can be handled by increasing this number (up to a point!).
# The Gunicorn docs recommend 2N + 1 where N is the number of CPUs you
# have.
workers = 3
# Make sure to load the application only in the main process before
# spawning the worker processes. This will save us memory when using
# multiple worker processes since the OS will be be able to take advantage
# of copy-on-write optimizations.
preload_app = True
| bind = 'localhost:8000'
workers = 3
preload_app = True |
"""
Generator expressions are lazily evaluated, which means that they generate and
return each value only when the generator is iterated. This is often useful when
ITERATING THROUGH LARGE DATEBASES, avoiding the need to create a duplicate of
the dataset in memory.
"""
for square in (x**2 for x in range(100)):
print(square)
"""
Another common use case is to avoid iterating over an entire iterable if doing
so is not necessary.
"""
| """
Generator expressions are lazily evaluated, which means that they generate and
return each value only when the generator is iterated. This is often useful when
ITERATING THROUGH LARGE DATEBASES, avoiding the need to create a duplicate of
the dataset in memory.
"""
for square in (x ** 2 for x in range(100)):
print(square)
'\nAnother common use case is to avoid iterating over an entire iterable if doing\nso is not necessary.\n' |
#check if number is prime or not
n = int(input("enter a number "))
for i in range(2, n):
if n % i == 0:
print("not a prime number")
break
else:
print("it is a prime number") | n = int(input('enter a number '))
for i in range(2, n):
if n % i == 0:
print('not a prime number')
break
else:
print('it is a prime number') |
#
# PySNMP MIB module EXTREME-EAPS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/EXTREME-BASE-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:07:14 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
ObjectIdentifier, Integer, OctetString = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "Integer", "OctetString")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueRangeConstraint, ValueSizeConstraint, ConstraintsUnion, SingleValueConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ValueSizeConstraint", "ConstraintsUnion", "SingleValueConstraint", "ConstraintsIntersection")
extremeAgent, = mibBuilder.importSymbols("EXTREME-BASE-MIB", "extremeAgent")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
Counter64, IpAddress, Integer32, Gauge32, Counter32, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, iso, NotificationType, ModuleIdentity, ObjectIdentity, TimeTicks, Bits, Unsigned32 = mibBuilder.importSymbols("SNMPv2-SMI", "Counter64", "IpAddress", "Integer32", "Gauge32", "Counter32", "MibIdentifier", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "iso", "NotificationType", "ModuleIdentity", "ObjectIdentity", "TimeTicks", "Bits", "Unsigned32")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
extremeEaps = ModuleIdentity((1, 3, 6, 1, 4, 1, 1916, 1, 18))
if mibBuilder.loadTexts: extremeEaps.setLastUpdated('0007240000Z')
if mibBuilder.loadTexts: extremeEaps.setOrganization('Extreme Networks, Inc.')
if mibBuilder.loadTexts: extremeEaps.setContactInfo('www.extremenetworks.com')
if mibBuilder.loadTexts: extremeEaps.setDescription('Ethernet Automatic Protection Switching information')
extremeEapsTable = MibTable((1, 3, 6, 1, 4, 1, 1916, 1, 18, 1), )
if mibBuilder.loadTexts: extremeEapsTable.setStatus('current')
if mibBuilder.loadTexts: extremeEapsTable.setDescription('This table contains EAPS information about all EAPS domains on this device.')
extremeEapsEntry = MibTableRow((1, 3, 6, 1, 4, 1, 1916, 1, 18, 1, 1), ).setIndexNames((0, "EXTREME-EAPS-MIB", "extremeEapsName"))
if mibBuilder.loadTexts: extremeEapsEntry.setStatus('current')
if mibBuilder.loadTexts: extremeEapsEntry.setDescription('An individual entry of this table contains EAPS information related to that EAPS domain.')
extremeEapsName = MibTableColumn((1, 3, 6, 1, 4, 1, 1916, 1, 18, 1, 1, 1), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 32))).setMaxAccess("readonly")
if mibBuilder.loadTexts: extremeEapsName.setStatus('current')
if mibBuilder.loadTexts: extremeEapsName.setDescription('The EAPS domain name.')
extremeEapsMode = MibTableColumn((1, 3, 6, 1, 4, 1, 1916, 1, 18, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("invalid", 0), ("master", 1), ("transit", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: extremeEapsMode.setStatus('current')
if mibBuilder.loadTexts: extremeEapsMode.setDescription('This indicates the mode of the EAPS domain.')
extremeEapsState = MibTableColumn((1, 3, 6, 1, 4, 1, 1916, 1, 18, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5, 6))).clone(namedValues=NamedValues(("idle", 0), ("complete", 1), ("failed", 2), ("linksup", 3), ("linkdown", 4), ("preforwarding", 5), ("init", 6)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: extremeEapsState.setStatus('current')
if mibBuilder.loadTexts: extremeEapsState.setDescription('This indicates the current EAPS state of this EAPS domain.')
extremeEapsPrevState = MibScalar((1, 3, 6, 1, 4, 1, 1916, 1, 18, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5, 6))).clone(namedValues=NamedValues(("idle", 0), ("complete", 1), ("failed", 2), ("linksup", 3), ("linkdown", 4), ("preforwarding", 5), ("init", 6)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: extremeEapsPrevState.setStatus('current')
if mibBuilder.loadTexts: extremeEapsPrevState.setDescription('This indicates the previous EAPS state of this EAPS domain. Used in state change traps information.')
mibBuilder.exportSymbols("EXTREME-EAPS-MIB", extremeEapsEntry=extremeEapsEntry, extremeEapsMode=extremeEapsMode, PYSNMP_MODULE_ID=extremeEaps, extremeEapsState=extremeEapsState, extremeEapsName=extremeEapsName, extremeEapsPrevState=extremeEapsPrevState, extremeEaps=extremeEaps, extremeEapsTable=extremeEapsTable)
| (object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString')
(named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues')
(value_range_constraint, value_size_constraint, constraints_union, single_value_constraint, constraints_intersection) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueRangeConstraint', 'ValueSizeConstraint', 'ConstraintsUnion', 'SingleValueConstraint', 'ConstraintsIntersection')
(extreme_agent,) = mibBuilder.importSymbols('EXTREME-BASE-MIB', 'extremeAgent')
(module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup')
(counter64, ip_address, integer32, gauge32, counter32, mib_identifier, mib_scalar, mib_table, mib_table_row, mib_table_column, iso, notification_type, module_identity, object_identity, time_ticks, bits, unsigned32) = mibBuilder.importSymbols('SNMPv2-SMI', 'Counter64', 'IpAddress', 'Integer32', 'Gauge32', 'Counter32', 'MibIdentifier', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'iso', 'NotificationType', 'ModuleIdentity', 'ObjectIdentity', 'TimeTicks', 'Bits', 'Unsigned32')
(display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention')
extreme_eaps = module_identity((1, 3, 6, 1, 4, 1, 1916, 1, 18))
if mibBuilder.loadTexts:
extremeEaps.setLastUpdated('0007240000Z')
if mibBuilder.loadTexts:
extremeEaps.setOrganization('Extreme Networks, Inc.')
if mibBuilder.loadTexts:
extremeEaps.setContactInfo('www.extremenetworks.com')
if mibBuilder.loadTexts:
extremeEaps.setDescription('Ethernet Automatic Protection Switching information')
extreme_eaps_table = mib_table((1, 3, 6, 1, 4, 1, 1916, 1, 18, 1))
if mibBuilder.loadTexts:
extremeEapsTable.setStatus('current')
if mibBuilder.loadTexts:
extremeEapsTable.setDescription('This table contains EAPS information about all EAPS domains on this device.')
extreme_eaps_entry = mib_table_row((1, 3, 6, 1, 4, 1, 1916, 1, 18, 1, 1)).setIndexNames((0, 'EXTREME-EAPS-MIB', 'extremeEapsName'))
if mibBuilder.loadTexts:
extremeEapsEntry.setStatus('current')
if mibBuilder.loadTexts:
extremeEapsEntry.setDescription('An individual entry of this table contains EAPS information related to that EAPS domain.')
extreme_eaps_name = mib_table_column((1, 3, 6, 1, 4, 1, 1916, 1, 18, 1, 1, 1), display_string().subtype(subtypeSpec=value_size_constraint(0, 32))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
extremeEapsName.setStatus('current')
if mibBuilder.loadTexts:
extremeEapsName.setDescription('The EAPS domain name.')
extreme_eaps_mode = mib_table_column((1, 3, 6, 1, 4, 1, 1916, 1, 18, 1, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1, 2))).clone(namedValues=named_values(('invalid', 0), ('master', 1), ('transit', 2)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
extremeEapsMode.setStatus('current')
if mibBuilder.loadTexts:
extremeEapsMode.setDescription('This indicates the mode of the EAPS domain.')
extreme_eaps_state = mib_table_column((1, 3, 6, 1, 4, 1, 1916, 1, 18, 1, 1, 3), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1, 2, 3, 4, 5, 6))).clone(namedValues=named_values(('idle', 0), ('complete', 1), ('failed', 2), ('linksup', 3), ('linkdown', 4), ('preforwarding', 5), ('init', 6)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
extremeEapsState.setStatus('current')
if mibBuilder.loadTexts:
extremeEapsState.setDescription('This indicates the current EAPS state of this EAPS domain.')
extreme_eaps_prev_state = mib_scalar((1, 3, 6, 1, 4, 1, 1916, 1, 18, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1, 2, 3, 4, 5, 6))).clone(namedValues=named_values(('idle', 0), ('complete', 1), ('failed', 2), ('linksup', 3), ('linkdown', 4), ('preforwarding', 5), ('init', 6)))).setMaxAccess('readonly')
if mibBuilder.loadTexts:
extremeEapsPrevState.setStatus('current')
if mibBuilder.loadTexts:
extremeEapsPrevState.setDescription('This indicates the previous EAPS state of this EAPS domain. Used in state change traps information.')
mibBuilder.exportSymbols('EXTREME-EAPS-MIB', extremeEapsEntry=extremeEapsEntry, extremeEapsMode=extremeEapsMode, PYSNMP_MODULE_ID=extremeEaps, extremeEapsState=extremeEapsState, extremeEapsName=extremeEapsName, extremeEapsPrevState=extremeEapsPrevState, extremeEaps=extremeEaps, extremeEapsTable=extremeEapsTable) |
# -*- coding: utf-8 -*-
operation = input()
total = 0
for i in range(144):
N = float(input())
line = i // 12
if (i > (13 * line)):
total += N
answer = total if (operation == 'S') else (total / 66)
print("%.1f" % answer) | operation = input()
total = 0
for i in range(144):
n = float(input())
line = i // 12
if i > 13 * line:
total += N
answer = total if operation == 'S' else total / 66
print('%.1f' % answer) |
# -*- coding: utf-8 -*-
"""Top-level package for light_tester."""
__author__ = """Gary Cremins"""
__email__ = 'gary.cremins1@ucdconnect.ie'
__version__ = '0.1.0'
| """Top-level package for light_tester."""
__author__ = 'Gary Cremins'
__email__ = 'gary.cremins1@ucdconnect.ie'
__version__ = '0.1.0' |
S = [3, 1, 3, 1]
N = len(S)-1
big_val = 1 << 62 # left bitwise shift is equivalent to raising 2 to the power of the positions shifted. so, big_val = 2 ^ 62.
A = [[big_val for i in range(N+1)] for j in range(N+1)]
def matrix_chain_cost(i, j):
global A
if i == j:
return 0
if A[i][j] != big_val:
return A[i][j]
for k in range(i, j):
A[i][j] = min(A[i][j], matrix_chain_cost(i, k) + matrix_chain_cost(k+1, j) + S[i-1] * S[k] * S[j])
return A[i][j]
print("Minimum cost of multiplication is", matrix_chain_cost(1, N)) | s = [3, 1, 3, 1]
n = len(S) - 1
big_val = 1 << 62
a = [[big_val for i in range(N + 1)] for j in range(N + 1)]
def matrix_chain_cost(i, j):
global A
if i == j:
return 0
if A[i][j] != big_val:
return A[i][j]
for k in range(i, j):
A[i][j] = min(A[i][j], matrix_chain_cost(i, k) + matrix_chain_cost(k + 1, j) + S[i - 1] * S[k] * S[j])
return A[i][j]
print('Minimum cost of multiplication is', matrix_chain_cost(1, N)) |
# Function: flips a pattern by mirror image
# Input:
# string - string pattern
# direction - flip horizontally or vertically
# Ouput: modified string pattern
def flip(st, direction):
row_strings = st.split("\n")
row_strings = row_strings[:-1]
st_out = ''
if (direction == 'Flip Horizontally'):
row_strings = row_strings[::-1]
for row in row_strings:
st_out += row + '\n'
else:
for row in row_strings:
st_out += row[::-1] + '\n'
return(st_out)
# Function: reflects pattern vertically
# Input:
# st - string pattern
# space - positive integer value, gap between original pattern and reflected pattern
# direction - 'Reflect Left' or 'Reflect Right', direction to perform vertical reflection
# Output:
# modified string pattern
def reflect_v(st, space, direction):
row_strings = st.split("\n")
row_strings = row_strings[:-1]
space_st = ""
if (direction == "Reflect Left"):
# Add spaces on the left of pattern
for row in row_strings:
row = space*"-" + row
space_st = space_st + row + "\n"
new_row_strings = space_st.split("\n")
reflected_row_strings = new_row_strings[:len(row_strings)]
st_out = ""
for row in reflected_row_strings:
if space >= 0:
row = row[::-1] + row
# Overlap
else:
row = row[:0:-1] + row
st_out = st_out + row + "\n"
else:
# Add spaces on the right of pattern
for row in row_strings:
row = row + space*"-"
space_st = space_st + row + "\n"
new_row_strings = space_st.split("\n")
reflected_row_strings = new_row_strings[:len(row_strings)]
st_out = ""
for row in reflected_row_strings:
if space >= 0:
row = row + row[::-1]
# Overlap
else:
row = row + row[len(row_strings[0])-2::-1]
st_out = st_out + row + "\n"
return st_out
# Function: reflect pattern horizontally
# Input:
# st - pattern string
# spacing - positive integer value, gap between original and reflected pattern
# direction - 'Reflect above' or 'Reflect below', direction to reflect horizontally
# Output: modified string pattern
def reflect_h(st, spacing, direction):
row_strings = st.split("\n")
reflect_st = ""
if spacing >= 0 :
row_strings = row_strings[:-1]
reflected_row_strings = list(reversed(row_strings))
row_length = len(row_strings[0])
# Create string for spacing area
spacing_st = 2*spacing*(row_length*'-' + '\n')
for row in reflected_row_strings:
reflect_st = reflect_st + row + "\n"
if (direction == 'Reflect Above'):
st_out = reflect_st + spacing_st + st
else:
st_out = st + spacing_st + reflect_st
# Overlap
else:
row_strings = row_strings[:-1]
reflected_row_strings = list(reversed(row_strings[1:]))
for row in reflected_row_strings:
reflect_st = reflect_st + row + "\n"
if (direction == 'Reflect Above'):
st_out = reflect_st + st
else:
st_out = st + reflect_st
return(st_out)
# Function: stack string pattern horizontally (by copying original string pattern and placing it above original string pattern)
# Input:
# st - string pattern
# space - positive integer, space between original pattern and copied pattern
# Output: modified string pattern
def stack_h(st, space):
row_strings = st.split("\n")
row_strings = row_strings[:-1]
st_out = ''
for row in row_strings:
st_out += row + space*'-' + row + '\n'
return(st_out)
# Function: stack string pattern horizontally (by copying original string pattern and placing it to the right of original string pattern)
# Input:
# st - string pattern
# space - positive integer, space between original pattern and copied pattern
# Output: modified string pattern
def stack_v(st, space):
row_strings = st.split("\n")
row_length = len(row_strings[0])
spacing_st = space*(row_length*'-' + '\n')
st_out = st + spacing_st + st
return(st_out)
# Function: copies original string pattern top left or bottom right direction
# Input:
# st - string pattern
# space - positive integer, space between original pattern and copied pattern
# Output: modified string pattern
def stack_d(st, space, direction):
row_strings = st.split("\n")
row_strings = row_strings[:-1]
row_height = len(row_strings)
row_length = len(row_strings[0])
left_pattern = ''
right_pattern = ''
st_out = ''
spacing_st = (row_length + space)*'-'
for row in row_strings:
left_pattern += row + spacing_st + '\n'
right_pattern += spacing_st + row + '\n'
if (direction == 'Stack Left'):
st_out += left_pattern + right_pattern
else:
st_out += right_pattern + left_pattern
return(st_out)
# Function: joins two string pattern horizontally
# Input:
# st1, st2 - string patterns
# space - positive integer, gap between two joined patterns
# Output: modified string pattern
def join_patterns(st1, st2, space):
pattern_1 = st1.split("\n")
pattern_1 = pattern_1[:-1]
pattern_2 = st2.split("\n")
pattern_2 = pattern_2[:-1]
height = max(len(pattern_1), len(pattern_2))
space_to_add_p1 = math.ceil( (height - len(pattern_1))/2 )
space_to_add_p2 = math.ceil( (height - len(pattern_2))/2 )
p1 = add_basket_space(st1, space_to_add_p1, 0)
p2 = add_basket_space(st2, space_to_add_p2, 0)
pattern_1 = p1.split("\n")
pattern_1 = pattern_1[:-1]
pattern_2 = p2.split("\n")
pattern_2 = pattern_2[:-1]
st_out = ''
for a,b in zip(pattern_1, pattern_2):
st_out += a + space*'-' + b + '\n'
return(st_out)
| def flip(st, direction):
row_strings = st.split('\n')
row_strings = row_strings[:-1]
st_out = ''
if direction == 'Flip Horizontally':
row_strings = row_strings[::-1]
for row in row_strings:
st_out += row + '\n'
else:
for row in row_strings:
st_out += row[::-1] + '\n'
return st_out
def reflect_v(st, space, direction):
row_strings = st.split('\n')
row_strings = row_strings[:-1]
space_st = ''
if direction == 'Reflect Left':
for row in row_strings:
row = space * '-' + row
space_st = space_st + row + '\n'
new_row_strings = space_st.split('\n')
reflected_row_strings = new_row_strings[:len(row_strings)]
st_out = ''
for row in reflected_row_strings:
if space >= 0:
row = row[::-1] + row
else:
row = row[:0:-1] + row
st_out = st_out + row + '\n'
else:
for row in row_strings:
row = row + space * '-'
space_st = space_st + row + '\n'
new_row_strings = space_st.split('\n')
reflected_row_strings = new_row_strings[:len(row_strings)]
st_out = ''
for row in reflected_row_strings:
if space >= 0:
row = row + row[::-1]
else:
row = row + row[len(row_strings[0]) - 2::-1]
st_out = st_out + row + '\n'
return st_out
def reflect_h(st, spacing, direction):
row_strings = st.split('\n')
reflect_st = ''
if spacing >= 0:
row_strings = row_strings[:-1]
reflected_row_strings = list(reversed(row_strings))
row_length = len(row_strings[0])
spacing_st = 2 * spacing * (row_length * '-' + '\n')
for row in reflected_row_strings:
reflect_st = reflect_st + row + '\n'
if direction == 'Reflect Above':
st_out = reflect_st + spacing_st + st
else:
st_out = st + spacing_st + reflect_st
else:
row_strings = row_strings[:-1]
reflected_row_strings = list(reversed(row_strings[1:]))
for row in reflected_row_strings:
reflect_st = reflect_st + row + '\n'
if direction == 'Reflect Above':
st_out = reflect_st + st
else:
st_out = st + reflect_st
return st_out
def stack_h(st, space):
row_strings = st.split('\n')
row_strings = row_strings[:-1]
st_out = ''
for row in row_strings:
st_out += row + space * '-' + row + '\n'
return st_out
def stack_v(st, space):
row_strings = st.split('\n')
row_length = len(row_strings[0])
spacing_st = space * (row_length * '-' + '\n')
st_out = st + spacing_st + st
return st_out
def stack_d(st, space, direction):
row_strings = st.split('\n')
row_strings = row_strings[:-1]
row_height = len(row_strings)
row_length = len(row_strings[0])
left_pattern = ''
right_pattern = ''
st_out = ''
spacing_st = (row_length + space) * '-'
for row in row_strings:
left_pattern += row + spacing_st + '\n'
right_pattern += spacing_st + row + '\n'
if direction == 'Stack Left':
st_out += left_pattern + right_pattern
else:
st_out += right_pattern + left_pattern
return st_out
def join_patterns(st1, st2, space):
pattern_1 = st1.split('\n')
pattern_1 = pattern_1[:-1]
pattern_2 = st2.split('\n')
pattern_2 = pattern_2[:-1]
height = max(len(pattern_1), len(pattern_2))
space_to_add_p1 = math.ceil((height - len(pattern_1)) / 2)
space_to_add_p2 = math.ceil((height - len(pattern_2)) / 2)
p1 = add_basket_space(st1, space_to_add_p1, 0)
p2 = add_basket_space(st2, space_to_add_p2, 0)
pattern_1 = p1.split('\n')
pattern_1 = pattern_1[:-1]
pattern_2 = p2.split('\n')
pattern_2 = pattern_2[:-1]
st_out = ''
for (a, b) in zip(pattern_1, pattern_2):
st_out += a + space * '-' + b + '\n'
return st_out |
matrix = [[dot == '#' for dot in line.strip()] for line in open('input.txt')]
diffs = [(x, y) for x in (-1, 0, 1) for y in (-1, 0, 1) if (x, y) != (0, 0)]
corners = [(x, y) for x in (0, len(matrix)-1) for y in (0, len(matrix[0])-1)]
for x, y in corners:
matrix[x][y] = True
def neighbors(matrix, x, y):
for i, j in diffs:
if 0 <= i+x < len(matrix) and 0 <= y+j < len(matrix[0]):
yield matrix[x+i][y+j]
else:
yield False
for i in range(100):
new_matrix = [[False] * len(row) for row in matrix]
for x in range(len(matrix)):
for y in range(len(matrix[0])):
neighbor_count = sum(neighbors(matrix, x, y))
if matrix[x][y]:
new_matrix[x][y] = neighbor_count in (2, 3)
else:
new_matrix[x][y] = neighbor_count == 3
matrix = new_matrix
for x, y in corners:
matrix[x][y] = True
print(sum(sum(row) for row in matrix))
| matrix = [[dot == '#' for dot in line.strip()] for line in open('input.txt')]
diffs = [(x, y) for x in (-1, 0, 1) for y in (-1, 0, 1) if (x, y) != (0, 0)]
corners = [(x, y) for x in (0, len(matrix) - 1) for y in (0, len(matrix[0]) - 1)]
for (x, y) in corners:
matrix[x][y] = True
def neighbors(matrix, x, y):
for (i, j) in diffs:
if 0 <= i + x < len(matrix) and 0 <= y + j < len(matrix[0]):
yield matrix[x + i][y + j]
else:
yield False
for i in range(100):
new_matrix = [[False] * len(row) for row in matrix]
for x in range(len(matrix)):
for y in range(len(matrix[0])):
neighbor_count = sum(neighbors(matrix, x, y))
if matrix[x][y]:
new_matrix[x][y] = neighbor_count in (2, 3)
else:
new_matrix[x][y] = neighbor_count == 3
matrix = new_matrix
for (x, y) in corners:
matrix[x][y] = True
print(sum((sum(row) for row in matrix))) |
def multiply(a, b):
c = [[0] * 3 for _ in range(3)]
for i in range(3):
for j in range(3):
for k in range(3):
c[i][j] += a[i][k] * b[k][j]
return c
q = int(input())
for _ in range(q):
x, y, z, t = input().split()
x = float(x)
y = float(y)
z = float(z)
t = int(t)
m = [
[1 - x, y, 0],
[0, 1 - y, z],
[x, 0, 1 - z],
]
mat = None
while t > 0:
if t & 1 == 1:
if mat is None:
mat = [[m[i][j] for j in range(3)] for i in range(3)]
else:
mat = multiply(mat, m)
m = multiply(m, m)
t >>= 1
print(*[sum(mat[i]) for i in range(3)]) | def multiply(a, b):
c = [[0] * 3 for _ in range(3)]
for i in range(3):
for j in range(3):
for k in range(3):
c[i][j] += a[i][k] * b[k][j]
return c
q = int(input())
for _ in range(q):
(x, y, z, t) = input().split()
x = float(x)
y = float(y)
z = float(z)
t = int(t)
m = [[1 - x, y, 0], [0, 1 - y, z], [x, 0, 1 - z]]
mat = None
while t > 0:
if t & 1 == 1:
if mat is None:
mat = [[m[i][j] for j in range(3)] for i in range(3)]
else:
mat = multiply(mat, m)
m = multiply(m, m)
t >>= 1
print(*[sum(mat[i]) for i in range(3)]) |
"""
exchanges. this acts as a routing table
"""
BITMEX = "BITMEX"
DERIBIT = "DERIBIT"
DELTA = "DELTA"
BITTREX = "BITTREX"
KUCOIN = "KUCOIN"
BINANCE = "BINANCE"
KRAKEN = "KRAKEN"
HITBTC = "HITBTC"
CRYPTOPIA = "CRYPTOPIA"
OKEX = "OKEX"
NAMES = [BITMEX, DERIBIT, DELTA, OKEX, BINANCE]
def exchange_exists(name):
return name in NAMES
| """
exchanges. this acts as a routing table
"""
bitmex = 'BITMEX'
deribit = 'DERIBIT'
delta = 'DELTA'
bittrex = 'BITTREX'
kucoin = 'KUCOIN'
binance = 'BINANCE'
kraken = 'KRAKEN'
hitbtc = 'HITBTC'
cryptopia = 'CRYPTOPIA'
okex = 'OKEX'
names = [BITMEX, DERIBIT, DELTA, OKEX, BINANCE]
def exchange_exists(name):
return name in NAMES |
# Exercise 3.1: Rewrite your pay computation to give the employee 1.5 times the
# rate for hours worked above 40 hours.
# Enter Hours: 45
# Enter Rate: 10
# Pay: 475.0
# Python for Everybody: Exploring Data Using Python 3
# by Charles R. Severance
hours = float(input("Enter hours: "))
rate_per_hour = float(input("Enter rate per hour: "))
additional_hours = hours - 40
gross_pay = 0
if additional_hours > 0:
hours_with_rate_per_hour = hours - additional_hours
gross_pay = hours_with_rate_per_hour * rate_per_hour
modified_rate_per_hour = rate_per_hour * 1.5
gross_pay += additional_hours * modified_rate_per_hour
else:
gross_pay = hours * rate_per_hour
print(gross_pay)
| hours = float(input('Enter hours: '))
rate_per_hour = float(input('Enter rate per hour: '))
additional_hours = hours - 40
gross_pay = 0
if additional_hours > 0:
hours_with_rate_per_hour = hours - additional_hours
gross_pay = hours_with_rate_per_hour * rate_per_hour
modified_rate_per_hour = rate_per_hour * 1.5
gross_pay += additional_hours * modified_rate_per_hour
else:
gross_pay = hours * rate_per_hour
print(gross_pay) |
class BaseEmployee():
"The base class for an employee."
# Note: Unlike c#, on initiliazing a child class, the base contructor is not called
# unless specifically called.
def __init__(self, id, city):
"Constructor for the base employee class."
print('Base constructor called.');
self.id = id;
self.city = city;
def __del__(self):
"Will be called on destruction of employee object. Can also be called explicitly."
print(self.__class__.__name__, 'destroyed');
def printEmployee(self):
print("Id:", self.id, "Name:", self.name, "City:", self.city); | class Baseemployee:
"""The base class for an employee."""
def __init__(self, id, city):
"""Constructor for the base employee class."""
print('Base constructor called.')
self.id = id
self.city = city
def __del__(self):
"""Will be called on destruction of employee object. Can also be called explicitly."""
print(self.__class__.__name__, 'destroyed')
def print_employee(self):
print('Id:', self.id, 'Name:', self.name, 'City:', self.city) |
ix.enable_command_history()
app = ix.application
clarisse_win = app.get_event_window()
ix.application.open_edit_color_space_window(clarisse_win)
ix.disable_command_history()
| ix.enable_command_history()
app = ix.application
clarisse_win = app.get_event_window()
ix.application.open_edit_color_space_window(clarisse_win)
ix.disable_command_history() |
distanca = int(input())
tempo = (2 * distanca)
print('%d minutos' %tempo) | distanca = int(input())
tempo = 2 * distanca
print('%d minutos' % tempo) |
def sayhello(name=None):
if name is None:
return "Hello World, Everyone!"
else:
return f"Hello World, {name}"
| def sayhello(name=None):
if name is None:
return 'Hello World, Everyone!'
else:
return f'Hello World, {name}' |
def binary_and(a: int , b: int) -> str:
"""
Take in 2 integers, convert them to binary,
return a binary number that is the
result of a binary and operation on the integers provided.
"""
if a < 0 or b < 0:
raise ValueError('The value of both number must be positive')
a_bin = str(bin(a))[2:] # remove the leading "0b"
b_bin = str(bin(b))[2:] # remove the leading "0b"
max_length = max( len(a_bin) , len(b_bin) )
return '0b' + "".join(
str( int( a_bit == '1' and b_bit == '1' ) )
for a_bit , b_bit in zip(a_bin.zfill(max_length) , b_bin.zfill(max_length))
)
if __name__ == '__main__':
print( binary_and(2 , 600) )
| def binary_and(a: int, b: int) -> str:
"""
Take in 2 integers, convert them to binary,
return a binary number that is the
result of a binary and operation on the integers provided.
"""
if a < 0 or b < 0:
raise value_error('The value of both number must be positive')
a_bin = str(bin(a))[2:]
b_bin = str(bin(b))[2:]
max_length = max(len(a_bin), len(b_bin))
return '0b' + ''.join((str(int(a_bit == '1' and b_bit == '1')) for (a_bit, b_bit) in zip(a_bin.zfill(max_length), b_bin.zfill(max_length))))
if __name__ == '__main__':
print(binary_and(2, 600)) |
def imgcd(m,n):
for i in range(1,min(m,n)+1):
if m%i==0 and n%i==0:
mcrf=i
return mcrf
a=input()
b=input()
c=imgcd(int(a),int(b))
print(c) | def imgcd(m, n):
for i in range(1, min(m, n) + 1):
if m % i == 0 and n % i == 0:
mcrf = i
return mcrf
a = input()
b = input()
c = imgcd(int(a), int(b))
print(c) |
class Tape(object):
blank = " "
def __init__(self, tape):
self.tape = tape
self.head = 0
| class Tape(object):
blank = ' '
def __init__(self, tape):
self.tape = tape
self.head = 0 |
''''
Problem:
Determine if two strings are permutations.
Assumptions:
String is composed of lower 128 ASCII characters.
Capitalization matters.
'''
def isPerm(s1, s2):
if len(s1) != len(s2):
return False
arr1 = [0] * 128
arr2 = [0] * 128
for c, d in zip(s1, s2):
arr1[ord(c)] += 1
arr2[ord(d)] += 1
for i in xrange(len(arr1)):
if arr1[i] != arr2[i]:
return False
return True
def test():
s1 = "read"
s2 = "dear"
assert isPerm(s1, s2) == True
s1 = "read"
s2 = "red"
assert isPerm(s1, s2) == False
s1 = "read"
s2 = "race"
assert isPerm(s1, s2) == False
s1 = "Read"
s2 = "read"
assert isPerm(s1, s2) == False
print("Test passed")
test()
| """'
Problem:
Determine if two strings are permutations.
Assumptions:
String is composed of lower 128 ASCII characters.
Capitalization matters.
"""
def is_perm(s1, s2):
if len(s1) != len(s2):
return False
arr1 = [0] * 128
arr2 = [0] * 128
for (c, d) in zip(s1, s2):
arr1[ord(c)] += 1
arr2[ord(d)] += 1
for i in xrange(len(arr1)):
if arr1[i] != arr2[i]:
return False
return True
def test():
s1 = 'read'
s2 = 'dear'
assert is_perm(s1, s2) == True
s1 = 'read'
s2 = 'red'
assert is_perm(s1, s2) == False
s1 = 'read'
s2 = 'race'
assert is_perm(s1, s2) == False
s1 = 'Read'
s2 = 'read'
assert is_perm(s1, s2) == False
print('Test passed')
test() |
#Write a function to find the longest common prefix string amongst an array of strings.
#If there is no common prefix, return an empty string "".
def longest_common_prefix(strs) -> str:
common = ""
strs.sort()
for i in range(0, len(strs[0])):
if strs[0][i] == strs[-1][i]:
common += strs[0][i]
if strs[0][i] != strs[-1][i]:
break
return common
print(longest_common_prefix(["flow", "flower", "flowing"]))
| def longest_common_prefix(strs) -> str:
common = ''
strs.sort()
for i in range(0, len(strs[0])):
if strs[0][i] == strs[-1][i]:
common += strs[0][i]
if strs[0][i] != strs[-1][i]:
break
return common
print(longest_common_prefix(['flow', 'flower', 'flowing'])) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.