content stringlengths 7 1.05M | fixed_cases stringlengths 1 1.28M |
|---|---|
# coding=utf-8
"""
@author: xing
@contact: 1059252359@qq.com
@file: testbed_parser.py
@date: 2021/3/5 16:12
@desc:
"""
def get_version(testbed: str):
path = [e for e in testbed.split(" ") if e.find("/") > -1][0]
full_name = path.split("/")[-1]
return full_name.replace(".jar", "")
def parse_engine_name(testbed: str):
return get_version(testbed).split("-")[0]
| """
@author: xing
@contact: 1059252359@qq.com
@file: testbed_parser.py
@date: 2021/3/5 16:12
@desc:
"""
def get_version(testbed: str):
path = [e for e in testbed.split(' ') if e.find('/') > -1][0]
full_name = path.split('/')[-1]
return full_name.replace('.jar', '')
def parse_engine_name(testbed: str):
return get_version(testbed).split('-')[0] |
def find_string_len():
str_dict = {x: len(x) for x in input().split(', ')}
return str_dict
def print_dict(dictionary):
print(', '.join([f'{k} -> {v}' for k, v in dictionary.items()]))
print_dict(find_string_len()) | def find_string_len():
str_dict = {x: len(x) for x in input().split(', ')}
return str_dict
def print_dict(dictionary):
print(', '.join([f'{k} -> {v}' for (k, v) in dictionary.items()]))
print_dict(find_string_len()) |
numbers = {
items
for items in range(2,471)
if (items % 7 == 0)
if (items % 5 != 0)
}
print (sorted(numbers)) | numbers = {items for items in range(2, 471) if items % 7 == 0 if items % 5 != 0}
print(sorted(numbers)) |
class Node:
def __init__(self, value):
self.value = value
self.next = None
class Queue:
def __init__(self):
self.first = None
self.last = None
self.length = 0
def peek(self):
if self.length > 0:
return f"First: {self.first.value}\nLast: {self.last.value}\n"
else:
return
def enqueue(self, value):
new_node = Node(value)
if self.length == 0:
self.first = new_node
self.last = new_node
self.length += 1
else:
new_node.next = self.last
self.last = new_node
self.length += 1
def dequeue(self):
if self.length > 0:
tmp = self.last
for i in range(self.length - 2):
# self.last = self.first.next
tmp = tmp.next
tmp.next = None
self.first = tmp
self.length -= 1
else:
return
# Instantiate Queue class
q = Queue()
q.enqueue('google') # 1 - First
q.enqueue('twitter') # 2
q.enqueue('steam') # 3
q.enqueue('tesla') # 4 - Last
print(q.peek())
q.dequeue()
print(q.peek())
q.dequeue()
print(q.peek())
| class Node:
def __init__(self, value):
self.value = value
self.next = None
class Queue:
def __init__(self):
self.first = None
self.last = None
self.length = 0
def peek(self):
if self.length > 0:
return f'First: {self.first.value}\nLast: {self.last.value}\n'
else:
return
def enqueue(self, value):
new_node = node(value)
if self.length == 0:
self.first = new_node
self.last = new_node
self.length += 1
else:
new_node.next = self.last
self.last = new_node
self.length += 1
def dequeue(self):
if self.length > 0:
tmp = self.last
for i in range(self.length - 2):
tmp = tmp.next
tmp.next = None
self.first = tmp
self.length -= 1
else:
return
q = queue()
q.enqueue('google')
q.enqueue('twitter')
q.enqueue('steam')
q.enqueue('tesla')
print(q.peek())
q.dequeue()
print(q.peek())
q.dequeue()
print(q.peek()) |
def mdc(number_one, number_two):
max_mdc = 1
if number_one < number_two:
for max in range(1, abs(number_one) + 1):
if number_one % max == 0 and number_two % max == 0:
max_mdc = max
elif number_one >= number_two:
for max in range(1, abs(number_two) + 1):
if number_one % max == 0 and number_two % max == 0:
max_mdc = max
return max_mdc
class Rational:
def __init__(self, numerator, denominator):
self.numerator = int(numerator)
self.denominator = int(denominator)
def get_numerator(self):
return self.numerator
def get_denominator(self):
return self.denominator
def to_float(self):
return self.numerator/self.denominator
def reciprocal(self):
return Rational(self.get_denominator(), self.get_numerator())
def reduce(self):
mdc_value = mdc(self.get_numerator(), self.get_denominator())
return Rational(self.get_numerator() / mdc_value, self.get_denominator() / mdc_value)
# Dunder methods
def __add__(self, other):
if isinstance(other, Rational):
new_denominator = self.get_denominator() * other.get_denominator()
return Rational(((new_denominator / self.get_denominator()) * self.get_numerator()) + ((new_denominator / other.get_denominator()) * other.get_numerator()), new_denominator).reduce()
elif isinstance(other, int):
return Rational(self.get_numerator() + self.get_denominator() * other, self.get_denominator()).reduce()
elif isinstance(other, float):
return self.to_float() + other
else:
return None
def __mul__(self, other):
if isinstance(other, Rational):
return Rational(self.get_numerator() * other.get_numerator(), self.get_denominator() * other.get_denominator()).reduce()
elif isinstance(other, int):
return Rational(self.get_numerator() * other, self.get_denominator()).reduce()
elif isinstance(other, float):
return self.to_float() * other
else:
return None
def __truediv__(self, other):
if isinstance(other, Rational):
return Rational(self.get_numerator() * other.get_denominator(), self.get_denominator() * other.get_numerator()).reduce()
elif isinstance(other, int):
return Rational(self.get_numerator(), self.get_denominator() * other).reduce()
elif isinstance(other, float):
return self.to_float() / other
else:
return None
def __sub__(self, other):
if isinstance(other, Rational):
return Rational((self.get_numerator() * other.get_denominator() - self.get_denominator() * other.get_numerator()), (self.get_denominator() * other.get_denominator())).reduce()
elif isinstance(other, int):
return Rational(self.get_numerator() - self.get_denominator() * other, self.get_denominator()).reduce()
elif isinstance(other, float):
return self.to_float() - other
else:
return None
| def mdc(number_one, number_two):
max_mdc = 1
if number_one < number_two:
for max in range(1, abs(number_one) + 1):
if number_one % max == 0 and number_two % max == 0:
max_mdc = max
elif number_one >= number_two:
for max in range(1, abs(number_two) + 1):
if number_one % max == 0 and number_two % max == 0:
max_mdc = max
return max_mdc
class Rational:
def __init__(self, numerator, denominator):
self.numerator = int(numerator)
self.denominator = int(denominator)
def get_numerator(self):
return self.numerator
def get_denominator(self):
return self.denominator
def to_float(self):
return self.numerator / self.denominator
def reciprocal(self):
return rational(self.get_denominator(), self.get_numerator())
def reduce(self):
mdc_value = mdc(self.get_numerator(), self.get_denominator())
return rational(self.get_numerator() / mdc_value, self.get_denominator() / mdc_value)
def __add__(self, other):
if isinstance(other, Rational):
new_denominator = self.get_denominator() * other.get_denominator()
return rational(new_denominator / self.get_denominator() * self.get_numerator() + new_denominator / other.get_denominator() * other.get_numerator(), new_denominator).reduce()
elif isinstance(other, int):
return rational(self.get_numerator() + self.get_denominator() * other, self.get_denominator()).reduce()
elif isinstance(other, float):
return self.to_float() + other
else:
return None
def __mul__(self, other):
if isinstance(other, Rational):
return rational(self.get_numerator() * other.get_numerator(), self.get_denominator() * other.get_denominator()).reduce()
elif isinstance(other, int):
return rational(self.get_numerator() * other, self.get_denominator()).reduce()
elif isinstance(other, float):
return self.to_float() * other
else:
return None
def __truediv__(self, other):
if isinstance(other, Rational):
return rational(self.get_numerator() * other.get_denominator(), self.get_denominator() * other.get_numerator()).reduce()
elif isinstance(other, int):
return rational(self.get_numerator(), self.get_denominator() * other).reduce()
elif isinstance(other, float):
return self.to_float() / other
else:
return None
def __sub__(self, other):
if isinstance(other, Rational):
return rational(self.get_numerator() * other.get_denominator() - self.get_denominator() * other.get_numerator(), self.get_denominator() * other.get_denominator()).reduce()
elif isinstance(other, int):
return rational(self.get_numerator() - self.get_denominator() * other, self.get_denominator()).reduce()
elif isinstance(other, float):
return self.to_float() - other
else:
return None |
#!/usr/bin/env python
command('start-configuration-editing')
command('cd /')
command('delete-element /sessionClusterConfig')
command('activate-configuration')
| command('start-configuration-editing')
command('cd /')
command('delete-element /sessionClusterConfig')
command('activate-configuration') |
class Field:
__slots__ = ('name', 'typ')
def __init__(self, typ, name=None):
self.typ = typ
self.name = name
def __get__(self, instance, owner):
if instance is None:
return self
typ = instance.__dict__.get(self.name)
return typ.value if typ else typ
def __set__(self, instance, value):
instance._changed(self.name)
instance.__dict__[self.name] = self.typ(value)
def marshal(self, instance):
return instance.__dict__[self.name].marshal()
| class Field:
__slots__ = ('name', 'typ')
def __init__(self, typ, name=None):
self.typ = typ
self.name = name
def __get__(self, instance, owner):
if instance is None:
return self
typ = instance.__dict__.get(self.name)
return typ.value if typ else typ
def __set__(self, instance, value):
instance._changed(self.name)
instance.__dict__[self.name] = self.typ(value)
def marshal(self, instance):
return instance.__dict__[self.name].marshal() |
@six.add_metaclass(BasicTestsMetaclass)
class ResourceListTests(BaseWebAPITestCase):
"""Testing the WatchedReviewGroupResource list API tests."""
fixtures = ["test_users"]
sample_api_url = "users/<username>/watched/review-groups/"
resource = resources.watched_review_group
def compare_item(self, item_rsp, obj):
watched_rsp = item_rsp["watched_review_group"]
self.assertEqual(watched_rsp["id"], obj.pk)
self.assertEqual(watched_rsp["name"], obj.name)
def setup_basic_get_test(self, user, with_local_site, local_site_name, populate_items):
if populate_items:
group = self.create_review_group(with_local_site=with_local_site)
profile = user.get_profile()
profile.starred_groups.add(group)
items = [group]
else:
items = []
return (get_watched_review_group_list_url(user.username, local_site_name), watched_review_group_list_mimetype, items)
def setup_basic_post_test(self, user, with_local_site, local_site_name, post_valid_data):
group = self.create_review_group(with_local_site=with_local_site)
if post_valid_data:
post_data = {"object_id": group.name}
else:
post_data = {}
return (get_watched_review_group_list_url(user.username, local_site_name), watched_review_group_item_mimetype, post_data, [group])
def check_post_result(self, user, rsp, group):
profile = user.get_profile()
self.assertIn(group, profile.starred_groups.all())
def test_post_with_does_not_exist_error(self):
"""Testing the POST users/<username>/watched/review-groups/ API
with Does Not Exist error
"""
rsp = self.api_post(get_watched_review_group_list_url(self.user.username), {"object_id": "invalidgroup"}, expected_status=404)
self.assertEqual(rsp["stat"], "fail")
self.assertEqual(rsp["err"]["code"], DOES_NOT_EXIST.code)
@add_fixtures(["test_site"])
def test_post_with_site_does_not_exist_error(self):
"""Testing the POST users/<username>/watched/review-groups/ API
with a local site and Does Not Exist error
"""
user = self._login_user(local_site=True)
rsp = self.api_post(get_watched_review_group_list_url(user.username, self.local_site_name), {"object_id": "devgroup"}, expected_status=404)
self.assertEqual(rsp["stat"], "fail")
self.assertEqual(rsp["err"]["code"], DOES_NOT_EXIST.code)
@six.add_metaclass(BasicTestsMetaclass)
class ResourceItemTests(BaseWebAPITestCase):
"""Testing the WatchedReviewGroupResource item API tests."""
fixtures = ["test_users"]
test_http_methods = ("DELETE", "PUT")
sample_api_url = "users/<username>/watched/review-groups/<id>/"
resource = resources.watched_review_group
def setup_http_not_allowed_item_test(self, user):
return get_watched_review_group_item_url(user.username, "my-group")
def setup_basic_delete_test(self, user, with_local_site, local_site_name):
group = self.create_review_group(with_local_site=with_local_site)
profile = user.get_profile()
profile.starred_groups.add(group)
return (get_watched_review_group_item_url(user.username, group.name, local_site_name), [profile, group])
def check_delete_result(self, user, profile, group):
self.assertNotIn(group, profile.starred_groups.all())
def test_delete_with_does_not_exist_error(self):
"""Testing the DELETE users/<username>/watched/review-groups/<id>/ API
with Does Not Exist error
"""
rsp = self.api_delete(get_watched_review_group_item_url(self.user.username, "invalidgroup"), expected_status=404)
self.assertEqual(rsp["stat"], "fail")
self.assertEqual(rsp["err"]["code"], DOES_NOT_EXIST.code)
def test_get(self):
"""Testing the GET users/<username>/watched/review-groups/<id>/ API"""
group = self.create_review_group()
profile = self.user.get_profile()
profile.starred_groups.add(group)
expected_url = self.base_url + get_review_group_item_url(group.name)
self.api_get(get_watched_review_group_item_url(self.user.username, group.pk), expected_status=302, expected_headers={"Location": expected_url})
@add_fixtures(["test_site"])
def test_get_with_site(self):
"""Testing the GET users/<username>/watched/review-groups/<id>/ API
with access to a local site
"""
user = self._login_user(local_site=True)
group = self.create_review_group(with_local_site=True)
profile = user.get_profile()
profile.starred_groups.add(group)
expected_url = self.base_url + get_review_group_item_url(group.name, self.local_site_name)
self.api_get(get_watched_review_group_item_url(user.username, group.pk, self.local_site_name), expected_status=302, expected_headers={"Location": expected_url})
@add_fixtures(["test_site"])
def test_get_with_site_no_access(self):
"""Testing the GET users/<username>/watched/review-groups/<id>/ API
without access to a local site
"""
group = self.create_review_group(with_local_site=True)
profile = self.user.get_profile()
profile.starred_groups.add(group)
rsp = self.api_get(get_watched_review_group_item_url(self.user.username, group.pk, self.local_site_name), expected_status=403)
self.assertEqual(rsp["stat"], "fail")
self.assertEqual(rsp["err"]["code"], PERMISSION_DENIED.code) | @six.add_metaclass(BasicTestsMetaclass)
class Resourcelisttests(BaseWebAPITestCase):
"""Testing the WatchedReviewGroupResource list API tests."""
fixtures = ['test_users']
sample_api_url = 'users/<username>/watched/review-groups/'
resource = resources.watched_review_group
def compare_item(self, item_rsp, obj):
watched_rsp = item_rsp['watched_review_group']
self.assertEqual(watched_rsp['id'], obj.pk)
self.assertEqual(watched_rsp['name'], obj.name)
def setup_basic_get_test(self, user, with_local_site, local_site_name, populate_items):
if populate_items:
group = self.create_review_group(with_local_site=with_local_site)
profile = user.get_profile()
profile.starred_groups.add(group)
items = [group]
else:
items = []
return (get_watched_review_group_list_url(user.username, local_site_name), watched_review_group_list_mimetype, items)
def setup_basic_post_test(self, user, with_local_site, local_site_name, post_valid_data):
group = self.create_review_group(with_local_site=with_local_site)
if post_valid_data:
post_data = {'object_id': group.name}
else:
post_data = {}
return (get_watched_review_group_list_url(user.username, local_site_name), watched_review_group_item_mimetype, post_data, [group])
def check_post_result(self, user, rsp, group):
profile = user.get_profile()
self.assertIn(group, profile.starred_groups.all())
def test_post_with_does_not_exist_error(self):
"""Testing the POST users/<username>/watched/review-groups/ API
with Does Not Exist error
"""
rsp = self.api_post(get_watched_review_group_list_url(self.user.username), {'object_id': 'invalidgroup'}, expected_status=404)
self.assertEqual(rsp['stat'], 'fail')
self.assertEqual(rsp['err']['code'], DOES_NOT_EXIST.code)
@add_fixtures(['test_site'])
def test_post_with_site_does_not_exist_error(self):
"""Testing the POST users/<username>/watched/review-groups/ API
with a local site and Does Not Exist error
"""
user = self._login_user(local_site=True)
rsp = self.api_post(get_watched_review_group_list_url(user.username, self.local_site_name), {'object_id': 'devgroup'}, expected_status=404)
self.assertEqual(rsp['stat'], 'fail')
self.assertEqual(rsp['err']['code'], DOES_NOT_EXIST.code)
@six.add_metaclass(BasicTestsMetaclass)
class Resourceitemtests(BaseWebAPITestCase):
"""Testing the WatchedReviewGroupResource item API tests."""
fixtures = ['test_users']
test_http_methods = ('DELETE', 'PUT')
sample_api_url = 'users/<username>/watched/review-groups/<id>/'
resource = resources.watched_review_group
def setup_http_not_allowed_item_test(self, user):
return get_watched_review_group_item_url(user.username, 'my-group')
def setup_basic_delete_test(self, user, with_local_site, local_site_name):
group = self.create_review_group(with_local_site=with_local_site)
profile = user.get_profile()
profile.starred_groups.add(group)
return (get_watched_review_group_item_url(user.username, group.name, local_site_name), [profile, group])
def check_delete_result(self, user, profile, group):
self.assertNotIn(group, profile.starred_groups.all())
def test_delete_with_does_not_exist_error(self):
"""Testing the DELETE users/<username>/watched/review-groups/<id>/ API
with Does Not Exist error
"""
rsp = self.api_delete(get_watched_review_group_item_url(self.user.username, 'invalidgroup'), expected_status=404)
self.assertEqual(rsp['stat'], 'fail')
self.assertEqual(rsp['err']['code'], DOES_NOT_EXIST.code)
def test_get(self):
"""Testing the GET users/<username>/watched/review-groups/<id>/ API"""
group = self.create_review_group()
profile = self.user.get_profile()
profile.starred_groups.add(group)
expected_url = self.base_url + get_review_group_item_url(group.name)
self.api_get(get_watched_review_group_item_url(self.user.username, group.pk), expected_status=302, expected_headers={'Location': expected_url})
@add_fixtures(['test_site'])
def test_get_with_site(self):
"""Testing the GET users/<username>/watched/review-groups/<id>/ API
with access to a local site
"""
user = self._login_user(local_site=True)
group = self.create_review_group(with_local_site=True)
profile = user.get_profile()
profile.starred_groups.add(group)
expected_url = self.base_url + get_review_group_item_url(group.name, self.local_site_name)
self.api_get(get_watched_review_group_item_url(user.username, group.pk, self.local_site_name), expected_status=302, expected_headers={'Location': expected_url})
@add_fixtures(['test_site'])
def test_get_with_site_no_access(self):
"""Testing the GET users/<username>/watched/review-groups/<id>/ API
without access to a local site
"""
group = self.create_review_group(with_local_site=True)
profile = self.user.get_profile()
profile.starred_groups.add(group)
rsp = self.api_get(get_watched_review_group_item_url(self.user.username, group.pk, self.local_site_name), expected_status=403)
self.assertEqual(rsp['stat'], 'fail')
self.assertEqual(rsp['err']['code'], PERMISSION_DENIED.code) |
# Take string, mirrors its string argument, and print result
def get_mirror(string):
# mirrors string argument
result = string + string[::-1]
return result
# Define main function
def main():
# Prompt user for a string
astring = input('Enter a string: ')
# Obtain mirror string
mirror = get_mirror(astring)
# Display mirror
print(mirror)
# Call main function
main()
| def get_mirror(string):
result = string + string[::-1]
return result
def main():
astring = input('Enter a string: ')
mirror = get_mirror(astring)
print(mirror)
main() |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def compute_short_chain(number):
"""Compute a short chain
Arguments:
number {int} -- Requested number for which to compute the square
Returns:
int -- Value of the square/short chain for the given number
"""
return number * number
def compute_long_chain(number):
"""Compute a long chain
Arguments:
number {int} -- Requested number for which to compute the cube
Returns:
int -- Value of the cube/long chain for the given number
"""
return number * number * number
def lambda_handler(event, context):
pass
| def compute_short_chain(number):
"""Compute a short chain
Arguments:
number {int} -- Requested number for which to compute the square
Returns:
int -- Value of the square/short chain for the given number
"""
return number * number
def compute_long_chain(number):
"""Compute a long chain
Arguments:
number {int} -- Requested number for which to compute the cube
Returns:
int -- Value of the cube/long chain for the given number
"""
return number * number * number
def lambda_handler(event, context):
pass |
#!/usr/bin/env python3
# with_example02.py
class Sample:
def __enter__(self):
return self
def __exit__(self, type, value, trace):
print("type:", type)
print("value:", value)
print("trace:", trace)
def do_something(self):
bar = 1/0
return bar + 10
with Sample() as sample:
sample.do_something()
| class Sample:
def __enter__(self):
return self
def __exit__(self, type, value, trace):
print('type:', type)
print('value:', value)
print('trace:', trace)
def do_something(self):
bar = 1 / 0
return bar + 10
with sample() as sample:
sample.do_something() |
class Node():
def __init__(self, value):
self.value = value
self.next = None
class LinkedList():
def __init__(self):
self.head = None
def __str__(self):
current = self.head
output = ''
while current:
output += f"{ {str(current.value)} } ->"
current = current.next
return output
def __iter__(self):
"""
loop over the linked list
"""
current = self.head
while current:
yield current.value
current = current.next
def append(self, value):
'''
this method to append value in the last node
input ==> value
'''
if value is None:
raise TypeError("insert() missing 1 required positional argument: 'value' ")
else:
new_node = Node(value)
if not self.head:
self.head = new_node
else:
new_node = Node(value)
current = self.head
while current.next:
current = current.next
current.next = new_node
def insert(self, value):
'''
this method to adds an element to the list
input ==> element
'''
node = Node(value)
node.next = self.head
self.head = node
def includes(self, values):
'''
this method to checks if an element
exists in the list and returns a boolean (True/Flase)
input ==> value
output ==> boolean
'''
if values is None:
raise TypeError("includes() missing 1 required positional argument: 'values' ")
else:
current_node = self.head
while current_node.next :
if current_node.value == values:
return True
else:
current_node = current_node.next
return False
###########################################################################
def insert_before(self,value,new_value):
'''
adds an element to the list befor element
its take to element
first argument the value wich we will insert befor it
the second is the value wich we will insert
'''
new_node = Node(new_value)
current = self.head
if not self.head:
self.head = new_node
else:
if current.value == value:
th_node = self.head
self.head = new_node
new_node.next = th_node
return
else:
current = self.head
while current.next :
if current.next.value == value:
th_node = current.next
current.next = new_node
new_node.next = th_node
return
else:
current = current.next
return
def insert_after(self, value, new_value):
'''
adds an element to the list after element
its take to element
first argument the value wich we will insert after it
the second is the value wich we will insert
'''
new_node = Node(new_value)
current = self.head
if not self.head:
self.head = new_node
else:
current = self.head
while current.next != None:
if current.next.value == value:
current = current.next
old_node = current.next
current.next = new_node
new_node.next = old_node
return
else:
current = current.next
return
###########################################################################
def kth_from_end(self, k):
"""takes in a value(k) and returns the Node k places away from the tail"""
current = self.head
arr = []
if k < 0:
return 'index can\'t be less the zero'
while current:
arr.append(current)
current = current.next
if len(arr) < k:
return 'index not found'
arr.reverse()
if k == len(arr):
k = k -1
return arr[k].value
#################################################################
def kth_from_end_second(self, k):
current = self.head
count = 0
while (current):
if (count == k):
return current.value
count += 1
current = current.next
#################################################################
def deleteNode(self, k):
temp = self.head
if (temp is not None):
if (temp.value == k):
self.head = temp.next
temp = None
return
while(temp is not None):
if temp.value == k:
break
prev = temp
temp = temp.next
if(temp == None):
return
prev.next = temp.next
temp = None
if __name__ == "__main__":
ll = LinkedList()
ll.append(1)
ll.append(2)
ll.append(3)
ll.append(12)
ll.append(232)
ll.append(324)
ll.append(14235)
ll.append(22366)
ll.append(3234)
ll.append(134)
ll.append(2545)
ll.append(367)
print(str(ll))
ll.deleteNode(22366)
ll.deleteNode(1)
ll.deleteNode(324)
ll.deleteNode(367)
print(str(ll))
| class Node:
def __init__(self, value):
self.value = value
self.next = None
class Linkedlist:
def __init__(self):
self.head = None
def __str__(self):
current = self.head
output = ''
while current:
output += f'{ {str(current.value)}} ->'
current = current.next
return output
def __iter__(self):
"""
loop over the linked list
"""
current = self.head
while current:
yield current.value
current = current.next
def append(self, value):
"""
this method to append value in the last node
input ==> value
"""
if value is None:
raise type_error("insert() missing 1 required positional argument: 'value' ")
else:
new_node = node(value)
if not self.head:
self.head = new_node
else:
new_node = node(value)
current = self.head
while current.next:
current = current.next
current.next = new_node
def insert(self, value):
"""
this method to adds an element to the list
input ==> element
"""
node = node(value)
node.next = self.head
self.head = node
def includes(self, values):
"""
this method to checks if an element
exists in the list and returns a boolean (True/Flase)
input ==> value
output ==> boolean
"""
if values is None:
raise type_error("includes() missing 1 required positional argument: 'values' ")
else:
current_node = self.head
while current_node.next:
if current_node.value == values:
return True
else:
current_node = current_node.next
return False
def insert_before(self, value, new_value):
"""
adds an element to the list befor element
its take to element
first argument the value wich we will insert befor it
the second is the value wich we will insert
"""
new_node = node(new_value)
current = self.head
if not self.head:
self.head = new_node
else:
if current.value == value:
th_node = self.head
self.head = new_node
new_node.next = th_node
return
else:
current = self.head
while current.next:
if current.next.value == value:
th_node = current.next
current.next = new_node
new_node.next = th_node
return
else:
current = current.next
return
def insert_after(self, value, new_value):
"""
adds an element to the list after element
its take to element
first argument the value wich we will insert after it
the second is the value wich we will insert
"""
new_node = node(new_value)
current = self.head
if not self.head:
self.head = new_node
else:
current = self.head
while current.next != None:
if current.next.value == value:
current = current.next
old_node = current.next
current.next = new_node
new_node.next = old_node
return
else:
current = current.next
return
def kth_from_end(self, k):
"""takes in a value(k) and returns the Node k places away from the tail"""
current = self.head
arr = []
if k < 0:
return "index can't be less the zero"
while current:
arr.append(current)
current = current.next
if len(arr) < k:
return 'index not found'
arr.reverse()
if k == len(arr):
k = k - 1
return arr[k].value
def kth_from_end_second(self, k):
current = self.head
count = 0
while current:
if count == k:
return current.value
count += 1
current = current.next
def delete_node(self, k):
temp = self.head
if temp is not None:
if temp.value == k:
self.head = temp.next
temp = None
return
while temp is not None:
if temp.value == k:
break
prev = temp
temp = temp.next
if temp == None:
return
prev.next = temp.next
temp = None
if __name__ == '__main__':
ll = linked_list()
ll.append(1)
ll.append(2)
ll.append(3)
ll.append(12)
ll.append(232)
ll.append(324)
ll.append(14235)
ll.append(22366)
ll.append(3234)
ll.append(134)
ll.append(2545)
ll.append(367)
print(str(ll))
ll.deleteNode(22366)
ll.deleteNode(1)
ll.deleteNode(324)
ll.deleteNode(367)
print(str(ll)) |
"""Module containing the exception class for describe-get-system proof of concept module."""
class DGSError(Exception):
"""Use to capture error DGS construction."""
class TemplateStorageError(DGSError):
"""Use to capture error for TemplateStorage."""
class AdaptorAuthenticationError(DGSError):
"""Use to capture error for adaptor connection"""
class InterpreterError(DGSError):
"""Use to capture error for interpreter"""
class NotImplementedFrameworkError(InterpreterError):
"""Use to capture error for not implement framework"""
class ComparisonOperatorError(InterpreterError):
"""Use to capture error for invalid comparison operator"""
class ConnectDeviceStatementError(InterpreterError):
"""Use to capture error for interpreting connect device statement"""
class DisconnectDeviceStatementError(InterpreterError):
"""Use to capture error for interpreting disconnect device statement"""
class ReleaseDeviceStatementError(InterpreterError):
"""Use to capture error for interpreting release device statement"""
class WaitForStatementError(InterpreterError):
"""Use to capture error for interpreting wait for statement"""
class PerformerStatementError(InterpreterError):
"""Use to capture error for performer statement"""
class VerificationStatementError(InterpreterError):
"""Use to capture error for verification statement"""
class ScriptBuilderError(InterpreterError):
"""Use to capture error for building test script"""
class DurationArgumentError(InterpreterError):
"""Use to capture error for wait_for function"""
class ConvertorTypeError(InterpreterError):
"""Use to capture convertor argument for filter method"""
class TemplateReferenceError(InterpreterError):
"""Use to capture template reference for filter method"""
class UtilsParsedTemplateError(InterpreterError):
"""Use to capture error for parsing template in utils"""
class ReportError(DGSError):
"""Use to capture error for report generation in report.py"""
| """Module containing the exception class for describe-get-system proof of concept module."""
class Dgserror(Exception):
"""Use to capture error DGS construction."""
class Templatestorageerror(DGSError):
"""Use to capture error for TemplateStorage."""
class Adaptorauthenticationerror(DGSError):
"""Use to capture error for adaptor connection"""
class Interpretererror(DGSError):
"""Use to capture error for interpreter"""
class Notimplementedframeworkerror(InterpreterError):
"""Use to capture error for not implement framework"""
class Comparisonoperatorerror(InterpreterError):
"""Use to capture error for invalid comparison operator"""
class Connectdevicestatementerror(InterpreterError):
"""Use to capture error for interpreting connect device statement"""
class Disconnectdevicestatementerror(InterpreterError):
"""Use to capture error for interpreting disconnect device statement"""
class Releasedevicestatementerror(InterpreterError):
"""Use to capture error for interpreting release device statement"""
class Waitforstatementerror(InterpreterError):
"""Use to capture error for interpreting wait for statement"""
class Performerstatementerror(InterpreterError):
"""Use to capture error for performer statement"""
class Verificationstatementerror(InterpreterError):
"""Use to capture error for verification statement"""
class Scriptbuildererror(InterpreterError):
"""Use to capture error for building test script"""
class Durationargumenterror(InterpreterError):
"""Use to capture error for wait_for function"""
class Convertortypeerror(InterpreterError):
"""Use to capture convertor argument for filter method"""
class Templatereferenceerror(InterpreterError):
"""Use to capture template reference for filter method"""
class Utilsparsedtemplateerror(InterpreterError):
"""Use to capture error for parsing template in utils"""
class Reporterror(DGSError):
"""Use to capture error for report generation in report.py""" |
N, M = map(int, input().split())
loop = (2**M)
print(1900*loop*M+100*(N-M)*loop)
| (n, m) = map(int, input().split())
loop = 2 ** M
print(1900 * loop * M + 100 * (N - M) * loop) |
def check_double(number):
if len(str(number))==(len(str(number*2))) and number!=number*2 :
return sorted(str(number)) == sorted(str(number*2))
return False
print(check_double(125874)) | def check_double(number):
if len(str(number)) == len(str(number * 2)) and number != number * 2:
return sorted(str(number)) == sorted(str(number * 2))
return False
print(check_double(125874)) |
docs = """django-mc-commands
=======================
[](https://travis-ci.org/mc706/django-angular-scaffold)
[](http://badge.fury.io/py/django-angular-scaffold)
[](https://landscape.io/github/mc706/django-angular-scaffold/master)
[](https://coveralls.io/r/mc706/django-angular-scaffold)
set of django management commands to manage versions and help out around building your app.
build by [@mc706](http://mc706.com)
##Installation
Install using pip
```
pip install django-mc-commands
```
include in your INSTALLED_APPS
```
#settings.py
...
INSTALLED_APPS = (
...
'mc_commands',
...
)
```
##Commands
The following are commands that are made available through this package.
###bootstrap
```
./manage.py bootstrap
```
Adds a few key files to your application
* `_version.py`
* `CHANGELOG.md`
* This docs file
* A separate internal app tuple file
###quality_check
```
./manage.py quality_check
```
Runs a few libraries to check the quality of the code in the repository
* pep8
* jshint
* xenon
* prospector
###runtests
```
./manage.py runtests
```
A shortcut command to run the internal apps with coverage and fail if coverage is below a certain amount
###freeze
```
./manage.py freeze
```
Shortcut wrapper around `pip freeze > requirements.txt`
###cut
```
./manage.py cut <type>
```
Cuts a release and pushed it to git. Will update the changelog, and update `_version.py` and tag a release.
Type options are:
* patch (default)
* minor
* major
Version users Semver major.minor.patch
""" | docs = "django-mc-commands\n=======================\n\n[](https://travis-ci.org/mc706/django-angular-scaffold)\n[](http://badge.fury.io/py/django-angular-scaffold)\n[](https://landscape.io/github/mc706/django-angular-scaffold/master)\n[](https://coveralls.io/r/mc706/django-angular-scaffold)\n\nset of django management commands to manage versions and help out around building your app.\n\nbuild by [@mc706](http://mc706.com)\n\n##Installation\n\nInstall using pip\n\n```\npip install django-mc-commands\n```\n\ninclude in your INSTALLED_APPS\n```\n#settings.py\n...\nINSTALLED_APPS = (\n ...\n 'mc_commands',\n ...\n)\n```\n\n##Commands\n\nThe following are commands that are made available through this package.\n\n\n###bootstrap\n\n```\n./manage.py bootstrap\n```\n\nAdds a few key files to your application\n\n* `_version.py`\n* `CHANGELOG.md`\n* This docs file\n* A separate internal app tuple file\n\n\n\n###quality_check\n\n```\n./manage.py quality_check\n```\n\nRuns a few libraries to check the quality of the code in the repository\n\n* pep8\n* jshint\n* xenon\n* prospector\n\n###runtests\n\n```\n./manage.py runtests\n```\n\nA shortcut command to run the internal apps with coverage and fail if coverage is below a certain amount\n\n###freeze\n\n```\n./manage.py freeze\n```\n\nShortcut wrapper around `pip freeze > requirements.txt`\n\n\n###cut\n\n```\n./manage.py cut <type>\n```\n\nCuts a release and pushed it to git. Will update the changelog, and update `_version.py` and tag a release.\n\nType options are:\n\n* patch (default)\n* minor\n* major\n\nVersion users Semver major.minor.patch\n\n" |
DEBUG = False
TESTING = False
PROXY = False # True if app is proxied by Apache or similar.
# Application Settings
BROWSER_NAME = 'Bravo'
DATASET_NAME = 'Example Dataset' # Change to your dataset name
SHOW_POWERED_BY = False
NUM_SAMPLES = 0 # Change to the number of samples you are using
NUM_VARIANTS = 'XYZ million' # Change to the number of variants you are using
# Database Settings
MONGO = {
'host': '127.0.0.1',
'port': 27017,
'name': 'bravo'
}
DOWNLOAD_ALL_FILEPATH = ''
URL_PREFIX = ''
# Google Analytics Settings
GOOGLE_ANALYTICS_TRACKING_ID = '' # (Optional) Change to your Google Analytics Tracking ID.
SECRET_KEY = '' # (Optional) Change to your Google Analytics Secret Key
# Google Auth Settings
GOOGLE_AUTH = False # True if app is using Google Auth 2.0
GOOGLE_LOGIN_CLIENT_ID = '' # Insert your Google Login Client ID
GOOGLE_LOGIN_CLIENT_SECRET = '' # Insert your Google Login Secret
TERMS = True # True if app requires 'Terms of Use'. Can be used only if GOOGLE_AUTH is enabled.
# Email Whitelist Settings
EMAIL_WHITELIST = False # True if app has whitelisted emails. Can be used only if GOOGLE_AUTH is enabled.
API_GOOGLE_AUTH = False
API_IP_WHITELIST = ['127.0.0.1']
API_VERSION = ''
API_DATASET_NAME = ''
API_COLLECTION_NAME = 'variants'
API_URL_PREFIX = '/api/' + API_VERSION
API_PAGE_SIZE = 1000
API_MAX_REGION = 250000
API_REQUESTS_RATE_LIMIT = ['1800/15 minute']
# BRAVO Settings
BRAVO_AUTH_SECRET = ''
BRAVO_ACCESS_SECRET = ''
BRAVO_AUTH_URL_PREFIX = '/api/' + API_VERSION + '/auth'
# Data Directory Settings. By default all data is stored in /data root directory
IGV_REFERENCE_PATH = '/data/genomes/genome.fa'
IGV_CRAM_DIRECTORY = '/data/cram/'
IGV_CACHE_COLLECTION = 'igv_cache'
IGV_CACHE_DIRECTORY = '/data/cache/igv_cache/'
IGV_CACHE_LIMIT = 1000
BASE_COVERAGE_DIRECTORY = '/data/coverage/'
# FASTA Data URL Settings.
FASTA_URL = 'https://<your-bravo-domain>/genomes/genome.fa' # Edit to reflect your URL for your BRAVO application
ADMINS = [
'email@email.email'
]
ADMIN = False # True if app is running in admin mode.
ADMIN_ALLOWED_IP = [] # IPs allowed to reach admin interface
| debug = False
testing = False
proxy = False
browser_name = 'Bravo'
dataset_name = 'Example Dataset'
show_powered_by = False
num_samples = 0
num_variants = 'XYZ million'
mongo = {'host': '127.0.0.1', 'port': 27017, 'name': 'bravo'}
download_all_filepath = ''
url_prefix = ''
google_analytics_tracking_id = ''
secret_key = ''
google_auth = False
google_login_client_id = ''
google_login_client_secret = ''
terms = True
email_whitelist = False
api_google_auth = False
api_ip_whitelist = ['127.0.0.1']
api_version = ''
api_dataset_name = ''
api_collection_name = 'variants'
api_url_prefix = '/api/' + API_VERSION
api_page_size = 1000
api_max_region = 250000
api_requests_rate_limit = ['1800/15 minute']
bravo_auth_secret = ''
bravo_access_secret = ''
bravo_auth_url_prefix = '/api/' + API_VERSION + '/auth'
igv_reference_path = '/data/genomes/genome.fa'
igv_cram_directory = '/data/cram/'
igv_cache_collection = 'igv_cache'
igv_cache_directory = '/data/cache/igv_cache/'
igv_cache_limit = 1000
base_coverage_directory = '/data/coverage/'
fasta_url = 'https://<your-bravo-domain>/genomes/genome.fa'
admins = ['email@email.email']
admin = False
admin_allowed_ip = [] |
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 13 04:08:08 2017
@author: Mayur
"""
# =============================================================================
# Problem 4 - Decrypt a Story
#
# For this problem, the graders will use our implementation of the Message,
# PlaintextMessage, and CiphertextMessage classes, so don't worry if you did not
# get the previous parts correct.
#
# Now that you have all the pieces to the puzzle, please use them to decode the
# file story.txt. The file ps6.py contains a helper function get_story_string()
# that returns the encrypted version of the story as a string. Create a
# CiphertextMessage object using the story string and use decrypt_message to
# return the appropriate shift value and unencrypted story string.
# =============================================================================
#code
def decrypt_story():
encryptedStory = get_story_string()
decryptedStory = CiphertextMessage(encryptedStory)
return decryptedStory.decrypt_message() | """
Created on Wed Dec 13 04:08:08 2017
@author: Mayur
"""
def decrypt_story():
encrypted_story = get_story_string()
decrypted_story = ciphertext_message(encryptedStory)
return decryptedStory.decrypt_message() |
# -*- coding: utf-8 -*-
# Copyright 2021 Cohesity Inc.
class CertificateDetails(object):
"""Implementation of the 'CertificateDetails' model.
Specifies details about a certificate.
Attributes:
cert_file_name (string): Specifies the filename of the certificate.
This is unique to each certificate generated.
expiry_date (string): Specifies the date in epoch till when the
certificate is valid.
host_ips (list of string): Each certificate can be deployed to
multiple hosts. List of all hosts is returned after deployment.
mtype (TypeCertificateDetailsEnum): Specifies the type of the host
such as 'kSapHana', 'kSapOracle', etc. Specifies the host type of
host for generating and deploying a Certificate. 'kOther'
indicates it is any of the other hosts. 'kSapOracle' indicates it
is a SAP Oracle host. 'kSapHana' indicates it is a SAP HANA host.
"""
# Create a mapping from Model property names to API property names
_names = {
"cert_file_name":'certFileName',
"expiry_date":'expiryDate',
"host_ips":'hostIps',
"mtype":'type'
}
def __init__(self,
cert_file_name=None,
expiry_date=None,
host_ips=None,
mtype=None):
"""Constructor for the CertificateDetails class"""
# Initialize members of the class
self.cert_file_name = cert_file_name
self.expiry_date = expiry_date
self.host_ips = host_ips
self.mtype = mtype
@classmethod
def from_dictionary(cls,
dictionary):
"""Creates an instance of this model from a dictionary
Args:
dictionary (dictionary): A dictionary representation of the object as
obtained from the deserialization of the server's response. The keys
MUST match property names in the API description.
Returns:
object: An instance of this structure class.
"""
if dictionary is None:
return None
# Extract variables from the dictionary
cert_file_name = dictionary.get('certFileName')
expiry_date = dictionary.get('expiryDate')
host_ips = dictionary.get('hostIps')
mtype = dictionary.get('type')
# Return an object of this model
return cls(cert_file_name,
expiry_date,
host_ips,
mtype)
| class Certificatedetails(object):
"""Implementation of the 'CertificateDetails' model.
Specifies details about a certificate.
Attributes:
cert_file_name (string): Specifies the filename of the certificate.
This is unique to each certificate generated.
expiry_date (string): Specifies the date in epoch till when the
certificate is valid.
host_ips (list of string): Each certificate can be deployed to
multiple hosts. List of all hosts is returned after deployment.
mtype (TypeCertificateDetailsEnum): Specifies the type of the host
such as 'kSapHana', 'kSapOracle', etc. Specifies the host type of
host for generating and deploying a Certificate. 'kOther'
indicates it is any of the other hosts. 'kSapOracle' indicates it
is a SAP Oracle host. 'kSapHana' indicates it is a SAP HANA host.
"""
_names = {'cert_file_name': 'certFileName', 'expiry_date': 'expiryDate', 'host_ips': 'hostIps', 'mtype': 'type'}
def __init__(self, cert_file_name=None, expiry_date=None, host_ips=None, mtype=None):
"""Constructor for the CertificateDetails class"""
self.cert_file_name = cert_file_name
self.expiry_date = expiry_date
self.host_ips = host_ips
self.mtype = mtype
@classmethod
def from_dictionary(cls, dictionary):
"""Creates an instance of this model from a dictionary
Args:
dictionary (dictionary): A dictionary representation of the object as
obtained from the deserialization of the server's response. The keys
MUST match property names in the API description.
Returns:
object: An instance of this structure class.
"""
if dictionary is None:
return None
cert_file_name = dictionary.get('certFileName')
expiry_date = dictionary.get('expiryDate')
host_ips = dictionary.get('hostIps')
mtype = dictionary.get('type')
return cls(cert_file_name, expiry_date, host_ips, mtype) |
## Coding Conventions
# 'p' variables in p_<fun> are container() type
# possible scopes: package, global, functions, ....
global curr_scope
curr_scope = None
global scope_count
scope_count = 0
global temp_count
temp_count = 0
global label_count
label_count = 0
class ScopeTree:
def __init__(self, parent, scopeName=None):
self.children = []
self.parent = parent
self.symbolTable = {} #{"var": [type, size, value, offset]}
self.typeTable = self.parent.typeTable if parent is not None else {}
if scopeName is None:
global scope_count
self.identity = {"name":scope_count}
scope_count += 1
else:
self.identity = {"name":scopeName}
scope_count += 1
def insert(self, id, type, is_var=1, arg_list=None, size=None, ret_type=None, length=None, base=None):
self.symbolTable[id] = {"type":type, "base":base, "is_var":is_var,"size":size, "arg_list":arg_list, "ret_type":ret_type, "length":length}
def insert_type(self, new_type, Ntype):
self.typeTable[new_type] = Ntype
def makeChildren(self, childName=None):
child = ScopeTree(self, childName)
self.children.append(child)
return child
def lookup(self, id):
if id in self.symbolTable:
return self.symbolTable[id]
else:
if self.parent is None:
return None
# raise_general_error("undeclared variable: " + id)
return self.parent.lookup(id)
def new_temp(self):
global temp_count
temp_count += 1
return "$"+str(temp_count)
def new_label(self):
global label_count
label_count += 1
return "#"+str(label_count)
class container(object):
def __init__(self,type=None,value=None):
self.code = list()
self.place = None
self.extra = dict()
self.type = type
self.value = value
class sourcefile(object):
def __init__(self):
self.code = list()
self.package = str()
# for each import - { package:package_name,as:local_name,path:package_path }
self.imports = list()
class Builtin(object):
def __init__(self,name,width=None):
self.name = name
self.width = width
self.base = None
def __len__(self):
return self.width
def __repr__(self):
return self.name
class Int(Builtin):
def __init__(self):
super().__init__("int",4)
class Float(Builtin):
def __init__(self):
super().__init__("float",8)
class String(Builtin):
def __init__(self):
super().__init__("string")
class Byte(Builtin):
def __init__(self):
super().__init__("byte",1)
class Void(Builtin):
def __init__(self):
super().__init__("void")
class Error(Builtin):
def __init__(self):
super().__init__("error")
typeOp = set({"array","struct","pointer","function","interface","slice","map"})
class Derived(object):
def __init__(self,op,base,arg=None):
self.arg = dict(arg)
if op in typeOp:
self.op = op
if isinstance(base,(Derived,Builtin)) and (not isinstance(base,(Error,Void))) :
self.base = base
if op == "arr" :
self.name = "arr" + base.name
elif op == "struct" :
self.name = "struct" + arg["name"]
# i am saying use attributes for array - base, just like for func type
class Tac(object):
def __init__(self, op=None, arg1=None, arg2=None, dst=None, type=None):
self.type = type
self.op = op
self.arg1 = arg1
self.arg2 = arg2
self.dst = dst
class LBL(Tac):
'''Label Operation -> label :'''
def __init__(self, arg1, type="LBL"):
super().__init__(type,arg1=arg1)
def __str__(self):
return " ".join([str(self.arg1),":"])
class BOP(Tac):
'''Binary Operation -> dst = arg1 op arg2'''
def __init__(self, op, arg1, arg2, dst, type="BOP"):
super().__init__(op=op,arg1=arg1,arg2=arg2,dst=dst,type=type)
def __str__(self):
return " ".join([self.dst,"=",str(self.arg1),self.op,str(self.arg2)])
class UOP(Tac):
'''Unary Operation -> dst = op arg1'''
def __init__(self,op,arg1,type="UOP"):
super().__init__(op=op,arg1=arg1,type=type)
def __str__(self):
return " ".join([self.dst,"=",self.op,str(self.arg1)])
class ASN(Tac):
'''Assignment Operation -> dst = arg1'''
def __init__(self,arg1,dst,type="ASN"):
super().__init__(arg1=arg1,dst=dst,type=type)
def __str__(self):
return " ".join([self.dst,"=",str(self.arg1)])
class JMP(Tac):
'''Jump Operation -> goto dst'''
def __init__(self,dst,type="JMP"):
super().__init__(dst=dst,type=type)
def __str__(self):
return " ".join(["goto",self.dst])
# class JIF(Tac):
# '''Jump If -> if arg1 goto dst'''
# def __init__(self,arg1,dst,type="JIF"):
# super().__init__(arg1=arg1,dst=dst,type=type)
# def __str__(self):
# return " ".join(["if",str(self.arg1),"goto",self.dst])
class CBR(Tac):
'''Conditional Branch -> if arg1 op arg2 goto dst'''
def __init__(self, op, arg1, arg2, dst, type="CBR"):
super().__init__(op=op,arg1=arg1,arg2=arg2,dst=dst,type=type)
def __str__(self):
return " ".join(["if",str(self.arg1),self.op,str(self.arg2),"goto",self.dst])
# class BOP(Tac):
# '''Binary Operation
# dst = arg1 op arg2
# op can be :
# + : Add
# - : Subtract
# * : Multiply
# & : Bitwise AND
# | : Bitwise OR
# ^ : Bitwise XOR
# && : Logical AND
# || : Logical OR
# '''
# def __init__(self, type, op, arg1, arg2, dst):
# super().__init__(type,op,arg1,arg2,dst)
#
# class LOP(Tac):
# '''Logical Operation
# dst = arg1 op arg2
# op can be :
# < : Less Than
# > : Greater Than
# <= : Less Than Equal
# >= : Greater Than Equal
# == : Equals
# != : Not Equals
# '''
# def __init__(self, type, op, arg1, arg2, dst):
# super().__init__(type,op,arg1,arg2,dst)
#
# class SOP(Tac):
# '''Shift Operation
# dst = arg1 op arg2
# op can be :
# << : Bitwise Shift Left
# >> : Bitwise Shift Right
# '''
# def __init__(self, type, op, arg1, arg2, dst):
# super().__init__(type,op,arg1,arg2,dst)
#
# class DOP(Tac):
# '''Division Operation
# dst = arg1 op arg2
# op can be :
# / : Divide
# % : Remainder
# '''
# def __init__(self, type, op, arg1, arg2, dst):
# super().__init__(type,op,arg1,arg2,dst)
def raise_typerror(p, s=""):
print("Type error", s)
print(p)
exit(-1)
def raise_out_of_bounds_error(p, s="" ):
print("out of bounds error")
print(p)
print(s)
exit(-1)
def raise_general_error(s):
print(s)
exit(-1)
def extract_package(package_name):
return package_name.split("/")[-1]
def print_scopeTree(node,source_root,flag=False):
temp = node
if flag :
print("")
print("me:", temp.identity)
for i in temp.children:
print("child:", i.identity)
print("symbolTable:")
for var, val in temp.symbolTable.items():
print(var, val)
print("TypeTable:")
for new_type, Ntype in temp.typeTable.items():
print(new_type, Ntype)
for i in temp.children:
print_scopeTree(i,source_root)
ipkgs = ""
for pkg in source_root.imports :
ipkgs = (ipkgs +"package :"+pkg["package"] + " , as :" +pkg["as"]
+" , path:"+pkg["path"] + "\n")
three_ac = ""
for line in source_root.code :
three_ac = three_ac + str(line) + "\n"
return three_ac[:-1],ipkgs[:-1],source_root.package
| global curr_scope
curr_scope = None
global scope_count
scope_count = 0
global temp_count
temp_count = 0
global label_count
label_count = 0
class Scopetree:
def __init__(self, parent, scopeName=None):
self.children = []
self.parent = parent
self.symbolTable = {}
self.typeTable = self.parent.typeTable if parent is not None else {}
if scopeName is None:
global scope_count
self.identity = {'name': scope_count}
scope_count += 1
else:
self.identity = {'name': scopeName}
scope_count += 1
def insert(self, id, type, is_var=1, arg_list=None, size=None, ret_type=None, length=None, base=None):
self.symbolTable[id] = {'type': type, 'base': base, 'is_var': is_var, 'size': size, 'arg_list': arg_list, 'ret_type': ret_type, 'length': length}
def insert_type(self, new_type, Ntype):
self.typeTable[new_type] = Ntype
def make_children(self, childName=None):
child = scope_tree(self, childName)
self.children.append(child)
return child
def lookup(self, id):
if id in self.symbolTable:
return self.symbolTable[id]
else:
if self.parent is None:
return None
return self.parent.lookup(id)
def new_temp(self):
global temp_count
temp_count += 1
return '$' + str(temp_count)
def new_label(self):
global label_count
label_count += 1
return '#' + str(label_count)
class Container(object):
def __init__(self, type=None, value=None):
self.code = list()
self.place = None
self.extra = dict()
self.type = type
self.value = value
class Sourcefile(object):
def __init__(self):
self.code = list()
self.package = str()
self.imports = list()
class Builtin(object):
def __init__(self, name, width=None):
self.name = name
self.width = width
self.base = None
def __len__(self):
return self.width
def __repr__(self):
return self.name
class Int(Builtin):
def __init__(self):
super().__init__('int', 4)
class Float(Builtin):
def __init__(self):
super().__init__('float', 8)
class String(Builtin):
def __init__(self):
super().__init__('string')
class Byte(Builtin):
def __init__(self):
super().__init__('byte', 1)
class Void(Builtin):
def __init__(self):
super().__init__('void')
class Error(Builtin):
def __init__(self):
super().__init__('error')
type_op = set({'array', 'struct', 'pointer', 'function', 'interface', 'slice', 'map'})
class Derived(object):
def __init__(self, op, base, arg=None):
self.arg = dict(arg)
if op in typeOp:
self.op = op
if isinstance(base, (Derived, Builtin)) and (not isinstance(base, (Error, Void))):
self.base = base
if op == 'arr':
self.name = 'arr' + base.name
elif op == 'struct':
self.name = 'struct' + arg['name']
class Tac(object):
def __init__(self, op=None, arg1=None, arg2=None, dst=None, type=None):
self.type = type
self.op = op
self.arg1 = arg1
self.arg2 = arg2
self.dst = dst
class Lbl(Tac):
"""Label Operation -> label :"""
def __init__(self, arg1, type='LBL'):
super().__init__(type, arg1=arg1)
def __str__(self):
return ' '.join([str(self.arg1), ':'])
class Bop(Tac):
"""Binary Operation -> dst = arg1 op arg2"""
def __init__(self, op, arg1, arg2, dst, type='BOP'):
super().__init__(op=op, arg1=arg1, arg2=arg2, dst=dst, type=type)
def __str__(self):
return ' '.join([self.dst, '=', str(self.arg1), self.op, str(self.arg2)])
class Uop(Tac):
"""Unary Operation -> dst = op arg1"""
def __init__(self, op, arg1, type='UOP'):
super().__init__(op=op, arg1=arg1, type=type)
def __str__(self):
return ' '.join([self.dst, '=', self.op, str(self.arg1)])
class Asn(Tac):
"""Assignment Operation -> dst = arg1"""
def __init__(self, arg1, dst, type='ASN'):
super().__init__(arg1=arg1, dst=dst, type=type)
def __str__(self):
return ' '.join([self.dst, '=', str(self.arg1)])
class Jmp(Tac):
"""Jump Operation -> goto dst"""
def __init__(self, dst, type='JMP'):
super().__init__(dst=dst, type=type)
def __str__(self):
return ' '.join(['goto', self.dst])
class Cbr(Tac):
"""Conditional Branch -> if arg1 op arg2 goto dst"""
def __init__(self, op, arg1, arg2, dst, type='CBR'):
super().__init__(op=op, arg1=arg1, arg2=arg2, dst=dst, type=type)
def __str__(self):
return ' '.join(['if', str(self.arg1), self.op, str(self.arg2), 'goto', self.dst])
def raise_typerror(p, s=''):
print('Type error', s)
print(p)
exit(-1)
def raise_out_of_bounds_error(p, s=''):
print('out of bounds error')
print(p)
print(s)
exit(-1)
def raise_general_error(s):
print(s)
exit(-1)
def extract_package(package_name):
return package_name.split('/')[-1]
def print_scope_tree(node, source_root, flag=False):
temp = node
if flag:
print('')
print('me:', temp.identity)
for i in temp.children:
print('child:', i.identity)
print('symbolTable:')
for (var, val) in temp.symbolTable.items():
print(var, val)
print('TypeTable:')
for (new_type, ntype) in temp.typeTable.items():
print(new_type, Ntype)
for i in temp.children:
print_scope_tree(i, source_root)
ipkgs = ''
for pkg in source_root.imports:
ipkgs = ipkgs + 'package :' + pkg['package'] + ' , as :' + pkg['as'] + ' , path:' + pkg['path'] + '\n'
three_ac = ''
for line in source_root.code:
three_ac = three_ac + str(line) + '\n'
return (three_ac[:-1], ipkgs[:-1], source_root.package) |
test=int(input())
for y in range(test):
k,dig0,dig1=input().split()
k,dig0,dig1=int(k),int(dig0),int(dig1)
sum1=dig0+dig1
for i in range(3,k+2):
y=sum1%10
sum1+=y
if(y==2):
ter1=((k-i)//4)
ter1*=20
sum1+=ter1
ter=k-i
if(ter%4==3):
sum1+=18
elif(ter%4==2):
sum1+=12
elif(ter%4==1):
sum1+=4
break
if(y==0):
break
if(sum1%3==0):
print("YES")
else:
print("NO") | test = int(input())
for y in range(test):
(k, dig0, dig1) = input().split()
(k, dig0, dig1) = (int(k), int(dig0), int(dig1))
sum1 = dig0 + dig1
for i in range(3, k + 2):
y = sum1 % 10
sum1 += y
if y == 2:
ter1 = (k - i) // 4
ter1 *= 20
sum1 += ter1
ter = k - i
if ter % 4 == 3:
sum1 += 18
elif ter % 4 == 2:
sum1 += 12
elif ter % 4 == 1:
sum1 += 4
break
if y == 0:
break
if sum1 % 3 == 0:
print('YES')
else:
print('NO') |
class Solution:
def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]:
h = []
for i, li in enumerate(mat):
l = self.countSoider(li)
heapq.heappush(h, (l, i))
ans = []
for _ in range(k):
ans.append(heapq.heappop(h)[1])
return ans
def countSoider(self, li):
l = 0
r = len(li)
if li[l] == 0:
return 0
if li[r - 1] == 1:
return r
while l < r:
mid = (l + r - 1) //2
if li[mid] == 0:
if li[mid - 1] == 1:
return mid
else:
r = mid - 1
else:
if li[mid + 1] == 0:
return mid + 1
else:
l = mid + 1
| class Solution:
def k_weakest_rows(self, mat: List[List[int]], k: int) -> List[int]:
h = []
for (i, li) in enumerate(mat):
l = self.countSoider(li)
heapq.heappush(h, (l, i))
ans = []
for _ in range(k):
ans.append(heapq.heappop(h)[1])
return ans
def count_soider(self, li):
l = 0
r = len(li)
if li[l] == 0:
return 0
if li[r - 1] == 1:
return r
while l < r:
mid = (l + r - 1) // 2
if li[mid] == 0:
if li[mid - 1] == 1:
return mid
else:
r = mid - 1
elif li[mid + 1] == 0:
return mid + 1
else:
l = mid + 1 |
# This file is needs to be multi-lingual in both Python and POSIX
# shell which "execfile" or "source" it respectively.
# This file should define a variable VERSION which we use as the
# debugger version number.
VERSION='0.3.6'
| version = '0.3.6' |
class Solution(object):
def findReplaceString(self, S, indexes, sources, targets):
"""
:type S: str
:type indexes: List[int]
:type sources: List[str]
:type targets: List[str]
:rtype: str
"""
finds = [S[idx:idx + len(source)] == source for idx, source in zip(indexes, sources)]
diff = 0
S = list(S)
for idx, find, source, target in sorted(zip(indexes, finds, sources, targets)):
if find:
S[idx + diff : idx + diff + len(source)] = list(target)
diff += len(target) - len(source)
return ''.join(S) | class Solution(object):
def find_replace_string(self, S, indexes, sources, targets):
"""
:type S: str
:type indexes: List[int]
:type sources: List[str]
:type targets: List[str]
:rtype: str
"""
finds = [S[idx:idx + len(source)] == source for (idx, source) in zip(indexes, sources)]
diff = 0
s = list(S)
for (idx, find, source, target) in sorted(zip(indexes, finds, sources, targets)):
if find:
S[idx + diff:idx + diff + len(source)] = list(target)
diff += len(target) - len(source)
return ''.join(S) |
# -*- coding: utf-8 -*-
"""
bandwidth
This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ).
"""
class CallEngineModifyConferenceRequest(object):
"""Implementation of the 'CallEngineModifyConferenceRequest' model.
TODO: type model description here.
Attributes:
status (StatusEnum): TODO: type description here.
redirect_url (string): TODO: type description here.
redirect_fallback_url (string): TODO: type description here.
redirect_method (RedirectMethodEnum): TODO: type description here.
redirect_fallback_method (RedirectFallbackMethodEnum): TODO: type
description here.
username (string): TODO: type description here.
password (string): TODO: type description here.
fallback_username (string): TODO: type description here.
fallback_password (string): TODO: type description here.
"""
# Create a mapping from Model property names to API property names
_names = {
"redirect_url": 'redirectUrl',
"status": 'status',
"redirect_fallback_url": 'redirectFallbackUrl',
"redirect_method": 'redirectMethod',
"redirect_fallback_method": 'redirectFallbackMethod',
"username": 'username',
"password": 'password',
"fallback_username": 'fallbackUsername',
"fallback_password": 'fallbackPassword'
}
def __init__(self,
redirect_url=None,
status=None,
redirect_fallback_url=None,
redirect_method=None,
redirect_fallback_method=None,
username=None,
password=None,
fallback_username=None,
fallback_password=None):
"""Constructor for the CallEngineModifyConferenceRequest class"""
# Initialize members of the class
self.status = status
self.redirect_url = redirect_url
self.redirect_fallback_url = redirect_fallback_url
self.redirect_method = redirect_method
self.redirect_fallback_method = redirect_fallback_method
self.username = username
self.password = password
self.fallback_username = fallback_username
self.fallback_password = fallback_password
@classmethod
def from_dictionary(cls,
dictionary):
"""Creates an instance of this model from a dictionary
Args:
dictionary (dictionary): A dictionary representation of the object
as obtained from the deserialization of the server's response. The
keys MUST match property names in the API description.
Returns:
object: An instance of this structure class.
"""
if dictionary is None:
return None
# Extract variables from the dictionary
redirect_url = dictionary.get('redirectUrl')
status = dictionary.get('status')
redirect_fallback_url = dictionary.get('redirectFallbackUrl')
redirect_method = dictionary.get('redirectMethod')
redirect_fallback_method = dictionary.get('redirectFallbackMethod')
username = dictionary.get('username')
password = dictionary.get('password')
fallback_username = dictionary.get('fallbackUsername')
fallback_password = dictionary.get('fallbackPassword')
# Return an object of this model
return cls(redirect_url,
status,
redirect_fallback_url,
redirect_method,
redirect_fallback_method,
username,
password,
fallback_username,
fallback_password)
| """
bandwidth
This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ).
"""
class Callenginemodifyconferencerequest(object):
"""Implementation of the 'CallEngineModifyConferenceRequest' model.
TODO: type model description here.
Attributes:
status (StatusEnum): TODO: type description here.
redirect_url (string): TODO: type description here.
redirect_fallback_url (string): TODO: type description here.
redirect_method (RedirectMethodEnum): TODO: type description here.
redirect_fallback_method (RedirectFallbackMethodEnum): TODO: type
description here.
username (string): TODO: type description here.
password (string): TODO: type description here.
fallback_username (string): TODO: type description here.
fallback_password (string): TODO: type description here.
"""
_names = {'redirect_url': 'redirectUrl', 'status': 'status', 'redirect_fallback_url': 'redirectFallbackUrl', 'redirect_method': 'redirectMethod', 'redirect_fallback_method': 'redirectFallbackMethod', 'username': 'username', 'password': 'password', 'fallback_username': 'fallbackUsername', 'fallback_password': 'fallbackPassword'}
def __init__(self, redirect_url=None, status=None, redirect_fallback_url=None, redirect_method=None, redirect_fallback_method=None, username=None, password=None, fallback_username=None, fallback_password=None):
"""Constructor for the CallEngineModifyConferenceRequest class"""
self.status = status
self.redirect_url = redirect_url
self.redirect_fallback_url = redirect_fallback_url
self.redirect_method = redirect_method
self.redirect_fallback_method = redirect_fallback_method
self.username = username
self.password = password
self.fallback_username = fallback_username
self.fallback_password = fallback_password
@classmethod
def from_dictionary(cls, dictionary):
"""Creates an instance of this model from a dictionary
Args:
dictionary (dictionary): A dictionary representation of the object
as obtained from the deserialization of the server's response. The
keys MUST match property names in the API description.
Returns:
object: An instance of this structure class.
"""
if dictionary is None:
return None
redirect_url = dictionary.get('redirectUrl')
status = dictionary.get('status')
redirect_fallback_url = dictionary.get('redirectFallbackUrl')
redirect_method = dictionary.get('redirectMethod')
redirect_fallback_method = dictionary.get('redirectFallbackMethod')
username = dictionary.get('username')
password = dictionary.get('password')
fallback_username = dictionary.get('fallbackUsername')
fallback_password = dictionary.get('fallbackPassword')
return cls(redirect_url, status, redirect_fallback_url, redirect_method, redirect_fallback_method, username, password, fallback_username, fallback_password) |
"""
@name: PyHouse/src/Modules/Drivers/test/xml_drivers.py
@author: D. Brian Kimmel
@contact: D.BrianKimmel@gmail.com
@copyright: (c) 2014-2016 by D. Brian Kimmel
@license: MIT License
@note: Created on Nov 9, 2014
@Summary:
"""
DRIVERS_XML = """
"""
DRIVERS_XSD = """
?xml version="1.0" encoding="UTF-8"?>
<xs:schema
xmlns:xs="http://www.w3.org/2001/XMLSchema"
targetNamespace="http://PyHouse.org"
xmlns="http://PyHouse.org"
elementFormDefault="qualified"
attributeFormDefault="unqualified">
</xs:schema>
-"""
# ## END DBK
| """
@name: PyHouse/src/Modules/Drivers/test/xml_drivers.py
@author: D. Brian Kimmel
@contact: D.BrianKimmel@gmail.com
@copyright: (c) 2014-2016 by D. Brian Kimmel
@license: MIT License
@note: Created on Nov 9, 2014
@Summary:
"""
drivers_xml = '\n'
drivers_xsd = '\n?xml version="1.0" encoding="UTF-8"?>\n<xs:schema\n xmlns:xs="http://www.w3.org/2001/XMLSchema"\n targetNamespace="http://PyHouse.org"\n xmlns="http://PyHouse.org"\n elementFormDefault="qualified"\n attributeFormDefault="unqualified">\n\n\n</xs:schema>\n-' |
tmp = 0
monday_temperatures = [9.1, 8.8, 7.5]
tmp = monday_temperatures.__getitem__(1)
tmp = monday_temperatures[1]
print(tmp) | tmp = 0
monday_temperatures = [9.1, 8.8, 7.5]
tmp = monday_temperatures.__getitem__(1)
tmp = monday_temperatures[1]
print(tmp) |
'''
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police.
Input: nums = [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4.
'''
class Solution:
def rob(self, nums: List[int]) -> int:
#handle base condition
if(len(nums) == 0):
return 0
if(len(nums) == 1):
return(nums[0])
if(len(nums) == 2):
return(max(nums[0],nums[1]))
dp = [0 for _ in range(len(nums))]
dp[0] = nums[0]
dp[1] = max(nums[0],nums[1])
for i in range(2,len(nums)):
dp[i] = max(nums[i]+dp[i-2],dp[i-1])
return(dp[-1])
| """
You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and it will automatically contact the police if two adjacent houses were broken into on the same night.
Given an integer array nums representing the amount of money of each house, return the maximum amount of money you can rob tonight without alerting the police.
Input: nums = [1,2,3,1]
Output: 4
Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).
Total amount you can rob = 1 + 3 = 4.
"""
class Solution:
def rob(self, nums: List[int]) -> int:
if len(nums) == 0:
return 0
if len(nums) == 1:
return nums[0]
if len(nums) == 2:
return max(nums[0], nums[1])
dp = [0 for _ in range(len(nums))]
dp[0] = nums[0]
dp[1] = max(nums[0], nums[1])
for i in range(2, len(nums)):
dp[i] = max(nums[i] + dp[i - 2], dp[i - 1])
return dp[-1] |
class Map:
def __init__(self, filepath):
#first index will be y, second is x
self.data = list()
with open(filepath, "r") as f:
for line in f:
line = line.strip()
self.data.append(line)
self.width = len(self.data[0])
self.height = len(self.data)
#Check that we loaded the map with the same width everywhere
assert all([self.width == len(i) for i in self.data])
def check(self, x, y):
if y >= self.height:
return None
return self.data[y][x%self.width] == "#"
def print(self):
for line in self.data:
print("".join(line))
class Sled:
def __init__(self, map_):
self.map = map_
def go(self, xpos, ypos, step_x, step_y):
count = 0
status = self.map.check(xpos,ypos)
while status is not None:
xpos += step_x
ypos += step_y
status = self.map.check(xpos,ypos)
if status:
count += 1
return count
| class Map:
def __init__(self, filepath):
self.data = list()
with open(filepath, 'r') as f:
for line in f:
line = line.strip()
self.data.append(line)
self.width = len(self.data[0])
self.height = len(self.data)
assert all([self.width == len(i) for i in self.data])
def check(self, x, y):
if y >= self.height:
return None
return self.data[y][x % self.width] == '#'
def print(self):
for line in self.data:
print(''.join(line))
class Sled:
def __init__(self, map_):
self.map = map_
def go(self, xpos, ypos, step_x, step_y):
count = 0
status = self.map.check(xpos, ypos)
while status is not None:
xpos += step_x
ypos += step_y
status = self.map.check(xpos, ypos)
if status:
count += 1
return count |
# https://www.hackerrank.com/challenges/s10-geometric-distribution-1/problem
# Enter your code here. Read input from STDIN. Print output to STDOUT
x,y=map(int,input().split())
z=int(input())
p=x/y
q=1-p
print(round((q**(z-1))*p,3)) | (x, y) = map(int, input().split())
z = int(input())
p = x / y
q = 1 - p
print(round(q ** (z - 1) * p, 3)) |
"""
Used for passing custom exceptions form the configuration_service to the rest of the application.
"""
class ConfigurationError(Exception):
"""Raised when error occurred while loading or saving properties"""
pass
| """
Used for passing custom exceptions form the configuration_service to the rest of the application.
"""
class Configurationerror(Exception):
"""Raised when error occurred while loading or saving properties"""
pass |
MP3_PREVIEW = "mp3_preview"
OGG_PREVIEW = "ogg_preview"
OGG_RELEASE = "ogg_release"
| mp3_preview = 'mp3_preview'
ogg_preview = 'ogg_preview'
ogg_release = 'ogg_release' |
MAJOR_COLORS = ['White', 'Red', 'Black', 'Yellow', 'Violet']
MINOR_COLORS = ["Blue", "Orange", "Green", "Brown", "Slate"]
def print_color_code_mapping():
print('{:15} {:15} {:5} \n'.format('Major Color', 'Minor Color', 'Pair No.'))
for major_color_index, major_color in enumerate(MAJOR_COLORS):
for minor_color_index, minor_color in enumerate(MINOR_COLORS):
print('{:15} {:15} {:5} \n'.format(major_color, minor_color, major_color_index * len(MINOR_COLORS) + minor_color_index + 1))
def get_color_from_pair_number(pair_number):
zero_based_pair_number = pair_number - 1
major_index = zero_based_pair_number // len(MINOR_COLORS)
if major_index >= len(MAJOR_COLORS):
raise Exception('Major index out of range')
minor_index = zero_based_pair_number % len(MINOR_COLORS)
if minor_index >= len(MINOR_COLORS):
raise Exception('Minor index out of range')
return MAJOR_COLORS[major_index], MINOR_COLORS[minor_index]
def get_pair_number_from_color(major_color, minor_color):
try:
major_index = MAJOR_COLORS.index(major_color)
except ValueError:
raise Exception('Major index out of range')
try:
minor_index = MINOR_COLORS.index(minor_color)
except ValueError:
raise Exception('Minor index out of range')
return major_index * len(MINOR_COLORS) + minor_index + 1
| major_colors = ['White', 'Red', 'Black', 'Yellow', 'Violet']
minor_colors = ['Blue', 'Orange', 'Green', 'Brown', 'Slate']
def print_color_code_mapping():
print('{:15} {:15} {:5} \n'.format('Major Color', 'Minor Color', 'Pair No.'))
for (major_color_index, major_color) in enumerate(MAJOR_COLORS):
for (minor_color_index, minor_color) in enumerate(MINOR_COLORS):
print('{:15} {:15} {:5} \n'.format(major_color, minor_color, major_color_index * len(MINOR_COLORS) + minor_color_index + 1))
def get_color_from_pair_number(pair_number):
zero_based_pair_number = pair_number - 1
major_index = zero_based_pair_number // len(MINOR_COLORS)
if major_index >= len(MAJOR_COLORS):
raise exception('Major index out of range')
minor_index = zero_based_pair_number % len(MINOR_COLORS)
if minor_index >= len(MINOR_COLORS):
raise exception('Minor index out of range')
return (MAJOR_COLORS[major_index], MINOR_COLORS[minor_index])
def get_pair_number_from_color(major_color, minor_color):
try:
major_index = MAJOR_COLORS.index(major_color)
except ValueError:
raise exception('Major index out of range')
try:
minor_index = MINOR_COLORS.index(minor_color)
except ValueError:
raise exception('Minor index out of range')
return major_index * len(MINOR_COLORS) + minor_index + 1 |
# 88. Merge Sorted Array
# ttungl@gmail.com
# Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.
# Note:
# You may assume that nums1 has enough space (size that is greater or equal to m + n)
# to hold additional elements from nums2. The number of elements initialized in nums1 and nums2 are m and n respectively.
class Solution(object):
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: void Do not return anything, modify nums1 in-place instead.
"""
# sol 1:
# time O(n)
# runtime: 42ms
while n > 0:
if m <= 0 or nums2[n-1] >= nums1[m-1]:
nums1[m+n-1] = nums2[n-1]
n -= 1
else: # m > 0 or nums2[n-1] < nums1[m-1]
nums1[m+n-1] = nums1[m-1]
m -= 1
# sol 2:
# time O(n logn)
# runtime: 38ms
nums1[m:] = nums2[:n]
nums1.sort()
| class Solution(object):
def merge(self, nums1, m, nums2, n):
"""
:type nums1: List[int]
:type m: int
:type nums2: List[int]
:type n: int
:rtype: void Do not return anything, modify nums1 in-place instead.
"""
while n > 0:
if m <= 0 or nums2[n - 1] >= nums1[m - 1]:
nums1[m + n - 1] = nums2[n - 1]
n -= 1
else:
nums1[m + n - 1] = nums1[m - 1]
m -= 1
nums1[m:] = nums2[:n]
nums1.sort() |
"""
Happy Cobra - Marirs
Skeleton of a Login & Registration system
MIT License
"""
| """
Happy Cobra - Marirs
Skeleton of a Login & Registration system
MIT License
""" |
"""
Your job is to create a class Dictionary which you can add words to and their entries. Example:
d = Dictionary()
d.new_entry('Apple', 'A fruit that grows on trees')
print(d.look('Apple'))
A fruit that grows on trees
print(d.look('Banana'))
Can't find entry for Banana
"""
class Dictionary:
def __init__(self):
self.dict_ = {}
def new_entry(self, key, value):
new = self.dict_.update([(key, value)])
return new
def look(self, key):
look = self.dict_.get(key, "Can't find entry for Banana")
return look
d = Dictionary()
d.new_entry('Apple', 'A fruit that grows on trees')
print(d.look('Apple'))
print(d.look('Banana'))
| """
Your job is to create a class Dictionary which you can add words to and their entries. Example:
d = Dictionary()
d.new_entry('Apple', 'A fruit that grows on trees')
print(d.look('Apple'))
A fruit that grows on trees
print(d.look('Banana'))
Can't find entry for Banana
"""
class Dictionary:
def __init__(self):
self.dict_ = {}
def new_entry(self, key, value):
new = self.dict_.update([(key, value)])
return new
def look(self, key):
look = self.dict_.get(key, "Can't find entry for Banana")
return look
d = dictionary()
d.new_entry('Apple', 'A fruit that grows on trees')
print(d.look('Apple'))
print(d.look('Banana')) |
CRITICAL_MARK_BEGIN = '<!-- BEGIN: django-critical css ('
CRITICAL_MARK_END = ') END: django-critical css -->'
CRITICAL_ASYNC_MARK = '<!-- django-critical async snippet -->'
CRITICAL_KEY_MARK_BEGIN = '<!-- BEGIN: django-critical key ('
CRITICAL_KEY_MARK_END = ') END: django-critical key -->'
| critical_mark_begin = '<!-- BEGIN: django-critical css ('
critical_mark_end = ') END: django-critical css -->'
critical_async_mark = '<!-- django-critical async snippet -->'
critical_key_mark_begin = '<!-- BEGIN: django-critical key ('
critical_key_mark_end = ') END: django-critical key -->' |
l=[]
z=[]
def selection_sort(l):
for i in range(0,5):
MIN=min(l)
z.append(MIN)
l.remove(MIN)
return z
print("Enter Integer list of 5 values")
for i in range(0, 5):
x = int(input())
l.append(x)
print("List is: ",l)
print("Sorted list is: ",selection_sort(l))
| l = []
z = []
def selection_sort(l):
for i in range(0, 5):
min = min(l)
z.append(MIN)
l.remove(MIN)
return z
print('Enter Integer list of 5 values')
for i in range(0, 5):
x = int(input())
l.append(x)
print('List is: ', l)
print('Sorted list is: ', selection_sort(l)) |
load("//tools/jest:jest.bzl", _jest_test = "jest_test")
load("//tools/go:go.bzl", _test_go_fmt = "test_go_fmt")
load("@io_bazel_rules_go//go:def.bzl", _go_binary = "go_binary", _go_library = "go_library", _go_test = "go_test")
load("@npm//@bazel/typescript:index.bzl", _ts_config = "ts_config", _ts_project = "ts_project")
load("@npm//eslint:index.bzl", _eslint_test = "eslint_test")
load("@build_bazel_rules_nodejs//:index.bzl", "js_library", _nodejs_binary = "nodejs_binary")
def nodejs_binary(**kwargs):
_nodejs_binary(**kwargs)
def ts_config(**kwargs):
_ts_config(**kwargs)
def jest_test(project_deps = [], deps = [], **kwargs):
_jest_test(
deps = deps + [x + "_js" for x in project_deps],
**kwargs
)
def ts_lint(name, srcs = [], tags = [], data = [], **kwargs):
targets = srcs + data
eslint_test(
name = name,
data = targets,
tags = tags + ["+formatting"],
args = ["$(location %s)" % x for x in targets],
**kwargs
)
def ts_project(name, project_deps = [], deps = [], srcs = [], incremental = None, composite = False, tsconfig = "//:tsconfig", declaration = False, preserve_jsx = None, **kwargs):
__ts_project(
name = name + "_ts",
deps = deps + [dep + "_ts" for dep in project_deps],
srcs = srcs,
composite = composite,
declaration = declaration,
tsconfig = tsconfig,
preserve_jsx = preserve_jsx,
incremental = incremental,
**kwargs
)
js_library(
name = name + "_js",
deps = [dep + "_js" for dep in project_deps] + deps,
srcs = [src[:src.rfind(".")] + ".js" for src in srcs],
**kwargs
)
def __ts_project(name, tags = [], deps = [], srcs = [], tsconfig = "//:tsconfig", **kwargs):
_ts_project(
name = name,
tsc = "@npm//ttypescript/bin:ttsc",
srcs = srcs,
deps = deps + ["@npm//typescript-transform-paths"],
tags = tags,
tsconfig = tsconfig,
**kwargs
)
ts_lint(name = name + "_lint", data = srcs, tags = tags)
def eslint_test(name = None, data = [], args = [], **kwargs):
_eslint_test(
name = name,
data = data + [
"//:.prettierrc.json",
"//:.gitignore",
"//:.editorconfig",
"//:.eslintrc.json",
"@npm//eslint-plugin-prettier",
"@npm//@typescript-eslint/parser",
"@npm//@typescript-eslint/eslint-plugin",
"@npm//eslint-config-prettier",
],
args = args + ["--ignore-path", "$(location //:.gitignore)"] +
["$(location " + x + ")" for x in data],
)
def go_binary(name = None, importpath = None, deps = [], **kwargs):
_go_binary(
name = name,
deps = deps,
importpath = importpath,
**kwargs
)
_test_go_fmt(
name = name + "_fmt",
**kwargs
)
def go_test(name = None, importpath = None, deps = [], **kwargs):
_go_test(
name = name,
deps = deps,
importpath = importpath,
**kwargs
)
_test_go_fmt(
name = name + "_fmt",
**kwargs
)
def go_library(name = None, importpath = None, deps = [], **kwargs):
_go_library(
name = name,
deps = deps,
importpath = importpath,
**kwargs
)
_test_go_fmt(
name = name + "_fmt",
**kwargs
)
| load('//tools/jest:jest.bzl', _jest_test='jest_test')
load('//tools/go:go.bzl', _test_go_fmt='test_go_fmt')
load('@io_bazel_rules_go//go:def.bzl', _go_binary='go_binary', _go_library='go_library', _go_test='go_test')
load('@npm//@bazel/typescript:index.bzl', _ts_config='ts_config', _ts_project='ts_project')
load('@npm//eslint:index.bzl', _eslint_test='eslint_test')
load('@build_bazel_rules_nodejs//:index.bzl', 'js_library', _nodejs_binary='nodejs_binary')
def nodejs_binary(**kwargs):
_nodejs_binary(**kwargs)
def ts_config(**kwargs):
_ts_config(**kwargs)
def jest_test(project_deps=[], deps=[], **kwargs):
_jest_test(deps=deps + [x + '_js' for x in project_deps], **kwargs)
def ts_lint(name, srcs=[], tags=[], data=[], **kwargs):
targets = srcs + data
eslint_test(name=name, data=targets, tags=tags + ['+formatting'], args=['$(location %s)' % x for x in targets], **kwargs)
def ts_project(name, project_deps=[], deps=[], srcs=[], incremental=None, composite=False, tsconfig='//:tsconfig', declaration=False, preserve_jsx=None, **kwargs):
__ts_project(name=name + '_ts', deps=deps + [dep + '_ts' for dep in project_deps], srcs=srcs, composite=composite, declaration=declaration, tsconfig=tsconfig, preserve_jsx=preserve_jsx, incremental=incremental, **kwargs)
js_library(name=name + '_js', deps=[dep + '_js' for dep in project_deps] + deps, srcs=[src[:src.rfind('.')] + '.js' for src in srcs], **kwargs)
def __ts_project(name, tags=[], deps=[], srcs=[], tsconfig='//:tsconfig', **kwargs):
_ts_project(name=name, tsc='@npm//ttypescript/bin:ttsc', srcs=srcs, deps=deps + ['@npm//typescript-transform-paths'], tags=tags, tsconfig=tsconfig, **kwargs)
ts_lint(name=name + '_lint', data=srcs, tags=tags)
def eslint_test(name=None, data=[], args=[], **kwargs):
_eslint_test(name=name, data=data + ['//:.prettierrc.json', '//:.gitignore', '//:.editorconfig', '//:.eslintrc.json', '@npm//eslint-plugin-prettier', '@npm//@typescript-eslint/parser', '@npm//@typescript-eslint/eslint-plugin', '@npm//eslint-config-prettier'], args=args + ['--ignore-path', '$(location //:.gitignore)'] + ['$(location ' + x + ')' for x in data])
def go_binary(name=None, importpath=None, deps=[], **kwargs):
_go_binary(name=name, deps=deps, importpath=importpath, **kwargs)
_test_go_fmt(name=name + '_fmt', **kwargs)
def go_test(name=None, importpath=None, deps=[], **kwargs):
_go_test(name=name, deps=deps, importpath=importpath, **kwargs)
_test_go_fmt(name=name + '_fmt', **kwargs)
def go_library(name=None, importpath=None, deps=[], **kwargs):
_go_library(name=name, deps=deps, importpath=importpath, **kwargs)
_test_go_fmt(name=name + '_fmt', **kwargs) |
antenna = int(input())
eyes = int(input())
if antenna>=3 and eyes<=4:
print("TroyMartian")
if antenna<=6 and eyes>=2:
print("VladSaturnian")
if antenna<=2 and eyes<= 3:
print("GraemeMercurian")
| antenna = int(input())
eyes = int(input())
if antenna >= 3 and eyes <= 4:
print('TroyMartian')
if antenna <= 6 and eyes >= 2:
print('VladSaturnian')
if antenna <= 2 and eyes <= 3:
print('GraemeMercurian') |
# test builtin abs function with float args
for val in (
"1.0",
"-1.0",
"0.0",
"-0.0",
"nan",
"-nan",
"inf",
"-inf",
):
print(val, abs(float(val)))
| for val in ('1.0', '-1.0', '0.0', '-0.0', 'nan', '-nan', 'inf', '-inf'):
print(val, abs(float(val))) |
# Big O complexity
# O(log2(n))
# works only on sorted array
# recursive
def binary_search_recursive(arr, arg, left, right):
if right >= left:
middle = left + (right - left) // 2
if arr[middle] == arg:
return middle
elif arr[middle] > arg:
return binary_search_recursive(arr, arg, left, middle - 1)
else:
return binary_search_recursive(arr, arg, middle + 1, right)
else:
return -1
# iterative
def binary_search(arr, arg, left, right):
while left <= right:
mid = left + (right - left) // 2
if arr[mid] == arg:
return mid
elif arr[mid] < arg:
left = mid + 1
else:
right = mid - 1
return -1
| def binary_search_recursive(arr, arg, left, right):
if right >= left:
middle = left + (right - left) // 2
if arr[middle] == arg:
return middle
elif arr[middle] > arg:
return binary_search_recursive(arr, arg, left, middle - 1)
else:
return binary_search_recursive(arr, arg, middle + 1, right)
else:
return -1
def binary_search(arr, arg, left, right):
while left <= right:
mid = left + (right - left) // 2
if arr[mid] == arg:
return mid
elif arr[mid] < arg:
left = mid + 1
else:
right = mid - 1
return -1 |
# -*- coding: utf-8 -*-
"""
Created on Sat Mar 26 19:20:16 2022
@author: ARYAMAN
"""
word_list =[]
with open("corncob_caps.txt", "r") as words:
lines = words.readlines()
final_list = []
for l in lines:
final_list.append(l.replace("\n","")) | """
Created on Sat Mar 26 19:20:16 2022
@author: ARYAMAN
"""
word_list = []
with open('corncob_caps.txt', 'r') as words:
lines = words.readlines()
final_list = []
for l in lines:
final_list.append(l.replace('\n', '')) |
s = input("s: ")
t = input("t: ")
if s == t:
print("Same")
else:
print("Different") | s = input('s: ')
t = input('t: ')
if s == t:
print('Same')
else:
print('Different') |
'''Deoxyribonucleic acid (DNA) is a chemical found in the nucleus
of cells and carries the "instructions" for the development and functioning of living organisms.
If you want to know more http://en.wikipedia.org/wiki/DNA
In DNA strings, symbols "A" and "T" are complements of each other,
as "C" and "G". You have function with one side of the DNA
(string, except for Haskell); you need to get the other complementary side.
DNA strand is never empty or there is no DNA at all (again, except for Haskell).'''
#ATTGC >>>> TAACG
def DNA_strand(dna):
Dna_dict = {'A': 'T', 'T': 'A', 'G': 'C', 'C': 'G'}
return ''.join(Dna_dict[letter] for letter in dna if letter in Dna_dict.keys())
'''also we can simply do : return dna.translate(str.maketrans('ATTGC', 'TAACG'))'''
| """Deoxyribonucleic acid (DNA) is a chemical found in the nucleus
of cells and carries the "instructions" for the development and functioning of living organisms.
If you want to know more http://en.wikipedia.org/wiki/DNA
In DNA strings, symbols "A" and "T" are complements of each other,
as "C" and "G". You have function with one side of the DNA
(string, except for Haskell); you need to get the other complementary side.
DNA strand is never empty or there is no DNA at all (again, except for Haskell)."""
def dna_strand(dna):
dna_dict = {'A': 'T', 'T': 'A', 'G': 'C', 'C': 'G'}
return ''.join((Dna_dict[letter] for letter in dna if letter in Dna_dict.keys()))
"also we can simply do : return dna.translate(str.maketrans('ATTGC', 'TAACG'))" |
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
#
# @name : E-ntel - Email Information Gathering
# @url : http://github.com/CybernetiX-S3C
# @author : John Modica (CybernetiX S3C)
R = "\033[%s;31m"
B = "\033[%s;34m"
G = "\033[%s;32m"
W = "\033[%s;38m"
Y = "\033[%s;33m"
E = "\033[0m" | r = '\x1b[%s;31m'
b = '\x1b[%s;34m'
g = '\x1b[%s;32m'
w = '\x1b[%s;38m'
y = '\x1b[%s;33m'
e = '\x1b[0m' |
# dummy wordlist
# by Jeeb
# Information about your version of Wordle
Metadata = {
"name": "Dummy",
"version": "dummy",
"guesses": 4,
"launch": (2222, 2, 16),
"boxes": ["[]", "!!", "<3", " ", " "],
"colors": [0x1666666, 0x1bb9900, 0x1008800, 0xe8e8e8, 0x1222222],
"keyboard": ["aaaaaaaaaa"], # max 10 keys per row, please
}
# Your custom list of non-answer words goes here
Words = ["b", "c", "d", "e", "f"]
# Your custom list of answer-words goes here
Answers = ["a"] | metadata = {'name': 'Dummy', 'version': 'dummy', 'guesses': 4, 'launch': (2222, 2, 16), 'boxes': ['[]', '!!', '<3', ' ', ' '], 'colors': [23488102, 29071616, 16812032, 15263976, 19014178], 'keyboard': ['aaaaaaaaaa']}
words = ['b', 'c', 'd', 'e', 'f']
answers = ['a'] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 28 08:56:55 2017
@author: Nadiar
"""
balance = 320000
annualInterestRate = 0.2
"""
Monthly interest rate = (Annual interest rate) / 12.0
Monthly payment lower bound = Balance / 12
Monthly payment upper bound =
(Balance x (1 + Monthly interest rate)^12) / 12.0
"""
monthlyInterestRate = annualInterestRate / 12.0
def monthlyUnpaidBalance(balance, guess):
return balance - guess
def updatedBalanceEachMonth(balance, guess):
return monthlyUnpaidBalance(balance, guess) \
+ monthlyInterestRate * \
+ monthlyUnpaidBalance(balance, guess)
def updatedBalance(balance, guess, nMonth):
"""
return balance after payment made with guess each month
"""
if (nMonth < 1):
return balance
else:
return updatedBalance(updatedBalanceEachMonth(balance, guess), guess, nMonth-1)
def remainingBalance(balance, guess):
return updatedBalance(balance, guess, 12)
def monthlyPaymentLowerBound(balance):
return balance / 12
def monthlyPaymentUpperBound(balance):
return (balance * (1 + monthlyInterestRate)**12) / 12.0
def generateGuess(lower, upper):
return (lower + upper) / 2
def bSearchIter(balance):
lower = monthlyPaymentLowerBound(balance)
upper = monthlyPaymentUpperBound(balance)
guess = (lower + upper) / 2
debt = remainingBalance(balance, guess)
# while guess is not minimum
while not (debt <= 0.01 and debt >= -0.01):
# if we pay more
if (debt < 0):
upper = guess
guess = (lower + upper) / 2
debt = remainingBalance(balance, guess)
# print("+++", debt)
# if we pay less
if (debt > 0):
lower = guess
guess = (lower + upper) / 2
debt = remainingBalance(balance, generateGuess(lower, upper))
# print("---", debt)
return guess
def bSearchRecur(balance, guess, lower, upper):
if (remainingBalance(balance, guess) <= 0.01 and
remainingBalance(balance, guess) >= -0.01):
return guess
if (remainingBalance(balance, guess) < 0):
return bSearchRecur(balance, generateGuess(lower, guess), lower, guess)
if (remainingBalance(balance, guess) > 0):
return bSearchRecur(balance, generateGuess(guess, upper), guess, upper)
def main(balance):
# return bSearchIter(balance)
return bSearchRecur(balance,
generateGuess(monthlyPaymentLowerBound(balance),
monthlyPaymentUpperBound(balance)),
monthlyPaymentLowerBound(balance),
monthlyPaymentUpperBound(balance))
print("Lowest Payment: %.2f" %main(balance))
| """
Created on Sat Jan 28 08:56:55 2017
@author: Nadiar
"""
balance = 320000
annual_interest_rate = 0.2
'\nMonthly interest rate = (Annual interest rate) / 12.0\nMonthly payment lower bound = Balance / 12\nMonthly payment upper bound =\n (Balance x (1 + Monthly interest rate)^12) / 12.0\n'
monthly_interest_rate = annualInterestRate / 12.0
def monthly_unpaid_balance(balance, guess):
return balance - guess
def updated_balance_each_month(balance, guess):
return monthly_unpaid_balance(balance, guess) + monthlyInterestRate * +monthly_unpaid_balance(balance, guess)
def updated_balance(balance, guess, nMonth):
"""
return balance after payment made with guess each month
"""
if nMonth < 1:
return balance
else:
return updated_balance(updated_balance_each_month(balance, guess), guess, nMonth - 1)
def remaining_balance(balance, guess):
return updated_balance(balance, guess, 12)
def monthly_payment_lower_bound(balance):
return balance / 12
def monthly_payment_upper_bound(balance):
return balance * (1 + monthlyInterestRate) ** 12 / 12.0
def generate_guess(lower, upper):
return (lower + upper) / 2
def b_search_iter(balance):
lower = monthly_payment_lower_bound(balance)
upper = monthly_payment_upper_bound(balance)
guess = (lower + upper) / 2
debt = remaining_balance(balance, guess)
while not (debt <= 0.01 and debt >= -0.01):
if debt < 0:
upper = guess
guess = (lower + upper) / 2
debt = remaining_balance(balance, guess)
if debt > 0:
lower = guess
guess = (lower + upper) / 2
debt = remaining_balance(balance, generate_guess(lower, upper))
return guess
def b_search_recur(balance, guess, lower, upper):
if remaining_balance(balance, guess) <= 0.01 and remaining_balance(balance, guess) >= -0.01:
return guess
if remaining_balance(balance, guess) < 0:
return b_search_recur(balance, generate_guess(lower, guess), lower, guess)
if remaining_balance(balance, guess) > 0:
return b_search_recur(balance, generate_guess(guess, upper), guess, upper)
def main(balance):
return b_search_recur(balance, generate_guess(monthly_payment_lower_bound(balance), monthly_payment_upper_bound(balance)), monthly_payment_lower_bound(balance), monthly_payment_upper_bound(balance))
print('Lowest Payment: %.2f' % main(balance)) |
# -*- coding: utf-8 -*-
"""
Created on Tue Feb 9 14:04:56 2021
@author: rowe1
"""
def a_star(start, target, tail, grid, graph, obstacles):
"""
Uses a_star heuristic to find a path from start to target and back to tail.
If such a path exists, return the path from start to target.
If such a path does not exist, returns a path from start to tail.
Cannot revisit the same node twice and cannot step on obstacles if obstacles[node] < k
where k is the number of steps taken so far.
Having a hashmap of obstacles allows for O(1) lookup times to see if a node is taken and
allows us to account for the snake's tail moving as we take steps forward without actually
updating the datastucture.
"""
| """
Created on Tue Feb 9 14:04:56 2021
@author: rowe1
"""
def a_star(start, target, tail, grid, graph, obstacles):
"""
Uses a_star heuristic to find a path from start to target and back to tail.
If such a path exists, return the path from start to target.
If such a path does not exist, returns a path from start to tail.
Cannot revisit the same node twice and cannot step on obstacles if obstacles[node] < k
where k is the number of steps taken so far.
Having a hashmap of obstacles allows for O(1) lookup times to see if a node is taken and
allows us to account for the snake's tail moving as we take steps forward without actually
updating the datastucture.
""" |
a = a+1
a += 1
b = b-5
b -= 5
| a = a + 1
a += 1
b = b - 5
b -= 5 |
class FieldC():
def __init__(self, name, column_type, primary_key, default):
self.name = name
self.column_type = column_type
self.primary_key = primary_key
self.default = default
def __str__(self):
return '<%s, %s:%s>' % (self.__class__.__name__, self.column_type, self.name)
class StringFieldC(FieldC):
def __init__(self, name=None, primary_key=False, default=None, ddl='varchat(255)'):
super().__init__(name, ddl, primary_key, default)
class TinyIntFieldC(FieldC):
def __init__(self, name=None, default=0):
super().__init__(name, 'tinyint', False, default)
class IntFieldC(FieldC):
def __init__(self, name=None, primary_key=False, default=0):
super().__init__(name, 'int', primary_key, default)
class BigIntFieldC(FieldC):
def __init__(self, name=None, primary_key=False, default=0):
super().__init__(name, 'bigint', primary_key, default)
class DoubleFieldC(FieldC):
def __init__(self, name=None, primary_key=False, default=0.0):
super().__init__(name, 'double', primary_key, default)
class TextFieldC(FieldC):
def __init__(self, name=None, default=None):
super().__init__(name, 'text', False, default)
| class Fieldc:
def __init__(self, name, column_type, primary_key, default):
self.name = name
self.column_type = column_type
self.primary_key = primary_key
self.default = default
def __str__(self):
return '<%s, %s:%s>' % (self.__class__.__name__, self.column_type, self.name)
class Stringfieldc(FieldC):
def __init__(self, name=None, primary_key=False, default=None, ddl='varchat(255)'):
super().__init__(name, ddl, primary_key, default)
class Tinyintfieldc(FieldC):
def __init__(self, name=None, default=0):
super().__init__(name, 'tinyint', False, default)
class Intfieldc(FieldC):
def __init__(self, name=None, primary_key=False, default=0):
super().__init__(name, 'int', primary_key, default)
class Bigintfieldc(FieldC):
def __init__(self, name=None, primary_key=False, default=0):
super().__init__(name, 'bigint', primary_key, default)
class Doublefieldc(FieldC):
def __init__(self, name=None, primary_key=False, default=0.0):
super().__init__(name, 'double', primary_key, default)
class Textfieldc(FieldC):
def __init__(self, name=None, default=None):
super().__init__(name, 'text', False, default) |
#line = r'''execute if score waveGlowTimer glowTimer matches %s run tag @e[type=!player,type=!dolphin,distance=%s,nbt={Attributes:[{Name:"generic.attackDamage"}]},nbt=!{Glowing: 1b}] add madeGlowing'''
#type=!player,type=!dolphin,distance=16..20,nbt={Attributes:[{Name:"generic.attackDamage"}]},nbt=!{Glowing: 1b}
line = r'''execute if score waveGlowTimer glowTimer matches %s if entity @a[distance=%s] run tag @s add madeGlowing'''
bandDistance = 4
bandDuration = 0
minDistance = 16
maxDistance = 64
timeMod = (3 * bandDistance)
distMod = maxDistance - minDistance
def dotdotspan(start, end):
if start != end:
return "%s..%s" % (start, end)
return str(start)
maxDistance += (minDistance - maxDistance) % timeMod
print("#NOTE: The conditions for waveGlowTimer wrapping in 'dotick' must be made to match the maximum count in this file (%r)" % (timeMod - 1,))
#print(r'''tag @e[type=!player,type=!dolphin,distance=..%s,nbt={Attributes:[{Name:"generic.attackDamage"}]},nbt=!{Glowing: 1b}] add madeGlowing''' % (minDistance-1,))
print(r'''execute if entity @a[distance=%s] run tag @s add madeGlowing''' % (minDistance-1,))
for ii, dd in enumerate(range(minDistance, maxDistance)):
startTime = ii % timeMod
endTime = (startTime + bandDuration) % timeMod
startDist = (dd - minDistance) % distMod + minDistance
endDist = (startDist + bandDistance - minDistance) % distMod + minDistance
if endTime != startTime + bandDuration:
if endDist != startDist + bandDistance:
print(line % (dotdotspan(startTime, timeMod-1), dotdotspan(startDist, distMod-1+minDistance)))
print(line % (dotdotspan(0, endTime), dotdotspan(startDist, distMod-1+minDistance)))
print(line % (dotdotspan(startTime, timeMod-1), dotdotspan(minDistance, endDist)))
print(line % (dotdotspan(0, endTime), dotdotspan(minDistance, endDist)))
else:
print(line % (dotdotspan(startTime, timeMod-1), dotdotspan(dd, dd + bandDistance)))
print(line % (dotdotspan(0, endTime), dotdotspan(dd, dd + bandDistance)))
else:
if endDist != startDist + bandDistance:
print(line % (dotdotspan(startTime, endTime), dotdotspan(startDist, distMod-1+minDistance)))
print(line % (dotdotspan(startTime, endTime), dotdotspan(minDistance, endDist)))
else:
print(line % (dotdotspan(startTime, endTime), dotdotspan(dd, dd + bandDistance)))
| line = 'execute if score waveGlowTimer glowTimer matches %s if entity @a[distance=%s] run tag @s add madeGlowing'
band_distance = 4
band_duration = 0
min_distance = 16
max_distance = 64
time_mod = 3 * bandDistance
dist_mod = maxDistance - minDistance
def dotdotspan(start, end):
if start != end:
return '%s..%s' % (start, end)
return str(start)
max_distance += (minDistance - maxDistance) % timeMod
print("#NOTE: The conditions for waveGlowTimer wrapping in 'dotick' must be made to match the maximum count in this file (%r)" % (timeMod - 1,))
print('execute if entity @a[distance=%s] run tag @s add madeGlowing' % (minDistance - 1,))
for (ii, dd) in enumerate(range(minDistance, maxDistance)):
start_time = ii % timeMod
end_time = (startTime + bandDuration) % timeMod
start_dist = (dd - minDistance) % distMod + minDistance
end_dist = (startDist + bandDistance - minDistance) % distMod + minDistance
if endTime != startTime + bandDuration:
if endDist != startDist + bandDistance:
print(line % (dotdotspan(startTime, timeMod - 1), dotdotspan(startDist, distMod - 1 + minDistance)))
print(line % (dotdotspan(0, endTime), dotdotspan(startDist, distMod - 1 + minDistance)))
print(line % (dotdotspan(startTime, timeMod - 1), dotdotspan(minDistance, endDist)))
print(line % (dotdotspan(0, endTime), dotdotspan(minDistance, endDist)))
else:
print(line % (dotdotspan(startTime, timeMod - 1), dotdotspan(dd, dd + bandDistance)))
print(line % (dotdotspan(0, endTime), dotdotspan(dd, dd + bandDistance)))
elif endDist != startDist + bandDistance:
print(line % (dotdotspan(startTime, endTime), dotdotspan(startDist, distMod - 1 + minDistance)))
print(line % (dotdotspan(startTime, endTime), dotdotspan(minDistance, endDist)))
else:
print(line % (dotdotspan(startTime, endTime), dotdotspan(dd, dd + bandDistance))) |
n,m=map(int,input().split())
x=[i for i in range(1,n+1)]
for i in range(m):
a,b=map(int,input().split())
x[a-1],x[b-1]=x[b-1],x[a-1]
for i in x: print(i,end=' ') | (n, m) = map(int, input().split())
x = [i for i in range(1, n + 1)]
for i in range(m):
(a, b) = map(int, input().split())
(x[a - 1], x[b - 1]) = (x[b - 1], x[a - 1])
for i in x:
print(i, end=' ') |
class DimError(Exception):
code = 1
error_types = dict(
InvalidPoolError=2,
InvalidIPError=3,
InvalidVLANError=4,
InvalidStatusError=5,
InvalidPriorityError=6,
InvalidGroupError=7,
InvalidUserError=8,
InvalidAccessRightError=9,
InvalidZoneError=10,
InvalidViewError=11,
MultipleViewsError=12,
InvalidParameterError=19,
AlreadyExistsError=20,
NotInPoolError=21,
NotInDelegationError=22,
PermissionDeniedError=23,
HasChildrenError=24,
)
for name, code in error_types.iteritems():
globals()[name] = type(name, (DimError,), {'code': code})
| class Dimerror(Exception):
code = 1
error_types = dict(InvalidPoolError=2, InvalidIPError=3, InvalidVLANError=4, InvalidStatusError=5, InvalidPriorityError=6, InvalidGroupError=7, InvalidUserError=8, InvalidAccessRightError=9, InvalidZoneError=10, InvalidViewError=11, MultipleViewsError=12, InvalidParameterError=19, AlreadyExistsError=20, NotInPoolError=21, NotInDelegationError=22, PermissionDeniedError=23, HasChildrenError=24)
for (name, code) in error_types.iteritems():
globals()[name] = type(name, (DimError,), {'code': code}) |
# ------------------------------------------------------------------------------
# Path setup
# Variables ending in _PATH are used as URL paths; those ending with _FSPATH
# are filesystem paths.
# For a single board setup (wakaba style), set SITE_PATH to / and point
# MATSUBA_PATH to /boardname/matsuba.py
# The base URL for the entire website. Used for RSS feeds if enabled, and some
# other stuff. The spam filter always accepts links within the site regardless
# of other spam-settings.
SITE_BASEURL = 'http://127.0.0.1/'
# Where are the boards?
# e.g. if you want http://yoursite.tld/matsuba/boardname/index.html
# then your SITE_PATH will be /matsuba
SITE_PATH = '/'
# Paths to various other places
MATSUBA_PATH = '/matsuba.py' # path to the dispatching cgi script
CSS_PATH = '/css'
JS_PATH = '/js'
IMG_PATH = '/img'
# Filesystem paths
SITE_FSPATH = '/home/you/public_html'
CSS_FSPATH = SITE_FSPATH + CSS_PATH
IMG_FSPATH = SITE_FSPATH + IMG_PATH
# Where is the private directory?
# This directory should NOT be web-accessible.
# Page templates and various other config files are located here.
PRIVATE_FSPATH = '/home/you/matsuba/priv'
# SQL configuration (for sqlite)
DB_DATABASE = PRIVATE_FSPATH + '/matsuba.db'
# ------------------------------------------------------------------------------
# Other options
# How many threads are shown on each page
THREADS_PER_PAGE = 10
# How many columns each row of the catalog should have
CATALOG_COLUMNS = THREADS_PER_PAGE
# How many pages of threads to keep
MAX_PAGES = 10
# How many replies before autosage
THREAD_AUTOSAGE_REPLIES = 100
# How many replies before autoclose
# (Not implemented)
THREAD_AUTOCLOSE_REPLIES = None
# How many replies to show per thread on the main page
MAX_REPLIES_SHOWN = 10
MAX_STICKY_REPLIES_SHOWN = 4
# How many characters can be in a name/link/subject (Wakaba uses 100 by default)
MAX_FIELD_LENGTH = 256
# How many characters can be in a post (Wakaba uses 8192)
MAX_MESSAGE_LENGTH = 65536
# Secret word, used to generate secure tripcodes. Make it long and random.
SECRET = "fill this with some actual random data"
# Allow posting new threads without images?
ALLOW_TEXT_THREADS = False
# Header that shows on the top of all boards. Don't put HTML here, since this
# shows up in the titlebar.
SITE_TITLE = u'hi'
# Top left text.
BOARD_LIST = u'''\
[Board list goes here]
'''
# Each board can override this.
MAX_FILESIZE = 1048576 * 4
# Force anonymous posting by default?
# This can be overriden on a per-board basis.
FORCED_ANON = False
# Name to use when no name is given.
# If this begins with "random:", names are randomized based on the parameters
# which follow. Possible values are:
# time[=seconds[+offset]] - reset names each day, or every <n> seconds
# (optionally adjusting the time first)
# by default, names will reset at midnight UTC if 'time' is given.
# board - each board gets a different name (otherwise random name is the
# same for all boards, as long as the other settings are the same)
# thread - names are unique to a thread. note that this requires an extra
# step to process the name for the first post in a thread.
# Names are always randomized by IP address, so even if no other parameters are
# given everyone still gets a unique statically assigned name. (as long as they
# have the same IP, of course)
ANONYMOUS = 'Anonymous'
#ANONYMOUS = 'random:board,thread,time'
# Rule set for generating poster IDs. Same format as above, except without the
# "random:" prefix. Set to an empty string to disable IDs.
# Possible values are:
# time, board, thread - same as above
# sage - ID is always "Heaven" for sage posts (2ch-ism)
# This rule will reset IDs every week, per board, per thread.
DEFAULT_ID_RULESET = '' # 'board,thread,time=604800,sage'
# Default template for boards without a defined template, and for pages that
# don't specify a board template (such as error messages)
DEFAULT_TEMPLATE = 'image'
# send xhtml to browsers that claim to support it?
# (this is broken for some reason, i don't know why)
USE_XHTML = False
# How many times can a link be repeated in a post before it is flagged as spam?
MAX_REPEATED_LINKS = 3
# for the two different flavors of rss feeds
RSS_REPLIES = 100
RSS_THREADS = 25
ABBREV_MAX_LINES = 15
ABBREV_LINE_LEN = 150
HARD_SPAM_FILES = ['spam-hardblock.txt']
SPAM_FILES = ['spam.txt', 'spam-local.txt'] + HARD_SPAM_FILES
LOGIN_TIMEOUT = 60 * 60 * 4
# ------------------------------------------------------------------------------
# Thumbnailing
THUMBNAIL_SIZE = [250, 175] # [0] is for the first post, [1] is for replies
CATNAIL_SIZE = 50 # size for thumbnails on catalog.html
GIF_MAX_FILESIZE = 524288 # animated gif thumbnailing threshold (needs gifsicle)
GIFSICLE_PATH = '/usr/bin/gifsicle' # for thumbnailing animated GIF files
CONVERT_PATH = '/usr/bin/convert' # used if PIL fails or isn't installed; set to None to disable ImageMagick
SIPS_PATH = None # for OS X
JPEG_QUALITY = 75
# Default thumbnails. These should go in the site-shared directory.
FALLBACK_THUMBNAIL = 'no_thumbnail.png'
DELETED_THUMBNAIL = 'file_deleted.png'
DELETED_THUMBNAIL_RES = 'file_deleted_res.png'
# ------------------------------------------------------------------------------
# don't mess with this
SITE_BASEURL = SITE_BASEURL.rstrip('/')
SITE_PATH = SITE_PATH.rstrip('/')
| site_baseurl = 'http://127.0.0.1/'
site_path = '/'
matsuba_path = '/matsuba.py'
css_path = '/css'
js_path = '/js'
img_path = '/img'
site_fspath = '/home/you/public_html'
css_fspath = SITE_FSPATH + CSS_PATH
img_fspath = SITE_FSPATH + IMG_PATH
private_fspath = '/home/you/matsuba/priv'
db_database = PRIVATE_FSPATH + '/matsuba.db'
threads_per_page = 10
catalog_columns = THREADS_PER_PAGE
max_pages = 10
thread_autosage_replies = 100
thread_autoclose_replies = None
max_replies_shown = 10
max_sticky_replies_shown = 4
max_field_length = 256
max_message_length = 65536
secret = 'fill this with some actual random data'
allow_text_threads = False
site_title = u'hi'
board_list = u'[Board list goes here]\n'
max_filesize = 1048576 * 4
forced_anon = False
anonymous = 'Anonymous'
default_id_ruleset = ''
default_template = 'image'
use_xhtml = False
max_repeated_links = 3
rss_replies = 100
rss_threads = 25
abbrev_max_lines = 15
abbrev_line_len = 150
hard_spam_files = ['spam-hardblock.txt']
spam_files = ['spam.txt', 'spam-local.txt'] + HARD_SPAM_FILES
login_timeout = 60 * 60 * 4
thumbnail_size = [250, 175]
catnail_size = 50
gif_max_filesize = 524288
gifsicle_path = '/usr/bin/gifsicle'
convert_path = '/usr/bin/convert'
sips_path = None
jpeg_quality = 75
fallback_thumbnail = 'no_thumbnail.png'
deleted_thumbnail = 'file_deleted.png'
deleted_thumbnail_res = 'file_deleted_res.png'
site_baseurl = SITE_BASEURL.rstrip('/')
site_path = SITE_PATH.rstrip('/') |
def test_standard(hatch, config_file, helpers):
result = hatch('config', 'set', 'project', 'foo')
assert result.exit_code == 0, result.output
assert result.output == helpers.dedent(
"""
New setting:
project = "foo"
"""
)
config_file.load()
assert config_file.model.project == 'foo'
def test_standard_deep(hatch, config_file, helpers):
result = hatch('config', 'set', 'template.name', 'foo')
assert result.exit_code == 0, result.output
assert result.output == helpers.dedent(
"""
New setting:
[template]
name = "foo"
"""
)
config_file.load()
assert config_file.model.template.name == 'foo'
def test_standard_complex_sequence(hatch, config_file, helpers):
result = hatch('config', 'set', 'dirs.project', "['/foo', '/bar']")
assert result.exit_code == 0, result.output
assert result.output == helpers.dedent(
"""
New setting:
[dirs]
project = ["/foo", "/bar"]
"""
)
config_file.load()
assert config_file.model.dirs.project == ['/foo', '/bar']
def test_standard_complex_map(hatch, config_file, helpers):
result = hatch('config', 'set', 'projects', "{'a': '/foo', 'b': '/bar'}")
assert result.exit_code == 0, result.output
assert result.output == helpers.dedent(
"""
New setting:
[projects]
a = "/foo"
b = "/bar"
"""
)
config_file.load()
assert config_file.model.projects['a'].location == '/foo'
assert config_file.model.projects['b'].location == '/bar'
def test_standard_hidden(hatch, config_file, helpers):
result = hatch('config', 'set', 'publish.pypi.auth', 'foo')
assert result.exit_code == 0, result.output
assert result.output == helpers.dedent(
"""
New setting:
[publish]
[publish.pypi]
auth = "<...>"
"""
)
config_file.load()
assert config_file.model.publish['pypi']['auth'] == 'foo'
def test_prompt(hatch, config_file, helpers):
result = hatch('config', 'set', 'project', input='foo')
assert result.exit_code == 0, result.output
assert result.output == helpers.dedent(
"""
Value for `project`: foo
New setting:
project = "foo"
"""
)
config_file.load()
assert config_file.model.project == 'foo'
def test_prompt_hidden(hatch, config_file, helpers):
result = hatch('config', 'set', 'publish.pypi.auth', input='foo')
assert result.exit_code == 0, result.output
assert result.output == helpers.dedent(
f"""
Value for `publish.pypi.auth`:{' '}
New setting:
[publish]
[publish.pypi]
auth = "<...>"
"""
)
config_file.load()
assert config_file.model.publish['pypi']['auth'] == 'foo'
def test_prevent_invalid_config(hatch, config_file, helpers):
original_mode = config_file.model.mode
result = hatch('config', 'set', 'mode', 'foo')
assert result.exit_code == 1
assert result.output == helpers.dedent(
"""
Error parsing config:
mode
must be one of: aware, local, project
"""
)
config_file.load()
assert config_file.model.mode == original_mode
def test_resolve_project_location_basic(hatch, config_file, helpers, temp_dir):
config_file.model.project = 'foo'
config_file.save()
with temp_dir.as_cwd():
result = hatch('config', 'set', 'projects.foo', '.')
path = str(temp_dir).replace('\\', '\\\\')
assert result.exit_code == 0, result.output
assert result.output == helpers.dedent(
f"""
New setting:
[projects]
foo = "{path}"
"""
)
config_file.load()
assert config_file.model.projects['foo'].location == str(temp_dir)
def test_resolve_project_location_complex(hatch, config_file, helpers, temp_dir):
config_file.model.project = 'foo'
config_file.save()
with temp_dir.as_cwd():
result = hatch('config', 'set', 'projects.foo.location', '.')
path = str(temp_dir).replace('\\', '\\\\')
assert result.exit_code == 0, result.output
assert result.output == helpers.dedent(
f"""
New setting:
[projects]
[projects.foo]
location = "{path}"
"""
)
config_file.load()
assert config_file.model.projects['foo'].location == str(temp_dir)
def test_project_location_basic_set_first_project(hatch, config_file, helpers, temp_dir):
with temp_dir.as_cwd():
result = hatch('config', 'set', 'projects.foo', '.')
path = str(temp_dir).replace('\\', '\\\\')
assert result.exit_code == 0, result.output
assert result.output == helpers.dedent(
f"""
New setting:
project = "foo"
[projects]
foo = "{path}"
"""
)
config_file.load()
assert config_file.model.project == 'foo'
assert config_file.model.projects['foo'].location == str(temp_dir)
def test_project_location_complex_set_first_project(hatch, config_file, helpers, temp_dir):
with temp_dir.as_cwd():
result = hatch('config', 'set', 'projects.foo.location', '.')
path = str(temp_dir).replace('\\', '\\\\')
assert result.exit_code == 0, result.output
assert result.output == helpers.dedent(
f"""
New setting:
project = "foo"
[projects]
[projects.foo]
location = "{path}"
"""
)
config_file.load()
assert config_file.model.project == 'foo'
assert config_file.model.projects['foo'].location == str(temp_dir)
| def test_standard(hatch, config_file, helpers):
result = hatch('config', 'set', 'project', 'foo')
assert result.exit_code == 0, result.output
assert result.output == helpers.dedent('\n New setting:\n project = "foo"\n ')
config_file.load()
assert config_file.model.project == 'foo'
def test_standard_deep(hatch, config_file, helpers):
result = hatch('config', 'set', 'template.name', 'foo')
assert result.exit_code == 0, result.output
assert result.output == helpers.dedent('\n New setting:\n [template]\n name = "foo"\n ')
config_file.load()
assert config_file.model.template.name == 'foo'
def test_standard_complex_sequence(hatch, config_file, helpers):
result = hatch('config', 'set', 'dirs.project', "['/foo', '/bar']")
assert result.exit_code == 0, result.output
assert result.output == helpers.dedent('\n New setting:\n [dirs]\n project = ["/foo", "/bar"]\n ')
config_file.load()
assert config_file.model.dirs.project == ['/foo', '/bar']
def test_standard_complex_map(hatch, config_file, helpers):
result = hatch('config', 'set', 'projects', "{'a': '/foo', 'b': '/bar'}")
assert result.exit_code == 0, result.output
assert result.output == helpers.dedent('\n New setting:\n [projects]\n a = "/foo"\n b = "/bar"\n ')
config_file.load()
assert config_file.model.projects['a'].location == '/foo'
assert config_file.model.projects['b'].location == '/bar'
def test_standard_hidden(hatch, config_file, helpers):
result = hatch('config', 'set', 'publish.pypi.auth', 'foo')
assert result.exit_code == 0, result.output
assert result.output == helpers.dedent('\n New setting:\n [publish]\n [publish.pypi]\n auth = "<...>"\n ')
config_file.load()
assert config_file.model.publish['pypi']['auth'] == 'foo'
def test_prompt(hatch, config_file, helpers):
result = hatch('config', 'set', 'project', input='foo')
assert result.exit_code == 0, result.output
assert result.output == helpers.dedent('\n Value for `project`: foo\n New setting:\n project = "foo"\n ')
config_file.load()
assert config_file.model.project == 'foo'
def test_prompt_hidden(hatch, config_file, helpers):
result = hatch('config', 'set', 'publish.pypi.auth', input='foo')
assert result.exit_code == 0, result.output
assert result.output == helpers.dedent(f"""\n Value for `publish.pypi.auth`:{' '}\n New setting:\n [publish]\n [publish.pypi]\n auth = "<...>"\n """)
config_file.load()
assert config_file.model.publish['pypi']['auth'] == 'foo'
def test_prevent_invalid_config(hatch, config_file, helpers):
original_mode = config_file.model.mode
result = hatch('config', 'set', 'mode', 'foo')
assert result.exit_code == 1
assert result.output == helpers.dedent('\n Error parsing config:\n mode\n must be one of: aware, local, project\n ')
config_file.load()
assert config_file.model.mode == original_mode
def test_resolve_project_location_basic(hatch, config_file, helpers, temp_dir):
config_file.model.project = 'foo'
config_file.save()
with temp_dir.as_cwd():
result = hatch('config', 'set', 'projects.foo', '.')
path = str(temp_dir).replace('\\', '\\\\')
assert result.exit_code == 0, result.output
assert result.output == helpers.dedent(f'\n New setting:\n [projects]\n foo = "{path}"\n ')
config_file.load()
assert config_file.model.projects['foo'].location == str(temp_dir)
def test_resolve_project_location_complex(hatch, config_file, helpers, temp_dir):
config_file.model.project = 'foo'
config_file.save()
with temp_dir.as_cwd():
result = hatch('config', 'set', 'projects.foo.location', '.')
path = str(temp_dir).replace('\\', '\\\\')
assert result.exit_code == 0, result.output
assert result.output == helpers.dedent(f'\n New setting:\n [projects]\n [projects.foo]\n location = "{path}"\n ')
config_file.load()
assert config_file.model.projects['foo'].location == str(temp_dir)
def test_project_location_basic_set_first_project(hatch, config_file, helpers, temp_dir):
with temp_dir.as_cwd():
result = hatch('config', 'set', 'projects.foo', '.')
path = str(temp_dir).replace('\\', '\\\\')
assert result.exit_code == 0, result.output
assert result.output == helpers.dedent(f'\n New setting:\n project = "foo"\n\n [projects]\n foo = "{path}"\n ')
config_file.load()
assert config_file.model.project == 'foo'
assert config_file.model.projects['foo'].location == str(temp_dir)
def test_project_location_complex_set_first_project(hatch, config_file, helpers, temp_dir):
with temp_dir.as_cwd():
result = hatch('config', 'set', 'projects.foo.location', '.')
path = str(temp_dir).replace('\\', '\\\\')
assert result.exit_code == 0, result.output
assert result.output == helpers.dedent(f'\n New setting:\n project = "foo"\n\n [projects]\n [projects.foo]\n location = "{path}"\n ')
config_file.load()
assert config_file.model.project == 'foo'
assert config_file.model.projects['foo'].location == str(temp_dir) |
"""Dummy class that does not inherit from the required AbstractObjectDetection."""
class ObjectDetection:
"""Dummy class that does not inherit from the required AbstractObjectDetection."""
| """Dummy class that does not inherit from the required AbstractObjectDetection."""
class Objectdetection:
"""Dummy class that does not inherit from the required AbstractObjectDetection.""" |
class Solution:
def judgeCircle(self, moves: str) -> bool:
"""String.
Running time: O(n) where n == len(moves).
"""
r, l, u, d = 0, 0, 0, 0
for m in moves:
if m == 'U':
u += 1
elif m == 'D':
d += 1
elif m == 'R':
r += 1
else:
l += 1
return u == d and l == r
| class Solution:
def judge_circle(self, moves: str) -> bool:
"""String.
Running time: O(n) where n == len(moves).
"""
(r, l, u, d) = (0, 0, 0, 0)
for m in moves:
if m == 'U':
u += 1
elif m == 'D':
d += 1
elif m == 'R':
r += 1
else:
l += 1
return u == d and l == r |
def type(a,b):
if isinstance(a,int) and isinstance(b,int):
return a+b
return 'Not integer type'
print(type(2,3))
print(type('a','boy')) | def type(a, b):
if isinstance(a, int) and isinstance(b, int):
return a + b
return 'Not integer type'
print(type(2, 3))
print(type('a', 'boy')) |
obj0 = SystemBusNode()
obj1 = SystemBusDeviceNode(
qom_type = "TYPE_INTERRUPT_CONTROLLER",
system_bus = obj0,
var_base = "interrupt_controller"
)
obj2 = SystemBusDeviceNode(
qom_type = "TYPE_UART",
system_bus = obj0,
var_base = "uart"
)
obj3 = DeviceNode(
qom_type = "TYPE_CPU",
var_base = "cpu"
)
obj4 = SystemBusDeviceNode(
qom_type = "UART",
system_bus = obj0,
var_base = "uart"
)
obj5 = SystemBusDeviceNode(
qom_type = "TYPE_PCI_HOST",
system_bus = obj0,
var_base = "pci_host"
)
obj6 = PCIExpressBusNode(
host_bridge = obj5
)
obj7 = PCIExpressDeviceNode(
qom_type = "TYPE_ETHERNET",
pci_express_bus = obj6,
slot = 0,
function = 0,
var_base = "ethernet"
)
obj8 = PCIExpressDeviceNode(
qom_type = "TYPE_ETHERNET",
pci_express_bus = obj6,
slot = 0,
function = 0,
var_base = "ethernet"
)
obj9 = SystemBusDeviceNode(
qom_type = "TYPE_ROM",
system_bus = obj0,
var_base = "rom"
)
obj10 = SystemBusDeviceNode(
qom_type = "TYPE_HID",
system_bus = obj0,
var_base = "hid"
)
obj11 = SystemBusDeviceNode(
qom_type = "TYPE_DISPLAY",
system_bus = obj0,
var_base = "display"
)
obj12 = IRQLine(
src_dev = obj1,
dst_dev = obj3
)
obj13 = IRQHub(
srcs = [],
dsts = []
)
obj14 = IRQLine(
src_dev = obj13,
dst_dev = obj1
)
obj15 = IRQLine(
src_dev = obj2,
dst_dev = obj13
)
obj16 = IRQLine(
src_dev = obj4,
dst_dev = obj13
)
obj17 = IRQLine(
src_dev = obj5,
dst_dev = obj1,
dst_irq_idx = 0x1
)
obj18 = IRQLine(
src_dev = obj9,
dst_dev = obj1,
dst_irq_idx = 0x2
)
obj19 = IRQLine(
src_dev = obj11,
dst_dev = obj1,
dst_irq_idx = 0x3
)
obj20 = IRQLine(
src_dev = obj10,
dst_dev = obj1,
dst_irq_idx = 0x4
)
obj21 = MachineNode(
name = "description0",
directory = ""
)
obj21.add_node(obj0, with_id = 0)
obj21.add_node(obj1, with_id = 1)
obj21.add_node(obj2, with_id = 2)
obj21.add_node(obj13, with_id = 3)
obj21.add_node(obj3, with_id = 4)
obj21.add_node(obj12, with_id = 5)
obj21.add_node(obj14, with_id = 6)
obj21.add_node(obj4, with_id = 7)
obj21.add_node(obj15, with_id = 8)
obj21.add_node(obj16, with_id = 9)
obj21.add_node(obj5, with_id = 10)
obj21.add_node(obj6, with_id = 11)
obj21.add_node(obj7, with_id = 12)
obj21.add_node(obj8, with_id = 13)
obj21.add_node(obj17, with_id = 14)
obj21.add_node(obj9, with_id = 15)
obj21.add_node(obj18, with_id = 16)
obj21.add_node(obj10, with_id = 17)
obj21.add_node(obj11, with_id = 18)
obj21.add_node(obj19, with_id = 19)
obj21.add_node(obj20, with_id = 20)
obj22 = MachineWidgetLayout(
mdwl = {
0: (
41.20573293511035,
125.9760158583141
),
0x1: (
96.1447438641203,
96.92583042837722
),
0x2: (
84.0,
189.0
),
0x3: (
148.0,
157.0
),
0x4: (
201.0,
34.0
),
0x7: (
154.0,
217.0
),
0xa: (
273.0,
241.0
),
0xb: (
293.0,
142.0
),
0xc: (
334.0,
55.0
),
0xd: (
333.0,
98.0
),
0xf: (
112.0,
26.0
),
0x11: (
-7.0,
16.0
),
0x12: (
-39.0,
60.0
),
-1: {
"physical layout": False,
"IRQ lines points": {
0x10: [],
0x13: [],
0x14: [],
0x5: [],
0x6: [],
0x8: [],
0x9: [],
0xe: [
(
230.0,
210.0
),
(
229.0,
165.0
)
]
},
"show mesh": False,
"mesh step": 0x14
}
},
mtwl = {},
use_tabs = True
)
obj23 = GUILayout(
desc_name = "description0",
opaque = obj22,
shown = True
)
obj23.lid = 0
obj24 = GUIProject(
layouts = [
obj23
],
build_path = None,
descriptions = [
obj21
]
)
| obj0 = system_bus_node()
obj1 = system_bus_device_node(qom_type='TYPE_INTERRUPT_CONTROLLER', system_bus=obj0, var_base='interrupt_controller')
obj2 = system_bus_device_node(qom_type='TYPE_UART', system_bus=obj0, var_base='uart')
obj3 = device_node(qom_type='TYPE_CPU', var_base='cpu')
obj4 = system_bus_device_node(qom_type='UART', system_bus=obj0, var_base='uart')
obj5 = system_bus_device_node(qom_type='TYPE_PCI_HOST', system_bus=obj0, var_base='pci_host')
obj6 = pci_express_bus_node(host_bridge=obj5)
obj7 = pci_express_device_node(qom_type='TYPE_ETHERNET', pci_express_bus=obj6, slot=0, function=0, var_base='ethernet')
obj8 = pci_express_device_node(qom_type='TYPE_ETHERNET', pci_express_bus=obj6, slot=0, function=0, var_base='ethernet')
obj9 = system_bus_device_node(qom_type='TYPE_ROM', system_bus=obj0, var_base='rom')
obj10 = system_bus_device_node(qom_type='TYPE_HID', system_bus=obj0, var_base='hid')
obj11 = system_bus_device_node(qom_type='TYPE_DISPLAY', system_bus=obj0, var_base='display')
obj12 = irq_line(src_dev=obj1, dst_dev=obj3)
obj13 = irq_hub(srcs=[], dsts=[])
obj14 = irq_line(src_dev=obj13, dst_dev=obj1)
obj15 = irq_line(src_dev=obj2, dst_dev=obj13)
obj16 = irq_line(src_dev=obj4, dst_dev=obj13)
obj17 = irq_line(src_dev=obj5, dst_dev=obj1, dst_irq_idx=1)
obj18 = irq_line(src_dev=obj9, dst_dev=obj1, dst_irq_idx=2)
obj19 = irq_line(src_dev=obj11, dst_dev=obj1, dst_irq_idx=3)
obj20 = irq_line(src_dev=obj10, dst_dev=obj1, dst_irq_idx=4)
obj21 = machine_node(name='description0', directory='')
obj21.add_node(obj0, with_id=0)
obj21.add_node(obj1, with_id=1)
obj21.add_node(obj2, with_id=2)
obj21.add_node(obj13, with_id=3)
obj21.add_node(obj3, with_id=4)
obj21.add_node(obj12, with_id=5)
obj21.add_node(obj14, with_id=6)
obj21.add_node(obj4, with_id=7)
obj21.add_node(obj15, with_id=8)
obj21.add_node(obj16, with_id=9)
obj21.add_node(obj5, with_id=10)
obj21.add_node(obj6, with_id=11)
obj21.add_node(obj7, with_id=12)
obj21.add_node(obj8, with_id=13)
obj21.add_node(obj17, with_id=14)
obj21.add_node(obj9, with_id=15)
obj21.add_node(obj18, with_id=16)
obj21.add_node(obj10, with_id=17)
obj21.add_node(obj11, with_id=18)
obj21.add_node(obj19, with_id=19)
obj21.add_node(obj20, with_id=20)
obj22 = machine_widget_layout(mdwl={0: (41.20573293511035, 125.9760158583141), 1: (96.1447438641203, 96.92583042837722), 2: (84.0, 189.0), 3: (148.0, 157.0), 4: (201.0, 34.0), 7: (154.0, 217.0), 10: (273.0, 241.0), 11: (293.0, 142.0), 12: (334.0, 55.0), 13: (333.0, 98.0), 15: (112.0, 26.0), 17: (-7.0, 16.0), 18: (-39.0, 60.0), -1: {'physical layout': False, 'IRQ lines points': {16: [], 19: [], 20: [], 5: [], 6: [], 8: [], 9: [], 14: [(230.0, 210.0), (229.0, 165.0)]}, 'show mesh': False, 'mesh step': 20}}, mtwl={}, use_tabs=True)
obj23 = gui_layout(desc_name='description0', opaque=obj22, shown=True)
obj23.lid = 0
obj24 = gui_project(layouts=[obj23], build_path=None, descriptions=[obj21]) |
"""
Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.
Your algorithm's runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1].
Solution:
- It's a typical binary search with a slight variation
- Ensure that all the indices are right.
"""
class Solution(object):
def find_first_occurence(self, nums, target, left, right):
if left > right: return -1
mid = (left+right)//2
if mid == 0 and nums[mid]==target: return 0
if nums[mid]==target and nums[mid-1]<target: return mid
if target > nums[mid]:
return self.find_first_occurence(nums, target, mid+1, right)
else:
return self.find_first_occurence(nums, target, left, mid-1)
def find_last_occurence(self, nums, target, left, right):
if left > right: return -1
mid = (left+right)//2
if mid == len(nums)-1 and nums[mid]==target:
return len(nums)-1
if nums[mid]==target and nums[mid+1]>target:
return mid
if target >= nums[mid]:
return self.find_last_occurence(nums, target, mid+1, right)
else:
return self.find_last_occurence(nums, target, left, mid-1)
def searchRange(self, nums, target):
if not nums: return [-1, -1]
first = self.find_first_occurence(nums, target, 0, len(nums)-1)
if first == -1: return [-1, -1]
last = self.find_last_occurence(nums, target, first, len(nums)-1)
return [first, last]
| """
Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.
Your algorithm's runtime complexity must be in the order of O(log n).
If the target is not found in the array, return [-1, -1].
Solution:
- It's a typical binary search with a slight variation
- Ensure that all the indices are right.
"""
class Solution(object):
def find_first_occurence(self, nums, target, left, right):
if left > right:
return -1
mid = (left + right) // 2
if mid == 0 and nums[mid] == target:
return 0
if nums[mid] == target and nums[mid - 1] < target:
return mid
if target > nums[mid]:
return self.find_first_occurence(nums, target, mid + 1, right)
else:
return self.find_first_occurence(nums, target, left, mid - 1)
def find_last_occurence(self, nums, target, left, right):
if left > right:
return -1
mid = (left + right) // 2
if mid == len(nums) - 1 and nums[mid] == target:
return len(nums) - 1
if nums[mid] == target and nums[mid + 1] > target:
return mid
if target >= nums[mid]:
return self.find_last_occurence(nums, target, mid + 1, right)
else:
return self.find_last_occurence(nums, target, left, mid - 1)
def search_range(self, nums, target):
if not nums:
return [-1, -1]
first = self.find_first_occurence(nums, target, 0, len(nums) - 1)
if first == -1:
return [-1, -1]
last = self.find_last_occurence(nums, target, first, len(nums) - 1)
return [first, last] |
FALSE=0
TRUE=1
DBSAVE=1
DBNOSAVE=0
INT_EXIT=0
INT_CONTINUE=1
INT_CANCEL=2
INT_TIMEOUT=3
DBMAXNUMLEN=33
DBMAXNAME=30
DBVERSION_UNKNOWN=0
DBVERSION_46=1
DBVERSION_100=2
DBVERSION_42=3
DBVERSION_70=4
DBVERSION_71=5
DBVERSION_72=6
DBTDS_UNKNOWN=0
DBTXPLEN=16
BCPMAXERRS=1
BCPFIRST=2
BCPLAST=3
BCPBATCH=4
BCPKEEPIDENTITY=8
BCPLABELED=5
BCPHINTS=6
DBCMDNONE=0
DBCMDPEND=1
DBCMDSENT=2
DBPARSEONLY=0
DBESTIMATE=1
DBSHOWPLAN=2
DBNOEXEC=3
DBARITHIGNORE=4
DBNOCOUNT=5
DBARITHABORT=6
DBTEXTLIMIT=7
DBBROWSE=8
DBOFFSET=9
DBSTAT=10
DBERRLVL=11
DBCONFIRM=12
DBSTORPROCID=13
DBBUFFER=14
DBNOAUTOFREE=15
DBROWCOUNT=16
DBTEXTSIZE=17
DBNATLANG=18
DBDATEFORMAT=19
DBPRPAD=20
DBPRCOLSEP=21
DBPRLINELEN=22
DBPRLINESEP=23
DBLFCONVERT=24
DBDATEFIRST=25
DBCHAINXACTS=26
DBFIPSFLAG=27
DBISOLATION=28
DBAUTH=29
DBIDENTITY=30
DBNOIDCOL=31
DBDATESHORT=32
DBCLIENTCURSORS=33
DBSETTIME=34
DBQUOTEDIDENT=35
DBNUMOPTIONS=36
DBPADOFF=0
DBPADON=1
OFF=0
ON=1
NOSUCHOPTION=2
MAXOPTTEXT=32
DBRESULT=1
DBNOTIFICATION=2
DBTIMEOUT=3
DBINTERRUPT=4
DBTXTSLEN=8
CHARBIND=0
STRINGBIND=1
NTBSTRINGBIND=2
VARYCHARBIND=3
VARYBINBIND=4
TINYBIND=6
SMALLBIND=7
INTBIND=8
FLT8BIND=9
REALBIND=10
DATETIMEBIND=11
SMALLDATETIMEBIND=12
MONEYBIND=13
SMALLMONEYBIND=14
BINARYBIND=15
BITBIND=16
NUMERICBIND=17
DECIMALBIND=18
BIGINTBIND=30
DBPRCOLSEP=21
DBPRLINELEN=22
DBRPCRETURN=1
DBRPCDEFAULT=2
NO_MORE_RESULTS=2
SUCCEED=1
FAIL=0
DB_IN=1
DB_OUT=2
DB_QUERYOUT=3
DBSINGLE=0
DBDOUBLE=1
DBBOTH=2
DBSETHOST=1
DBSETUSER=2
DBSETPWD=3
DBSETAPP=5
DBSETBCP=6
DBSETCHARSET=10
DBSETPACKET=11
DBSETENCRYPT=12
DBSETLABELED=13
DBSETDBNAME=14 | false = 0
true = 1
dbsave = 1
dbnosave = 0
int_exit = 0
int_continue = 1
int_cancel = 2
int_timeout = 3
dbmaxnumlen = 33
dbmaxname = 30
dbversion_unknown = 0
dbversion_46 = 1
dbversion_100 = 2
dbversion_42 = 3
dbversion_70 = 4
dbversion_71 = 5
dbversion_72 = 6
dbtds_unknown = 0
dbtxplen = 16
bcpmaxerrs = 1
bcpfirst = 2
bcplast = 3
bcpbatch = 4
bcpkeepidentity = 8
bcplabeled = 5
bcphints = 6
dbcmdnone = 0
dbcmdpend = 1
dbcmdsent = 2
dbparseonly = 0
dbestimate = 1
dbshowplan = 2
dbnoexec = 3
dbarithignore = 4
dbnocount = 5
dbarithabort = 6
dbtextlimit = 7
dbbrowse = 8
dboffset = 9
dbstat = 10
dberrlvl = 11
dbconfirm = 12
dbstorprocid = 13
dbbuffer = 14
dbnoautofree = 15
dbrowcount = 16
dbtextsize = 17
dbnatlang = 18
dbdateformat = 19
dbprpad = 20
dbprcolsep = 21
dbprlinelen = 22
dbprlinesep = 23
dblfconvert = 24
dbdatefirst = 25
dbchainxacts = 26
dbfipsflag = 27
dbisolation = 28
dbauth = 29
dbidentity = 30
dbnoidcol = 31
dbdateshort = 32
dbclientcursors = 33
dbsettime = 34
dbquotedident = 35
dbnumoptions = 36
dbpadoff = 0
dbpadon = 1
off = 0
on = 1
nosuchoption = 2
maxopttext = 32
dbresult = 1
dbnotification = 2
dbtimeout = 3
dbinterrupt = 4
dbtxtslen = 8
charbind = 0
stringbind = 1
ntbstringbind = 2
varycharbind = 3
varybinbind = 4
tinybind = 6
smallbind = 7
intbind = 8
flt8_bind = 9
realbind = 10
datetimebind = 11
smalldatetimebind = 12
moneybind = 13
smallmoneybind = 14
binarybind = 15
bitbind = 16
numericbind = 17
decimalbind = 18
bigintbind = 30
dbprcolsep = 21
dbprlinelen = 22
dbrpcreturn = 1
dbrpcdefault = 2
no_more_results = 2
succeed = 1
fail = 0
db_in = 1
db_out = 2
db_queryout = 3
dbsingle = 0
dbdouble = 1
dbboth = 2
dbsethost = 1
dbsetuser = 2
dbsetpwd = 3
dbsetapp = 5
dbsetbcp = 6
dbsetcharset = 10
dbsetpacket = 11
dbsetencrypt = 12
dbsetlabeled = 13
dbsetdbname = 14 |
# O(N) where n is len of string
def get_str_zig_zagged(s, numRows):
if numRows == 1:
return s
ret = ''
n = len(s)
cycle_len = numRows*2 - 2
for i in range(numRows):
j = 0
while j +i < n:
ret += s[j+i]
if (i != 0 and i != numRows -1 and j + cycle_len -i < n):
ret += s[j + cycle_len - i]
j += cycle_len
return ret | def get_str_zig_zagged(s, numRows):
if numRows == 1:
return s
ret = ''
n = len(s)
cycle_len = numRows * 2 - 2
for i in range(numRows):
j = 0
while j + i < n:
ret += s[j + i]
if i != 0 and i != numRows - 1 and (j + cycle_len - i < n):
ret += s[j + cycle_len - i]
j += cycle_len
return ret |
"""
A. The reconstructions preserve most of the latent features well:
- shape: ovals shapes are well preserved, whereas squares lose some sharpness
in their edges. Hearts are poorly preserved, as the sharp angles of their edges are lost.
- scale: shape scales are well preserved.
- orientation: orientations are well preserved.
- posX and posY: shape positions are very well preserved.
B. Since several of the latent features of the images are well preserved
in the reconstructions, it is possible that the VAE encoder has indeed
learned a feature space very similar to the known latent dimensions of the data.
However, it is also possible that the VAE encoder instead learned a different
latent feature space that is good enough to achieve reasonable image reconstruction.
Examining the RSMs should shed light on that.
"""; | """
A. The reconstructions preserve most of the latent features well:
- shape: ovals shapes are well preserved, whereas squares lose some sharpness
in their edges. Hearts are poorly preserved, as the sharp angles of their edges are lost.
- scale: shape scales are well preserved.
- orientation: orientations are well preserved.
- posX and posY: shape positions are very well preserved.
B. Since several of the latent features of the images are well preserved
in the reconstructions, it is possible that the VAE encoder has indeed
learned a feature space very similar to the known latent dimensions of the data.
However, it is also possible that the VAE encoder instead learned a different
latent feature space that is good enough to achieve reasonable image reconstruction.
Examining the RSMs should shed light on that.
""" |
red = 0
black = 1
empty = 2
#Expected Outcome: True
row_win = [
[empty, empty, empty, empty, empty, empty, empty],
[empty, empty, empty, empty, empty, empty, empty],
[empty, red, red, red, red, empty, empty],
[red, black, red, black, red, empty, empty],
[black, red, black, red, black, black, empty],
[black, black, red, black, black, red, black],
]
#Expected Outcome: True
col_win = [
[empty, empty, empty, empty, empty, empty, empty],
[empty, empty, empty, empty, empty, empty, empty],
[empty, red, empty, empty, empty, empty, empty],
[black, red, empty, empty, empty, empty, empty],
[black, red, empty, empty, empty, empty, empty],
[black, red, black, empty, empty, empty, empty],
]
#Expected Outcome: True
pos_diagonal_win = [
[empty, empty, empty, empty, empty, empty, empty],
[empty, empty, empty, empty, empty, empty, empty],
[empty, empty, empty, red, empty, empty, empty],
[empty, empty, red, black, empty, empty, empty],
[black, red, red, black, black, empty, empty],
[red, red, black, black, black, empty, empty],
]
#Expected Outcome: True
neg_diagonal_win = [
[empty, empty, empty, empty, empty, empty, empty],
[empty, empty, empty, empty, empty, empty, empty],
[red, black, empty, empty, empty, empty, empty],
[black, red, empty, empty, empty, empty, empty],
[black, red, red, black, empty, empty, empty],
[black, red, black, red, empty, empty, empty],
]
#Expected Outcome: True
almost_row_win = [
[empty, empty, empty, empty, empty, empty, empty],
[empty, empty, empty, empty, empty, empty, empty],
[empty, red, red, red, empty, empty, red],
[red, black, red, black, red, black, black],
[black, red, black, red, black, black, red],
[black, black, red, black, black, red, black],
]
#Expected Outcome: True
almost_col_win = [
[empty, empty, empty, empty, empty, empty, empty],
[empty, empty, empty, empty, empty, empty, empty],
[empty, empty, empty, empty, empty, empty, empty],
[black, red, empty, empty, empty, empty, empty],
[black, red, empty, empty, empty, empty, empty],
[black, red, black, empty, empty, empty, empty],
]
#Expected Outcome: True
almost_pos_diagonal_win = [
[empty, empty, empty, empty, empty, empty, empty],
[empty, empty, empty, empty, empty, empty, empty],
[empty, empty, empty, empty, empty, empty, empty],
[black, red, red, black, empty, empty, empty],
[black, red, red, black, empty, empty, empty],
[red, red, black, black, black, empty, empty],
]
#Expected Outcome: True
almost_neg_diagonal_win = [
[empty, empty, empty, empty, empty, empty, empty],
[empty, empty, empty, empty, empty, empty, empty],
[red, empty, empty, empty, empty, empty, empty],
[black, red, empty, empty, empty, empty, empty],
[black, red, red, empty, empty, empty, empty],
[black, red, black, empty, empty, empty, empty],
]
#Expected Outcome: False
col_loss = [
[empty, empty, empty, empty, empty, empty, empty],
[empty, empty, empty, empty, empty, empty, empty],
[black, empty, empty, empty, empty, empty, empty],
[black, red, empty, empty, empty, empty, empty],
[black, red, empty, empty, empty, empty, empty],
[black, red, empty, empty, empty, empty, empty],
]
#Expected Outcome: False (invalid board)
col_black_won_first = [
[empty, empty, empty, empty, empty, empty, empty],
[empty, empty, empty, empty, empty, empty, empty],
[black, red, empty, empty, empty, empty, empty],
[black, red, empty, empty, empty, empty, empty],
[black, red, empty, empty, empty, empty, empty],
[black, red, empty, empty, empty, empty, empty],
]
#Expected Outcome: False
black_won = [
[empty, empty, empty, empty, empty, empty, empty],
[empty, empty, empty, empty, empty, empty, empty],
[black, empty, empty, empty, empty, empty, empty],
[black, red, empty, empty, empty, empty, empty],
[black, red, empty, empty, empty, empty, empty],
[black, red, empty, empty, empty, empty, empty],
] | red = 0
black = 1
empty = 2
row_win = [[empty, empty, empty, empty, empty, empty, empty], [empty, empty, empty, empty, empty, empty, empty], [empty, red, red, red, red, empty, empty], [red, black, red, black, red, empty, empty], [black, red, black, red, black, black, empty], [black, black, red, black, black, red, black]]
col_win = [[empty, empty, empty, empty, empty, empty, empty], [empty, empty, empty, empty, empty, empty, empty], [empty, red, empty, empty, empty, empty, empty], [black, red, empty, empty, empty, empty, empty], [black, red, empty, empty, empty, empty, empty], [black, red, black, empty, empty, empty, empty]]
pos_diagonal_win = [[empty, empty, empty, empty, empty, empty, empty], [empty, empty, empty, empty, empty, empty, empty], [empty, empty, empty, red, empty, empty, empty], [empty, empty, red, black, empty, empty, empty], [black, red, red, black, black, empty, empty], [red, red, black, black, black, empty, empty]]
neg_diagonal_win = [[empty, empty, empty, empty, empty, empty, empty], [empty, empty, empty, empty, empty, empty, empty], [red, black, empty, empty, empty, empty, empty], [black, red, empty, empty, empty, empty, empty], [black, red, red, black, empty, empty, empty], [black, red, black, red, empty, empty, empty]]
almost_row_win = [[empty, empty, empty, empty, empty, empty, empty], [empty, empty, empty, empty, empty, empty, empty], [empty, red, red, red, empty, empty, red], [red, black, red, black, red, black, black], [black, red, black, red, black, black, red], [black, black, red, black, black, red, black]]
almost_col_win = [[empty, empty, empty, empty, empty, empty, empty], [empty, empty, empty, empty, empty, empty, empty], [empty, empty, empty, empty, empty, empty, empty], [black, red, empty, empty, empty, empty, empty], [black, red, empty, empty, empty, empty, empty], [black, red, black, empty, empty, empty, empty]]
almost_pos_diagonal_win = [[empty, empty, empty, empty, empty, empty, empty], [empty, empty, empty, empty, empty, empty, empty], [empty, empty, empty, empty, empty, empty, empty], [black, red, red, black, empty, empty, empty], [black, red, red, black, empty, empty, empty], [red, red, black, black, black, empty, empty]]
almost_neg_diagonal_win = [[empty, empty, empty, empty, empty, empty, empty], [empty, empty, empty, empty, empty, empty, empty], [red, empty, empty, empty, empty, empty, empty], [black, red, empty, empty, empty, empty, empty], [black, red, red, empty, empty, empty, empty], [black, red, black, empty, empty, empty, empty]]
col_loss = [[empty, empty, empty, empty, empty, empty, empty], [empty, empty, empty, empty, empty, empty, empty], [black, empty, empty, empty, empty, empty, empty], [black, red, empty, empty, empty, empty, empty], [black, red, empty, empty, empty, empty, empty], [black, red, empty, empty, empty, empty, empty]]
col_black_won_first = [[empty, empty, empty, empty, empty, empty, empty], [empty, empty, empty, empty, empty, empty, empty], [black, red, empty, empty, empty, empty, empty], [black, red, empty, empty, empty, empty, empty], [black, red, empty, empty, empty, empty, empty], [black, red, empty, empty, empty, empty, empty]]
black_won = [[empty, empty, empty, empty, empty, empty, empty], [empty, empty, empty, empty, empty, empty, empty], [black, empty, empty, empty, empty, empty, empty], [black, red, empty, empty, empty, empty, empty], [black, red, empty, empty, empty, empty, empty], [black, red, empty, empty, empty, empty, empty]] |
class Vertex:
def __init__(self, value):
self.value = value
self.edges = {}
def add_edge(self, vertex, weight=0):
self.edges[vertex] = weight
def get_edges(self):
return list(self.edges.keys())
class Graph:
def __init__(self, directed = False):
self.graph_dict = {}
self.directed = directed
def add_vertex(self, vertex):
self.graph_dict[vertex.value] = vertex
def add_edge(self, from_vertex, to_vertex, weight = 0):
self.graph_dict[from_vertex.value].add_edge(to_vertex.value, weight)
if not self.directed:
self.graph_dict[to_vertex.value].add_edge(from_vertex.value, weight)
#BFS
def find_path(self, start_vertex, end_vertex):
start = [start_vertex]
seen = {}
while len(start) > 0:
current_vertex = start.pop(0)
seen[current_vertex] = True
if current_vertex == end_vertex:
return True
else:
vertices_to_visit = set(self.graph_dict[current_vertex].edges.keys())
start += [vertex for vertex in vertices_to_visit if vertex not in seen]
return False
class adjacency_matrices:
def __init__(self, data):
self.graph = data
self.matrix_elements = sorted(self.graph.keys())
self.cols = self.rows = len(self.matrix_elements)
def create_matrix(self):
adjacency_matrices = [[0 for x in range(self.rows)] for y in range(self.cols)]
edges_list = []
# we found all the vertexcies that have relationship between them
# then we store them in pair as
# [(A, B), (A, C), (B, E), ...]
for key in self.matrix_elements:
for neighbor in self.graph[key]:
edges_list.append((key, neighbor))
# then we fill the grids that relationship with 1
for edge in edges_list:
index_of_first_vertex = self.matrix_elements.index(edge[0])
index_of_second_vertex = self.matrix_elements.index(edge[1])
adjacency_matrices[index_of_first_vertex][index_of_second_vertex] = 1
| class Vertex:
def __init__(self, value):
self.value = value
self.edges = {}
def add_edge(self, vertex, weight=0):
self.edges[vertex] = weight
def get_edges(self):
return list(self.edges.keys())
class Graph:
def __init__(self, directed=False):
self.graph_dict = {}
self.directed = directed
def add_vertex(self, vertex):
self.graph_dict[vertex.value] = vertex
def add_edge(self, from_vertex, to_vertex, weight=0):
self.graph_dict[from_vertex.value].add_edge(to_vertex.value, weight)
if not self.directed:
self.graph_dict[to_vertex.value].add_edge(from_vertex.value, weight)
def find_path(self, start_vertex, end_vertex):
start = [start_vertex]
seen = {}
while len(start) > 0:
current_vertex = start.pop(0)
seen[current_vertex] = True
if current_vertex == end_vertex:
return True
else:
vertices_to_visit = set(self.graph_dict[current_vertex].edges.keys())
start += [vertex for vertex in vertices_to_visit if vertex not in seen]
return False
class Adjacency_Matrices:
def __init__(self, data):
self.graph = data
self.matrix_elements = sorted(self.graph.keys())
self.cols = self.rows = len(self.matrix_elements)
def create_matrix(self):
adjacency_matrices = [[0 for x in range(self.rows)] for y in range(self.cols)]
edges_list = []
for key in self.matrix_elements:
for neighbor in self.graph[key]:
edges_list.append((key, neighbor))
for edge in edges_list:
index_of_first_vertex = self.matrix_elements.index(edge[0])
index_of_second_vertex = self.matrix_elements.index(edge[1])
adjacency_matrices[index_of_first_vertex][index_of_second_vertex] = 1 |
"""
@author: David Lei
@since: 6/11/2017
https://www.hackerrank.com/challenges/reverse-a-doubly-linked-list/problem
Given the head to a doubly linked list reverse it and return the head of the reversed list.
Both pass :)
"""
def ReverseIterative(head):
if not head:
return head
cur = head
while cur:
next_node = cur.next
cur.next = cur.prev
cur.prev = next_node
if not next_node: # End of the list.
return cur
cur = next_node
def ReverseRecursive(head):
if not head:
return head
if head.next is None: # Base case, end of the list.
tmp = head.next
head.next = head.prev
head.prev = tmp
return head
next_node = head.next
head.next = head.prev
head.prev = next_node
return ReverseRecursive(next_node)
| """
@author: David Lei
@since: 6/11/2017
https://www.hackerrank.com/challenges/reverse-a-doubly-linked-list/problem
Given the head to a doubly linked list reverse it and return the head of the reversed list.
Both pass :)
"""
def reverse_iterative(head):
if not head:
return head
cur = head
while cur:
next_node = cur.next
cur.next = cur.prev
cur.prev = next_node
if not next_node:
return cur
cur = next_node
def reverse_recursive(head):
if not head:
return head
if head.next is None:
tmp = head.next
head.next = head.prev
head.prev = tmp
return head
next_node = head.next
head.next = head.prev
head.prev = next_node
return reverse_recursive(next_node) |
N = int(input())
if N <= 5:
print(N + 2)
elif N == 6:
print('1')
else:
print('2')
| n = int(input())
if N <= 5:
print(N + 2)
elif N == 6:
print('1')
else:
print('2') |
class ManipulationVelocities(object):
"""
Describes the speed at which manipulations occurs.
ManipulationVelocities(linearVelocity: Vector,angularVelocity: float,expansionVelocity: Vector)
"""
@staticmethod
def __new__(self,linearVelocity,angularVelocity,expansionVelocity):
""" __new__(cls: type,linearVelocity: Vector,angularVelocity: float,expansionVelocity: Vector) """
pass
AngularVelocity=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the speed of rotation.
Get: AngularVelocity(self: ManipulationVelocities) -> float
"""
ExpansionVelocity=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the rate at which the manipulation is resized.
Get: ExpansionVelocity(self: ManipulationVelocities) -> Vector
"""
LinearVelocity=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets or sets the speed of linear motion.
Get: LinearVelocity(self: ManipulationVelocities) -> Vector
"""
| class Manipulationvelocities(object):
"""
Describes the speed at which manipulations occurs.
ManipulationVelocities(linearVelocity: Vector,angularVelocity: float,expansionVelocity: Vector)
"""
@staticmethod
def __new__(self, linearVelocity, angularVelocity, expansionVelocity):
""" __new__(cls: type,linearVelocity: Vector,angularVelocity: float,expansionVelocity: Vector) """
pass
angular_velocity = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Gets or sets the speed of rotation.\n\n\n\nGet: AngularVelocity(self: ManipulationVelocities) -> float\n\n\n\n'
expansion_velocity = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Gets or sets the rate at which the manipulation is resized.\n\n\n\nGet: ExpansionVelocity(self: ManipulationVelocities) -> Vector\n\n\n\n'
linear_velocity = property(lambda self: object(), lambda self, v: None, lambda self: None)
'Gets or sets the speed of linear motion.\n\n\n\nGet: LinearVelocity(self: ManipulationVelocities) -> Vector\n\n\n\n' |
# First step printing UI
def drawFields(field):
for row in range(5):
if row % 2 == 0:
fieldRow = int(row / 2)
for column in range(5): # 0,1,2,3,4 --> 0,.,1,.,2
if column % 2 == 0: # 0,2,4
fieldColumn = int(column / 2) # 0,1,2
if column != 4:
print(field[fieldColumn][fieldRow], end="")
else:
print(field[fieldColumn][fieldRow])
else:
print("|", end="")
else:
print("-----")
Player = 1
currentField = [[" ", " ", " "], [" ", " ", " "], [" ", " ", " "]]
drawFields(currentField)
while(True):
print("Player turn: ", Player)
MoveRow = int(input("Please enter the row: "))
MoveColumn = int(input("Please enter the column: "))
if Player == 1:
if currentField[MoveColumn][MoveRow] == " ":
currentField[MoveColumn][MoveRow] = "X"
Player = 2
else:
if currentField[MoveColumn][MoveRow] == " ":
currentField[MoveColumn][MoveRow] = "O"
Player = 1
drawFields(currentField)
| def draw_fields(field):
for row in range(5):
if row % 2 == 0:
field_row = int(row / 2)
for column in range(5):
if column % 2 == 0:
field_column = int(column / 2)
if column != 4:
print(field[fieldColumn][fieldRow], end='')
else:
print(field[fieldColumn][fieldRow])
else:
print('|', end='')
else:
print('-----')
player = 1
current_field = [[' ', ' ', ' '], [' ', ' ', ' '], [' ', ' ', ' ']]
draw_fields(currentField)
while True:
print('Player turn: ', Player)
move_row = int(input('Please enter the row: '))
move_column = int(input('Please enter the column: '))
if Player == 1:
if currentField[MoveColumn][MoveRow] == ' ':
currentField[MoveColumn][MoveRow] = 'X'
player = 2
elif currentField[MoveColumn][MoveRow] == ' ':
currentField[MoveColumn][MoveRow] = 'O'
player = 1
draw_fields(currentField) |
# print index of string
str_one = 'python land is a place for everyone not just beginner'
# 012345
print(str_one[0]) # print the first letter of our string str-one
print(str_one[-1]) # pring the last letter of our string str_one
# print special range of string
print(str_one[0:4]) # reult will be from index 0 till index 4, index 4 is not included, only 4 index is included.
print(str_one[0:]) # start from index 0 till end and will print whole string
print(str_one[1:]) # same as above just start from index 1
# f string in python, good for concat multiple string
first_name = 'pooya'
last_name = 'panahandeh'
message = f'{first_name} [{last_name}] is a beginner programmer.' # f string is a method to manipulate the string
print(message)
# get the number of element of string
course = 'python is awsome'
print(len(course))
# change string to upper case
print(course.upper())
# change letter to lower case
course_two = "NODEJS PROGRAMMING"
print(course_two.lower())
# finding specific element in string
str_two = 'we are one of the best group of people'
print(str_two.find('g'))
# replace two words in string
print(str_two.replace('best', 'fucking best'))
print('one' in str_two) # checking if there the string we mentioned is exist in str_two or not, result will be true or false
# division and remainder operation in python
print(10 / 3) # result will be float
print(10 // 3) # result will be integer
# multiplication
print(10 * 2) # multiplication of two number
print(10 ** 2) # power of number
# assign variable to number and manipulate.
x = 10
# x = x + 4 short way in next line
x += 4
print(x)
# first multiplication then addition
z = 10 + 2 ** 2
print(z)
| str_one = 'python land is a place for everyone not just beginner'
print(str_one[0])
print(str_one[-1])
print(str_one[0:4])
print(str_one[0:])
print(str_one[1:])
first_name = 'pooya'
last_name = 'panahandeh'
message = f'{first_name} [{last_name}] is a beginner programmer.'
print(message)
course = 'python is awsome'
print(len(course))
print(course.upper())
course_two = 'NODEJS PROGRAMMING'
print(course_two.lower())
str_two = 'we are one of the best group of people'
print(str_two.find('g'))
print(str_two.replace('best', 'fucking best'))
print('one' in str_two)
print(10 / 3)
print(10 // 3)
print(10 * 2)
print(10 ** 2)
x = 10
x += 4
print(x)
z = 10 + 2 ** 2
print(z) |
# https://leetcode.com/problems/excel-sheet-column-title/
# ---------------------------------------------------
# Runtime Complexity: O(log26(n)) => O(log(n))
# Space Complexity: O(log26(n)) => O(log(n)), if we take into account res, otherwise it's O(1).
class Solution:
def convertToTitle(self, n: int) -> str:
res = ''
while n > 0:
# Because Radix starts from 1 to 26.
# In contrast to decimal Radix (which is from 0 to 9)
n -= 1
ch_code = n % 26
n = (n - ch_code) // 26
res = chr(ord('A') + ch_code) + res
return res
# ---------------------------------------------------
# Test Cases
# ---------------------------------------------------
solution = Solution()
# 'A'
print(solution.convertToTitle(1))
# 'B'
print(solution.convertToTitle(2))
# 'Z'
print(solution.convertToTitle(26))
# 'AB'
print(solution.convertToTitle(28))
# 'ZY'
print(solution.convertToTitle(701))
# 'BMG'
print(solution.convertToTitle(1697))
| class Solution:
def convert_to_title(self, n: int) -> str:
res = ''
while n > 0:
n -= 1
ch_code = n % 26
n = (n - ch_code) // 26
res = chr(ord('A') + ch_code) + res
return res
solution = solution()
print(solution.convertToTitle(1))
print(solution.convertToTitle(2))
print(solution.convertToTitle(26))
print(solution.convertToTitle(28))
print(solution.convertToTitle(701))
print(solution.convertToTitle(1697)) |
###############################################################################
##
## protoql.py
##
## A language for rapid assembly, querying, and interactive visual rendering
## of common, abstract mathematical structures.
##
## Web: protoql.org
## Version: 0.0.3.0
##
##
###############################################################################
##
def html(raw):
"""
Render a stand-alone HTML page containing the supplied diagram.
"""
prefix = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="http://code.jquery.com/jquery-2.2.0.min.js"></script>
<script>
(function (protoql) {
"use strict";
/*****************************************************************************
** Notation library (individually instantiated by each visualization object).
*/
protoql.Notation = (function(Visualization) {
var V = Visualization, Notation = {};
/***************************************************************************
** Static routines and methods.
*/
Notation.decorators =
(function(raw) {
raw = raw.trim();
if (raw.length > 0 && raw.charAt(0) == "!") {
V.interaction = {'zoom':false, 'pan':false, 'drag':false, 'edit':false};
return raw.substr(1);
} else if (raw.length > 0 && raw.charAt(0) == "#") {
V.interaction = {'zoom':true, 'pan':true, 'drag':true, 'edit':true};
return raw.substr(1);
} else
return raw;
});
Notation.graph =
(function(raw) {
raw = Notation.decorators(raw);
if (raw.length == 0 || raw.substr(0,6) != "graph(") return false;
var member = (function(x,xs) { for (var i=0; i<xs.length; i++) if (xs[i]==x) return true; return false; });
var set = (function(l) { var s = []; for (var i=0; i<l.length; i++) if (!member(l[i],s)) s.push(l[i]); return s; });
raw = raw.trim()
.replace(/{/g, "set<[").replace(/}/g, "]>")
.replace(/\(/g, "[").replace(/\)/g, "]")
.replace(/</g, "(").replace(/>/g, ")")
.replace("graph[", "[");
var args = eval(raw), nodes = null, links = null;
if (args.length == 1) {
links = args[0], nodes = [];
for (var i = 0; i < links.length; i++)
nodes = nodes.concat([links[i][0], links[i][1]]);
nodes = set(nodes);
} else if (args.length == 2) {
nodes = set(args[0]), links = args[1];
}
var listOfListsOfNodes = [];
var rows = Math.ceil(Math.sqrt(nodes.length)), cols = Math.ceil(Math.sqrt(nodes.length));
var col = 0;
for (var i = 0; i < nodes.length; i++) {
if ((i % cols) == 0)
listOfListsOfNodes.push([]);
listOfListsOfNodes[listOfListsOfNodes.length-1].push(nodes[i]);
for (var j = 0; j < links.length; j++) {
if (links[j][0] == nodes[i]) links[j][0] = [listOfListsOfNodes.length-1, (i % cols)];
if (links[j][1] == nodes[i]) links[j][1] = [listOfListsOfNodes.length-1, (i % cols)];
}
}
return Notation.listOfListsOfNodesToData({nodes:listOfListsOfNodes, links:links, groups:[]}, false);
});
Notation.relation =
(function(raw) {
raw = Notation.decorators(raw);
if (raw.length == 0 || raw.substr(0,9) != "relation(") return false;
var member = (function(x,xs) { for (var i=0; i<xs.length; i++) if (xs[i]==x) return true; return false; });
var set = (function(l) { var s = []; for (var i=0; i<l.length; i++) if (!member(l[i],s)) s.push(l[i]); return s; });
raw = raw.trim()
.replace(/{/g, "set<[").replace(/}/g, "]>")
.replace(/\(/g, "[").replace(/\)/g, "]")
.replace(/</g, "(").replace(/>/g, ")")
.replace("relation[", "[");
var args = eval(raw), dom = null, cod = null, links = null;
if (args.length == 1) {
links = args[0], dom = [];
for (var i = 0; i < links.length; i++)
dom = dom.concat([links[i][0], links[i][1]]);
cod = dom = set(dom);
} else if (args.length == 2) {
dom = args[0], cod = args[0], links = args[1];
} else if (args.length == 3) {
dom = args[0], cod = args[1], links = args[2];
}
var listOfListsOfNodes = [];
for (var i = 0; i < Math.max(dom.length, cod.length); i++) {
var a = (i < dom.length) ? dom[i] : null;
var b = (i < cod.length) ? cod[i] : null;
listOfListsOfNodes.push([a, null, b]);
for (var j = 0; j < links.length; j++) {
if (a != null && links[j][0] == a) links[j][0] = [i, 0];
if (b != null && links[j][1] == b) links[j][1] = [i, 2];
}
}
return Notation.listOfListsOfNodesToData({nodes:listOfListsOfNodes, links:links, groups:[]}, false);
});
Notation.table =
(function(raw) {
raw = Notation.decorators(raw);
if (raw.length == 0 || raw.substr(0,6) != "table(")
return false;
raw = raw.trim().replace("table(", "(");
var listOfListsOfNodes = eval(raw);
var check = true;
for (var r = 0; r < listOfListsOfNodes.length; r++)
for (var c = 0; c < listOfListsOfNodes[r].length; c++)
check = check && (
(listOfListsOfNodes[r][c] == null) || (typeof listOfListsOfNodes[r][c] === "string")
|| (listOfListsOfNodes[r][c].constructor === Array && listOfListsOfNodes[r][c].length == 1)
);
if (!check)
return false;
return Notation.listOfListsOfNodesToData({nodes:listOfListsOfNodes, links:[], groups:[]}, true);
});
Notation.listOfListsOfNodesToData =
(function(d, deriveLinks) {
var rows = d.nodes.length;
var cols = 0; for (var i = 0; i < d.nodes.length; i++) cols = Math.max(cols, d.nodes[i].length);
V.layout.grid.width = Math.floor(V.dimensions.width/cols);
V.layout.grid.height = Math.floor(V.dimensions.height/rows);
//var x = d3.scale.ordinal().domain(d3.range(cols)).rangePoints([0, V.dimensions.width], 1);
//var y = d3.scale.ordinal().domain(d3.range(rows)).rangePoints([0, V.dimensions.height], 1);
var c = d3.scale.category20().domain(d3.range(7));
V.data.nodes = [];
for (var row = 0; row < d.nodes.length; row++) {
for (var col = 0; col < d.nodes[row].length; col++) {
if (d.nodes[row][col] != null) {
var t = (typeof d.nodes[row][col] === "string") ? d.nodes[row][col] : d.nodes[row][col][0];
var es_txt = t.split("``"), t = es_txt[es_txt.length - 1], es = (es_txt.length == 2) ? es_txt[0].split("`") : [];
var shape = (typeof d.nodes[row][col] === "string") ? "circle" : "rect";
var node = {
color: c(Math.floor(Math.random()*7)), shape: shape, text: t,
rx: 5, ry: 5, offx: 0, offy: 0, x: V.layout.grid.width*col, y: V.layout.grid.height*row
};
d.nodes[row][col] = node;
V.data.nodes.push(node);
if (deriveLinks) {
for (var i = 0; i < es.length; i++) {
var e = es[i].split(":")[0],
lbl = (es[i].split(":").length > 0) ? es[i].split(":")[1] : null;
var tr = row, tc = col;
for (var j = 0; j < e.length; j++) {
if (e[j] == "u") tr -= 1;
else if (e[j] == "d") tr += 1;
else if (e[j] == "l") tc -= 1;
else if (e[j] == "r") tc += 1;
else if (e[j] == "s") /* Self-link; nothing. */;
}
d.links.push([[row,col], [tr,tc]].concat((lbl != null) ? [lbl] : []));
}
}
}
}
}
V.data.links = [];
for (var i = 0; i < d.links.length; i++) {
var s = d.links[i][0], t = d.links[i][1],
e = {source:d.nodes[s[0]][s[1]], target:d.nodes[t[0]][t[1]], curved:false};
if (d.links[i].length == 3)
e.label = d.links[i][2];
V.data.links.push(e);
}
return true;
});
/***************************************************************************
** Initialization.
*/
return Notation;
}); // /protoql.Notation
/*****************************************************************************
** Geometry library (individually instantiated by each visualization object).
*/
protoql.Geometry = (function(Visualization) {
var V = Visualization, Geometry = {};
/***************************************************************************
** Static routines for vector arithmetic and shape intersections.
*/
Geometry.sum = (function(v, w) { return {x: v.x + w.x, y: v.y + w.y}; });
Geometry.diff = (function(v, w) { return {x: v.x - w.x, y: v.y - w.y}; });
Geometry.length = (function(v) { return Math.sqrt(Math.pow(v.x,2) + Math.pow(v.y,2)); });
Geometry.scale = (function(s, v) { return {x: s*v.x, y: s*v.y}; });
Geometry.middle = (function(v, w) { return Geometry.sum(v,Geometry.scale(0.5,Geometry.diff(w,v))); });
Geometry.rotate = (function(v) { return {x:0-v.y, y:v.x}; });
Geometry.normalize =
(function(v) {
var d = Math.sqrt(Math.pow(v.x,2) + Math.pow(v.y,2));
return {x: v.x/d, y: v.y/d};
});
Geometry.orth =
(function(s, t) {
return Geometry.rotate(Geometry.normalize(Geometry.diff(t, s)));
});
Geometry.offpath =
(function(s, t, a) {
var r = Geometry.sum(Geometry.middle(s, t), Geometry.scale(a, Geometry.orth(s, t)));
if(isNaN(r.x) || isNaN(r.y))
return Geometry.middle(s, t);
return r;
});
Geometry.intersects =
(function(c, d, a, b) {
var x1 = c.x, x2 = d.x, x3 = a.x, x4 = b.x, y1 = c.y, y2 = d.y, y3 = a.y, y4 = b.y,
x13 = x1 - x3, x21 = x2 - x1, x43 = x4 - x3, y13 = y1 - y3, y21 = y2 - y1, y43 = y4 - y3,
ua = (x43 * y13 - y43 * x13) / (y43 * x21 - x43 * y21);
return {x:x1 + ua * x21, y:y1 + ua * y21};
});
Geometry.maxRadiusToOutside =
(function(s, t) {
var r1 = null, r2 = null;
if (s.shape == 'rect') r1 = Math.max(s.height, s.width)/1.7;
else if (s.shape == "circle") r1 = s.r;
if (t.shape == 'rect') r2 = Math.max(t.height, t.width)/1.7;
else if (t.shape == "circle") r2 = t.r;
return Math.max(r1, r2);
});
Geometry.inShape =
(function(p, s) {
if (s.shape == 'rect')
return p.x > s.x - (s.width/2) && p.x < s.x +(s.width/2) && p.y > s.y - (s.height/2) && p.y < s.y + (s.height/2);
else if (s.shape == "circle")
return Math.sqrt(Math.pow(s.x - p.x, 2) + Math.pow(s.y - p.y, 2)) < s.r;
});
Geometry.inLine =
(function(a,c,d) {
return a.x >= Math.min(c.x,d.x) && a.x <= Math.max(c.x,d.x) && a.y >= Math.min(c.y,d.y) && a.y <= Math.max(c.y,d.y);
});
Geometry.onEdgeCirc =
(function(e, which, offset) {
offset = (offset == null) ? {x:0, y:0} : offset; // So symmetric edges intersect in different locations.
var c = e[which];
var dx = (which == "source" ? -1 : 1)*(e.source.x - e.target.x),
dy = (which == "source" ? -1 : 1)*(e.target.y - e.source.y);
var d = Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2));
var x = c.x + ((c.r*dx)/d), y = c.y - ((c.r*dy)/d);
return {x:isNaN(x) ? c.x : x, y:isNaN(y) ? c.y : y};
});
Geometry.onEdgeRect =
(function(e, which, offset) {
offset = (offset == null) ? {x:0, y:0} : offset; // So symmetric edges intersect in different locations.
var r = Geometry.centeredPaddedRect(e[which]);
var a = Geometry.sum(e.source, offset), b = Geometry.sum(e.target, offset);
var lines = [
[r, {x:r.x+r.width,y:r.y}], [{x:r.x,y:r.y+r.height}, {x:r.x+r.width,y:r.y+r.height}],
[r, {x:r.x,y:r.y+r.height}], [{x:r.x+r.width,y:r.y}, {x:r.x+r.width,y:r.y+r.height}]
];
var inters = lines.map(function(x) { return Geometry.intersects(x[0],x[1],a,b); });
if (Geometry.inLine(inters[0],a,b) && inters[0].x >= r.x && inters[0].x <= r.x + r.width)
return inters[0];
else if (Geometry.inLine(inters[1],a,b) && inters[1].x >= r.x && inters[1].x <= r.x + r.width)
return inters[1];
else if (Geometry.inLine(inters[2],a,b) && inters[2].y >= r.y && inters[2].y <= r.y + r.height)
return inters[2];
else if (Geometry.inLine(inters[3],a,b) && inters[3].y >= r.y && inters[3].y <= r.y + r.height)
return inters[3];
else
return e[which];
});
Geometry.onEdge =
(function(e, which, offset) {
if (e[which].shape == "rect")
return Geometry.onEdgeRect(e, which, offset);
if (e[which].shape == "circle")
return Geometry.onEdgeCirc(e, which, offset);
});
Geometry.centeredPaddedRect =
(function(node) {
var rect = {};
rect.x = node.x - (node.width + V.dimensions.padding) / 2;
rect.y = node.y - (node.height + V.dimensions.padding) / 2;
rect.width = node.width + V.dimensions.padding;
rect.height = node.height + V.dimensions.padding;
return rect;
});
/***************************************************************************
** Initialization.
*/
return Geometry;
}); // /protoql.Geometry
/*****************************************************************************
** Interactive visualization objects.
*/
protoql.Visualizations = (function(arg) {
var vs = [];
if (arg.constructor === Array)
for (var i = 0; i < arg.length; i++)
vs.push(protoql.Visualization(arg[i]));
else if (arg instanceof jQuery && typeof arg.each === "function")
arg.each(function(index) {
vs.push(protoql.Visualization($(this)));
});
return vs;
});
protoql.Visualization = (function(arg) {
// Process constructor argument.
var id = null, obj = null, val = null;
if (typeof arg === "string") {
id = arg;
obj = document.getElementById(id);
val = (obj != null) ? obj.innerHTML : null;
} else if (arg instanceof jQuery) {
obj = arg;
if (typeof obj.attr('id') !== "string") // Generate random identifier.
obj.attr('id', "id"+Date.now()+""+Math.floor(Math.random()*10000));
id = obj.attr('id');
val = obj.html();
}
var Visualization = {}, V = Visualization;
/***************************************************************************
** Data fields and properties.
*/
Visualization.divId = id;
Visualization.obj = obj;
Visualization.val = val;
Visualization.svg = null;
Visualization.vis = null;
Visualization.zoom = d3.behavior.zoom();
Visualization.zoompan = {translate:{x:0, y:0}, scale:1};
Visualization.built = false;
Visualization.force = null;
Visualization.data = {nodes: null, links: null, groups: null};
Visualization.nodesEnter = null;
Visualization.linksEnter = null;
Visualization.dimensions = {width: null, height: null, padding: null};
Visualization.layout = {grid: {width: null, height: null}};
Visualization.interaction = {zoom:true, pan:true, drag:true, edit:false};
var G = Visualization.geometry = protoql.Geometry(Visualization);
var N = Visualization.notation = protoql.Notation(Visualization);
/***************************************************************************
** Routines and methods.
*/
var lineFunction =
d3.svg
.line()
.x(function (d) { return d.x; })
.y(function (d) { return d.y; })
.interpolate("basis");
// Resolve collisions between nodes.
var collision =
(function(alpha) {
var padding = 6;
var maxRadius = 7;
var quadtree = d3.geom.quadtree(nodes);
return function(d) {
var r = d.r + maxRadius + padding,
nx1 = d.x - r, nx2 = d.x + r,
ny1 = d.y - r, ny2 = d.y + r;
quadtree.visit(function(quad, x1, y1, x2, y2) {
if (quad.point && (quad.point !== d)) {
var x = d.x - quad.point.x, y = d.y - quad.point.y,
l = Math.sqrt(x * x + y * y),
r = d.r + quad.point.r + (d.color !== quad.point.color) * padding;
if (l < r) {
l = (l - r) / l * alpha;
d.x -= x *= l;
d.y -= y *= l;
quad.point.x += x;
quad.point.y += y;
}
}
return x1 > nx2 || x2 < nx1 || y1 > ny2 || y2 < ny1;
});
};
});
var alignment =
(function(alpha) {
return function(d) {
d.cx = Math.floor(d.x - (d.x % V.layout.grid.width)+(V.layout.grid.width*0.5));
d.x += (d.cx - d.x) * alpha;
d.cy = Math.floor(d.y - (d.y % V.layout.grid.height)+(V.layout.grid.height*0.5));
d.y += (d.cy - d.y) * alpha;
};
});
var tick =
(function(e) {
V.nodesEnter
.each(alignment(0.8 * e.alpha))
//.each(collision(.5))
.attr("transform", function (d) { return "translate("+(d.x + d.offx)+","+(d.y + d.offy)+")"; });
V.linksEnter
.attr("d", function (e) {
var s = G.onEdge(e, 'source'), t = G.onEdge(e, 'target'),
points = null, lbl = [e.source, e.target, 15];
if (G.inShape(t, e.source) || G.inShape(s, e.target)) {
var orient = (e.source == e.target) ? -1 : 1,
es = e.source, et = e.target,
d = G.diff(e.source, e.target),
l = G.length(d),
m = Math.abs(G.maxRadiusToOutside(e.source, e.target)),
kx = (l < 2) ? m + 9 : d.x * Math.min(1.3*m, 1.5*(m/(l+1))), ky = (l < 2) ? m + 9 : d.y * Math.min(1.3*m, 1.5*(m/(l+1))),
p = {x:es.x + 1.3*ky, y:es.y - kx}, q = {x:et.x + (orient*(0.9)*ky), y:et.y - kx},
s = G.onEdge({source:es, target:p}, 'source'), t = G.onEdge({source:q, target:et}, 'target');
points = [s, p, q, t];
lbl = [p,q,10];
} else if (e.curved == true) {
var off = G.scale(5, G.orth(s, t)), s = G.onEdge(e, 'source', off), t = G.onEdge(e, 'target', off);
points = [s, G.offpath(s, t, 5), t];
} else {
points = [s, t];
}
// Position the edge label.
var t = V.zoompan.translate, s = V.zoompan.scale,
o = G.sum(G.offpath(G.scale(s, lbl[0]), G.scale(s, lbl[1]), lbl[2]*s), t);
e.labelText.attr("transform", function (d) { return "translate("+o.x+","+o.y+") scale(" + s + ")"; });
return lineFunction(points);
});
});
var textToSpans =
(function(d) {
var lines = d.text.split("`");
var dy = '13';
d.textElt.text('');
for (var i = 0; i < lines.length; i++) {
d.textElt.append('tspan').text(lines[i]).attr('x', 0).attr('dy', dy);
dy = '15';
}
});
var symmetricLinks =
(function(links) {
for (var i = 0; i < links.length; i++) {
for (var j = 0; j < i; j++) {
if ( links[i].source == links[j].target
&& links[j].source == links[i].target
&& links[i].source != links[i].target
&& links[j].source != links[j].target
) {
links[i].curved = true;
links[j].curved = true;
}
}
}
});
Visualization.height =
// Public method.
(function() {
return V.dimensions.height;
});
Visualization.build =
// Public method.
(function(value) {
var raw = null, data = null;
if (V.obj instanceof jQuery) {
raw = (value != null) ? value : obj.html();
obj.html("");
if (V.dimensions.width == null || V.dimensions.height == null)
V.dimensions = {width:V.obj.width(), height:V.obj.height(), padding:10};
} else {
raw = (value != null) ? value : obj.innerHTML;
obj.innerHTML = "";
if (V.dimensions.width == null || V.dimensions.height == null)
V.dimensions = {width:V.obj.clientWidth, height:V.obj.clientHeight, padding:10};
}
if (V.dimensions.width == null || isNaN(V.dimensions.width) || V.dimensions.width == 0)
V.dimensions.width = 600;
if (V.dimensions.height == null || isNaN(V.dimensions.height) || V.dimensions.height == 0)
V.dimensions.height = 300;
if (V.notation.relation(raw)) {}
else if (V.notation.graph(raw)) {}
else if (V.notation.table(raw)) {}
else {
console.log("Representation not recognized.");
return;
}
symmetricLinks(V.data.links); // Mark symmetric pairs of links.
V.force =
d3.layout.force()
.nodes(V.data.nodes)
//.links(V.data.links) // Disabled to avoid inadvertent clustering after building.
.size([V.dimensions.width, V.dimensions.height])
.gravity(0).charge(0).linkStrength(0)
.on("tick", tick)
.start()
;
if (V.svg != null)
V.svg.remove();
V.svg =
d3.select('#' + id)
.append("svg")
.attr("width", "100%").attr("height", "100%")
.attr('viewBox', '0 0 ' + V.dimensions.width + ' ' + V.dimensions.height)
.attr('preserveAspectRatio', 'xMidYMid meet')
;
// If editing of the diagram notation is enabled.
if (V.interaction.edit) {
V.console =
d3.select('#' + id)
.append("textarea")
.attr("rows","4").attr("style", "width:"+(V.dimensions.width-6)+"px; margin:0px;")
.property("value", (raw.trim().charAt(0) == "#") ? raw.trim().substr(1) : raw.trim())
.each(function() { V.txt = this; })
;
document.getElementById(id).style.padding = '0px';
document.getElementById(id).style.height = 'auto';
}
var canvas = V.svg.append('rect').attr({'width':'100%', 'height':'100%'}).attr('fill-opacity', '0');
if (V.interaction.zoom)
canvas.call(
V.zoom
.on("zoom", function() {
var tr = d3.event.translate, sc = d3.event.scale;
V.zoompan = {translate:{x:tr[0], y:tr[1]},scale:sc};
V.vis.attr("transform", "translate(" + tr + ")" + " scale(" + sc + ")");
V.force.resume();
})
)
.on("dblclick.zoom", function() {
if (V.txt != null)
V.build(V.txt.value);
var edgeFade = 20, panZoom = 200;
V.linksEnter.each(function(e) { e.labelText.transition().duration(edgeFade).attr("opacity", 0); });
setTimeout(function() { // Wait for edges to fade out.
V.vis.transition().duration(panZoom).attr('transform', 'translate(0,0) scale(1)');
V.zoom.translate([0,0]).scale(1);
V.zoompan = {translate:{x:0, y:0},scale:1};
setTimeout(function() {V.linksEnter.each(function(e) {e.labelText.transition().duration(edgeFade).attr("opacity", 1);})}, panZoom);
}, edgeFade);
})
;
V.vis =
V.svg
.append('g')//.attr('transform', 'translate(250,250) scale(0.3)')
;
V.svg
.append('svg:defs')
.append('svg:marker')
.attr('id', 'end-arrow-' + V.divId) // Use separate namespaces for each diagram's arrow ends.
.attr('viewBox', '0 -5 10 10').attr('refX', 8)
.attr('markerWidth', 8).attr('markerHeight', 8).attr('orient', 'auto')
.append('svg:path')
.attr('d', 'M0,-5L10,0L0,5L2,0')/*.attr('stroke-width', '1px')*/.attr('fill', '#000000')
;
V.linksEnter =
V.vis.selectAll(".link")
.data(V.data.links).enter()
.append("path").attr("class", "link")
.style("stroke", "black")
.style("fill", "none")
//.style("marker-end", function(l) { return 'url(' + window.location.href + '#end-arrow-' + V.divId + ')'; })
.style("marker-end", function(l) { return 'url(#end-arrow-' + V.divId + ')'; })
.each(function(e) { // Add edge labels.
e.labelText =
V.svg
.append("text")
.text(function () { return e.label; })
.attr("text-anchor", "middle")
.attr("font-size", "12px")
.style("cursor", "all-scroll")
;
})
;
V.nodesEnter =
V.vis.selectAll(".node")
.data(V.data.nodes).enter()
.append("g")
.attr("x", function(d) { return d.cx; })
.attr("y", function(d) { return d.cy; })
.call((V.interaction.drag ? V.force.drag : function(){}))
;
V.nodesEnter.filter(function (d) {return d.shape == "rect";})
.append("rect")
.attr("class", "node_rect")
.attr("rx", function(d) { return d.rx; })
.attr("ry", function(d) { return d.ry; })
.attr("width", function(d) { return d.width; })
.attr("height", function(d) { return d.height; })
.style("fill", function(d) { return "#DADADA"; /*d.color*/; })
.style("stroke", "#4F4F4F")
.style("opacity", 0.8)
.style("cursor", "all-scroll")
;
V.nodesEnter.filter(function (d) {return d.shape == "circle";})
.append("circle")
.attr("class", "node_circle")
.attr("r", function(d) { return d.r; })
.style("stroke", "#4F4F4F")
.style("fill", function(d) { return "#DADADA"; /*d.color*/; })
.style("opacity", 0.8)
.style("cursor", "all-scroll")
;
V.nodesEnter
.append("text")
.text(function (d) { d.textElt = d3.select(this); return d.text; })
.each(textToSpans)
.attr("text-anchor", "middle")
.style("cursor", "all-scroll")
//.style("stroke", "white").style("fill", "white")
.each(function(d) {
var bbox = this.parentNode.getBBox();
d.width = Math.max(19, bbox.width);
d.height = Math.max(19, bbox.height);
})
;
V.vis.selectAll(".node_rect")
.attr("x", function(d) { return -0.5 * (d.width + V.dimensions.padding); })
.attr("y", function(d) { return -0.5 * V.dimensions.padding; })
.attr("width", function(d) { return d.width + V.dimensions.padding; })
.attr("height", function(d) { return d.height + V.dimensions.padding; })
.each(function(d) { d.offy = ((-1) * (d.height/2)); })
;
V.vis.selectAll(".node_circle")
.attr("cy", function(d) { return 0.5*this.parentNode.getBBox().height; })
.attr("r", function(d) { var bbox = this.parentNode.getBBox(); d.r = V.dimensions.padding-3+((Math.max(bbox.width, bbox.height))/2); return d.r; })
.each(function(d) { d.offy = ((-1) * (d.height/2)); })
;
V.built = true;
});
/***************************************************************************
** Initialization.
*/
Visualization.build();
return Visualization;
}); // /protoql.Visualization
})(typeof exports !== 'undefined' ? exports : (this.protoql = {}));
</script>
<style>.pql { display:inline-block; width:600px; height:400px; }</style>
</head>
<body style="padding:0px;" onload="protoql.Visualizations($('.pql'));">
<div class="pql" style="position:absolute; margin:-3px 0px 0px -8px; top:0px; bottom:10px; height:100%; width:100%;">
"""
suffix = """
</div>
</body>
</html>
"""
return prefix + raw + suffix
##eof | def html(raw):
"""
Render a stand-alone HTML page containing the supplied diagram.
"""
prefix = '\n<!DOCTYPE html>\n<html lang="en">\n <head>\n <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />\n <script src="http://d3js.org/d3.v3.min.js"></script>\n <script src="http://code.jquery.com/jquery-2.2.0.min.js"></script>\n <script>\n(function (protoql) {\n\n "use strict";\n\n /*****************************************************************************\n ** Notation library (individually instantiated by each visualization object).\n */\n\n protoql.Notation = (function(Visualization) {\n \n var V = Visualization, Notation = {};\n\n /***************************************************************************\n ** Static routines and methods.\n */\n\n Notation.decorators =\n (function(raw) {\n raw = raw.trim();\n if (raw.length > 0 && raw.charAt(0) == "!") {\n V.interaction = {\'zoom\':false, \'pan\':false, \'drag\':false, \'edit\':false};\n return raw.substr(1);\n } else if (raw.length > 0 && raw.charAt(0) == "#") {\n V.interaction = {\'zoom\':true, \'pan\':true, \'drag\':true, \'edit\':true};\n return raw.substr(1);\n } else\n return raw;\n });\n\n Notation.graph =\n (function(raw) {\n raw = Notation.decorators(raw);\n if (raw.length == 0 || raw.substr(0,6) != "graph(") return false;\n var member = (function(x,xs) { for (var i=0; i<xs.length; i++) if (xs[i]==x) return true; return false; });\n var set = (function(l) { var s = []; for (var i=0; i<l.length; i++) if (!member(l[i],s)) s.push(l[i]); return s; });\n raw = raw.trim()\n .replace(/{/g, "set<[").replace(/}/g, "]>")\n .replace(/\\(/g, "[").replace(/\\)/g, "]")\n .replace(/</g, "(").replace(/>/g, ")")\n .replace("graph[", "[");\n var args = eval(raw), nodes = null, links = null;\n if (args.length == 1) {\n links = args[0], nodes = [];\n for (var i = 0; i < links.length; i++)\n nodes = nodes.concat([links[i][0], links[i][1]]);\n nodes = set(nodes);\n } else if (args.length == 2) {\n nodes = set(args[0]), links = args[1];\n }\n var listOfListsOfNodes = [];\n var rows = Math.ceil(Math.sqrt(nodes.length)), cols = Math.ceil(Math.sqrt(nodes.length));\n var col = 0;\n for (var i = 0; i < nodes.length; i++) {\n if ((i % cols) == 0)\n listOfListsOfNodes.push([]);\n listOfListsOfNodes[listOfListsOfNodes.length-1].push(nodes[i]);\n for (var j = 0; j < links.length; j++) {\n if (links[j][0] == nodes[i]) links[j][0] = [listOfListsOfNodes.length-1, (i % cols)];\n if (links[j][1] == nodes[i]) links[j][1] = [listOfListsOfNodes.length-1, (i % cols)];\n }\n }\n return Notation.listOfListsOfNodesToData({nodes:listOfListsOfNodes, links:links, groups:[]}, false);\n });\n\n Notation.relation =\n (function(raw) {\n raw = Notation.decorators(raw);\n if (raw.length == 0 || raw.substr(0,9) != "relation(") return false;\n var member = (function(x,xs) { for (var i=0; i<xs.length; i++) if (xs[i]==x) return true; return false; });\n var set = (function(l) { var s = []; for (var i=0; i<l.length; i++) if (!member(l[i],s)) s.push(l[i]); return s; });\n raw = raw.trim()\n .replace(/{/g, "set<[").replace(/}/g, "]>")\n .replace(/\\(/g, "[").replace(/\\)/g, "]")\n .replace(/</g, "(").replace(/>/g, ")")\n .replace("relation[", "[");\n var args = eval(raw), dom = null, cod = null, links = null;\n if (args.length == 1) {\n links = args[0], dom = [];\n for (var i = 0; i < links.length; i++)\n dom = dom.concat([links[i][0], links[i][1]]);\n cod = dom = set(dom);\n } else if (args.length == 2) {\n dom = args[0], cod = args[0], links = args[1];\n } else if (args.length == 3) {\n dom = args[0], cod = args[1], links = args[2];\n }\n var listOfListsOfNodes = [];\n for (var i = 0; i < Math.max(dom.length, cod.length); i++) {\n var a = (i < dom.length) ? dom[i] : null;\n var b = (i < cod.length) ? cod[i] : null; \n listOfListsOfNodes.push([a, null, b]);\n for (var j = 0; j < links.length; j++) {\n if (a != null && links[j][0] == a) links[j][0] = [i, 0];\n if (b != null && links[j][1] == b) links[j][1] = [i, 2];\n }\n }\n return Notation.listOfListsOfNodesToData({nodes:listOfListsOfNodes, links:links, groups:[]}, false);\n });\n\n Notation.table =\n (function(raw) {\n raw = Notation.decorators(raw);\n if (raw.length == 0 || raw.substr(0,6) != "table(")\n return false;\n raw = raw.trim().replace("table(", "(");\n var listOfListsOfNodes = eval(raw);\n var check = true;\n for (var r = 0; r < listOfListsOfNodes.length; r++)\n for (var c = 0; c < listOfListsOfNodes[r].length; c++)\n check = check && (\n (listOfListsOfNodes[r][c] == null) || (typeof listOfListsOfNodes[r][c] === "string")\n || (listOfListsOfNodes[r][c].constructor === Array && listOfListsOfNodes[r][c].length == 1)\n );\n if (!check)\n return false;\n\n return Notation.listOfListsOfNodesToData({nodes:listOfListsOfNodes, links:[], groups:[]}, true);\n });\n\n Notation.listOfListsOfNodesToData =\n (function(d, deriveLinks) {\n var rows = d.nodes.length;\n var cols = 0; for (var i = 0; i < d.nodes.length; i++) cols = Math.max(cols, d.nodes[i].length);\n\n V.layout.grid.width = Math.floor(V.dimensions.width/cols);\n V.layout.grid.height = Math.floor(V.dimensions.height/rows);\n //var x = d3.scale.ordinal().domain(d3.range(cols)).rangePoints([0, V.dimensions.width], 1);\n //var y = d3.scale.ordinal().domain(d3.range(rows)).rangePoints([0, V.dimensions.height], 1);\n var c = d3.scale.category20().domain(d3.range(7));\n V.data.nodes = [];\n for (var row = 0; row < d.nodes.length; row++) {\n for (var col = 0; col < d.nodes[row].length; col++) {\n if (d.nodes[row][col] != null) {\n var t = (typeof d.nodes[row][col] === "string") ? d.nodes[row][col] : d.nodes[row][col][0];\n var es_txt = t.split("``"), t = es_txt[es_txt.length - 1], es = (es_txt.length == 2) ? es_txt[0].split("`") : [];\n var shape = (typeof d.nodes[row][col] === "string") ? "circle" : "rect";\n var node = {\n color: c(Math.floor(Math.random()*7)), shape: shape, text: t, \n rx: 5, ry: 5, offx: 0, offy: 0, x: V.layout.grid.width*col, y: V.layout.grid.height*row\n };\n d.nodes[row][col] = node;\n V.data.nodes.push(node);\n if (deriveLinks) {\n for (var i = 0; i < es.length; i++) {\n var e = es[i].split(":")[0],\n lbl = (es[i].split(":").length > 0) ? es[i].split(":")[1] : null;\n var tr = row, tc = col;\n for (var j = 0; j < e.length; j++) {\n if (e[j] == "u") tr -= 1;\n else if (e[j] == "d") tr += 1;\n else if (e[j] == "l") tc -= 1;\n else if (e[j] == "r") tc += 1;\n else if (e[j] == "s") /* Self-link; nothing. */;\n }\n d.links.push([[row,col], [tr,tc]].concat((lbl != null) ? [lbl] : []));\n }\n }\n }\n }\n }\n V.data.links = [];\n for (var i = 0; i < d.links.length; i++) {\n var s = d.links[i][0], t = d.links[i][1],\n e = {source:d.nodes[s[0]][s[1]], target:d.nodes[t[0]][t[1]], curved:false};\n if (d.links[i].length == 3)\n e.label = d.links[i][2];\n V.data.links.push(e);\n }\n\n return true;\n });\n\n /***************************************************************************\n ** Initialization.\n */\n\n return Notation;\n\n }); // /protoql.Notation\n\n /*****************************************************************************\n ** Geometry library (individually instantiated by each visualization object).\n */\n\n protoql.Geometry = (function(Visualization) {\n\n var V = Visualization, Geometry = {};\n\n /***************************************************************************\n ** Static routines for vector arithmetic and shape intersections.\n */\n\n Geometry.sum = (function(v, w) { return {x: v.x + w.x, y: v.y + w.y}; });\n Geometry.diff = (function(v, w) { return {x: v.x - w.x, y: v.y - w.y}; });\n Geometry.length = (function(v) { return Math.sqrt(Math.pow(v.x,2) + Math.pow(v.y,2)); });\n Geometry.scale = (function(s, v) { return {x: s*v.x, y: s*v.y}; });\n Geometry.middle = (function(v, w) { return Geometry.sum(v,Geometry.scale(0.5,Geometry.diff(w,v))); });\n Geometry.rotate = (function(v) { return {x:0-v.y, y:v.x}; });\n Geometry.normalize =\n (function(v) {\n var d = Math.sqrt(Math.pow(v.x,2) + Math.pow(v.y,2));\n return {x: v.x/d, y: v.y/d};\n });\n Geometry.orth =\n (function(s, t) {\n return Geometry.rotate(Geometry.normalize(Geometry.diff(t, s)));\n });\n Geometry.offpath =\n (function(s, t, a) {\n var r = Geometry.sum(Geometry.middle(s, t), Geometry.scale(a, Geometry.orth(s, t)));\n if(isNaN(r.x) || isNaN(r.y))\n return Geometry.middle(s, t);\n return r;\n });\n\n Geometry.intersects =\n (function(c, d, a, b) {\n var x1 = c.x, x2 = d.x, x3 = a.x, x4 = b.x, y1 = c.y, y2 = d.y, y3 = a.y, y4 = b.y,\n x13 = x1 - x3, x21 = x2 - x1, x43 = x4 - x3, y13 = y1 - y3, y21 = y2 - y1, y43 = y4 - y3,\n ua = (x43 * y13 - y43 * x13) / (y43 * x21 - x43 * y21);\n return {x:x1 + ua * x21, y:y1 + ua * y21};\n });\n\n Geometry.maxRadiusToOutside =\n (function(s, t) {\n var r1 = null, r2 = null;\n if (s.shape == \'rect\') r1 = Math.max(s.height, s.width)/1.7;\n else if (s.shape == "circle") r1 = s.r;\n if (t.shape == \'rect\') r2 = Math.max(t.height, t.width)/1.7;\n else if (t.shape == "circle") r2 = t.r;\n return Math.max(r1, r2);\n });\n\n Geometry.inShape =\n (function(p, s) {\n if (s.shape == \'rect\')\n return p.x > s.x - (s.width/2) && p.x < s.x +(s.width/2) && p.y > s.y - (s.height/2) && p.y < s.y + (s.height/2);\n else if (s.shape == "circle")\n return Math.sqrt(Math.pow(s.x - p.x, 2) + Math.pow(s.y - p.y, 2)) < s.r;\n });\n\n Geometry.inLine =\n (function(a,c,d) {\n return a.x >= Math.min(c.x,d.x) && a.x <= Math.max(c.x,d.x) && a.y >= Math.min(c.y,d.y) && a.y <= Math.max(c.y,d.y);\n });\n\n Geometry.onEdgeCirc =\n (function(e, which, offset) {\n offset = (offset == null) ? {x:0, y:0} : offset; // So symmetric edges intersect in different locations.\n var c = e[which];\n var dx = (which == "source" ? -1 : 1)*(e.source.x - e.target.x), \n dy = (which == "source" ? -1 : 1)*(e.target.y - e.source.y);\n var d = Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2));\n var x = c.x + ((c.r*dx)/d), y = c.y - ((c.r*dy)/d);\n return {x:isNaN(x) ? c.x : x, y:isNaN(y) ? c.y : y};\n });\n\n Geometry.onEdgeRect =\n (function(e, which, offset) {\n offset = (offset == null) ? {x:0, y:0} : offset; // So symmetric edges intersect in different locations.\n var r = Geometry.centeredPaddedRect(e[which]);\n var a = Geometry.sum(e.source, offset), b = Geometry.sum(e.target, offset);\n var lines = [\n [r, {x:r.x+r.width,y:r.y}], [{x:r.x,y:r.y+r.height}, {x:r.x+r.width,y:r.y+r.height}],\n [r, {x:r.x,y:r.y+r.height}], [{x:r.x+r.width,y:r.y}, {x:r.x+r.width,y:r.y+r.height}]\n ];\n var inters = lines.map(function(x) { return Geometry.intersects(x[0],x[1],a,b); });\n if (Geometry.inLine(inters[0],a,b) && inters[0].x >= r.x && inters[0].x <= r.x + r.width)\n return inters[0];\n else if (Geometry.inLine(inters[1],a,b) && inters[1].x >= r.x && inters[1].x <= r.x + r.width)\n return inters[1];\n else if (Geometry.inLine(inters[2],a,b) && inters[2].y >= r.y && inters[2].y <= r.y + r.height)\n return inters[2];\n else if (Geometry.inLine(inters[3],a,b) && inters[3].y >= r.y && inters[3].y <= r.y + r.height)\n return inters[3];\n else\n return e[which];\n });\n\n Geometry.onEdge =\n (function(e, which, offset) {\n if (e[which].shape == "rect")\n return Geometry.onEdgeRect(e, which, offset);\n if (e[which].shape == "circle")\n return Geometry.onEdgeCirc(e, which, offset);\n });\n\n Geometry.centeredPaddedRect =\n (function(node) {\n var rect = {};\n rect.x = node.x - (node.width + V.dimensions.padding) / 2;\n rect.y = node.y - (node.height + V.dimensions.padding) / 2;\n rect.width = node.width + V.dimensions.padding;\n rect.height = node.height + V.dimensions.padding;\n return rect;\n });\n\n /***************************************************************************\n ** Initialization.\n */\n\n return Geometry;\n\n }); // /protoql.Geometry\n\n /*****************************************************************************\n ** Interactive visualization objects.\n */\n\n protoql.Visualizations = (function(arg) {\n var vs = []; \n if (arg.constructor === Array)\n for (var i = 0; i < arg.length; i++)\n vs.push(protoql.Visualization(arg[i]));\n else if (arg instanceof jQuery && typeof arg.each === "function")\n arg.each(function(index) {\n vs.push(protoql.Visualization($(this)));\n });\n return vs;\n });\n\n protoql.Visualization = (function(arg) {\n\n // Process constructor argument. \n var id = null, obj = null, val = null;\n if (typeof arg === "string") {\n id = arg;\n obj = document.getElementById(id);\n val = (obj != null) ? obj.innerHTML : null;\n } else if (arg instanceof jQuery) {\n obj = arg;\n if (typeof obj.attr(\'id\') !== "string") // Generate random identifier.\n obj.attr(\'id\', "id"+Date.now()+""+Math.floor(Math.random()*10000));\n id = obj.attr(\'id\');\n val = obj.html();\n }\n\n var Visualization = {}, V = Visualization;\n\n /***************************************************************************\n ** Data fields and properties.\n */\n\n Visualization.divId = id;\n Visualization.obj = obj;\n Visualization.val = val;\n Visualization.svg = null;\n Visualization.vis = null;\n Visualization.zoom = d3.behavior.zoom();\n Visualization.zoompan = {translate:{x:0, y:0}, scale:1};\n Visualization.built = false;\n Visualization.force = null;\n Visualization.data = {nodes: null, links: null, groups: null};\n Visualization.nodesEnter = null;\n Visualization.linksEnter = null;\n Visualization.dimensions = {width: null, height: null, padding: null};\n Visualization.layout = {grid: {width: null, height: null}};\n Visualization.interaction = {zoom:true, pan:true, drag:true, edit:false};\n var G = Visualization.geometry = protoql.Geometry(Visualization);\n var N = Visualization.notation = protoql.Notation(Visualization);\n\n /***************************************************************************\n ** Routines and methods.\n */\n \n var lineFunction = \n d3.svg\n .line()\n .x(function (d) { return d.x; })\n .y(function (d) { return d.y; })\n .interpolate("basis");\n\n // Resolve collisions between nodes.\n var collision =\n (function(alpha) {\n var padding = 6;\n var maxRadius = 7;\n var quadtree = d3.geom.quadtree(nodes);\n return function(d) {\n var r = d.r + maxRadius + padding,\n nx1 = d.x - r, nx2 = d.x + r,\n ny1 = d.y - r, ny2 = d.y + r;\n quadtree.visit(function(quad, x1, y1, x2, y2) {\n if (quad.point && (quad.point !== d)) {\n var x = d.x - quad.point.x, y = d.y - quad.point.y,\n l = Math.sqrt(x * x + y * y),\n r = d.r + quad.point.r + (d.color !== quad.point.color) * padding;\n if (l < r) {\n l = (l - r) / l * alpha;\n d.x -= x *= l;\n d.y -= y *= l;\n quad.point.x += x;\n quad.point.y += y;\n }\n }\n return x1 > nx2 || x2 < nx1 || y1 > ny2 || y2 < ny1;\n });\n };\n });\n\n var alignment =\n (function(alpha) {\n return function(d) {\n d.cx = Math.floor(d.x - (d.x % V.layout.grid.width)+(V.layout.grid.width*0.5));\n d.x += (d.cx - d.x) * alpha;\n d.cy = Math.floor(d.y - (d.y % V.layout.grid.height)+(V.layout.grid.height*0.5));\n d.y += (d.cy - d.y) * alpha;\n };\n });\n\n var tick =\n (function(e) {\n V.nodesEnter\n .each(alignment(0.8 * e.alpha))\n //.each(collision(.5))\n .attr("transform", function (d) { return "translate("+(d.x + d.offx)+","+(d.y + d.offy)+")"; });\n V.linksEnter\n .attr("d", function (e) {\n var s = G.onEdge(e, \'source\'), t = G.onEdge(e, \'target\'), \n points = null, lbl = [e.source, e.target, 15];\n if (G.inShape(t, e.source) || G.inShape(s, e.target)) {\n var orient = (e.source == e.target) ? -1 : 1,\n es = e.source, et = e.target, \n d = G.diff(e.source, e.target),\n l = G.length(d),\n m = Math.abs(G.maxRadiusToOutside(e.source, e.target)),\n kx = (l < 2) ? m + 9 : d.x * Math.min(1.3*m, 1.5*(m/(l+1))), ky = (l < 2) ? m + 9 : d.y * Math.min(1.3*m, 1.5*(m/(l+1))),\n p = {x:es.x + 1.3*ky, y:es.y - kx}, q = {x:et.x + (orient*(0.9)*ky), y:et.y - kx},\n s = G.onEdge({source:es, target:p}, \'source\'), t = G.onEdge({source:q, target:et}, \'target\');\n points = [s, p, q, t];\n lbl = [p,q,10];\n } else if (e.curved == true) {\n var off = G.scale(5, G.orth(s, t)), s = G.onEdge(e, \'source\', off), t = G.onEdge(e, \'target\', off);\n points = [s, G.offpath(s, t, 5), t];\n } else {\n points = [s, t];\n }\n\n // Position the edge label.\n var t = V.zoompan.translate, s = V.zoompan.scale,\n o = G.sum(G.offpath(G.scale(s, lbl[0]), G.scale(s, lbl[1]), lbl[2]*s), t);\n e.labelText.attr("transform", function (d) { return "translate("+o.x+","+o.y+") scale(" + s + ")"; });\n\n return lineFunction(points);\n });\n });\n\n var textToSpans =\n (function(d) {\n var lines = d.text.split("`");\n var dy = \'13\';\n d.textElt.text(\'\');\n for (var i = 0; i < lines.length; i++) {\n d.textElt.append(\'tspan\').text(lines[i]).attr(\'x\', 0).attr(\'dy\', dy);\n dy = \'15\';\n }\n });\n\n var symmetricLinks =\n (function(links) {\n for (var i = 0; i < links.length; i++) {\n for (var j = 0; j < i; j++) {\n if ( links[i].source == links[j].target\n && links[j].source == links[i].target\n && links[i].source != links[i].target\n && links[j].source != links[j].target\n ) {\n links[i].curved = true;\n links[j].curved = true;\n }\n }\n }\n });\n\n Visualization.height =\n // Public method.\n (function() {\n return V.dimensions.height;\n });\n\n Visualization.build =\n // Public method.\n (function(value) {\n var raw = null, data = null;\n if (V.obj instanceof jQuery) {\n raw = (value != null) ? value : obj.html();\n obj.html("");\n if (V.dimensions.width == null || V.dimensions.height == null)\n V.dimensions = {width:V.obj.width(), height:V.obj.height(), padding:10};\n } else {\n raw = (value != null) ? value : obj.innerHTML;\n obj.innerHTML = "";\n if (V.dimensions.width == null || V.dimensions.height == null)\n V.dimensions = {width:V.obj.clientWidth, height:V.obj.clientHeight, padding:10};\n }\n\n if (V.dimensions.width == null || isNaN(V.dimensions.width) || V.dimensions.width == 0)\n V.dimensions.width = 600;\n if (V.dimensions.height == null || isNaN(V.dimensions.height) || V.dimensions.height == 0)\n V.dimensions.height = 300;\n\n if (V.notation.relation(raw)) {}\n else if (V.notation.graph(raw)) {}\n else if (V.notation.table(raw)) {}\n else {\n console.log("Representation not recognized.");\n return;\n }\n\n symmetricLinks(V.data.links); // Mark symmetric pairs of links.\n V.force = \n d3.layout.force()\n .nodes(V.data.nodes)\n //.links(V.data.links) // Disabled to avoid inadvertent clustering after building.\n .size([V.dimensions.width, V.dimensions.height])\n .gravity(0).charge(0).linkStrength(0)\n .on("tick", tick)\n .start()\n ;\n if (V.svg != null)\n V.svg.remove();\n V.svg = \n d3.select(\'#\' + id)\n .append("svg")\n .attr("width", "100%").attr("height", "100%")\n .attr(\'viewBox\', \'0 0 \' + V.dimensions.width + \' \' + V.dimensions.height)\n .attr(\'preserveAspectRatio\', \'xMidYMid meet\')\n ;\n\n // If editing of the diagram notation is enabled.\n if (V.interaction.edit) {\n V.console =\n d3.select(\'#\' + id)\n .append("textarea")\n .attr("rows","4").attr("style", "width:"+(V.dimensions.width-6)+"px; margin:0px;")\n .property("value", (raw.trim().charAt(0) == "#") ? raw.trim().substr(1) : raw.trim())\n .each(function() { V.txt = this; })\n ;\n document.getElementById(id).style.padding = \'0px\';\n document.getElementById(id).style.height = \'auto\';\n }\n\n var canvas = V.svg.append(\'rect\').attr({\'width\':\'100%\', \'height\':\'100%\'}).attr(\'fill-opacity\', \'0\');\n if (V.interaction.zoom)\n canvas.call(\n V.zoom\n .on("zoom", function() {\n var tr = d3.event.translate, sc = d3.event.scale;\n V.zoompan = {translate:{x:tr[0], y:tr[1]},scale:sc};\n V.vis.attr("transform", "translate(" + tr + ")" + " scale(" + sc + ")");\n V.force.resume();\n })\n )\n .on("dblclick.zoom", function() {\n if (V.txt != null)\n V.build(V.txt.value);\n var edgeFade = 20, panZoom = 200;\n V.linksEnter.each(function(e) { e.labelText.transition().duration(edgeFade).attr("opacity", 0); });\n setTimeout(function() { // Wait for edges to fade out.\n V.vis.transition().duration(panZoom).attr(\'transform\', \'translate(0,0) scale(1)\');\n V.zoom.translate([0,0]).scale(1);\n V.zoompan = {translate:{x:0, y:0},scale:1};\n setTimeout(function() {V.linksEnter.each(function(e) {e.labelText.transition().duration(edgeFade).attr("opacity", 1);})}, panZoom);\n }, edgeFade);\n })\n ;\n V.vis =\n V.svg\n .append(\'g\')//.attr(\'transform\', \'translate(250,250) scale(0.3)\')\n ;\n V.svg\n .append(\'svg:defs\')\n .append(\'svg:marker\')\n .attr(\'id\', \'end-arrow-\' + V.divId) // Use separate namespaces for each diagram\'s arrow ends.\n .attr(\'viewBox\', \'0 -5 10 10\').attr(\'refX\', 8)\n .attr(\'markerWidth\', 8).attr(\'markerHeight\', 8).attr(\'orient\', \'auto\')\n .append(\'svg:path\')\n .attr(\'d\', \'M0,-5L10,0L0,5L2,0\')/*.attr(\'stroke-width\', \'1px\')*/.attr(\'fill\', \'#000000\')\n ;\n V.linksEnter = \n V.vis.selectAll(".link")\n .data(V.data.links).enter()\n .append("path").attr("class", "link")\n .style("stroke", "black")\n .style("fill", "none")\n //.style("marker-end", function(l) { return \'url(\' + window.location.href + \'#end-arrow-\' + V.divId + \')\'; })\n .style("marker-end", function(l) { return \'url(#end-arrow-\' + V.divId + \')\'; })\n .each(function(e) { // Add edge labels.\n e.labelText = \n V.svg\n .append("text")\n .text(function () { return e.label; })\n .attr("text-anchor", "middle")\n .attr("font-size", "12px")\n .style("cursor", "all-scroll")\n ;\n })\n ;\n V.nodesEnter = \n V.vis.selectAll(".node")\n .data(V.data.nodes).enter()\n .append("g")\n .attr("x", function(d) { return d.cx; })\n .attr("y", function(d) { return d.cy; })\n .call((V.interaction.drag ? V.force.drag : function(){}))\n ;\n V.nodesEnter.filter(function (d) {return d.shape == "rect";})\n .append("rect")\n .attr("class", "node_rect")\n .attr("rx", function(d) { return d.rx; })\n .attr("ry", function(d) { return d.ry; })\n .attr("width", function(d) { return d.width; })\n .attr("height", function(d) { return d.height; })\n .style("fill", function(d) { return "#DADADA"; /*d.color*/; })\n .style("stroke", "#4F4F4F")\n .style("opacity", 0.8)\n .style("cursor", "all-scroll")\n ;\n V.nodesEnter.filter(function (d) {return d.shape == "circle";})\n .append("circle")\n .attr("class", "node_circle")\n .attr("r", function(d) { return d.r; })\n .style("stroke", "#4F4F4F")\n .style("fill", function(d) { return "#DADADA"; /*d.color*/; })\n .style("opacity", 0.8)\n .style("cursor", "all-scroll")\n ;\n V.nodesEnter\n .append("text")\n .text(function (d) { d.textElt = d3.select(this); return d.text; })\n .each(textToSpans)\n .attr("text-anchor", "middle")\n .style("cursor", "all-scroll")\n //.style("stroke", "white").style("fill", "white")\n .each(function(d) {\n var bbox = this.parentNode.getBBox();\n d.width = Math.max(19, bbox.width);\n d.height = Math.max(19, bbox.height);\n })\n ;\n V.vis.selectAll(".node_rect")\n .attr("x", function(d) { return -0.5 * (d.width + V.dimensions.padding); })\n .attr("y", function(d) { return -0.5 * V.dimensions.padding; })\n .attr("width", function(d) { return d.width + V.dimensions.padding; })\n .attr("height", function(d) { return d.height + V.dimensions.padding; })\n .each(function(d) { d.offy = ((-1) * (d.height/2)); })\n ;\n V.vis.selectAll(".node_circle")\n .attr("cy", function(d) { return 0.5*this.parentNode.getBBox().height; })\n .attr("r", function(d) { var bbox = this.parentNode.getBBox(); d.r = V.dimensions.padding-3+((Math.max(bbox.width, bbox.height))/2); return d.r; })\n .each(function(d) { d.offy = ((-1) * (d.height/2)); })\n ;\n V.built = true;\n });\n\n /***************************************************************************\n ** Initialization.\n */\n\n Visualization.build();\n\n return Visualization;\n\n }); // /protoql.Visualization\n\n})(typeof exports !== \'undefined\' ? exports : (this.protoql = {}));\n </script>\n <style>.pql { display:inline-block; width:600px; height:400px; }</style>\n </head>\n <body style="padding:0px;" onload="protoql.Visualizations($(\'.pql\'));">\n <div class="pql" style="position:absolute; margin:-3px 0px 0px -8px; top:0px; bottom:10px; height:100%; width:100%;">\n'
suffix = '\n </div>\n </body>\n</html>\n'
return prefix + raw + suffix |
class DataDictException(Exception):
def __init__(self, message, data_dict=None, exc=None):
self._message = message
if data_dict is None:
data_dict = {}
formatted_data_dict = {}
for key, value in data_dict.items():
formatted_data_dict[str(key)] = str(value)
if exc is not None:
formatted_data_dict['exc'] = str(exc)
self._formatted_data_dict = formatted_data_dict
formatted_message = '{0}: {1}'.format(self._message,
str(formatted_data_dict).replace(': ', '=').replace('\'', '')[1:-1])
super().__init__(formatted_message)
| class Datadictexception(Exception):
def __init__(self, message, data_dict=None, exc=None):
self._message = message
if data_dict is None:
data_dict = {}
formatted_data_dict = {}
for (key, value) in data_dict.items():
formatted_data_dict[str(key)] = str(value)
if exc is not None:
formatted_data_dict['exc'] = str(exc)
self._formatted_data_dict = formatted_data_dict
formatted_message = '{0}: {1}'.format(self._message, str(formatted_data_dict).replace(': ', '=').replace("'", '')[1:-1])
super().__init__(formatted_message) |
def hello_request(data):
data['type'] = 'hello_request'
return data
def hello_response(data):
data['type'] = 'hello_reply'
return data
def goodbye(data):
data['type'] = 'goodbye'
return data
def ok():
return {'type': 'ok'}
def shout(data):
data['type'] = 'shout'
return data
def proto_welcome():
return {'type': 'welcome'}
def proto_page(uri, pubkey, guid, text, signature, nickname, PGPPubKey, email,
bitmessage, arbiter, notary, arbiter_description, sin):
data = {
'type': 'page',
'uri': uri,
'pubkey': pubkey,
'senderGUID': guid,
'text': text,
'nickname': nickname,
'PGPPubKey': PGPPubKey,
'email': email,
'bitmessage': bitmessage,
'arbiter': arbiter,
'notary': notary,
'arbiter_description': arbiter_description,
'sin': sin
}
return data
def query_page(guid):
data = {'type': 'query_page', 'findGUID': guid}
return data
def order(id, buyer, seller, state, text, escrows=None, tx=None):
if not escrows:
escrows = []
data = {
'type': 'order',
'order_id': id,
'buyer': buyer.encode('hex'),
'seller': seller.encode('hex'),
'escrows': escrows
}
# this is who signs
# this is who the review is about
# the signature
# the signature
if data.get('tex'):
data['tx'] = tx.encode('hex')
# some text
data['text'] = text
# some text
data['address'] = ''
data['state'] = state
# new -> accepted/rejected -> payed -> sent -> received
return data
def proto_listing(productTitle, productDescription, productPrice,
productQuantity, market_id, productShippingPrice,
productImageName, productImageData):
data = {
'productTitle': productTitle,
'productDescription': productDescription,
'productPrice': productPrice,
'productQuantity': productQuantity,
'market_id': market_id,
'productShippingPrice': productShippingPrice,
'productImageName': productImageName,
'productImageData': productImageData
}
return data
def proto_store(key, value, originalPublisherID, age):
data = {
'type': 'store',
'key': key,
'value': value,
'originalPublisherID': originalPublisherID,
'age': age
}
return data
def negotiate_pubkey(nickname, ident_pubkey):
data = {
'type': 'negotiate_pubkey',
'nickname': nickname,
'ident_pubkey': ident_pubkey.encode("hex")
}
return data
def proto_response_pubkey(nickname, pubkey, signature):
data = {
'type': "proto_response_pubkey",
'nickname': nickname,
'pubkey': pubkey.encode("hex"),
'signature': signature.encode("hex")
}
return data
| def hello_request(data):
data['type'] = 'hello_request'
return data
def hello_response(data):
data['type'] = 'hello_reply'
return data
def goodbye(data):
data['type'] = 'goodbye'
return data
def ok():
return {'type': 'ok'}
def shout(data):
data['type'] = 'shout'
return data
def proto_welcome():
return {'type': 'welcome'}
def proto_page(uri, pubkey, guid, text, signature, nickname, PGPPubKey, email, bitmessage, arbiter, notary, arbiter_description, sin):
data = {'type': 'page', 'uri': uri, 'pubkey': pubkey, 'senderGUID': guid, 'text': text, 'nickname': nickname, 'PGPPubKey': PGPPubKey, 'email': email, 'bitmessage': bitmessage, 'arbiter': arbiter, 'notary': notary, 'arbiter_description': arbiter_description, 'sin': sin}
return data
def query_page(guid):
data = {'type': 'query_page', 'findGUID': guid}
return data
def order(id, buyer, seller, state, text, escrows=None, tx=None):
if not escrows:
escrows = []
data = {'type': 'order', 'order_id': id, 'buyer': buyer.encode('hex'), 'seller': seller.encode('hex'), 'escrows': escrows}
if data.get('tex'):
data['tx'] = tx.encode('hex')
data['text'] = text
data['address'] = ''
data['state'] = state
return data
def proto_listing(productTitle, productDescription, productPrice, productQuantity, market_id, productShippingPrice, productImageName, productImageData):
data = {'productTitle': productTitle, 'productDescription': productDescription, 'productPrice': productPrice, 'productQuantity': productQuantity, 'market_id': market_id, 'productShippingPrice': productShippingPrice, 'productImageName': productImageName, 'productImageData': productImageData}
return data
def proto_store(key, value, originalPublisherID, age):
data = {'type': 'store', 'key': key, 'value': value, 'originalPublisherID': originalPublisherID, 'age': age}
return data
def negotiate_pubkey(nickname, ident_pubkey):
data = {'type': 'negotiate_pubkey', 'nickname': nickname, 'ident_pubkey': ident_pubkey.encode('hex')}
return data
def proto_response_pubkey(nickname, pubkey, signature):
data = {'type': 'proto_response_pubkey', 'nickname': nickname, 'pubkey': pubkey.encode('hex'), 'signature': signature.encode('hex')}
return data |
# The new config inherits a base config to highlight the necessary modification
_base_ = '../cascade_rcnn/cascade_mask_rcnn_x101_32x4d_fpn_mstrain_3x_coco.py'
# We also need to change the num_classes in head to match the dataset's annotation
model = dict(
roi_head=dict(
bbox_head=[
dict(type='Shared2FCBBoxHead', num_classes=1),
dict(type='Shared2FCBBoxHead', num_classes=1),
dict(type='Shared2FCBBoxHead', num_classes=1)
],
mask_head=dict(num_classes=1)
)
)
# Modify dataset related settings
dataset_type = 'CocoDataset'
classes = ('nucleus',)
runner = dict(type='EpochBasedRunner', max_epochs=200)
test_pipeline = [
dict(type='LoadImageFromFile'),
dict(
type='MultiScaleFlipAug',
img_scale=(1333, 800),
flip=False,
transforms=[
dict(type='Resize', keep_ratio=True),
dict(type='RandomFlip'),
dict(
type='Normalize',
mean=[123.675, 116.28, 103.53],
std=[58.395, 57.12, 57.375],
to_rgb=True),
dict(type='Pad', size_divisor=32),
dict(type='DefaultFormatBundle'),
dict(type='Collect', keys=['img']),
])
]
train_pipeline = [
dict(type='LoadImageFromFile'),
dict(
type='LoadAnnotations',
with_bbox=True,
with_mask=True,
poly2mask=False),
dict(type='Resize', img_scale=(1333, 800), keep_ratio=True),
dict(type='RandomFlip', flip_ratio=0.5),
dict(
type='Normalize',
mean=[123.675, 116.28, 103.53],
std=[58.395, 57.12, 57.375],
to_rgb=True),
dict(type='Pad', size_divisor=32),
dict(type='DefaultFormatBundle'),
dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels', 'gt_masks'])
]
data = dict(
samples_per_gpu=1,
workers_per_gpu=1,
train=dict(
type='RepeatDataset',
times=3,
dataset=dict(
type='CocoDataset',
ann_file='/work/zchin31415/nucleus_data/annotations/instance_all_train.json',
img_prefix='/work/zchin31415/nucleus_data/all_train',
# classes=('tennis', )
pipeline=train_pipeline
),
classes=classes,
ann_file='/work/zchin31415/nucleus_data/annotations/instance_all_train.json',
img_prefix='/work/zchin31415/nucleus_data/all_train'),
val=dict(
type=dataset_type,
ann_file='/work/zchin31415/nucleus_data/annotations/instance_all_train.json',
img_prefix='/work/zchin31415/nucleus_data/all_train',
classes=classes),
test=dict(
type=dataset_type,
ann_file='/work/zchin31415/nucleus_data/annotations/instance_test.json',
img_prefix='/work/zchin31415/nucleus_data/test',
pipeline=test_pipeline,
classes=classes)
)
load_from = '/home/zchin31415/mmdet-nucleus-instance-segmentation/mmdetection/checkpoints/cascade_mask_rcnn_x101_32x4d_fpn_mstrain_3x_coco_20210706_225234-40773067.pth'
| _base_ = '../cascade_rcnn/cascade_mask_rcnn_x101_32x4d_fpn_mstrain_3x_coco.py'
model = dict(roi_head=dict(bbox_head=[dict(type='Shared2FCBBoxHead', num_classes=1), dict(type='Shared2FCBBoxHead', num_classes=1), dict(type='Shared2FCBBoxHead', num_classes=1)], mask_head=dict(num_classes=1)))
dataset_type = 'CocoDataset'
classes = ('nucleus',)
runner = dict(type='EpochBasedRunner', max_epochs=200)
test_pipeline = [dict(type='LoadImageFromFile'), dict(type='MultiScaleFlipAug', img_scale=(1333, 800), flip=False, transforms=[dict(type='Resize', keep_ratio=True), dict(type='RandomFlip'), dict(type='Normalize', mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True), dict(type='Pad', size_divisor=32), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img'])])]
train_pipeline = [dict(type='LoadImageFromFile'), dict(type='LoadAnnotations', with_bbox=True, with_mask=True, poly2mask=False), dict(type='Resize', img_scale=(1333, 800), keep_ratio=True), dict(type='RandomFlip', flip_ratio=0.5), dict(type='Normalize', mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True), dict(type='Pad', size_divisor=32), dict(type='DefaultFormatBundle'), dict(type='Collect', keys=['img', 'gt_bboxes', 'gt_labels', 'gt_masks'])]
data = dict(samples_per_gpu=1, workers_per_gpu=1, train=dict(type='RepeatDataset', times=3, dataset=dict(type='CocoDataset', ann_file='/work/zchin31415/nucleus_data/annotations/instance_all_train.json', img_prefix='/work/zchin31415/nucleus_data/all_train', pipeline=train_pipeline), classes=classes, ann_file='/work/zchin31415/nucleus_data/annotations/instance_all_train.json', img_prefix='/work/zchin31415/nucleus_data/all_train'), val=dict(type=dataset_type, ann_file='/work/zchin31415/nucleus_data/annotations/instance_all_train.json', img_prefix='/work/zchin31415/nucleus_data/all_train', classes=classes), test=dict(type=dataset_type, ann_file='/work/zchin31415/nucleus_data/annotations/instance_test.json', img_prefix='/work/zchin31415/nucleus_data/test', pipeline=test_pipeline, classes=classes))
load_from = '/home/zchin31415/mmdet-nucleus-instance-segmentation/mmdetection/checkpoints/cascade_mask_rcnn_x101_32x4d_fpn_mstrain_3x_coco_20210706_225234-40773067.pth' |
class Solution:
def maxCoins(self, piles: List[int]) -> int:
piles=sorted(piles)
n=len(piles)
answer=0
for i in range(int(n/3),n, 2):
answer+=piles[i]
return answer
| class Solution:
def max_coins(self, piles: List[int]) -> int:
piles = sorted(piles)
n = len(piles)
answer = 0
for i in range(int(n / 3), n, 2):
answer += piles[i]
return answer |
m: int; n: int; i: int; j: int
m = int(input("Qual a quantidade de linhas da matriz? "))
n = int(input("Qual a quantidade de colunas da matriz? "))
mat: [[int]] = [[0 for x in range(n)] for x in range(m)]
for i in range(0, m):
for j in range(0, n):
mat[i][j] = int(input(f"Elemento [{i},{j}]: "))
print("VALORES NEGATIVOS:")
for i in range(0, m):
for j in range(0, n):
if mat[i][j] < 0:
print(mat[i][j])
| m: int
n: int
i: int
j: int
m = int(input('Qual a quantidade de linhas da matriz? '))
n = int(input('Qual a quantidade de colunas da matriz? '))
mat: [[int]] = [[0 for x in range(n)] for x in range(m)]
for i in range(0, m):
for j in range(0, n):
mat[i][j] = int(input(f'Elemento [{i},{j}]: '))
print('VALORES NEGATIVOS:')
for i in range(0, m):
for j in range(0, n):
if mat[i][j] < 0:
print(mat[i][j]) |
#MenuTitle: Change LayerColor to Purple
# -*- coding: utf-8 -*-
font = Glyphs.font
selectedLayers = font.selectedLayers
for thisLayer in selectedLayers:
thisGlyph = thisLayer.parent
thisGlyph.layers[font.selectedFontMaster.id].color = 8
| font = Glyphs.font
selected_layers = font.selectedLayers
for this_layer in selectedLayers:
this_glyph = thisLayer.parent
thisGlyph.layers[font.selectedFontMaster.id].color = 8 |
# Line SPW setup for 17B-162 w/ rest frequencies
# SPW $: [Name, Restfreq, Num chans, Chans for uvcontsub]
# Notes for uvcontsub channels:
# - Avoid first and last 5% of channels in a SPW
# - Avoid -80 to -280 km/s for M33
# - Avoid -30 to 30 km/s for MW
# Channel offset b/w cubes made with test_line_imaging.py (excludes edge
# channels) and the full SPW (since we split from the full SPW):
# Halp - 7 channels
# OH - 13 channels
# HI - 205 channels
linespw_dict = {0: ["HI", "1.420405752GHz", 4096, "1240~1560;2820~3410"],
1: ["H166alp", "1.42473GHz", 128, "32~47;107~114"],
2: ["H164alp", "1.47734GHz", 128, "32~47;107~114"],
3: ["OH1612", "1.612231GHz", 256, "53~88;223~240"],
4: ["H158alp", "1.65154GHz", 128, "32~47;107~114"],
5: ["OH1665", "1.6654018GHz", 256, "53~88;223~240"],
6: ["OH1667", "1.667359GHz", 256, "53~88;223~240"],
7: ["OH1720", "1.72053GHz", 256, "53~88;223~240"],
8: ["H153alp", "1.81825GHz", 128, "32~47;107~114"],
9: ["H152alp", "1.85425GHz", 128, "32~47;107~114"]}
| linespw_dict = {0: ['HI', '1.420405752GHz', 4096, '1240~1560;2820~3410'], 1: ['H166alp', '1.42473GHz', 128, '32~47;107~114'], 2: ['H164alp', '1.47734GHz', 128, '32~47;107~114'], 3: ['OH1612', '1.612231GHz', 256, '53~88;223~240'], 4: ['H158alp', '1.65154GHz', 128, '32~47;107~114'], 5: ['OH1665', '1.6654018GHz', 256, '53~88;223~240'], 6: ['OH1667', '1.667359GHz', 256, '53~88;223~240'], 7: ['OH1720', '1.72053GHz', 256, '53~88;223~240'], 8: ['H153alp', '1.81825GHz', 128, '32~47;107~114'], 9: ['H152alp', '1.85425GHz', 128, '32~47;107~114']} |
'''
Input
An integer t, 1<=t<=100, denoting the number of testcases, followed by t lines, each containing a single integer n, 1<=n<=100.
Output
For each integer n given at input, display a line with the value of n!
Example
Sample input:
4
1
2
5
3
Sample output:
1
2
120
6
'''
t=int(input())
for i in range(t):
n=int(input())
ans=1
while n>1:
ans*=n
n-=1
print(ans) | """
Input
An integer t, 1<=t<=100, denoting the number of testcases, followed by t lines, each containing a single integer n, 1<=n<=100.
Output
For each integer n given at input, display a line with the value of n!
Example
Sample input:
4
1
2
5
3
Sample output:
1
2
120
6
"""
t = int(input())
for i in range(t):
n = int(input())
ans = 1
while n > 1:
ans *= n
n -= 1
print(ans) |
VERSION = "0.1a"
class Port(object):
def __init__(self):
raise NotImplementedError("Abstract Class!")
def __init__(self, portType):
self.portType = portType
return
def isType(self, _type):
if _type == self.portType:
return True
return False
class Component(object):
def __init__(self):
raise NotImplementedError("Abstract Class!")
def setServices(self, services):
"""
input: services object.
output: void
"""
raise NotImplementedError("Abstract Class!")
class ComponentRelease(object):
def __init__(self):
raise NotImplementedError("Abstract Class!")
def releaseServices(self, services):
"""
input: services object.
output: void
"""
raise NotImplementedError("Abstract Class!")
class ComponentID(object):
def __init__(self):
raise NotImplementedError("Abstract Class!")
def getInstanceName(self):
"""
input: none
output: a string identifier for the component (uuid?).
throws CCAException.
"""
raise NotImplementedError("Abstract Class!")
def getSerialization(self):
"""
input: none
output: a serialization of the object sufficient for saving the component's state to disk and restart at a different time.
throws CCAException.
"""
raise NotImplementedError("Abstract Class!")
class Services(object):
def __init__(self):
raise NotImplementedError("Abstract Class!")
def getComponentID(self):
"""
input: none
output: a ComponentID object
"""
raise NotImplementedError("Abstract Class!")
def createTypeMap(self):
"""
input: none
output: a TypeMap object
throws CCAException
"""
raise NotImplementedError("Abstract Class!")
def registerUsesPort(self, portName, type, properties):
"""
input: string portName, string type, and TypeMap properties
output: void
throws CCAException
"""
raise NotImplementedError("Abstract Class!")
def unregisterUsesPort(self, portName):
"""
input: string portName
output: void
throws CCAException
"""
raise NotImplementedError("Abstract Class!")
def addProvidesPort(self, inPort, portName, type, properties):
"""
input: Port inPort, string portName, string type, and TypeMap properties
output: void
throws CCAException
"""
raise NotImplementedError("Abstract Class!")
def removeProvidesPort(self, portName):
"""
input: string portName
output: void
throws CCAException
"""
raise NotImplementedError("Abstract Class!")
def getPortProperties(self, portName):
"""
input: string portName
output: a TypeMap object
"""
raise NotImplementedError("Abstract Class!")
def getPort(self, portName):
"""
input: string portName
output: a Port object
throws CCAException
"""
raise NotImplementedError("Abstract Class!")
def getPortNonblocking(self, portName):
"""
input: string portName
output: a Port object
throws CCAException
"""
raise NotImplementedError("Abstract Class!")
def releasePort(self, portName):
"""
input: string portName
output: void
throws CCAException
"""
raise NotImplementedError("Abstract Class!")
def registerForRelease(self, callback):
"""
input: a gov.cca.ComponentRelease object callback
output: void
"""
raise NotImplementedError("Abstract Class!")
class AbstractFramework(object):
def __init__(self):
raise NotImplementedError("Abstract Class!")
def createTypeMap(self):
"""
input: none
output: a TypeMap object
throws CCAException
"""
raise NotImplementedError("Abstract Class!")
def createEmptyFramework(self):
"""
input: none
output: a AbstractFramework object
throws CCAException
"""
raise NotImplementedError("Abstract Class!")
def getServices(self, selfInstanceName, selfClassName, selfProperties):
"""
input: a string selfInstanceName, string selfClassName, TypeMap selfProperties
output: a Services object
throws CCAException
"""
raise NotImplementedError("Abstract Class!")
def releaseServices(self, services):
"""
input: a Services object
output: a AbstractFramework object
throws CCAException
"""
raise NotImplementedError("Abstract Class!")
def shutdownFramework(self):
"""
input: none
output: void
throws CCAException
"""
raise NotImplementedError("Abstract Class!")
class ComponentClassDescription(object):
def __init__(self):
raise NotImplementedError("Abstract Class!")
def getComponentClassName(self):
"""
input: none
output: a string
throws CCAException
"""
raise NotImplementedError("Abstract Class!")
class ConnectionID(object):
def __init__(self):
raise NotImplementedError("Abstract Class!")
def getProvider(self):
"""
input: none
output: a ComponentID object
throws CCAException
"""
raise NotImplementedError("Abstract Class!")
def getUser(self):
"""
input: none
output: a ComponentID object
throws CCAException
"""
raise NotImplementedError("Abstract Class!")
def getProviderPortName(self):
"""
input: none
output: a string
throws CCAException
"""
raise NotImplementedError("Abstract Class!")
def getUserPortName(self):
"""
input: none
output: a string
throws CCAException
"""
raise NotImplementedError("Abstract Class!")
class Type(object):
none, Int, Long, Float, Double, Fcomplex, Dcomplex, String, Bool, IntArray, LongArray, FloatArray, DoubleArray, FcomplexArray, DComplexArray, StringArray, BoolArray = range(17)
def __init__(self):
raise NotImplementedError("Enumeration!")
class TypeMap(object):
def __init__(self):
raise NotImplementedError("Abstract Class!")
def getInt(self, key, dflt):
"""
input: string key, integer dflt
output: a integer
throws TypeMismatchException
"""
raise NotImplementedError("Abstract Class!")
def getLong(self, key, dflt):
"""
input: string key, long dflt
output: a long
throws TypeMismatchException
"""
raise NotImplementedError("Abstract Class!")
def getFloat(self, key, dflt):
"""
input: string key, float dflt
output: a float
throws TypeMismatchException
"""
raise NotImplementedError("Abstract Class!")
def getDouble(self, key, dflt):
"""
input: string key, double dflt
output: a double
throws TypeMismatchException
"""
raise NotImplementedError("Abstract Class!")
def getFcomplex(self, key, dflt):
"""
input: string key, fcomplex dflt
output: a fcomplex
throws TypeMismatchException
"""
raise NotImplementedError("Abstract Class!")
def getDcomplex(self, key, dflt):
"""
input: string key, dcomplex dflt
output: a dcomplex
throws TypeMismatchException
"""
raise NotImplementedError("Abstract Class!")
def getString(self, key, dflt):
"""
input: string key, string dflt
output: a integer
throws TypeMismatchException
"""
raise NotImplementedError("Abstract Class!")
def getBool(self, key, dflt):
"""
input: string key, bool dflt
output: a boolean
throws TypeMismatchException
"""
raise NotImplementedError("Abstract Class!")
def getIntArray(self, key, dflt):
"""
input: string key, int dflt
output: a list of int
"""
raise NotImplementedError("Abstract Class!")
def getLongArray(self, key, dflt):
"""
input: string key, long dflt
output: a list of long
"""
raise NotImplementedError("Abstract Class!")
def getFloatArray(self, key, dflt):
"""
input: string key, float dflt
output: a list of float
"""
raise NotImplementedError("Abstract Class!")
def getDoubleArray(self, key, dflt):
"""
input: string key, double dflt
output: a list of double
"""
raise NotImplementedError("Abstract Class!")
def getFcomplexArray(self, key, dflt):
"""
input: string key, fcomplex dflt
output: a list of fcomplex
"""
raise NotImplementedError("Abstract Class!")
def getDcomplexArray(self, key, dflt):
"""
input: string key, dcomplex dflt
output: a list of dcomplex
"""
raise NotImplementedError("Abstract Class!")
def getStringArray(self, key, dflt):
"""
input: string key, string dflt
output: a list of string
"""
raise NotImplementedError("Abstract Class!")
def getBoolArray(self, key, dflt):
"""
input: string key, bool dflt
output: a list of bool
"""
raise NotImplementedError("Abstract Class!")
def putInt(self, key, value):
"""
input: string key, integer value
output: void
throws TypeMismatchException
"""
raise NotImplementedError("Abstract Class!")
def putLong(self, key, value):
"""
input: string key, long value
output: void
throws TypeMismatchException
"""
raise NotImplementedError("Abstract Class!")
def putFloat(self, key, value):
"""
input: string key, float value
output: void
throws TypeMismatchException
"""
raise NotImplementedError("Abstract Class!")
def putDouble(self, key, value):
"""
input: string key, double value
output: void
throws TypeMismatchException
"""
raise NotImplementedError("Abstract Class!")
def putFcomplex(self, key, value):
"""
input: string key, fcomplex value
output: void
throws TypeMismatchException
"""
raise NotImplementedError("Abstract Class!")
def putDcomplex(self, key, value):
"""
input: string key, dcomplex value
output: void
throws TypeMismatchException
"""
raise NotImplementedError("Abstract Class!")
def putString(self, key, value):
"""
input: string key, string value
output: void
throws TypeMismatchException
"""
raise NotImplementedError("Abstract Class!")
def putBool(self, key, value):
"""
input: string key, bool value
output: void
throws TypeMismatchException
"""
raise NotImplementedError("Abstract Class!")
def putIntArray(self, key, value):
"""
input: string key, int list value
output: void
"""
raise NotImplementedError("Abstract Class!")
def putLongArray(self, key, value):
"""
input: string key, long list value
output: void
"""
raise NotImplementedError("Abstract Class!")
def putFloatArray(self, key, value):
"""
input: string key, float list value
output: void
"""
raise NotImplementedError("Abstract Class!")
def putDoubleArray(self, key, value):
"""
input: string key, double list value
output: void
"""
raise NotImplementedError("Abstract Class!")
def putFcomplexArray(self, key, value):
"""
input: string key, fcomplex list value
output: void
"""
raise NotImplementedError("Abstract Class!")
def putDcomplexArray(self, key, value):
"""
input: string key, dcomplex list value
output: void
"""
raise NotImplementedError("Abstract Class!")
def putStringArray(self, key, value):
"""
input: string key, string list value
output: void
"""
raise NotImplementedError("Abstract Class!")
def putBoolArray(self, key, value):
"""
input: string key, bool list value
output: void
"""
raise NotImplementedError("Abstract Class!")
def cloneTypeMap(self):
"""
input: none
output: a TypeMap object
"""
raise NotImplementedError("Abstract Class!")
def cloneEmpty(self):
"""
input: none
output: a TypeMap object
"""
raise NotImplementedError("Abstract Class!")
def remove(self, key):
"""
input: a string key
output: void
"""
raise NotImplementedError("Abstract Class!")
def getAllKeys(self, t):
"""
input: Type object t
output: a list of strings
"""
raise NotImplementedError("Abstract Class!")
def hasKey(self, key):
"""
input: a string key
output: boolean
"""
raise NotImplementedError("Abstract Class!")
def typeOf(self, key):
"""
input: a string key
output: a Type object
"""
raise NotImplementedError("Abstract Class!")
class CCAExceptionType(object):
Unexpected = -1
Nonstandard = 1
PortNotDefined = 2
PortAlreadyDefined = 3
PortNotConnected = 4
PortNotInUse = 5
UsesPortNotReleased = 6
BadPortName = 7
BadPortType = 8
BadProperties = 9
BadPortInfo = 10
OutOfMemory = 11
NetworkError = 12
def __init__(self):
raise NotImplementedError("Enumeration!")
class CCAException(Exception):
def __init__(self):
raise NotImplementedError("Abstract Class!")
def getCCAExceptionType(self):
"""
input: none
output: a CCAException object
"""
raise NotImplementedError("Abstract Class!")
def setCCAExceptionType(self, exceptionType):
"""
input: a field from CCAExceptionType
output: a CCAException object
"""
raise NotImplementedError("Abstract Class!")
| version = '0.1a'
class Port(object):
def __init__(self):
raise not_implemented_error('Abstract Class!')
def __init__(self, portType):
self.portType = portType
return
def is_type(self, _type):
if _type == self.portType:
return True
return False
class Component(object):
def __init__(self):
raise not_implemented_error('Abstract Class!')
def set_services(self, services):
"""
input: services object.
output: void
"""
raise not_implemented_error('Abstract Class!')
class Componentrelease(object):
def __init__(self):
raise not_implemented_error('Abstract Class!')
def release_services(self, services):
"""
input: services object.
output: void
"""
raise not_implemented_error('Abstract Class!')
class Componentid(object):
def __init__(self):
raise not_implemented_error('Abstract Class!')
def get_instance_name(self):
"""
input: none
output: a string identifier for the component (uuid?).
throws CCAException.
"""
raise not_implemented_error('Abstract Class!')
def get_serialization(self):
"""
input: none
output: a serialization of the object sufficient for saving the component's state to disk and restart at a different time.
throws CCAException.
"""
raise not_implemented_error('Abstract Class!')
class Services(object):
def __init__(self):
raise not_implemented_error('Abstract Class!')
def get_component_id(self):
"""
input: none
output: a ComponentID object
"""
raise not_implemented_error('Abstract Class!')
def create_type_map(self):
"""
input: none
output: a TypeMap object
throws CCAException
"""
raise not_implemented_error('Abstract Class!')
def register_uses_port(self, portName, type, properties):
"""
input: string portName, string type, and TypeMap properties
output: void
throws CCAException
"""
raise not_implemented_error('Abstract Class!')
def unregister_uses_port(self, portName):
"""
input: string portName
output: void
throws CCAException
"""
raise not_implemented_error('Abstract Class!')
def add_provides_port(self, inPort, portName, type, properties):
"""
input: Port inPort, string portName, string type, and TypeMap properties
output: void
throws CCAException
"""
raise not_implemented_error('Abstract Class!')
def remove_provides_port(self, portName):
"""
input: string portName
output: void
throws CCAException
"""
raise not_implemented_error('Abstract Class!')
def get_port_properties(self, portName):
"""
input: string portName
output: a TypeMap object
"""
raise not_implemented_error('Abstract Class!')
def get_port(self, portName):
"""
input: string portName
output: a Port object
throws CCAException
"""
raise not_implemented_error('Abstract Class!')
def get_port_nonblocking(self, portName):
"""
input: string portName
output: a Port object
throws CCAException
"""
raise not_implemented_error('Abstract Class!')
def release_port(self, portName):
"""
input: string portName
output: void
throws CCAException
"""
raise not_implemented_error('Abstract Class!')
def register_for_release(self, callback):
"""
input: a gov.cca.ComponentRelease object callback
output: void
"""
raise not_implemented_error('Abstract Class!')
class Abstractframework(object):
def __init__(self):
raise not_implemented_error('Abstract Class!')
def create_type_map(self):
"""
input: none
output: a TypeMap object
throws CCAException
"""
raise not_implemented_error('Abstract Class!')
def create_empty_framework(self):
"""
input: none
output: a AbstractFramework object
throws CCAException
"""
raise not_implemented_error('Abstract Class!')
def get_services(self, selfInstanceName, selfClassName, selfProperties):
"""
input: a string selfInstanceName, string selfClassName, TypeMap selfProperties
output: a Services object
throws CCAException
"""
raise not_implemented_error('Abstract Class!')
def release_services(self, services):
"""
input: a Services object
output: a AbstractFramework object
throws CCAException
"""
raise not_implemented_error('Abstract Class!')
def shutdown_framework(self):
"""
input: none
output: void
throws CCAException
"""
raise not_implemented_error('Abstract Class!')
class Componentclassdescription(object):
def __init__(self):
raise not_implemented_error('Abstract Class!')
def get_component_class_name(self):
"""
input: none
output: a string
throws CCAException
"""
raise not_implemented_error('Abstract Class!')
class Connectionid(object):
def __init__(self):
raise not_implemented_error('Abstract Class!')
def get_provider(self):
"""
input: none
output: a ComponentID object
throws CCAException
"""
raise not_implemented_error('Abstract Class!')
def get_user(self):
"""
input: none
output: a ComponentID object
throws CCAException
"""
raise not_implemented_error('Abstract Class!')
def get_provider_port_name(self):
"""
input: none
output: a string
throws CCAException
"""
raise not_implemented_error('Abstract Class!')
def get_user_port_name(self):
"""
input: none
output: a string
throws CCAException
"""
raise not_implemented_error('Abstract Class!')
class Type(object):
(none, int, long, float, double, fcomplex, dcomplex, string, bool, int_array, long_array, float_array, double_array, fcomplex_array, d_complex_array, string_array, bool_array) = range(17)
def __init__(self):
raise not_implemented_error('Enumeration!')
class Typemap(object):
def __init__(self):
raise not_implemented_error('Abstract Class!')
def get_int(self, key, dflt):
"""
input: string key, integer dflt
output: a integer
throws TypeMismatchException
"""
raise not_implemented_error('Abstract Class!')
def get_long(self, key, dflt):
"""
input: string key, long dflt
output: a long
throws TypeMismatchException
"""
raise not_implemented_error('Abstract Class!')
def get_float(self, key, dflt):
"""
input: string key, float dflt
output: a float
throws TypeMismatchException
"""
raise not_implemented_error('Abstract Class!')
def get_double(self, key, dflt):
"""
input: string key, double dflt
output: a double
throws TypeMismatchException
"""
raise not_implemented_error('Abstract Class!')
def get_fcomplex(self, key, dflt):
"""
input: string key, fcomplex dflt
output: a fcomplex
throws TypeMismatchException
"""
raise not_implemented_error('Abstract Class!')
def get_dcomplex(self, key, dflt):
"""
input: string key, dcomplex dflt
output: a dcomplex
throws TypeMismatchException
"""
raise not_implemented_error('Abstract Class!')
def get_string(self, key, dflt):
"""
input: string key, string dflt
output: a integer
throws TypeMismatchException
"""
raise not_implemented_error('Abstract Class!')
def get_bool(self, key, dflt):
"""
input: string key, bool dflt
output: a boolean
throws TypeMismatchException
"""
raise not_implemented_error('Abstract Class!')
def get_int_array(self, key, dflt):
"""
input: string key, int dflt
output: a list of int
"""
raise not_implemented_error('Abstract Class!')
def get_long_array(self, key, dflt):
"""
input: string key, long dflt
output: a list of long
"""
raise not_implemented_error('Abstract Class!')
def get_float_array(self, key, dflt):
"""
input: string key, float dflt
output: a list of float
"""
raise not_implemented_error('Abstract Class!')
def get_double_array(self, key, dflt):
"""
input: string key, double dflt
output: a list of double
"""
raise not_implemented_error('Abstract Class!')
def get_fcomplex_array(self, key, dflt):
"""
input: string key, fcomplex dflt
output: a list of fcomplex
"""
raise not_implemented_error('Abstract Class!')
def get_dcomplex_array(self, key, dflt):
"""
input: string key, dcomplex dflt
output: a list of dcomplex
"""
raise not_implemented_error('Abstract Class!')
def get_string_array(self, key, dflt):
"""
input: string key, string dflt
output: a list of string
"""
raise not_implemented_error('Abstract Class!')
def get_bool_array(self, key, dflt):
"""
input: string key, bool dflt
output: a list of bool
"""
raise not_implemented_error('Abstract Class!')
def put_int(self, key, value):
"""
input: string key, integer value
output: void
throws TypeMismatchException
"""
raise not_implemented_error('Abstract Class!')
def put_long(self, key, value):
"""
input: string key, long value
output: void
throws TypeMismatchException
"""
raise not_implemented_error('Abstract Class!')
def put_float(self, key, value):
"""
input: string key, float value
output: void
throws TypeMismatchException
"""
raise not_implemented_error('Abstract Class!')
def put_double(self, key, value):
"""
input: string key, double value
output: void
throws TypeMismatchException
"""
raise not_implemented_error('Abstract Class!')
def put_fcomplex(self, key, value):
"""
input: string key, fcomplex value
output: void
throws TypeMismatchException
"""
raise not_implemented_error('Abstract Class!')
def put_dcomplex(self, key, value):
"""
input: string key, dcomplex value
output: void
throws TypeMismatchException
"""
raise not_implemented_error('Abstract Class!')
def put_string(self, key, value):
"""
input: string key, string value
output: void
throws TypeMismatchException
"""
raise not_implemented_error('Abstract Class!')
def put_bool(self, key, value):
"""
input: string key, bool value
output: void
throws TypeMismatchException
"""
raise not_implemented_error('Abstract Class!')
def put_int_array(self, key, value):
"""
input: string key, int list value
output: void
"""
raise not_implemented_error('Abstract Class!')
def put_long_array(self, key, value):
"""
input: string key, long list value
output: void
"""
raise not_implemented_error('Abstract Class!')
def put_float_array(self, key, value):
"""
input: string key, float list value
output: void
"""
raise not_implemented_error('Abstract Class!')
def put_double_array(self, key, value):
"""
input: string key, double list value
output: void
"""
raise not_implemented_error('Abstract Class!')
def put_fcomplex_array(self, key, value):
"""
input: string key, fcomplex list value
output: void
"""
raise not_implemented_error('Abstract Class!')
def put_dcomplex_array(self, key, value):
"""
input: string key, dcomplex list value
output: void
"""
raise not_implemented_error('Abstract Class!')
def put_string_array(self, key, value):
"""
input: string key, string list value
output: void
"""
raise not_implemented_error('Abstract Class!')
def put_bool_array(self, key, value):
"""
input: string key, bool list value
output: void
"""
raise not_implemented_error('Abstract Class!')
def clone_type_map(self):
"""
input: none
output: a TypeMap object
"""
raise not_implemented_error('Abstract Class!')
def clone_empty(self):
"""
input: none
output: a TypeMap object
"""
raise not_implemented_error('Abstract Class!')
def remove(self, key):
"""
input: a string key
output: void
"""
raise not_implemented_error('Abstract Class!')
def get_all_keys(self, t):
"""
input: Type object t
output: a list of strings
"""
raise not_implemented_error('Abstract Class!')
def has_key(self, key):
"""
input: a string key
output: boolean
"""
raise not_implemented_error('Abstract Class!')
def type_of(self, key):
"""
input: a string key
output: a Type object
"""
raise not_implemented_error('Abstract Class!')
class Ccaexceptiontype(object):
unexpected = -1
nonstandard = 1
port_not_defined = 2
port_already_defined = 3
port_not_connected = 4
port_not_in_use = 5
uses_port_not_released = 6
bad_port_name = 7
bad_port_type = 8
bad_properties = 9
bad_port_info = 10
out_of_memory = 11
network_error = 12
def __init__(self):
raise not_implemented_error('Enumeration!')
class Ccaexception(Exception):
def __init__(self):
raise not_implemented_error('Abstract Class!')
def get_cca_exception_type(self):
"""
input: none
output: a CCAException object
"""
raise not_implemented_error('Abstract Class!')
def set_cca_exception_type(self, exceptionType):
"""
input: a field from CCAExceptionType
output: a CCAException object
"""
raise not_implemented_error('Abstract Class!') |
number = int(input())
dp = []
dp.append([0, 1])
for n in range(1, number):
dp.append([])
dp[n].append(sum(dp[n-1])) # 0
dp[n].append(dp[n-1][0]) # 1
print(sum(dp[number-1]))
| number = int(input())
dp = []
dp.append([0, 1])
for n in range(1, number):
dp.append([])
dp[n].append(sum(dp[n - 1]))
dp[n].append(dp[n - 1][0])
print(sum(dp[number - 1])) |
#!/usr/bin/env python3
with open('challenge67_data.txt', 'r') as f:
triangle = [[int(i) for i in l.split(' ')] for l in f.readlines()]
longest_paths = [[0] * (i+1) for i in range(len(triangle))]
# edges between x and x + 1
# Algorithm:
# Start at top
# Go to each branch, make note of the longest path to get to that point
# find the longest path in the bottom row
longest_paths[0][0] = triangle[0][0]
# now, each location has up to 2 sources (x and/or x-1, y-1)
# we can set the cost to arrive at each location the greater of the source + that locations cost
for y, row in enumerate(triangle):
if y == 0:
continue
for x, n in enumerate(row):
total_cost1 = 0
total_cost2 = 0
total_cost1 = n + longest_paths[y-1][x-1]
try:
total_cost2 = n + longest_paths[y-1][x]
except IndexError:
pass
longest_paths[y][x] = max(total_cost1, total_cost2)
# print('\n'.join([str(l) for l in longest_paths]))
print(max(longest_paths[-1]))
| with open('challenge67_data.txt', 'r') as f:
triangle = [[int(i) for i in l.split(' ')] for l in f.readlines()]
longest_paths = [[0] * (i + 1) for i in range(len(triangle))]
longest_paths[0][0] = triangle[0][0]
for (y, row) in enumerate(triangle):
if y == 0:
continue
for (x, n) in enumerate(row):
total_cost1 = 0
total_cost2 = 0
total_cost1 = n + longest_paths[y - 1][x - 1]
try:
total_cost2 = n + longest_paths[y - 1][x]
except IndexError:
pass
longest_paths[y][x] = max(total_cost1, total_cost2)
print(max(longest_paths[-1])) |
media_filter_parameter_schema = [
{
'name': 'media_id',
'in': 'query',
'required': False,
'description': 'List of integers identifying media.',
'explode': False,
'schema': {
'type': 'array',
'items': {
'type': 'integer',
'minimum': 1,
},
},
},
{
'name': 'type',
'in': 'query',
'required': False,
'description': 'Unique integer identifying media type.',
'schema': {'type': 'integer'},
},
{
'name': 'name',
'in': 'query',
'required': False,
'description': 'Name of the media to filter on.',
'schema': {'type': 'string'},
},
{
'name': 'section',
'in': 'query',
'required': False,
'description': 'Unique integer identifying a media section.',
'schema': {'type': 'integer'},
},
{
'name': 'dtype',
'in': 'query',
'required': False,
'description': 'Data type of the files, either image or video.',
'schema': {'type': 'string', 'enum': ['image', 'video', 'multi']},
},
{
'name': 'md5',
'in': 'query',
'required': False,
'description': 'MD5 sum of the media file.',
'schema': {'type': 'string'},
},
{
'name': 'gid',
'in': 'query',
'required': False,
'description': 'Upload group ID of the media file.',
'schema': {'type': 'string'},
},
{
'name': 'uid',
'in': 'query',
'required': False,
'description': 'Upload unique ID of the media file.',
'schema': {'type': 'string'},
},
{
'name': 'after',
'in': 'query',
'required': False,
'description': 'If given, all results returned will be after the '
'file with this filename. The `start` and `stop` '
'parameters are relative to this modified range.',
'schema': {'type': 'string'},
},
{
"name": "archive_lifecycle",
"in": "query",
"required": False,
"description": ("Archive lifecycle of the files, one of live (live only), archived "
"(to_archive, archived, or to_live), or all. Defaults to 'live'"),
"schema": {"type": "string", "enum": ["live", "archived", "all"]},
},
{
'name': 'annotation_search',
'in': 'query',
'required': False,
'description': 'Lucene query syntax string for use with Elasticsearch. '
'See <a href=https://www.elastic.co/guide/en/elasticsearch/'
'reference/7.10/query-dsl-query-string-query.html#query-string-syntax>reference</a>. '
'This search is applied to child annotations of media only.',
'schema': {'type': 'string'},
},
]
| media_filter_parameter_schema = [{'name': 'media_id', 'in': 'query', 'required': False, 'description': 'List of integers identifying media.', 'explode': False, 'schema': {'type': 'array', 'items': {'type': 'integer', 'minimum': 1}}}, {'name': 'type', 'in': 'query', 'required': False, 'description': 'Unique integer identifying media type.', 'schema': {'type': 'integer'}}, {'name': 'name', 'in': 'query', 'required': False, 'description': 'Name of the media to filter on.', 'schema': {'type': 'string'}}, {'name': 'section', 'in': 'query', 'required': False, 'description': 'Unique integer identifying a media section.', 'schema': {'type': 'integer'}}, {'name': 'dtype', 'in': 'query', 'required': False, 'description': 'Data type of the files, either image or video.', 'schema': {'type': 'string', 'enum': ['image', 'video', 'multi']}}, {'name': 'md5', 'in': 'query', 'required': False, 'description': 'MD5 sum of the media file.', 'schema': {'type': 'string'}}, {'name': 'gid', 'in': 'query', 'required': False, 'description': 'Upload group ID of the media file.', 'schema': {'type': 'string'}}, {'name': 'uid', 'in': 'query', 'required': False, 'description': 'Upload unique ID of the media file.', 'schema': {'type': 'string'}}, {'name': 'after', 'in': 'query', 'required': False, 'description': 'If given, all results returned will be after the file with this filename. The `start` and `stop` parameters are relative to this modified range.', 'schema': {'type': 'string'}}, {'name': 'archive_lifecycle', 'in': 'query', 'required': False, 'description': "Archive lifecycle of the files, one of live (live only), archived (to_archive, archived, or to_live), or all. Defaults to 'live'", 'schema': {'type': 'string', 'enum': ['live', 'archived', 'all']}}, {'name': 'annotation_search', 'in': 'query', 'required': False, 'description': 'Lucene query syntax string for use with Elasticsearch. See <a href=https://www.elastic.co/guide/en/elasticsearch/reference/7.10/query-dsl-query-string-query.html#query-string-syntax>reference</a>. This search is applied to child annotations of media only.', 'schema': {'type': 'string'}}] |
class Solution(object):
def wiggleSort(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
nLen = len(nums) - 1
nums.sort()
fidx = nLen // 2
sidx = nLen // 2 + 1
swapIdx = 0
while swapIdx < nLen - 1:
nums[swapIdx], nums[fidx] = nums[fidx], nums[swapIdx]
swapIdx += 1
fidx += 1
nums[swapIdx], nums[sidx] = nums[sidx], nums[swapIdx]
swapIdx += 1
sidx += 1
| class Solution(object):
def wiggle_sort(self, nums):
"""
:type nums: List[int]
:rtype: None Do not return anything, modify nums in-place instead.
"""
n_len = len(nums) - 1
nums.sort()
fidx = nLen // 2
sidx = nLen // 2 + 1
swap_idx = 0
while swapIdx < nLen - 1:
(nums[swapIdx], nums[fidx]) = (nums[fidx], nums[swapIdx])
swap_idx += 1
fidx += 1
(nums[swapIdx], nums[sidx]) = (nums[sidx], nums[swapIdx])
swap_idx += 1
sidx += 1 |
class Request:
def __init__(self,number, time):
self.number = number
self.time = time
| class Request:
def __init__(self, number, time):
self.number = number
self.time = time |
# abrir y leer archivo
f = open ('input.txt','r')
mensaje = f.read()
f.close()
# divido por linea y guardo en una lista
list_sits = mensaje.split('\n')
def extractRow(row,ini,end):
ini = ini
end = end
distance = end - ini
current = list(row)
for i in current:
distance = int(distance/2)
if(i=="F"):
end = ini + distance
elif(i=="B"):
ini = end - distance
return ini
def extractColumn(column,ini,end):
ini = ini
end = end
distance = end - ini
current = list(column)
for i in current:
distance = int(distance/2)
if(i=="L"):
end = ini + distance
elif(i=="R"):
ini = end - distance
return ini
higher_seat_id = 0
for i in list_sits:
row = extractRow(i[:-3],0,127)
column = extractColumn(i[-3:],0,7)
seat_id = row * 8 + column
if(higher_seat_id<=seat_id):
higher_seat_id = seat_id
print(higher_seat_id) | f = open('input.txt', 'r')
mensaje = f.read()
f.close()
list_sits = mensaje.split('\n')
def extract_row(row, ini, end):
ini = ini
end = end
distance = end - ini
current = list(row)
for i in current:
distance = int(distance / 2)
if i == 'F':
end = ini + distance
elif i == 'B':
ini = end - distance
return ini
def extract_column(column, ini, end):
ini = ini
end = end
distance = end - ini
current = list(column)
for i in current:
distance = int(distance / 2)
if i == 'L':
end = ini + distance
elif i == 'R':
ini = end - distance
return ini
higher_seat_id = 0
for i in list_sits:
row = extract_row(i[:-3], 0, 127)
column = extract_column(i[-3:], 0, 7)
seat_id = row * 8 + column
if higher_seat_id <= seat_id:
higher_seat_id = seat_id
print(higher_seat_id) |
"""
[2015-12-09] Challenge #244 [Intermediate] Higher order functions Array language (part 2)
https://www.reddit.com/r/dailyprogrammer/comments/3w324a/20151209_challenge_244_intermediate_higher_order/
Monday's challenge is a prerequisite. Sorry.
# J theory
Adverbs and Conjunctions in J (modifiers as a shorter group name) are primarily used to implement higher order
functions.
An adverb takes 1 parameter (that may be a function ) and may return a function (for today, assume it can only return a
function). Adverb parameter name is u.
A conjunction takes 2 parameters and may (does today) return a function. Conjunction parameter names are u and v.
From Monday, the function parameters in our array language all have 2 parameters x and y.
In J, adverbs appear to the right of their u function parameter, and x ( if not missing) and y appear to the left and
right of the group (called verb phase). More adverbs and conjunctions can appear to the right of the verb phrase, and
the evaluation order inside a verb phrase is left to right. ie. function returned by first adverb, is an input the to
next adverb on its right.
In J, Conjunctions have their u parameter (can be a verb phrase without parentheses) on the left, and their v parameter
on the right. If v is not parenthesized, then only one token (function or array or variable) is the v conjunction
parameter. More adverbs and conjunctions can be added to the right of the verb phrase.
You can use your language's natural parsing rules instead.
# 1. an insert adverb
This is actually easy and already implemented as `reduce` and `foldright` in most languages. It is `/` in J
+/ 1 2 3 4 NB. +/ is the whole verb phrase
10
1 + 2 + 3 + 4
10
an adverb in general takes one parameter (that may be a verb/function), and may return a function. The insert adverb
does take a function as parameter (add in above example), and the result is a monad function (a function that ignores
its 2nd x parameter). It may be easier, to model the insert function as the complete chain:
Insert(u, y):
where u is the function parameter, and y is an array where u is applied between items of y. But an ideal model is:
Insert(u): NB. find a function to return without needing to look at y parameters.
The result of Insert ignores any x parameter.
The definition of item in J:
A list (1d array) is a list of "scalar items"
A table (2d array) is a list of "list items"
A brick (3d array) is a list of "table items"
so,
iota 2 3
0 1 2
3 4 5
+/ iota 2 3 NB. or: (add insert) (iota 2 3)
3 5 7
0 1 2 + 3 4 5
3 5 7
+/ iota 10 5 NB. or: insert(add) iota ([2, 3])
225 235 245 255 265
iota 3 2 4 NB. result has 3 items
0 1 2 3
4 5 6 7
8 9 10 11
12 13 14 15
16 17 18 19
20 21 22 23
+/ iota 3 2 4 NB. remember insert applies between items.
24 27 30 33
36 39 42 45
+/ +/ iota 3 2 4
60 66 72 78
Implement an insert adverb in your favorite language.
J definition of insert (variation from builtin to ignore x parameter) : `insert =: 1 : 'u/@:]'`
# 2. a swap adverb
swap is an adverb that reverses the x and y parameters to its function parameter such that y is passed x, and x is
passed y. If there is no x, parameter, then the function is passed (y,y)
a perhaps easy model is: the signature `swap(u, x, y=x):` but a better signature would be `swap(u):` and return a
composition of u and the swapping mechanics needed.
swap is ~ in J. iota is from Monday's challenge.
2 3 iota~ 1 NB. 1 + iota 2 3
1 2 3
4 5 6
iota~ 4 NB. 4 + iota 4
4 5 6 7
iota~/ 2 2 4 NB. insert swap iota between items of 2 2 4
4 6
iota~/ 2 4
4 5
iota insert~ 2 2 3 NB. swap (insert iota) between items of 3 2 3.
2 3 4 5
6 7 8 9
10 11 12 13
14 15 16 17
18 19 20 21
22 23 24 25
last result is same as if swap is ommitted, because insert has been defined to ignore x parameter, and swap duplicates
y as x. swap applies to the function after insert (result of insert)
swap(add) ([1, 2, 3]) NB. y is copied into x parameter
2 4 6
implement a swap adverb.
# 3. Compose conjunction.
Composition of functions u and v should be familiar. An easy model is:
`compose(u,v,y,x):` creating equivalent result to `u(v(y, x))`
note that the u function ignores its x parameter (x default value will be passed to it)
An ideal signature for compose, is compose(u,v): (In J, compose is `@:`)
2 3 iota@:+ 1 2 NB. compose(iota, add)([2,3],[1,2])
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
# 4. append itemize, and joincells functions
In Monday's bonus and iota function, the request was to make a recursive function that would then `joincells` of its
recursive calls to make one large array.
if you `append` 2 lists together, you get 1 larger list. A scalar appended with a list or scalar is also a list.
The `itemize` function takes an array and increases its dimensions by 1, creating a single item in a higher dimension.
itemize on a scalar creates a list of 1 item. itemize on a list creates a table with 1 record (that contains the
original list). itemize on a table creates a 3d array with 1 item that is a table.
If you `append` 2 items of the same dimensions, the result is 2 items. 1 record appended to 3 records is 4 items of
records (a table with 4 items). (the difference between a record and a list is that a record is a table with 1 row
(item). A list is a collection of scalar (items))
If you `append` a smaller-dimensioned item (list) with a larger-dimensioned item (record), the smaller-dimensioned item
is `itemize`d until it is the same dimension as the larger item. `append` of an item with empty item (empty can still
be high dimensioned) results in 1 item of the largest-dimensioned-parameter.
3 4 5 , iota 0 0 0 NB. append list with empty 3d array.
3 4 5
above result looks like a list, but is a brick (3d) with 1 table item, that has 1 record item.
the `joincells` function is something that was used by iota (whether you realized it or not) on the bonus applications
of Monday's challenge.
`cells` are an internal list of arrays. The algorithm is:
Find the largest dimensioned cell (array in the list).
With iota, create an empty cell that is 1 dimension higher than that maximum dimension. (for example: if all the cells
are lists, then `iota 0 0` creates an empty 0 record table.
With that new cell added on the right of the list of cells, insert(append) all the cells. (foldright append to all of
the cells). As an alternative to the iota call, you may also repeatedly itemize each of the cell arrays until they are
one dimension higher than the max-dimension-cell.
itemize(y , x=ignored): Rank _ _ NB. adds 1 dimension to y
append(y , x): Rank _ _ NB. joins x (first) to y (last). see itemize preprocessing rules
above.
joincells(listofarrays): internal function NB. see above algorithm. Though an internal function, can also be
implemented with boxes.
(itemize 4) append 1 2 3 NB. scalar 4 made into list append to other list = list
4 1 2 3
(itemize 4) append (itemize 1 2 3) NB. list append to table = table. Fills are applied to shorter list.
4 0 0
1 2 3
1 2 3 joincells 7 NB. though internal, if there are only 2 arrays to join, it works as a f(y,x)
function.
1 2 3
7 0 0
1 2 3 joincells iota 2 4
1 2 3 0
0 0 0 0
0 1 2 3
4 5 6 7
1 2 3 4 joincells iota 2 3 NB. fills are applied on the append stage.
1 2 3 4
0 0 0 0
0 1 2 0
3 4 5 0
try to implement joincells as `compose(insert(append), pretransform_arrays_function):`
# 5. Rank conjunction
This is the main challenge of the day...
The Rank conjunction can be used to split up a function call into many function calls that each results in a cell, and
then the joincells function above turns those individual function calls into a single array result.
While each function has a built in default rank, the rank conjunction **can lower** the "operating" rank of a function.
This is easier to understand as splitting the inputs to the function. `"` is the rank in J. the v (right) argument
to rank can be:
1 number: splits y argument into cells of that dimension. x rank is infinity (or is ignored).
2 numbers: splits y into cells of first number dimension, and splits x into 2nd number dimension.
`Rank(u, _ _) ` specifies rank infinity for x and y which is the same as no rank modifier at all since the full arrays
of x and y will be passed to u.
you may use 32000 as a substitute for infinity, or the default value for both "v parameters" to Rank.
`Rank(iota, 0 0)` will split the y and x parameters into scalars and call iota for each split
pR 1 3 iota("0 0) 3 4 NB. "(0 0) is Rank(u, 0 0) (an adverb) iota("0 0) is Rank(iota, 0 0). returns a
function.
1 2 3 0
3 4 5 6
equivalent to:
(1 iota 3) joincells (3 iota 4)
1 2 3 0
3 4 5 6
1 2 + 3 4 5 NB. an error in J, because only length 1 items are expanded to match the other argument lengths.
1 2 +("0 1) 3 4 5 NB. using rank to pass compatible lengths. (the order of rank v parameters in J is reversed
because x is on the left, and y on the right.
4 5 6
5 6 7
1 2 +("1 0) 3 4 5
4 5
5 6
6 7
Note in the last 2 examples, 2 items were matched with 1 item (first), and 1 item was matched with 3 items (2nd).
When matching different length items, if the lower array count is 1 item, then it is copied the number of times needed
to be the same length as the other array.
(add insert) iota 10 5 NB. seen before puts insert between rows. end result is sum of columns.
225 235 245 255 265
(add insert)"1 iota 10 5 NB. cells are the rows. result of each cell is sum of rows (a scalar). joincells
makes a list.
10 35 60 85 110 135 160 185 210 235
the last call is equivalent to `Compose(Rank(insert(add)), 1), iota)([10,5])`
#6. simple functions
`Left(y,x): return y` `]` in J
`Right(y,x): return swap(Left)(y, x=missing)` NB. returns y if there is no x. `[` in J
`double(y,x=ignored): return swap(add) y` NB. ignores x.
double 5
10
1 2 3 double~ 5 NB. swapped so passes x as y.
2 4 6
double~ 5 2 NB. if there was an x, then double that. Since there isn't, double y.
10 4
double~/ 5 2 NB. insert(swap(double))([5,2])
10
5 double~ 2
10
"""
def main():
pass
if __name__ == "__main__":
main()
| """
[2015-12-09] Challenge #244 [Intermediate] Higher order functions Array language (part 2)
https://www.reddit.com/r/dailyprogrammer/comments/3w324a/20151209_challenge_244_intermediate_higher_order/
Monday's challenge is a prerequisite. Sorry.
# J theory
Adverbs and Conjunctions in J (modifiers as a shorter group name) are primarily used to implement higher order
functions.
An adverb takes 1 parameter (that may be a function ) and may return a function (for today, assume it can only return a
function). Adverb parameter name is u.
A conjunction takes 2 parameters and may (does today) return a function. Conjunction parameter names are u and v.
From Monday, the function parameters in our array language all have 2 parameters x and y.
In J, adverbs appear to the right of their u function parameter, and x ( if not missing) and y appear to the left and
right of the group (called verb phase). More adverbs and conjunctions can appear to the right of the verb phrase, and
the evaluation order inside a verb phrase is left to right. ie. function returned by first adverb, is an input the to
next adverb on its right.
In J, Conjunctions have their u parameter (can be a verb phrase without parentheses) on the left, and their v parameter
on the right. If v is not parenthesized, then only one token (function or array or variable) is the v conjunction
parameter. More adverbs and conjunctions can be added to the right of the verb phrase.
You can use your language's natural parsing rules instead.
# 1. an insert adverb
This is actually easy and already implemented as `reduce` and `foldright` in most languages. It is `/` in J
+/ 1 2 3 4 NB. +/ is the whole verb phrase
10
1 + 2 + 3 + 4
10
an adverb in general takes one parameter (that may be a verb/function), and may return a function. The insert adverb
does take a function as parameter (add in above example), and the result is a monad function (a function that ignores
its 2nd x parameter). It may be easier, to model the insert function as the complete chain:
Insert(u, y):
where u is the function parameter, and y is an array where u is applied between items of y. But an ideal model is:
Insert(u): NB. find a function to return without needing to look at y parameters.
The result of Insert ignores any x parameter.
The definition of item in J:
A list (1d array) is a list of "scalar items"
A table (2d array) is a list of "list items"
A brick (3d array) is a list of "table items"
so,
iota 2 3
0 1 2
3 4 5
+/ iota 2 3 NB. or: (add insert) (iota 2 3)
3 5 7
0 1 2 + 3 4 5
3 5 7
+/ iota 10 5 NB. or: insert(add) iota ([2, 3])
225 235 245 255 265
iota 3 2 4 NB. result has 3 items
0 1 2 3
4 5 6 7
8 9 10 11
12 13 14 15
16 17 18 19
20 21 22 23
+/ iota 3 2 4 NB. remember insert applies between items.
24 27 30 33
36 39 42 45
+/ +/ iota 3 2 4
60 66 72 78
Implement an insert adverb in your favorite language.
J definition of insert (variation from builtin to ignore x parameter) : `insert =: 1 : 'u/@:]'`
# 2. a swap adverb
swap is an adverb that reverses the x and y parameters to its function parameter such that y is passed x, and x is
passed y. If there is no x, parameter, then the function is passed (y,y)
a perhaps easy model is: the signature `swap(u, x, y=x):` but a better signature would be `swap(u):` and return a
composition of u and the swapping mechanics needed.
swap is ~ in J. iota is from Monday's challenge.
2 3 iota~ 1 NB. 1 + iota 2 3
1 2 3
4 5 6
iota~ 4 NB. 4 + iota 4
4 5 6 7
iota~/ 2 2 4 NB. insert swap iota between items of 2 2 4
4 6
iota~/ 2 4
4 5
iota insert~ 2 2 3 NB. swap (insert iota) between items of 3 2 3.
2 3 4 5
6 7 8 9
10 11 12 13
14 15 16 17
18 19 20 21
22 23 24 25
last result is same as if swap is ommitted, because insert has been defined to ignore x parameter, and swap duplicates
y as x. swap applies to the function after insert (result of insert)
swap(add) ([1, 2, 3]) NB. y is copied into x parameter
2 4 6
implement a swap adverb.
# 3. Compose conjunction.
Composition of functions u and v should be familiar. An easy model is:
`compose(u,v,y,x):` creating equivalent result to `u(v(y, x))`
note that the u function ignores its x parameter (x default value will be passed to it)
An ideal signature for compose, is compose(u,v): (In J, compose is `@:`)
2 3 iota@:+ 1 2 NB. compose(iota, add)([2,3],[1,2])
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
# 4. append itemize, and joincells functions
In Monday's bonus and iota function, the request was to make a recursive function that would then `joincells` of its
recursive calls to make one large array.
if you `append` 2 lists together, you get 1 larger list. A scalar appended with a list or scalar is also a list.
The `itemize` function takes an array and increases its dimensions by 1, creating a single item in a higher dimension.
itemize on a scalar creates a list of 1 item. itemize on a list creates a table with 1 record (that contains the
original list). itemize on a table creates a 3d array with 1 item that is a table.
If you `append` 2 items of the same dimensions, the result is 2 items. 1 record appended to 3 records is 4 items of
records (a table with 4 items). (the difference between a record and a list is that a record is a table with 1 row
(item). A list is a collection of scalar (items))
If you `append` a smaller-dimensioned item (list) with a larger-dimensioned item (record), the smaller-dimensioned item
is `itemize`d until it is the same dimension as the larger item. `append` of an item with empty item (empty can still
be high dimensioned) results in 1 item of the largest-dimensioned-parameter.
3 4 5 , iota 0 0 0 NB. append list with empty 3d array.
3 4 5
above result looks like a list, but is a brick (3d) with 1 table item, that has 1 record item.
the `joincells` function is something that was used by iota (whether you realized it or not) on the bonus applications
of Monday's challenge.
`cells` are an internal list of arrays. The algorithm is:
Find the largest dimensioned cell (array in the list).
With iota, create an empty cell that is 1 dimension higher than that maximum dimension. (for example: if all the cells
are lists, then `iota 0 0` creates an empty 0 record table.
With that new cell added on the right of the list of cells, insert(append) all the cells. (foldright append to all of
the cells). As an alternative to the iota call, you may also repeatedly itemize each of the cell arrays until they are
one dimension higher than the max-dimension-cell.
itemize(y , x=ignored): Rank _ _ NB. adds 1 dimension to y
append(y , x): Rank _ _ NB. joins x (first) to y (last). see itemize preprocessing rules
above.
joincells(listofarrays): internal function NB. see above algorithm. Though an internal function, can also be
implemented with boxes.
(itemize 4) append 1 2 3 NB. scalar 4 made into list append to other list = list
4 1 2 3
(itemize 4) append (itemize 1 2 3) NB. list append to table = table. Fills are applied to shorter list.
4 0 0
1 2 3
1 2 3 joincells 7 NB. though internal, if there are only 2 arrays to join, it works as a f(y,x)
function.
1 2 3
7 0 0
1 2 3 joincells iota 2 4
1 2 3 0
0 0 0 0
0 1 2 3
4 5 6 7
1 2 3 4 joincells iota 2 3 NB. fills are applied on the append stage.
1 2 3 4
0 0 0 0
0 1 2 0
3 4 5 0
try to implement joincells as `compose(insert(append), pretransform_arrays_function):`
# 5. Rank conjunction
This is the main challenge of the day...
The Rank conjunction can be used to split up a function call into many function calls that each results in a cell, and
then the joincells function above turns those individual function calls into a single array result.
While each function has a built in default rank, the rank conjunction **can lower** the "operating" rank of a function.
This is easier to understand as splitting the inputs to the function. `"` is the rank in J. the v (right) argument
to rank can be:
1 number: splits y argument into cells of that dimension. x rank is infinity (or is ignored).
2 numbers: splits y into cells of first number dimension, and splits x into 2nd number dimension.
`Rank(u, _ _) ` specifies rank infinity for x and y which is the same as no rank modifier at all since the full arrays
of x and y will be passed to u.
you may use 32000 as a substitute for infinity, or the default value for both "v parameters" to Rank.
`Rank(iota, 0 0)` will split the y and x parameters into scalars and call iota for each split
pR 1 3 iota("0 0) 3 4 NB. "(0 0) is Rank(u, 0 0) (an adverb) iota("0 0) is Rank(iota, 0 0). returns a
function.
1 2 3 0
3 4 5 6
equivalent to:
(1 iota 3) joincells (3 iota 4)
1 2 3 0
3 4 5 6
1 2 + 3 4 5 NB. an error in J, because only length 1 items are expanded to match the other argument lengths.
1 2 +("0 1) 3 4 5 NB. using rank to pass compatible lengths. (the order of rank v parameters in J is reversed
because x is on the left, and y on the right.
4 5 6
5 6 7
1 2 +("1 0) 3 4 5
4 5
5 6
6 7
Note in the last 2 examples, 2 items were matched with 1 item (first), and 1 item was matched with 3 items (2nd).
When matching different length items, if the lower array count is 1 item, then it is copied the number of times needed
to be the same length as the other array.
(add insert) iota 10 5 NB. seen before puts insert between rows. end result is sum of columns.
225 235 245 255 265
(add insert)"1 iota 10 5 NB. cells are the rows. result of each cell is sum of rows (a scalar). joincells
makes a list.
10 35 60 85 110 135 160 185 210 235
the last call is equivalent to `Compose(Rank(insert(add)), 1), iota)([10,5])`
#6. simple functions
`Left(y,x): return y` `]` in J
`Right(y,x): return swap(Left)(y, x=missing)` NB. returns y if there is no x. `[` in J
`double(y,x=ignored): return swap(add) y` NB. ignores x.
double 5
10
1 2 3 double~ 5 NB. swapped so passes x as y.
2 4 6
double~ 5 2 NB. if there was an x, then double that. Since there isn't, double y.
10 4
double~/ 5 2 NB. insert(swap(double))([5,2])
10
5 double~ 2
10
"""
def main():
pass
if __name__ == '__main__':
main() |
w, h, n = map(int, input().split())
def k_fit_dip(side):
w_k = side // w
h_k = side // h
return w_k * h_k
def size_search():
left = 0
right = 10 ** 14
while right - left > 1:
mid = (right + left) // 2
k_dip = k_fit_dip(mid)
if k_dip >= n:
right = mid
else:
left = mid
return right
print(size_search())
| (w, h, n) = map(int, input().split())
def k_fit_dip(side):
w_k = side // w
h_k = side // h
return w_k * h_k
def size_search():
left = 0
right = 10 ** 14
while right - left > 1:
mid = (right + left) // 2
k_dip = k_fit_dip(mid)
if k_dip >= n:
right = mid
else:
left = mid
return right
print(size_search()) |
"""
Copy List with Random Pointer
A linked list of length n is given such that each node contains an additional random pointer,
which could point to any node in the list, or null.
Construct a deep copy of the list. The deep copy should consist of exactly n brand new nodes,
where each new node has its value set to the value of its corresponding original node.
Both the next and random pointer of the new nodes should point to new nodes in the
copied list such that the pointers in the original list and copied list represent the same list state.
None of the pointers in the new list should point to nodes in the original list.
For example, if there are two nodes X and Y in the original list, where X.random --> Y,
then for the corresponding two nodes x and y in the copied list, x.random --> y.
Return the head of the copied linked list.
The linked list is represented in the input/output as a list of n nodes. Each node is represented as a pair of [val, random_index] where:
val: an integer representing Node.val
random_index: the index of the node (range from 0 to n-1) that the random pointer points to, or null if it does not point to any node.
Your code will only be given the head of the original linked list.
Example 1:
Input: head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
Output: [[7,null],[13,0],[11,4],[10,2],[1,0]]
Example 2:
Input: head = [[1,1],[2,1]]
Output: [[1,1],[2,1]]
Example 3:
Input: head = [[3,null],[3,0],[3,null]]
Output: [[3,null],[3,0],[3,null]]
Example 4:
Input: head = []
Output: []
Explanation: The given linked list is empty (null pointer), so return null.
Constraints:
0 <= n <= 1000
-10000 <= Node.val <= 10000
Node.random is null or is pointing to some node in the linked list.
"""
class Node:
def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
self.val = int(x)
self.next = next
self.random = random
class Solution(object):
def copyRandomList(self, head):
"""
:type head: Node
:rtype: Node
"""
if not head:
return head
# Creating a new weaved list of original and copied nodes.
ptr = head
while ptr:
# Cloned node
new_node = Node(ptr.val, None, None)
# Inserting the cloned node just next to the original node.
# If A->B->C is the original linked list,
# Linked list after weaving cloned nodes would be A->A'->B->B'->C->C'
new_node.next = ptr.next
ptr.next = new_node
ptr = new_node.next
ptr = head
# Now link the random pointers of the new nodes created.
# Iterate the newly created list and use the original nodes random pointers,
# to assign references to random pointers for cloned nodes.
while ptr:
ptr.next.random = ptr.random.next if ptr.random else None
ptr = ptr.next.next
# Unweave the linked list to get back the original linked list and the cloned list.
# i.e. A->A'->B->B'->C->C' would be broken to A->B->C and A'->B'->C'
ptr_old_list = head # A->B->C
ptr_new_list = head.next # A'->B'->C'
head_new = head.next
while ptr_old_list:
ptr_old_list.next = ptr_old_list.next.next
ptr_new_list.next = ptr_new_list.next.next if ptr_new_list.next else None
ptr_old_list = ptr_old_list.next
ptr_new_list = ptr_new_list.next
return head_new
| """
Copy List with Random Pointer
A linked list of length n is given such that each node contains an additional random pointer,
which could point to any node in the list, or null.
Construct a deep copy of the list. The deep copy should consist of exactly n brand new nodes,
where each new node has its value set to the value of its corresponding original node.
Both the next and random pointer of the new nodes should point to new nodes in the
copied list such that the pointers in the original list and copied list represent the same list state.
None of the pointers in the new list should point to nodes in the original list.
For example, if there are two nodes X and Y in the original list, where X.random --> Y,
then for the corresponding two nodes x and y in the copied list, x.random --> y.
Return the head of the copied linked list.
The linked list is represented in the input/output as a list of n nodes. Each node is represented as a pair of [val, random_index] where:
val: an integer representing Node.val
random_index: the index of the node (range from 0 to n-1) that the random pointer points to, or null if it does not point to any node.
Your code will only be given the head of the original linked list.
Example 1:
Input: head = [[7,null],[13,0],[11,4],[10,2],[1,0]]
Output: [[7,null],[13,0],[11,4],[10,2],[1,0]]
Example 2:
Input: head = [[1,1],[2,1]]
Output: [[1,1],[2,1]]
Example 3:
Input: head = [[3,null],[3,0],[3,null]]
Output: [[3,null],[3,0],[3,null]]
Example 4:
Input: head = []
Output: []
Explanation: The given linked list is empty (null pointer), so return null.
Constraints:
0 <= n <= 1000
-10000 <= Node.val <= 10000
Node.random is null or is pointing to some node in the linked list.
"""
class Node:
def __init__(self, x: int, next: 'Node'=None, random: 'Node'=None):
self.val = int(x)
self.next = next
self.random = random
class Solution(object):
def copy_random_list(self, head):
"""
:type head: Node
:rtype: Node
"""
if not head:
return head
ptr = head
while ptr:
new_node = node(ptr.val, None, None)
new_node.next = ptr.next
ptr.next = new_node
ptr = new_node.next
ptr = head
while ptr:
ptr.next.random = ptr.random.next if ptr.random else None
ptr = ptr.next.next
ptr_old_list = head
ptr_new_list = head.next
head_new = head.next
while ptr_old_list:
ptr_old_list.next = ptr_old_list.next.next
ptr_new_list.next = ptr_new_list.next.next if ptr_new_list.next else None
ptr_old_list = ptr_old_list.next
ptr_new_list = ptr_new_list.next
return head_new |
# Tuples is an immutable object in Python. It means once data is set, you cannot change those data.
# Can be used for constant data or dictionary without key (nested tuples)
# Empty Tuple initialization
tup = ()
print(tup)
# Tuple initialization with data
# I didn't like this way thought ;)
tup1 = 'python', 'aws', 'security'
print(tup1)
# Another for doing the same
tup2 = ('python', 'django', 'linux')
print(tup2)
# Concatenation
tup3 = tup1 + tup2
print(tup3)
# Nesting of tuples
tup4 = (tup1, tup2)
print(tup4)
# Length of a tuple
print(len(tup3))
print(len(tup4))
# Tuple Indexing and slicing
print(tup3[2])
print(tup2[1:])
# Deleting a tuple, removing individual element from the tuple is not possible. It deletes the whole tuple
del tup4
# Converts a list into tuple
tup5 = tuple(["Sanjeev", '2021', "Flexmind"])
print(tup5)
# try tuple() to a string
tup6 = tuple('Python')
print(tup6)
#Tuple iteration
for tup in tup5:
print(tup)
# Max and min method
max_elem = max(tup1)
print("max element: ", max_elem)
print("min element: ", min(tup5))
| tup = ()
print(tup)
tup1 = ('python', 'aws', 'security')
print(tup1)
tup2 = ('python', 'django', 'linux')
print(tup2)
tup3 = tup1 + tup2
print(tup3)
tup4 = (tup1, tup2)
print(tup4)
print(len(tup3))
print(len(tup4))
print(tup3[2])
print(tup2[1:])
del tup4
tup5 = tuple(['Sanjeev', '2021', 'Flexmind'])
print(tup5)
tup6 = tuple('Python')
print(tup6)
for tup in tup5:
print(tup)
max_elem = max(tup1)
print('max element: ', max_elem)
print('min element: ', min(tup5)) |
class CombinationIterator:
def __init__(self, characters, combinationLength):
self.characters = characters
self.combinationLength = combinationLength
self.every_comb = self.generate()
def generate(self):
every_comb = []
for i in range(2**len(self.characters)):
string = ""
for j in range(len(self.characters)):
if ((1<<j) & i > 0):
string += self.characters[j]
if len(string) == self.combinationLength and string not in every_comb:
every_comb.append(string)
every_comb.sort()
return every_comb
def nextStr(self):
for id in range(len(self.every_comb)):
return self.every_comb.pop(id)
def hasNext(self):
if len(self.every_comb) >= 1:
return True
return False
itr = CombinationIterator("bvwz", 2)
#print(itr.every_comb)
| class Combinationiterator:
def __init__(self, characters, combinationLength):
self.characters = characters
self.combinationLength = combinationLength
self.every_comb = self.generate()
def generate(self):
every_comb = []
for i in range(2 ** len(self.characters)):
string = ''
for j in range(len(self.characters)):
if 1 << j & i > 0:
string += self.characters[j]
if len(string) == self.combinationLength and string not in every_comb:
every_comb.append(string)
every_comb.sort()
return every_comb
def next_str(self):
for id in range(len(self.every_comb)):
return self.every_comb.pop(id)
def has_next(self):
if len(self.every_comb) >= 1:
return True
return False
itr = combination_iterator('bvwz', 2) |
class Set:
""" Set Implement in Python 3 """
def __init__(self, values=None):
"""this is the constructor it gets called when you create a new Set."""
self.dict = {} # Each instance of set has it's own dict property
if values is not None:
for value in values:
self.add(value)
def __repr__(self):
""" this is the string representations of a set objects"""
return f"Set: {self.dict.keys()}"
# we'll represnt membership by being a key in self.dict with value True
def add(self, value):
self.dict[value] = True
def contains(self, value):
return value in self.dict
def remove(self, value):
del self.dict[value]
| class Set:
""" Set Implement in Python 3 """
def __init__(self, values=None):
"""this is the constructor it gets called when you create a new Set."""
self.dict = {}
if values is not None:
for value in values:
self.add(value)
def __repr__(self):
""" this is the string representations of a set objects"""
return f'Set: {self.dict.keys()}'
def add(self, value):
self.dict[value] = True
def contains(self, value):
return value in self.dict
def remove(self, value):
del self.dict[value] |
def digit_count1(n):
n = str(n)
return int(''.join(str(n.count(i)) for i in n))
def digit_count2(n):
num_counts = dict()
str_n = str(n)
for x in str_n:
if x not in num_counts:
num_counts[x] = 1
else:
num_counts[x] += 1
return int("".join(str(num_counts[x]) for x in str_n))
dc1 = digit_count1(136116), digit_count1(221333), digit_count1(136116), digit_count1(2)
print(dc1)
dc2 = digit_count2(136116), digit_count2(221333), digit_count2(136116), digit_count2(2)
print(dc2) | def digit_count1(n):
n = str(n)
return int(''.join((str(n.count(i)) for i in n)))
def digit_count2(n):
num_counts = dict()
str_n = str(n)
for x in str_n:
if x not in num_counts:
num_counts[x] = 1
else:
num_counts[x] += 1
return int(''.join((str(num_counts[x]) for x in str_n)))
dc1 = (digit_count1(136116), digit_count1(221333), digit_count1(136116), digit_count1(2))
print(dc1)
dc2 = (digit_count2(136116), digit_count2(221333), digit_count2(136116), digit_count2(2))
print(dc2) |
DARK_SKY_BASE_URL = 'https://api.darksky.net/forecast'
WEATHER_COLUMNS = [
'time',
'summary',
'icon',
'sunriseTime',
'sunsetTime',
'precipIntensity',
'precipIntensityMax',
'precipProbability',
'precipType',
'temperatureHigh',
'temperatureHighTime',
'temperatureLow',
'temperatureLowTime',
'dewPoint',
'humidity',
'pressure',
'windSpeed',
'windGust',
'windGustTime',
'windBearing',
'cloudCover',
'uvIndex',
'uvIndexTime',
'visibility',
'ozone',
]
FEATURE_COLUMNS = [
'sunriseTime',
'sunsetTime',
'precipIntensity',
'precipIntensityMax',
'precipProbability',
'temperatureHigh',
'temperatureHighTime',
'temperatureLow',
'temperatureLowTime',
'dewPoint',
'humidity',
'pressure',
'windSpeed',
'windGust',
'windGustTime',
'windBearing',
'cloudCover',
'uvIndex',
'uvIndexTime',
'visibility',
'ozone',
'summary_Clear throughout the day.',
'summary_Drizzle in the afternoon and evening.',
'summary_Drizzle in the morning and afternoon.',
'summary_Drizzle starting in the afternoon.',
'summary_Drizzle until morning, starting again in the evening.',
'summary_Foggy in the morning and afternoon.',
'summary_Foggy in the morning.',
'summary_Foggy overnight.',
'summary_Foggy starting in the afternoon.',
'summary_Foggy throughout the day.',
'summary_Foggy until evening.',
'summary_Heavy rain until morning, starting again in the evening.',
'summary_Light rain in the afternoon and evening.',
'summary_Light rain in the evening and overnight.',
'summary_Light rain in the morning and afternoon.',
'summary_Light rain in the morning and overnight.',
'summary_Light rain in the morning.',
'summary_Light rain overnight.',
'summary_Light rain starting in the afternoon.',
'summary_Light rain throughout the day.',
'summary_Light rain until evening.',
'summary_Light rain until morning, starting again in the evening.',
'summary_Mostly cloudy throughout the day.',
'summary_Overcast throughout the day.',
'summary_Partly cloudy throughout the day.',
'summary_Possible drizzle in the afternoon and evening.',
'summary_Possible drizzle in the evening and overnight.',
'summary_Possible drizzle in the morning and afternoon.',
'summary_Possible drizzle in the morning.',
'summary_Possible drizzle overnight.',
'summary_Possible drizzle throughout the day.',
'summary_Possible drizzle until morning, starting again in the evening.',
'summary_Possible light rain until evening.',
'summary_Rain in the evening and overnight.',
'summary_Rain in the morning and afternoon.',
'summary_Rain in the morning.',
'summary_Rain overnight.',
'summary_Rain starting in the afternoon.',
'summary_Rain throughout the day.',
'summary_Rain until evening.',
'summary_Rain until morning, starting again in the evening.',
'icon_clear-day',
'icon_cloudy',
'icon_fog',
'icon_partly-cloudy-day',
'icon_rain',
'didRain_False',
'didRain_True',
]
LABEL_COLUMN = 'peak_traffic_load'
| dark_sky_base_url = 'https://api.darksky.net/forecast'
weather_columns = ['time', 'summary', 'icon', 'sunriseTime', 'sunsetTime', 'precipIntensity', 'precipIntensityMax', 'precipProbability', 'precipType', 'temperatureHigh', 'temperatureHighTime', 'temperatureLow', 'temperatureLowTime', 'dewPoint', 'humidity', 'pressure', 'windSpeed', 'windGust', 'windGustTime', 'windBearing', 'cloudCover', 'uvIndex', 'uvIndexTime', 'visibility', 'ozone']
feature_columns = ['sunriseTime', 'sunsetTime', 'precipIntensity', 'precipIntensityMax', 'precipProbability', 'temperatureHigh', 'temperatureHighTime', 'temperatureLow', 'temperatureLowTime', 'dewPoint', 'humidity', 'pressure', 'windSpeed', 'windGust', 'windGustTime', 'windBearing', 'cloudCover', 'uvIndex', 'uvIndexTime', 'visibility', 'ozone', 'summary_Clear throughout the day.', 'summary_Drizzle in the afternoon and evening.', 'summary_Drizzle in the morning and afternoon.', 'summary_Drizzle starting in the afternoon.', 'summary_Drizzle until morning, starting again in the evening.', 'summary_Foggy in the morning and afternoon.', 'summary_Foggy in the morning.', 'summary_Foggy overnight.', 'summary_Foggy starting in the afternoon.', 'summary_Foggy throughout the day.', 'summary_Foggy until evening.', 'summary_Heavy rain until morning, starting again in the evening.', 'summary_Light rain in the afternoon and evening.', 'summary_Light rain in the evening and overnight.', 'summary_Light rain in the morning and afternoon.', 'summary_Light rain in the morning and overnight.', 'summary_Light rain in the morning.', 'summary_Light rain overnight.', 'summary_Light rain starting in the afternoon.', 'summary_Light rain throughout the day.', 'summary_Light rain until evening.', 'summary_Light rain until morning, starting again in the evening.', 'summary_Mostly cloudy throughout the day.', 'summary_Overcast throughout the day.', 'summary_Partly cloudy throughout the day.', 'summary_Possible drizzle in the afternoon and evening.', 'summary_Possible drizzle in the evening and overnight.', 'summary_Possible drizzle in the morning and afternoon.', 'summary_Possible drizzle in the morning.', 'summary_Possible drizzle overnight.', 'summary_Possible drizzle throughout the day.', 'summary_Possible drizzle until morning, starting again in the evening.', 'summary_Possible light rain until evening.', 'summary_Rain in the evening and overnight.', 'summary_Rain in the morning and afternoon.', 'summary_Rain in the morning.', 'summary_Rain overnight.', 'summary_Rain starting in the afternoon.', 'summary_Rain throughout the day.', 'summary_Rain until evening.', 'summary_Rain until morning, starting again in the evening.', 'icon_clear-day', 'icon_cloudy', 'icon_fog', 'icon_partly-cloudy-day', 'icon_rain', 'didRain_False', 'didRain_True']
label_column = 'peak_traffic_load' |
# Write a procedure, rotate which takes as its input a string of lower case
# letters, a-z, and spaces, and an integer n, and returns the string constructed
# by shifting each of the letters n steps, and leaving the spaces unchanged.
# Note that 'a' follows 'z'. You can use an additional procedure if you
# choose to as long as rotate returns the correct string.
# Note that n can be positive, negative or zero.
def rotate(string_, shift):
output = []
for letter in string_:
if letter == ' ':
output.append(' ')
else:
output.append(shift_n_letters(letter, shift))
return ''.join(output)
def shift_n_letters(letter, n):
result = ord(letter) + n
if result < ord('a'):
return chr(ord('z') - (ord('a') - result) + 1)
elif result > ord('z'):
return chr(ord('a') + (result - ord('z')) - 1)
else:
return chr(result)
print(rotate ('sarah', 13))
# >>> 'fnenu'
print(rotate('fnenu', 13))
# >>> 'sarah'
print(rotate('dave', 5))
# >>>'ifaj'
print(rotate('ifaj', -5))
# >>>'dave'
print(rotate(("zw pfli tfuv nfibj tfiivtkcp pfl jyflcu "
"sv rscv kf ivru kyzj"), -17))
# >>> ???
| def rotate(string_, shift):
output = []
for letter in string_:
if letter == ' ':
output.append(' ')
else:
output.append(shift_n_letters(letter, shift))
return ''.join(output)
def shift_n_letters(letter, n):
result = ord(letter) + n
if result < ord('a'):
return chr(ord('z') - (ord('a') - result) + 1)
elif result > ord('z'):
return chr(ord('a') + (result - ord('z')) - 1)
else:
return chr(result)
print(rotate('sarah', 13))
print(rotate('fnenu', 13))
print(rotate('dave', 5))
print(rotate('ifaj', -5))
print(rotate('zw pfli tfuv nfibj tfiivtkcp pfl jyflcu sv rscv kf ivru kyzj', -17)) |
# eisagwgh stoixeiwn
my_list = []
# insert the first element
my_list.append(2)
print("This is the new list: ", my_list)
# insert the second element
my_list.append(3)
print("This is the new list: ", my_list)
my_list.append("Names")
print("This is a mixed list, with integers and strings: ", my_list)
# Afairwntas ena stoixeio
# removing the second element, which is 3
my_list.remove(3)
print("this is the list after removing \'3\': ", my_list)
# removing the first element of the list
my_list.remove(my_list[0])
print("This is the list after removing my_list[0]: ", my_list)
| my_list = []
my_list.append(2)
print('This is the new list: ', my_list)
my_list.append(3)
print('This is the new list: ', my_list)
my_list.append('Names')
print('This is a mixed list, with integers and strings: ', my_list)
my_list.remove(3)
print("this is the list after removing '3': ", my_list)
my_list.remove(my_list[0])
print('This is the list after removing my_list[0]: ', my_list) |
def save():
"""
For now this function is a placeholder for the eventual function
which will save the state of the FHD program at certain points depending
on community feedback.
"""
print("If you're seeing this, then fhd_save_io hasn't been made yet.")
print("If you have ideas on how we should save the state of FHD throughout its runtime.")
print("Please raise an issue on the repository")
def restore():
"""
For now this function is a placeholder for the eventual function
which will restore the state of the FHD program at certain points depending
on community feedback.
"""
print("If you're seeing this the restore function hasn't been created yet") | def save():
"""
For now this function is a placeholder for the eventual function
which will save the state of the FHD program at certain points depending
on community feedback.
"""
print("If you're seeing this, then fhd_save_io hasn't been made yet.")
print('If you have ideas on how we should save the state of FHD throughout its runtime.')
print('Please raise an issue on the repository')
def restore():
"""
For now this function is a placeholder for the eventual function
which will restore the state of the FHD program at certain points depending
on community feedback.
"""
print("If you're seeing this the restore function hasn't been created yet") |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# parameters.py
# search query
search_query = 'site:linkedin.com/in/ AND "guide touristique" AND "paris"'
# file were scraped profile information will be stored
file_name = 'candidates.csv'
# login credentials
linkedin_username = 'YOUR EMAIL GOES HERE'
linkedin_password = 'YOUR PASSWORD GOES HERE'
| search_query = 'site:linkedin.com/in/ AND "guide touristique" AND "paris"'
file_name = 'candidates.csv'
linkedin_username = 'YOUR EMAIL GOES HERE'
linkedin_password = 'YOUR PASSWORD GOES HERE' |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.