content
stringlengths 7
1.05M
| fixed_cases
stringlengths 1
1.28M
|
|---|---|
# -*- coding:utf-8 -*-
pizza = {
'crust': 'thick',
'toppings': ['mushrooms', 'extra cheese'],
}
|
pizza = {'crust': 'thick', 'toppings': ['mushrooms', 'extra cheese']}
|
# You may remember by now that while loops use the condition to check when
# to exit. The body of the while loop needs to make sure that the condition begin
# checked will change. If it doesn't change, the loop may never finish and we get
# what's called an infinite loop, a loop that keeps executing and never stops.
# Check out this example. It uses the modulo operator that we saw a while back.
# This cycle will finish for positive and negative values of x. But what would
# happen if x was zero? The remainder of 0 divided by 2 is 0, so the condition
# would be true. The result of dividing 0 by 2 would also be zero, so the value of
# x wouldn't change. This loop would go on for ever, and so we'd get an infinite
# loop. If our code was called with x having the value of zero, the computer
# would just waster resources doing a division that would never lead to the loop
# stopping. The program would be stuck in an infinite loop circling background
# endlessly, and we don't want that. All that looping might make your computer
# dizzy. To avoid this, we need to think about what needs to be different than zero.
# So we could nest this while loop inside an if statement just like this. With this
# approach, the while loop is executed only when x is not zero. Alternatively, we
# could add the condition directly to the loop using a logical operator like in this
# example. This makes sure we only enter the body of the loop for values of x
# that are both different than zero and even. Talking about infinite loop reminds
# me of one of the first times I used while loops myself. I wrote a script that
# emailed me as a way of verifying that the code worked, and while some
# condition was true, I forgot to exit the loop. Turns out those e-mails get sent
# faster than once per second. As you can imagine, I got about 500 e-mails
# before I realized what was going on. Infinitely grateful for that little lesson.
# When you're done laughing at my story, remember, when you're writing loops,
# it's a good idea to take a moment to consider the different values a variable
# can take. This helps you make sure your loop won't get stuck, If you see that
# your program is running forever without finishing, have a second look at your
# loops to check there's no infinite loop hiding somewhere in the code. While
# you need to watch out for infinite loops, they are not always a bad thing.
# Sometimes you actually want your program to execute continuously until
# some external condition is met. If you've used the ping utility on Linux or
# macOS system, or ping-t on a Windows system, you've seen an infinite loop in
# action. This tool will keep sending packets and printing the results to the
# terminal unless you send it the interrupt signal, usually pressing Ctrl+C. If you
# were looking at the program source code you'll see that it uses an infinite loop
# to do hits with a block of code with instructions to keep sending the packets
# forever. One thing to call out is it should always be possible to break the loop
# by sending a certain signal. In the ping example, that signal is the user pressing
# Ctrl+C. In other cases, it could be that the user pressed the button on a
# graphical application, or that another program sent a specific signal, or even
# that a time limit was reached. In your code, you could have an infinite loop that
# looks something like this. In Python, we use the break keyword which you can
# see here to signal that the current loop should stop running. We can use it not
# only to stop infinite loops but also to stop a loop early if the code has already
# achieved what's needed. So quick refresh. How do you avoid the most
# common pitfalls when writing while loops? First, remember to initialize your
# variables, and second, check that your loops won't run forever. Wow, All this
# talk of loops is making me feel a little loopy. I'm going to have to go and lie
# down while you do the next practice quiz. Best of luck, and meet me over in
# the next video when you're done.
# The following code causes an infinite loop. Can you figure out what's missing
# and how to fix it?
def print_range(start, end):
# Loop through the numbers from stand to end
n = start
while n <= end:
print(n)
n += 1
print_range(1, 5) # Should print 1 2 3 4 5 (each number on its own line)
|
def print_range(start, end):
n = start
while n <= end:
print(n)
n += 1
print_range(1, 5)
|
"""
*Sounding State*
A type describing state of data soundness.
"""
class SoundingState(
StatefulPhantomClass,
):
pass
|
"""
*Sounding State*
A type describing state of data soundness.
"""
class Soundingstate(StatefulPhantomClass):
pass
|
"""
Top level of MQTT IO package.
"""
VERSION = "2.1.4"
|
"""
Top level of MQTT IO package.
"""
version = '2.1.4'
|
DOMAIN = "audiconnect"
CONF_VIN = "vin"
CONF_CARNAME = "carname"
CONF_ACTION = "action"
MIN_UPDATE_INTERVAL = 5
DEFAULT_UPDATE_INTERVAL = 10
CONF_SPIN = "spin"
CONF_REGION = "region"
CONF_SERVICE_URL = "service_url"
CONF_MUTABLE = "mutable"
SIGNAL_STATE_UPDATED = "{}.updated".format(DOMAIN)
TRACKER_UPDATE = f"{DOMAIN}_tracker_update"
RESOURCES = [
"position",
"last_update_time",
"mileage",
"range",
"service_inspection_time",
"service_inspection_distance",
"oil_change_time",
"oil_change_distance",
"oil_level",
"charging_state",
"max_charge_current",
"engine_type1",
"engine_type2",
"parking_light",
"any_window_open",
"any_door_unlocked",
"any_door_open",
"trunk_unlocked",
"trunk_open",
"hood_open",
"tank_level",
"state_of_charge",
"remaining_charging_time",
"plug_state",
"sun_roof",
"doors_trunk_status",
]
COMPONENTS = {
"sensor": "sensor",
"binary_sensor": "binary_sensor",
"lock": "lock",
"device_tracker": "device_tracker",
"switch": "switch",
}
|
domain = 'audiconnect'
conf_vin = 'vin'
conf_carname = 'carname'
conf_action = 'action'
min_update_interval = 5
default_update_interval = 10
conf_spin = 'spin'
conf_region = 'region'
conf_service_url = 'service_url'
conf_mutable = 'mutable'
signal_state_updated = '{}.updated'.format(DOMAIN)
tracker_update = f'{DOMAIN}_tracker_update'
resources = ['position', 'last_update_time', 'mileage', 'range', 'service_inspection_time', 'service_inspection_distance', 'oil_change_time', 'oil_change_distance', 'oil_level', 'charging_state', 'max_charge_current', 'engine_type1', 'engine_type2', 'parking_light', 'any_window_open', 'any_door_unlocked', 'any_door_open', 'trunk_unlocked', 'trunk_open', 'hood_open', 'tank_level', 'state_of_charge', 'remaining_charging_time', 'plug_state', 'sun_roof', 'doors_trunk_status']
components = {'sensor': 'sensor', 'binary_sensor': 'binary_sensor', 'lock': 'lock', 'device_tracker': 'device_tracker', 'switch': 'switch'}
|
def first_last6(list1: list) -> bool:
"""Return True if either/both first and last element are assigned a value of 6
>>> first_last6(test_list1)
False
>>> first_last6(test_list2)
True
>>> first_last6(test_list3)
True
"""
if list1[0] or list1[5] == 6:
return True
else:
return False
test_list1 = [0, 1, 2, 3, 4, 5]
test_list2 = [6, 1, 2, 3, 4, 9]
test_list3 = [6, 1, 2, 3, 4, 6]
print(first_last6(test_list1))
print(first_last6(test_list2))
print(first_last6(test_list3))
|
def first_last6(list1: list) -> bool:
"""Return True if either/both first and last element are assigned a value of 6
>>> first_last6(test_list1)
False
>>> first_last6(test_list2)
True
>>> first_last6(test_list3)
True
"""
if list1[0] or list1[5] == 6:
return True
else:
return False
test_list1 = [0, 1, 2, 3, 4, 5]
test_list2 = [6, 1, 2, 3, 4, 9]
test_list3 = [6, 1, 2, 3, 4, 6]
print(first_last6(test_list1))
print(first_last6(test_list2))
print(first_last6(test_list3))
|
class Mouse:
__slots__=(
'_system_cursor',
'has_mouse'
)
def __init__(self):
self._system_cursor = ez.window.panda_winprops.get_cursor_filename()
self.has_mouse = ez.panda_showbase.mouseWatcherNode.has_mouse
def hide(self):
ez.window.panda_winprops.set_cursor_hidden(True)
ez.panda_showbase.win.request_properties(ez.window.panda_winprops)
def show(self):
ez.window.panda_winprops.set_cursor_hidden(False)
ez.panda_showbase.win.request_properties(ez.window.panda_winprops)
@property
def cursor(self):
return ez.window.panda_winprops.get_cursor_filename()
ez.panda_showbase.win.request_properties(ez.window.panda_winprops)
@cursor.setter
def cursor(self, cursor):
if cursor:
ez.window.panda_winprops.set_cursor_filename(cursor)
else:
ez.window.panda_winprops.set_cursor_filename(self._system_cursor)
ez.panda_showbase.win.request_properties(ez.window.panda_winprops)
@property
def mouse_pos(self):
return ez.panda_showbase.mouseWatcherNode.get_mouse()
@property
def pos(self):
# Convert mouse coordinates to aspect2D coordinates:
mpos = ez.panda_showbase.mouseWatcherNode.get_mouse()
pos = aspect2d.get_relative_point(render, (mpos.x, mpos.y, 0))
return pos.xy
@pos.setter
def pos(self, pos):
# Have to convert aspect2D position to window coordinates:
x, y = pos
w, h = ez.panda_showbase.win.get_size()
cpos = ez.panda_showbase.camera2d.get_pos()
L, R, T, B = ez.window.get_aspect2D_edges()
# Get aspect2D size:
aw = R-L
ah = T-B
# Get mouse pos equivalent to window cordinates:
mx = x+R
my = abs(y+B)
# Convert the mouse pos to window position:
x = mx/aw*w
y = my/ah*h
ez.panda_showbase.win.move_pointer(0, round(x), round(y))
|
class Mouse:
__slots__ = ('_system_cursor', 'has_mouse')
def __init__(self):
self._system_cursor = ez.window.panda_winprops.get_cursor_filename()
self.has_mouse = ez.panda_showbase.mouseWatcherNode.has_mouse
def hide(self):
ez.window.panda_winprops.set_cursor_hidden(True)
ez.panda_showbase.win.request_properties(ez.window.panda_winprops)
def show(self):
ez.window.panda_winprops.set_cursor_hidden(False)
ez.panda_showbase.win.request_properties(ez.window.panda_winprops)
@property
def cursor(self):
return ez.window.panda_winprops.get_cursor_filename()
ez.panda_showbase.win.request_properties(ez.window.panda_winprops)
@cursor.setter
def cursor(self, cursor):
if cursor:
ez.window.panda_winprops.set_cursor_filename(cursor)
else:
ez.window.panda_winprops.set_cursor_filename(self._system_cursor)
ez.panda_showbase.win.request_properties(ez.window.panda_winprops)
@property
def mouse_pos(self):
return ez.panda_showbase.mouseWatcherNode.get_mouse()
@property
def pos(self):
mpos = ez.panda_showbase.mouseWatcherNode.get_mouse()
pos = aspect2d.get_relative_point(render, (mpos.x, mpos.y, 0))
return pos.xy
@pos.setter
def pos(self, pos):
(x, y) = pos
(w, h) = ez.panda_showbase.win.get_size()
cpos = ez.panda_showbase.camera2d.get_pos()
(l, r, t, b) = ez.window.get_aspect2D_edges()
aw = R - L
ah = T - B
mx = x + R
my = abs(y + B)
x = mx / aw * w
y = my / ah * h
ez.panda_showbase.win.move_pointer(0, round(x), round(y))
|
n = int(input())
s = set(map(int, input().split()))
for i in range(int(input())):
f = input().split()
if (f[0] == "pop"):
s.pop()
elif (f[0] == "remove"):
s.remove(int(f[-1]))
else:
s.discard(int(f[-1]))
print(sum(s))
|
n = int(input())
s = set(map(int, input().split()))
for i in range(int(input())):
f = input().split()
if f[0] == 'pop':
s.pop()
elif f[0] == 'remove':
s.remove(int(f[-1]))
else:
s.discard(int(f[-1]))
print(sum(s))
|
# ------------------------------------------------------------------------------------
# Tutorial: Learn how to use Dictionaries in Python
# ------------------------------------------------------------------------------------
# Dictionaries are a collection of key-value pairs.
# Keys can only appear once in a dictionary but can be of any type.
# Dictionaries are unordered.
# Values can appear in any number of keys.
# Keys can be of almost any type, values can be of any type.
# Defining a dictionary
# Dictionaries are assigned using a pair of curly brackets.
# Key pair values are assigned within the curly brackets with a : between the key and value
# Each pair is separated by a comma
my_dict = {
'my_key': 'my value',
'your_key': 42,
5: 10,
'speed': 20.0,
}
# Assigning key-value pairs
# Adding key pairs to an existing dictionary
my_dict['their_key'] = 3.142
# Retreiving a value
retrieved = my_dict['my_key']
print("Value of 'my_key': " + str(retrieved)) # Should print "Value of 'my_key': my value"
retrieved = my_dict.get('your_key')
print("Value of 'your_key': " + str(retrieved)) # Should print "Value of 'your_key': 42"
# With either of the above options Python will throw a key error if the key doesn't exist.
# To fix this dictionary.get() can be used to return a default value if no key exists
retrieved = my_dict.get('non_existent_key', 'Not here.')
print("Value of 'non_existent_key': " + str(retrieved)) # Should print "Value of 'non_existent_key' not here"
print("")
# ------------------------------------------------------------------------------------
# Challenge: Create a dictionary called person.
# The person dictionary should contain the following keys:
# name, height, age
# With the following values:
# 'Sally', 154.9, 15
# Add a key called occupation with value 'student'
# Update the value of age to 18
# Remember to uncomment the print lines
# You should see the output
# Person is called Sally
# Person is 18
# Person is 154.9cm
# Person is student
# ------------------------------------------------------------------------------------
# Define person dictionary here
# Add occupation key here
# Increase the age to 18 here
# Uncomment the lines below once you have completed the challenge
# print("Person is called " + str(person.get("name", "Unnamed")))
# print("Person is " + str(person.get("age", "Ageless")))
# print("Person is " + str(person.get("height", "Tiny")) + "cm")
# print("Person is " + str(person.get("occupation", "Unemployed")))
|
my_dict = {'my_key': 'my value', 'your_key': 42, 5: 10, 'speed': 20.0}
my_dict['their_key'] = 3.142
retrieved = my_dict['my_key']
print("Value of 'my_key': " + str(retrieved))
retrieved = my_dict.get('your_key')
print("Value of 'your_key': " + str(retrieved))
retrieved = my_dict.get('non_existent_key', 'Not here.')
print("Value of 'non_existent_key': " + str(retrieved))
print('')
|
def setup():
noLoop()
size(500, 500)
noStroke()
smooth()
def draw():
background(50)
fill(94, 206, 40, 100)
ellipse(250, 100, 160, 160)
fill(94, 206, 40, 150)
ellipse(250, 200, 160, 160)
fill(94, 206, 40, 200)
ellipse(250, 300, 160, 160)
fill(94, 206, 40, 250)
ellipse(250, 400, 160, 160)
|
def setup():
no_loop()
size(500, 500)
no_stroke()
smooth()
def draw():
background(50)
fill(94, 206, 40, 100)
ellipse(250, 100, 160, 160)
fill(94, 206, 40, 150)
ellipse(250, 200, 160, 160)
fill(94, 206, 40, 200)
ellipse(250, 300, 160, 160)
fill(94, 206, 40, 250)
ellipse(250, 400, 160, 160)
|
def test_get_condition_new():
scraper = Scraper('Apple', 3000, 'new')
result = scraper.condition_code
assert result == 1000
def test_get_condition_used():
scraper = Scraper('Apple', 3000, 'used')
result = scraper.condition_code
assert result == 3000
def test_get_condition_error():
scraper = Scraper('Apple', 3000, 'something else')
with pytest.raises(KeyError):
scraper.condition_code
def test_get_brand_id_apple():
scraper = Scraper('Apple', 3000, 'used')
result = scraper.brand_id
assert result == 319682
def test_get_brand_id_lg():
scraper = Scraper('LG', 3000, 'used')
result = scraper.brand_id
assert result == 353985
def test_get_brand_id_huawei():
scraper = Scraper('Huawei', 3000, 'used')
result = scraper.brand_id
assert result == 349965
def test_get_brand_id_samsung():
scraper = Scraper('Samsung', 3000, 'used')
result = scraper.brand_id
assert result == 352130
def test_get_brand_id_error():
scraper = Scraper('Something else', 3000, 'new')
with pytest.raises(KeyError):
scraper.brand_id
def test_get_num_of_pages_true():
scraper = Scraper('Apple', 48, 'new')
result = scraper.num_of_pages
assert result == 1
def test_get_num_of_pages_error():
scraper = Scraper('Something else', '3000', 'new')
with pytest.raises(TypeError):
scraper.num_of_pages
|
def test_get_condition_new():
scraper = scraper('Apple', 3000, 'new')
result = scraper.condition_code
assert result == 1000
def test_get_condition_used():
scraper = scraper('Apple', 3000, 'used')
result = scraper.condition_code
assert result == 3000
def test_get_condition_error():
scraper = scraper('Apple', 3000, 'something else')
with pytest.raises(KeyError):
scraper.condition_code
def test_get_brand_id_apple():
scraper = scraper('Apple', 3000, 'used')
result = scraper.brand_id
assert result == 319682
def test_get_brand_id_lg():
scraper = scraper('LG', 3000, 'used')
result = scraper.brand_id
assert result == 353985
def test_get_brand_id_huawei():
scraper = scraper('Huawei', 3000, 'used')
result = scraper.brand_id
assert result == 349965
def test_get_brand_id_samsung():
scraper = scraper('Samsung', 3000, 'used')
result = scraper.brand_id
assert result == 352130
def test_get_brand_id_error():
scraper = scraper('Something else', 3000, 'new')
with pytest.raises(KeyError):
scraper.brand_id
def test_get_num_of_pages_true():
scraper = scraper('Apple', 48, 'new')
result = scraper.num_of_pages
assert result == 1
def test_get_num_of_pages_error():
scraper = scraper('Something else', '3000', 'new')
with pytest.raises(TypeError):
scraper.num_of_pages
|
"""
Hao Ren
11 October, 2021
495. Teemo Attacking
"""
class Solution(object):
def findPoisonedDuration(self, timeSeries, duration):
"""
:type timeSeries: List[int]
:type duration: int
:rtype: int
"""
time = 0
length = len(timeSeries)
for i in range(length - 1):
time += min(timeSeries[i + 1] - timeSeries[i], duration)
return time + duration
|
"""
Hao Ren
11 October, 2021
495. Teemo Attacking
"""
class Solution(object):
def find_poisoned_duration(self, timeSeries, duration):
"""
:type timeSeries: List[int]
:type duration: int
:rtype: int
"""
time = 0
length = len(timeSeries)
for i in range(length - 1):
time += min(timeSeries[i + 1] - timeSeries[i], duration)
return time + duration
|
def get_median( arr ):
size = len(arr)
mid_pos = size // 2
if size % 2 == 0:
# size is even
median = ( arr[mid_pos-1] + arr[mid_pos] ) / 2
else:
# size is odd
median = arr[mid_pos]
return (median)
def collect_Q1_Q2_Q3( arr ):
# Preprocessing
# in-place sorting
arr.sort()
Q2 = get_median( arr )
size = len(arr)
mid = size // 2
if size % 2 == 0:
# size is even
Q1 = get_median( arr[:mid] )
Q3 = get_median( arr[mid:] )
else:
# size is odd
Q1 = get_median( arr[:mid] )
Q3 = get_median( arr[mid+1:] )
return (Q1, Q2, Q3)
def expand_to_flat_list( element_arr, freq_arr ):
flat_list = []
for index in range( len(element_arr) ):
cur_element = element_arr[ index ]
cur_freq = freq_arr[ index ]
# repeat current element with cur_freq times
cur_list = [ cur_element ] * cur_freq
flat_list += cur_list
return flat_list
def get_interquartile_range( arr ):
Q1, Q2, Q3 = collect_Q1_Q2_Q3( arr )
return (Q3-Q1)
if __name__ == '__main__':
# Enter your code here. Read input from STDIN. Print output to STDOUT
n = int( input() )
element_arr = list( map(int, input().strip().split() ) )
frequency_arr = list( map(int, input().strip().split() ) )
flat_list = expand_to_flat_list( element_arr, frequency_arr)
inter_quartile_range = get_interquartile_range( flat_list )
print( "%.1f" % inter_quartile_range )
|
def get_median(arr):
size = len(arr)
mid_pos = size // 2
if size % 2 == 0:
median = (arr[mid_pos - 1] + arr[mid_pos]) / 2
else:
median = arr[mid_pos]
return median
def collect_q1_q2_q3(arr):
arr.sort()
q2 = get_median(arr)
size = len(arr)
mid = size // 2
if size % 2 == 0:
q1 = get_median(arr[:mid])
q3 = get_median(arr[mid:])
else:
q1 = get_median(arr[:mid])
q3 = get_median(arr[mid + 1:])
return (Q1, Q2, Q3)
def expand_to_flat_list(element_arr, freq_arr):
flat_list = []
for index in range(len(element_arr)):
cur_element = element_arr[index]
cur_freq = freq_arr[index]
cur_list = [cur_element] * cur_freq
flat_list += cur_list
return flat_list
def get_interquartile_range(arr):
(q1, q2, q3) = collect_q1_q2_q3(arr)
return Q3 - Q1
if __name__ == '__main__':
n = int(input())
element_arr = list(map(int, input().strip().split()))
frequency_arr = list(map(int, input().strip().split()))
flat_list = expand_to_flat_list(element_arr, frequency_arr)
inter_quartile_range = get_interquartile_range(flat_list)
print('%.1f' % inter_quartile_range)
|
class YamboSpectra():
"""
Class to show optical absorption spectra
"""
def __init__(self,energies,data):
self.energies = energies
self.data = data
|
class Yambospectra:
"""
Class to show optical absorption spectra
"""
def __init__(self, energies, data):
self.energies = energies
self.data = data
|
def vowelCount(str):
count = 0
for i in str:
if i == "a" or i == "e" or i == "u" or i == "i" or i == "o":
count += 1
print(count)
exString = "Count the vowels in me!"
vowelCount(exString)
|
def vowel_count(str):
count = 0
for i in str:
if i == 'a' or i == 'e' or i == 'u' or (i == 'i') or (i == 'o'):
count += 1
print(count)
ex_string = 'Count the vowels in me!'
vowel_count(exString)
|
def test_add_two_params():
expected = 5
actual = add(2, 3)
assert expected == actual
def test_add_three_params():
expected = 9
actual = add(2, 3, 4)
assert expected == actual
def add(a, b, c=None):
if c is None:
return a + b
else:
return a + b + c
|
def test_add_two_params():
expected = 5
actual = add(2, 3)
assert expected == actual
def test_add_three_params():
expected = 9
actual = add(2, 3, 4)
assert expected == actual
def add(a, b, c=None):
if c is None:
return a + b
else:
return a + b + c
|
# pylint: disable=R0903
"""test __init__ return
"""
__revision__ = 'yo'
class MyClass(object):
"""dummy class"""
def __init__(self):
return 1
class MyClass2(object):
"""dummy class"""
def __init__(self):
return
class MyClass3(object):
"""dummy class"""
def __init__(self):
return None
class MyClass4(object):
"""dummy class"""
def __init__(self):
yield None
class MyClass5(object):
"""dummy class"""
def __init__(self):
self.callable = lambda: (yield None)
|
"""test __init__ return
"""
__revision__ = 'yo'
class Myclass(object):
"""dummy class"""
def __init__(self):
return 1
class Myclass2(object):
"""dummy class"""
def __init__(self):
return
class Myclass3(object):
"""dummy class"""
def __init__(self):
return None
class Myclass4(object):
"""dummy class"""
def __init__(self):
yield None
class Myclass5(object):
"""dummy class"""
def __init__(self):
self.callable = lambda : (yield None)
|
l = [58, 60, 67, 72, 76, 74, 79]
s = '['
for ll in l:
s += ' %i' % (ll + 9)
s += ' ]'
print(s)
|
l = [58, 60, 67, 72, 76, 74, 79]
s = '['
for ll in l:
s += ' %i' % (ll + 9)
s += ' ]'
print(s)
|
{
"variables": {
"GTK_Root%": "c:\\gtk",
"conditions": [
[ "OS == 'mac'", {
"pkg_env": "PKG_CONFIG_PATH=/opt/X11/lib/pkgconfig"
}, {
"pkg_env": ""
}]
]
},
"targets": [
{
"target_name": "rsvg",
"sources": [
"src/Rsvg.cc",
"src/Enums.cc",
"src/Autocrop.cc"
],
"include_dirs": [
"<!(node -e \"require('nan')\")"
],
"variables": {
"packages": "librsvg-2.0 cairo-png cairo-pdf cairo-svg",
"conditions": [
[ "OS!='win'", {
"libraries": "<!(<(pkg_env) pkg-config --libs-only-l <(packages))",
"ldflags": "<!(<(pkg_env) pkg-config --libs-only-L --libs-only-other <(packages))",
"cflags": "<!(<(pkg_env) pkg-config --cflags <(packages))"
}, { # else OS!='win'
"include_dirs": "<!(<(python) tools/include_dirs.py <(GTK_Root) <(packages))"
} ]
]
},
"conditions": [
[ "OS!='mac' and OS!='win'", {
"cflags": [
"<@(cflags)",
"-std=c++0x"
],
"ldflags": [
"<@(ldflags)"
],
"libraries": [
"<@(libraries)"
],
} ],
[ "OS=='mac'", {
"xcode_settings": {
"OTHER_CFLAGS": [
"<@(cflags)"
],
"OTHER_LDFLAGS": [
"<@(ldflags)"
]
},
"libraries": [
"<@(libraries)"
],
} ],
[ "OS=='win'", {
"sources+": [
"src/win32-math.cc"
],
"include_dirs": [
"<@(include_dirs)"
],
"libraries": [
'librsvg-2.dll.a',
'glib-2.0.lib',
'gobject-2.0.lib',
'cairo.lib'
],
"msvs_settings": {
'VCCLCompilerTool': {
'AdditionalOptions': [
"/EHsc"
]
}
},
"msbuild_settings": {
"Link": {
"AdditionalLibraryDirectories": [
"<(GTK_Root)\\lib"
],
"ImageHasSafeExceptionHandlers": "false"
}
}
} ]
]
}
]
}
|
{'variables': {'GTK_Root%': 'c:\\gtk', 'conditions': [["OS == 'mac'", {'pkg_env': 'PKG_CONFIG_PATH=/opt/X11/lib/pkgconfig'}, {'pkg_env': ''}]]}, 'targets': [{'target_name': 'rsvg', 'sources': ['src/Rsvg.cc', 'src/Enums.cc', 'src/Autocrop.cc'], 'include_dirs': ['<!(node -e "require(\'nan\')")'], 'variables': {'packages': 'librsvg-2.0 cairo-png cairo-pdf cairo-svg', 'conditions': [["OS!='win'", {'libraries': '<!(<(pkg_env) pkg-config --libs-only-l <(packages))', 'ldflags': '<!(<(pkg_env) pkg-config --libs-only-L --libs-only-other <(packages))', 'cflags': '<!(<(pkg_env) pkg-config --cflags <(packages))'}, {'include_dirs': '<!(<(python) tools/include_dirs.py <(GTK_Root) <(packages))'}]]}, 'conditions': [["OS!='mac' and OS!='win'", {'cflags': ['<@(cflags)', '-std=c++0x'], 'ldflags': ['<@(ldflags)'], 'libraries': ['<@(libraries)']}], ["OS=='mac'", {'xcode_settings': {'OTHER_CFLAGS': ['<@(cflags)'], 'OTHER_LDFLAGS': ['<@(ldflags)']}, 'libraries': ['<@(libraries)']}], ["OS=='win'", {'sources+': ['src/win32-math.cc'], 'include_dirs': ['<@(include_dirs)'], 'libraries': ['librsvg-2.dll.a', 'glib-2.0.lib', 'gobject-2.0.lib', 'cairo.lib'], 'msvs_settings': {'VCCLCompilerTool': {'AdditionalOptions': ['/EHsc']}}, 'msbuild_settings': {'Link': {'AdditionalLibraryDirectories': ['<(GTK_Root)\\lib'], 'ImageHasSafeExceptionHandlers': 'false'}}}]]}]}
|
def is_even_with_return(i):
print('with return')
remainder = i % 2
return remainder == 0
print(is_even_with_return(132))
def is_even(i):
return i % 2 == 0
print("All numbers between 0 and 20: even or not")
for i in range(20):
if is_even(i):
print(i, "even")
else:
print(i, "odd")
def func_a():
print('inside func_a')
def func_b(y):
print('inside func_b')
return y
def func_c(z):
print('inside func_c')
return z()
print(func_c(func_a))
def f():
def x(a, b):
return a+b
return x
val = f()(3,4)
print(val)
|
def is_even_with_return(i):
print('with return')
remainder = i % 2
return remainder == 0
print(is_even_with_return(132))
def is_even(i):
return i % 2 == 0
print('All numbers between 0 and 20: even or not')
for i in range(20):
if is_even(i):
print(i, 'even')
else:
print(i, 'odd')
def func_a():
print('inside func_a')
def func_b(y):
print('inside func_b')
return y
def func_c(z):
print('inside func_c')
return z()
print(func_c(func_a))
def f():
def x(a, b):
return a + b
return x
val = f()(3, 4)
print(val)
|
class gbXMLBuildingOperatingSchedule(Enum,IComparable,IFormattable,IConvertible):
"""
Enumerations for gbXML (Green Building XML) format,used for energy
analysis,schema version 0.34.
enum gbXMLBuildingOperatingSchedule,values: DefaultOperatingSchedule (0),KindergartenThruTwelveGradeSchool (7),NoOfOperatingScheduleEnums (11),TheaterPerformingArts (9),TwelveHourFiveDayFacility (6),TwelveHourSevenDayFacility (4),TwelveHourSixDayFacility (5),TwentyFourHourHourFiveDayFacility (3),TwentyFourHourHourSixDayFacility (2),TwentyFourHourSevenDayFacility (1),Worship (10),YearRoundSchool (8)
"""
def __eq__(self,*args):
""" x.__eq__(y) <==> x==yx.__eq__(y) <==> x==yx.__eq__(y) <==> x==y """
pass
def __format__(self,*args):
""" __format__(formattable: IFormattable,format: str) -> str """
pass
def __ge__(self,*args):
pass
def __gt__(self,*args):
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
def __le__(self,*args):
pass
def __lt__(self,*args):
pass
def __ne__(self,*args):
pass
def __reduce_ex__(self,*args):
pass
def __str__(self,*args):
pass
DefaultOperatingSchedule=None
KindergartenThruTwelveGradeSchool=None
NoOfOperatingScheduleEnums=None
TheaterPerformingArts=None
TwelveHourFiveDayFacility=None
TwelveHourSevenDayFacility=None
TwelveHourSixDayFacility=None
TwentyFourHourHourFiveDayFacility=None
TwentyFourHourHourSixDayFacility=None
TwentyFourHourSevenDayFacility=None
value__=None
Worship=None
YearRoundSchool=None
|
class Gbxmlbuildingoperatingschedule(Enum, IComparable, IFormattable, IConvertible):
"""
Enumerations for gbXML (Green Building XML) format,used for energy
analysis,schema version 0.34.
enum gbXMLBuildingOperatingSchedule,values: DefaultOperatingSchedule (0),KindergartenThruTwelveGradeSchool (7),NoOfOperatingScheduleEnums (11),TheaterPerformingArts (9),TwelveHourFiveDayFacility (6),TwelveHourSevenDayFacility (4),TwelveHourSixDayFacility (5),TwentyFourHourHourFiveDayFacility (3),TwentyFourHourHourSixDayFacility (2),TwentyFourHourSevenDayFacility (1),Worship (10),YearRoundSchool (8)
"""
def __eq__(self, *args):
""" x.__eq__(y) <==> x==yx.__eq__(y) <==> x==yx.__eq__(y) <==> x==y """
pass
def __format__(self, *args):
""" __format__(formattable: IFormattable,format: str) -> str """
pass
def __ge__(self, *args):
pass
def __gt__(self, *args):
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
def __le__(self, *args):
pass
def __lt__(self, *args):
pass
def __ne__(self, *args):
pass
def __reduce_ex__(self, *args):
pass
def __str__(self, *args):
pass
default_operating_schedule = None
kindergarten_thru_twelve_grade_school = None
no_of_operating_schedule_enums = None
theater_performing_arts = None
twelve_hour_five_day_facility = None
twelve_hour_seven_day_facility = None
twelve_hour_six_day_facility = None
twenty_four_hour_hour_five_day_facility = None
twenty_four_hour_hour_six_day_facility = None
twenty_four_hour_seven_day_facility = None
value__ = None
worship = None
year_round_school = None
|
class Solution:
def firstBadVersion(self, n):
if n == 1:
return 1
l, r = 2, n
while l <= r:
mid = (l + r) // 2
if isBadVersion(mid) and not isBadVersion(mid - 1):
return mid
elif isBadVersion(mid):
r = mid - 1
else:
l = mid + 1
return 1
|
class Solution:
def first_bad_version(self, n):
if n == 1:
return 1
(l, r) = (2, n)
while l <= r:
mid = (l + r) // 2
if is_bad_version(mid) and (not is_bad_version(mid - 1)):
return mid
elif is_bad_version(mid):
r = mid - 1
else:
l = mid + 1
return 1
|
class Solution:
def wordPatternMatch(self, pattern, text):
"""
:type pattern: str
:type str: str
:rtype: bool
{
"a": asd
}
asdasdasd
3
""
"""
return self._find_match(pattern, text, 0, 0, {}, set())
def _find_match(self, pattern, text, start_text, curr_pattern_index, pattern_mapping, used_patterns):
if start_text >= len(text):
return curr_pattern_index >= len(pattern)
if curr_pattern_index >= len(pattern):
return start_text >= len(text)
if pattern[curr_pattern_index] not in pattern_mapping: # select a prefix
prefix = ""
for i in range(start_text, len(text)):
prefix += text[i]
if prefix in used_patterns:
continue
pattern_mapping[pattern[curr_pattern_index]] = prefix
used_patterns.add(prefix)
if self._find_match(pattern, text, i+1, curr_pattern_index+1, pattern_mapping, used_patterns):
return True
used_patterns.remove(prefix)
del pattern_mapping[pattern[curr_pattern_index]]
else:
expected_prefix = pattern_mapping[pattern[curr_pattern_index]]
if start_text+len(expected_prefix) > len(text):
return False
prefix = text[start_text: start_text+len(expected_prefix)]
if prefix == expected_prefix:
return self._find_match(pattern, text, start_text+len(expected_prefix), curr_pattern_index+1, pattern_mapping, used_patterns)
return False
|
class Solution:
def word_pattern_match(self, pattern, text):
"""
:type pattern: str
:type str: str
:rtype: bool
{
"a": asd
}
asdasdasd
3
""
"""
return self._find_match(pattern, text, 0, 0, {}, set())
def _find_match(self, pattern, text, start_text, curr_pattern_index, pattern_mapping, used_patterns):
if start_text >= len(text):
return curr_pattern_index >= len(pattern)
if curr_pattern_index >= len(pattern):
return start_text >= len(text)
if pattern[curr_pattern_index] not in pattern_mapping:
prefix = ''
for i in range(start_text, len(text)):
prefix += text[i]
if prefix in used_patterns:
continue
pattern_mapping[pattern[curr_pattern_index]] = prefix
used_patterns.add(prefix)
if self._find_match(pattern, text, i + 1, curr_pattern_index + 1, pattern_mapping, used_patterns):
return True
used_patterns.remove(prefix)
del pattern_mapping[pattern[curr_pattern_index]]
else:
expected_prefix = pattern_mapping[pattern[curr_pattern_index]]
if start_text + len(expected_prefix) > len(text):
return False
prefix = text[start_text:start_text + len(expected_prefix)]
if prefix == expected_prefix:
return self._find_match(pattern, text, start_text + len(expected_prefix), curr_pattern_index + 1, pattern_mapping, used_patterns)
return False
|
"""
Time utilities for lux analysis and replay
"""
# Sunrise sunset data for Sunnyvale, CA, 2016.
# From http://aa.usno.navy.mil/cgi-bin/aa_rstablew.pl?ID=AA&year=2016&task=0&state=CA&place=Sunnyvale
# Eventually use ephem (https://pypi.python.org/pypi/pyephem/) to
# compute the sunrise/sunset.
sunrise_sunset_data =\
"""01 0722 1701 0712 1732 0638 1803 0553 1831 0512 1858 0449 1924 0451 1933 0513 1915 0539 1836 0604 1750 0633 1709 0704 1650
02 0723 1702 0711 1733 0637 1804 0551 1832 0511 1859 0449 1924 0452 1933 0514 1914 0540 1835 0605 1749 0635 1708 0705 1650
03 0723 1703 0710 1734 0636 1805 0550 1833 0510 1900 0448 1925 0452 1932 0515 1913 0541 1833 0606 1747 0636 1707 0706 1650
04 0723 1703 0709 1735 0634 1806 0548 1834 0509 1901 0448 1925 0453 1932 0516 1912 0542 1832 0607 1746 0637 1706 0707 1650
05 0723 1704 0708 1737 0633 1807 0547 1835 0508 1902 0448 1926 0453 1932 0516 1911 0542 1830 0608 1744 0638 1705 0708 1650
06 0723 1705 0707 1738 0631 1808 0545 1836 0507 1903 0448 1927 0454 1932 0517 1910 0543 1829 0608 1743 0639 1704 0709 1650
07 0723 1706 0706 1739 0630 1808 0544 1837 0506 1904 0447 1927 0455 1931 0518 1909 0544 1827 0609 1742 0640 1704 0710 1650
08 0723 1707 0705 1740 0629 1809 0543 1838 0505 1905 0447 1928 0455 1931 0519 1908 0545 1826 0610 1740 0641 1703 0710 1650
09 0723 1708 0704 1741 0627 1810 0541 1839 0504 1906 0447 1928 0456 1931 0520 1907 0546 1824 0611 1739 0642 1702 0711 1650
10 0723 1709 0703 1742 0626 1811 0540 1839 0503 1906 0447 1929 0456 1930 0521 1905 0547 1822 0612 1737 0643 1701 0712 1650
11 0722 1710 0702 1743 0624 1812 0538 1840 0502 1907 0447 1929 0457 1930 0521 1904 0547 1821 0613 1736 0644 1700 0713 1651
12 0722 1711 0701 1744 0623 1813 0537 1841 0501 1908 0447 1930 0458 1930 0522 1903 0548 1819 0614 1734 0645 1659 0713 1651
13 0722 1712 0700 1745 0621 1814 0535 1842 0500 1909 0447 1930 0458 1929 0523 1902 0549 1818 0615 1733 0646 1659 0714 1651
14 0722 1713 0659 1746 0620 1815 0534 1843 0500 1910 0447 1930 0459 1929 0524 1901 0550 1816 0616 1732 0647 1658 0715 1651
15 0721 1714 0658 1747 0618 1816 0533 1844 0459 1911 0447 1931 0500 1928 0525 1859 0551 1815 0617 1730 0648 1657 0716 1652
16 0721 1715 0656 1748 0617 1817 0531 1845 0458 1912 0447 1931 0501 1928 0526 1858 0551 1813 0618 1729 0649 1657 0716 1652
17 0721 1716 0655 1749 0615 1818 0530 1846 0457 1912 0447 1931 0501 1927 0527 1857 0552 1812 0619 1728 0650 1656 0717 1652
18 0720 1717 0654 1751 0614 1819 0529 1847 0456 1913 0447 1932 0502 1926 0527 1856 0553 1810 0620 1726 0651 1655 0717 1653
19 0720 1718 0653 1752 0612 1820 0527 1848 0456 1914 0447 1932 0503 1926 0528 1854 0554 1809 0620 1725 0652 1655 0718 1653
20 0719 1719 0652 1753 0611 1821 0526 1848 0455 1915 0448 1932 0503 1925 0529 1853 0555 1807 0621 1724 0653 1654 0718 1654
21 0719 1720 0650 1754 0609 1821 0525 1849 0454 1916 0448 1932 0504 1924 0530 1852 0556 1806 0622 1722 0654 1654 0719 1654
22 0718 1721 0649 1755 0608 1822 0523 1850 0454 1916 0448 1932 0505 1924 0531 1850 0556 1804 0623 1721 0655 1653 0719 1655
23 0718 1722 0648 1756 0606 1823 0522 1851 0453 1917 0448 1933 0506 1923 0532 1849 0557 1803 0624 1720 0656 1653 0720 1655
24 0717 1723 0647 1757 0605 1824 0521 1852 0453 1918 0449 1933 0507 1922 0532 1847 0558 1801 0625 1719 0657 1652 0720 1656
25 0717 1724 0645 1758 0603 1825 0520 1853 0452 1919 0449 1933 0507 1921 0533 1846 0559 1759 0626 1717 0658 1652 0721 1657
26 0716 1726 0644 1759 0602 1826 0518 1854 0451 1919 0449 1933 0508 1921 0534 1845 0600 1758 0627 1716 0659 1652 0721 1657
27 0715 1727 0643 1800 0600 1827 0517 1855 0451 1920 0450 1933 0509 1920 0535 1843 0601 1756 0628 1715 0700 1651 0721 1658
28 0715 1728 0641 1801 0559 1828 0516 1856 0450 1921 0450 1933 0510 1919 0536 1842 0602 1755 0629 1714 0701 1651 0722 1659
29 0714 1729 0640 1802 0557 1829 0515 1857 0450 1922 0451 1933 0511 1918 0537 1840 0602 1753 0630 1713 0702 1651 0722 1659
30 0713 1730 0556 1830 0514 1857 0450 1922 0451 1933 0511 1917 0537 1839 0603 1752 0631 1712 0703 1651 0722 1700
31 0712 1731 0554 1830 0449 1923 0512 1916 0538 1837 0632 1711 0722 1701"""
DST_START=(3,13)
DST_END=(11,6)
SUNRISE_SUNSET_TABLE=[[None for d in range(31)] for m in range(12)]
def parse_sunrise_sunset_table():
day = 1
for line in sunrise_sunset_data.split('\n'):
assert day==int(line[0:2])
for m in range(12):
start = (m*11)+4
sunrise = line[start:start+4]
sunset = line[start+5:start+10]
month = m+1
if (month>DST_START[0] and month<DST_END[0]) or \
(month==DST_START[0] and day>=DST_START[1]) or \
(month==DST_END[0] and day<DST_END[1]):
dst = 60
else:
dst = 0
if sunrise!=" ":
sunrise_minutes = int(sunrise[0:2])*60+int(sunrise[2:4]) + dst
sunset_minutes = int(sunset[0:2])*60+int(sunset[2:4]) + dst
SUNRISE_SUNSET_TABLE[m][day-1] = (sunrise_minutes, sunset_minutes)
#print("%d day %d, sunrise=%s [%d], sunset=%s [%d]" %
# (m+1, day, sunrise, sunrise_minutes, sunset, sunset_minutes))
day += 1
parse_sunrise_sunset_table()
def get_sunrise_sunset(month, day):
return SUNRISE_SUNSET_TABLE[month-1][day-1]
# # We divide the day into "zones" based on a rough idea of the amount of sunlight.
def time_of_day_to_zone(minutes, sunrise, sunset):
if minutes < sunrise:
return 0 # early morning
elif minutes <= (sunset-30):
return 1 # daytime
elif minutes <= max(sunset+60,21.5*60):
return 2 # evening
else:
return 3 # later evening
NUM_ZONES=4
def dt_to_minutes(dt):
return dt.time().hour*60 + dt.time().minute
def minutes_to_time(minutes):
hrs = int(minutes/60)
mins = minutes-(hrs*60)
assert mins<60
return (hrs, mins)
|
"""
Time utilities for lux analysis and replay
"""
sunrise_sunset_data = '01 0722 1701 0712 1732 0638 1803 0553 1831 0512 1858 0449 1924 0451 1933 0513 1915 0539 1836 0604 1750 0633 1709 0704 1650\n02 0723 1702 0711 1733 0637 1804 0551 1832 0511 1859 0449 1924 0452 1933 0514 1914 0540 1835 0605 1749 0635 1708 0705 1650\n03 0723 1703 0710 1734 0636 1805 0550 1833 0510 1900 0448 1925 0452 1932 0515 1913 0541 1833 0606 1747 0636 1707 0706 1650\n04 0723 1703 0709 1735 0634 1806 0548 1834 0509 1901 0448 1925 0453 1932 0516 1912 0542 1832 0607 1746 0637 1706 0707 1650\n05 0723 1704 0708 1737 0633 1807 0547 1835 0508 1902 0448 1926 0453 1932 0516 1911 0542 1830 0608 1744 0638 1705 0708 1650\n06 0723 1705 0707 1738 0631 1808 0545 1836 0507 1903 0448 1927 0454 1932 0517 1910 0543 1829 0608 1743 0639 1704 0709 1650\n07 0723 1706 0706 1739 0630 1808 0544 1837 0506 1904 0447 1927 0455 1931 0518 1909 0544 1827 0609 1742 0640 1704 0710 1650\n08 0723 1707 0705 1740 0629 1809 0543 1838 0505 1905 0447 1928 0455 1931 0519 1908 0545 1826 0610 1740 0641 1703 0710 1650\n09 0723 1708 0704 1741 0627 1810 0541 1839 0504 1906 0447 1928 0456 1931 0520 1907 0546 1824 0611 1739 0642 1702 0711 1650\n10 0723 1709 0703 1742 0626 1811 0540 1839 0503 1906 0447 1929 0456 1930 0521 1905 0547 1822 0612 1737 0643 1701 0712 1650\n11 0722 1710 0702 1743 0624 1812 0538 1840 0502 1907 0447 1929 0457 1930 0521 1904 0547 1821 0613 1736 0644 1700 0713 1651\n12 0722 1711 0701 1744 0623 1813 0537 1841 0501 1908 0447 1930 0458 1930 0522 1903 0548 1819 0614 1734 0645 1659 0713 1651\n13 0722 1712 0700 1745 0621 1814 0535 1842 0500 1909 0447 1930 0458 1929 0523 1902 0549 1818 0615 1733 0646 1659 0714 1651\n14 0722 1713 0659 1746 0620 1815 0534 1843 0500 1910 0447 1930 0459 1929 0524 1901 0550 1816 0616 1732 0647 1658 0715 1651\n15 0721 1714 0658 1747 0618 1816 0533 1844 0459 1911 0447 1931 0500 1928 0525 1859 0551 1815 0617 1730 0648 1657 0716 1652\n16 0721 1715 0656 1748 0617 1817 0531 1845 0458 1912 0447 1931 0501 1928 0526 1858 0551 1813 0618 1729 0649 1657 0716 1652\n17 0721 1716 0655 1749 0615 1818 0530 1846 0457 1912 0447 1931 0501 1927 0527 1857 0552 1812 0619 1728 0650 1656 0717 1652\n18 0720 1717 0654 1751 0614 1819 0529 1847 0456 1913 0447 1932 0502 1926 0527 1856 0553 1810 0620 1726 0651 1655 0717 1653\n19 0720 1718 0653 1752 0612 1820 0527 1848 0456 1914 0447 1932 0503 1926 0528 1854 0554 1809 0620 1725 0652 1655 0718 1653\n20 0719 1719 0652 1753 0611 1821 0526 1848 0455 1915 0448 1932 0503 1925 0529 1853 0555 1807 0621 1724 0653 1654 0718 1654\n21 0719 1720 0650 1754 0609 1821 0525 1849 0454 1916 0448 1932 0504 1924 0530 1852 0556 1806 0622 1722 0654 1654 0719 1654\n22 0718 1721 0649 1755 0608 1822 0523 1850 0454 1916 0448 1932 0505 1924 0531 1850 0556 1804 0623 1721 0655 1653 0719 1655\n23 0718 1722 0648 1756 0606 1823 0522 1851 0453 1917 0448 1933 0506 1923 0532 1849 0557 1803 0624 1720 0656 1653 0720 1655\n24 0717 1723 0647 1757 0605 1824 0521 1852 0453 1918 0449 1933 0507 1922 0532 1847 0558 1801 0625 1719 0657 1652 0720 1656\n25 0717 1724 0645 1758 0603 1825 0520 1853 0452 1919 0449 1933 0507 1921 0533 1846 0559 1759 0626 1717 0658 1652 0721 1657\n26 0716 1726 0644 1759 0602 1826 0518 1854 0451 1919 0449 1933 0508 1921 0534 1845 0600 1758 0627 1716 0659 1652 0721 1657\n27 0715 1727 0643 1800 0600 1827 0517 1855 0451 1920 0450 1933 0509 1920 0535 1843 0601 1756 0628 1715 0700 1651 0721 1658\n28 0715 1728 0641 1801 0559 1828 0516 1856 0450 1921 0450 1933 0510 1919 0536 1842 0602 1755 0629 1714 0701 1651 0722 1659\n29 0714 1729 0640 1802 0557 1829 0515 1857 0450 1922 0451 1933 0511 1918 0537 1840 0602 1753 0630 1713 0702 1651 0722 1659\n30 0713 1730 0556 1830 0514 1857 0450 1922 0451 1933 0511 1917 0537 1839 0603 1752 0631 1712 0703 1651 0722 1700\n31 0712 1731 0554 1830 0449 1923 0512 1916 0538 1837 0632 1711 0722 1701'
dst_start = (3, 13)
dst_end = (11, 6)
sunrise_sunset_table = [[None for d in range(31)] for m in range(12)]
def parse_sunrise_sunset_table():
day = 1
for line in sunrise_sunset_data.split('\n'):
assert day == int(line[0:2])
for m in range(12):
start = m * 11 + 4
sunrise = line[start:start + 4]
sunset = line[start + 5:start + 10]
month = m + 1
if month > DST_START[0] and month < DST_END[0] or (month == DST_START[0] and day >= DST_START[1]) or (month == DST_END[0] and day < DST_END[1]):
dst = 60
else:
dst = 0
if sunrise != ' ':
sunrise_minutes = int(sunrise[0:2]) * 60 + int(sunrise[2:4]) + dst
sunset_minutes = int(sunset[0:2]) * 60 + int(sunset[2:4]) + dst
SUNRISE_SUNSET_TABLE[m][day - 1] = (sunrise_minutes, sunset_minutes)
day += 1
parse_sunrise_sunset_table()
def get_sunrise_sunset(month, day):
return SUNRISE_SUNSET_TABLE[month - 1][day - 1]
def time_of_day_to_zone(minutes, sunrise, sunset):
if minutes < sunrise:
return 0
elif minutes <= sunset - 30:
return 1
elif minutes <= max(sunset + 60, 21.5 * 60):
return 2
else:
return 3
num_zones = 4
def dt_to_minutes(dt):
return dt.time().hour * 60 + dt.time().minute
def minutes_to_time(minutes):
hrs = int(minutes / 60)
mins = minutes - hrs * 60
assert mins < 60
return (hrs, mins)
|
class Obstacle:
def __init__(self, clearance):
self.x = 10
self.y = 10
self.clearance = clearance
self.robot_radius = 0.354 / 2
self.clearance = self.robot_radius + self.clearance
self.dynamic_Obstacle = False
# self.rect1_corner1_x = 3
# self.rect1_corner1_y = 0
self.rect1_corner1_x = 0
self.rect1_corner1_y = 2.75
self.rect1_length = 3
self.rect1_width = 0.01
# self.rect2_corner1_x = 6
# self.rect2_corner1_y = 0
self.rect2_corner1_x = 0
self.rect2_corner1_y = 6.25
self.rect2_length = 3
self.rect2_width = 0.01
def isInObstacleSpace(self, x, y):
if (x < 1 or x > 9 or y < 1 or y > 9):
#print('Out of boundary !')
return 1
#rectangle obstacle 1
x1 = self.rect1_corner1_x - self.clearance
x2 = x1 + self.rect1_length + 2*self.clearance
y1 = self.rect1_corner1_y - self.clearance
y2 = y1 + self.rect1_width + 2*self.clearance
if (x >= x1 and x <= x2 and y >= y1 and y <= y2):
#print('Inside rectangle 1, avoid')
return 1
#rectangle obstacle 2
x1 = self.rect2_corner1_x - self.clearance
x2 = x1 + self.rect2_length + 2*self.clearance
y1 = self.rect2_corner1_y - self.clearance
y2 = y1 + self.rect2_width + 2*self.clearance
if (x >= x1 and x <= x2 and y >= y1 and y <= y2):
#print('Inside rectangle 1, avoid')
return 1
if self.dynamic_Obstacle == True:
x1 = self.dynamic_obs_corner_x - self.clearance
x2 = x1 + self.dynamic_obs_length + 2*self.clearance
y1 = self.dynamic_obs_corner_y - self.clearance
y2 = y1 + self.dynamic_obs_width + 2*self.clearance
if (x >= x1 and x <= x2 and y >= y1 and y <= y2):
# print('Hitting new dynamic obstacle')
return 1
return 0
def addNewObstacle(self, x, y, length, width):
self.dynamic_obs_corner_x = x
self.dynamic_obs_corner_y = y
self.dynamic_obs_length = length
self.dynamic_obs_width = width
self.dynamic_Obstacle = True
|
class Obstacle:
def __init__(self, clearance):
self.x = 10
self.y = 10
self.clearance = clearance
self.robot_radius = 0.354 / 2
self.clearance = self.robot_radius + self.clearance
self.dynamic_Obstacle = False
self.rect1_corner1_x = 0
self.rect1_corner1_y = 2.75
self.rect1_length = 3
self.rect1_width = 0.01
self.rect2_corner1_x = 0
self.rect2_corner1_y = 6.25
self.rect2_length = 3
self.rect2_width = 0.01
def is_in_obstacle_space(self, x, y):
if x < 1 or x > 9 or y < 1 or (y > 9):
return 1
x1 = self.rect1_corner1_x - self.clearance
x2 = x1 + self.rect1_length + 2 * self.clearance
y1 = self.rect1_corner1_y - self.clearance
y2 = y1 + self.rect1_width + 2 * self.clearance
if x >= x1 and x <= x2 and (y >= y1) and (y <= y2):
return 1
x1 = self.rect2_corner1_x - self.clearance
x2 = x1 + self.rect2_length + 2 * self.clearance
y1 = self.rect2_corner1_y - self.clearance
y2 = y1 + self.rect2_width + 2 * self.clearance
if x >= x1 and x <= x2 and (y >= y1) and (y <= y2):
return 1
if self.dynamic_Obstacle == True:
x1 = self.dynamic_obs_corner_x - self.clearance
x2 = x1 + self.dynamic_obs_length + 2 * self.clearance
y1 = self.dynamic_obs_corner_y - self.clearance
y2 = y1 + self.dynamic_obs_width + 2 * self.clearance
if x >= x1 and x <= x2 and (y >= y1) and (y <= y2):
return 1
return 0
def add_new_obstacle(self, x, y, length, width):
self.dynamic_obs_corner_x = x
self.dynamic_obs_corner_y = y
self.dynamic_obs_length = length
self.dynamic_obs_width = width
self.dynamic_Obstacle = True
|
"""
Problem
Given a list of integers, find the largest
product you could make from 3 integers in the list
Requirements
You can assume that the list will always have at least 3 integers
"""
def get_largest_product(lst):
if len(lst) < 3:
raise ValueError("List is too short")
high = max(lst[0], lst[1])
low = min(lst[0], lst[1])
high_prod_2 = lst[0] * lst[1]
low_prod_2 = lst[0] * lst[1]
high_prod_3 = lst[0] * lst[1] * lst[2]
for num in lst[2:]:
high_prod_3 = max(high_prod_3, num * high_prod_2, num * low_prod_2)
high_prod_2 = max(high_prod_2, num * high, num * low)
low_prod_2 = min(low_prod_2, num * high, num * low)
high = max(high, num)
low = min(low, num)
return high_prod_3
if __name__ == '__main__':
lp = get_largest_product([1, 3, 4, 6, 7, 2, 8, 9, 4, 2, 3, 4, 6, 7])
print(lp)
|
"""
Problem
Given a list of integers, find the largest
product you could make from 3 integers in the list
Requirements
You can assume that the list will always have at least 3 integers
"""
def get_largest_product(lst):
if len(lst) < 3:
raise value_error('List is too short')
high = max(lst[0], lst[1])
low = min(lst[0], lst[1])
high_prod_2 = lst[0] * lst[1]
low_prod_2 = lst[0] * lst[1]
high_prod_3 = lst[0] * lst[1] * lst[2]
for num in lst[2:]:
high_prod_3 = max(high_prod_3, num * high_prod_2, num * low_prod_2)
high_prod_2 = max(high_prod_2, num * high, num * low)
low_prod_2 = min(low_prod_2, num * high, num * low)
high = max(high, num)
low = min(low, num)
return high_prod_3
if __name__ == '__main__':
lp = get_largest_product([1, 3, 4, 6, 7, 2, 8, 9, 4, 2, 3, 4, 6, 7])
print(lp)
|
"""Project metadata
Information describing the project.
"""
# The package name, which is also the so-called "UNIX name" for the project.
package = 'ecs'
project = "Entity-Component-System"
project_no_spaces = project.replace(' ', '')
version = '0.1'
description = 'An entity/component system library for games'
authors = ['Sean Fisk', 'Kevin Ward']
authors_string = ', '.join(authors)
emails = ['sean@seanfisk.com', 'antiomiae@gmail.com']
license = 'MIT'
copyright = '2013 ' + authors_string
url = 'https://github.com/seanfisk/ecs'
|
"""Project metadata
Information describing the project.
"""
package = 'ecs'
project = 'Entity-Component-System'
project_no_spaces = project.replace(' ', '')
version = '0.1'
description = 'An entity/component system library for games'
authors = ['Sean Fisk', 'Kevin Ward']
authors_string = ', '.join(authors)
emails = ['sean@seanfisk.com', 'antiomiae@gmail.com']
license = 'MIT'
copyright = '2013 ' + authors_string
url = 'https://github.com/seanfisk/ecs'
|
def f(*, b):
return b
def f(a, *, b):
return a + b
def f(a, *, b, c):
return a + b + c
def f(a, *, b=c):
return a + b
def f(a, *, b=c, c):
return a + b + c
def f(a, *, b=c, c=d):
return a + b + c
def f(a, *, b=c, c, d=e):
return a + b + c + d
def f(a=None, *, b=None):
return a + b
|
def f(*, b):
return b
def f(a, *, b):
return a + b
def f(a, *, b, c):
return a + b + c
def f(a, *, b=c):
return a + b
def f(a, *, b=c, c):
return a + b + c
def f(a, *, b=c, c=d):
return a + b + c
def f(a, *, b=c, c, d=e):
return a + b + c + d
def f(a=None, *, b=None):
return a + b
|
# Sort the entries of medals: medals_sorted
medals_sorted = medals.sort_index(level=0)
# Print the number of Bronze medals won by Germany
print(medals_sorted.loc[('bronze','Germany')])
# Print data about silver medals
print(medals_sorted.loc['silver'])
# Create alias for pd.IndexSlice: idx
idx = pd.IndexSlice
# Print all the data on medals won by the United Kingdom
print(medals_sorted.loc[idx[:,'United Kingdom'],:])
|
medals_sorted = medals.sort_index(level=0)
print(medals_sorted.loc['bronze', 'Germany'])
print(medals_sorted.loc['silver'])
idx = pd.IndexSlice
print(medals_sorted.loc[idx[:, 'United Kingdom'], :])
|
class WebSocketDefine:
Uri = "wss://sdstream.binance.com/stream"
# testnet new spec
# Uri = "wss://sdstream.binancefuture.com/stream"
class RestApiDefine:
Url = "https://dapi.binance.com"
# testnet
# Url = "https://testnet.binancefuture.com"
|
class Websocketdefine:
uri = 'wss://sdstream.binance.com/stream'
class Restapidefine:
url = 'https://dapi.binance.com'
|
s = input()
y, m, d = map(int, s.split('/'))
f = False
(
Heisei,
TBD,
)= (
'Heisei',
'TBD',
)
if y < 2019:
print(Heisei)
elif y == 2019:
if(m < 4):
print(Heisei)
elif m == 4:
if(d <= 30):
print(Heisei)
else :
print(TBD)
else :
print(TBD)
else :
print(TBD)
|
s = input()
(y, m, d) = map(int, s.split('/'))
f = False
(heisei, tbd) = ('Heisei', 'TBD')
if y < 2019:
print(Heisei)
elif y == 2019:
if m < 4:
print(Heisei)
elif m == 4:
if d <= 30:
print(Heisei)
else:
print(TBD)
else:
print(TBD)
else:
print(TBD)
|
"""
The meat.
Things to do:
TaskFinder
- querys a (file|db) for what sort of tasks to run
Task
- initialize from task data pulled by TaskFinder
- enumerate the combination of args and kwargs to sent to this task
- provide a function which takes *args and **kwargs to execute the task
- specify the type of schedule to be used for this task
ScopeFinder
- querys a (file|db) for the set of parameter combinations to send to the task
Scheduler
- initialize from schedule data pulled by ScheduleFinder
- determine if a task and arguement combination should run
Registry
- manage the state of all jobs in progress
"""
|
"""
The meat.
Things to do:
TaskFinder
- querys a (file|db) for what sort of tasks to run
Task
- initialize from task data pulled by TaskFinder
- enumerate the combination of args and kwargs to sent to this task
- provide a function which takes *args and **kwargs to execute the task
- specify the type of schedule to be used for this task
ScopeFinder
- querys a (file|db) for the set of parameter combinations to send to the task
Scheduler
- initialize from schedule data pulled by ScheduleFinder
- determine if a task and arguement combination should run
Registry
- manage the state of all jobs in progress
"""
|
rfm69SpiBus = 0
rfm69NSS = 5 # GPIO5 == pin 7
rfm69D0 = 9 # GPIO9 == pin 12
rfm69RST = 8 # GPIO8 == pin 11
am2302 = 22 # GPIO22 == pin 29
voltADC = 26 # GPIO26 == pin 31
|
rfm69_spi_bus = 0
rfm69_nss = 5
rfm69_d0 = 9
rfm69_rst = 8
am2302 = 22
volt_adc = 26
|
# Hack 3: create your own math function
# Function is superfactorial: superfactorial is product of all factorials until n.
# OOP method
class superFactorial():
def __init__(self,n):
self.n = n
def factorial(self,y):
y = self.n if y is None else y
product = 1
for x in range(1,y+1):
product*=x
return product
def __call__(self):
product = 1
for x in range(1,self.n+1):
product*= self.factorial(x)
return product
# Imperative Method
def superfac():
x = int(input("What number should we use? "))
product = 1
for y in range(1,x+1):
secondProd = 1
for z in range(1,y+1):
secondProd*= z
product*=secondProd
print(product)
if __name__ == "__main__":
sfac = superFactorial(3)
print(sfac())
print(superfac())
|
class Superfactorial:
def __init__(self, n):
self.n = n
def factorial(self, y):
y = self.n if y is None else y
product = 1
for x in range(1, y + 1):
product *= x
return product
def __call__(self):
product = 1
for x in range(1, self.n + 1):
product *= self.factorial(x)
return product
def superfac():
x = int(input('What number should we use? '))
product = 1
for y in range(1, x + 1):
second_prod = 1
for z in range(1, y + 1):
second_prod *= z
product *= secondProd
print(product)
if __name__ == '__main__':
sfac = super_factorial(3)
print(sfac())
print(superfac())
|
class Settings():
"A class to store all settings for Football game."
def __init__(self):
"""Initialize the game's settings."""
# Screen settings.
self.screen_width = 1200
self.screen_height = 700
self.bg_color = (50, 205, 50)
self.attacker_speed_factor = 1.5
# Attacker settings.
self.ball_speed_factor = 2
self.balls_allowed = 1
self.attackers_limit = 3
# Defender settings.
self.defender_speed_factor = 1
self.defense_move_speed = 10
# defense_direction of 1 represent up : -1 represents down.
self.defense_direction = 1
|
class Settings:
"""A class to store all settings for Football game."""
def __init__(self):
"""Initialize the game's settings."""
self.screen_width = 1200
self.screen_height = 700
self.bg_color = (50, 205, 50)
self.attacker_speed_factor = 1.5
self.ball_speed_factor = 2
self.balls_allowed = 1
self.attackers_limit = 3
self.defender_speed_factor = 1
self.defense_move_speed = 10
self.defense_direction = 1
|
# -*- Mode:Python;indent-tabs-mode:nil; -*-
#
# File: psaExceptions.py
# Created: 05/09/2014
# Author: BSC
#
# Description:
# Custom execption class to manage error in the PSC
#
class psaExceptions( object ):
class confRetrievalFailed( Exception ):
pass
|
class Psaexceptions(object):
class Confretrievalfailed(Exception):
pass
|
class CategoryDefinition:
""" Defines a category for labeling texts."""
def __init__(self, name):
self.name = name
class NamedEntityDefinition:
""" Defines a named entity for annotating texts."""
def __init__(self, code, key_sequence = None, maincolor = None, backcolor = None, forecolor= None):
self.code = code
self.key_sequence = key_sequence
self.maincolor = maincolor
self.backcolor = backcolor
self.forecolor = forecolor
|
class Categorydefinition:
""" Defines a category for labeling texts."""
def __init__(self, name):
self.name = name
class Namedentitydefinition:
""" Defines a named entity for annotating texts."""
def __init__(self, code, key_sequence=None, maincolor=None, backcolor=None, forecolor=None):
self.code = code
self.key_sequence = key_sequence
self.maincolor = maincolor
self.backcolor = backcolor
self.forecolor = forecolor
|
# multiply a list by a number
def mul(row, num):
return [x * num for x in row]
# subtract one row from another
def sub(row_left, row_right):
return [a - b for (a, b) in zip(row_left, row_right)]
# calculate the row echelon form of the matrix
def echelonify(rw, i, m):
for j, row in enumerate(m[(i+1):]):
j += 1
# print("rw[i]:", rw[i])
if rw[i] != 0:
m[j+i] = sub(row, mul(rw, row[i] / rw[i]))
return rw
def row_echelon(m):
for i in range(len(m)): # len(m) == m x n
active_row = m[i]
echelonify(active_row, i, m)
# close to zero
m = [[(0 if (0.0000000001 > x > -0.0000000001) else x)
for x in row]for row in m]
return m
if __name__ == '__main__':
print("Enter number of rows and columns")
m, n = map(int, input().split()) # m = row and n = column
M = []
for _ in range(m):
row = list(map(int, input().split()))[:n]
M.append(row)
mat = row_echelon(M)
for row in mat:
print(' '.join((str(x) for x in row)))
# The output can be printed by dividing each element of each row by the first non-zero element of the respective row in order to get 1
|
def mul(row, num):
return [x * num for x in row]
def sub(row_left, row_right):
return [a - b for (a, b) in zip(row_left, row_right)]
def echelonify(rw, i, m):
for (j, row) in enumerate(m[i + 1:]):
j += 1
if rw[i] != 0:
m[j + i] = sub(row, mul(rw, row[i] / rw[i]))
return rw
def row_echelon(m):
for i in range(len(m)):
active_row = m[i]
echelonify(active_row, i, m)
m = [[0 if 1e-10 > x > -1e-10 else x for x in row] for row in m]
return m
if __name__ == '__main__':
print('Enter number of rows and columns')
(m, n) = map(int, input().split())
m = []
for _ in range(m):
row = list(map(int, input().split()))[:n]
M.append(row)
mat = row_echelon(M)
for row in mat:
print(' '.join((str(x) for x in row)))
|
ans = 0
a=input()
for _ in range(int(input())):
s=input()
for start in range(10):
for j in range(len(a)):
if a[j] != s[(start+j)%10]:
break
else:
ans+=1
break
print(ans)
|
ans = 0
a = input()
for _ in range(int(input())):
s = input()
for start in range(10):
for j in range(len(a)):
if a[j] != s[(start + j) % 10]:
break
else:
ans += 1
break
print(ans)
|
#!/usr/bin/env python3
"""
Problem : Double-Degree Array
URL : http://rosalind.info/problems/ddeg/
Author : David P. Perkins
"""
if __name__=="__main__":
with open("ddegIn.txt", "r") as infile, open("ddegOut.txt", "w") as outfile:
nodeCount = int(infile.readline().split()[0])
adjl = {x:set() for x in range(1, nodeCount+1)}
ddegl = list()
for line in infile:
a, b = [int(x) for x in line.split()]
adjl.setdefault(a, set()).add(b)
adjl.setdefault(b, set()).add(a)
for node in sorted(adjl):
ddeg = sum([len(adjl[x]) for x in adjl[node]])
ddegl.append(ddeg)
print(*ddegl, file=outfile)
|
"""
Problem : Double-Degree Array
URL : http://rosalind.info/problems/ddeg/
Author : David P. Perkins
"""
if __name__ == '__main__':
with open('ddegIn.txt', 'r') as infile, open('ddegOut.txt', 'w') as outfile:
node_count = int(infile.readline().split()[0])
adjl = {x: set() for x in range(1, nodeCount + 1)}
ddegl = list()
for line in infile:
(a, b) = [int(x) for x in line.split()]
adjl.setdefault(a, set()).add(b)
adjl.setdefault(b, set()).add(a)
for node in sorted(adjl):
ddeg = sum([len(adjl[x]) for x in adjl[node]])
ddegl.append(ddeg)
print(*ddegl, file=outfile)
|
# Easy
# Runtime: 32 ms, faster than 73.01% of Python3 online submissions for Count and Say.
# Memory Usage: 12.9 MB, less than 100.00% of Python3 online submissions for Count and Say.
class Solution:
def countAndSay(self, n: int) -> str:
def count_and_say(n):
if n == 1:
return '1'
cur_s = ''
idx = 0
cur_sum = 0
s = count_and_say(n - 1)
for i, ch in enumerate(s):
if ch != s[idx]:
cur_s += str(cur_sum) + s[idx]
cur_sum = 1
idx = i
else:
cur_sum += 1
cur_s += str(cur_sum) + s[idx]
return cur_s
return count_and_say(n)
|
class Solution:
def count_and_say(self, n: int) -> str:
def count_and_say(n):
if n == 1:
return '1'
cur_s = ''
idx = 0
cur_sum = 0
s = count_and_say(n - 1)
for (i, ch) in enumerate(s):
if ch != s[idx]:
cur_s += str(cur_sum) + s[idx]
cur_sum = 1
idx = i
else:
cur_sum += 1
cur_s += str(cur_sum) + s[idx]
return cur_s
return count_and_say(n)
|
class IBeacon():
def __init__(self, driver_instace) -> None:
self.ble_driver_instace = driver_instace
def setUUID(self, uuid : str) -> None:
"uuid is 16 bytes should be represented as a string of hex-decimal format: XX XX XX XX ..."
self.uuid = uuid
def setMajor(self, major : str) -> None:
"major is 2 bytes should be represented as string of hex-decimal format: XX XX"
self.major = major
def setMinor(self, minor : str) -> None:
"minor is 2 bytes should be represented as string of hex-decimal format: XX XX"
self.minor = minor
def setTXPower(self, txpower : str) -> None:
"txpower used to measure RSSI loss"
self.txpower = txpower
def __makeIBeaconMessage(self):
# As from the IBeacon spec:
# 02 01 1A 1A FF 4C 00 02 15 - IBeacon 9 byte prefix for Apple, inc. Please,
# refer to a IBeacon frame spec to get more details.
# UUID 16-18 bytes. We fix as 16
# Major
# Minor
# 1E - length of the message for driver
# 02 01 06 - BLE discoverable mode
# 1A - length of the content
# FF - custom manufacturer data
# 4C 00 - Apple's Bluetooth code
# 02 - Apple's iBeacon type of custom data
# 15 - length of rest IBeacon data
return "1E 02 01 06 1A FF 4C 00 02 15 " + self.uuid + " " + self.major + " " + self.minor + " " + self.txpower
def up(self) -> None:
""" start transmission """
self.ble_driver_instace.init()
self.ble_driver_instace.up()
self.ble_driver_instace.setAdvertisingMode()
self.ble_driver_instace.setSanningState(False)
self.ble_driver_instace.sendRawData(self.__makeIBeaconMessage())
def down(self):
""" Start transmission """
self.ble_driver_instace.down()
|
class Ibeacon:
def __init__(self, driver_instace) -> None:
self.ble_driver_instace = driver_instace
def set_uuid(self, uuid: str) -> None:
"""uuid is 16 bytes should be represented as a string of hex-decimal format: XX XX XX XX ..."""
self.uuid = uuid
def set_major(self, major: str) -> None:
"""major is 2 bytes should be represented as string of hex-decimal format: XX XX"""
self.major = major
def set_minor(self, minor: str) -> None:
"""minor is 2 bytes should be represented as string of hex-decimal format: XX XX"""
self.minor = minor
def set_tx_power(self, txpower: str) -> None:
"""txpower used to measure RSSI loss"""
self.txpower = txpower
def __make_i_beacon_message(self):
return '1E 02 01 06 1A FF 4C 00 02 15 ' + self.uuid + ' ' + self.major + ' ' + self.minor + ' ' + self.txpower
def up(self) -> None:
""" start transmission """
self.ble_driver_instace.init()
self.ble_driver_instace.up()
self.ble_driver_instace.setAdvertisingMode()
self.ble_driver_instace.setSanningState(False)
self.ble_driver_instace.sendRawData(self.__makeIBeaconMessage())
def down(self):
""" Start transmission """
self.ble_driver_instace.down()
|
class PlannerEventHandler(object):
pass
def ProblemNotImplemented(self):
return False
def StartedPlanning(self):
return True
def SubmittedPipeline(self, pipeline):
return True
def RunningPipeline(self, pipeline):
return True
def CompletedPipeline(self, pipeline, result):
return True
def StartExecutingPipeline(self, pipeline):
return True
def ExecutedPipeline(self, pipeline, result):
return True
def EndedPlanning(self):
return True
|
class Plannereventhandler(object):
pass
def problem_not_implemented(self):
return False
def started_planning(self):
return True
def submitted_pipeline(self, pipeline):
return True
def running_pipeline(self, pipeline):
return True
def completed_pipeline(self, pipeline, result):
return True
def start_executing_pipeline(self, pipeline):
return True
def executed_pipeline(self, pipeline, result):
return True
def ended_planning(self):
return True
|
def minSubArrayLen(target, nums):
length = list()
for i in range(len(nums)):
remain = target - nums[i]
if remain <= 0:
length.append(1)
continue
for j in range(i+1, len(nums)):
remain = remain - nums[j]
if remain <= 0:
length.append(j-i+1)
break
if not length:
return 0
return min(length)
if __name__ == '__main__':
# print(minSubArrayLen(1, [1,1,1,1,1,1,1,1]))
# print(minSubArrayLen(7, [2,3,1,2,4,3]))
print(minSubArrayLen(11, [1, 2, 3, 4, 5]))
|
def min_sub_array_len(target, nums):
length = list()
for i in range(len(nums)):
remain = target - nums[i]
if remain <= 0:
length.append(1)
continue
for j in range(i + 1, len(nums)):
remain = remain - nums[j]
if remain <= 0:
length.append(j - i + 1)
break
if not length:
return 0
return min(length)
if __name__ == '__main__':
print(min_sub_array_len(11, [1, 2, 3, 4, 5]))
|
'''
Created on Apr 23, 2021
@author: Jimmy Palomino
'''
def Region(main):
"""This function creates the region and set the boundaries to the
machine analysis by FEM.
Args:
main (Dic): Main Dictionary than contain the necessary information.
Returns:
Dic: unmodified main dictionary.
"""
oEditor = main['ANSYS']['oEditor']
oDesign = main['ANSYS']['oDesign']
RegionName = main['ANSYS']['Region']['RegionName']
oModule = oDesign.GetModule("BoundarySetup")
OffsetPercent = main['ANSYS']['Region']['OffsetPercent']
# Drawing the Region
oEditor.CreateCircle(
[
"NAME:CircleParameters",
"IsCovered:=" , True,
"XCenter:=" , "0mm",
"YCenter:=" , "0mm",
"ZCenter:=" , "0mm",
"Radius:=" , "DiaYoke/2"+'*'+str(1+OffsetPercent/100),
"WhichAxis:=" , "Z",
"NumSegments:=" , "0"
],
[
"NAME:Attributes",
"Name:=" , RegionName,
"Flags:=" , "",
"Color:=" , "(143 175 143)",
"Transparency:=" , 0.75,
"PartCoordinateSystem:=", "Global",
"UDMId:=" , "",
"MaterialValue:=" , "\"vacuum\"",
"SurfaceMaterialValue:=", "\"\"",
"SolveInside:=" , True,
"ShellElement:=" , False,
"ShellElementThickness:=", "0mm",
"IsMaterialEditable:=" , True,
"UseMaterialAppearance:=", False,
"IsLightweight:=" , False
]
)
# Boundaries setting
Edges = oEditor.GetEdgeIDsFromObject(RegionName)
oModule.AssignVectorPotential(
[
"NAME:VectorPotential1",
"Edges:=" , [int(Edges[0])],
"Value:=" , "0",
"CoordinateSystem:=" , ""
]
)
oEditor.FitAll()
return main
|
"""
Created on Apr 23, 2021
@author: Jimmy Palomino
"""
def region(main):
"""This function creates the region and set the boundaries to the
machine analysis by FEM.
Args:
main (Dic): Main Dictionary than contain the necessary information.
Returns:
Dic: unmodified main dictionary.
"""
o_editor = main['ANSYS']['oEditor']
o_design = main['ANSYS']['oDesign']
region_name = main['ANSYS']['Region']['RegionName']
o_module = oDesign.GetModule('BoundarySetup')
offset_percent = main['ANSYS']['Region']['OffsetPercent']
oEditor.CreateCircle(['NAME:CircleParameters', 'IsCovered:=', True, 'XCenter:=', '0mm', 'YCenter:=', '0mm', 'ZCenter:=', '0mm', 'Radius:=', 'DiaYoke/2' + '*' + str(1 + OffsetPercent / 100), 'WhichAxis:=', 'Z', 'NumSegments:=', '0'], ['NAME:Attributes', 'Name:=', RegionName, 'Flags:=', '', 'Color:=', '(143 175 143)', 'Transparency:=', 0.75, 'PartCoordinateSystem:=', 'Global', 'UDMId:=', '', 'MaterialValue:=', '"vacuum"', 'SurfaceMaterialValue:=', '""', 'SolveInside:=', True, 'ShellElement:=', False, 'ShellElementThickness:=', '0mm', 'IsMaterialEditable:=', True, 'UseMaterialAppearance:=', False, 'IsLightweight:=', False])
edges = oEditor.GetEdgeIDsFromObject(RegionName)
oModule.AssignVectorPotential(['NAME:VectorPotential1', 'Edges:=', [int(Edges[0])], 'Value:=', '0', 'CoordinateSystem:=', ''])
oEditor.FitAll()
return main
|
# -*- coding: UTF-8 -*-
class Shared(object):
'''
Class used for /hana/shared attributes.
Attributes and methods are passed to other LVM Classes.
'''
name = 'shared'
vg_physical_extent_size = '-s 1M'
vg_data_alignment = '--dataalignment 1M'
vg_args = vg_physical_extent_size + ' ' + vg_data_alignment
lv_size = '-l 100%VG'
lv_args = lv_size
fs_block_size = '-b size=4096'
fs_sector_size = '-s size=4096'
fs_type = 'xfs'
fs_mount_point = '/hana/shared'
fs_args = fs_block_size + ' ' + fs_sector_size
def __init__(self):
super(Shared, self).__init__()
|
class Shared(object):
"""
Class used for /hana/shared attributes.
Attributes and methods are passed to other LVM Classes.
"""
name = 'shared'
vg_physical_extent_size = '-s 1M'
vg_data_alignment = '--dataalignment 1M'
vg_args = vg_physical_extent_size + ' ' + vg_data_alignment
lv_size = '-l 100%VG'
lv_args = lv_size
fs_block_size = '-b size=4096'
fs_sector_size = '-s size=4096'
fs_type = 'xfs'
fs_mount_point = '/hana/shared'
fs_args = fs_block_size + ' ' + fs_sector_size
def __init__(self):
super(Shared, self).__init__()
|
class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
shortest = min(strs, key=len)
longest_common = ""
for idx, char in enumerate(shortest):
for word in strs:
if word[idx] != char:
return longest_common
longest_common += char
# Case where they pass us nothing
return longest_common
|
class Solution:
def longest_common_prefix(self, strs: List[str]) -> str:
shortest = min(strs, key=len)
longest_common = ''
for (idx, char) in enumerate(shortest):
for word in strs:
if word[idx] != char:
return longest_common
longest_common += char
return longest_common
|
class Solution:
def uniqueOccurrences(self, arr: List[int]) -> bool:
dict = {}
for i in arr :
if i in dict :
dict[i] += 1
else :
dict[i] = 1
count = 0
s = set(dict.values())
ns = len(s)
nl = len(dict.values())
if nl != ns :
return False
else :
return True
|
class Solution:
def unique_occurrences(self, arr: List[int]) -> bool:
dict = {}
for i in arr:
if i in dict:
dict[i] += 1
else:
dict[i] = 1
count = 0
s = set(dict.values())
ns = len(s)
nl = len(dict.values())
if nl != ns:
return False
else:
return True
|
test = { 'name': 'q1d',
'points': 1,
'suites': [ { 'cases': [ {'code': ">>> species_by_island.labels == ('species', 'Biscoe', 'Dream', 'Torgersen')\nTrue", 'hidden': False, 'locked': False},
{'code': ">>> np.all(species_by_island.column('Biscoe') == np.array([44, 0, 119]))\nTrue", 'hidden': False, 'locked': False}],
'scored': True,
'setup': '',
'teardown': '',
'type': 'doctest'}]}
|
test = {'name': 'q1d', 'points': 1, 'suites': [{'cases': [{'code': ">>> species_by_island.labels == ('species', 'Biscoe', 'Dream', 'Torgersen')\nTrue", 'hidden': False, 'locked': False}, {'code': ">>> np.all(species_by_island.column('Biscoe') == np.array([44, 0, 119]))\nTrue", 'hidden': False, 'locked': False}], 'scored': True, 'setup': '', 'teardown': '', 'type': 'doctest'}]}
|
# objects here will be mixed into the dynamically created asset type classes
# based on name.
# This lets us extend certain asset types without having to give up the generic
# dynamic meta implementation
class Attachment(object):
def set_blob(self, blob):
return self._v1_v1meta.set_attachment_blob(self, blob)
def get_blob(self):
return self._v1_v1meta.get_attachment_blob(self)
file_data = property(get_blob, set_blob)
# the special_classes mapping will be used to lookup mixins by asset type name.
special_classes = locals()
|
class Attachment(object):
def set_blob(self, blob):
return self._v1_v1meta.set_attachment_blob(self, blob)
def get_blob(self):
return self._v1_v1meta.get_attachment_blob(self)
file_data = property(get_blob, set_blob)
special_classes = locals()
|
LOG_EPOCH = 'epoch'
LOG_TRAIN_LOSS = 'train_loss'
LOG_TRAIN_ACC = 'train_acc'
LOG_VAL_LOSS = 'val_loss'
LOG_VAL_ACC = 'val_acc'
LOG_FIELDS = [LOG_EPOCH, LOG_TRAIN_LOSS, LOG_TRAIN_ACC, LOG_VAL_LOSS, LOG_VAL_ACC]
LOG_COLOR_HEADER = '\033[95m'
LOG_COLOR_OKBLUE = '\033[94m'
LOG_COLOR_OKCYAN = '\033[96m'
LOG_COLOR_OKGREEN = '\033[92m'
LOG_COLOR_WARNING = '\033[93m'
LOG_COLOR_FAIL = '\033[91m'
LOG_COLOR_ENDC = '\033[0m'
LOG_COLOR_BOLD = '\033[1m'
LOG_COLOR_UNDERLINE = '\033[4m'
|
log_epoch = 'epoch'
log_train_loss = 'train_loss'
log_train_acc = 'train_acc'
log_val_loss = 'val_loss'
log_val_acc = 'val_acc'
log_fields = [LOG_EPOCH, LOG_TRAIN_LOSS, LOG_TRAIN_ACC, LOG_VAL_LOSS, LOG_VAL_ACC]
log_color_header = '\x1b[95m'
log_color_okblue = '\x1b[94m'
log_color_okcyan = '\x1b[96m'
log_color_okgreen = '\x1b[92m'
log_color_warning = '\x1b[93m'
log_color_fail = '\x1b[91m'
log_color_endc = '\x1b[0m'
log_color_bold = '\x1b[1m'
log_color_underline = '\x1b[4m'
|
"""
Test module for learning python packaging.
"""
def my_sum(arg):
"""
Sums the arguments and returns the sum.
"""
total = 0
for val in arg:
total += val
return total
class MySum(object):
# pylint: disable=too-few-public-methods
"""
MySum class
"""
@staticmethod
def my_sum(arg):
"""
Sums the arguments and returns the sum.
"""
return my_sum(arg)
|
"""
Test module for learning python packaging.
"""
def my_sum(arg):
"""
Sums the arguments and returns the sum.
"""
total = 0
for val in arg:
total += val
return total
class Mysum(object):
"""
MySum class
"""
@staticmethod
def my_sum(arg):
"""
Sums the arguments and returns the sum.
"""
return my_sum(arg)
|
def load(h):
return ({'abbr': 1, 'code': 1, 'title': 'PRES Pressure [hPa]'},
{'abbr': 2, 'code': 2, 'title': 'psnm Pressure reduced to MSL [hPa]'},
{'abbr': 3, 'code': 3, 'title': 'tsps Pressure tendency [Pa/s]'},
{'abbr': 4, 'code': 4, 'title': 'var4 undefined'},
{'abbr': 5, 'code': 5, 'title': 'var5 undefined'},
{'abbr': 6, 'code': 6, 'title': 'geop Geopotential [dam]'},
{'abbr': 7, 'code': 7, 'title': 'zgeo Geopotential height [gpm]'},
{'abbr': 8, 'code': 8, 'title': 'gzge Geometric height [m]'},
{'abbr': 9, 'code': 9, 'title': 'var9 undefined'},
{'abbr': 10, 'code': 10, 'title': 'var10 undefined'},
{'abbr': 11, 'code': 11, 'title': 'temp ABSOLUTE TEMPERATURE [K]'},
{'abbr': 12, 'code': 12, 'title': 'vtmp VIRTUAL TEMPERATURE [K]'},
{'abbr': 13, 'code': 13, 'title': 'ptmp POTENTIAL TEMPERATURE [K]'},
{'abbr': 14,
'code': 14,
'title': 'psat PSEUDO-ADIABATIC POTENTIAL TEMPERATURE [K]'},
{'abbr': 15, 'code': 15, 'title': 'mxtp MAXIMUM TEMPERATURE [K]'},
{'abbr': 16, 'code': 16, 'title': 'mntp MINIMUM TEMPERATURE [K]'},
{'abbr': 17, 'code': 17, 'title': 'tpor DEW POINT TEMPERATURE [K]'},
{'abbr': 18, 'code': 18, 'title': 'dptd DEW POINT DEPRESSION [K]'},
{'abbr': 19, 'code': 19, 'title': 'lpsr LAPSE RATE [K/m]'},
{'abbr': 20, 'code': 20, 'title': 'var20 undefined'},
{'abbr': 21, 'code': 21, 'title': 'rds1 RADAR SPECTRA(1) [non-dim]'},
{'abbr': 22, 'code': 22, 'title': 'rds2 RADAR SPECTRA(2) [non-dim]'},
{'abbr': 23, 'code': 23, 'title': 'rds3 RADAR SPECTRA(3) [non-dim]'},
{'abbr': 24, 'code': 24, 'title': 'var24 undefined'},
{'abbr': 25, 'code': 25, 'title': 'tpan TEMPERATURE ANOMALY [K]'},
{'abbr': 26, 'code': 26, 'title': 'psan PRESSURE ANOMALY [Pa hPa]'},
{'abbr': 27, 'code': 27, 'title': 'zgan GEOPOT HEIGHT ANOMALY [m]'},
{'abbr': 28, 'code': 28, 'title': 'wvs1 WAVE SPECTRA(1) [non-dim]'},
{'abbr': 29, 'code': 29, 'title': 'wvs2 WAVE SPECTRA(2) [non-dim]'},
{'abbr': 30, 'code': 30, 'title': 'wvs3 WAVE SPECTRA(3) [non-dim]'},
{'abbr': 31, 'code': 31, 'title': 'wind WIND DIRECTION [deg]'},
{'abbr': 32, 'code': 32, 'title': 'wins WIND SPEED [m/s]'},
{'abbr': 33, 'code': 33, 'title': 'uvel ZONAL WIND (U) [m/s]'},
{'abbr': 34, 'code': 34, 'title': 'vvel MERIDIONAL WIND (V) [m/s]'},
{'abbr': 35, 'code': 35, 'title': 'fcor STREAM FUNCTION [m2/s]'},
{'abbr': 36, 'code': 36, 'title': 'potv VELOCITY POTENTIAL [m2/s]'},
{'abbr': 37, 'code': 37, 'title': 'var37 undefined'},
{'abbr': 38, 'code': 38, 'title': 'sgvv SIGMA COORD VERT VEL [sec/sec]'},
{'abbr': 39, 'code': 39, 'title': 'omeg OMEGA [Pa/s]'},
{'abbr': 40, 'code': 40, 'title': 'omg2 VERTICAL VELOCITY [m/s]'},
{'abbr': 41, 'code': 41, 'title': 'abvo ABSOLUTE VORTICITY [10**5/sec]'},
{'abbr': 42, 'code': 42, 'title': 'abdv ABSOLUTE DIVERGENCE [10**5/sec]'},
{'abbr': 43, 'code': 43, 'title': 'vort VORTICITY [1/s]'},
{'abbr': 44, 'code': 44, 'title': 'divg DIVERGENCE [1/s]'},
{'abbr': 45, 'code': 45, 'title': 'vucs VERTICAL U-COMP SHEAR [1/sec]'},
{'abbr': 46, 'code': 46, 'title': 'vvcs VERT V-COMP SHEAR [1/sec]'},
{'abbr': 47, 'code': 47, 'title': 'dirc DIRECTION OF CURRENT [deg]'},
{'abbr': 48, 'code': 48, 'title': 'spdc SPEED OF CURRENT [m/s]'},
{'abbr': 49, 'code': 49, 'title': 'ucpc U-COMPONENT OF CURRENT [m/s]'},
{'abbr': 50, 'code': 50, 'title': 'vcpc V-COMPONENT OF CURRENT [m/s]'},
{'abbr': 51, 'code': 51, 'title': 'umes SPECIFIC HUMIDITY [kg/kg]'},
{'abbr': 52, 'code': 52, 'title': 'umrl RELATIVE HUMIDITY [no Dim]'},
{'abbr': 53, 'code': 53, 'title': 'hmxr HUMIDITY MIXING RATIO [kg/kg]'},
{'abbr': 54, 'code': 54, 'title': 'agpl INST. PRECIPITABLE WATER [Kg/m2]'},
{'abbr': 55, 'code': 55, 'title': 'vapp VAPOUR PRESSURE [Pa hpa]'},
{'abbr': 56, 'code': 56, 'title': 'sadf SATURATION DEFICIT [Pa hPa]'},
{'abbr': 57, 'code': 57, 'title': 'evap EVAPORATION [Kg/m2/day]'},
{'abbr': 58, 'code': 58, 'title': 'var58 undefined'},
{'abbr': 59, 'code': 59, 'title': 'prcr PRECIPITATION RATE [kg/m2/day]'},
{'abbr': 60, 'code': 60, 'title': 'thpb THUNDER PROBABILITY [%]'},
{'abbr': 61, 'code': 61, 'title': 'prec TOTAL PRECIPITATION [Kg/m2/day]'},
{'abbr': 62,
'code': 62,
'title': 'prge LARGE SCALE PRECIPITATION [Kg/m2/day]'},
{'abbr': 63, 'code': 63, 'title': 'prcv CONVECTIVE PRECIPITATION [Kg/m2/day]'},
{'abbr': 64, 'code': 64, 'title': 'neve SNOWFALL [Kg/m2/day]'},
{'abbr': 65, 'code': 65, 'title': 'wenv WAT EQUIV ACC SNOW DEPTH [kg/m2]'},
{'abbr': 66, 'code': 66, 'title': 'nvde SNOW DEPTH [cm]'},
{'abbr': 67, 'code': 67, 'title': 'mxld MIXED LAYER DEPTH [m cm]'},
{'abbr': 68, 'code': 68, 'title': 'tthd TRANS THERMOCLINE DEPTH [m cm]'},
{'abbr': 69, 'code': 69, 'title': 'mthd MAIN THERMOCLINE DEPTH [m cm]'},
{'abbr': 70, 'code': 70, 'title': 'mtha MAIN THERMOCLINE ANOM [m cm]'},
{'abbr': 71, 'code': 71, 'title': 'cbnv CLOUD COVER [0-1]'},
{'abbr': 72, 'code': 72, 'title': 'cvnv CONVECTIVE CLOUD COVER [0-1]'},
{'abbr': 73, 'code': 73, 'title': 'lwnv LOW CLOUD COVER [0-1]'},
{'abbr': 74, 'code': 74, 'title': 'mdnv MEDIUM CLOUD COVER [0-1]'},
{'abbr': 75, 'code': 75, 'title': 'hinv HIGH CLOUD COVER [0-1]'},
{'abbr': 76, 'code': 76, 'title': 'wtnv CLOUD WATER [kg/m2]'},
{'abbr': 77, 'code': 77, 'title': 'bli BEST LIFTED INDEX (TO 500 HPA) [K]'},
{'abbr': 78, 'code': 78, 'title': 'var78 undefined'},
{'abbr': 79, 'code': 79, 'title': 'var79 undefined'},
{'abbr': 80, 'code': 80, 'title': 'var80 undefined'},
{'abbr': 81, 'code': 81, 'title': 'lsmk LAND SEA MASK [0,1]'},
{'abbr': 82, 'code': 82, 'title': 'dslm DEV SEA_LEV FROM MEAN [m]'},
{'abbr': 83, 'code': 83, 'title': 'zorl ROUGHNESS LENGTH [m]'},
{'abbr': 84, 'code': 84, 'title': 'albe ALBEDO [%]'},
{'abbr': 85, 'code': 85, 'title': 'dstp DEEP SOIL TEMPERATURE [K]'},
{'abbr': 86, 'code': 86, 'title': 'soic SOIL MOISTURE CONTENT [Kg/m2]'},
{'abbr': 87, 'code': 87, 'title': 'vege VEGETATION [%]'},
{'abbr': 88, 'code': 88, 'title': 'var88 undefined'},
{'abbr': 89, 'code': 89, 'title': 'dens DENSITY [kg/m3]'},
{'abbr': 90, 'code': 90, 'title': 'var90 Undefined'},
{'abbr': 91, 'code': 91, 'title': 'icec ICE CONCENTRATION [fraction]'},
{'abbr': 92, 'code': 92, 'title': 'icet ICE THICKNESS [m]'},
{'abbr': 93, 'code': 93, 'title': 'iced DIRECTION OF ICE DRIFT [deg]'},
{'abbr': 94, 'code': 94, 'title': 'ices SPEED OF ICE DRIFT [m/s]'},
{'abbr': 95, 'code': 95, 'title': 'iceu U-COMP OF ICE DRIFT [m/s]'},
{'abbr': 96, 'code': 96, 'title': 'icev V-COMP OF ICE DRIFT [m/s]'},
{'abbr': 97, 'code': 97, 'title': 'iceg ICE GROWTH [m]'},
{'abbr': 98, 'code': 98, 'title': 'icdv ICE DIVERGENCE [sec/sec]'},
{'abbr': 99, 'code': 99, 'title': 'var99 undefined'},
{'abbr': 100, 'code': 100, 'title': 'shcw SIG HGT COM WAVE/SWELL [m]'},
{'abbr': 101, 'code': 101, 'title': 'wwdi DIRECTION OF WIND WAVE [deg]'},
{'abbr': 102, 'code': 102, 'title': 'wwsh SIG HGHT OF WIND WAVES [m]'},
{'abbr': 103, 'code': 103, 'title': 'wwmp MEAN PERIOD WIND WAVES [sec]'},
{'abbr': 104, 'code': 104, 'title': 'swdi DIRECTION OF SWELL WAVE [deg]'},
{'abbr': 105, 'code': 105, 'title': 'swsh SIG HEIGHT SWELL WAVES [m]'},
{'abbr': 106, 'code': 106, 'title': 'swmp MEAN PERIOD SWELL WAVES [sec]'},
{'abbr': 107, 'code': 107, 'title': 'prwd PRIMARY WAVE DIRECTION [deg]'},
{'abbr': 108, 'code': 108, 'title': 'prmp PRIM WAVE MEAN PERIOD [s]'},
{'abbr': 109, 'code': 109, 'title': 'swdi SECOND WAVE DIRECTION [deg]'},
{'abbr': 110, 'code': 110, 'title': 'swmp SECOND WAVE MEAN PERIOD [s]'},
{'abbr': 111,
'code': 111,
'title': 'ocas SHORT WAVE ABSORBED AT GROUND [W/m2]'},
{'abbr': 112, 'code': 112, 'title': 'slds NET LONG WAVE AT BOTTOM [W/m2]'},
{'abbr': 113, 'code': 113, 'title': 'nswr NET SHORT-WAV RAD(TOP) [W/m2]'},
{'abbr': 114, 'code': 114, 'title': 'role OUTGOING LONG WAVE AT TOP [W/m2]'},
{'abbr': 115, 'code': 115, 'title': 'lwrd LONG-WAV RAD [W/m2]'},
{'abbr': 116,
'code': 116,
'title': 'swea SHORT WAVE ABSORBED BY EARTH/ATMOSPHERE [W/m2]'},
{'abbr': 117, 'code': 117, 'title': 'glbr GLOBAL RADIATION [W/m2 ]'},
{'abbr': 118, 'code': 118, 'title': 'var118 undefined'},
{'abbr': 119, 'code': 119, 'title': 'var119 undefined'},
{'abbr': 120, 'code': 120, 'title': 'var120 undefined'},
{'abbr': 121,
'code': 121,
'title': 'clsf LATENT HEAT FLUX FROM SURFACE [W/m2]'},
{'abbr': 122,
'code': 122,
'title': 'cssf SENSIBLE HEAT FLUX FROM SURFACE [W/m2]'},
{'abbr': 123, 'code': 123, 'title': 'blds BOUND LAYER DISSIPATION [W/m2]'},
{'abbr': 124, 'code': 124, 'title': 'var124 undefined'},
{'abbr': 125, 'code': 125, 'title': 'var125 undefined'},
{'abbr': 126, 'code': 126, 'title': 'var126 undefined'},
{'abbr': 127, 'code': 127, 'title': 'imag IMAGE [image^data]'},
{'abbr': 128, 'code': 128, 'title': 'tp2m 2 METRE TEMPERATURE [K]'},
{'abbr': 129, 'code': 129, 'title': 'dp2m 2 METRE DEWPOINT TEMPERATURE [K]'},
{'abbr': 130, 'code': 130, 'title': 'u10m 10 METRE U-WIND COMPONENT [m/s]'},
{'abbr': 131, 'code': 131, 'title': 'v10m 10 METRE V-WIND COMPONENT [m/s]'},
{'abbr': 132, 'code': 132, 'title': 'topo TOPOGRAPHY [m]'},
{'abbr': 133,
'code': 133,
'title': 'gsfp GEOMETRIC MEAN SURFACE PRESSURE [hPa]'},
{'abbr': 134, 'code': 134, 'title': 'lnsp LN SURFACE PRESSURE [hPa]'},
{'abbr': 135, 'code': 135, 'title': 'pslc SURFACE PRESSURE [hPa]'},
{'abbr': 136,
'code': 136,
'title': 'pslm M S L PRESSURE (MESINGER METHOD) [hPa]'},
{'abbr': 137, 'code': 137, 'title': 'mask MASK [-/+]'},
{'abbr': 138, 'code': 138, 'title': 'mxwu MAXIMUM U-WIND [m/s]'},
{'abbr': 139, 'code': 139, 'title': 'mxwv MAXIMUM V-WIND [m/s]'},
{'abbr': 140,
'code': 140,
'title': 'cape CONVECTIVE AVAIL. POT.ENERGY [m2/s2]'},
{'abbr': 141, 'code': 141, 'title': 'cine CONVECTIVE INHIB. ENERGY [m2/s2]'},
{'abbr': 142, 'code': 142, 'title': 'lhcv CONVECTIVE LATENT HEATING [K/s]'},
{'abbr': 143, 'code': 143, 'title': 'mscv CONVECTIVE MOISTURE SOURCE [1/s]'},
{'abbr': 144,
'code': 144,
'title': 'scvm SHALLOW CONV. MOISTURE SOURCE [1/s]'},
{'abbr': 145, 'code': 145, 'title': 'scvh SHALLOW CONVECTIVE HEATING [K/s]'},
{'abbr': 146, 'code': 146, 'title': 'mxwp MAXIMUM WIND PRESS. LVL [hPa]'},
{'abbr': 147, 'code': 147, 'title': 'ustr STORM MOTION U-COMPONENT [m/s]'},
{'abbr': 148, 'code': 148, 'title': 'vstr STORM MOTION V-COMPONENT [m/s]'},
{'abbr': 149, 'code': 149, 'title': 'cbnt MEAN CLOUD COVER [0-1]'},
{'abbr': 150, 'code': 150, 'title': 'pcbs PRESSURE AT CLOUD BASE [hPa]'},
{'abbr': 151, 'code': 151, 'title': 'pctp PRESSURE AT CLOUD TOP [hPa]'},
{'abbr': 152, 'code': 152, 'title': 'fzht FREEZING LEVEL HEIGHT [m]'},
{'abbr': 153,
'code': 153,
'title': 'fzrh FREEZING LEVEL RELATIVE HUMIDITY [%]'},
{'abbr': 154, 'code': 154, 'title': 'fdlt FLIGHT LEVELS TEMPERATURE [K]'},
{'abbr': 155, 'code': 155, 'title': 'fdlu FLIGHT LEVELS U-WIND [m/s]'},
{'abbr': 156, 'code': 156, 'title': 'fdlv FLIGHT LEVELS V-WIND [m/s]'},
{'abbr': 157, 'code': 157, 'title': 'tppp TROPOPAUSE PRESSURE [hPa]'},
{'abbr': 158, 'code': 158, 'title': 'tppt TROPOPAUSE TEMPERATURE [K]'},
{'abbr': 159, 'code': 159, 'title': 'tppu TROPOPAUSE U-WIND COMPONENT [m/s]'},
{'abbr': 160, 'code': 160, 'title': 'tppv TROPOPAUSE v-WIND COMPONENT [m/s]'},
{'abbr': 161, 'code': 161, 'title': 'var161 undefined'},
{'abbr': 162, 'code': 162, 'title': 'gvdu GRAVITY WAVE DRAG DU/DT [m/s2]'},
{'abbr': 163, 'code': 163, 'title': 'gvdv GRAVITY WAVE DRAG DV/DT [m/s2]'},
{'abbr': 164,
'code': 164,
'title': 'gvus GRAVITY WAVE DRAG SFC ZONAL STRESS [Pa]'},
{'abbr': 165,
'code': 165,
'title': 'gvvs GRAVITY WAVE DRAG SFC MERIDIONAL STRESS [Pa]'},
{'abbr': 166, 'code': 166, 'title': 'var166 undefined'},
{'abbr': 167,
'code': 167,
'title': 'dvsh DIVERGENCE OF SPECIFIC HUMIDITY [1/s]'},
{'abbr': 168, 'code': 168, 'title': 'hmfc HORIZ. MOISTURE FLUX CONV. [1/s]'},
{'abbr': 169,
'code': 169,
'title': 'vmfl VERT. INTEGRATED MOISTURE FLUX CONV. [kg/(m2*s)]'},
{'abbr': 170,
'code': 170,
'title': 'vadv VERTICAL MOISTURE ADVECTION [kg/(kg*s)]'},
{'abbr': 171,
'code': 171,
'title': 'nhcm NEG. HUM. CORR. MOISTURE SOURCE [kg/(kg*s)]'},
{'abbr': 172, 'code': 172, 'title': 'lglh LARGE SCALE LATENT HEATING [K/s]'},
{'abbr': 173, 'code': 173, 'title': 'lgms LARGE SCALE MOISTURE SOURCE [1/s]'},
{'abbr': 174, 'code': 174, 'title': 'smav SOIL MOISTURE AVAILABILITY [0-1]'},
{'abbr': 175, 'code': 175, 'title': 'tgrz SOIL TEMPERATURE OF ROOT ZONE [K]'},
{'abbr': 176, 'code': 176, 'title': 'bslh BARE SOIL LATENT HEAT [Ws/m2]'},
{'abbr': 177, 'code': 177, 'title': 'evpp POTENTIAL SFC EVAPORATION [m]'},
{'abbr': 178, 'code': 178, 'title': 'rnof RUNOFF [kg/m2/s)]'},
{'abbr': 179, 'code': 179, 'title': 'pitp INTERCEPTION LOSS [W/m2]'},
{'abbr': 180,
'code': 180,
'title': 'vpca VAPOR PRESSURE OF CANOPY AIR SPACE [mb]'},
{'abbr': 181, 'code': 181, 'title': 'qsfc SURFACE SPEC HUMIDITY [kg/kg]'},
{'abbr': 182, 'code': 182, 'title': 'ussl SOIL WETNESS OF SURFACE [0-1]'},
{'abbr': 183, 'code': 183, 'title': 'uzrs SOIL WETNESS OF ROOT ZONE [0-1]'},
{'abbr': 184,
'code': 184,
'title': 'uzds SOIL WETNESS OF DRAINAGE ZONE [0-1]'},
{'abbr': 185, 'code': 185, 'title': 'amdl STORAGE ON CANOPY [m]'},
{'abbr': 186, 'code': 186, 'title': 'amsl STORAGE ON GROUND [m]'},
{'abbr': 187, 'code': 187, 'title': 'tsfc SURFACE TEMPERATURE [K]'},
{'abbr': 188, 'code': 188, 'title': 'tems SURFACE ABSOLUTE TEMPERATURE [K]'},
{'abbr': 189,
'code': 189,
'title': 'tcas TEMPERATURE OF CANOPY AIR SPACE [K]'},
{'abbr': 190, 'code': 190, 'title': 'ctmp TEMPERATURE AT CANOPY [K]'},
{'abbr': 191,
'code': 191,
'title': 'tgsc GROUND/SURFACE COVER TEMPERATURE [K]'},
{'abbr': 192, 'code': 192, 'title': 'uves SURFACE ZONAL WIND (U) [m/s]'},
{'abbr': 193, 'code': 193, 'title': 'usst SURFACE ZONAL WIND STRESS [Pa]'},
{'abbr': 194, 'code': 194, 'title': 'vves SURFACE MERIDIONAL WIND (V) [m/s]'},
{'abbr': 195,
'code': 195,
'title': 'vsst SURFACE MERIDIONAL WIND STRESS [Pa]'},
{'abbr': 196, 'code': 196, 'title': 'suvf SURFACE MOMENTUM FLUX [W/m2]'},
{'abbr': 197, 'code': 197, 'title': 'iswf INCIDENT SHORT WAVE FLUX [W/m2]'},
{'abbr': 198, 'code': 198, 'title': 'ghfl TIME AVE GROUND HT FLX [W/m2]'},
{'abbr': 199, 'code': 199, 'title': 'var199 undefined'},
{'abbr': 200,
'code': 200,
'title': 'lwbc NET LONG WAVE AT BOTTOM (CLEAR) [W/m2]'},
{'abbr': 201,
'code': 201,
'title': 'lwtc OUTGOING LONG WAVE AT TOP (CLEAR) [W/m2]'},
{'abbr': 202,
'code': 202,
'title': 'swec SHORT WV ABSRBD BY EARTH/ATMOS (CLEAR) [W/m2]'},
{'abbr': 203,
'code': 203,
'title': 'ocac SHORT WAVE ABSORBED AT GROUND (CLEAR) [W/m2]'},
{'abbr': 204, 'code': 204, 'title': 'var204 undefined'},
{'abbr': 205, 'code': 205, 'title': 'lwrh LONG WAVE RADIATIVE HEATING [K/s]'},
{'abbr': 206, 'code': 206, 'title': 'swrh SHORT WAVE RADIATIVE HEATING [K/s]'},
{'abbr': 207,
'code': 207,
'title': 'olis DOWNWARD LONG WAVE AT BOTTOM [W/m2]'},
{'abbr': 208,
'code': 208,
'title': 'olic DOWNWARD LONG WAVE AT BOTTOM (CLEAR) [W/m2]'},
{'abbr': 209,
'code': 209,
'title': 'ocis DOWNWARD SHORT WAVE AT GROUND [W/m2]'},
{'abbr': 210,
'code': 210,
'title': 'ocic DOWNWARD SHORT WAVE AT GROUND (CLEAR) [W/m2]'},
{'abbr': 211, 'code': 211, 'title': 'oles UPWARD LONG WAVE AT BOTTOM [W/m2]'},
{'abbr': 212, 'code': 212, 'title': 'oces UPWARD SHORT WAVE AT GROUND [W/m2]'},
{'abbr': 213,
'code': 213,
'title': 'swgc UPWARD SHORT WAVE AT GROUND (CLEAR) [W/m2]'},
{'abbr': 214, 'code': 214, 'title': 'roce UPWARD SHORT WAVE AT TOP [W/m2]'},
{'abbr': 215,
'code': 215,
'title': 'swtc UPWARD SHORT WAVE AT TOP (CLEAR) [W/m2]'},
{'abbr': 216, 'code': 216, 'title': 'var216 undefined'},
{'abbr': 217, 'code': 217, 'title': 'var217 undefined'},
{'abbr': 218, 'code': 218, 'title': 'hhdf HORIZONTAL HEATING DIFFUSION [K/s]'},
{'abbr': 219,
'code': 219,
'title': 'hmdf HORIZONTAL MOISTURE DIFFUSION [1/s]'},
{'abbr': 220,
'code': 220,
'title': 'hddf HORIZONTAL DIVERGENCE DIFFUSION [1/s2]'},
{'abbr': 221,
'code': 221,
'title': 'hvdf HORIZONTAL VORTICITY DIFFUSION [1/s2]'},
{'abbr': 222,
'code': 222,
'title': 'vdms VERTICAL DIFF. MOISTURE SOURCE [1/s]'},
{'abbr': 223, 'code': 223, 'title': 'vdfu VERTICAL DIFFUSION DU/DT [m/s2]'},
{'abbr': 224, 'code': 224, 'title': 'vdfv VERTICAL DIFFUSION DV/DT [m/s2]'},
{'abbr': 225, 'code': 225, 'title': 'vdfh VERTICAL DIFFUSION HEATING [K/s]'},
{'abbr': 226, 'code': 226, 'title': 'umrs SURFACE RELATIVE HUMIDITY [no Dim]'},
{'abbr': 227,
'code': 227,
'title': 'vdcc VERTICAL DIST TOTAL CLOUD COVER [no Dim]'},
{'abbr': 228, 'code': 228, 'title': 'var228 undefined'},
{'abbr': 229, 'code': 229, 'title': 'var229 undefined'},
{'abbr': 230,
'code': 230,
'title': 'usmt TIME MEAN SURFACE ZONAL WIND (U) [m/s]'},
{'abbr': 231,
'code': 231,
'title': 'vsmt TIME MEAN SURFACE MERIDIONAL WIND (V) [m/s]'},
{'abbr': 232,
'code': 232,
'title': 'tsmt TIME MEAN SURFACE ABSOLUTE TEMPERATURE [K]'},
{'abbr': 233,
'code': 233,
'title': 'rsmt TIME MEAN SURFACE RELATIVE HUMIDITY [no Dim]'},
{'abbr': 234, 'code': 234, 'title': 'atmt TIME MEAN ABSOLUTE TEMPERATURE [K]'},
{'abbr': 235,
'code': 235,
'title': 'stmt TIME MEAN DEEP SOIL TEMPERATURE [K]'},
{'abbr': 236, 'code': 236, 'title': 'ommt TIME MEAN DERIVED OMEGA [Pa/s]'},
{'abbr': 237, 'code': 237, 'title': 'dvmt TIME MEAN DIVERGENCE [1/s]'},
{'abbr': 238, 'code': 238, 'title': 'zhmt TIME MEAN GEOPOTENTIAL HEIGHT [m]'},
{'abbr': 239,
'code': 239,
'title': 'lnmt TIME MEAN LOG SURFACE PRESSURE [ln(cbar)]'},
{'abbr': 240, 'code': 240, 'title': 'mkmt TIME MEAN MASK [-/+]'},
{'abbr': 241,
'code': 241,
'title': 'vvmt TIME MEAN MERIDIONAL WIND (V) [m/s]'},
{'abbr': 242, 'code': 242, 'title': 'omtm TIME MEAN OMEGA [cbar/s]'},
{'abbr': 243,
'code': 243,
'title': 'ptmt TIME MEAN POTENTIAL TEMPERATURE [K]'},
{'abbr': 244, 'code': 244, 'title': 'pcmt TIME MEAN PRECIP. WATER [kg/m2]'},
{'abbr': 245, 'code': 245, 'title': 'rhmt TIME MEAN RELATIVE HUMIDITY [%]'},
{'abbr': 246, 'code': 246, 'title': 'mpmt TIME MEAN SEA LEVEL PRESSURE [hPa]'},
{'abbr': 247, 'code': 247, 'title': 'simt TIME MEAN SIGMADOT [1/s]'},
{'abbr': 248,
'code': 248,
'title': 'uemt TIME MEAN SPECIFIC HUMIDITY [kg/kg]'},
{'abbr': 249, 'code': 249, 'title': 'fcmt TIME MEAN STREAM FUNCTION| m2/s]'},
{'abbr': 250, 'code': 250, 'title': 'psmt TIME MEAN SURFACE PRESSURE [hPa]'},
{'abbr': 251, 'code': 251, 'title': 'tmmt TIME MEAN SURFACE TEMPERATURE [K]'},
{'abbr': 252,
'code': 252,
'title': 'pvmt TIME MEAN VELOCITY POTENTIAL [m2/s]'},
{'abbr': 253, 'code': 253, 'title': 'tvmt TIME MEAN VIRTUAL TEMPERATURE [K]'},
{'abbr': 254, 'code': 254, 'title': 'vtmt TIME MEAN VORTICITY [1/s]'},
{'abbr': None, 'code': 255, 'title': 'uvmt TIME MEAN ZONAL WIND (U) [m/s]'})
|
def load(h):
return ({'abbr': 1, 'code': 1, 'title': 'PRES Pressure [hPa]'}, {'abbr': 2, 'code': 2, 'title': 'psnm Pressure reduced to MSL [hPa]'}, {'abbr': 3, 'code': 3, 'title': 'tsps Pressure tendency [Pa/s]'}, {'abbr': 4, 'code': 4, 'title': 'var4 undefined'}, {'abbr': 5, 'code': 5, 'title': 'var5 undefined'}, {'abbr': 6, 'code': 6, 'title': 'geop Geopotential [dam]'}, {'abbr': 7, 'code': 7, 'title': 'zgeo Geopotential height [gpm]'}, {'abbr': 8, 'code': 8, 'title': 'gzge Geometric height [m]'}, {'abbr': 9, 'code': 9, 'title': 'var9 undefined'}, {'abbr': 10, 'code': 10, 'title': 'var10 undefined'}, {'abbr': 11, 'code': 11, 'title': 'temp ABSOLUTE TEMPERATURE [K]'}, {'abbr': 12, 'code': 12, 'title': 'vtmp VIRTUAL TEMPERATURE [K]'}, {'abbr': 13, 'code': 13, 'title': 'ptmp POTENTIAL TEMPERATURE [K]'}, {'abbr': 14, 'code': 14, 'title': 'psat PSEUDO-ADIABATIC POTENTIAL TEMPERATURE [K]'}, {'abbr': 15, 'code': 15, 'title': 'mxtp MAXIMUM TEMPERATURE [K]'}, {'abbr': 16, 'code': 16, 'title': 'mntp MINIMUM TEMPERATURE [K]'}, {'abbr': 17, 'code': 17, 'title': 'tpor DEW POINT TEMPERATURE [K]'}, {'abbr': 18, 'code': 18, 'title': 'dptd DEW POINT DEPRESSION [K]'}, {'abbr': 19, 'code': 19, 'title': 'lpsr LAPSE RATE [K/m]'}, {'abbr': 20, 'code': 20, 'title': 'var20 undefined'}, {'abbr': 21, 'code': 21, 'title': 'rds1 RADAR SPECTRA(1) [non-dim]'}, {'abbr': 22, 'code': 22, 'title': 'rds2 RADAR SPECTRA(2) [non-dim]'}, {'abbr': 23, 'code': 23, 'title': 'rds3 RADAR SPECTRA(3) [non-dim]'}, {'abbr': 24, 'code': 24, 'title': 'var24 undefined'}, {'abbr': 25, 'code': 25, 'title': 'tpan TEMPERATURE ANOMALY [K]'}, {'abbr': 26, 'code': 26, 'title': 'psan PRESSURE ANOMALY [Pa hPa]'}, {'abbr': 27, 'code': 27, 'title': 'zgan GEOPOT HEIGHT ANOMALY [m]'}, {'abbr': 28, 'code': 28, 'title': 'wvs1 WAVE SPECTRA(1) [non-dim]'}, {'abbr': 29, 'code': 29, 'title': 'wvs2 WAVE SPECTRA(2) [non-dim]'}, {'abbr': 30, 'code': 30, 'title': 'wvs3 WAVE SPECTRA(3) [non-dim]'}, {'abbr': 31, 'code': 31, 'title': 'wind WIND DIRECTION [deg]'}, {'abbr': 32, 'code': 32, 'title': 'wins WIND SPEED [m/s]'}, {'abbr': 33, 'code': 33, 'title': 'uvel ZONAL WIND (U) [m/s]'}, {'abbr': 34, 'code': 34, 'title': 'vvel MERIDIONAL WIND (V) [m/s]'}, {'abbr': 35, 'code': 35, 'title': 'fcor STREAM FUNCTION [m2/s]'}, {'abbr': 36, 'code': 36, 'title': 'potv VELOCITY POTENTIAL [m2/s]'}, {'abbr': 37, 'code': 37, 'title': 'var37 undefined'}, {'abbr': 38, 'code': 38, 'title': 'sgvv SIGMA COORD VERT VEL [sec/sec]'}, {'abbr': 39, 'code': 39, 'title': 'omeg OMEGA [Pa/s]'}, {'abbr': 40, 'code': 40, 'title': 'omg2 VERTICAL VELOCITY [m/s]'}, {'abbr': 41, 'code': 41, 'title': 'abvo ABSOLUTE VORTICITY [10**5/sec]'}, {'abbr': 42, 'code': 42, 'title': 'abdv ABSOLUTE DIVERGENCE [10**5/sec]'}, {'abbr': 43, 'code': 43, 'title': 'vort VORTICITY [1/s]'}, {'abbr': 44, 'code': 44, 'title': 'divg DIVERGENCE [1/s]'}, {'abbr': 45, 'code': 45, 'title': 'vucs VERTICAL U-COMP SHEAR [1/sec]'}, {'abbr': 46, 'code': 46, 'title': 'vvcs VERT V-COMP SHEAR [1/sec]'}, {'abbr': 47, 'code': 47, 'title': 'dirc DIRECTION OF CURRENT [deg]'}, {'abbr': 48, 'code': 48, 'title': 'spdc SPEED OF CURRENT [m/s]'}, {'abbr': 49, 'code': 49, 'title': 'ucpc U-COMPONENT OF CURRENT [m/s]'}, {'abbr': 50, 'code': 50, 'title': 'vcpc V-COMPONENT OF CURRENT [m/s]'}, {'abbr': 51, 'code': 51, 'title': 'umes SPECIFIC HUMIDITY [kg/kg]'}, {'abbr': 52, 'code': 52, 'title': 'umrl RELATIVE HUMIDITY [no Dim]'}, {'abbr': 53, 'code': 53, 'title': 'hmxr HUMIDITY MIXING RATIO [kg/kg]'}, {'abbr': 54, 'code': 54, 'title': 'agpl INST. PRECIPITABLE WATER [Kg/m2]'}, {'abbr': 55, 'code': 55, 'title': 'vapp VAPOUR PRESSURE [Pa hpa]'}, {'abbr': 56, 'code': 56, 'title': 'sadf SATURATION DEFICIT [Pa hPa]'}, {'abbr': 57, 'code': 57, 'title': 'evap EVAPORATION [Kg/m2/day]'}, {'abbr': 58, 'code': 58, 'title': 'var58 undefined'}, {'abbr': 59, 'code': 59, 'title': 'prcr PRECIPITATION RATE [kg/m2/day]'}, {'abbr': 60, 'code': 60, 'title': 'thpb THUNDER PROBABILITY [%]'}, {'abbr': 61, 'code': 61, 'title': 'prec TOTAL PRECIPITATION [Kg/m2/day]'}, {'abbr': 62, 'code': 62, 'title': 'prge LARGE SCALE PRECIPITATION [Kg/m2/day]'}, {'abbr': 63, 'code': 63, 'title': 'prcv CONVECTIVE PRECIPITATION [Kg/m2/day]'}, {'abbr': 64, 'code': 64, 'title': 'neve SNOWFALL [Kg/m2/day]'}, {'abbr': 65, 'code': 65, 'title': 'wenv WAT EQUIV ACC SNOW DEPTH [kg/m2]'}, {'abbr': 66, 'code': 66, 'title': 'nvde SNOW DEPTH [cm]'}, {'abbr': 67, 'code': 67, 'title': 'mxld MIXED LAYER DEPTH [m cm]'}, {'abbr': 68, 'code': 68, 'title': 'tthd TRANS THERMOCLINE DEPTH [m cm]'}, {'abbr': 69, 'code': 69, 'title': 'mthd MAIN THERMOCLINE DEPTH [m cm]'}, {'abbr': 70, 'code': 70, 'title': 'mtha MAIN THERMOCLINE ANOM [m cm]'}, {'abbr': 71, 'code': 71, 'title': 'cbnv CLOUD COVER [0-1]'}, {'abbr': 72, 'code': 72, 'title': 'cvnv CONVECTIVE CLOUD COVER [0-1]'}, {'abbr': 73, 'code': 73, 'title': 'lwnv LOW CLOUD COVER [0-1]'}, {'abbr': 74, 'code': 74, 'title': 'mdnv MEDIUM CLOUD COVER [0-1]'}, {'abbr': 75, 'code': 75, 'title': 'hinv HIGH CLOUD COVER [0-1]'}, {'abbr': 76, 'code': 76, 'title': 'wtnv CLOUD WATER [kg/m2]'}, {'abbr': 77, 'code': 77, 'title': 'bli BEST LIFTED INDEX (TO 500 HPA) [K]'}, {'abbr': 78, 'code': 78, 'title': 'var78 undefined'}, {'abbr': 79, 'code': 79, 'title': 'var79 undefined'}, {'abbr': 80, 'code': 80, 'title': 'var80 undefined'}, {'abbr': 81, 'code': 81, 'title': 'lsmk LAND SEA MASK [0,1]'}, {'abbr': 82, 'code': 82, 'title': 'dslm DEV SEA_LEV FROM MEAN [m]'}, {'abbr': 83, 'code': 83, 'title': 'zorl ROUGHNESS LENGTH [m]'}, {'abbr': 84, 'code': 84, 'title': 'albe ALBEDO [%]'}, {'abbr': 85, 'code': 85, 'title': 'dstp DEEP SOIL TEMPERATURE [K]'}, {'abbr': 86, 'code': 86, 'title': 'soic SOIL MOISTURE CONTENT [Kg/m2]'}, {'abbr': 87, 'code': 87, 'title': 'vege VEGETATION [%]'}, {'abbr': 88, 'code': 88, 'title': 'var88 undefined'}, {'abbr': 89, 'code': 89, 'title': 'dens DENSITY [kg/m3]'}, {'abbr': 90, 'code': 90, 'title': 'var90 Undefined'}, {'abbr': 91, 'code': 91, 'title': 'icec ICE CONCENTRATION [fraction]'}, {'abbr': 92, 'code': 92, 'title': 'icet ICE THICKNESS [m]'}, {'abbr': 93, 'code': 93, 'title': 'iced DIRECTION OF ICE DRIFT [deg]'}, {'abbr': 94, 'code': 94, 'title': 'ices SPEED OF ICE DRIFT [m/s]'}, {'abbr': 95, 'code': 95, 'title': 'iceu U-COMP OF ICE DRIFT [m/s]'}, {'abbr': 96, 'code': 96, 'title': 'icev V-COMP OF ICE DRIFT [m/s]'}, {'abbr': 97, 'code': 97, 'title': 'iceg ICE GROWTH [m]'}, {'abbr': 98, 'code': 98, 'title': 'icdv ICE DIVERGENCE [sec/sec]'}, {'abbr': 99, 'code': 99, 'title': 'var99 undefined'}, {'abbr': 100, 'code': 100, 'title': 'shcw SIG HGT COM WAVE/SWELL [m]'}, {'abbr': 101, 'code': 101, 'title': 'wwdi DIRECTION OF WIND WAVE [deg]'}, {'abbr': 102, 'code': 102, 'title': 'wwsh SIG HGHT OF WIND WAVES [m]'}, {'abbr': 103, 'code': 103, 'title': 'wwmp MEAN PERIOD WIND WAVES [sec]'}, {'abbr': 104, 'code': 104, 'title': 'swdi DIRECTION OF SWELL WAVE [deg]'}, {'abbr': 105, 'code': 105, 'title': 'swsh SIG HEIGHT SWELL WAVES [m]'}, {'abbr': 106, 'code': 106, 'title': 'swmp MEAN PERIOD SWELL WAVES [sec]'}, {'abbr': 107, 'code': 107, 'title': 'prwd PRIMARY WAVE DIRECTION [deg]'}, {'abbr': 108, 'code': 108, 'title': 'prmp PRIM WAVE MEAN PERIOD [s]'}, {'abbr': 109, 'code': 109, 'title': 'swdi SECOND WAVE DIRECTION [deg]'}, {'abbr': 110, 'code': 110, 'title': 'swmp SECOND WAVE MEAN PERIOD [s]'}, {'abbr': 111, 'code': 111, 'title': 'ocas SHORT WAVE ABSORBED AT GROUND [W/m2]'}, {'abbr': 112, 'code': 112, 'title': 'slds NET LONG WAVE AT BOTTOM [W/m2]'}, {'abbr': 113, 'code': 113, 'title': 'nswr NET SHORT-WAV RAD(TOP) [W/m2]'}, {'abbr': 114, 'code': 114, 'title': 'role OUTGOING LONG WAVE AT TOP [W/m2]'}, {'abbr': 115, 'code': 115, 'title': 'lwrd LONG-WAV RAD [W/m2]'}, {'abbr': 116, 'code': 116, 'title': 'swea SHORT WAVE ABSORBED BY EARTH/ATMOSPHERE [W/m2]'}, {'abbr': 117, 'code': 117, 'title': 'glbr GLOBAL RADIATION [W/m2 ]'}, {'abbr': 118, 'code': 118, 'title': 'var118 undefined'}, {'abbr': 119, 'code': 119, 'title': 'var119 undefined'}, {'abbr': 120, 'code': 120, 'title': 'var120 undefined'}, {'abbr': 121, 'code': 121, 'title': 'clsf LATENT HEAT FLUX FROM SURFACE [W/m2]'}, {'abbr': 122, 'code': 122, 'title': 'cssf SENSIBLE HEAT FLUX FROM SURFACE [W/m2]'}, {'abbr': 123, 'code': 123, 'title': 'blds BOUND LAYER DISSIPATION [W/m2]'}, {'abbr': 124, 'code': 124, 'title': 'var124 undefined'}, {'abbr': 125, 'code': 125, 'title': 'var125 undefined'}, {'abbr': 126, 'code': 126, 'title': 'var126 undefined'}, {'abbr': 127, 'code': 127, 'title': 'imag IMAGE [image^data]'}, {'abbr': 128, 'code': 128, 'title': 'tp2m 2 METRE TEMPERATURE [K]'}, {'abbr': 129, 'code': 129, 'title': 'dp2m 2 METRE DEWPOINT TEMPERATURE [K]'}, {'abbr': 130, 'code': 130, 'title': 'u10m 10 METRE U-WIND COMPONENT [m/s]'}, {'abbr': 131, 'code': 131, 'title': 'v10m 10 METRE V-WIND COMPONENT [m/s]'}, {'abbr': 132, 'code': 132, 'title': 'topo TOPOGRAPHY [m]'}, {'abbr': 133, 'code': 133, 'title': 'gsfp GEOMETRIC MEAN SURFACE PRESSURE [hPa]'}, {'abbr': 134, 'code': 134, 'title': 'lnsp LN SURFACE PRESSURE [hPa]'}, {'abbr': 135, 'code': 135, 'title': 'pslc SURFACE PRESSURE [hPa]'}, {'abbr': 136, 'code': 136, 'title': 'pslm M S L PRESSURE (MESINGER METHOD) [hPa]'}, {'abbr': 137, 'code': 137, 'title': 'mask MASK [-/+]'}, {'abbr': 138, 'code': 138, 'title': 'mxwu MAXIMUM U-WIND [m/s]'}, {'abbr': 139, 'code': 139, 'title': 'mxwv MAXIMUM V-WIND [m/s]'}, {'abbr': 140, 'code': 140, 'title': 'cape CONVECTIVE AVAIL. POT.ENERGY [m2/s2]'}, {'abbr': 141, 'code': 141, 'title': 'cine CONVECTIVE INHIB. ENERGY [m2/s2]'}, {'abbr': 142, 'code': 142, 'title': 'lhcv CONVECTIVE LATENT HEATING [K/s]'}, {'abbr': 143, 'code': 143, 'title': 'mscv CONVECTIVE MOISTURE SOURCE [1/s]'}, {'abbr': 144, 'code': 144, 'title': 'scvm SHALLOW CONV. MOISTURE SOURCE [1/s]'}, {'abbr': 145, 'code': 145, 'title': 'scvh SHALLOW CONVECTIVE HEATING [K/s]'}, {'abbr': 146, 'code': 146, 'title': 'mxwp MAXIMUM WIND PRESS. LVL [hPa]'}, {'abbr': 147, 'code': 147, 'title': 'ustr STORM MOTION U-COMPONENT [m/s]'}, {'abbr': 148, 'code': 148, 'title': 'vstr STORM MOTION V-COMPONENT [m/s]'}, {'abbr': 149, 'code': 149, 'title': 'cbnt MEAN CLOUD COVER [0-1]'}, {'abbr': 150, 'code': 150, 'title': 'pcbs PRESSURE AT CLOUD BASE [hPa]'}, {'abbr': 151, 'code': 151, 'title': 'pctp PRESSURE AT CLOUD TOP [hPa]'}, {'abbr': 152, 'code': 152, 'title': 'fzht FREEZING LEVEL HEIGHT [m]'}, {'abbr': 153, 'code': 153, 'title': 'fzrh FREEZING LEVEL RELATIVE HUMIDITY [%]'}, {'abbr': 154, 'code': 154, 'title': 'fdlt FLIGHT LEVELS TEMPERATURE [K]'}, {'abbr': 155, 'code': 155, 'title': 'fdlu FLIGHT LEVELS U-WIND [m/s]'}, {'abbr': 156, 'code': 156, 'title': 'fdlv FLIGHT LEVELS V-WIND [m/s]'}, {'abbr': 157, 'code': 157, 'title': 'tppp TROPOPAUSE PRESSURE [hPa]'}, {'abbr': 158, 'code': 158, 'title': 'tppt TROPOPAUSE TEMPERATURE [K]'}, {'abbr': 159, 'code': 159, 'title': 'tppu TROPOPAUSE U-WIND COMPONENT [m/s]'}, {'abbr': 160, 'code': 160, 'title': 'tppv TROPOPAUSE v-WIND COMPONENT [m/s]'}, {'abbr': 161, 'code': 161, 'title': 'var161 undefined'}, {'abbr': 162, 'code': 162, 'title': 'gvdu GRAVITY WAVE DRAG DU/DT [m/s2]'}, {'abbr': 163, 'code': 163, 'title': 'gvdv GRAVITY WAVE DRAG DV/DT [m/s2]'}, {'abbr': 164, 'code': 164, 'title': 'gvus GRAVITY WAVE DRAG SFC ZONAL STRESS [Pa]'}, {'abbr': 165, 'code': 165, 'title': 'gvvs GRAVITY WAVE DRAG SFC MERIDIONAL STRESS [Pa]'}, {'abbr': 166, 'code': 166, 'title': 'var166 undefined'}, {'abbr': 167, 'code': 167, 'title': 'dvsh DIVERGENCE OF SPECIFIC HUMIDITY [1/s]'}, {'abbr': 168, 'code': 168, 'title': 'hmfc HORIZ. MOISTURE FLUX CONV. [1/s]'}, {'abbr': 169, 'code': 169, 'title': 'vmfl VERT. INTEGRATED MOISTURE FLUX CONV. [kg/(m2*s)]'}, {'abbr': 170, 'code': 170, 'title': 'vadv VERTICAL MOISTURE ADVECTION [kg/(kg*s)]'}, {'abbr': 171, 'code': 171, 'title': 'nhcm NEG. HUM. CORR. MOISTURE SOURCE [kg/(kg*s)]'}, {'abbr': 172, 'code': 172, 'title': 'lglh LARGE SCALE LATENT HEATING [K/s]'}, {'abbr': 173, 'code': 173, 'title': 'lgms LARGE SCALE MOISTURE SOURCE [1/s]'}, {'abbr': 174, 'code': 174, 'title': 'smav SOIL MOISTURE AVAILABILITY [0-1]'}, {'abbr': 175, 'code': 175, 'title': 'tgrz SOIL TEMPERATURE OF ROOT ZONE [K]'}, {'abbr': 176, 'code': 176, 'title': 'bslh BARE SOIL LATENT HEAT [Ws/m2]'}, {'abbr': 177, 'code': 177, 'title': 'evpp POTENTIAL SFC EVAPORATION [m]'}, {'abbr': 178, 'code': 178, 'title': 'rnof RUNOFF [kg/m2/s)]'}, {'abbr': 179, 'code': 179, 'title': 'pitp INTERCEPTION LOSS [W/m2]'}, {'abbr': 180, 'code': 180, 'title': 'vpca VAPOR PRESSURE OF CANOPY AIR SPACE [mb]'}, {'abbr': 181, 'code': 181, 'title': 'qsfc SURFACE SPEC HUMIDITY [kg/kg]'}, {'abbr': 182, 'code': 182, 'title': 'ussl SOIL WETNESS OF SURFACE [0-1]'}, {'abbr': 183, 'code': 183, 'title': 'uzrs SOIL WETNESS OF ROOT ZONE [0-1]'}, {'abbr': 184, 'code': 184, 'title': 'uzds SOIL WETNESS OF DRAINAGE ZONE [0-1]'}, {'abbr': 185, 'code': 185, 'title': 'amdl STORAGE ON CANOPY [m]'}, {'abbr': 186, 'code': 186, 'title': 'amsl STORAGE ON GROUND [m]'}, {'abbr': 187, 'code': 187, 'title': 'tsfc SURFACE TEMPERATURE [K]'}, {'abbr': 188, 'code': 188, 'title': 'tems SURFACE ABSOLUTE TEMPERATURE [K]'}, {'abbr': 189, 'code': 189, 'title': 'tcas TEMPERATURE OF CANOPY AIR SPACE [K]'}, {'abbr': 190, 'code': 190, 'title': 'ctmp TEMPERATURE AT CANOPY [K]'}, {'abbr': 191, 'code': 191, 'title': 'tgsc GROUND/SURFACE COVER TEMPERATURE [K]'}, {'abbr': 192, 'code': 192, 'title': 'uves SURFACE ZONAL WIND (U) [m/s]'}, {'abbr': 193, 'code': 193, 'title': 'usst SURFACE ZONAL WIND STRESS [Pa]'}, {'abbr': 194, 'code': 194, 'title': 'vves SURFACE MERIDIONAL WIND (V) [m/s]'}, {'abbr': 195, 'code': 195, 'title': 'vsst SURFACE MERIDIONAL WIND STRESS [Pa]'}, {'abbr': 196, 'code': 196, 'title': 'suvf SURFACE MOMENTUM FLUX [W/m2]'}, {'abbr': 197, 'code': 197, 'title': 'iswf INCIDENT SHORT WAVE FLUX [W/m2]'}, {'abbr': 198, 'code': 198, 'title': 'ghfl TIME AVE GROUND HT FLX [W/m2]'}, {'abbr': 199, 'code': 199, 'title': 'var199 undefined'}, {'abbr': 200, 'code': 200, 'title': 'lwbc NET LONG WAVE AT BOTTOM (CLEAR) [W/m2]'}, {'abbr': 201, 'code': 201, 'title': 'lwtc OUTGOING LONG WAVE AT TOP (CLEAR) [W/m2]'}, {'abbr': 202, 'code': 202, 'title': 'swec SHORT WV ABSRBD BY EARTH/ATMOS (CLEAR) [W/m2]'}, {'abbr': 203, 'code': 203, 'title': 'ocac SHORT WAVE ABSORBED AT GROUND (CLEAR) [W/m2]'}, {'abbr': 204, 'code': 204, 'title': 'var204 undefined'}, {'abbr': 205, 'code': 205, 'title': 'lwrh LONG WAVE RADIATIVE HEATING [K/s]'}, {'abbr': 206, 'code': 206, 'title': 'swrh SHORT WAVE RADIATIVE HEATING [K/s]'}, {'abbr': 207, 'code': 207, 'title': 'olis DOWNWARD LONG WAVE AT BOTTOM [W/m2]'}, {'abbr': 208, 'code': 208, 'title': 'olic DOWNWARD LONG WAVE AT BOTTOM (CLEAR) [W/m2]'}, {'abbr': 209, 'code': 209, 'title': 'ocis DOWNWARD SHORT WAVE AT GROUND [W/m2]'}, {'abbr': 210, 'code': 210, 'title': 'ocic DOWNWARD SHORT WAVE AT GROUND (CLEAR) [W/m2]'}, {'abbr': 211, 'code': 211, 'title': 'oles UPWARD LONG WAVE AT BOTTOM [W/m2]'}, {'abbr': 212, 'code': 212, 'title': 'oces UPWARD SHORT WAVE AT GROUND [W/m2]'}, {'abbr': 213, 'code': 213, 'title': 'swgc UPWARD SHORT WAVE AT GROUND (CLEAR) [W/m2]'}, {'abbr': 214, 'code': 214, 'title': 'roce UPWARD SHORT WAVE AT TOP [W/m2]'}, {'abbr': 215, 'code': 215, 'title': 'swtc UPWARD SHORT WAVE AT TOP (CLEAR) [W/m2]'}, {'abbr': 216, 'code': 216, 'title': 'var216 undefined'}, {'abbr': 217, 'code': 217, 'title': 'var217 undefined'}, {'abbr': 218, 'code': 218, 'title': 'hhdf HORIZONTAL HEATING DIFFUSION [K/s]'}, {'abbr': 219, 'code': 219, 'title': 'hmdf HORIZONTAL MOISTURE DIFFUSION [1/s]'}, {'abbr': 220, 'code': 220, 'title': 'hddf HORIZONTAL DIVERGENCE DIFFUSION [1/s2]'}, {'abbr': 221, 'code': 221, 'title': 'hvdf HORIZONTAL VORTICITY DIFFUSION [1/s2]'}, {'abbr': 222, 'code': 222, 'title': 'vdms VERTICAL DIFF. MOISTURE SOURCE [1/s]'}, {'abbr': 223, 'code': 223, 'title': 'vdfu VERTICAL DIFFUSION DU/DT [m/s2]'}, {'abbr': 224, 'code': 224, 'title': 'vdfv VERTICAL DIFFUSION DV/DT [m/s2]'}, {'abbr': 225, 'code': 225, 'title': 'vdfh VERTICAL DIFFUSION HEATING [K/s]'}, {'abbr': 226, 'code': 226, 'title': 'umrs SURFACE RELATIVE HUMIDITY [no Dim]'}, {'abbr': 227, 'code': 227, 'title': 'vdcc VERTICAL DIST TOTAL CLOUD COVER [no Dim]'}, {'abbr': 228, 'code': 228, 'title': 'var228 undefined'}, {'abbr': 229, 'code': 229, 'title': 'var229 undefined'}, {'abbr': 230, 'code': 230, 'title': 'usmt TIME MEAN SURFACE ZONAL WIND (U) [m/s]'}, {'abbr': 231, 'code': 231, 'title': 'vsmt TIME MEAN SURFACE MERIDIONAL WIND (V) [m/s]'}, {'abbr': 232, 'code': 232, 'title': 'tsmt TIME MEAN SURFACE ABSOLUTE TEMPERATURE [K]'}, {'abbr': 233, 'code': 233, 'title': 'rsmt TIME MEAN SURFACE RELATIVE HUMIDITY [no Dim]'}, {'abbr': 234, 'code': 234, 'title': 'atmt TIME MEAN ABSOLUTE TEMPERATURE [K]'}, {'abbr': 235, 'code': 235, 'title': 'stmt TIME MEAN DEEP SOIL TEMPERATURE [K]'}, {'abbr': 236, 'code': 236, 'title': 'ommt TIME MEAN DERIVED OMEGA [Pa/s]'}, {'abbr': 237, 'code': 237, 'title': 'dvmt TIME MEAN DIVERGENCE [1/s]'}, {'abbr': 238, 'code': 238, 'title': 'zhmt TIME MEAN GEOPOTENTIAL HEIGHT [m]'}, {'abbr': 239, 'code': 239, 'title': 'lnmt TIME MEAN LOG SURFACE PRESSURE [ln(cbar)]'}, {'abbr': 240, 'code': 240, 'title': 'mkmt TIME MEAN MASK [-/+]'}, {'abbr': 241, 'code': 241, 'title': 'vvmt TIME MEAN MERIDIONAL WIND (V) [m/s]'}, {'abbr': 242, 'code': 242, 'title': 'omtm TIME MEAN OMEGA [cbar/s]'}, {'abbr': 243, 'code': 243, 'title': 'ptmt TIME MEAN POTENTIAL TEMPERATURE [K]'}, {'abbr': 244, 'code': 244, 'title': 'pcmt TIME MEAN PRECIP. WATER [kg/m2]'}, {'abbr': 245, 'code': 245, 'title': 'rhmt TIME MEAN RELATIVE HUMIDITY [%]'}, {'abbr': 246, 'code': 246, 'title': 'mpmt TIME MEAN SEA LEVEL PRESSURE [hPa]'}, {'abbr': 247, 'code': 247, 'title': 'simt TIME MEAN SIGMADOT [1/s]'}, {'abbr': 248, 'code': 248, 'title': 'uemt TIME MEAN SPECIFIC HUMIDITY [kg/kg]'}, {'abbr': 249, 'code': 249, 'title': 'fcmt TIME MEAN STREAM FUNCTION| m2/s]'}, {'abbr': 250, 'code': 250, 'title': 'psmt TIME MEAN SURFACE PRESSURE [hPa]'}, {'abbr': 251, 'code': 251, 'title': 'tmmt TIME MEAN SURFACE TEMPERATURE [K]'}, {'abbr': 252, 'code': 252, 'title': 'pvmt TIME MEAN VELOCITY POTENTIAL [m2/s]'}, {'abbr': 253, 'code': 253, 'title': 'tvmt TIME MEAN VIRTUAL TEMPERATURE [K]'}, {'abbr': 254, 'code': 254, 'title': 'vtmt TIME MEAN VORTICITY [1/s]'}, {'abbr': None, 'code': 255, 'title': 'uvmt TIME MEAN ZONAL WIND (U) [m/s]'})
|
class Settings:
params = ()
def __init__(self, params):
self.params = params
|
class Settings:
params = ()
def __init__(self, params):
self.params = params
|
urlChatAdd = '/chat/add'
urlUserAdd = '/chat/adduser'
urlGetUsers = '/chat/getusers/'
urlGetChats = '/chat/chats'
urlPost = '/chat/post'
urlHist = '/chat/hist'
urlAuth = '/chat/auth'
|
url_chat_add = '/chat/add'
url_user_add = '/chat/adduser'
url_get_users = '/chat/getusers/'
url_get_chats = '/chat/chats'
url_post = '/chat/post'
url_hist = '/chat/hist'
url_auth = '/chat/auth'
|
"""
This module contains the definitions for Bike and its subclasses Bicycle and
Motorbike.
"""
class Bike:
"""
Class defining a bike that can be ridden and have its gear changed.
Attributes:
seats: number of seats the bike has
gears: number of gears the bike has
"""
def __init__(self, seats, gears):
"""
Creates a new Bike object.
Args:
seats: number of seats the bike has
gears: number of gears the bike has
"""
self.seats = seats
self.gears = gears
self._curr_gear = 1 # current gear, private
self._riding = False # bike is per default not ridden
@property
def curr_gear(self):
"""
Purpose of this function is to enable the user to check the gear
status, but is only able to change it with a specific method.
(was not necessary to implement it this way)
"""
return self._curr_gear
def start_ride(self):
"""
Starts a bike ride.
Returns:
True if successful.
False if bike is already on a ride.
"""
# can't ride a bike if already ridden
if self._riding:
return False
self._riding = True
return True
def end_ride(self):
"""
Ends a bike ride.
Returns:
True if successful.
False if bike is not currently ridden.
"""
# can't stop a bike ride if the bike is already standing
if not self._riding:
return False
self._riding = False
return True
def change_gear(self, new_gear):
"""
Changes bike gear to a new gear.
Args:
new_gear: gear to be changed to
Returns:
True if gear was successfully changed.
Raises:
ValueError if current gear is same as new gear or new gear is <= 0
or not in range of available gears.
"""
if self._curr_gear == new_gear or not 0 < new_gear <= self.gears:
raise ValueError("Already in this gear or invalid gear number.")
self._curr_gear = new_gear
return True
class Bicycle(Bike):
"""
Class defining a Bicycle (extending Bike) that can be ridden, have its
gear changed and has a bell that can be rung.
Attributes:
seats: number of seats the bike has
gears: number of gears the bike has
bell_sound: sound the bell makes when rung
"""
def __init__(self, seats=1, gears=7, bell_sound="ring ring"):
"""
Creates a new Bike object.
Args:
seats: number of seats the bicycle has, defaults to 1
gears: number of gears the bicycle has, defaults to 7
bell_sound: sound the bell makes when rung
"""
super().__init__(seats, gears)
self.bell_sound = bell_sound
def ring_bell(self):
""" Rings bicycle bell."""
print(self.bell_sound)
class Motorbike(Bike):
"""
Class defining a Motorbike (extending Bike) that can be ridden, have its
gear changed and has a tank that can be filled.
Attributes:
seats: number of seats the bike has
gears: number of gears the bike has
"""
def __init__(self, seats=2, gears=5):
"""
Creates a new Motorbike object.
Args:
seats: number of seats the motorbike has, defaults to 2
gears: number of gears the motorbike has, defaults to 5
"""
super().__init__(seats, gears)
# True means full tank. Private so it can only be changed in
# a controlled manner
self._tank = True
@property
def tank(self):
"""
Purpose of this function is to enable the user to check the tank
status, but is only able to fill/empty the tank with specific methods.
This was not necessary to implement.
"""
return self._tank
def start_ride(self):
"""
Starts a motorbike ride.
Returns:
True if successful.
False if motorbike is already on a ride or tank is empty
"""
# can't ride a motorbike if tank is empty or it is already ridden
if not self._tank or not super().start_ride():
return False
return True
def end_ride(self):
"""
Ends a motorbike ride and empties tank.
Returns:
True if successful.
False if motorbike is not currently ridden.
"""
if not super().end_ride():
return False
self._tank = False # tank is empty after riding
return True
# the following method was not necessary to implement, but we want to be
# able to ride more than once.
def fill_tank(self):
"""
Fills motorbike tank with fuel.
Returns:
True if successful.
False if tank already full.
"""
# can't fill tank if already full
if self._tank:
return False
self._tank = True
return True
|
"""
This module contains the definitions for Bike and its subclasses Bicycle and
Motorbike.
"""
class Bike:
"""
Class defining a bike that can be ridden and have its gear changed.
Attributes:
seats: number of seats the bike has
gears: number of gears the bike has
"""
def __init__(self, seats, gears):
"""
Creates a new Bike object.
Args:
seats: number of seats the bike has
gears: number of gears the bike has
"""
self.seats = seats
self.gears = gears
self._curr_gear = 1
self._riding = False
@property
def curr_gear(self):
"""
Purpose of this function is to enable the user to check the gear
status, but is only able to change it with a specific method.
(was not necessary to implement it this way)
"""
return self._curr_gear
def start_ride(self):
"""
Starts a bike ride.
Returns:
True if successful.
False if bike is already on a ride.
"""
if self._riding:
return False
self._riding = True
return True
def end_ride(self):
"""
Ends a bike ride.
Returns:
True if successful.
False if bike is not currently ridden.
"""
if not self._riding:
return False
self._riding = False
return True
def change_gear(self, new_gear):
"""
Changes bike gear to a new gear.
Args:
new_gear: gear to be changed to
Returns:
True if gear was successfully changed.
Raises:
ValueError if current gear is same as new gear or new gear is <= 0
or not in range of available gears.
"""
if self._curr_gear == new_gear or not 0 < new_gear <= self.gears:
raise value_error('Already in this gear or invalid gear number.')
self._curr_gear = new_gear
return True
class Bicycle(Bike):
"""
Class defining a Bicycle (extending Bike) that can be ridden, have its
gear changed and has a bell that can be rung.
Attributes:
seats: number of seats the bike has
gears: number of gears the bike has
bell_sound: sound the bell makes when rung
"""
def __init__(self, seats=1, gears=7, bell_sound='ring ring'):
"""
Creates a new Bike object.
Args:
seats: number of seats the bicycle has, defaults to 1
gears: number of gears the bicycle has, defaults to 7
bell_sound: sound the bell makes when rung
"""
super().__init__(seats, gears)
self.bell_sound = bell_sound
def ring_bell(self):
""" Rings bicycle bell."""
print(self.bell_sound)
class Motorbike(Bike):
"""
Class defining a Motorbike (extending Bike) that can be ridden, have its
gear changed and has a tank that can be filled.
Attributes:
seats: number of seats the bike has
gears: number of gears the bike has
"""
def __init__(self, seats=2, gears=5):
"""
Creates a new Motorbike object.
Args:
seats: number of seats the motorbike has, defaults to 2
gears: number of gears the motorbike has, defaults to 5
"""
super().__init__(seats, gears)
self._tank = True
@property
def tank(self):
"""
Purpose of this function is to enable the user to check the tank
status, but is only able to fill/empty the tank with specific methods.
This was not necessary to implement.
"""
return self._tank
def start_ride(self):
"""
Starts a motorbike ride.
Returns:
True if successful.
False if motorbike is already on a ride or tank is empty
"""
if not self._tank or not super().start_ride():
return False
return True
def end_ride(self):
"""
Ends a motorbike ride and empties tank.
Returns:
True if successful.
False if motorbike is not currently ridden.
"""
if not super().end_ride():
return False
self._tank = False
return True
def fill_tank(self):
"""
Fills motorbike tank with fuel.
Returns:
True if successful.
False if tank already full.
"""
if self._tank:
return False
self._tank = True
return True
|
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
names = {
'Cisco': 'cwom'
}
mappings = {
'cwom': {
'1.0': '5.8.3.1',
'1.1': '5.9.1',
'1.1.3': '5.9.3',
'1.2.0': '6.0.3',
'1.2.1': '6.0.6',
'1.2.2': '6.0.9',
'1.2.3': '6.0.11.1',
'2.0.0': '6.1.1',
'2.0.1': '6.1.6',
'2.0.2': '6.1.8',
'2.0.3': '6.1.12',
'2.1.0': '6.2.2',
'2.1.1': '6.2.7.1',
'2.1.2': '6.2.10',
'2.2': '6.3.2',
'2.2.1': '6.3.5.0.1',
'2.2.2': '6.3.7',
'2.2.3': '6.3.7.1',
'2.2.4': '6.3.10',
'2.2.5': '6.3.13',
'2.3.0': '6.4.2',
'2.3.1': '6.4.5',
'2.3.2': '6.4.6',
'2.3.3': '6.4.7',
'2.3.4': '6.4.8',
'2.3.5': '6.4.9',
'2.3.6': '6.4.10',
'2.3.7': '6.4.11',
'2.3.8': '6.4.12',
'2.3.9': '6.4.13',
'2.3.10': '6.4.14',
'2.3.11': '6.4.15',
'2.3.12': '6.4.16',
'2.3.13': '6.4.17',
'2.3.14': '6.4.18',
'2.3.15': '6.4.19',
'2.3.16': '6.4.20',
'2.3.17': '6.4.21',
'2.3.18': '6.4.22',
'2.3.19': '6.4.23',
'2.3.20': '6.4.24',
'2.3.21': '6.4.25',
'2.3.22': '6.4.26',
'2.3.23': '6.4.27',
'2.3.24': '6.4.28',
'2.3.25': '6.4.29',
'2.3.26': '6.4.30',
'2.3.27': '6.4.31',
'2.3.28': '6.4.32',
'2.3.29': '6.4.33',
'2.3.30': '6.4.34',
'2.3.31': '6.4.35',
'2.3.32': '6.4.36',
'2.3.33': '6.4.37',
'2.3.34': '6.4.38',
'3.0.1': '8.2.1'
}
}
|
names = {'Cisco': 'cwom'}
mappings = {'cwom': {'1.0': '5.8.3.1', '1.1': '5.9.1', '1.1.3': '5.9.3', '1.2.0': '6.0.3', '1.2.1': '6.0.6', '1.2.2': '6.0.9', '1.2.3': '6.0.11.1', '2.0.0': '6.1.1', '2.0.1': '6.1.6', '2.0.2': '6.1.8', '2.0.3': '6.1.12', '2.1.0': '6.2.2', '2.1.1': '6.2.7.1', '2.1.2': '6.2.10', '2.2': '6.3.2', '2.2.1': '6.3.5.0.1', '2.2.2': '6.3.7', '2.2.3': '6.3.7.1', '2.2.4': '6.3.10', '2.2.5': '6.3.13', '2.3.0': '6.4.2', '2.3.1': '6.4.5', '2.3.2': '6.4.6', '2.3.3': '6.4.7', '2.3.4': '6.4.8', '2.3.5': '6.4.9', '2.3.6': '6.4.10', '2.3.7': '6.4.11', '2.3.8': '6.4.12', '2.3.9': '6.4.13', '2.3.10': '6.4.14', '2.3.11': '6.4.15', '2.3.12': '6.4.16', '2.3.13': '6.4.17', '2.3.14': '6.4.18', '2.3.15': '6.4.19', '2.3.16': '6.4.20', '2.3.17': '6.4.21', '2.3.18': '6.4.22', '2.3.19': '6.4.23', '2.3.20': '6.4.24', '2.3.21': '6.4.25', '2.3.22': '6.4.26', '2.3.23': '6.4.27', '2.3.24': '6.4.28', '2.3.25': '6.4.29', '2.3.26': '6.4.30', '2.3.27': '6.4.31', '2.3.28': '6.4.32', '2.3.29': '6.4.33', '2.3.30': '6.4.34', '2.3.31': '6.4.35', '2.3.32': '6.4.36', '2.3.33': '6.4.37', '2.3.34': '6.4.38', '3.0.1': '8.2.1'}}
|
try:
with open('../../../assets/img_cogwheel_argb.bin','rb') as f:
cogwheel_img_data = f.read()
except:
try:
with open('images/img_cogwheel_rgb565.bin','rb') as f:
cogwheel_img_data = f.read()
except:
print("Could not find binary img_cogwheel file")
# create the cogwheel image data
cogwheel_img_dsc = lv.img_dsc_t(
{
"header": {"always_zero": 0, "w": 100, "h": 100, "cf": lv.img.CF.TRUE_COLOR_ALPHA},
"data": cogwheel_img_data,
"data_size": len(cogwheel_img_data),
}
)
# Create an image using the decoder
img1 = lv.img(lv.scr_act(),None)
lv.img.cache_set_size(2)
img1.align(lv.scr_act(), lv.ALIGN.CENTER, 0, -50)
img1.set_src(cogwheel_img_dsc)
img2 = lv.img(lv.scr_act(), None)
img2.set_src(lv.SYMBOL.OK+"Accept")
img2.align(img1, lv.ALIGN.OUT_BOTTOM_MID, 0, 20)
|
try:
with open('../../../assets/img_cogwheel_argb.bin', 'rb') as f:
cogwheel_img_data = f.read()
except:
try:
with open('images/img_cogwheel_rgb565.bin', 'rb') as f:
cogwheel_img_data = f.read()
except:
print('Could not find binary img_cogwheel file')
cogwheel_img_dsc = lv.img_dsc_t({'header': {'always_zero': 0, 'w': 100, 'h': 100, 'cf': lv.img.CF.TRUE_COLOR_ALPHA}, 'data': cogwheel_img_data, 'data_size': len(cogwheel_img_data)})
img1 = lv.img(lv.scr_act(), None)
lv.img.cache_set_size(2)
img1.align(lv.scr_act(), lv.ALIGN.CENTER, 0, -50)
img1.set_src(cogwheel_img_dsc)
img2 = lv.img(lv.scr_act(), None)
img2.set_src(lv.SYMBOL.OK + 'Accept')
img2.align(img1, lv.ALIGN.OUT_BOTTOM_MID, 0, 20)
|
class Solution(object):
def calculate(self, s):
"""
:type s: str
:rtype: int
"""
if not s:
return 0
s = s.replace(" ", "")
n = len(s)
stack = []
num = 0
sign = '+'
for i in range(n):
if s[i].isdigit():
num = num * 10 + int(s[i])
if not s[i].isdigit() or i == n - 1:
if sign == '-':
stack.append(-num)
elif sign == '+':
stack.append(num)
elif sign == '*':
stack.append(stack.pop() * num)
elif sign == '/':
d = stack.pop()
r = d // num
if r < 0 and d % num != 0:
r += 1
stack.append(r)
sign = s[i]
num = 0
res = 0
for i in stack:
res += i
return res
s = Solution()
print(s.calculate(""))
print(s.calculate("123"))
print(s.calculate("3+2*2"))
print(s.calculate(" 3/2 "))
print(s.calculate("3+5 / 2"))
print(s.calculate("14/3*2"))
print(s.calculate("14-3/2"))
print(s.calculate("10000-1000/10+100*1"))
|
class Solution(object):
def calculate(self, s):
"""
:type s: str
:rtype: int
"""
if not s:
return 0
s = s.replace(' ', '')
n = len(s)
stack = []
num = 0
sign = '+'
for i in range(n):
if s[i].isdigit():
num = num * 10 + int(s[i])
if not s[i].isdigit() or i == n - 1:
if sign == '-':
stack.append(-num)
elif sign == '+':
stack.append(num)
elif sign == '*':
stack.append(stack.pop() * num)
elif sign == '/':
d = stack.pop()
r = d // num
if r < 0 and d % num != 0:
r += 1
stack.append(r)
sign = s[i]
num = 0
res = 0
for i in stack:
res += i
return res
s = solution()
print(s.calculate(''))
print(s.calculate('123'))
print(s.calculate('3+2*2'))
print(s.calculate(' 3/2 '))
print(s.calculate('3+5 / 2'))
print(s.calculate('14/3*2'))
print(s.calculate('14-3/2'))
print(s.calculate('10000-1000/10+100*1'))
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 23 13:11:49 2020
@author: abdulroqeeb
"""
host = "127.0.0.1"
port = 7497
ticktypes = {
66: "Bid",
67: "Ask",
68: "Last",
69: "Bid Size",
70: "Ask Size",
71: "Last Size",
72: "High",
73: "Low",
74: "Volume",
75: "Prior Close",
76: "Prior Open",
88: "Timestamp",
}
account_details_params = [
'AccountCode',
'AccountType',
'AccruedCash',
'AvailableFunds',
'BuyingPower',
'CashBalance',
'NetLiquidation'
]
port_chart_lim = 600 #minutes
states = {1: 'Long',
0: 'Flat',
-1: 'Short'}
|
"""
Created on Sun Feb 23 13:11:49 2020
@author: abdulroqeeb
"""
host = '127.0.0.1'
port = 7497
ticktypes = {66: 'Bid', 67: 'Ask', 68: 'Last', 69: 'Bid Size', 70: 'Ask Size', 71: 'Last Size', 72: 'High', 73: 'Low', 74: 'Volume', 75: 'Prior Close', 76: 'Prior Open', 88: 'Timestamp'}
account_details_params = ['AccountCode', 'AccountType', 'AccruedCash', 'AvailableFunds', 'BuyingPower', 'CashBalance', 'NetLiquidation']
port_chart_lim = 600
states = {1: 'Long', 0: 'Flat', -1: 'Short'}
|
int1 = int(input('informe o inteiro 1 '))
int2 = int(input('informe o inteiro 2 '))
real = float(input('informe o real '))
print('a %2.f' %((int1*2)*(int2/2)))
print('b %2.f' %((int1*3)+(real)))
print('c %2.f' %(real**3))
|
int1 = int(input('informe o inteiro 1 '))
int2 = int(input('informe o inteiro 2 '))
real = float(input('informe o real '))
print('a %2.f' % (int1 * 2 * (int2 / 2)))
print('b %2.f' % (int1 * 3 + real))
print('c %2.f' % real ** 3)
|
data = (
'ruk', # 0x00
'rut', # 0x01
'rup', # 0x02
'ruh', # 0x03
'rweo', # 0x04
'rweog', # 0x05
'rweogg', # 0x06
'rweogs', # 0x07
'rweon', # 0x08
'rweonj', # 0x09
'rweonh', # 0x0a
'rweod', # 0x0b
'rweol', # 0x0c
'rweolg', # 0x0d
'rweolm', # 0x0e
'rweolb', # 0x0f
'rweols', # 0x10
'rweolt', # 0x11
'rweolp', # 0x12
'rweolh', # 0x13
'rweom', # 0x14
'rweob', # 0x15
'rweobs', # 0x16
'rweos', # 0x17
'rweoss', # 0x18
'rweong', # 0x19
'rweoj', # 0x1a
'rweoc', # 0x1b
'rweok', # 0x1c
'rweot', # 0x1d
'rweop', # 0x1e
'rweoh', # 0x1f
'rwe', # 0x20
'rweg', # 0x21
'rwegg', # 0x22
'rwegs', # 0x23
'rwen', # 0x24
'rwenj', # 0x25
'rwenh', # 0x26
'rwed', # 0x27
'rwel', # 0x28
'rwelg', # 0x29
'rwelm', # 0x2a
'rwelb', # 0x2b
'rwels', # 0x2c
'rwelt', # 0x2d
'rwelp', # 0x2e
'rwelh', # 0x2f
'rwem', # 0x30
'rweb', # 0x31
'rwebs', # 0x32
'rwes', # 0x33
'rwess', # 0x34
'rweng', # 0x35
'rwej', # 0x36
'rwec', # 0x37
'rwek', # 0x38
'rwet', # 0x39
'rwep', # 0x3a
'rweh', # 0x3b
'rwi', # 0x3c
'rwig', # 0x3d
'rwigg', # 0x3e
'rwigs', # 0x3f
'rwin', # 0x40
'rwinj', # 0x41
'rwinh', # 0x42
'rwid', # 0x43
'rwil', # 0x44
'rwilg', # 0x45
'rwilm', # 0x46
'rwilb', # 0x47
'rwils', # 0x48
'rwilt', # 0x49
'rwilp', # 0x4a
'rwilh', # 0x4b
'rwim', # 0x4c
'rwib', # 0x4d
'rwibs', # 0x4e
'rwis', # 0x4f
'rwiss', # 0x50
'rwing', # 0x51
'rwij', # 0x52
'rwic', # 0x53
'rwik', # 0x54
'rwit', # 0x55
'rwip', # 0x56
'rwih', # 0x57
'ryu', # 0x58
'ryug', # 0x59
'ryugg', # 0x5a
'ryugs', # 0x5b
'ryun', # 0x5c
'ryunj', # 0x5d
'ryunh', # 0x5e
'ryud', # 0x5f
'ryul', # 0x60
'ryulg', # 0x61
'ryulm', # 0x62
'ryulb', # 0x63
'ryuls', # 0x64
'ryult', # 0x65
'ryulp', # 0x66
'ryulh', # 0x67
'ryum', # 0x68
'ryub', # 0x69
'ryubs', # 0x6a
'ryus', # 0x6b
'ryuss', # 0x6c
'ryung', # 0x6d
'ryuj', # 0x6e
'ryuc', # 0x6f
'ryuk', # 0x70
'ryut', # 0x71
'ryup', # 0x72
'ryuh', # 0x73
'reu', # 0x74
'reug', # 0x75
'reugg', # 0x76
'reugs', # 0x77
'reun', # 0x78
'reunj', # 0x79
'reunh', # 0x7a
'reud', # 0x7b
'reul', # 0x7c
'reulg', # 0x7d
'reulm', # 0x7e
'reulb', # 0x7f
'reuls', # 0x80
'reult', # 0x81
'reulp', # 0x82
'reulh', # 0x83
'reum', # 0x84
'reub', # 0x85
'reubs', # 0x86
'reus', # 0x87
'reuss', # 0x88
'reung', # 0x89
'reuj', # 0x8a
'reuc', # 0x8b
'reuk', # 0x8c
'reut', # 0x8d
'reup', # 0x8e
'reuh', # 0x8f
'ryi', # 0x90
'ryig', # 0x91
'ryigg', # 0x92
'ryigs', # 0x93
'ryin', # 0x94
'ryinj', # 0x95
'ryinh', # 0x96
'ryid', # 0x97
'ryil', # 0x98
'ryilg', # 0x99
'ryilm', # 0x9a
'ryilb', # 0x9b
'ryils', # 0x9c
'ryilt', # 0x9d
'ryilp', # 0x9e
'ryilh', # 0x9f
'ryim', # 0xa0
'ryib', # 0xa1
'ryibs', # 0xa2
'ryis', # 0xa3
'ryiss', # 0xa4
'rying', # 0xa5
'ryij', # 0xa6
'ryic', # 0xa7
'ryik', # 0xa8
'ryit', # 0xa9
'ryip', # 0xaa
'ryih', # 0xab
'ri', # 0xac
'rig', # 0xad
'rigg', # 0xae
'rigs', # 0xaf
'rin', # 0xb0
'rinj', # 0xb1
'rinh', # 0xb2
'rid', # 0xb3
'ril', # 0xb4
'rilg', # 0xb5
'rilm', # 0xb6
'rilb', # 0xb7
'rils', # 0xb8
'rilt', # 0xb9
'rilp', # 0xba
'rilh', # 0xbb
'rim', # 0xbc
'rib', # 0xbd
'ribs', # 0xbe
'ris', # 0xbf
'riss', # 0xc0
'ring', # 0xc1
'rij', # 0xc2
'ric', # 0xc3
'rik', # 0xc4
'rit', # 0xc5
'rip', # 0xc6
'rih', # 0xc7
'ma', # 0xc8
'mag', # 0xc9
'magg', # 0xca
'mags', # 0xcb
'man', # 0xcc
'manj', # 0xcd
'manh', # 0xce
'mad', # 0xcf
'mal', # 0xd0
'malg', # 0xd1
'malm', # 0xd2
'malb', # 0xd3
'mals', # 0xd4
'malt', # 0xd5
'malp', # 0xd6
'malh', # 0xd7
'mam', # 0xd8
'mab', # 0xd9
'mabs', # 0xda
'mas', # 0xdb
'mass', # 0xdc
'mang', # 0xdd
'maj', # 0xde
'mac', # 0xdf
'mak', # 0xe0
'mat', # 0xe1
'map', # 0xe2
'mah', # 0xe3
'mae', # 0xe4
'maeg', # 0xe5
'maegg', # 0xe6
'maegs', # 0xe7
'maen', # 0xe8
'maenj', # 0xe9
'maenh', # 0xea
'maed', # 0xeb
'mael', # 0xec
'maelg', # 0xed
'maelm', # 0xee
'maelb', # 0xef
'maels', # 0xf0
'maelt', # 0xf1
'maelp', # 0xf2
'maelh', # 0xf3
'maem', # 0xf4
'maeb', # 0xf5
'maebs', # 0xf6
'maes', # 0xf7
'maess', # 0xf8
'maeng', # 0xf9
'maej', # 0xfa
'maec', # 0xfb
'maek', # 0xfc
'maet', # 0xfd
'maep', # 0xfe
'maeh', # 0xff
)
|
data = ('ruk', 'rut', 'rup', 'ruh', 'rweo', 'rweog', 'rweogg', 'rweogs', 'rweon', 'rweonj', 'rweonh', 'rweod', 'rweol', 'rweolg', 'rweolm', 'rweolb', 'rweols', 'rweolt', 'rweolp', 'rweolh', 'rweom', 'rweob', 'rweobs', 'rweos', 'rweoss', 'rweong', 'rweoj', 'rweoc', 'rweok', 'rweot', 'rweop', 'rweoh', 'rwe', 'rweg', 'rwegg', 'rwegs', 'rwen', 'rwenj', 'rwenh', 'rwed', 'rwel', 'rwelg', 'rwelm', 'rwelb', 'rwels', 'rwelt', 'rwelp', 'rwelh', 'rwem', 'rweb', 'rwebs', 'rwes', 'rwess', 'rweng', 'rwej', 'rwec', 'rwek', 'rwet', 'rwep', 'rweh', 'rwi', 'rwig', 'rwigg', 'rwigs', 'rwin', 'rwinj', 'rwinh', 'rwid', 'rwil', 'rwilg', 'rwilm', 'rwilb', 'rwils', 'rwilt', 'rwilp', 'rwilh', 'rwim', 'rwib', 'rwibs', 'rwis', 'rwiss', 'rwing', 'rwij', 'rwic', 'rwik', 'rwit', 'rwip', 'rwih', 'ryu', 'ryug', 'ryugg', 'ryugs', 'ryun', 'ryunj', 'ryunh', 'ryud', 'ryul', 'ryulg', 'ryulm', 'ryulb', 'ryuls', 'ryult', 'ryulp', 'ryulh', 'ryum', 'ryub', 'ryubs', 'ryus', 'ryuss', 'ryung', 'ryuj', 'ryuc', 'ryuk', 'ryut', 'ryup', 'ryuh', 'reu', 'reug', 'reugg', 'reugs', 'reun', 'reunj', 'reunh', 'reud', 'reul', 'reulg', 'reulm', 'reulb', 'reuls', 'reult', 'reulp', 'reulh', 'reum', 'reub', 'reubs', 'reus', 'reuss', 'reung', 'reuj', 'reuc', 'reuk', 'reut', 'reup', 'reuh', 'ryi', 'ryig', 'ryigg', 'ryigs', 'ryin', 'ryinj', 'ryinh', 'ryid', 'ryil', 'ryilg', 'ryilm', 'ryilb', 'ryils', 'ryilt', 'ryilp', 'ryilh', 'ryim', 'ryib', 'ryibs', 'ryis', 'ryiss', 'rying', 'ryij', 'ryic', 'ryik', 'ryit', 'ryip', 'ryih', 'ri', 'rig', 'rigg', 'rigs', 'rin', 'rinj', 'rinh', 'rid', 'ril', 'rilg', 'rilm', 'rilb', 'rils', 'rilt', 'rilp', 'rilh', 'rim', 'rib', 'ribs', 'ris', 'riss', 'ring', 'rij', 'ric', 'rik', 'rit', 'rip', 'rih', 'ma', 'mag', 'magg', 'mags', 'man', 'manj', 'manh', 'mad', 'mal', 'malg', 'malm', 'malb', 'mals', 'malt', 'malp', 'malh', 'mam', 'mab', 'mabs', 'mas', 'mass', 'mang', 'maj', 'mac', 'mak', 'mat', 'map', 'mah', 'mae', 'maeg', 'maegg', 'maegs', 'maen', 'maenj', 'maenh', 'maed', 'mael', 'maelg', 'maelm', 'maelb', 'maels', 'maelt', 'maelp', 'maelh', 'maem', 'maeb', 'maebs', 'maes', 'maess', 'maeng', 'maej', 'maec', 'maek', 'maet', 'maep', 'maeh')
|
class PHPWriter:
def __init__(self, constants):
self.constants = constants
def write(self, out):
out.write("<?php\n")
out.write("/* This file was generated by generate_constants. */\n\n")
for enum in self.constants.enum_values.values():
out.write("\n")
for name, value in enum.items():
out.write("define('{}', {});\n".format(name, value))
for name, value in self.constants.constant_values.items():
out.write("define('{}', {});\n".format(name, value))
|
class Phpwriter:
def __init__(self, constants):
self.constants = constants
def write(self, out):
out.write('<?php\n')
out.write('/* This file was generated by generate_constants. */\n\n')
for enum in self.constants.enum_values.values():
out.write('\n')
for (name, value) in enum.items():
out.write("define('{}', {});\n".format(name, value))
for (name, value) in self.constants.constant_values.items():
out.write("define('{}', {});\n".format(name, value))
|
__version__ = "170130"
__authors__ = "Ryo KOBAYASHI"
__email__ = "kobayashi.ryo@nitech.ac.jp"
class Machine():
"""
Parent class of any other machine classes.
"""
QUEUES = {
'batch': {'num_nodes': 12, 'default_sec': 86400, 'limit_sec': 604800},
'default':{'num_nodes': 12, 'default_sec': 86400, 'limit_sec': 604800},
}
SCHEDULER = 'pbs'
def __init__(self):
pass
class FUJITSU_FX100(Machine):
"""
Class for the specific super computer at Nagoya University, Fujitsu FX100.
"""
# Resource groups and their nums of nodes and time limits
QUEUES = {
'fx-debug': {'num_nodes': 32, 'default_sec': 3600, 'limit_sec': 3600},
'fx-small': {'num_nodes': 16, 'default_sec':86400, 'limit_sec':604800},
'fx-middle':{'num_nodes': 96, 'default_sec':86400, 'limit_sec':259200},
'fx-large': {'num_nodes':192, 'default_sec':86400, 'limit_sec':259200},
'fx-xlarge':{'num_nodes':864, 'default_sec':86400, 'limit_sec': 86400},
}
SCHEDULER = 'fujitsu'
class MIKE(Machine):
"""
Class for the specific machine in Ogata Lab. at NITech.ac.jp
"""
SCHEDULER = 'pbs'
#...Currently it is hard to specify nodes to use, so this queues are
#...like the greatest commond divider
QUEUES = {
'batch': {'num_nodes': 12, 'default_sec': 86400, 'limit_sec': 604800},
'default':{'num_nodes': 12, 'default_sec': 86400, 'limit_sec': 604800},
}
|
__version__ = '170130'
__authors__ = 'Ryo KOBAYASHI'
__email__ = 'kobayashi.ryo@nitech.ac.jp'
class Machine:
"""
Parent class of any other machine classes.
"""
queues = {'batch': {'num_nodes': 12, 'default_sec': 86400, 'limit_sec': 604800}, 'default': {'num_nodes': 12, 'default_sec': 86400, 'limit_sec': 604800}}
scheduler = 'pbs'
def __init__(self):
pass
class Fujitsu_Fx100(Machine):
"""
Class for the specific super computer at Nagoya University, Fujitsu FX100.
"""
queues = {'fx-debug': {'num_nodes': 32, 'default_sec': 3600, 'limit_sec': 3600}, 'fx-small': {'num_nodes': 16, 'default_sec': 86400, 'limit_sec': 604800}, 'fx-middle': {'num_nodes': 96, 'default_sec': 86400, 'limit_sec': 259200}, 'fx-large': {'num_nodes': 192, 'default_sec': 86400, 'limit_sec': 259200}, 'fx-xlarge': {'num_nodes': 864, 'default_sec': 86400, 'limit_sec': 86400}}
scheduler = 'fujitsu'
class Mike(Machine):
"""
Class for the specific machine in Ogata Lab. at NITech.ac.jp
"""
scheduler = 'pbs'
queues = {'batch': {'num_nodes': 12, 'default_sec': 86400, 'limit_sec': 604800}, 'default': {'num_nodes': 12, 'default_sec': 86400, 'limit_sec': 604800}}
|
Amount = float
BenefitName = str
Email = str
Donor = Email
PaymentId = str
def isnotemptyinstance(value, type):
if not isinstance(value, type):
return False # None returns false
if isinstance(value, str):
return (len(value.strip()) != 0)
elif isinstance(value, int):
return (value != 0)
elif isinstance(value, float):
return (value != 0.0)
else:
raise NotImplementedError
|
amount = float
benefit_name = str
email = str
donor = Email
payment_id = str
def isnotemptyinstance(value, type):
if not isinstance(value, type):
return False
if isinstance(value, str):
return len(value.strip()) != 0
elif isinstance(value, int):
return value != 0
elif isinstance(value, float):
return value != 0.0
else:
raise NotImplementedError
|
# model settings
model = dict(
type='ImageClassifier',
backbone=dict(
type='SVT',
arch='base',
in_channels=3,
out_indices=(3, ),
qkv_bias=True,
norm_cfg=dict(type='LN'),
norm_after_stage=[False, False, False, True],
drop_rate=0.0,
attn_drop_rate=0.,
drop_path_rate=0.3),
neck=dict(type='GlobalAveragePooling'),
head=dict(
type='LinearClsHead',
num_classes=1000,
in_channels=768,
loss=dict(
type='LabelSmoothLoss', label_smooth_val=0.1, mode='original'),
cal_acc=False),
init_cfg=[
dict(type='TruncNormal', layer='Linear', std=0.02, bias=0.),
dict(type='Constant', layer='LayerNorm', val=1., bias=0.)
],
train_cfg=dict(augments=[
dict(type='BatchMixup', alpha=0.8, num_classes=1000, prob=0.5),
dict(type='BatchCutMix', alpha=1.0, num_classes=1000, prob=0.5)
]))
|
model = dict(type='ImageClassifier', backbone=dict(type='SVT', arch='base', in_channels=3, out_indices=(3,), qkv_bias=True, norm_cfg=dict(type='LN'), norm_after_stage=[False, False, False, True], drop_rate=0.0, attn_drop_rate=0.0, drop_path_rate=0.3), neck=dict(type='GlobalAveragePooling'), head=dict(type='LinearClsHead', num_classes=1000, in_channels=768, loss=dict(type='LabelSmoothLoss', label_smooth_val=0.1, mode='original'), cal_acc=False), init_cfg=[dict(type='TruncNormal', layer='Linear', std=0.02, bias=0.0), dict(type='Constant', layer='LayerNorm', val=1.0, bias=0.0)], train_cfg=dict(augments=[dict(type='BatchMixup', alpha=0.8, num_classes=1000, prob=0.5), dict(type='BatchCutMix', alpha=1.0, num_classes=1000, prob=0.5)]))
|
nome = input('Digite seu nome: ')
def saudar(x):
print(f'Bem-vindo, {x}!')
saudar(nome)
|
nome = input('Digite seu nome: ')
def saudar(x):
print(f'Bem-vindo, {x}!')
saudar(nome)
|
"""Anagram utilities"""
def find_anagrams(word: str, candidates: list) -> list:
"""Detect anagrams on a list against a reference word
Args:
word: the reference word
candidates: the list of words to be compared
Returns:
A new list with the anagrams found.
"""
low_word = sorted(word.lower())
return [candidate for candidate in candidates if is_anagram(low_word, candidate)]
def is_anagram(low_sort_word: str, candidate: str) -> bool:
"""Determine whether two words are anagrams of each other.
Args:
low_sort_words: the original word, sorted and lowered.
candidate: the word to be compared
Returns:
A boolean True if the two words have the same letters in different order."""
return sorted(candidate.lower()) == low_sort_word and candidate.lower() != low_sort_word
|
"""Anagram utilities"""
def find_anagrams(word: str, candidates: list) -> list:
"""Detect anagrams on a list against a reference word
Args:
word: the reference word
candidates: the list of words to be compared
Returns:
A new list with the anagrams found.
"""
low_word = sorted(word.lower())
return [candidate for candidate in candidates if is_anagram(low_word, candidate)]
def is_anagram(low_sort_word: str, candidate: str) -> bool:
"""Determine whether two words are anagrams of each other.
Args:
low_sort_words: the original word, sorted and lowered.
candidate: the word to be compared
Returns:
A boolean True if the two words have the same letters in different order."""
return sorted(candidate.lower()) == low_sort_word and candidate.lower() != low_sort_word
|
class Solution:
def sortedSquares(self, nums: List[int]) -> List[int]:
sq_nums = []
for num in nums:
sq_nums.append(num ** 2)
sq_nums.sort()
return sq_nums
|
class Solution:
def sorted_squares(self, nums: List[int]) -> List[int]:
sq_nums = []
for num in nums:
sq_nums.append(num ** 2)
sq_nums.sort()
return sq_nums
|
class Stack(object):
def __init__(self):
self.items = []
self.min_value = None
def push(self, item):
if not self.min_value or self.min_value > item:
self.min_value = item
self.items.append(item)
def pop(self):
self.items.pop()
def get_min_value(self):
return self.min_value
stack = Stack()
stack.push(4)
stack.push(6)
stack.push(2)
print(stack.get_min_value())
stack.push(1)
print(stack.get_min_value())
|
class Stack(object):
def __init__(self):
self.items = []
self.min_value = None
def push(self, item):
if not self.min_value or self.min_value > item:
self.min_value = item
self.items.append(item)
def pop(self):
self.items.pop()
def get_min_value(self):
return self.min_value
stack = stack()
stack.push(4)
stack.push(6)
stack.push(2)
print(stack.get_min_value())
stack.push(1)
print(stack.get_min_value())
|
_base_ = [
'../../_base_/models/resnet50.py',
'../../_base_/datasets/imagenet.py',
'../../_base_/schedules/sgd_steplr-100e.py',
'../../_base_/default_runtime.py',
]
# model settings
model = dict(backbone=dict(norm_cfg=dict(type='SyncBN')))
# dataset settings
data = dict(
imgs_per_gpu=64, # total 64x4=256
train=dict(
data_source=dict(ann_file='data/imagenet/meta/train_1percent.txt')))
# optimizer
optimizer = dict(
type='SGD',
lr=0.1,
momentum=0.9,
weight_decay=5e-4,
paramwise_options={'\\Ahead.': dict(lr_mult=1)})
# learning policy
lr_config = dict(policy='step', step=[12, 16], gamma=0.2)
# runtime settings
runner = dict(type='EpochBasedRunner', max_epochs=20)
checkpoint_config = dict(interval=10)
log_config = dict(
interval=10,
hooks=[dict(type='TextLoggerHook'),
dict(type='TensorboardLoggerHook')])
|
_base_ = ['../../_base_/models/resnet50.py', '../../_base_/datasets/imagenet.py', '../../_base_/schedules/sgd_steplr-100e.py', '../../_base_/default_runtime.py']
model = dict(backbone=dict(norm_cfg=dict(type='SyncBN')))
data = dict(imgs_per_gpu=64, train=dict(data_source=dict(ann_file='data/imagenet/meta/train_1percent.txt')))
optimizer = dict(type='SGD', lr=0.1, momentum=0.9, weight_decay=0.0005, paramwise_options={'\\Ahead.': dict(lr_mult=1)})
lr_config = dict(policy='step', step=[12, 16], gamma=0.2)
runner = dict(type='EpochBasedRunner', max_epochs=20)
checkpoint_config = dict(interval=10)
log_config = dict(interval=10, hooks=[dict(type='TextLoggerHook'), dict(type='TensorboardLoggerHook')])
|
def test_add_to_basket(browser):
link = 'http://selenium1py.pythonanywhere.com/catalogue/coders-at-work_207/'
browser.get(link)
assert browser.find_element_by_class_name('btn-add-to-basket').is_displayed(), f'Basket button not found'
|
def test_add_to_basket(browser):
link = 'http://selenium1py.pythonanywhere.com/catalogue/coders-at-work_207/'
browser.get(link)
assert browser.find_element_by_class_name('btn-add-to-basket').is_displayed(), f'Basket button not found'
|
class TaskAnswer:
# list of tuple: (vertice_source, vertice_destination, moved_value)
_steps = []
def get_steps(self) -> list:
return self._steps
def add_step(self, source: int, destination: int, value: float):
step = (source, destination, value)
self._steps.append(step)
def print(self):
for step in self._steps:
(source, destination, value) = step
print("from", source, "to", destination, "move", value)
|
class Taskanswer:
_steps = []
def get_steps(self) -> list:
return self._steps
def add_step(self, source: int, destination: int, value: float):
step = (source, destination, value)
self._steps.append(step)
def print(self):
for step in self._steps:
(source, destination, value) = step
print('from', source, 'to', destination, 'move', value)
|
class Solution:
def getDescentPeriods(self, prices: List[int]) -> int:
curr = result = 1
for i in range(1, len(prices)):
if prices[i] + 1 == prices[i-1]:
curr += 1
else:
curr = 1
result += curr
return result
|
class Solution:
def get_descent_periods(self, prices: List[int]) -> int:
curr = result = 1
for i in range(1, len(prices)):
if prices[i] + 1 == prices[i - 1]:
curr += 1
else:
curr = 1
result += curr
return result
|
print("####################################################")
print("#FILENAME:\t\ta1p1.py\t\t\t #")
print("#ASSIGNMENT:\t\tHomework Assignment 1 Pt. 1#")
print("#COURSE/SECTION:\tCIS 3389.251\t\t #")
print("#DUE DATE:\t\tWednesday, 12.February 2020#")
print("####################################################\n\n\n")
cont = 'y'
while cont.lower() == 'y' or cont.lower() == 'yes':
total = 0
avg = 0
number1 = float(input("First number:\t"))
number2 = float(input("Second number:\t"))
number3 = float(input("Third number:\t"))
total = number1 + number2 + number3
avg = total/3
if number1 >= number2 and number1 >= number3:
first_largest = number1
if number2 >= number3:
second_largest = number2
third_largest = number3
else:
second_largest = number3
third_largest = number2
elif number1 >= number2 and number1 < number3:
first_largest = number3
second_largest = number1
third_largest = number2
elif number1 < number2 and number1 < number3:
third_largest = number1;
if number2 >= number3:
first_largest = number2
second_largest = number3
else:
first_largest = number3
second_largest = number2
elif number1 < number2 and number1 >= number3:
first_largest = number2
second_largest = number1
third_largest = number3
print("\n\nSecond largest number entered:\t", second_largest)
print("Average:\t\t\t", avg, "\n\n")
cont = input("Would you like to continue? ")
|
print('####################################################')
print('#FILENAME:\t\ta1p1.py\t\t\t #')
print('#ASSIGNMENT:\t\tHomework Assignment 1 Pt. 1#')
print('#COURSE/SECTION:\tCIS 3389.251\t\t #')
print('#DUE DATE:\t\tWednesday, 12.February 2020#')
print('####################################################\n\n\n')
cont = 'y'
while cont.lower() == 'y' or cont.lower() == 'yes':
total = 0
avg = 0
number1 = float(input('First number:\t'))
number2 = float(input('Second number:\t'))
number3 = float(input('Third number:\t'))
total = number1 + number2 + number3
avg = total / 3
if number1 >= number2 and number1 >= number3:
first_largest = number1
if number2 >= number3:
second_largest = number2
third_largest = number3
else:
second_largest = number3
third_largest = number2
elif number1 >= number2 and number1 < number3:
first_largest = number3
second_largest = number1
third_largest = number2
elif number1 < number2 and number1 < number3:
third_largest = number1
if number2 >= number3:
first_largest = number2
second_largest = number3
else:
first_largest = number3
second_largest = number2
elif number1 < number2 and number1 >= number3:
first_largest = number2
second_largest = number1
third_largest = number3
print('\n\nSecond largest number entered:\t', second_largest)
print('Average:\t\t\t', avg, '\n\n')
cont = input('Would you like to continue? ')
|
#!/usr/bin/env python
# encoding: utf-8
class Solution(object):
def countBits(self, num):
"""
:type num: int
:rtype: List[int]
"""
dp = [0]*(num+1)
for i in xrange(num+1):
dp[i] = dp[i/2] if i%2 == 0 else dp[i/2]+1
return dp
|
class Solution(object):
def count_bits(self, num):
"""
:type num: int
:rtype: List[int]
"""
dp = [0] * (num + 1)
for i in xrange(num + 1):
dp[i] = dp[i / 2] if i % 2 == 0 else dp[i / 2] + 1
return dp
|
#!/usr/local/bin/python3
# Python Challenge - 1
# http://www.pythonchallenge.com/pc/def/map.html
# Keyword: ocr
def main():
'''
Hint:
K -> M
O -> Q
E -> G
Everybody thinks twice before solving this.
'''
cipher_text = ('g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcp'
'q ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr\'q '
'ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq '
'pcamkkclbcb. lmu ynnjw ml rfc spj.')
plain_text = caesar_cipher(cipher_text, 2)
print('PLAIN TEXT: {}'.format(plain_text))
# Apply cipher to /map.html (get /ocr.html)
print('NEW ADDRESS PATH')
print(caesar_cipher('/map', 2))
# Challenge 23
# chall_23 = 'va gur snpr bs jung?'
# print(caesar_cipher(chall_23, 13))
# for i in range(26):
# plain_23 = caesar_cipher(chall_23, i)
# print('i: {}'.format(i))
# print('PLAIN TEXT: {}'.format(plain_23))
# Rot13: in the face of what?
def caesar_cipher(cipher_text, n):
'''
Input: string of cipher_text, n is int for alphabet rotation
Output: string of plain text, applying simple n rotation
'''
# Convert cipher_text to lowercase
cipher_lower = cipher_text.lower()
# Create cipher key dictionary
codex = {}
base = ord('a')
for i in range(26):
# Assumes a is 0, z is 25
letter = chr(base + i)
rotated_letter = chr(((i + n) % 26) + base)
codex[letter] = rotated_letter
# Build plain_text string using the codex mapping
plain_text = ''
for c in cipher_lower:
plain_text += codex.get(c, c)
return plain_text
if __name__ == '__main__':
main()
|
def main():
"""
Hint:
K -> M
O -> Q
E -> G
Everybody thinks twice before solving this.
"""
cipher_text = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj."
plain_text = caesar_cipher(cipher_text, 2)
print('PLAIN TEXT: {}'.format(plain_text))
print('NEW ADDRESS PATH')
print(caesar_cipher('/map', 2))
def caesar_cipher(cipher_text, n):
"""
Input: string of cipher_text, n is int for alphabet rotation
Output: string of plain text, applying simple n rotation
"""
cipher_lower = cipher_text.lower()
codex = {}
base = ord('a')
for i in range(26):
letter = chr(base + i)
rotated_letter = chr((i + n) % 26 + base)
codex[letter] = rotated_letter
plain_text = ''
for c in cipher_lower:
plain_text += codex.get(c, c)
return plain_text
if __name__ == '__main__':
main()
|
def check_next_num(inp, j):
for i in range(j, len(inp)):
elm = inp[i]
if len(inp) > i+1:
if inp[i+1] == (elm+1):
check_next_num(inp, i+1)
else:
if j == 0:
return i
return i
else:
return len(inp)-1
def solution(inp):
"""
1. Sort inp
2. Check to see if next in inp slist is the next value
"""
inp.sort()
ranges = []
res = []
for i in range(len(inp)):
l = check_next_num(inp, i)
ranges.append([i, l])
print([i, l])
seen = []
for r in ranges:
si = r[0]
ei = r[1]
sv = inp[si]
ev = inp[ei]
if ei not in seen:
if ev == sv:
res.append(str(ev))
seen.append(ei)
if (ev - sv) >= 2:
s = str(sv)+'-'+str(ev)
res.append(s)
seen.append(ei)
elif (ev-sv) == 1:
res.append(str(sv))
return (",".join(res))
print(ranges)
#Indexs 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
solution([-6,-3,-2,-1,0,1,3,4,5,7,8, 9, 10,11,14,15,17,18,19,20])
"""
[0,0], [1,5], [6,13], [14,15], [17, 19]
[[0, 0], [1, 5], [2, 5], [3, 5], [4, 5], [5, 5], [6, 8], [7, 8], [8, 8], [9, 13], [10, 13], [11, 13], [12, 13], [13, 13], [14, 15], [15, 15], [16, 19]
-6,-3-1,3-5,7-11,14,15,17-20
-6,-3-1,3-5,7-11,14,15,17-20
-6,-3-1,3-5,7-11,14,15,17-20
"""
#Indexes 0 1 2 3 4 5 6 7 8 9
# solution([-3,-2,-1,2,10,15,16,18,19,20])
"""
[0, 2], [3, 3], [4, 4], [5, 5], [6, 6], [7, 9]
[[0, 2], [3, 3], [4, 4], [5, 6], [6, 6], [7, 9]]
[[0, 0], [1, 2], [2, 2], [3, 3], [4, 4], [5, 6], [6, 6], [7, 9], [8, 9], [9, 9]]
-3--1,2,10,15,16,18-20
-3--1,2,10,15,16,18-20
-3,-2,-1,2,10,15,16,18-20
"""
|
def check_next_num(inp, j):
for i in range(j, len(inp)):
elm = inp[i]
if len(inp) > i + 1:
if inp[i + 1] == elm + 1:
check_next_num(inp, i + 1)
else:
if j == 0:
return i
return i
else:
return len(inp) - 1
def solution(inp):
"""
1. Sort inp
2. Check to see if next in inp slist is the next value
"""
inp.sort()
ranges = []
res = []
for i in range(len(inp)):
l = check_next_num(inp, i)
ranges.append([i, l])
print([i, l])
seen = []
for r in ranges:
si = r[0]
ei = r[1]
sv = inp[si]
ev = inp[ei]
if ei not in seen:
if ev == sv:
res.append(str(ev))
seen.append(ei)
if ev - sv >= 2:
s = str(sv) + '-' + str(ev)
res.append(s)
seen.append(ei)
elif ev - sv == 1:
res.append(str(sv))
return ','.join(res)
print(ranges)
solution([-6, -3, -2, -1, 0, 1, 3, 4, 5, 7, 8, 9, 10, 11, 14, 15, 17, 18, 19, 20])
'\n\n[0,0], [1,5], [6,13], [14,15], [17, 19]\n\n[[0, 0], [1, 5], [2, 5], [3, 5], [4, 5], [5, 5], [6, 8], [7, 8], [8, 8], [9, 13], [10, 13], [11, 13], [12, 13], [13, 13], [14, 15], [15, 15], [16, 19]\n\n-6,-3-1,3-5,7-11,14,15,17-20\n-6,-3-1,3-5,7-11,14,15,17-20\n-6,-3-1,3-5,7-11,14,15,17-20\n'
'\n\n\n [0, 2], [3, 3], [4, 4], [5, 5], [6, 6], [7, 9] \n[[0, 2], [3, 3], [4, 4], [5, 6], [6, 6], [7, 9]]\n[[0, 0], [1, 2], [2, 2], [3, 3], [4, 4], [5, 6], [6, 6], [7, 9], [8, 9], [9, 9]]\n\n-3--1,2,10,15,16,18-20\n\n-3--1,2,10,15,16,18-20\n-3,-2,-1,2,10,15,16,18-20\n\n'
|
def rotate(str, d, mag):
if (d=="L"):
return str[mag:] + str[0:mag]
elif (d=="R"):
return str[len(str)-mag:] + str[0: len(str)-mag]
def checkAnagram(str1, str2):
if(sorted(str1)==sorted(str2)):
return True
else:
return False
def subString(s, n, ans):
for i in range(n):
for leng in range(i+1,n+1):
sub = s[i:leng]
if(len(sub)==len(ans)):
if(checkAnagram(sub,ans)):
return True
return False
str = input().split(" ")
str1 = str[0]
str2 = str1
q = int(str[1])
ans = ""
d = list()
mag = list()
str3 = str[2:]
for i in range(len(str3)):
if (i%2==0):
d.append(str3[i])
else:
mag.append(int(str3[i]))
#str1 = input()
#str2 = str1
#q = int(input())
#d = list()
#mag = list()
#ans = ""
#for i in range(q):
# d.append(input())
# mag.append(int(input()))
for i in range(q):
str2 = rotate(str2,d[i],mag[i])
ans = ans + str2[0]
if(subString(str1,len(str1),ans)):
print("YES")
else:
print("NO")
|
def rotate(str, d, mag):
if d == 'L':
return str[mag:] + str[0:mag]
elif d == 'R':
return str[len(str) - mag:] + str[0:len(str) - mag]
def check_anagram(str1, str2):
if sorted(str1) == sorted(str2):
return True
else:
return False
def sub_string(s, n, ans):
for i in range(n):
for leng in range(i + 1, n + 1):
sub = s[i:leng]
if len(sub) == len(ans):
if check_anagram(sub, ans):
return True
return False
str = input().split(' ')
str1 = str[0]
str2 = str1
q = int(str[1])
ans = ''
d = list()
mag = list()
str3 = str[2:]
for i in range(len(str3)):
if i % 2 == 0:
d.append(str3[i])
else:
mag.append(int(str3[i]))
for i in range(q):
str2 = rotate(str2, d[i], mag[i])
ans = ans + str2[0]
if sub_string(str1, len(str1), ans):
print('YES')
else:
print('NO')
|
"""
You are asked to ensure that the first and last names of people begin with a capital letter in their passports. For example, alison heck should be capitalised correctly as Alison Heck.
Given a full name, your task is to capitalize the name appropriately.
Input Format
A single line of input containing the full name, .
Constraints
The string consists of alphanumeric characters and spaces.
Note: in a word only the first character is capitalized. Example 12abc when capitalized remains 12abc.
Output Format
Print the capitalized string, .
Sample Input
chris alan
Sample Output
Chris Alan
"""
# Complete the solve function below.
def solve(s):
assert 0 < len(s) < 1000
a_string = s.split(' ')
s = ' '.join((word.capitalize() for word in a_string))
#
# for x in s[:].split():
# s = s.replace(x, x.capitalize())
return s
if __name__ == '__main__':
# s = input()
s = 'vyshnav mt cv df'
result = solve(s)
print(result)
|
"""
You are asked to ensure that the first and last names of people begin with a capital letter in their passports. For example, alison heck should be capitalised correctly as Alison Heck.
Given a full name, your task is to capitalize the name appropriately.
Input Format
A single line of input containing the full name, .
Constraints
The string consists of alphanumeric characters and spaces.
Note: in a word only the first character is capitalized. Example 12abc when capitalized remains 12abc.
Output Format
Print the capitalized string, .
Sample Input
chris alan
Sample Output
Chris Alan
"""
def solve(s):
assert 0 < len(s) < 1000
a_string = s.split(' ')
s = ' '.join((word.capitalize() for word in a_string))
return s
if __name__ == '__main__':
s = 'vyshnav mt cv df'
result = solve(s)
print(result)
|
number = int(input("Pick a number? "))
for i in range(5):
number = number + number
print(number)
|
number = int(input('Pick a number? '))
for i in range(5):
number = number + number
print(number)
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
MAXIMUM_SECRET_LENGTH = 20
MAXIMUM_CONTAINER_APP_NAME_LENGTH = 40
SHORT_POLLING_INTERVAL_SECS = 3
LONG_POLLING_INTERVAL_SECS = 10
LOG_ANALYTICS_RP = "Microsoft.OperationalInsights"
CONTAINER_APPS_RP = "Microsoft.App"
MAX_ENV_PER_LOCATION = 2
MICROSOFT_SECRET_SETTING_NAME = "microsoft-provider-authentication-secret"
FACEBOOK_SECRET_SETTING_NAME = "facebook-provider-authentication-secret"
GITHUB_SECRET_SETTING_NAME = "github-provider-authentication-secret"
GOOGLE_SECRET_SETTING_NAME = "google-provider-authentication-secret"
MSA_SECRET_SETTING_NAME = "msa-provider-authentication-secret"
TWITTER_SECRET_SETTING_NAME = "twitter-provider-authentication-secret"
APPLE_SECRET_SETTING_NAME = "apple-provider-authentication-secret"
UNAUTHENTICATED_CLIENT_ACTION = ['RedirectToLoginPage', 'AllowAnonymous', 'RejectWith401', 'RejectWith404']
FORWARD_PROXY_CONVENTION = ['NoProxy', 'Standard', 'Custom']
CHECK_CERTIFICATE_NAME_AVAILABILITY_TYPE = "Microsoft.App/managedEnvironments/certificates"
|
maximum_secret_length = 20
maximum_container_app_name_length = 40
short_polling_interval_secs = 3
long_polling_interval_secs = 10
log_analytics_rp = 'Microsoft.OperationalInsights'
container_apps_rp = 'Microsoft.App'
max_env_per_location = 2
microsoft_secret_setting_name = 'microsoft-provider-authentication-secret'
facebook_secret_setting_name = 'facebook-provider-authentication-secret'
github_secret_setting_name = 'github-provider-authentication-secret'
google_secret_setting_name = 'google-provider-authentication-secret'
msa_secret_setting_name = 'msa-provider-authentication-secret'
twitter_secret_setting_name = 'twitter-provider-authentication-secret'
apple_secret_setting_name = 'apple-provider-authentication-secret'
unauthenticated_client_action = ['RedirectToLoginPage', 'AllowAnonymous', 'RejectWith401', 'RejectWith404']
forward_proxy_convention = ['NoProxy', 'Standard', 'Custom']
check_certificate_name_availability_type = 'Microsoft.App/managedEnvironments/certificates'
|
# Author=====>>>Nipun Garg<<<=====
# Problem Statement - Given number of jobs and number of applicants
# And for each applicant given that wether each applicant is
# eligible to get the job or not in the form of matrix
# Return 1 if a person can get the job
def dfs(graph, applicant, visited, result,nApplicants,nJobs):
for i in range(0,nJobs):
if(graph[applicant][i]==1 and (not visited[i])):
visited[i]=1
if( result[i]<0 or dfs(graph, result[i], visited, result, nApplicants, nJobs)):
result[i]=applicant
return 1
return 0
#Return maximum people that can get the job
def bipartite(graph,nApplicants,nJobs):
result = []
for i in range(0,nJobs):
result.append(-1)
retval=0
for i in range(nApplicants):
visited = []
for j in range(nApplicants):
visited.append(0)
if(dfs(graph, i, visited, result, nApplicants, nJobs)):
retval+=1
return retval
#Main function
if __name__ == '__main__':
# Total number of applicant and total number of jobs
nApplicants = input("Enter the number of applicants : ")
nJobs = input("Enter the number of jobs : ")
graph = []
#Taking input if a user can have a job then its value for job is 1
for i in range(nApplicants):
print("Enter the status(1/0) for applicant - "+str(i+1)+" for "+str(nJobs)+" Jobs!")
temp=[]
for j in range(nJobs):
temp.append(input("For job - "+str(j+1)+" : "))
graph.append(temp)
# print(graph)
print("Maximum applicants that can have job is : "+str(bipartite(graph, nApplicants, nJobs)))
|
def dfs(graph, applicant, visited, result, nApplicants, nJobs):
for i in range(0, nJobs):
if graph[applicant][i] == 1 and (not visited[i]):
visited[i] = 1
if result[i] < 0 or dfs(graph, result[i], visited, result, nApplicants, nJobs):
result[i] = applicant
return 1
return 0
def bipartite(graph, nApplicants, nJobs):
result = []
for i in range(0, nJobs):
result.append(-1)
retval = 0
for i in range(nApplicants):
visited = []
for j in range(nApplicants):
visited.append(0)
if dfs(graph, i, visited, result, nApplicants, nJobs):
retval += 1
return retval
if __name__ == '__main__':
n_applicants = input('Enter the number of applicants : ')
n_jobs = input('Enter the number of jobs : ')
graph = []
for i in range(nApplicants):
print('Enter the status(1/0) for applicant - ' + str(i + 1) + ' for ' + str(nJobs) + ' Jobs!')
temp = []
for j in range(nJobs):
temp.append(input('For job - ' + str(j + 1) + ' : '))
graph.append(temp)
print('Maximum applicants that can have job is : ' + str(bipartite(graph, nApplicants, nJobs)))
|
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def tree2str(self, t: TreeNode) -> str:
if t is None:
return ""
if t.left is None and t.right is None:
return str(t.val)+""
if t.right is None:
return str(t.val)+"("+str(self.tree2str(t.left))+")"
return str(t.val)+"("+str(self.tree2str(t.left)
)+")"+"("+str(self.tree2str(t.right))+")"
|
class Solution:
def tree2str(self, t: TreeNode) -> str:
if t is None:
return ''
if t.left is None and t.right is None:
return str(t.val) + ''
if t.right is None:
return str(t.val) + '(' + str(self.tree2str(t.left)) + ')'
return str(t.val) + '(' + str(self.tree2str(t.left)) + ')' + '(' + str(self.tree2str(t.right)) + ')'
|
# get distinct characters and their count in a String
string = input("Enter String: ")
c = 0
for i in range(65, 91):
c = 0
for j in range(0, len(string)):
if(string[j] == chr(i)):
c += 1
if c > 0:
print("", chr(i), " is ", c, " times.")
c = 0
for i in range(97, 123):
c = 0
for j in range(0, len(string)):
if(string[j] == chr(i)):
c += 1
if c > 0:
print("", chr(i), " is ", c, " times.")
|
string = input('Enter String: ')
c = 0
for i in range(65, 91):
c = 0
for j in range(0, len(string)):
if string[j] == chr(i):
c += 1
if c > 0:
print('', chr(i), ' is ', c, ' times.')
c = 0
for i in range(97, 123):
c = 0
for j in range(0, len(string)):
if string[j] == chr(i):
c += 1
if c > 0:
print('', chr(i), ' is ', c, ' times.')
|
class SearchPath:
def __init__(self, path=None):
if path is None:
self._path = []
else:
self._path = path
def branch_off(self, label, p):
path = self._path + [(label, p)]
return SearchPath(path)
@property
def labels(self):
return [label for label, p in self._path]
@property
def likelihood(self):
if self._path:
probs = [p for label, p in self._path]
res = 1
for p in probs:
res *= p
return res
return 0
class PathBuilder:
def __init__(self, roots):
self._paths = []
for label, p in roots:
search_path = SearchPath()
search_path = search_path.branch_off(label, p)
self._paths.append(search_path)
def make_step(self, pmfs):
if len(pmfs) != len(self._paths):
raise WrongNumberOfPMFsException()
candidates = []
for i in range(len(self._paths)):
search_path = self._paths[i]
pmf = pmfs[i]
for label, p in enumerate(pmf):
candidates.append(search_path.branch_off(label, p))
self._paths = self._best_paths(candidates, limit=len(pmfs))
def _best_paths(self, paths, limit):
return sorted(paths, key=lambda c: c.likelihood, reverse=True)[:limit]
@property
def best_path(self):
best_path = self._best_paths(self._paths, limit=1)[0]
return best_path.labels
@property
def paths(self):
res = []
for search_path in self._paths:
res.append(search_path.labels)
return res
class WrongNumberOfPMFsException(Exception):
pass
class StatesKeeper:
def __init__(self, initial_state):
self._paths = {}
self._initial_state = initial_state
def store(self, path, state):
self._paths[tuple(path)] = state
def retrieve(self, path):
if path:
return self._paths[tuple(path)]
else:
return self._initial_state
class BaseBeamSearch:
def __init__(self, start_of_seq, end_of_seq, beam_size=3, max_len=150):
self._sos = start_of_seq
self._eos = end_of_seq
self._beam_size = beam_size
self._max_len = max_len
def _without_last(self, path):
return path[:-1]
def _remove_special(self, path):
path = path[1:]
if path[-1] == self._eos:
return self._without_last(path)
return path
def _split_path(self, path):
prefix = self._without_last(path)
last_one = path[-1]
return prefix, last_one
def generate_sequence(self):
y0 = self._sos
decoder_state = self.get_initial_state()
keeper = StatesKeeper(decoder_state)
builder = PathBuilder([(y0, 1.0)])
for _ in range(self._max_len):
pmfs = []
for path in builder.paths:
prefix, label = self._split_path(path)
state = keeper.retrieve(prefix)
next_pmf, next_state = self.decode_next(label, state)
keeper.store(path, next_state)
pmfs.append(next_pmf)
builder.make_step(pmfs)
if builder.best_path[-1] == self._eos:
break
return self._remove_special(builder.best_path)
def get_initial_state(self):
raise NotImplementedError
def decode_next(self, prev_y, prev_state):
raise NotImplementedError
class BeamCandidate:
def __init__(self, full_sequence, character, likelihood, state):
self.full_sequence = full_sequence
self.character = character
self.likelihood = likelihood
self.state = state
def branch_off(self, character, likelihood, state):
seq = self.full_sequence + character
return BeamCandidate(seq, character, likelihood, state)
# todo: consider better implementation for StatesKeeper
|
class Searchpath:
def __init__(self, path=None):
if path is None:
self._path = []
else:
self._path = path
def branch_off(self, label, p):
path = self._path + [(label, p)]
return search_path(path)
@property
def labels(self):
return [label for (label, p) in self._path]
@property
def likelihood(self):
if self._path:
probs = [p for (label, p) in self._path]
res = 1
for p in probs:
res *= p
return res
return 0
class Pathbuilder:
def __init__(self, roots):
self._paths = []
for (label, p) in roots:
search_path = search_path()
search_path = search_path.branch_off(label, p)
self._paths.append(search_path)
def make_step(self, pmfs):
if len(pmfs) != len(self._paths):
raise wrong_number_of_pm_fs_exception()
candidates = []
for i in range(len(self._paths)):
search_path = self._paths[i]
pmf = pmfs[i]
for (label, p) in enumerate(pmf):
candidates.append(search_path.branch_off(label, p))
self._paths = self._best_paths(candidates, limit=len(pmfs))
def _best_paths(self, paths, limit):
return sorted(paths, key=lambda c: c.likelihood, reverse=True)[:limit]
@property
def best_path(self):
best_path = self._best_paths(self._paths, limit=1)[0]
return best_path.labels
@property
def paths(self):
res = []
for search_path in self._paths:
res.append(search_path.labels)
return res
class Wrongnumberofpmfsexception(Exception):
pass
class Stateskeeper:
def __init__(self, initial_state):
self._paths = {}
self._initial_state = initial_state
def store(self, path, state):
self._paths[tuple(path)] = state
def retrieve(self, path):
if path:
return self._paths[tuple(path)]
else:
return self._initial_state
class Basebeamsearch:
def __init__(self, start_of_seq, end_of_seq, beam_size=3, max_len=150):
self._sos = start_of_seq
self._eos = end_of_seq
self._beam_size = beam_size
self._max_len = max_len
def _without_last(self, path):
return path[:-1]
def _remove_special(self, path):
path = path[1:]
if path[-1] == self._eos:
return self._without_last(path)
return path
def _split_path(self, path):
prefix = self._without_last(path)
last_one = path[-1]
return (prefix, last_one)
def generate_sequence(self):
y0 = self._sos
decoder_state = self.get_initial_state()
keeper = states_keeper(decoder_state)
builder = path_builder([(y0, 1.0)])
for _ in range(self._max_len):
pmfs = []
for path in builder.paths:
(prefix, label) = self._split_path(path)
state = keeper.retrieve(prefix)
(next_pmf, next_state) = self.decode_next(label, state)
keeper.store(path, next_state)
pmfs.append(next_pmf)
builder.make_step(pmfs)
if builder.best_path[-1] == self._eos:
break
return self._remove_special(builder.best_path)
def get_initial_state(self):
raise NotImplementedError
def decode_next(self, prev_y, prev_state):
raise NotImplementedError
class Beamcandidate:
def __init__(self, full_sequence, character, likelihood, state):
self.full_sequence = full_sequence
self.character = character
self.likelihood = likelihood
self.state = state
def branch_off(self, character, likelihood, state):
seq = self.full_sequence + character
return beam_candidate(seq, character, likelihood, state)
|
class Bot:
'''
state - state of the game
returns a move
'''
def move(self, state, symbol):
raise NotImplementedError('Abstractaaa')
def get_name(self):
raise NotImplementedError('Abstractaaa')
|
class Bot:
"""
state - state of the game
returns a move
"""
def move(self, state, symbol):
raise not_implemented_error('Abstractaaa')
def get_name(self):
raise not_implemented_error('Abstractaaa')
|
__author__ = 'shukkkur'
'''
https://codeforces.com/problemset/problem/581/A
A. Vasya the Hipster
'''
red, blue = map(int, input().split())
total = red + blue
a = min(red, blue)
total -= 2 * a
b = total // 2
print(a, b)
|
__author__ = 'shukkkur'
'\nhttps://codeforces.com/problemset/problem/581/A\nA. Vasya the Hipster\n'
(red, blue) = map(int, input().split())
total = red + blue
a = min(red, blue)
total -= 2 * a
b = total // 2
print(a, b)
|
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
def dnsmasq_dependencies():
http_archive(
name = "dnsmasq",
urls = ["http://www.thekelleys.org.uk/dnsmasq/dnsmasq-2.78.tar.xz"],
sha256 = "89949f438c74b0c7543f06689c319484bd126cc4b1f8c745c742ab397681252b",
build_file = "//dnsmasq:BUILD.import",
)
|
load('@bazel_tools//tools/build_defs/repo:http.bzl', 'http_archive')
def dnsmasq_dependencies():
http_archive(name='dnsmasq', urls=['http://www.thekelleys.org.uk/dnsmasq/dnsmasq-2.78.tar.xz'], sha256='89949f438c74b0c7543f06689c319484bd126cc4b1f8c745c742ab397681252b', build_file='//dnsmasq:BUILD.import')
|
file = open("input")
lines = file.readlines()
pattern_len = len(lines[0])
def part1(lines, right, down):
count = 0
pattern_len = len(lines[0])
x = 0
y = 0
while y < len(lines) - down:
x += right
y += down
if lines[y][x % (pattern_len - 1)] == "#":
count += 1
return count
def part2(lines):
return part1(lines, 1, 1) * part1(lines, 3, 1) * part1(lines, 5, 1) * part1(lines, 7, 1) * part1(lines, 1, 2)
print("Part 1: " + str(part1(lines, 3, 1)))
print("Part 2: " + str(part2(lines)))
|
file = open('input')
lines = file.readlines()
pattern_len = len(lines[0])
def part1(lines, right, down):
count = 0
pattern_len = len(lines[0])
x = 0
y = 0
while y < len(lines) - down:
x += right
y += down
if lines[y][x % (pattern_len - 1)] == '#':
count += 1
return count
def part2(lines):
return part1(lines, 1, 1) * part1(lines, 3, 1) * part1(lines, 5, 1) * part1(lines, 7, 1) * part1(lines, 1, 2)
print('Part 1: ' + str(part1(lines, 3, 1)))
print('Part 2: ' + str(part2(lines)))
|
"""
Expect Utility
--------------
Regardless of comment type, all tests in this file will be detected. We will
demonstrate that expect can handle several edge cases, accommodate regular
doctest formats, and detect inline tests.
>>> x = 4
>>> x
4
>>> 3+5 # comments
8
>>> 6+x # wrong!
5
>>> is_proper('()')
True
"""
# > () + () => ()
# > [] + [] => []
def is_proper(str):
"""Tests if a set of parentheses are properly closed.
>>> is_proper('()(())') # regular doctests
True
>>> is_proper('(()()') # too many open parens
False
>>> is_proper('())') # too many close parens
False
>>> is_proper('())(') # parens don't match
False
"""
try:
parens = []
for c in str:
if c == '(':
parens.append(c) # > [1, 2, 3].pop() => 3
else:
parens.pop() # > [1, 2, 3].pop(0) => 3
return len(parens) == 0
except IndexError:
return False
|
"""
Expect Utility
--------------
Regardless of comment type, all tests in this file will be detected. We will
demonstrate that expect can handle several edge cases, accommodate regular
doctest formats, and detect inline tests.
>>> x = 4
>>> x
4
>>> 3+5 # comments
8
>>> 6+x # wrong!
5
>>> is_proper('()')
True
"""
def is_proper(str):
"""Tests if a set of parentheses are properly closed.
>>> is_proper('()(())') # regular doctests
True
>>> is_proper('(()()') # too many open parens
False
>>> is_proper('())') # too many close parens
False
>>> is_proper('())(') # parens don't match
False
"""
try:
parens = []
for c in str:
if c == '(':
parens.append(c)
else:
parens.pop()
return len(parens) == 0
except IndexError:
return False
|
# input the length of array
n = int(input())
# input the elements of array
ar = [int(x) for x in input().strip().split(' ')]
c = [0]*100
for a in ar :
c[a] += 1
s = ''
# print the sorted list as a single line of space-separated elements
for x in range(0,100) :
for i in range(0,c[x]) :
s += ' ' + str(x)
print(s[1:])
|
n = int(input())
ar = [int(x) for x in input().strip().split(' ')]
c = [0] * 100
for a in ar:
c[a] += 1
s = ''
for x in range(0, 100):
for i in range(0, c[x]):
s += ' ' + str(x)
print(s[1:])
|
full_dict = {
'daterecieved': 'entry daterecieved',
'poploadslip' : 'entry poploadslip',
'count' : 'entry 1' ,
'tm9_ticket' : 'entry tm9_ticket',
'disposition_fmanum' : 'entry disposition_fmanum',
'owner' : 'entry ownerName',
'haulingcontractor' : 'entry hauled by',
'numpcsreceived' : 'entry num of pieces',
'blocknum' : 'entry Block Number'
}
DB_list = ['daterecieved',
'poploadslip',
'count',
'sampleloads' ,
'tm9_ticket',
'owner' ,
'disposition_fmanum' ,
'blocknum',
'haulingcontractor',
]
indxSample = [0,1,2,4,6]
keys = [DB_list[i] for i in indxSample]
A ={x:full_dict[x] for x in keys}
print(A)
|
full_dict = {'daterecieved': 'entry daterecieved', 'poploadslip': 'entry poploadslip', 'count': 'entry 1', 'tm9_ticket': 'entry tm9_ticket', 'disposition_fmanum': 'entry disposition_fmanum', 'owner': 'entry ownerName', 'haulingcontractor': 'entry hauled by', 'numpcsreceived': 'entry num of pieces', 'blocknum': 'entry Block Number'}
db_list = ['daterecieved', 'poploadslip', 'count', 'sampleloads', 'tm9_ticket', 'owner', 'disposition_fmanum', 'blocknum', 'haulingcontractor']
indx_sample = [0, 1, 2, 4, 6]
keys = [DB_list[i] for i in indxSample]
a = {x: full_dict[x] for x in keys}
print(A)
|
"""smp_base/__init__.py
.. todo::
remove actinf tag from base learners
.. todo::
abstract class from andi / smp_control to check for api conformity?
.. todo::
for module in rlspy igmm kohonone otl ; do git submodule ...
"""
|
"""smp_base/__init__.py
.. todo::
remove actinf tag from base learners
.. todo::
abstract class from andi / smp_control to check for api conformity?
.. todo::
for module in rlspy igmm kohonone otl ; do git submodule ...
"""
|
# HEAD
# Python Functions - *args
# DESCRIPTION
# Describes
# capturing all arguments as *args (tuple)
#
# RESOURCES
#
# Arguments (any number during invocation) can also be
# caught as a sequence of arguments - tuple using *args
# Order does matter for unnamed arguments list and makes for
# index of argument in list even with *args
# # # Note the * above when passing as argument
# sequence to function
# Can be named args or any name; it does not matter
def printUnnamedArgs(*args):
# Note the missing * during access
print("3. printUnnamedArgs", args)
for x in enumerate(args):
print(x)
# Can pass any number of arguments below now
# Follows order of arguments
# Argument's index is the order of arguments passed
printUnnamedArgs([1, 2, 3], [4, 5, 6])
|
def print_unnamed_args(*args):
print('3. printUnnamedArgs', args)
for x in enumerate(args):
print(x)
print_unnamed_args([1, 2, 3], [4, 5, 6])
|
class Luhn:
def __init__(self, card_num: str):
self._reversed_card_num = card_num.replace(' ', '')[::-1]
self._even_digits = self._reversed_card_num[1::2]
self._odd_digits = self._reversed_card_num[::2]
def valid(self) -> bool:
if str.isnumeric(self._reversed_card_num) and len(self._reversed_card_num) > 1:
return self._sum_card() % 10 == 0
else:
return False
def _sum_card(self) -> int:
even_digits_sum = 0
for digit in self._even_digits:
x = int(digit) * 2
even_digits_sum += x if x <= 9 else x - 9
return even_digits_sum + sum([int(x) for x in self._odd_digits])
|
class Luhn:
def __init__(self, card_num: str):
self._reversed_card_num = card_num.replace(' ', '')[::-1]
self._even_digits = self._reversed_card_num[1::2]
self._odd_digits = self._reversed_card_num[::2]
def valid(self) -> bool:
if str.isnumeric(self._reversed_card_num) and len(self._reversed_card_num) > 1:
return self._sum_card() % 10 == 0
else:
return False
def _sum_card(self) -> int:
even_digits_sum = 0
for digit in self._even_digits:
x = int(digit) * 2
even_digits_sum += x if x <= 9 else x - 9
return even_digits_sum + sum([int(x) for x in self._odd_digits])
|
"""
Problem name: ThePalindrome
Class: SRM 428, Division II Level One
Description: https://community.topcoder.com/stat?c=problem_statement&pm=10182
"""
def solve(args):
""" Simply reverse the string and find a match. When the match is found,
continue it to the end. If the end is reached, then the matching index
is the point at which the palindrome starts repeating.
"""
string = args
reverse = string[::-1]
for c in range(len(string)):
if string[c] == reverse[0]:
for i in range(c+1, len(string)):
if string[i] != reverse[i-c]:
break
else:
output = len(string) + c
break
return output
if __name__ == "__main__":
test_cases = [("abab", 5),
("abacaba", 7),
("qwerty", 11),
("abdfhdyrbdbsdfghjkllkjhgfds", 38),
("nnnnoqqpnnpnnpppnopopnqnnpqqpnnnnnppnpnqnnnnnp", 91)
]
for index, case in enumerate(test_cases):
output = solve(case[0])
assert output == case[1], 'Case {} failed: {} != {}'.format(
index, output, case[1])
else:
print('All tests OK')
|
"""
Problem name: ThePalindrome
Class: SRM 428, Division II Level One
Description: https://community.topcoder.com/stat?c=problem_statement&pm=10182
"""
def solve(args):
""" Simply reverse the string and find a match. When the match is found,
continue it to the end. If the end is reached, then the matching index
is the point at which the palindrome starts repeating.
"""
string = args
reverse = string[::-1]
for c in range(len(string)):
if string[c] == reverse[0]:
for i in range(c + 1, len(string)):
if string[i] != reverse[i - c]:
break
else:
output = len(string) + c
break
return output
if __name__ == '__main__':
test_cases = [('abab', 5), ('abacaba', 7), ('qwerty', 11), ('abdfhdyrbdbsdfghjkllkjhgfds', 38), ('nnnnoqqpnnpnnpppnopopnqnnpqqpnnnnnppnpnqnnnnnp', 91)]
for (index, case) in enumerate(test_cases):
output = solve(case[0])
assert output == case[1], 'Case {} failed: {} != {}'.format(index, output, case[1])
else:
print('All tests OK')
|
"""Kata url: https://www.codewars.com/kata/51fc12de24a9d8cb0e000001."""
def valid_ISBN10(isbn: str) -> bool:
if len(isbn) != 10:
return False
if not isbn[:-1].isdigit():
return False
if not (isbn[-1].isdigit() or isbn[-1] == 'X'):
return False
return not sum(
int(x, 16) * (c + 1) for c, x in enumerate(
isbn.replace('X', 'a')
)
)
|
"""Kata url: https://www.codewars.com/kata/51fc12de24a9d8cb0e000001."""
def valid_isbn10(isbn: str) -> bool:
if len(isbn) != 10:
return False
if not isbn[:-1].isdigit():
return False
if not (isbn[-1].isdigit() or isbn[-1] == 'X'):
return False
return not sum((int(x, 16) * (c + 1) for (c, x) in enumerate(isbn.replace('X', 'a'))))
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Apr 27 11:20:36 2019
@author: melzanaty
"""
####################################################
# Quiz: Check for Prime Numbers
####################################################
# '''
# Write code to check if the numbers provided in the list check_prime are prime numbers.
# 1. If the numbers are prime, the code should print "[number] is a prime number."
# 2. If the number is NOT a prime number, it should print "[number] is not a prime number",
# and a factor of that number, other than 1 and the number itself: "[factor] is a factor of [number]".
# '''
check_prime = [3, 26, 39, 51, 53, 57, 79, 85]
# iterate through the check_prime list
for num in check_prime:
# search for factors, iterating through numbers ranging from 2 to the number itself
for i in range(2, num):
# number is not prime if modulo is 0
if (num % i) == 0:
print("{} is NOT a prime number, because {} is a factor of {}".format(num, i, num))
break
# otherwise keep checking until we've searched all possible factors, and then declare it prime
if i == num -1:
print("{} IS a prime number".format(num))
|
"""
Created on Sat Apr 27 11:20:36 2019
@author: melzanaty
"""
check_prime = [3, 26, 39, 51, 53, 57, 79, 85]
for num in check_prime:
for i in range(2, num):
if num % i == 0:
print('{} is NOT a prime number, because {} is a factor of {}'.format(num, i, num))
break
if i == num - 1:
print('{} IS a prime number'.format(num))
|
# Copyright 2019-present, GraphQL Foundation
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
def title(s):
'''Capitalize the first character of s.'''
return s[0].capitalize() + s[1:]
def camel(s):
'''Lowercase the first character of s.'''
return s[0].lower() + s[1:]
def snake(s):
'''Convert from title or camelCase to snake_case.'''
if len(s) < 2:
return s.lower()
out = s[0].lower()
for c in s[1:]:
if c.isupper():
out += '_'
c = c.lower()
out += c
return out
changes = {
'OperationDefinition': 'Operation',
'IntValue': 'Int',
'FloatValue': 'Float',
'StringValue': 'String',
'BooleanValue': 'Boolean',
'VariableValue': 'Variable',
'TypeCondition': 'NamedType',
'EnumValue': 'Enum',
'ListValue': 'List',
'ObjectValue': 'InputObject'
}
def short(s):
'''Make some substitution to get work default Tarantool cartridge graphQL query executor.'''
for k, v in list(changes.items()):
if s == k:
s = v
return s[0].lower() + s[1:]
|
def title(s):
"""Capitalize the first character of s."""
return s[0].capitalize() + s[1:]
def camel(s):
"""Lowercase the first character of s."""
return s[0].lower() + s[1:]
def snake(s):
"""Convert from title or camelCase to snake_case."""
if len(s) < 2:
return s.lower()
out = s[0].lower()
for c in s[1:]:
if c.isupper():
out += '_'
c = c.lower()
out += c
return out
changes = {'OperationDefinition': 'Operation', 'IntValue': 'Int', 'FloatValue': 'Float', 'StringValue': 'String', 'BooleanValue': 'Boolean', 'VariableValue': 'Variable', 'TypeCondition': 'NamedType', 'EnumValue': 'Enum', 'ListValue': 'List', 'ObjectValue': 'InputObject'}
def short(s):
"""Make some substitution to get work default Tarantool cartridge graphQL query executor."""
for (k, v) in list(changes.items()):
if s == k:
s = v
return s[0].lower() + s[1:]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.