ngram
listlengths 0
67.8k
|
|---|
[
"record: return record['_id'] else: self.repair() raise KeyError() def complete(self, url): self.db.crawl_queue.update({'_id': url}, {'$set':",
"import datetime, timedelta from pymongo import MongoClient, errors class MongoQueue: # possible states",
"self.COMPLETE}}) def repair(self): \"\"\"Release stalled jobs \"\"\" record = self.db.crawl_queue.find_and_modify( query={'timestamp': {'$lt': datetime.now()",
"PROCESSING, COMPLETE = range(3) def __init__(self, client=None, timeout=300): self.client = MongoClient() if client",
"\"\"\" record = self.db.crawl_queue.find_and_modify(query={'status': self.OUTSTANDING}, update={'$set': {'status': self.PROCESSING, 'timestamp': datetime.now()}}) if record: return",
"complete(self, url): self.db.crawl_queue.update({'_id': url}, {'$set': {'status': self.COMPLETE}}) def repair(self): \"\"\"Release stalled jobs \"\"\"",
"'status': self.OUTSTANDING}) except errors.DuplicateKeyError as e: pass # this is already in the",
"stalled jobs \"\"\" record = self.db.crawl_queue.find_and_modify( query={'timestamp': {'$lt': datetime.now() - timedelta(seconds=self.timeout)}, 'status': {'$ne':",
"{'$ne': self.COMPLETE}}) return True if record else False def push(self, url): \"\"\"Add new",
"a KeyError exception is raised. \"\"\" record = self.db.crawl_queue.find_and_modify(query={'status': self.OUTSTANDING}, update={'$set': {'status': self.PROCESSING,",
"pass # this is already in the queue def pop(self): \"\"\"Get an outstanding",
"else: self.repair() raise KeyError() def complete(self, url): self.db.crawl_queue.update({'_id': url}, {'$set': {'status': self.COMPLETE}}) def",
"True if record else False def push(self, url): \"\"\"Add new URL to queue",
"queue and set its status to processing. If the queue is empty a",
"raised. \"\"\" record = self.db.crawl_queue.find_and_modify(query={'status': self.OUTSTANDING}, update={'$set': {'status': self.PROCESSING, 'timestamp': datetime.now()}}) if record:",
"outstanding URL from the queue and set its status to processing. If the",
"is raised. \"\"\" record = self.db.crawl_queue.find_and_modify(query={'status': self.OUTSTANDING}, update={'$set': {'status': self.PROCESSING, 'timestamp': datetime.now()}}) if",
"e: pass # this is already in the queue def pop(self): \"\"\"Get an",
"def __init__(self, client=None, timeout=300): self.client = MongoClient() if client is None else client",
"URL to queue if does not exist \"\"\" try: self.db.crawl_queue.insert({'_id': url, 'status': self.OUTSTANDING})",
"= self.client.cache self.timeout = timeout def __bool__(self): \"\"\"Returns True if there are more",
"self.db.crawl_queue.find_one({'status': {'$ne': self.COMPLETE}}) return True if record else False def push(self, url): \"\"\"Add",
"self.timeout = timeout def __bool__(self): \"\"\"Returns True if there are more jobs to",
"timeout=300): self.client = MongoClient() if client is None else client self.db = self.client.cache",
"the queue is empty a KeyError exception is raised. \"\"\" record = self.db.crawl_queue.find_and_modify(query={'status':",
"url): self.db.crawl_queue.update({'_id': url}, {'$set': {'status': self.COMPLETE}}) def repair(self): \"\"\"Release stalled jobs \"\"\" record",
"jobs to process \"\"\" record = self.db.crawl_queue.find_one({'status': {'$ne': self.COMPLETE}}) return True if record",
"timedelta from pymongo import MongoClient, errors class MongoQueue: # possible states of a",
"to processing. If the queue is empty a KeyError exception is raised. \"\"\"",
"empty a KeyError exception is raised. \"\"\" record = self.db.crawl_queue.find_and_modify(query={'status': self.OUTSTANDING}, update={'$set': {'status':",
"datetime.now()}}) if record: return record['_id'] else: self.repair() raise KeyError() def complete(self, url): self.db.crawl_queue.update({'_id':",
"try: self.db.crawl_queue.insert({'_id': url, 'status': self.OUTSTANDING}) except errors.DuplicateKeyError as e: pass # this is",
"self.db.crawl_queue.find_and_modify(query={'status': self.OUTSTANDING}, update={'$set': {'status': self.PROCESSING, 'timestamp': datetime.now()}}) if record: return record['_id'] else: self.repair()",
"an outstanding URL from the queue and set its status to processing. If",
"repair(self): \"\"\"Release stalled jobs \"\"\" record = self.db.crawl_queue.find_and_modify( query={'timestamp': {'$lt': datetime.now() - timedelta(seconds=self.timeout)},",
"are more jobs to process \"\"\" record = self.db.crawl_queue.find_one({'status': {'$ne': self.COMPLETE}}) return True",
"exist \"\"\" try: self.db.crawl_queue.insert({'_id': url, 'status': self.OUTSTANDING}) except errors.DuplicateKeyError as e: pass #",
"client self.db = self.client.cache self.timeout = timeout def __bool__(self): \"\"\"Returns True if there",
"does not exist \"\"\" try: self.db.crawl_queue.insert({'_id': url, 'status': self.OUTSTANDING}) except errors.DuplicateKeyError as e:",
"else False def push(self, url): \"\"\"Add new URL to queue if does not",
"status to processing. If the queue is empty a KeyError exception is raised.",
"{'status': self.COMPLETE}}) def repair(self): \"\"\"Release stalled jobs \"\"\" record = self.db.crawl_queue.find_and_modify( query={'timestamp': {'$lt':",
"range(3) def __init__(self, client=None, timeout=300): self.client = MongoClient() if client is None else",
"the queue def pop(self): \"\"\"Get an outstanding URL from the queue and set",
"datetime import datetime, timedelta from pymongo import MongoClient, errors class MongoQueue: # possible",
"= self.db.crawl_queue.find_and_modify(query={'status': self.OUTSTANDING}, update={'$set': {'status': self.PROCESSING, 'timestamp': datetime.now()}}) if record: return record['_id'] else:",
"# possible states of a download OUTSTANDING, PROCESSING, COMPLETE = range(3) def __init__(self,",
"possible states of a download OUTSTANDING, PROCESSING, COMPLETE = range(3) def __init__(self, client=None,",
"if client is None else client self.db = self.client.cache self.timeout = timeout def",
"already in the queue def pop(self): \"\"\"Get an outstanding URL from the queue",
"from pymongo import MongoClient, errors class MongoQueue: # possible states of a download",
"def pop(self): \"\"\"Get an outstanding URL from the queue and set its status",
"False def push(self, url): \"\"\"Add new URL to queue if does not exist",
"and set its status to processing. If the queue is empty a KeyError",
"datetime, timedelta from pymongo import MongoClient, errors class MongoQueue: # possible states of",
"self.client = MongoClient() if client is None else client self.db = self.client.cache self.timeout",
"timeout def __bool__(self): \"\"\"Returns True if there are more jobs to process \"\"\"",
"= self.db.crawl_queue.find_one({'status': {'$ne': self.COMPLETE}}) return True if record else False def push(self, url):",
"url): \"\"\"Add new URL to queue if does not exist \"\"\" try: self.db.crawl_queue.insert({'_id':",
"self.repair() raise KeyError() def complete(self, url): self.db.crawl_queue.update({'_id': url}, {'$set': {'status': self.COMPLETE}}) def repair(self):",
"= self.db.crawl_queue.find_and_modify( query={'timestamp': {'$lt': datetime.now() - timedelta(seconds=self.timeout)}, 'status': {'$ne': self.COMPLETE}}, update={'$set': {'status': self.OUTSTANDING}})",
"client=None, timeout=300): self.client = MongoClient() if client is None else client self.db =",
"to process \"\"\" record = self.db.crawl_queue.find_one({'status': {'$ne': self.COMPLETE}}) return True if record else",
"new URL to queue if does not exist \"\"\" try: self.db.crawl_queue.insert({'_id': url, 'status':",
"queue is empty a KeyError exception is raised. \"\"\" record = self.db.crawl_queue.find_and_modify(query={'status': self.OUTSTANDING},",
"its status to processing. If the queue is empty a KeyError exception is",
"import MongoClient, errors class MongoQueue: # possible states of a download OUTSTANDING, PROCESSING,",
"record = self.db.crawl_queue.find_and_modify(query={'status': self.OUTSTANDING}, update={'$set': {'status': self.PROCESSING, 'timestamp': datetime.now()}}) if record: return record['_id']",
"errors.DuplicateKeyError as e: pass # this is already in the queue def pop(self):",
"url, 'status': self.OUTSTANDING}) except errors.DuplicateKeyError as e: pass # this is already in",
"MongoQueue: # possible states of a download OUTSTANDING, PROCESSING, COMPLETE = range(3) def",
"a download OUTSTANDING, PROCESSING, COMPLETE = range(3) def __init__(self, client=None, timeout=300): self.client =",
"jobs \"\"\" record = self.db.crawl_queue.find_and_modify( query={'timestamp': {'$lt': datetime.now() - timedelta(seconds=self.timeout)}, 'status': {'$ne': self.COMPLETE}},",
"True if there are more jobs to process \"\"\" record = self.db.crawl_queue.find_one({'status': {'$ne':",
"\"\"\"Add new URL to queue if does not exist \"\"\" try: self.db.crawl_queue.insert({'_id': url,",
"MongoClient() if client is None else client self.db = self.client.cache self.timeout = timeout",
"return True if record else False def push(self, url): \"\"\"Add new URL to",
"MongoClient, errors class MongoQueue: # possible states of a download OUTSTANDING, PROCESSING, COMPLETE",
"url}, {'$set': {'status': self.COMPLETE}}) def repair(self): \"\"\"Release stalled jobs \"\"\" record = self.db.crawl_queue.find_and_modify(",
"self.OUTSTANDING}) except errors.DuplicateKeyError as e: pass # this is already in the queue",
"'timestamp': datetime.now()}}) if record: return record['_id'] else: self.repair() raise KeyError() def complete(self, url):",
"datetime.now() - timedelta(seconds=self.timeout)}, 'status': {'$ne': self.COMPLETE}}, update={'$set': {'status': self.OUTSTANDING}}) if record: print('Released:', record['_id'])",
"\"\"\"Release stalled jobs \"\"\" record = self.db.crawl_queue.find_and_modify( query={'timestamp': {'$lt': datetime.now() - timedelta(seconds=self.timeout)}, 'status':",
"in the queue def pop(self): \"\"\"Get an outstanding URL from the queue and",
"download OUTSTANDING, PROCESSING, COMPLETE = range(3) def __init__(self, client=None, timeout=300): self.client = MongoClient()",
"{'$set': {'status': self.COMPLETE}}) def repair(self): \"\"\"Release stalled jobs \"\"\" record = self.db.crawl_queue.find_and_modify( query={'timestamp':",
"client is None else client self.db = self.client.cache self.timeout = timeout def __bool__(self):",
"return record['_id'] else: self.repair() raise KeyError() def complete(self, url): self.db.crawl_queue.update({'_id': url}, {'$set': {'status':",
"{'$lt': datetime.now() - timedelta(seconds=self.timeout)}, 'status': {'$ne': self.COMPLETE}}, update={'$set': {'status': self.OUTSTANDING}}) if record: print('Released:',",
"raise KeyError() def complete(self, url): self.db.crawl_queue.update({'_id': url}, {'$set': {'status': self.COMPLETE}}) def repair(self): \"\"\"Release",
"processing. If the queue is empty a KeyError exception is raised. \"\"\" record",
"queue def pop(self): \"\"\"Get an outstanding URL from the queue and set its",
"set its status to processing. If the queue is empty a KeyError exception",
"{'status': self.PROCESSING, 'timestamp': datetime.now()}}) if record: return record['_id'] else: self.repair() raise KeyError() def",
"record else False def push(self, url): \"\"\"Add new URL to queue if does",
"more jobs to process \"\"\" record = self.db.crawl_queue.find_one({'status': {'$ne': self.COMPLETE}}) return True if",
"if does not exist \"\"\" try: self.db.crawl_queue.insert({'_id': url, 'status': self.OUTSTANDING}) except errors.DuplicateKeyError as",
"except errors.DuplicateKeyError as e: pass # this is already in the queue def",
"\"\"\" record = self.db.crawl_queue.find_and_modify( query={'timestamp': {'$lt': datetime.now() - timedelta(seconds=self.timeout)}, 'status': {'$ne': self.COMPLETE}}, update={'$set':",
"from datetime import datetime, timedelta from pymongo import MongoClient, errors class MongoQueue: #",
"there are more jobs to process \"\"\" record = self.db.crawl_queue.find_one({'status': {'$ne': self.COMPLETE}}) return",
"not exist \"\"\" try: self.db.crawl_queue.insert({'_id': url, 'status': self.OUTSTANDING}) except errors.DuplicateKeyError as e: pass",
"# this is already in the queue def pop(self): \"\"\"Get an outstanding URL",
"is empty a KeyError exception is raised. \"\"\" record = self.db.crawl_queue.find_and_modify(query={'status': self.OUTSTANDING}, update={'$set':",
"self.OUTSTANDING}, update={'$set': {'status': self.PROCESSING, 'timestamp': datetime.now()}}) if record: return record['_id'] else: self.repair() raise",
"record = self.db.crawl_queue.find_and_modify( query={'timestamp': {'$lt': datetime.now() - timedelta(seconds=self.timeout)}, 'status': {'$ne': self.COMPLETE}}, update={'$set': {'status':",
"def push(self, url): \"\"\"Add new URL to queue if does not exist \"\"\"",
"self.COMPLETE}}) return True if record else False def push(self, url): \"\"\"Add new URL",
"from the queue and set its status to processing. If the queue is",
"OUTSTANDING, PROCESSING, COMPLETE = range(3) def __init__(self, client=None, timeout=300): self.client = MongoClient() if",
"\"\"\" record = self.db.crawl_queue.find_one({'status': {'$ne': self.COMPLETE}}) return True if record else False def",
"KeyError exception is raised. \"\"\" record = self.db.crawl_queue.find_and_modify(query={'status': self.OUTSTANDING}, update={'$set': {'status': self.PROCESSING, 'timestamp':",
"update={'$set': {'status': self.PROCESSING, 'timestamp': datetime.now()}}) if record: return record['_id'] else: self.repair() raise KeyError()",
"push(self, url): \"\"\"Add new URL to queue if does not exist \"\"\" try:",
"is already in the queue def pop(self): \"\"\"Get an outstanding URL from the",
"__init__(self, client=None, timeout=300): self.client = MongoClient() if client is None else client self.db",
"class MongoQueue: # possible states of a download OUTSTANDING, PROCESSING, COMPLETE = range(3)",
"of a download OUTSTANDING, PROCESSING, COMPLETE = range(3) def __init__(self, client=None, timeout=300): self.client",
"self.db.crawl_queue.update({'_id': url}, {'$set': {'status': self.COMPLETE}}) def repair(self): \"\"\"Release stalled jobs \"\"\" record =",
"queue if does not exist \"\"\" try: self.db.crawl_queue.insert({'_id': url, 'status': self.OUTSTANDING}) except errors.DuplicateKeyError",
"self.db.crawl_queue.find_and_modify( query={'timestamp': {'$lt': datetime.now() - timedelta(seconds=self.timeout)}, 'status': {'$ne': self.COMPLETE}}, update={'$set': {'status': self.OUTSTANDING}}) if",
"self.db.crawl_queue.insert({'_id': url, 'status': self.OUTSTANDING}) except errors.DuplicateKeyError as e: pass # this is already",
"\"\"\"Get an outstanding URL from the queue and set its status to processing.",
"self.db = self.client.cache self.timeout = timeout def __bool__(self): \"\"\"Returns True if there are",
"self.client.cache self.timeout = timeout def __bool__(self): \"\"\"Returns True if there are more jobs",
"COMPLETE = range(3) def __init__(self, client=None, timeout=300): self.client = MongoClient() if client is",
"KeyError() def complete(self, url): self.db.crawl_queue.update({'_id': url}, {'$set': {'status': self.COMPLETE}}) def repair(self): \"\"\"Release stalled",
"self.PROCESSING, 'timestamp': datetime.now()}}) if record: return record['_id'] else: self.repair() raise KeyError() def complete(self,",
"if there are more jobs to process \"\"\" record = self.db.crawl_queue.find_one({'status': {'$ne': self.COMPLETE}})",
"pop(self): \"\"\"Get an outstanding URL from the queue and set its status to",
"__bool__(self): \"\"\"Returns True if there are more jobs to process \"\"\" record =",
"record['_id'] else: self.repair() raise KeyError() def complete(self, url): self.db.crawl_queue.update({'_id': url}, {'$set': {'status': self.COMPLETE}})",
"= timeout def __bool__(self): \"\"\"Returns True if there are more jobs to process",
"If the queue is empty a KeyError exception is raised. \"\"\" record =",
"exception is raised. \"\"\" record = self.db.crawl_queue.find_and_modify(query={'status': self.OUTSTANDING}, update={'$set': {'status': self.PROCESSING, 'timestamp': datetime.now()}})",
"\"\"\"Returns True if there are more jobs to process \"\"\" record = self.db.crawl_queue.find_one({'status':",
"= range(3) def __init__(self, client=None, timeout=300): self.client = MongoClient() if client is None",
"is None else client self.db = self.client.cache self.timeout = timeout def __bool__(self): \"\"\"Returns",
"None else client self.db = self.client.cache self.timeout = timeout def __bool__(self): \"\"\"Returns True",
"the queue and set its status to processing. If the queue is empty",
"to queue if does not exist \"\"\" try: self.db.crawl_queue.insert({'_id': url, 'status': self.OUTSTANDING}) except",
"process \"\"\" record = self.db.crawl_queue.find_one({'status': {'$ne': self.COMPLETE}}) return True if record else False",
"else client self.db = self.client.cache self.timeout = timeout def __bool__(self): \"\"\"Returns True if",
"def repair(self): \"\"\"Release stalled jobs \"\"\" record = self.db.crawl_queue.find_and_modify( query={'timestamp': {'$lt': datetime.now() -",
"<reponame>godontop/python<gh_stars>0 from datetime import datetime, timedelta from pymongo import MongoClient, errors class MongoQueue:",
"errors class MongoQueue: # possible states of a download OUTSTANDING, PROCESSING, COMPLETE =",
"record = self.db.crawl_queue.find_one({'status': {'$ne': self.COMPLETE}}) return True if record else False def push(self,",
"def complete(self, url): self.db.crawl_queue.update({'_id': url}, {'$set': {'status': self.COMPLETE}}) def repair(self): \"\"\"Release stalled jobs",
"\"\"\" try: self.db.crawl_queue.insert({'_id': url, 'status': self.OUTSTANDING}) except errors.DuplicateKeyError as e: pass # this",
"= MongoClient() if client is None else client self.db = self.client.cache self.timeout =",
"states of a download OUTSTANDING, PROCESSING, COMPLETE = range(3) def __init__(self, client=None, timeout=300):",
"def __bool__(self): \"\"\"Returns True if there are more jobs to process \"\"\" record",
"if record else False def push(self, url): \"\"\"Add new URL to queue if",
"if record: return record['_id'] else: self.repair() raise KeyError() def complete(self, url): self.db.crawl_queue.update({'_id': url},",
"URL from the queue and set its status to processing. If the queue",
"pymongo import MongoClient, errors class MongoQueue: # possible states of a download OUTSTANDING,",
"query={'timestamp': {'$lt': datetime.now() - timedelta(seconds=self.timeout)}, 'status': {'$ne': self.COMPLETE}}, update={'$set': {'status': self.OUTSTANDING}}) if record:",
"as e: pass # this is already in the queue def pop(self): \"\"\"Get",
"this is already in the queue def pop(self): \"\"\"Get an outstanding URL from"
] |
[
"\"\"\" from typing import Any from sims4communitylib.modinfo import ModInfo from sims4communitylib.testing.common_assertion_utils import CommonAssertionUtils",
"COLONOLNUTTY \"\"\" from typing import Any from sims4communitylib.modinfo import ModInfo from sims4communitylib.testing.common_assertion_utils import",
"_additional_value and key_value == _additional_key_word_value: return True result = CommonFunctionUtils.run_with_arguments(_function, _additional_value, key_value=_additional_key_word_value)(normal_val, normal_key_arg=normal_key_val)",
"from sims4communitylib.utils.common_function_utils import CommonFunctionUtils # noinspection PyMissingOrEmptyDocstring @CommonTestService.test_class(ModInfo.get_identity()) class CommonFunctionUtilsTests: @staticmethod @CommonTestService.test(True, True,",
"True, True, True) @CommonTestService.test(True, False, True, False) @CommonTestService.test(True, False, False, True) @CommonTestService.test(False, False,",
"def run_with_arguments_should_work_properly() -> None: _additional_value = 'No' _additional_key_word_value = 'What' normal_val = 'one'",
"func_result_two: bool, all_must_pass: bool, expected_result: bool): def _function_one(*_, **__) -> Any: return func_result_one",
"\"\"\" The Sims 4 Community Library is licensed under the Creative Commons Attribution",
"@CommonTestService.test_class(ModInfo.get_identity()) class CommonFunctionUtilsTests: @staticmethod @CommonTestService.test(True, True, True, True) @CommonTestService.test(True, False, True, False) @CommonTestService.test(True,",
"CommonAssertionUtils.are_equal(result, expected_result) @staticmethod @CommonTestService.test(True, False) @CommonTestService.test(False, True) def run_predicate_with_reversed_result_should_work_properly(func_result: bool, expected_result: bool): def",
"and key_value == _additional_key_word_value: return True result = CommonFunctionUtils.run_with_arguments(_function, _additional_value, key_value=_additional_key_word_value)(normal_val, normal_key_arg=normal_key_val) CommonAssertionUtils.is_true(result,",
"= CommonFunctionUtils.run_predicates_as_one((_function_one, _function_two), all_must_pass=all_must_pass)() CommonAssertionUtils.are_equal(result, expected_result) @staticmethod @CommonTestService.test(True, False) @CommonTestService.test(False, True) def run_predicate_with_reversed_result_should_work_properly(func_result:",
"CommonAssertionUtils.are_equal(result, expected_result) @staticmethod @CommonTestService.test() def run_with_arguments_should_work_properly() -> None: _additional_value = 'No' _additional_key_word_value =",
"Any: return func_result result = CommonFunctionUtils.run_predicate_with_reversed_result(_function)() CommonAssertionUtils.are_equal(result, expected_result) @staticmethod @CommonTestService.test() def run_with_arguments_should_work_properly() ->",
"normal_val and normal_key_arg == normal_key_val and value_one == _additional_value and key_value == _additional_key_word_value:",
"(CC BY 4.0). https://creativecommons.org/licenses/by/4.0/ https://creativecommons.org/licenses/by/4.0/legalcode Copyright (c) COLONOLNUTTY \"\"\" from typing import Any",
"expected_result: bool): def _function_one(*_, **__) -> Any: return func_result_one def _function_two(*_, **__) ->",
"from sims4communitylib.modinfo import ModInfo from sims4communitylib.testing.common_assertion_utils import CommonAssertionUtils from sims4communitylib.testing.common_test_service import CommonTestService from",
"from sims4communitylib.testing.common_test_service import CommonTestService from sims4communitylib.utils.common_function_utils import CommonFunctionUtils # noinspection PyMissingOrEmptyDocstring @CommonTestService.test_class(ModInfo.get_identity()) class",
"public license (CC BY 4.0). https://creativecommons.org/licenses/by/4.0/ https://creativecommons.org/licenses/by/4.0/legalcode Copyright (c) COLONOLNUTTY \"\"\" from typing",
"False, False, True) @CommonTestService.test(False, False, False, False) def run_predicates_as_one_should_work_properly(func_result_one: bool, func_result_two: bool, all_must_pass:",
"https://creativecommons.org/licenses/by/4.0/ https://creativecommons.org/licenses/by/4.0/legalcode Copyright (c) COLONOLNUTTY \"\"\" from typing import Any from sims4communitylib.modinfo import",
"normal_val = 'one' normal_key_val = 'two' def _function(normal_arg: str, value_one: str, normal_key_arg: str=None,",
"from sims4communitylib.testing.common_assertion_utils import CommonAssertionUtils from sims4communitylib.testing.common_test_service import CommonTestService from sims4communitylib.utils.common_function_utils import CommonFunctionUtils #",
"= CommonFunctionUtils.run_predicate_with_reversed_result(_function)() CommonAssertionUtils.are_equal(result, expected_result) @staticmethod @CommonTestService.test() def run_with_arguments_should_work_properly() -> None: _additional_value = 'No'",
"@CommonTestService.test() def run_with_arguments_should_work_properly() -> None: _additional_value = 'No' _additional_key_word_value = 'What' normal_val =",
"Copyright (c) COLONOLNUTTY \"\"\" from typing import Any from sims4communitylib.modinfo import ModInfo from",
"func_result_one def _function_two(*_, **__) -> Any: return func_result_two result = CommonFunctionUtils.run_predicates_as_one((_function_one, _function_two), all_must_pass=all_must_pass)()",
"run_predicate_with_reversed_result_should_work_properly(func_result: bool, expected_result: bool): def _function(*_, **__) -> Any: return func_result result =",
"'No' _additional_key_word_value = 'What' normal_val = 'one' normal_key_val = 'two' def _function(normal_arg: str,",
"sims4communitylib.testing.common_test_service import CommonTestService from sims4communitylib.utils.common_function_utils import CommonFunctionUtils # noinspection PyMissingOrEmptyDocstring @CommonTestService.test_class(ModInfo.get_identity()) class CommonFunctionUtilsTests:",
"Creative Commons Attribution 4.0 International public license (CC BY 4.0). https://creativecommons.org/licenses/by/4.0/ https://creativecommons.org/licenses/by/4.0/legalcode Copyright",
"@CommonTestService.test(True, False) @CommonTestService.test(False, True) def run_predicate_with_reversed_result_should_work_properly(func_result: bool, expected_result: bool): def _function(*_, **__) ->",
"@CommonTestService.test(True, False, True, False) @CommonTestService.test(True, False, False, True) @CommonTestService.test(False, False, False, False) def",
"value_one: str, normal_key_arg: str=None, key_value: str=None) -> Any: CommonAssertionUtils.are_equal(value_one, _additional_value) CommonAssertionUtils.are_equal(key_value, _additional_key_word_value) CommonAssertionUtils.are_equal(normal_arg,",
"and normal_key_arg == normal_key_val and value_one == _additional_value and key_value == _additional_key_word_value: return",
"== normal_val and normal_key_arg == normal_key_val and value_one == _additional_value and key_value ==",
"False) @CommonTestService.test(False, True) def run_predicate_with_reversed_result_should_work_properly(func_result: bool, expected_result: bool): def _function(*_, **__) -> Any:",
"4 Community Library is licensed under the Creative Commons Attribution 4.0 International public",
"bool): def _function(*_, **__) -> Any: return func_result result = CommonFunctionUtils.run_predicate_with_reversed_result(_function)() CommonAssertionUtils.are_equal(result, expected_result)",
"'two' def _function(normal_arg: str, value_one: str, normal_key_arg: str=None, key_value: str=None) -> Any: CommonAssertionUtils.are_equal(value_one,",
"normal_arg == normal_val and normal_key_arg == normal_key_val and value_one == _additional_value and key_value",
"True) @CommonTestService.test(False, False, False, False) def run_predicates_as_one_should_work_properly(func_result_one: bool, func_result_two: bool, all_must_pass: bool, expected_result:",
"https://creativecommons.org/licenses/by/4.0/legalcode Copyright (c) COLONOLNUTTY \"\"\" from typing import Any from sims4communitylib.modinfo import ModInfo",
"return func_result_two result = CommonFunctionUtils.run_predicates_as_one((_function_one, _function_two), all_must_pass=all_must_pass)() CommonAssertionUtils.are_equal(result, expected_result) @staticmethod @CommonTestService.test(True, False) @CommonTestService.test(False,",
"value_one == _additional_value and key_value == _additional_key_word_value: return True result = CommonFunctionUtils.run_with_arguments(_function, _additional_value,",
"_function(*_, **__) -> Any: return func_result result = CommonFunctionUtils.run_predicate_with_reversed_result(_function)() CommonAssertionUtils.are_equal(result, expected_result) @staticmethod @CommonTestService.test()",
"(c) COLONOLNUTTY \"\"\" from typing import Any from sims4communitylib.modinfo import ModInfo from sims4communitylib.testing.common_assertion_utils",
"return func_result result = CommonFunctionUtils.run_predicate_with_reversed_result(_function)() CommonAssertionUtils.are_equal(result, expected_result) @staticmethod @CommonTestService.test() def run_with_arguments_should_work_properly() -> None:",
"key_value == _additional_key_word_value: return True result = CommonFunctionUtils.run_with_arguments(_function, _additional_value, key_value=_additional_key_word_value)(normal_val, normal_key_arg=normal_key_val) CommonAssertionUtils.is_true(result, message='Failed",
"expected_result) @staticmethod @CommonTestService.test() def run_with_arguments_should_work_properly() -> None: _additional_value = 'No' _additional_key_word_value = 'What'",
"-> None: _additional_value = 'No' _additional_key_word_value = 'What' normal_val = 'one' normal_key_val =",
"# noinspection PyMissingOrEmptyDocstring @CommonTestService.test_class(ModInfo.get_identity()) class CommonFunctionUtilsTests: @staticmethod @CommonTestService.test(True, True, True, True) @CommonTestService.test(True, False,",
"Commons Attribution 4.0 International public license (CC BY 4.0). https://creativecommons.org/licenses/by/4.0/ https://creativecommons.org/licenses/by/4.0/legalcode Copyright (c)",
"sims4communitylib.modinfo import ModInfo from sims4communitylib.testing.common_assertion_utils import CommonAssertionUtils from sims4communitylib.testing.common_test_service import CommonTestService from sims4communitylib.utils.common_function_utils",
"Attribution 4.0 International public license (CC BY 4.0). https://creativecommons.org/licenses/by/4.0/ https://creativecommons.org/licenses/by/4.0/legalcode Copyright (c) COLONOLNUTTY",
"def _function_two(*_, **__) -> Any: return func_result_two result = CommonFunctionUtils.run_predicates_as_one((_function_one, _function_two), all_must_pass=all_must_pass)() CommonAssertionUtils.are_equal(result,",
"import CommonAssertionUtils from sims4communitylib.testing.common_test_service import CommonTestService from sims4communitylib.utils.common_function_utils import CommonFunctionUtils # noinspection PyMissingOrEmptyDocstring",
"None: _additional_value = 'No' _additional_key_word_value = 'What' normal_val = 'one' normal_key_val = 'two'",
"4.0). https://creativecommons.org/licenses/by/4.0/ https://creativecommons.org/licenses/by/4.0/legalcode Copyright (c) COLONOLNUTTY \"\"\" from typing import Any from sims4communitylib.modinfo",
"str=None) -> Any: CommonAssertionUtils.are_equal(value_one, _additional_value) CommonAssertionUtils.are_equal(key_value, _additional_key_word_value) CommonAssertionUtils.are_equal(normal_arg, normal_val) CommonAssertionUtils.are_equal(normal_key_arg, normal_key_val) if normal_arg",
"CommonAssertionUtils.are_equal(normal_arg, normal_val) CommonAssertionUtils.are_equal(normal_key_arg, normal_key_val) if normal_arg == normal_val and normal_key_arg == normal_key_val and",
"result = CommonFunctionUtils.run_with_arguments(_function, _additional_value, key_value=_additional_key_word_value)(normal_val, normal_key_arg=normal_key_val) CommonAssertionUtils.is_true(result, message='Failed to send proper arguments: {}'.format(result))",
"= 'two' def _function(normal_arg: str, value_one: str, normal_key_arg: str=None, key_value: str=None) -> Any:",
"sims4communitylib.utils.common_function_utils import CommonFunctionUtils # noinspection PyMissingOrEmptyDocstring @CommonTestService.test_class(ModInfo.get_identity()) class CommonFunctionUtilsTests: @staticmethod @CommonTestService.test(True, True, True,",
"import CommonFunctionUtils # noinspection PyMissingOrEmptyDocstring @CommonTestService.test_class(ModInfo.get_identity()) class CommonFunctionUtilsTests: @staticmethod @CommonTestService.test(True, True, True, True)",
"Library is licensed under the Creative Commons Attribution 4.0 International public license (CC",
"import Any from sims4communitylib.modinfo import ModInfo from sims4communitylib.testing.common_assertion_utils import CommonAssertionUtils from sims4communitylib.testing.common_test_service import",
"class CommonFunctionUtilsTests: @staticmethod @CommonTestService.test(True, True, True, True) @CommonTestService.test(True, False, True, False) @CommonTestService.test(True, False,",
"CommonFunctionUtils.run_predicates_as_one((_function_one, _function_two), all_must_pass=all_must_pass)() CommonAssertionUtils.are_equal(result, expected_result) @staticmethod @CommonTestService.test(True, False) @CommonTestService.test(False, True) def run_predicate_with_reversed_result_should_work_properly(func_result: bool,",
"all_must_pass: bool, expected_result: bool): def _function_one(*_, **__) -> Any: return func_result_one def _function_two(*_,",
"normal_key_arg: str=None, key_value: str=None) -> Any: CommonAssertionUtils.are_equal(value_one, _additional_value) CommonAssertionUtils.are_equal(key_value, _additional_key_word_value) CommonAssertionUtils.are_equal(normal_arg, normal_val) CommonAssertionUtils.are_equal(normal_key_arg,",
"run_predicates_as_one_should_work_properly(func_result_one: bool, func_result_two: bool, all_must_pass: bool, expected_result: bool): def _function_one(*_, **__) -> Any:",
"func_result_two result = CommonFunctionUtils.run_predicates_as_one((_function_one, _function_two), all_must_pass=all_must_pass)() CommonAssertionUtils.are_equal(result, expected_result) @staticmethod @CommonTestService.test(True, False) @CommonTestService.test(False, True)",
"**__) -> Any: return func_result result = CommonFunctionUtils.run_predicate_with_reversed_result(_function)() CommonAssertionUtils.are_equal(result, expected_result) @staticmethod @CommonTestService.test() def",
"str, value_one: str, normal_key_arg: str=None, key_value: str=None) -> Any: CommonAssertionUtils.are_equal(value_one, _additional_value) CommonAssertionUtils.are_equal(key_value, _additional_key_word_value)",
"all_must_pass=all_must_pass)() CommonAssertionUtils.are_equal(result, expected_result) @staticmethod @CommonTestService.test(True, False) @CommonTestService.test(False, True) def run_predicate_with_reversed_result_should_work_properly(func_result: bool, expected_result: bool):",
"CommonFunctionUtils # noinspection PyMissingOrEmptyDocstring @CommonTestService.test_class(ModInfo.get_identity()) class CommonFunctionUtilsTests: @staticmethod @CommonTestService.test(True, True, True, True) @CommonTestService.test(True,",
"True, False) @CommonTestService.test(True, False, False, True) @CommonTestService.test(False, False, False, False) def run_predicates_as_one_should_work_properly(func_result_one: bool,",
"str=None, key_value: str=None) -> Any: CommonAssertionUtils.are_equal(value_one, _additional_value) CommonAssertionUtils.are_equal(key_value, _additional_key_word_value) CommonAssertionUtils.are_equal(normal_arg, normal_val) CommonAssertionUtils.are_equal(normal_key_arg, normal_key_val)",
"-> Any: return func_result result = CommonFunctionUtils.run_predicate_with_reversed_result(_function)() CommonAssertionUtils.are_equal(result, expected_result) @staticmethod @CommonTestService.test() def run_with_arguments_should_work_properly()",
"bool, expected_result: bool): def _function(*_, **__) -> Any: return func_result result = CommonFunctionUtils.run_predicate_with_reversed_result(_function)()",
"CommonAssertionUtils.are_equal(normal_key_arg, normal_key_val) if normal_arg == normal_val and normal_key_arg == normal_key_val and value_one ==",
"== _additional_value and key_value == _additional_key_word_value: return True result = CommonFunctionUtils.run_with_arguments(_function, _additional_value, key_value=_additional_key_word_value)(normal_val,",
"@staticmethod @CommonTestService.test(True, True, True, True) @CommonTestService.test(True, False, True, False) @CommonTestService.test(True, False, False, True)",
"import ModInfo from sims4communitylib.testing.common_assertion_utils import CommonAssertionUtils from sims4communitylib.testing.common_test_service import CommonTestService from sims4communitylib.utils.common_function_utils import",
"result = CommonFunctionUtils.run_predicates_as_one((_function_one, _function_two), all_must_pass=all_must_pass)() CommonAssertionUtils.are_equal(result, expected_result) @staticmethod @CommonTestService.test(True, False) @CommonTestService.test(False, True) def",
"The Sims 4 Community Library is licensed under the Creative Commons Attribution 4.0",
"_function(normal_arg: str, value_one: str, normal_key_arg: str=None, key_value: str=None) -> Any: CommonAssertionUtils.are_equal(value_one, _additional_value) CommonAssertionUtils.are_equal(key_value,",
"from typing import Any from sims4communitylib.modinfo import ModInfo from sims4communitylib.testing.common_assertion_utils import CommonAssertionUtils from",
"@CommonTestService.test(True, True, True, True) @CommonTestService.test(True, False, True, False) @CommonTestService.test(True, False, False, True) @CommonTestService.test(False,",
"license (CC BY 4.0). https://creativecommons.org/licenses/by/4.0/ https://creativecommons.org/licenses/by/4.0/legalcode Copyright (c) COLONOLNUTTY \"\"\" from typing import",
"_additional_value = 'No' _additional_key_word_value = 'What' normal_val = 'one' normal_key_val = 'two' def",
"bool, expected_result: bool): def _function_one(*_, **__) -> Any: return func_result_one def _function_two(*_, **__)",
"'What' normal_val = 'one' normal_key_val = 'two' def _function(normal_arg: str, value_one: str, normal_key_arg:",
"_additional_key_word_value: return True result = CommonFunctionUtils.run_with_arguments(_function, _additional_value, key_value=_additional_key_word_value)(normal_val, normal_key_arg=normal_key_val) CommonAssertionUtils.is_true(result, message='Failed to send",
"False, False, False) def run_predicates_as_one_should_work_properly(func_result_one: bool, func_result_two: bool, all_must_pass: bool, expected_result: bool): def",
"import CommonTestService from sims4communitylib.utils.common_function_utils import CommonFunctionUtils # noinspection PyMissingOrEmptyDocstring @CommonTestService.test_class(ModInfo.get_identity()) class CommonFunctionUtilsTests: @staticmethod",
"normal_key_val = 'two' def _function(normal_arg: str, value_one: str, normal_key_arg: str=None, key_value: str=None) ->",
"CommonTestService from sims4communitylib.utils.common_function_utils import CommonFunctionUtils # noinspection PyMissingOrEmptyDocstring @CommonTestService.test_class(ModInfo.get_identity()) class CommonFunctionUtilsTests: @staticmethod @CommonTestService.test(True,",
"ModInfo from sims4communitylib.testing.common_assertion_utils import CommonAssertionUtils from sims4communitylib.testing.common_test_service import CommonTestService from sims4communitylib.utils.common_function_utils import CommonFunctionUtils",
"PyMissingOrEmptyDocstring @CommonTestService.test_class(ModInfo.get_identity()) class CommonFunctionUtilsTests: @staticmethod @CommonTestService.test(True, True, True, True) @CommonTestService.test(True, False, True, False)",
"-> Any: return func_result_two result = CommonFunctionUtils.run_predicates_as_one((_function_one, _function_two), all_must_pass=all_must_pass)() CommonAssertionUtils.are_equal(result, expected_result) @staticmethod @CommonTestService.test(True,",
"@CommonTestService.test(False, True) def run_predicate_with_reversed_result_should_work_properly(func_result: bool, expected_result: bool): def _function(*_, **__) -> Any: return",
"def run_predicate_with_reversed_result_should_work_properly(func_result: bool, expected_result: bool): def _function(*_, **__) -> Any: return func_result result",
"BY 4.0). https://creativecommons.org/licenses/by/4.0/ https://creativecommons.org/licenses/by/4.0/legalcode Copyright (c) COLONOLNUTTY \"\"\" from typing import Any from",
"'one' normal_key_val = 'two' def _function(normal_arg: str, value_one: str, normal_key_arg: str=None, key_value: str=None)",
"is licensed under the Creative Commons Attribution 4.0 International public license (CC BY",
"@CommonTestService.test(False, False, False, False) def run_predicates_as_one_should_work_properly(func_result_one: bool, func_result_two: bool, all_must_pass: bool, expected_result: bool):",
"**__) -> Any: return func_result_one def _function_two(*_, **__) -> Any: return func_result_two result",
"CommonFunctionUtils.run_predicate_with_reversed_result(_function)() CommonAssertionUtils.are_equal(result, expected_result) @staticmethod @CommonTestService.test() def run_with_arguments_should_work_properly() -> None: _additional_value = 'No' _additional_key_word_value",
"@CommonTestService.test(True, False, False, True) @CommonTestService.test(False, False, False, False) def run_predicates_as_one_should_work_properly(func_result_one: bool, func_result_two: bool,",
"_function_two), all_must_pass=all_must_pass)() CommonAssertionUtils.are_equal(result, expected_result) @staticmethod @CommonTestService.test(True, False) @CommonTestService.test(False, True) def run_predicate_with_reversed_result_should_work_properly(func_result: bool, expected_result:",
"@staticmethod @CommonTestService.test(True, False) @CommonTestService.test(False, True) def run_predicate_with_reversed_result_should_work_properly(func_result: bool, expected_result: bool): def _function(*_, **__)",
"sims4communitylib.testing.common_assertion_utils import CommonAssertionUtils from sims4communitylib.testing.common_test_service import CommonTestService from sims4communitylib.utils.common_function_utils import CommonFunctionUtils # noinspection",
"Community Library is licensed under the Creative Commons Attribution 4.0 International public license",
"bool): def _function_one(*_, **__) -> Any: return func_result_one def _function_two(*_, **__) -> Any:",
"Sims 4 Community Library is licensed under the Creative Commons Attribution 4.0 International",
"CommonAssertionUtils from sims4communitylib.testing.common_test_service import CommonTestService from sims4communitylib.utils.common_function_utils import CommonFunctionUtils # noinspection PyMissingOrEmptyDocstring @CommonTestService.test_class(ModInfo.get_identity())",
"True, True) @CommonTestService.test(True, False, True, False) @CommonTestService.test(True, False, False, True) @CommonTestService.test(False, False, False,",
"if normal_arg == normal_val and normal_key_arg == normal_key_val and value_one == _additional_value and",
"result = CommonFunctionUtils.run_predicate_with_reversed_result(_function)() CommonAssertionUtils.are_equal(result, expected_result) @staticmethod @CommonTestService.test() def run_with_arguments_should_work_properly() -> None: _additional_value =",
"def _function_one(*_, **__) -> Any: return func_result_one def _function_two(*_, **__) -> Any: return",
"False, True, False) @CommonTestService.test(True, False, False, True) @CommonTestService.test(False, False, False, False) def run_predicates_as_one_should_work_properly(func_result_one:",
"expected_result: bool): def _function(*_, **__) -> Any: return func_result result = CommonFunctionUtils.run_predicate_with_reversed_result(_function)() CommonAssertionUtils.are_equal(result,",
"def _function(*_, **__) -> Any: return func_result result = CommonFunctionUtils.run_predicate_with_reversed_result(_function)() CommonAssertionUtils.are_equal(result, expected_result) @staticmethod",
"_function_two(*_, **__) -> Any: return func_result_two result = CommonFunctionUtils.run_predicates_as_one((_function_one, _function_two), all_must_pass=all_must_pass)() CommonAssertionUtils.are_equal(result, expected_result)",
"True result = CommonFunctionUtils.run_with_arguments(_function, _additional_value, key_value=_additional_key_word_value)(normal_val, normal_key_arg=normal_key_val) CommonAssertionUtils.is_true(result, message='Failed to send proper arguments:",
"bool, func_result_two: bool, all_must_pass: bool, expected_result: bool): def _function_one(*_, **__) -> Any: return",
"**__) -> Any: return func_result_two result = CommonFunctionUtils.run_predicates_as_one((_function_one, _function_two), all_must_pass=all_must_pass)() CommonAssertionUtils.are_equal(result, expected_result) @staticmethod",
"Any: return func_result_two result = CommonFunctionUtils.run_predicates_as_one((_function_one, _function_two), all_must_pass=all_must_pass)() CommonAssertionUtils.are_equal(result, expected_result) @staticmethod @CommonTestService.test(True, False)",
"the Creative Commons Attribution 4.0 International public license (CC BY 4.0). https://creativecommons.org/licenses/by/4.0/ https://creativecommons.org/licenses/by/4.0/legalcode",
"key_value: str=None) -> Any: CommonAssertionUtils.are_equal(value_one, _additional_value) CommonAssertionUtils.are_equal(key_value, _additional_key_word_value) CommonAssertionUtils.are_equal(normal_arg, normal_val) CommonAssertionUtils.are_equal(normal_key_arg, normal_key_val) if",
"_additional_value) CommonAssertionUtils.are_equal(key_value, _additional_key_word_value) CommonAssertionUtils.are_equal(normal_arg, normal_val) CommonAssertionUtils.are_equal(normal_key_arg, normal_key_val) if normal_arg == normal_val and normal_key_arg",
"Any: return func_result_one def _function_two(*_, **__) -> Any: return func_result_two result = CommonFunctionUtils.run_predicates_as_one((_function_one,",
"CommonAssertionUtils.are_equal(value_one, _additional_value) CommonAssertionUtils.are_equal(key_value, _additional_key_word_value) CommonAssertionUtils.are_equal(normal_arg, normal_val) CommonAssertionUtils.are_equal(normal_key_arg, normal_key_val) if normal_arg == normal_val and",
"False, False) def run_predicates_as_one_should_work_properly(func_result_one: bool, func_result_two: bool, all_must_pass: bool, expected_result: bool): def _function_one(*_,",
"normal_key_val) if normal_arg == normal_val and normal_key_arg == normal_key_val and value_one == _additional_value",
"normal_val) CommonAssertionUtils.are_equal(normal_key_arg, normal_key_val) if normal_arg == normal_val and normal_key_arg == normal_key_val and value_one",
"== _additional_key_word_value: return True result = CommonFunctionUtils.run_with_arguments(_function, _additional_value, key_value=_additional_key_word_value)(normal_val, normal_key_arg=normal_key_val) CommonAssertionUtils.is_true(result, message='Failed to",
"= 'No' _additional_key_word_value = 'What' normal_val = 'one' normal_key_val = 'two' def _function(normal_arg:",
"under the Creative Commons Attribution 4.0 International public license (CC BY 4.0). https://creativecommons.org/licenses/by/4.0/",
"True) @CommonTestService.test(True, False, True, False) @CommonTestService.test(True, False, False, True) @CommonTestService.test(False, False, False, False)",
"True) def run_predicate_with_reversed_result_should_work_properly(func_result: bool, expected_result: bool): def _function(*_, **__) -> Any: return func_result",
"Any from sims4communitylib.modinfo import ModInfo from sims4communitylib.testing.common_assertion_utils import CommonAssertionUtils from sims4communitylib.testing.common_test_service import CommonTestService",
"return func_result_one def _function_two(*_, **__) -> Any: return func_result_two result = CommonFunctionUtils.run_predicates_as_one((_function_one, _function_two),",
"False) @CommonTestService.test(True, False, False, True) @CommonTestService.test(False, False, False, False) def run_predicates_as_one_should_work_properly(func_result_one: bool, func_result_two:",
"CommonFunctionUtilsTests: @staticmethod @CommonTestService.test(True, True, True, True) @CommonTestService.test(True, False, True, False) @CommonTestService.test(True, False, False,",
"4.0 International public license (CC BY 4.0). https://creativecommons.org/licenses/by/4.0/ https://creativecommons.org/licenses/by/4.0/legalcode Copyright (c) COLONOLNUTTY \"\"\"",
"licensed under the Creative Commons Attribution 4.0 International public license (CC BY 4.0).",
"noinspection PyMissingOrEmptyDocstring @CommonTestService.test_class(ModInfo.get_identity()) class CommonFunctionUtilsTests: @staticmethod @CommonTestService.test(True, True, True, True) @CommonTestService.test(True, False, True,",
"False) def run_predicates_as_one_should_work_properly(func_result_one: bool, func_result_two: bool, all_must_pass: bool, expected_result: bool): def _function_one(*_, **__)",
"CommonAssertionUtils.are_equal(key_value, _additional_key_word_value) CommonAssertionUtils.are_equal(normal_arg, normal_val) CommonAssertionUtils.are_equal(normal_key_arg, normal_key_val) if normal_arg == normal_val and normal_key_arg ==",
"expected_result) @staticmethod @CommonTestService.test(True, False) @CommonTestService.test(False, True) def run_predicate_with_reversed_result_should_work_properly(func_result: bool, expected_result: bool): def _function(*_,",
"_additional_key_word_value) CommonAssertionUtils.are_equal(normal_arg, normal_val) CommonAssertionUtils.are_equal(normal_key_arg, normal_key_val) if normal_arg == normal_val and normal_key_arg == normal_key_val",
"and value_one == _additional_value and key_value == _additional_key_word_value: return True result = CommonFunctionUtils.run_with_arguments(_function,",
"-> Any: return func_result_one def _function_two(*_, **__) -> Any: return func_result_two result =",
"= 'one' normal_key_val = 'two' def _function(normal_arg: str, value_one: str, normal_key_arg: str=None, key_value:",
"== normal_key_val and value_one == _additional_value and key_value == _additional_key_word_value: return True result",
"str, normal_key_arg: str=None, key_value: str=None) -> Any: CommonAssertionUtils.are_equal(value_one, _additional_value) CommonAssertionUtils.are_equal(key_value, _additional_key_word_value) CommonAssertionUtils.are_equal(normal_arg, normal_val)",
"return True result = CommonFunctionUtils.run_with_arguments(_function, _additional_value, key_value=_additional_key_word_value)(normal_val, normal_key_arg=normal_key_val) CommonAssertionUtils.is_true(result, message='Failed to send proper",
"normal_key_val and value_one == _additional_value and key_value == _additional_key_word_value: return True result =",
"bool, all_must_pass: bool, expected_result: bool): def _function_one(*_, **__) -> Any: return func_result_one def",
"def run_predicates_as_one_should_work_properly(func_result_one: bool, func_result_two: bool, all_must_pass: bool, expected_result: bool): def _function_one(*_, **__) ->",
"def _function(normal_arg: str, value_one: str, normal_key_arg: str=None, key_value: str=None) -> Any: CommonAssertionUtils.are_equal(value_one, _additional_value)",
"Any: CommonAssertionUtils.are_equal(value_one, _additional_value) CommonAssertionUtils.are_equal(key_value, _additional_key_word_value) CommonAssertionUtils.are_equal(normal_arg, normal_val) CommonAssertionUtils.are_equal(normal_key_arg, normal_key_val) if normal_arg == normal_val",
"func_result result = CommonFunctionUtils.run_predicate_with_reversed_result(_function)() CommonAssertionUtils.are_equal(result, expected_result) @staticmethod @CommonTestService.test() def run_with_arguments_should_work_properly() -> None: _additional_value",
"@staticmethod @CommonTestService.test() def run_with_arguments_should_work_properly() -> None: _additional_value = 'No' _additional_key_word_value = 'What' normal_val",
"run_with_arguments_should_work_properly() -> None: _additional_value = 'No' _additional_key_word_value = 'What' normal_val = 'one' normal_key_val",
"_function_one(*_, **__) -> Any: return func_result_one def _function_two(*_, **__) -> Any: return func_result_two",
"_additional_key_word_value = 'What' normal_val = 'one' normal_key_val = 'two' def _function(normal_arg: str, value_one:",
"International public license (CC BY 4.0). https://creativecommons.org/licenses/by/4.0/ https://creativecommons.org/licenses/by/4.0/legalcode Copyright (c) COLONOLNUTTY \"\"\" from",
"typing import Any from sims4communitylib.modinfo import ModInfo from sims4communitylib.testing.common_assertion_utils import CommonAssertionUtils from sims4communitylib.testing.common_test_service",
"-> Any: CommonAssertionUtils.are_equal(value_one, _additional_value) CommonAssertionUtils.are_equal(key_value, _additional_key_word_value) CommonAssertionUtils.are_equal(normal_arg, normal_val) CommonAssertionUtils.are_equal(normal_key_arg, normal_key_val) if normal_arg ==",
"normal_key_arg == normal_key_val and value_one == _additional_value and key_value == _additional_key_word_value: return True",
"False, True) @CommonTestService.test(False, False, False, False) def run_predicates_as_one_should_work_properly(func_result_one: bool, func_result_two: bool, all_must_pass: bool,",
"= 'What' normal_val = 'one' normal_key_val = 'two' def _function(normal_arg: str, value_one: str,"
] |
[
"db = pymysql.connect(host=\"127.0.0.1\", database=\"bugtracker\", user=\"root\", password=\"\") try: cursor = db.cursor() cursor.execute(\"select * from",
"password=\"\") try: cursor = db.cursor() cursor.execute(\"select * from mantis_project_table\") for row in cursor.fetchall():",
"= db.cursor() cursor.execute(\"select * from mantis_project_table\") for row in cursor.fetchall(): print(row) finally: db.close()",
"pymysql.cursors db = pymysql.connect(host=\"127.0.0.1\", database=\"bugtracker\", user=\"root\", password=\"\") try: cursor = db.cursor() cursor.execute(\"select *",
"user=\"root\", password=\"\") try: cursor = db.cursor() cursor.execute(\"select * from mantis_project_table\") for row in",
"try: cursor = db.cursor() cursor.execute(\"select * from mantis_project_table\") for row in cursor.fetchall(): print(row)",
"cursor = db.cursor() cursor.execute(\"select * from mantis_project_table\") for row in cursor.fetchall(): print(row) finally:",
"import pymysql.cursors db = pymysql.connect(host=\"127.0.0.1\", database=\"bugtracker\", user=\"root\", password=\"\") try: cursor = db.cursor() cursor.execute(\"select",
"database=\"bugtracker\", user=\"root\", password=\"\") try: cursor = db.cursor() cursor.execute(\"select * from mantis_project_table\") for row",
"= pymysql.connect(host=\"127.0.0.1\", database=\"bugtracker\", user=\"root\", password=\"\") try: cursor = db.cursor() cursor.execute(\"select * from mantis_project_table\")",
"pymysql.connect(host=\"127.0.0.1\", database=\"bugtracker\", user=\"root\", password=\"\") try: cursor = db.cursor() cursor.execute(\"select * from mantis_project_table\") for",
"<filename>check_db_connection.py import pymysql.cursors db = pymysql.connect(host=\"127.0.0.1\", database=\"bugtracker\", user=\"root\", password=\"\") try: cursor = db.cursor()"
] |
[
"collections.namedtuple('SockFilterError', ['address']) def __init__(self, address): self.address = address def __repr__(self): return repr(self._tuple) def",
"== other._tuple def __ne__(self, other): if not hasattr(other, '_tuple'): return False return self._tuple",
"def __eq__(self, other): if not hasattr(other, '_tuple'): return False return self._tuple == other._tuple",
"['address']) def __init__(self, address): self.address = address def __repr__(self): return repr(self._tuple) def __str__(self):",
"__repr__(self): return repr(self._tuple) def __str__(self): return str(self._tuple) def __unicode__(self): return unicode(self._tuple) def __eq__(self,",
"not hasattr(other, '_tuple'): return False return self._tuple == other._tuple def __ne__(self, other): if",
"return str(self._tuple) def __unicode__(self): return unicode(self._tuple) def __eq__(self, other): if not hasattr(other, '_tuple'):",
"Tuple = collections.namedtuple('SockFilterError', ['address']) def __init__(self, address): self.address = address def __repr__(self): return",
"def __ne__(self, other): if not hasattr(other, '_tuple'): return False return self._tuple != other._tuple",
"class SockFilterError(Exception): Tuple = collections.namedtuple('SockFilterError', ['address']) def __init__(self, address): self.address = address def",
"= collections.namedtuple('SockFilterError', ['address']) def __init__(self, address): self.address = address def __repr__(self): return repr(self._tuple)",
"'_tuple'): return False return self._tuple == other._tuple def __ne__(self, other): if not hasattr(other,",
"__eq__(self, other): if not hasattr(other, '_tuple'): return False return self._tuple == other._tuple def",
"not hasattr(other, '_tuple'): return False return self._tuple != other._tuple @property def _tuple(self): return",
"__all__ = ['SockFilterError'] import collections class SockFilterError(Exception): Tuple = collections.namedtuple('SockFilterError', ['address']) def __init__(self,",
"if not hasattr(other, '_tuple'): return False return self._tuple == other._tuple def __ne__(self, other):",
"SockFilterError(Exception): Tuple = collections.namedtuple('SockFilterError', ['address']) def __init__(self, address): self.address = address def __repr__(self):",
"other): if not hasattr(other, '_tuple'): return False return self._tuple == other._tuple def __ne__(self,",
"address def __repr__(self): return repr(self._tuple) def __str__(self): return str(self._tuple) def __unicode__(self): return unicode(self._tuple)",
"import collections class SockFilterError(Exception): Tuple = collections.namedtuple('SockFilterError', ['address']) def __init__(self, address): self.address =",
"__str__(self): return str(self._tuple) def __unicode__(self): return unicode(self._tuple) def __eq__(self, other): if not hasattr(other,",
"return repr(self._tuple) def __str__(self): return str(self._tuple) def __unicode__(self): return unicode(self._tuple) def __eq__(self, other):",
"other._tuple def __ne__(self, other): if not hasattr(other, '_tuple'): return False return self._tuple !=",
"return False return self._tuple == other._tuple def __ne__(self, other): if not hasattr(other, '_tuple'):",
"return self._tuple == other._tuple def __ne__(self, other): if not hasattr(other, '_tuple'): return False",
"def __unicode__(self): return unicode(self._tuple) def __eq__(self, other): if not hasattr(other, '_tuple'): return False",
"def __str__(self): return str(self._tuple) def __unicode__(self): return unicode(self._tuple) def __eq__(self, other): if not",
"['SockFilterError'] import collections class SockFilterError(Exception): Tuple = collections.namedtuple('SockFilterError', ['address']) def __init__(self, address): self.address",
"address): self.address = address def __repr__(self): return repr(self._tuple) def __str__(self): return str(self._tuple) def",
"repr(self._tuple) def __str__(self): return str(self._tuple) def __unicode__(self): return unicode(self._tuple) def __eq__(self, other): if",
"False return self._tuple == other._tuple def __ne__(self, other): if not hasattr(other, '_tuple'): return",
"__ne__(self, other): if not hasattr(other, '_tuple'): return False return self._tuple != other._tuple @property",
"other): if not hasattr(other, '_tuple'): return False return self._tuple != other._tuple @property def",
"if not hasattr(other, '_tuple'): return False return self._tuple != other._tuple @property def _tuple(self):",
"__unicode__(self): return unicode(self._tuple) def __eq__(self, other): if not hasattr(other, '_tuple'): return False return",
"self._tuple == other._tuple def __ne__(self, other): if not hasattr(other, '_tuple'): return False return",
"= address def __repr__(self): return repr(self._tuple) def __str__(self): return str(self._tuple) def __unicode__(self): return",
"self.address = address def __repr__(self): return repr(self._tuple) def __str__(self): return str(self._tuple) def __unicode__(self):",
"str(self._tuple) def __unicode__(self): return unicode(self._tuple) def __eq__(self, other): if not hasattr(other, '_tuple'): return",
"__init__(self, address): self.address = address def __repr__(self): return repr(self._tuple) def __str__(self): return str(self._tuple)",
"def __repr__(self): return repr(self._tuple) def __str__(self): return str(self._tuple) def __unicode__(self): return unicode(self._tuple) def",
"hasattr(other, '_tuple'): return False return self._tuple != other._tuple @property def _tuple(self): return self.Tuple(address=self.address)",
"unicode(self._tuple) def __eq__(self, other): if not hasattr(other, '_tuple'): return False return self._tuple ==",
"hasattr(other, '_tuple'): return False return self._tuple == other._tuple def __ne__(self, other): if not",
"def __init__(self, address): self.address = address def __repr__(self): return repr(self._tuple) def __str__(self): return",
"return unicode(self._tuple) def __eq__(self, other): if not hasattr(other, '_tuple'): return False return self._tuple",
"= ['SockFilterError'] import collections class SockFilterError(Exception): Tuple = collections.namedtuple('SockFilterError', ['address']) def __init__(self, address):",
"collections class SockFilterError(Exception): Tuple = collections.namedtuple('SockFilterError', ['address']) def __init__(self, address): self.address = address"
] |
[
"row and n is col def searchInSortedMatrix(matrix, target): row = 0 col =",
"> -1: if target == matrix[row][col]: return [row, col] if target > matrix[row][col]:",
"if target > matrix[row][col]: row += 1 else: col -= 1 return [-1,",
"col > -1: if target == matrix[row][col]: return [row, col] if target >",
"is row and n is col def searchInSortedMatrix(matrix, target): row = 0 col",
"and col > -1: if target == matrix[row][col]: return [row, col] if target",
"O(1) space # m is row and n is col def searchInSortedMatrix(matrix, target):",
"return [row, col] if target > matrix[row][col]: row += 1 else: col -=",
"[row, col] if target > matrix[row][col]: row += 1 else: col -= 1",
"+ n) time | O(1) space # m is row and n is",
"col] if target > matrix[row][col]: row += 1 else: col -= 1 return",
"m is row and n is col def searchInSortedMatrix(matrix, target): row = 0",
"if target == matrix[row][col]: return [row, col] if target > matrix[row][col]: row +=",
"target == matrix[row][col]: return [row, col] if target > matrix[row][col]: row += 1",
"n) time | O(1) space # m is row and n is col",
"searchInSortedMatrix(matrix, target): row = 0 col = len(matrix[0]) - 1 while row <",
"0 col = len(matrix[0]) - 1 while row < len(matrix) and col >",
"# m is row and n is col def searchInSortedMatrix(matrix, target): row =",
"O(m + n) time | O(1) space # m is row and n",
"len(matrix) and col > -1: if target == matrix[row][col]: return [row, col] if",
"n is col def searchInSortedMatrix(matrix, target): row = 0 col = len(matrix[0]) -",
"# O(m + n) time | O(1) space # m is row and",
"| O(1) space # m is row and n is col def searchInSortedMatrix(matrix,",
"1 while row < len(matrix) and col > -1: if target == matrix[row][col]:",
"== matrix[row][col]: return [row, col] if target > matrix[row][col]: row += 1 else:",
"space # m is row and n is col def searchInSortedMatrix(matrix, target): row",
"def searchInSortedMatrix(matrix, target): row = 0 col = len(matrix[0]) - 1 while row",
"< len(matrix) and col > -1: if target == matrix[row][col]: return [row, col]",
"col def searchInSortedMatrix(matrix, target): row = 0 col = len(matrix[0]) - 1 while",
"and n is col def searchInSortedMatrix(matrix, target): row = 0 col = len(matrix[0])",
"time | O(1) space # m is row and n is col def",
"col = len(matrix[0]) - 1 while row < len(matrix) and col > -1:",
"= len(matrix[0]) - 1 while row < len(matrix) and col > -1: if",
"- 1 while row < len(matrix) and col > -1: if target ==",
"target > matrix[row][col]: row += 1 else: col -= 1 return [-1, -1]",
"is col def searchInSortedMatrix(matrix, target): row = 0 col = len(matrix[0]) - 1",
"len(matrix[0]) - 1 while row < len(matrix) and col > -1: if target",
"<filename>searching/search_in_sorter_matrix.py # O(m + n) time | O(1) space # m is row",
"matrix[row][col]: return [row, col] if target > matrix[row][col]: row += 1 else: col",
"-1: if target == matrix[row][col]: return [row, col] if target > matrix[row][col]: row",
"while row < len(matrix) and col > -1: if target == matrix[row][col]: return",
"target): row = 0 col = len(matrix[0]) - 1 while row < len(matrix)",
"row < len(matrix) and col > -1: if target == matrix[row][col]: return [row,",
"row = 0 col = len(matrix[0]) - 1 while row < len(matrix) and",
"= 0 col = len(matrix[0]) - 1 while row < len(matrix) and col"
] |
[
"Author: <NAME> # Date: 2018.7.16 # Version: 1.0 #==========================================================# class Event_Output(object): def output(self,",
"as events: events.write(\"====================\"+\"event \"+str(i)+\"====================\") events.write(\"\\n\") events.write(\"pem: \"+str(p1)) events.write(\"\\n\") events.write(\"pep: \"+str(p2)) events.write(\"\\n\") events.write(\"pmm: \"+str(p3))",
"e+e- -> Z/gamma -> mu+mu- # Author: <NAME> # Date: 2018.7.16 # Version:",
"p1, p2, p3, p4): with open(\"event.txt\",\"a\") as events: events.write(\"====================\"+\"event \"+str(i)+\"====================\") events.write(\"\\n\") events.write(\"pem: \"+str(p1))",
"1.0 #==========================================================# class Event_Output(object): def output(self, i, p1, p2, p3, p4): with open(\"event.txt\",\"a\")",
"events: events.write(\"====================\"+\"event \"+str(i)+\"====================\") events.write(\"\\n\") events.write(\"pem: \"+str(p1)) events.write(\"\\n\") events.write(\"pep: \"+str(p2)) events.write(\"\\n\") events.write(\"pmm: \"+str(p3)) events.write(\"\\n\")",
"output(self, i, p1, p2, p3, p4): with open(\"event.txt\",\"a\") as events: events.write(\"====================\"+\"event \"+str(i)+\"====================\") events.write(\"\\n\")",
"# Process: e+e- -> Z/gamma -> mu+mu- # Author: <NAME> # Date: 2018.7.16",
"Date: 2018.7.16 # Version: 1.0 #==========================================================# class Event_Output(object): def output(self, i, p1, p2,",
"Process: e+e- -> Z/gamma -> mu+mu- # Author: <NAME> # Date: 2018.7.16 #",
"Version: 1.0 #==========================================================# class Event_Output(object): def output(self, i, p1, p2, p3, p4): with",
"# Author: <NAME> # Date: 2018.7.16 # Version: 1.0 #==========================================================# class Event_Output(object): def",
"events.write(\"\\n\") events.write(\"pem: \"+str(p1)) events.write(\"\\n\") events.write(\"pep: \"+str(p2)) events.write(\"\\n\") events.write(\"pmm: \"+str(p3)) events.write(\"\\n\") events.write(\"pmp: \"+str(p4)) events.write(\"\\n\")",
"p4): with open(\"event.txt\",\"a\") as events: events.write(\"====================\"+\"event \"+str(i)+\"====================\") events.write(\"\\n\") events.write(\"pem: \"+str(p1)) events.write(\"\\n\") events.write(\"pep: \"+str(p2))",
"Z/gamma -> mu+mu- # Author: <NAME> # Date: 2018.7.16 # Version: 1.0 #==========================================================#",
"-> mu+mu- # Author: <NAME> # Date: 2018.7.16 # Version: 1.0 #==========================================================# class",
"2018.7.16 # Version: 1.0 #==========================================================# class Event_Output(object): def output(self, i, p1, p2, p3,",
"def output(self, i, p1, p2, p3, p4): with open(\"event.txt\",\"a\") as events: events.write(\"====================\"+\"event \"+str(i)+\"====================\")",
"p3, p4): with open(\"event.txt\",\"a\") as events: events.write(\"====================\"+\"event \"+str(i)+\"====================\") events.write(\"\\n\") events.write(\"pem: \"+str(p1)) events.write(\"\\n\") events.write(\"pep:",
"#==========================================================# class Event_Output(object): def output(self, i, p1, p2, p3, p4): with open(\"event.txt\",\"a\") as",
"# Version: 1.0 #==========================================================# class Event_Output(object): def output(self, i, p1, p2, p3, p4):",
"with open(\"event.txt\",\"a\") as events: events.write(\"====================\"+\"event \"+str(i)+\"====================\") events.write(\"\\n\") events.write(\"pem: \"+str(p1)) events.write(\"\\n\") events.write(\"pep: \"+str(p2)) events.write(\"\\n\")",
"events.write(\"pem: \"+str(p1)) events.write(\"\\n\") events.write(\"pep: \"+str(p2)) events.write(\"\\n\") events.write(\"pmm: \"+str(p3)) events.write(\"\\n\") events.write(\"pmp: \"+str(p4)) events.write(\"\\n\") events.write(\"\\n\")",
"mu+mu- # Author: <NAME> # Date: 2018.7.16 # Version: 1.0 #==========================================================# class Event_Output(object):",
"i, p1, p2, p3, p4): with open(\"event.txt\",\"a\") as events: events.write(\"====================\"+\"event \"+str(i)+\"====================\") events.write(\"\\n\") events.write(\"pem:",
"events.write(\"====================\"+\"event \"+str(i)+\"====================\") events.write(\"\\n\") events.write(\"pem: \"+str(p1)) events.write(\"\\n\") events.write(\"pep: \"+str(p2)) events.write(\"\\n\") events.write(\"pmm: \"+str(p3)) events.write(\"\\n\") events.write(\"pmp:",
"p2, p3, p4): with open(\"event.txt\",\"a\") as events: events.write(\"====================\"+\"event \"+str(i)+\"====================\") events.write(\"\\n\") events.write(\"pem: \"+str(p1)) events.write(\"\\n\")",
"\"+str(i)+\"====================\") events.write(\"\\n\") events.write(\"pem: \"+str(p1)) events.write(\"\\n\") events.write(\"pep: \"+str(p2)) events.write(\"\\n\") events.write(\"pmm: \"+str(p3)) events.write(\"\\n\") events.write(\"pmp: \"+str(p4))",
"class Event_Output(object): def output(self, i, p1, p2, p3, p4): with open(\"event.txt\",\"a\") as events:",
"<NAME> # Date: 2018.7.16 # Version: 1.0 #==========================================================# class Event_Output(object): def output(self, i,",
"open(\"event.txt\",\"a\") as events: events.write(\"====================\"+\"event \"+str(i)+\"====================\") events.write(\"\\n\") events.write(\"pem: \"+str(p1)) events.write(\"\\n\") events.write(\"pep: \"+str(p2)) events.write(\"\\n\") events.write(\"pmm:",
"#==========================================================# # Process: e+e- -> Z/gamma -> mu+mu- # Author: <NAME> # Date:",
"# Date: 2018.7.16 # Version: 1.0 #==========================================================# class Event_Output(object): def output(self, i, p1,",
"Event_Output(object): def output(self, i, p1, p2, p3, p4): with open(\"event.txt\",\"a\") as events: events.write(\"====================\"+\"event",
"-> Z/gamma -> mu+mu- # Author: <NAME> # Date: 2018.7.16 # Version: 1.0"
] |
[
"aio_background/__init__.py\") with open(\"README.md\", \"r\") as fh: long_description = fh.read() setup( name=\"aio-background\", version=read_version(), description=\"A",
"find version in aio_background/__init__.py\") with open(\"README.md\", \"r\") as fh: long_description = fh.read() setup(",
"import re from pathlib import Path from setuptools import setup install_requires = [\"croniter>=1.0.1\"]",
"[\"croniter>=1.0.1\"] def read(*parts): return Path(__file__).resolve().parent.joinpath(*parts).read_text().strip() def read_version(): regexp = re.compile(r\"^__version__\\W*=\\W*\\\"([\\d.abrc]+)\\\"\") for line in",
"\"__init__.py\").splitlines(): match = regexp.match(line) if match is not None: return match.group(1) else: raise",
"for line in read(\"aio_background\", \"__init__.py\").splitlines(): match = regexp.match(line) if match is not None:",
"fh: long_description = fh.read() setup( name=\"aio-background\", version=read_version(), description=\"A thing to run tasks in",
"def read_version(): regexp = re.compile(r\"^__version__\\W*=\\W*\\\"([\\d.abrc]+)\\\"\") for line in read(\"aio_background\", \"__init__.py\").splitlines(): match = regexp.match(line)",
"return match.group(1) else: raise RuntimeError(\"Cannot find version in aio_background/__init__.py\") with open(\"README.md\", \"r\") as",
"in read(\"aio_background\", \"__init__.py\").splitlines(): match = regexp.match(line) if match is not None: return match.group(1)",
"= fh.read() setup( name=\"aio-background\", version=read_version(), description=\"A thing to run tasks in the background\",",
"regexp = re.compile(r\"^__version__\\W*=\\W*\\\"([\\d.abrc]+)\\\"\") for line in read(\"aio_background\", \"__init__.py\").splitlines(): match = regexp.match(line) if match",
"to run tasks in the background\", long_description=long_description, long_description_content_type=\"text/markdown\", platforms=[\"macOS\", \"POSIX\", \"Windows\"], author=\"<NAME>\", python_requires=\">=3.9\",",
"background\", long_description=long_description, long_description_content_type=\"text/markdown\", platforms=[\"macOS\", \"POSIX\", \"Windows\"], author=\"<NAME>\", python_requires=\">=3.9\", project_urls={}, author_email=\"<EMAIL>\", license=\"MIT\", packages=[\"aio_background\"], package_dir={\"aio_background\":",
"\"POSIX\", \"Windows\"], author=\"<NAME>\", python_requires=\">=3.9\", project_urls={}, author_email=\"<EMAIL>\", license=\"MIT\", packages=[\"aio_background\"], package_dir={\"aio_background\": \"./aio_background\"}, package_data={\"aio_background\": [\"py.typed\"]}, install_requires=install_requires,",
"in the background\", long_description=long_description, long_description_content_type=\"text/markdown\", platforms=[\"macOS\", \"POSIX\", \"Windows\"], author=\"<NAME>\", python_requires=\">=3.9\", project_urls={}, author_email=\"<EMAIL>\", license=\"MIT\",",
"= re.compile(r\"^__version__\\W*=\\W*\\\"([\\d.abrc]+)\\\"\") for line in read(\"aio_background\", \"__init__.py\").splitlines(): match = regexp.match(line) if match is",
"line in read(\"aio_background\", \"__init__.py\").splitlines(): match = regexp.match(line) if match is not None: return",
"Path(__file__).resolve().parent.joinpath(*parts).read_text().strip() def read_version(): regexp = re.compile(r\"^__version__\\W*=\\W*\\\"([\\d.abrc]+)\\\"\") for line in read(\"aio_background\", \"__init__.py\").splitlines(): match =",
"fh.read() setup( name=\"aio-background\", version=read_version(), description=\"A thing to run tasks in the background\", long_description=long_description,",
"import setup install_requires = [\"croniter>=1.0.1\"] def read(*parts): return Path(__file__).resolve().parent.joinpath(*parts).read_text().strip() def read_version(): regexp =",
"open(\"README.md\", \"r\") as fh: long_description = fh.read() setup( name=\"aio-background\", version=read_version(), description=\"A thing to",
"in aio_background/__init__.py\") with open(\"README.md\", \"r\") as fh: long_description = fh.read() setup( name=\"aio-background\", version=read_version(),",
"regexp.match(line) if match is not None: return match.group(1) else: raise RuntimeError(\"Cannot find version",
"match = regexp.match(line) if match is not None: return match.group(1) else: raise RuntimeError(\"Cannot",
"long_description=long_description, long_description_content_type=\"text/markdown\", platforms=[\"macOS\", \"POSIX\", \"Windows\"], author=\"<NAME>\", python_requires=\">=3.9\", project_urls={}, author_email=\"<EMAIL>\", license=\"MIT\", packages=[\"aio_background\"], package_dir={\"aio_background\": \"./aio_background\"},",
"platforms=[\"macOS\", \"POSIX\", \"Windows\"], author=\"<NAME>\", python_requires=\">=3.9\", project_urls={}, author_email=\"<EMAIL>\", license=\"MIT\", packages=[\"aio_background\"], package_dir={\"aio_background\": \"./aio_background\"}, package_data={\"aio_background\": [\"py.typed\"]},",
"from setuptools import setup install_requires = [\"croniter>=1.0.1\"] def read(*parts): return Path(__file__).resolve().parent.joinpath(*parts).read_text().strip() def read_version():",
"long_description_content_type=\"text/markdown\", platforms=[\"macOS\", \"POSIX\", \"Windows\"], author=\"<NAME>\", python_requires=\">=3.9\", project_urls={}, author_email=\"<EMAIL>\", license=\"MIT\", packages=[\"aio_background\"], package_dir={\"aio_background\": \"./aio_background\"}, package_data={\"aio_background\":",
"read_version(): regexp = re.compile(r\"^__version__\\W*=\\W*\\\"([\\d.abrc]+)\\\"\") for line in read(\"aio_background\", \"__init__.py\").splitlines(): match = regexp.match(line) if",
"re from pathlib import Path from setuptools import setup install_requires = [\"croniter>=1.0.1\"] def",
"with open(\"README.md\", \"r\") as fh: long_description = fh.read() setup( name=\"aio-background\", version=read_version(), description=\"A thing",
"match.group(1) else: raise RuntimeError(\"Cannot find version in aio_background/__init__.py\") with open(\"README.md\", \"r\") as fh:",
"is not None: return match.group(1) else: raise RuntimeError(\"Cannot find version in aio_background/__init__.py\") with",
"install_requires = [\"croniter>=1.0.1\"] def read(*parts): return Path(__file__).resolve().parent.joinpath(*parts).read_text().strip() def read_version(): regexp = re.compile(r\"^__version__\\W*=\\W*\\\"([\\d.abrc]+)\\\"\") for",
"tasks in the background\", long_description=long_description, long_description_content_type=\"text/markdown\", platforms=[\"macOS\", \"POSIX\", \"Windows\"], author=\"<NAME>\", python_requires=\">=3.9\", project_urls={}, author_email=\"<EMAIL>\",",
"setup install_requires = [\"croniter>=1.0.1\"] def read(*parts): return Path(__file__).resolve().parent.joinpath(*parts).read_text().strip() def read_version(): regexp = re.compile(r\"^__version__\\W*=\\W*\\\"([\\d.abrc]+)\\\"\")",
"re.compile(r\"^__version__\\W*=\\W*\\\"([\\d.abrc]+)\\\"\") for line in read(\"aio_background\", \"__init__.py\").splitlines(): match = regexp.match(line) if match is not",
"not None: return match.group(1) else: raise RuntimeError(\"Cannot find version in aio_background/__init__.py\") with open(\"README.md\",",
"None: return match.group(1) else: raise RuntimeError(\"Cannot find version in aio_background/__init__.py\") with open(\"README.md\", \"r\")",
"version in aio_background/__init__.py\") with open(\"README.md\", \"r\") as fh: long_description = fh.read() setup( name=\"aio-background\",",
"RuntimeError(\"Cannot find version in aio_background/__init__.py\") with open(\"README.md\", \"r\") as fh: long_description = fh.read()",
"return Path(__file__).resolve().parent.joinpath(*parts).read_text().strip() def read_version(): regexp = re.compile(r\"^__version__\\W*=\\W*\\\"([\\d.abrc]+)\\\"\") for line in read(\"aio_background\", \"__init__.py\").splitlines(): match",
"= regexp.match(line) if match is not None: return match.group(1) else: raise RuntimeError(\"Cannot find",
"Path from setuptools import setup install_requires = [\"croniter>=1.0.1\"] def read(*parts): return Path(__file__).resolve().parent.joinpath(*parts).read_text().strip() def",
"match is not None: return match.group(1) else: raise RuntimeError(\"Cannot find version in aio_background/__init__.py\")",
"from pathlib import Path from setuptools import setup install_requires = [\"croniter>=1.0.1\"] def read(*parts):",
"as fh: long_description = fh.read() setup( name=\"aio-background\", version=read_version(), description=\"A thing to run tasks",
"name=\"aio-background\", version=read_version(), description=\"A thing to run tasks in the background\", long_description=long_description, long_description_content_type=\"text/markdown\", platforms=[\"macOS\",",
"def read(*parts): return Path(__file__).resolve().parent.joinpath(*parts).read_text().strip() def read_version(): regexp = re.compile(r\"^__version__\\W*=\\W*\\\"([\\d.abrc]+)\\\"\") for line in read(\"aio_background\",",
"description=\"A thing to run tasks in the background\", long_description=long_description, long_description_content_type=\"text/markdown\", platforms=[\"macOS\", \"POSIX\", \"Windows\"],",
"the background\", long_description=long_description, long_description_content_type=\"text/markdown\", platforms=[\"macOS\", \"POSIX\", \"Windows\"], author=\"<NAME>\", python_requires=\">=3.9\", project_urls={}, author_email=\"<EMAIL>\", license=\"MIT\", packages=[\"aio_background\"],",
"read(\"aio_background\", \"__init__.py\").splitlines(): match = regexp.match(line) if match is not None: return match.group(1) else:",
"if match is not None: return match.group(1) else: raise RuntimeError(\"Cannot find version in",
"else: raise RuntimeError(\"Cannot find version in aio_background/__init__.py\") with open(\"README.md\", \"r\") as fh: long_description",
"setup( name=\"aio-background\", version=read_version(), description=\"A thing to run tasks in the background\", long_description=long_description, long_description_content_type=\"text/markdown\",",
"author=\"<NAME>\", python_requires=\">=3.9\", project_urls={}, author_email=\"<EMAIL>\", license=\"MIT\", packages=[\"aio_background\"], package_dir={\"aio_background\": \"./aio_background\"}, package_data={\"aio_background\": [\"py.typed\"]}, install_requires=install_requires, include_package_data=True, )",
"raise RuntimeError(\"Cannot find version in aio_background/__init__.py\") with open(\"README.md\", \"r\") as fh: long_description =",
"version=read_version(), description=\"A thing to run tasks in the background\", long_description=long_description, long_description_content_type=\"text/markdown\", platforms=[\"macOS\", \"POSIX\",",
"\"r\") as fh: long_description = fh.read() setup( name=\"aio-background\", version=read_version(), description=\"A thing to run",
"pathlib import Path from setuptools import setup install_requires = [\"croniter>=1.0.1\"] def read(*parts): return",
"thing to run tasks in the background\", long_description=long_description, long_description_content_type=\"text/markdown\", platforms=[\"macOS\", \"POSIX\", \"Windows\"], author=\"<NAME>\",",
"run tasks in the background\", long_description=long_description, long_description_content_type=\"text/markdown\", platforms=[\"macOS\", \"POSIX\", \"Windows\"], author=\"<NAME>\", python_requires=\">=3.9\", project_urls={},",
"\"Windows\"], author=\"<NAME>\", python_requires=\">=3.9\", project_urls={}, author_email=\"<EMAIL>\", license=\"MIT\", packages=[\"aio_background\"], package_dir={\"aio_background\": \"./aio_background\"}, package_data={\"aio_background\": [\"py.typed\"]}, install_requires=install_requires, include_package_data=True,",
"setuptools import setup install_requires = [\"croniter>=1.0.1\"] def read(*parts): return Path(__file__).resolve().parent.joinpath(*parts).read_text().strip() def read_version(): regexp",
"= [\"croniter>=1.0.1\"] def read(*parts): return Path(__file__).resolve().parent.joinpath(*parts).read_text().strip() def read_version(): regexp = re.compile(r\"^__version__\\W*=\\W*\\\"([\\d.abrc]+)\\\"\") for line",
"import Path from setuptools import setup install_requires = [\"croniter>=1.0.1\"] def read(*parts): return Path(__file__).resolve().parent.joinpath(*parts).read_text().strip()",
"read(*parts): return Path(__file__).resolve().parent.joinpath(*parts).read_text().strip() def read_version(): regexp = re.compile(r\"^__version__\\W*=\\W*\\\"([\\d.abrc]+)\\\"\") for line in read(\"aio_background\", \"__init__.py\").splitlines():",
"long_description = fh.read() setup( name=\"aio-background\", version=read_version(), description=\"A thing to run tasks in the"
] |
[
"float(input('Qual é o seu Peso? Kg')) altura = float(input('Qual é a sua Altura?",
"é {:.1f}'.format(imc)) if imc <= 18.5: print('Você esta abaixo do Peso!') elif imc",
"(altura ** 2) print('O seu Indice de massa muscular é {:.1f}'.format(imc)) if imc",
"m')) imc = peso / (altura ** 2) print('O seu Indice de massa",
"de massa muscular é {:.1f}'.format(imc)) if imc <= 18.5: print('Você esta abaixo do",
"29.9: print('Levemente acima do Peso!') elif imc <= 34.9: print('Obesidade grau 1') elif",
"acima do Peso!') elif imc <= 34.9: print('Obesidade grau 1') elif imc <=",
"print('Obesidade grau 1') elif imc <= 39.9: print('Obesidade grau 2 (Severa)') elif imc",
"imc <= 29.9: print('Levemente acima do Peso!') elif imc <= 34.9: print('Obesidade grau",
"<= 24.9: print('Peso ideal. Parabéns!') elif imc <= 29.9: print('Levemente acima do Peso!')",
"o seu Peso? Kg')) altura = float(input('Qual é a sua Altura? m')) imc",
"seu Indice de massa muscular é {:.1f}'.format(imc)) if imc <= 18.5: print('Você esta",
"muscular é {:.1f}'.format(imc)) if imc <= 18.5: print('Você esta abaixo do Peso!') elif",
"Peso!') elif imc <= 34.9: print('Obesidade grau 1') elif imc <= 39.9: print('Obesidade",
"2) print('O seu Indice de massa muscular é {:.1f}'.format(imc)) if imc <= 18.5:",
"/ (altura ** 2) print('O seu Indice de massa muscular é {:.1f}'.format(imc)) if",
"** 2) print('O seu Indice de massa muscular é {:.1f}'.format(imc)) if imc <=",
"<= 18.5: print('Você esta abaixo do Peso!') elif imc <= 24.9: print('Peso ideal.",
"<= 34.9: print('Obesidade grau 1') elif imc <= 39.9: print('Obesidade grau 2 (Severa)')",
"= float(input('Qual é o seu Peso? Kg')) altura = float(input('Qual é a sua",
"if imc <= 18.5: print('Você esta abaixo do Peso!') elif imc <= 24.9:",
"abaixo do Peso!') elif imc <= 24.9: print('Peso ideal. Parabéns!') elif imc <=",
"é o seu Peso? Kg')) altura = float(input('Qual é a sua Altura? m'))",
"= peso / (altura ** 2) print('O seu Indice de massa muscular é",
"<= 29.9: print('Levemente acima do Peso!') elif imc <= 34.9: print('Obesidade grau 1')",
"{:.1f}'.format(imc)) if imc <= 18.5: print('Você esta abaixo do Peso!') elif imc <=",
"Kg')) altura = float(input('Qual é a sua Altura? m')) imc = peso /",
"print('Levemente acima do Peso!') elif imc <= 34.9: print('Obesidade grau 1') elif imc",
"24.9: print('Peso ideal. Parabéns!') elif imc <= 29.9: print('Levemente acima do Peso!') elif",
"sua Altura? m')) imc = peso / (altura ** 2) print('O seu Indice",
"imc <= 39.9: print('Obesidade grau 2 (Severa)') elif imc >= 40: print('Obesidade grau",
"ideal. Parabéns!') elif imc <= 29.9: print('Levemente acima do Peso!') elif imc <=",
"Altura? m')) imc = peso / (altura ** 2) print('O seu Indice de",
"imc <= 34.9: print('Obesidade grau 1') elif imc <= 39.9: print('Obesidade grau 2",
"Parabéns!') elif imc <= 29.9: print('Levemente acima do Peso!') elif imc <= 34.9:",
"peso / (altura ** 2) print('O seu Indice de massa muscular é {:.1f}'.format(imc))",
"imc <= 18.5: print('Você esta abaixo do Peso!') elif imc <= 24.9: print('Peso",
"print('Peso ideal. Parabéns!') elif imc <= 29.9: print('Levemente acima do Peso!') elif imc",
"seu Peso? Kg')) altura = float(input('Qual é a sua Altura? m')) imc =",
"imc <= 24.9: print('Peso ideal. Parabéns!') elif imc <= 29.9: print('Levemente acima do",
"elif imc <= 34.9: print('Obesidade grau 1') elif imc <= 39.9: print('Obesidade grau",
"grau 1') elif imc <= 39.9: print('Obesidade grau 2 (Severa)') elif imc >=",
"Indice de massa muscular é {:.1f}'.format(imc)) if imc <= 18.5: print('Você esta abaixo",
"elif imc <= 24.9: print('Peso ideal. Parabéns!') elif imc <= 29.9: print('Levemente acima",
"Peso!') elif imc <= 24.9: print('Peso ideal. Parabéns!') elif imc <= 29.9: print('Levemente",
"= float(input('Qual é a sua Altura? m')) imc = peso / (altura **",
"34.9: print('Obesidade grau 1') elif imc <= 39.9: print('Obesidade grau 2 (Severa)') elif",
"altura = float(input('Qual é a sua Altura? m')) imc = peso / (altura",
"elif imc <= 39.9: print('Obesidade grau 2 (Severa)') elif imc >= 40: print('Obesidade",
"do Peso!') elif imc <= 34.9: print('Obesidade grau 1') elif imc <= 39.9:",
"Peso? Kg')) altura = float(input('Qual é a sua Altura? m')) imc = peso",
"39.9: print('Obesidade grau 2 (Severa)') elif imc >= 40: print('Obesidade grau 3 (mórbida)')",
"peso = float(input('Qual é o seu Peso? Kg')) altura = float(input('Qual é a",
"float(input('Qual é a sua Altura? m')) imc = peso / (altura ** 2)",
"elif imc <= 29.9: print('Levemente acima do Peso!') elif imc <= 34.9: print('Obesidade",
"a sua Altura? m')) imc = peso / (altura ** 2) print('O seu",
"é a sua Altura? m')) imc = peso / (altura ** 2) print('O",
"print('Você esta abaixo do Peso!') elif imc <= 24.9: print('Peso ideal. Parabéns!') elif",
"esta abaixo do Peso!') elif imc <= 24.9: print('Peso ideal. Parabéns!') elif imc",
"18.5: print('Você esta abaixo do Peso!') elif imc <= 24.9: print('Peso ideal. Parabéns!')",
"1') elif imc <= 39.9: print('Obesidade grau 2 (Severa)') elif imc >= 40:",
"<= 39.9: print('Obesidade grau 2 (Severa)') elif imc >= 40: print('Obesidade grau 3",
"do Peso!') elif imc <= 24.9: print('Peso ideal. Parabéns!') elif imc <= 29.9:",
"massa muscular é {:.1f}'.format(imc)) if imc <= 18.5: print('Você esta abaixo do Peso!')",
"print('O seu Indice de massa muscular é {:.1f}'.format(imc)) if imc <= 18.5: print('Você",
"imc = peso / (altura ** 2) print('O seu Indice de massa muscular"
] |
[] |
[
"= \"USD\" elif \"€\" in items[i]: currency = \"EUR\" elif \"£\" in items[i]:",
"= document[0].description for text in document: top_x_axis = text.bounding_poly.vertices[0].x top_y_axis = text.bounding_poly.vertices[0].y bottom_y_axis",
"in orders: p = re.findall(price, i)[0] tally[i.split(p)[0]] = float(p) tally2[\"store\"] = first_line for",
"lines.items(): if top_y_axis < s_item[0][1]: lines[s_top_y_axis][1].append((top_x_axis, text.description)) break for _, item in lines.items():",
"= vision.ImageAnnotatorClient() def process_image(image_file): total = -1 with io.open(image_file, 'rb') as image_file: content",
"def process_image(image_file): total = -1 with io.open(image_file, 'rb') as image_file: content = image_file.read()",
"range(len(items)): if pattern.match(items[i]) and not total_regex.match(items[i]) and not re.match(\"Total Tax\", items[i]) and not",
"= float(p) tally2[\"store\"] = first_line for i in range(len(items)): if \"$\" in items[i]:",
"key=lambda t: t[0]) items.append( (item[0], ' '.join([word for _, word in words]), words))",
"]?)([0-9a-zA-Z.']+[ ])+[$£€]?[0-9]+\\.[0-9][0-9])\") total_regex = re.compile( \"(([0-9]+/[0-9]+)?[ ]?([0-9]+[:][0-9]+)?)?[ ]?((BALANCE DUE)?(Amount)?((Total)?(total)?(TOTAL)?[ ]?(Due)?(TO PAY)?))[ ]?[:]?[ ]?(([£$€]?)([0-9]+[.][0-9][0-9]))\")",
"os.environ[\"GOOGLE_APPLICATION_CREDENTIALS\"] = \"swagger_server/firebase_key.json\" client = vision.ImageAnnotatorClient() def process_image(image_file): total = -1 with io.open(image_file,",
"= \"EUR\" elif \"£\" in items[i]: currency = \"GBP\" else: currency = \"UKN\"",
"items[i] = items[i][1] orders = [] pattern = re.compile( \"(([0-9]?[x]?[ ]?)([0-9a-zA-Z.']+[ ])+[$£€]?[0-9]+\\.[0-9][0-9])\") total_regex",
"lines[s_top_y_axis][1].append((top_x_axis, text.description)) break for _, item in lines.items(): if item[1]: words = sorted(item[1],",
"Tax\", items[i]) and not re.match(\"Visa\", items[i]) and not re.match(\"Subtotal\", items[i]): orders.append(items[i]) price =",
"]?([0-9]+[:][0-9]+)?)?[ ]?((BALANCE DUE)?(Amount)?((Total)?(total)?(TOTAL)?[ ]?(Due)?(TO PAY)?))[ ]?[:]?[ ]?(([£$€]?)([0-9]+[.][0-9][0-9]))\") for i in range(len(items)): if pattern.match(items[i])",
"elif \"€\" in items[i]: currency = \"EUR\" elif \"£\" in items[i]: currency =",
"tot = items[i] p = re.findall(price, tot)[0] tally2[\"total\"] = float(p) break else: tot",
"i)[0] tally[i.split(p)[0]] = float(p) tally2[\"store\"] = first_line for i in range(len(items)): if \"$\"",
"= client.document_text_detection(image=image) response = client.text_detection(image=image) document = response.text_annotations[1:] items = [] lines =",
"document[0].description for text in document: top_x_axis = text.bounding_poly.vertices[0].x top_y_axis = text.bounding_poly.vertices[0].y bottom_y_axis =",
"range(len(items)): items[i] = items[i][1] orders = [] pattern = re.compile( \"(([0-9]?[x]?[ ]?)([0-9a-zA-Z.']+[ ])+[$£€]?[0-9]+\\.[0-9][0-9])\")",
"\"[0-9]+\\.[0-9]+\" for i in orders: p = re.findall(price, i)[0] tally[i.split(p)[0]] = float(p) tally2[\"store\"]",
"pattern.match(items[i]) and not total_regex.match(items[i]) and not re.match(\"Total Tax\", items[i]) and not re.match(\"Tax\", items[i])",
"i in range(len(items)): if \"$\" in items[i]: currency = \"USD\" elif \"€\" in",
"top_y_axis = text.bounding_poly.vertices[0].y bottom_y_axis = text.bounding_poly.vertices[3].y if top_y_axis not in lines: lines[top_y_axis] =",
"'rb') as image_file: content = image_file.read() image = vision.types.Image(content=content) # response = client.document_text_detection(image=image)",
"currency = \"GBP\" else: currency = \"UKN\" if total_regex.match(items[i]) and not re.match(\"[$]?[0-9]+\\.[0-9][0-9]\", items[i]):",
"currency = \"EUR\" elif \"£\" in items[i]: currency = \"GBP\" else: currency =",
"total = -1 with io.open(image_file, 'rb') as image_file: content = image_file.read() image =",
"if \"$\" in items[i]: currency = \"USD\" elif \"€\" in items[i]: currency =",
"t[0]) items.append( (item[0], ' '.join([word for _, word in words]), words)) for i",
"= re.compile( \"(([0-9]?[x]?[ ]?)([0-9a-zA-Z.']+[ ])+[$£€]?[0-9]+\\.[0-9][0-9])\") total_regex = re.compile( \"(([0-9]+/[0-9]+)?[ ]?([0-9]+[:][0-9]+)?)?[ ]?((BALANCE DUE)?(Amount)?((Total)?(total)?(TOTAL)?[ ]?(Due)?(TO",
"orders.append(items[i]) price = \"[0-9]+\\.[0-9]+\" for i in orders: p = re.findall(price, i)[0] tally[i.split(p)[0]]",
"not re.match(\"[$]?[0-9]+\\.[0-9][0-9]\", items[i]): tot = items[i] p = re.findall(price, tot)[0] tally2[\"total\"] = float(p)",
"and not re.match(\"Total Tax\", items[i]) and not re.match(\"Tax\", items[i]) and not re.match(\"Sales Tax\",",
"in words]), words)) for i in range(len(items)): items[i] = items[i][1] orders = []",
"i in range(len(items)): items[i] = items[i][1] orders = [] pattern = re.compile( \"(([0-9]?[x]?[",
"words = sorted(item[1], key=lambda t: t[0]) items.append( (item[0], ' '.join([word for _, word",
"total_regex.match(items[i]) and not re.match(\"Total Tax\", items[i]) and not re.match(\"Tax\", items[i]) and not re.match(\"Sales",
"image_file: content = image_file.read() image = vision.types.Image(content=content) # response = client.document_text_detection(image=image) response =",
"items[i]) and not re.match(\"Tax\", items[i]) and not re.match(\"Sales Tax\", items[i]) and not re.match(\"Visa\",",
"and not re.match(\"Tax\", items[i]) and not re.match(\"Sales Tax\", items[i]) and not re.match(\"Visa\", items[i])",
"= first_line for i in range(len(items)): if \"$\" in items[i]: currency = \"USD\"",
"in range(len(items)): items[i] = items[i][1] orders = [] pattern = re.compile( \"(([0-9]?[x]?[ ]?)([0-9a-zA-Z.']+[",
"[(top_y_axis, bottom_y_axis), []] for s_top_y_axis, s_item in lines.items(): if top_y_axis < s_item[0][1]: lines[s_top_y_axis][1].append((top_x_axis,",
"{} tally2 = {} first_line = document[0].description for text in document: top_x_axis =",
"lines = {} tally = {} tally2 = {} first_line = document[0].description for",
"for i in orders: p = re.findall(price, i)[0] tally[i.split(p)[0]] = float(p) tally2[\"store\"] =",
"client = vision.ImageAnnotatorClient() def process_image(image_file): total = -1 with io.open(image_file, 'rb') as image_file:",
"in lines.items(): if item[1]: words = sorted(item[1], key=lambda t: t[0]) items.append( (item[0], '",
"s_item in lines.items(): if top_y_axis < s_item[0][1]: lines[s_top_y_axis][1].append((top_x_axis, text.description)) break for _, item",
"[]] for s_top_y_axis, s_item in lines.items(): if top_y_axis < s_item[0][1]: lines[s_top_y_axis][1].append((top_x_axis, text.description)) break",
"])+[$£€]?[0-9]+\\.[0-9][0-9])\") total_regex = re.compile( \"(([0-9]+/[0-9]+)?[ ]?([0-9]+[:][0-9]+)?)?[ ]?((BALANCE DUE)?(Amount)?((Total)?(total)?(TOTAL)?[ ]?(Due)?(TO PAY)?))[ ]?[:]?[ ]?(([£$€]?)([0-9]+[.][0-9][0-9]))\") for",
"-1 with io.open(image_file, 'rb') as image_file: content = image_file.read() image = vision.types.Image(content=content) #",
"= {} first_line = document[0].description for text in document: top_x_axis = text.bounding_poly.vertices[0].x top_y_axis",
"if pattern.match(items[i]) and not total_regex.match(items[i]) and not re.match(\"Total Tax\", items[i]) and not re.match(\"Tax\",",
"for text in document: top_x_axis = text.bounding_poly.vertices[0].x top_y_axis = text.bounding_poly.vertices[0].y bottom_y_axis = text.bounding_poly.vertices[3].y",
"t: t[0]) items.append( (item[0], ' '.join([word for _, word in words]), words)) for",
"item[1]: words = sorted(item[1], key=lambda t: t[0]) items.append( (item[0], ' '.join([word for _,",
"in items[i]: currency = \"USD\" elif \"€\" in items[i]: currency = \"EUR\" elif",
"= [] lines = {} tally = {} tally2 = {} first_line =",
"image = vision.types.Image(content=content) # response = client.document_text_detection(image=image) response = client.text_detection(image=image) document = response.text_annotations[1:]",
"\"(([0-9]?[x]?[ ]?)([0-9a-zA-Z.']+[ ])+[$£€]?[0-9]+\\.[0-9][0-9])\") total_regex = re.compile( \"(([0-9]+/[0-9]+)?[ ]?([0-9]+[:][0-9]+)?)?[ ]?((BALANCE DUE)?(Amount)?((Total)?(total)?(TOTAL)?[ ]?(Due)?(TO PAY)?))[ ]?[:]?[",
"re.match(\"Sales Tax\", items[i]) and not re.match(\"Visa\", items[i]) and not re.match(\"Subtotal\", items[i]): orders.append(items[i]) price",
"total_regex.match(items[i]) and not re.match(\"[$]?[0-9]+\\.[0-9][0-9]\", items[i]): tot = items[i] p = re.findall(price, tot)[0] tally2[\"total\"]",
"= sorted(item[1], key=lambda t: t[0]) items.append( (item[0], ' '.join([word for _, word in",
"= vision.types.Image(content=content) # response = client.document_text_detection(image=image) response = client.text_detection(image=image) document = response.text_annotations[1:] items",
"= text.bounding_poly.vertices[3].y if top_y_axis not in lines: lines[top_y_axis] = [(top_y_axis, bottom_y_axis), []] for",
"for s_top_y_axis, s_item in lines.items(): if top_y_axis < s_item[0][1]: lines[s_top_y_axis][1].append((top_x_axis, text.description)) break for",
"price = \"[0-9]+\\.[0-9]+\" for i in orders: p = re.findall(price, i)[0] tally[i.split(p)[0]] =",
"= float(p) break else: tot = -1 tally2[\"currency\"] = currency return tally, tally2",
"re import os os.environ[\"GOOGLE_APPLICATION_CREDENTIALS\"] = \"swagger_server/firebase_key.json\" client = vision.ImageAnnotatorClient() def process_image(image_file): total =",
"for _, item in lines.items(): if item[1]: words = sorted(item[1], key=lambda t: t[0])",
"for i in range(len(items)): if pattern.match(items[i]) and not total_regex.match(items[i]) and not re.match(\"Total Tax\",",
"not in lines: lines[top_y_axis] = [(top_y_axis, bottom_y_axis), []] for s_top_y_axis, s_item in lines.items():",
"and not re.match(\"[$]?[0-9]+\\.[0-9][0-9]\", items[i]): tot = items[i] p = re.findall(price, tot)[0] tally2[\"total\"] =",
"= image_file.read() image = vision.types.Image(content=content) # response = client.document_text_detection(image=image) response = client.text_detection(image=image) document",
"vision.ImageAnnotatorClient() def process_image(image_file): total = -1 with io.open(image_file, 'rb') as image_file: content =",
"import vision import io import re import os os.environ[\"GOOGLE_APPLICATION_CREDENTIALS\"] = \"swagger_server/firebase_key.json\" client =",
"= items[i] p = re.findall(price, tot)[0] tally2[\"total\"] = float(p) break else: tot =",
"if total_regex.match(items[i]) and not re.match(\"[$]?[0-9]+\\.[0-9][0-9]\", items[i]): tot = items[i] p = re.findall(price, tot)[0]",
"DUE)?(Amount)?((Total)?(total)?(TOTAL)?[ ]?(Due)?(TO PAY)?))[ ]?[:]?[ ]?(([£$€]?)([0-9]+[.][0-9][0-9]))\") for i in range(len(items)): if pattern.match(items[i]) and not",
"item in lines.items(): if item[1]: words = sorted(item[1], key=lambda t: t[0]) items.append( (item[0],",
"and not total_regex.match(items[i]) and not re.match(\"Total Tax\", items[i]) and not re.match(\"Tax\", items[i]) and",
"_, item in lines.items(): if item[1]: words = sorted(item[1], key=lambda t: t[0]) items.append(",
"for i in range(len(items)): items[i] = items[i][1] orders = [] pattern = re.compile(",
"' '.join([word for _, word in words]), words)) for i in range(len(items)): items[i]",
"tally[i.split(p)[0]] = float(p) tally2[\"store\"] = first_line for i in range(len(items)): if \"$\" in",
"s_top_y_axis, s_item in lines.items(): if top_y_axis < s_item[0][1]: lines[s_top_y_axis][1].append((top_x_axis, text.description)) break for _,",
"first_line for i in range(len(items)): if \"$\" in items[i]: currency = \"USD\" elif",
"items[i]: currency = \"GBP\" else: currency = \"UKN\" if total_regex.match(items[i]) and not re.match(\"[$]?[0-9]+\\.[0-9][0-9]\",",
"re.match(\"[$]?[0-9]+\\.[0-9][0-9]\", items[i]): tot = items[i] p = re.findall(price, tot)[0] tally2[\"total\"] = float(p) break",
"= items[i][1] orders = [] pattern = re.compile( \"(([0-9]?[x]?[ ]?)([0-9a-zA-Z.']+[ ])+[$£€]?[0-9]+\\.[0-9][0-9])\") total_regex =",
"text in document: top_x_axis = text.bounding_poly.vertices[0].x top_y_axis = text.bounding_poly.vertices[0].y bottom_y_axis = text.bounding_poly.vertices[3].y if",
"range(len(items)): if \"$\" in items[i]: currency = \"USD\" elif \"€\" in items[i]: currency",
"else: currency = \"UKN\" if total_regex.match(items[i]) and not re.match(\"[$]?[0-9]+\\.[0-9][0-9]\", items[i]): tot = items[i]",
"text.bounding_poly.vertices[3].y if top_y_axis not in lines: lines[top_y_axis] = [(top_y_axis, bottom_y_axis), []] for s_top_y_axis,",
"word in words]), words)) for i in range(len(items)): items[i] = items[i][1] orders =",
"\"(([0-9]+/[0-9]+)?[ ]?([0-9]+[:][0-9]+)?)?[ ]?((BALANCE DUE)?(Amount)?((Total)?(total)?(TOTAL)?[ ]?(Due)?(TO PAY)?))[ ]?[:]?[ ]?(([£$€]?)([0-9]+[.][0-9][0-9]))\") for i in range(len(items)): if",
"response.text_annotations[1:] items = [] lines = {} tally = {} tally2 = {}",
"pattern = re.compile( \"(([0-9]?[x]?[ ]?)([0-9a-zA-Z.']+[ ])+[$£€]?[0-9]+\\.[0-9][0-9])\") total_regex = re.compile( \"(([0-9]+/[0-9]+)?[ ]?([0-9]+[:][0-9]+)?)?[ ]?((BALANCE DUE)?(Amount)?((Total)?(total)?(TOTAL)?[",
"= text.bounding_poly.vertices[0].y bottom_y_axis = text.bounding_poly.vertices[3].y if top_y_axis not in lines: lines[top_y_axis] = [(top_y_axis,",
"total_regex = re.compile( \"(([0-9]+/[0-9]+)?[ ]?([0-9]+[:][0-9]+)?)?[ ]?((BALANCE DUE)?(Amount)?((Total)?(total)?(TOTAL)?[ ]?(Due)?(TO PAY)?))[ ]?[:]?[ ]?(([£$€]?)([0-9]+[.][0-9][0-9]))\") for i",
"lines[top_y_axis] = [(top_y_axis, bottom_y_axis), []] for s_top_y_axis, s_item in lines.items(): if top_y_axis <",
"bottom_y_axis = text.bounding_poly.vertices[3].y if top_y_axis not in lines: lines[top_y_axis] = [(top_y_axis, bottom_y_axis), []]",
"]?(Due)?(TO PAY)?))[ ]?[:]?[ ]?(([£$€]?)([0-9]+[.][0-9][0-9]))\") for i in range(len(items)): if pattern.match(items[i]) and not total_regex.match(items[i])",
"= \"swagger_server/firebase_key.json\" client = vision.ImageAnnotatorClient() def process_image(image_file): total = -1 with io.open(image_file, 'rb')",
"re.match(\"Subtotal\", items[i]): orders.append(items[i]) price = \"[0-9]+\\.[0-9]+\" for i in orders: p = re.findall(price,",
"'.join([word for _, word in words]), words)) for i in range(len(items)): items[i] =",
"response = client.text_detection(image=image) document = response.text_annotations[1:] items = [] lines = {} tally",
"for i in range(len(items)): if \"$\" in items[i]: currency = \"USD\" elif \"€\"",
"break for _, item in lines.items(): if item[1]: words = sorted(item[1], key=lambda t:",
"tally2 = {} first_line = document[0].description for text in document: top_x_axis = text.bounding_poly.vertices[0].x",
"and not re.match(\"Visa\", items[i]) and not re.match(\"Subtotal\", items[i]): orders.append(items[i]) price = \"[0-9]+\\.[0-9]+\" for",
"in range(len(items)): if pattern.match(items[i]) and not total_regex.match(items[i]) and not re.match(\"Total Tax\", items[i]) and",
"re.match(\"Tax\", items[i]) and not re.match(\"Sales Tax\", items[i]) and not re.match(\"Visa\", items[i]) and not",
"currency = \"USD\" elif \"€\" in items[i]: currency = \"EUR\" elif \"£\" in",
"{} tally = {} tally2 = {} first_line = document[0].description for text in",
"\"£\" in items[i]: currency = \"GBP\" else: currency = \"UKN\" if total_regex.match(items[i]) and",
"= \"GBP\" else: currency = \"UKN\" if total_regex.match(items[i]) and not re.match(\"[$]?[0-9]+\\.[0-9][0-9]\", items[i]): tot",
"tot)[0] tally2[\"total\"] = float(p) break else: tot = -1 tally2[\"currency\"] = currency return",
"= re.findall(price, i)[0] tally[i.split(p)[0]] = float(p) tally2[\"store\"] = first_line for i in range(len(items)):",
"currency = \"UKN\" if total_regex.match(items[i]) and not re.match(\"[$]?[0-9]+\\.[0-9][0-9]\", items[i]): tot = items[i] p",
"elif \"£\" in items[i]: currency = \"GBP\" else: currency = \"UKN\" if total_regex.match(items[i])",
"= \"UKN\" if total_regex.match(items[i]) and not re.match(\"[$]?[0-9]+\\.[0-9][0-9]\", items[i]): tot = items[i] p =",
"in document: top_x_axis = text.bounding_poly.vertices[0].x top_y_axis = text.bounding_poly.vertices[0].y bottom_y_axis = text.bounding_poly.vertices[3].y if top_y_axis",
"vision.types.Image(content=content) # response = client.document_text_detection(image=image) response = client.text_detection(image=image) document = response.text_annotations[1:] items =",
"in items[i]: currency = \"EUR\" elif \"£\" in items[i]: currency = \"GBP\" else:",
"= \"[0-9]+\\.[0-9]+\" for i in orders: p = re.findall(price, i)[0] tally[i.split(p)[0]] = float(p)",
"\"UKN\" if total_regex.match(items[i]) and not re.match(\"[$]?[0-9]+\\.[0-9][0-9]\", items[i]): tot = items[i] p = re.findall(price,",
"items[i]) and not re.match(\"Sales Tax\", items[i]) and not re.match(\"Visa\", items[i]) and not re.match(\"Subtotal\",",
"]?((BALANCE DUE)?(Amount)?((Total)?(total)?(TOTAL)?[ ]?(Due)?(TO PAY)?))[ ]?[:]?[ ]?(([£$€]?)([0-9]+[.][0-9][0-9]))\") for i in range(len(items)): if pattern.match(items[i]) and",
"= re.compile( \"(([0-9]+/[0-9]+)?[ ]?([0-9]+[:][0-9]+)?)?[ ]?((BALANCE DUE)?(Amount)?((Total)?(total)?(TOTAL)?[ ]?(Due)?(TO PAY)?))[ ]?[:]?[ ]?(([£$€]?)([0-9]+[.][0-9][0-9]))\") for i in",
"as image_file: content = image_file.read() image = vision.types.Image(content=content) # response = client.document_text_detection(image=image) response",
"= client.text_detection(image=image) document = response.text_annotations[1:] items = [] lines = {} tally =",
"= re.findall(price, tot)[0] tally2[\"total\"] = float(p) break else: tot = -1 tally2[\"currency\"] =",
"import os os.environ[\"GOOGLE_APPLICATION_CREDENTIALS\"] = \"swagger_server/firebase_key.json\" client = vision.ImageAnnotatorClient() def process_image(image_file): total = -1",
"io.open(image_file, 'rb') as image_file: content = image_file.read() image = vision.types.Image(content=content) # response =",
"text.bounding_poly.vertices[0].y bottom_y_axis = text.bounding_poly.vertices[3].y if top_y_axis not in lines: lines[top_y_axis] = [(top_y_axis, bottom_y_axis),",
"words]), words)) for i in range(len(items)): items[i] = items[i][1] orders = [] pattern",
"items[i]) and not re.match(\"Visa\", items[i]) and not re.match(\"Subtotal\", items[i]): orders.append(items[i]) price = \"[0-9]+\\.[0-9]+\"",
"client.text_detection(image=image) document = response.text_annotations[1:] items = [] lines = {} tally = {}",
"\"EUR\" elif \"£\" in items[i]: currency = \"GBP\" else: currency = \"UKN\" if",
"lines: lines[top_y_axis] = [(top_y_axis, bottom_y_axis), []] for s_top_y_axis, s_item in lines.items(): if top_y_axis",
"]?(([£$€]?)([0-9]+[.][0-9][0-9]))\") for i in range(len(items)): if pattern.match(items[i]) and not total_regex.match(items[i]) and not re.match(\"Total",
"{} first_line = document[0].description for text in document: top_x_axis = text.bounding_poly.vertices[0].x top_y_axis =",
"p = re.findall(price, tot)[0] tally2[\"total\"] = float(p) break else: tot = -1 tally2[\"currency\"]",
"items[i]: currency = \"USD\" elif \"€\" in items[i]: currency = \"EUR\" elif \"£\"",
"vision import io import re import os os.environ[\"GOOGLE_APPLICATION_CREDENTIALS\"] = \"swagger_server/firebase_key.json\" client = vision.ImageAnnotatorClient()",
"re.findall(price, tot)[0] tally2[\"total\"] = float(p) break else: tot = -1 tally2[\"currency\"] = currency",
"orders: p = re.findall(price, i)[0] tally[i.split(p)[0]] = float(p) tally2[\"store\"] = first_line for i",
"s_item[0][1]: lines[s_top_y_axis][1].append((top_x_axis, text.description)) break for _, item in lines.items(): if item[1]: words =",
"re.findall(price, i)[0] tally[i.split(p)[0]] = float(p) tally2[\"store\"] = first_line for i in range(len(items)): if",
"not total_regex.match(items[i]) and not re.match(\"Total Tax\", items[i]) and not re.match(\"Tax\", items[i]) and not",
"re.match(\"Visa\", items[i]) and not re.match(\"Subtotal\", items[i]): orders.append(items[i]) price = \"[0-9]+\\.[0-9]+\" for i in",
"[] lines = {} tally = {} tally2 = {} first_line = document[0].description",
"items[i] p = re.findall(price, tot)[0] tally2[\"total\"] = float(p) break else: tot = -1",
"top_y_axis not in lines: lines[top_y_axis] = [(top_y_axis, bottom_y_axis), []] for s_top_y_axis, s_item in",
"< s_item[0][1]: lines[s_top_y_axis][1].append((top_x_axis, text.description)) break for _, item in lines.items(): if item[1]: words",
"with io.open(image_file, 'rb') as image_file: content = image_file.read() image = vision.types.Image(content=content) # response",
"bottom_y_axis), []] for s_top_y_axis, s_item in lines.items(): if top_y_axis < s_item[0][1]: lines[s_top_y_axis][1].append((top_x_axis, text.description))",
"not re.match(\"Total Tax\", items[i]) and not re.match(\"Tax\", items[i]) and not re.match(\"Sales Tax\", items[i])",
"p = re.findall(price, i)[0] tally[i.split(p)[0]] = float(p) tally2[\"store\"] = first_line for i in",
"google.cloud import vision import io import re import os os.environ[\"GOOGLE_APPLICATION_CREDENTIALS\"] = \"swagger_server/firebase_key.json\" client",
"not re.match(\"Tax\", items[i]) and not re.match(\"Sales Tax\", items[i]) and not re.match(\"Visa\", items[i]) and",
"sorted(item[1], key=lambda t: t[0]) items.append( (item[0], ' '.join([word for _, word in words]),",
"response = client.document_text_detection(image=image) response = client.text_detection(image=image) document = response.text_annotations[1:] items = [] lines",
"# response = client.document_text_detection(image=image) response = client.text_detection(image=image) document = response.text_annotations[1:] items = []",
"document = response.text_annotations[1:] items = [] lines = {} tally = {} tally2",
"= -1 with io.open(image_file, 'rb') as image_file: content = image_file.read() image = vision.types.Image(content=content)",
"items[i]): tot = items[i] p = re.findall(price, tot)[0] tally2[\"total\"] = float(p) break else:",
"in items[i]: currency = \"GBP\" else: currency = \"UKN\" if total_regex.match(items[i]) and not",
"]?[:]?[ ]?(([£$€]?)([0-9]+[.][0-9][0-9]))\") for i in range(len(items)): if pattern.match(items[i]) and not total_regex.match(items[i]) and not",
"text.description)) break for _, item in lines.items(): if item[1]: words = sorted(item[1], key=lambda",
"if item[1]: words = sorted(item[1], key=lambda t: t[0]) items.append( (item[0], ' '.join([word for",
"client.document_text_detection(image=image) response = client.text_detection(image=image) document = response.text_annotations[1:] items = [] lines = {}",
"first_line = document[0].description for text in document: top_x_axis = text.bounding_poly.vertices[0].x top_y_axis = text.bounding_poly.vertices[0].y",
"in lines: lines[top_y_axis] = [(top_y_axis, bottom_y_axis), []] for s_top_y_axis, s_item in lines.items(): if",
"= {} tally2 = {} first_line = document[0].description for text in document: top_x_axis",
"io import re import os os.environ[\"GOOGLE_APPLICATION_CREDENTIALS\"] = \"swagger_server/firebase_key.json\" client = vision.ImageAnnotatorClient() def process_image(image_file):",
"(item[0], ' '.join([word for _, word in words]), words)) for i in range(len(items)):",
"content = image_file.read() image = vision.types.Image(content=content) # response = client.document_text_detection(image=image) response = client.text_detection(image=image)",
"Tax\", items[i]) and not re.match(\"Tax\", items[i]) and not re.match(\"Sales Tax\", items[i]) and not",
"and not re.match(\"Sales Tax\", items[i]) and not re.match(\"Visa\", items[i]) and not re.match(\"Subtotal\", items[i]):",
"not re.match(\"Sales Tax\", items[i]) and not re.match(\"Visa\", items[i]) and not re.match(\"Subtotal\", items[i]): orders.append(items[i])",
"top_x_axis = text.bounding_poly.vertices[0].x top_y_axis = text.bounding_poly.vertices[0].y bottom_y_axis = text.bounding_poly.vertices[3].y if top_y_axis not in",
"items[i]: currency = \"EUR\" elif \"£\" in items[i]: currency = \"GBP\" else: currency",
"= {} tally = {} tally2 = {} first_line = document[0].description for text",
"items[i][1] orders = [] pattern = re.compile( \"(([0-9]?[x]?[ ]?)([0-9a-zA-Z.']+[ ])+[$£€]?[0-9]+\\.[0-9][0-9])\") total_regex = re.compile(",
"re.compile( \"(([0-9]+/[0-9]+)?[ ]?([0-9]+[:][0-9]+)?)?[ ]?((BALANCE DUE)?(Amount)?((Total)?(total)?(TOTAL)?[ ]?(Due)?(TO PAY)?))[ ]?[:]?[ ]?(([£$€]?)([0-9]+[.][0-9][0-9]))\") for i in range(len(items)):",
"and not re.match(\"Subtotal\", items[i]): orders.append(items[i]) price = \"[0-9]+\\.[0-9]+\" for i in orders: p",
"tally = {} tally2 = {} first_line = document[0].description for text in document:",
"top_y_axis < s_item[0][1]: lines[s_top_y_axis][1].append((top_x_axis, text.description)) break for _, item in lines.items(): if item[1]:",
"if top_y_axis < s_item[0][1]: lines[s_top_y_axis][1].append((top_x_axis, text.description)) break for _, item in lines.items(): if",
"[] pattern = re.compile( \"(([0-9]?[x]?[ ]?)([0-9a-zA-Z.']+[ ])+[$£€]?[0-9]+\\.[0-9][0-9])\") total_regex = re.compile( \"(([0-9]+/[0-9]+)?[ ]?([0-9]+[:][0-9]+)?)?[ ]?((BALANCE",
"items[i]) and not re.match(\"Subtotal\", items[i]): orders.append(items[i]) price = \"[0-9]+\\.[0-9]+\" for i in orders:",
"in lines.items(): if top_y_axis < s_item[0][1]: lines[s_top_y_axis][1].append((top_x_axis, text.description)) break for _, item in",
"if top_y_axis not in lines: lines[top_y_axis] = [(top_y_axis, bottom_y_axis), []] for s_top_y_axis, s_item",
"re.compile( \"(([0-9]?[x]?[ ]?)([0-9a-zA-Z.']+[ ])+[$£€]?[0-9]+\\.[0-9][0-9])\") total_regex = re.compile( \"(([0-9]+/[0-9]+)?[ ]?([0-9]+[:][0-9]+)?)?[ ]?((BALANCE DUE)?(Amount)?((Total)?(total)?(TOTAL)?[ ]?(Due)?(TO PAY)?))[",
"process_image(image_file): total = -1 with io.open(image_file, 'rb') as image_file: content = image_file.read() image",
"i in range(len(items)): if pattern.match(items[i]) and not total_regex.match(items[i]) and not re.match(\"Total Tax\", items[i])",
"items.append( (item[0], ' '.join([word for _, word in words]), words)) for i in",
"orders = [] pattern = re.compile( \"(([0-9]?[x]?[ ]?)([0-9a-zA-Z.']+[ ])+[$£€]?[0-9]+\\.[0-9][0-9])\") total_regex = re.compile( \"(([0-9]+/[0-9]+)?[",
"\"$\" in items[i]: currency = \"USD\" elif \"€\" in items[i]: currency = \"EUR\"",
"tally2[\"total\"] = float(p) break else: tot = -1 tally2[\"currency\"] = currency return tally,",
"\"€\" in items[i]: currency = \"EUR\" elif \"£\" in items[i]: currency = \"GBP\"",
"import io import re import os os.environ[\"GOOGLE_APPLICATION_CREDENTIALS\"] = \"swagger_server/firebase_key.json\" client = vision.ImageAnnotatorClient() def",
"items[i]): orders.append(items[i]) price = \"[0-9]+\\.[0-9]+\" for i in orders: p = re.findall(price, i)[0]",
"\"swagger_server/firebase_key.json\" client = vision.ImageAnnotatorClient() def process_image(image_file): total = -1 with io.open(image_file, 'rb') as",
"image_file.read() image = vision.types.Image(content=content) # response = client.document_text_detection(image=image) response = client.text_detection(image=image) document =",
"text.bounding_poly.vertices[0].x top_y_axis = text.bounding_poly.vertices[0].y bottom_y_axis = text.bounding_poly.vertices[3].y if top_y_axis not in lines: lines[top_y_axis]",
"_, word in words]), words)) for i in range(len(items)): items[i] = items[i][1] orders",
"tally2[\"store\"] = first_line for i in range(len(items)): if \"$\" in items[i]: currency =",
"items = [] lines = {} tally = {} tally2 = {} first_line",
"\"USD\" elif \"€\" in items[i]: currency = \"EUR\" elif \"£\" in items[i]: currency",
"float(p) tally2[\"store\"] = first_line for i in range(len(items)): if \"$\" in items[i]: currency",
"= response.text_annotations[1:] items = [] lines = {} tally = {} tally2 =",
"= [(top_y_axis, bottom_y_axis), []] for s_top_y_axis, s_item in lines.items(): if top_y_axis < s_item[0][1]:",
"words)) for i in range(len(items)): items[i] = items[i][1] orders = [] pattern =",
"not re.match(\"Subtotal\", items[i]): orders.append(items[i]) price = \"[0-9]+\\.[0-9]+\" for i in orders: p =",
"document: top_x_axis = text.bounding_poly.vertices[0].x top_y_axis = text.bounding_poly.vertices[0].y bottom_y_axis = text.bounding_poly.vertices[3].y if top_y_axis not",
"= text.bounding_poly.vertices[0].x top_y_axis = text.bounding_poly.vertices[0].y bottom_y_axis = text.bounding_poly.vertices[3].y if top_y_axis not in lines:",
"os os.environ[\"GOOGLE_APPLICATION_CREDENTIALS\"] = \"swagger_server/firebase_key.json\" client = vision.ImageAnnotatorClient() def process_image(image_file): total = -1 with",
"i in orders: p = re.findall(price, i)[0] tally[i.split(p)[0]] = float(p) tally2[\"store\"] = first_line",
"re.match(\"Total Tax\", items[i]) and not re.match(\"Tax\", items[i]) and not re.match(\"Sales Tax\", items[i]) and",
"PAY)?))[ ]?[:]?[ ]?(([£$€]?)([0-9]+[.][0-9][0-9]))\") for i in range(len(items)): if pattern.match(items[i]) and not total_regex.match(items[i]) and",
"in range(len(items)): if \"$\" in items[i]: currency = \"USD\" elif \"€\" in items[i]:",
"for _, word in words]), words)) for i in range(len(items)): items[i] = items[i][1]",
"= [] pattern = re.compile( \"(([0-9]?[x]?[ ]?)([0-9a-zA-Z.']+[ ])+[$£€]?[0-9]+\\.[0-9][0-9])\") total_regex = re.compile( \"(([0-9]+/[0-9]+)?[ ]?([0-9]+[:][0-9]+)?)?[",
"\"GBP\" else: currency = \"UKN\" if total_regex.match(items[i]) and not re.match(\"[$]?[0-9]+\\.[0-9][0-9]\", items[i]): tot =",
"import re import os os.environ[\"GOOGLE_APPLICATION_CREDENTIALS\"] = \"swagger_server/firebase_key.json\" client = vision.ImageAnnotatorClient() def process_image(image_file): total",
"lines.items(): if item[1]: words = sorted(item[1], key=lambda t: t[0]) items.append( (item[0], ' '.join([word",
"not re.match(\"Visa\", items[i]) and not re.match(\"Subtotal\", items[i]): orders.append(items[i]) price = \"[0-9]+\\.[0-9]+\" for i",
"from google.cloud import vision import io import re import os os.environ[\"GOOGLE_APPLICATION_CREDENTIALS\"] = \"swagger_server/firebase_key.json\""
] |
[] |
[
"= models.CharField(\"Http Status\",max_length=255,blank=True) type = models.CharField(\"Error type\",max_length=255,blank=True) code = models.CharField(\"Error code\",max_length=255,blank=True) param =",
"models.ForeignKey(User, verbose_name=\"User\", blank=True, null=True,on_delete=models.SET_NULL) date = models.DateTimeField(\"Error Date and Time\", auto_now_add=True) json_data =",
"message\",max_length=255,blank=True) class Meta: ordering = ('-date',) verbose_name = \"Stripe Error\" def __unicode__(self): return",
"verbose_name=\"User\", blank=True, null=True,on_delete=models.SET_NULL) date = models.DateTimeField(\"Error Date and Time\", auto_now_add=True) json_data = models.TextField(\"Json",
"models.CharField(\"Error code\",max_length=255,blank=True) param = models.CharField(\"Error param\",max_length=255,blank=True) message = models.CharField(\"Error message\",max_length=255,blank=True) class Meta: ordering",
"status = models.CharField(\"Http Status\",max_length=255,blank=True) type = models.CharField(\"Error type\",max_length=255,blank=True) code = models.CharField(\"Error code\",max_length=255,blank=True) param",
"= models.CharField(\"Error param\",max_length=255,blank=True) message = models.CharField(\"Error message\",max_length=255,blank=True) class Meta: ordering = ('-date',) verbose_name",
"django.contrib.auth.models import User #Stripe########################### class Stripe_Error(models.Model): user = models.ForeignKey(User, verbose_name=\"User\", blank=True, null=True,on_delete=models.SET_NULL) date",
"auto_now_add=True) json_data = models.TextField(\"Json Data\",blank=True) status = models.CharField(\"Http Status\",max_length=255,blank=True) type = models.CharField(\"Error type\",max_length=255,blank=True)",
"null=True,on_delete=models.SET_NULL) date = models.DateTimeField(\"Error Date and Time\", auto_now_add=True) json_data = models.TextField(\"Json Data\",blank=True) status",
"class Meta: ordering = ('-date',) verbose_name = \"Stripe Error\" def __unicode__(self): return str(self.date)",
"code = models.CharField(\"Error code\",max_length=255,blank=True) param = models.CharField(\"Error param\",max_length=255,blank=True) message = models.CharField(\"Error message\",max_length=255,blank=True) class",
"= models.TextField(\"Json Data\",blank=True) status = models.CharField(\"Http Status\",max_length=255,blank=True) type = models.CharField(\"Error type\",max_length=255,blank=True) code =",
"import User #Stripe########################### class Stripe_Error(models.Model): user = models.ForeignKey(User, verbose_name=\"User\", blank=True, null=True,on_delete=models.SET_NULL) date =",
"Status\",max_length=255,blank=True) type = models.CharField(\"Error type\",max_length=255,blank=True) code = models.CharField(\"Error code\",max_length=255,blank=True) param = models.CharField(\"Error param\",max_length=255,blank=True)",
"type = models.CharField(\"Error type\",max_length=255,blank=True) code = models.CharField(\"Error code\",max_length=255,blank=True) param = models.CharField(\"Error param\",max_length=255,blank=True) message",
"models.CharField(\"Error type\",max_length=255,blank=True) code = models.CharField(\"Error code\",max_length=255,blank=True) param = models.CharField(\"Error param\",max_length=255,blank=True) message = models.CharField(\"Error",
"= models.ForeignKey(User, verbose_name=\"User\", blank=True, null=True,on_delete=models.SET_NULL) date = models.DateTimeField(\"Error Date and Time\", auto_now_add=True) json_data",
"and Time\", auto_now_add=True) json_data = models.TextField(\"Json Data\",blank=True) status = models.CharField(\"Http Status\",max_length=255,blank=True) type =",
"Data\",blank=True) status = models.CharField(\"Http Status\",max_length=255,blank=True) type = models.CharField(\"Error type\",max_length=255,blank=True) code = models.CharField(\"Error code\",max_length=255,blank=True)",
"import models from django.contrib.auth.models import User #Stripe########################### class Stripe_Error(models.Model): user = models.ForeignKey(User, verbose_name=\"User\",",
"= models.DateTimeField(\"Error Date and Time\", auto_now_add=True) json_data = models.TextField(\"Json Data\",blank=True) status = models.CharField(\"Http",
"models.CharField(\"Http Status\",max_length=255,blank=True) type = models.CharField(\"Error type\",max_length=255,blank=True) code = models.CharField(\"Error code\",max_length=255,blank=True) param = models.CharField(\"Error",
"param\",max_length=255,blank=True) message = models.CharField(\"Error message\",max_length=255,blank=True) class Meta: ordering = ('-date',) verbose_name = \"Stripe",
"#Stripe########################### class Stripe_Error(models.Model): user = models.ForeignKey(User, verbose_name=\"User\", blank=True, null=True,on_delete=models.SET_NULL) date = models.DateTimeField(\"Error Date",
"django.db import models from django.contrib.auth.models import User #Stripe########################### class Stripe_Error(models.Model): user = models.ForeignKey(User,",
"Date and Time\", auto_now_add=True) json_data = models.TextField(\"Json Data\",blank=True) status = models.CharField(\"Http Status\",max_length=255,blank=True) type",
"json_data = models.TextField(\"Json Data\",blank=True) status = models.CharField(\"Http Status\",max_length=255,blank=True) type = models.CharField(\"Error type\",max_length=255,blank=True) code",
"models.TextField(\"Json Data\",blank=True) status = models.CharField(\"Http Status\",max_length=255,blank=True) type = models.CharField(\"Error type\",max_length=255,blank=True) code = models.CharField(\"Error",
"models from django.contrib.auth.models import User #Stripe########################### class Stripe_Error(models.Model): user = models.ForeignKey(User, verbose_name=\"User\", blank=True,",
"blank=True, null=True,on_delete=models.SET_NULL) date = models.DateTimeField(\"Error Date and Time\", auto_now_add=True) json_data = models.TextField(\"Json Data\",blank=True)",
"Time\", auto_now_add=True) json_data = models.TextField(\"Json Data\",blank=True) status = models.CharField(\"Http Status\",max_length=255,blank=True) type = models.CharField(\"Error",
"param = models.CharField(\"Error param\",max_length=255,blank=True) message = models.CharField(\"Error message\",max_length=255,blank=True) class Meta: ordering = ('-date',)",
"user = models.ForeignKey(User, verbose_name=\"User\", blank=True, null=True,on_delete=models.SET_NULL) date = models.DateTimeField(\"Error Date and Time\", auto_now_add=True)",
"= models.CharField(\"Error message\",max_length=255,blank=True) class Meta: ordering = ('-date',) verbose_name = \"Stripe Error\" def",
"= models.CharField(\"Error type\",max_length=255,blank=True) code = models.CharField(\"Error code\",max_length=255,blank=True) param = models.CharField(\"Error param\",max_length=255,blank=True) message =",
"User #Stripe########################### class Stripe_Error(models.Model): user = models.ForeignKey(User, verbose_name=\"User\", blank=True, null=True,on_delete=models.SET_NULL) date = models.DateTimeField(\"Error",
"<reponame>aykutgk/GoNaturalistic from django.db import models from django.contrib.auth.models import User #Stripe########################### class Stripe_Error(models.Model): user",
"date = models.DateTimeField(\"Error Date and Time\", auto_now_add=True) json_data = models.TextField(\"Json Data\",blank=True) status =",
"Stripe_Error(models.Model): user = models.ForeignKey(User, verbose_name=\"User\", blank=True, null=True,on_delete=models.SET_NULL) date = models.DateTimeField(\"Error Date and Time\",",
"= models.CharField(\"Error code\",max_length=255,blank=True) param = models.CharField(\"Error param\",max_length=255,blank=True) message = models.CharField(\"Error message\",max_length=255,blank=True) class Meta:",
"type\",max_length=255,blank=True) code = models.CharField(\"Error code\",max_length=255,blank=True) param = models.CharField(\"Error param\",max_length=255,blank=True) message = models.CharField(\"Error message\",max_length=255,blank=True)",
"from django.contrib.auth.models import User #Stripe########################### class Stripe_Error(models.Model): user = models.ForeignKey(User, verbose_name=\"User\", blank=True, null=True,on_delete=models.SET_NULL)",
"message = models.CharField(\"Error message\",max_length=255,blank=True) class Meta: ordering = ('-date',) verbose_name = \"Stripe Error\"",
"class Stripe_Error(models.Model): user = models.ForeignKey(User, verbose_name=\"User\", blank=True, null=True,on_delete=models.SET_NULL) date = models.DateTimeField(\"Error Date and",
"code\",max_length=255,blank=True) param = models.CharField(\"Error param\",max_length=255,blank=True) message = models.CharField(\"Error message\",max_length=255,blank=True) class Meta: ordering =",
"models.CharField(\"Error param\",max_length=255,blank=True) message = models.CharField(\"Error message\",max_length=255,blank=True) class Meta: ordering = ('-date',) verbose_name =",
"models.CharField(\"Error message\",max_length=255,blank=True) class Meta: ordering = ('-date',) verbose_name = \"Stripe Error\" def __unicode__(self):",
"from django.db import models from django.contrib.auth.models import User #Stripe########################### class Stripe_Error(models.Model): user =",
"models.DateTimeField(\"Error Date and Time\", auto_now_add=True) json_data = models.TextField(\"Json Data\",blank=True) status = models.CharField(\"Http Status\",max_length=255,blank=True)"
] |
[
"min_child_weight=1, # 决定最小叶子节点样本权重和,使一个结点分裂的最小权值之和, 避免过拟合 subsample=0.8, colsample_bytree=0.8, # 每棵树的列数 colsample_bylevel=0.8, # 每一层的列数 reg_alpha=0.0, reg_lambda=0.0,",
"colsample_bylevel=0.8, # 每一层的列数 reg_alpha=0.0, reg_lambda=0.0, scale_pos_weight=scale_pos_weight, random_state=seed, n_jobs=n_jobs, silent=True ) self.params = self.params_sk.copy()",
"%s ' % _[-1]) else: _ = cv_rst['test-%s-mean' % self.metrics] self.best_iter = len(_)",
"= len(_) print('\\nBest Iter: %s' % self.best_iter) print('Best Score: %s ' % _[-1])",
"feval(y_pred, y_true): y_true = y_true.get_label() return '1 / (1 + rmse)', 1 /(rmse(y_true,",
"xgboost as xgb class BaselineXGB(object): \"\"\" 待补充: https://xgboost.readthedocs.io/en/release_0.81/tutorials/feature_interaction_constraint.html 新版xgb支持交叉特征interaction_constraints tree_method='exact' b_xgb = BaselineXGB(X,",
"(1 + rmse)', 1 /(rmse(y_true, y_pred) + 1), True :param scale_pos_weight: \"\"\" self.data",
"= metrics self.feval = feval self.best_iter = None # sklearn params self.params_sk =",
"self.params['num_class'] = self.num_class def run(self, return_model=False, nfold=5, early_stopping_rounds=100, verbose_eval=50): print(\"XGB CV ...\\n\") try:",
"_[-1]) else: _ = cv_rst['test-%s-mean' % self.metrics] self.best_iter = len(_) print('\\nBest Iter: %s'",
"of strings or None, optional (default=None) binary: 'auc', 'binary_error', 'binary_logloss' multiclass: 'multi_error', 'multi_logloss'",
"# sklearn params self.params_sk = dict( booster='gbtree', objective=objective, max_depth=7, learning_rate=learning_rate, gamma=0.0, # 描述分裂的最小",
") self.params = self.params_sk.copy() self.params['eta'] = self.params.pop('learning_rate') self.params['alpha'] = self.params.pop('reg_alpha') self.params['lambda'] = self.params.pop('reg_lambda')",
"xgb.DMatrix(data, label=None, missing=None, feature_types=None)\") if isinstance(self.metrics, str): _ = cv_rst['test-%s-mean' % self.metrics] self.best_iter",
":param metrics: string, list of strings or None, optional (default=None) binary: 'auc', 'binary_error',",
"metrics='auc', feval=None, objective='binary:logistic', scale_pos_weight=1, n_jobs=8, seed=0): # seed不能为None \"\"\" https://blog.csdn.net/fuqiuai/article/details/79495910 https://blog.csdn.net/fantacy10000/article/details/84504394 :param objective:",
"= self.params_sk.copy() self.params['eta'] = self.params.pop('learning_rate') self.params['alpha'] = self.params.pop('reg_alpha') self.params['lambda'] = self.params.pop('reg_lambda') if self.objective",
"list of strings or None, optional (default=None) binary: 'auc', 'binary_error', 'binary_logloss' multiclass: 'multi_error',",
"# -*- coding: utf-8 -*- \"\"\" __title__ = 'xgb' __author__ = 'JieYuan' __mtime__",
"nfold=nfold, num_boost_round=2500, stratified=False if 'reg' in self.objective else True, early_stopping_rounds=early_stopping_rounds, verbose_eval=verbose_eval, as_pandas=False )",
"self.params.pop('learning_rate') self.params['alpha'] = self.params.pop('reg_alpha') self.params['lambda'] = self.params.pop('reg_lambda') if self.objective == 'multi:softmax': self.num_class =",
"reg_lambda=0.0, scale_pos_weight=scale_pos_weight, random_state=seed, n_jobs=n_jobs, silent=True ) self.params = self.params_sk.copy() self.params['eta'] = self.params.pop('learning_rate') self.params['alpha']",
"print('Best Score: %s ' % _[-1]) else: _ = cv_rst['test-%s-mean' % self.metrics] self.best_iter",
"/(rmse(y_true, y_pred) + 1), True :param scale_pos_weight: \"\"\" self.data = xgb.DMatrix(X, y, missing=missing)",
"% self.best_iter) print('Best Score: %s ' % _[-1]) self.params_sk['n_estimators'] = self.best_iter if return_model:",
"xgb class BaselineXGB(object): \"\"\" 待补充: https://xgboost.readthedocs.io/en/release_0.81/tutorials/feature_interaction_constraint.html 新版xgb支持交叉特征interaction_constraints tree_method='exact' b_xgb = BaselineXGB(X, y, learning_rate=0.01)",
"'auc', 'binary_error', 'binary_logloss' multiclass: 'multi_error', 'multi_logloss' https://lightgbm.readthedocs.io/en/latest/Parameters.html#metric-parameters :param feval: def feval(y_pred, y_true): y_true",
"# 描述分裂的最小 gain, 控制树的有用的分裂 min_child_weight=1, # 决定最小叶子节点样本权重和,使一个结点分裂的最小权值之和, 避免过拟合 subsample=0.8, colsample_bytree=0.8, # 每棵树的列数 colsample_bylevel=0.8,",
"params self.params_sk = dict( booster='gbtree', objective=objective, max_depth=7, learning_rate=learning_rate, gamma=0.0, # 描述分裂的最小 gain, 控制树的有用的分裂",
"subsample=0.8, colsample_bytree=0.8, # 每棵树的列数 colsample_bylevel=0.8, # 每一层的列数 reg_alpha=0.0, reg_lambda=0.0, scale_pos_weight=scale_pos_weight, random_state=seed, n_jobs=n_jobs, silent=True",
"cv_rst['test-%s-mean' % self.metrics] self.best_iter = len(_) print('\\nBest Iter: %s' % self.best_iter) print('Best Score:",
"return '1 / (1 + rmse)', 1 /(rmse(y_true, y_pred) + 1), True :param",
"self.objective = objective self.metrics = metrics self.feval = feval self.best_iter = None #",
"+ 1), True :param scale_pos_weight: \"\"\" self.data = xgb.DMatrix(X, y, missing=missing) self.objective =",
"run(self, return_model=False, nfold=5, early_stopping_rounds=100, verbose_eval=50): print(\"XGB CV ...\\n\") try: cv_rst = xgb.cv( self.params,",
"rmse)', 1 /(rmse(y_true, y_pred) + 1), True :param scale_pos_weight: \"\"\" self.data = xgb.DMatrix(X,",
"TypeError: print(\"Please: self.xgb_data = xgb.DMatrix(data, label=None, missing=None, feature_types=None)\") if isinstance(self.metrics, str): _ =",
"reg_alpha=0.0, reg_lambda=0.0, scale_pos_weight=scale_pos_weight, random_state=seed, n_jobs=n_jobs, silent=True ) self.params = self.params_sk.copy() self.params['eta'] = self.params.pop('learning_rate')",
"# 每一层的列数 reg_alpha=0.0, reg_lambda=0.0, scale_pos_weight=scale_pos_weight, random_state=seed, n_jobs=n_jobs, silent=True ) self.params = self.params_sk.copy() self.params['eta']",
"% self.best_iter) print('Best Score: %s ' % _[-1]) else: _ = cv_rst['test-%s-mean' %",
"feature_types=None)\") if isinstance(self.metrics, str): _ = cv_rst['test-%s-mean' % self.metrics] self.best_iter = len(_) print('\\nBest",
"y_pred) + 1), True :param scale_pos_weight: \"\"\" self.data = xgb.DMatrix(X, y, missing=missing) self.objective",
"1 /(rmse(y_true, y_pred) + 1), True :param scale_pos_weight: \"\"\" self.data = xgb.DMatrix(X, y,",
"random_state=seed, n_jobs=n_jobs, silent=True ) self.params = self.params_sk.copy() self.params['eta'] = self.params.pop('learning_rate') self.params['alpha'] = self.params.pop('reg_alpha')",
"Iter: %s' % self.best_iter) print('Best Score: %s ' % _[-1]) else: _ =",
"if isinstance(self.metrics, str): _ = cv_rst['test-%s-mean' % self.metrics] self.best_iter = len(_) print('\\nBest Iter:",
"else True, early_stopping_rounds=early_stopping_rounds, verbose_eval=verbose_eval, as_pandas=False ) except TypeError: print(\"Please: self.xgb_data = xgb.DMatrix(data, label=None,",
"self.metrics = metrics self.feval = feval self.best_iter = None # sklearn params self.params_sk",
"print('\\nBest Iter: %s' % self.best_iter) print('Best Score: %s ' % _[-1]) self.params_sk['n_estimators'] =",
"'multi:softmax': self.num_class = len(set(y)) self.params['objective'] = self.objective self.params['num_class'] = self.num_class def run(self, return_model=False,",
"= self.params.pop('reg_alpha') self.params['lambda'] = self.params.pop('reg_lambda') if self.objective == 'multi:softmax': self.num_class = len(set(y)) self.params['objective']",
"self.params['eta'] = self.params.pop('learning_rate') self.params['alpha'] = self.params.pop('reg_alpha') self.params['lambda'] = self.params.pop('reg_lambda') if self.objective == 'multi:softmax':",
"python # -*- coding: utf-8 -*- \"\"\" __title__ = 'xgb' __author__ = 'JieYuan'",
"len(set(y)) self.params['objective'] = self.objective self.params['num_class'] = self.num_class def run(self, return_model=False, nfold=5, early_stopping_rounds=100, verbose_eval=50):",
"<filename>tql/algo_ml/models/classifier/baseline_xgb.py #!/usr/bin/env python # -*- coding: utf-8 -*- \"\"\" __title__ = 'xgb' __author__",
"feval: def feval(y_pred, y_true): y_true = y_true.get_label() return '1 / (1 + rmse)',",
"print(\"Please: self.xgb_data = xgb.DMatrix(data, label=None, missing=None, feature_types=None)\") if isinstance(self.metrics, str): _ = cv_rst['test-%s-mean'",
"b_xgb.run() \"\"\" def __init__(self, X, y, learning_rate=0.01, missing=None, metrics='auc', feval=None, objective='binary:logistic', scale_pos_weight=1, n_jobs=8,",
"tree_method='exact' b_xgb = BaselineXGB(X, y, learning_rate=0.01) b_xgb.run() \"\"\" def __init__(self, X, y, learning_rate=0.01,",
"'binary:logistic', 'multi:softmax', 'reg:linear' :param metrics: string, list of strings or None, optional (default=None)",
"colsample_bytree=0.8, # 每棵树的列数 colsample_bylevel=0.8, # 每一层的列数 reg_alpha=0.0, reg_lambda=0.0, scale_pos_weight=scale_pos_weight, random_state=seed, n_jobs=n_jobs, silent=True )",
"None # sklearn params self.params_sk = dict( booster='gbtree', objective=objective, max_depth=7, learning_rate=learning_rate, gamma=0.0, #",
"__init__(self, X, y, learning_rate=0.01, missing=None, metrics='auc', feval=None, objective='binary:logistic', scale_pos_weight=1, n_jobs=8, seed=0): # seed不能为None",
"or None, optional (default=None) binary: 'auc', 'binary_error', 'binary_logloss' multiclass: 'multi_error', 'multi_logloss' https://lightgbm.readthedocs.io/en/latest/Parameters.html#metric-parameters :param",
"'binary_logloss' multiclass: 'multi_error', 'multi_logloss' https://lightgbm.readthedocs.io/en/latest/Parameters.html#metric-parameters :param feval: def feval(y_pred, y_true): y_true = y_true.get_label()",
"missing=missing) self.objective = objective self.metrics = metrics self.feval = feval self.best_iter = None",
"y, learning_rate=0.01, missing=None, metrics='auc', feval=None, objective='binary:logistic', scale_pos_weight=1, n_jobs=8, seed=0): # seed不能为None \"\"\" https://blog.csdn.net/fuqiuai/article/details/79495910",
"= y_true.get_label() return '1 / (1 + rmse)', 1 /(rmse(y_true, y_pred) + 1),",
"# seed不能为None \"\"\" https://blog.csdn.net/fuqiuai/article/details/79495910 https://blog.csdn.net/fantacy10000/article/details/84504394 :param objective: 'binary:logistic', 'multi:softmax', 'reg:linear' :param metrics: string,",
"sklearn params self.params_sk = dict( booster='gbtree', objective=objective, max_depth=7, learning_rate=learning_rate, gamma=0.0, # 描述分裂的最小 gain,",
"num_boost_round=2500, stratified=False if 'reg' in self.objective else True, early_stopping_rounds=early_stopping_rounds, verbose_eval=verbose_eval, as_pandas=False ) except",
"\"\"\" __title__ = 'xgb' __author__ = 'JieYuan' __mtime__ = '19-1-2' \"\"\" import xgboost",
"' % _[-1]) else: _ = cv_rst['test-%s-mean' % self.metrics] self.best_iter = len(_) print('\\nBest",
"__mtime__ = '19-1-2' \"\"\" import xgboost as xgb class BaselineXGB(object): \"\"\" 待补充: https://xgboost.readthedocs.io/en/release_0.81/tutorials/feature_interaction_constraint.html",
"= '19-1-2' \"\"\" import xgboost as xgb class BaselineXGB(object): \"\"\" 待补充: https://xgboost.readthedocs.io/en/release_0.81/tutorials/feature_interaction_constraint.html 新版xgb支持交叉特征interaction_constraints",
"https://xgboost.readthedocs.io/en/release_0.81/tutorials/feature_interaction_constraint.html 新版xgb支持交叉特征interaction_constraints tree_method='exact' b_xgb = BaselineXGB(X, y, learning_rate=0.01) b_xgb.run() \"\"\" def __init__(self, X,",
"if 'reg' in self.objective else True, early_stopping_rounds=early_stopping_rounds, verbose_eval=verbose_eval, as_pandas=False ) except TypeError: print(\"Please:",
"= BaselineXGB(X, y, learning_rate=0.01) b_xgb.run() \"\"\" def __init__(self, X, y, learning_rate=0.01, missing=None, metrics='auc',",
"'reg:linear' :param metrics: string, list of strings or None, optional (default=None) binary: 'auc',",
"'JieYuan' __mtime__ = '19-1-2' \"\"\" import xgboost as xgb class BaselineXGB(object): \"\"\" 待补充:",
"self.data = xgb.DMatrix(X, y, missing=missing) self.objective = objective self.metrics = metrics self.feval =",
"决定最小叶子节点样本权重和,使一个结点分裂的最小权值之和, 避免过拟合 subsample=0.8, colsample_bytree=0.8, # 每棵树的列数 colsample_bylevel=0.8, # 每一层的列数 reg_alpha=0.0, reg_lambda=0.0, scale_pos_weight=scale_pos_weight, random_state=seed,",
"cv_rst = xgb.cv( self.params, self.data, metrics=self.metrics, feval=self.feval, nfold=nfold, num_boost_round=2500, stratified=False if 'reg' in",
"xgb.cv( self.params, self.data, metrics=self.metrics, feval=self.feval, nfold=nfold, num_boost_round=2500, stratified=False if 'reg' in self.objective else",
"#!/usr/bin/env python # -*- coding: utf-8 -*- \"\"\" __title__ = 'xgb' __author__ =",
"# 决定最小叶子节点样本权重和,使一个结点分裂的最小权值之和, 避免过拟合 subsample=0.8, colsample_bytree=0.8, # 每棵树的列数 colsample_bylevel=0.8, # 每一层的列数 reg_alpha=0.0, reg_lambda=0.0, scale_pos_weight=scale_pos_weight,",
"self.params['alpha'] = self.params.pop('reg_alpha') self.params['lambda'] = self.params.pop('reg_lambda') if self.objective == 'multi:softmax': self.num_class = len(set(y))",
"str): _ = cv_rst['test-%s-mean' % self.metrics] self.best_iter = len(_) print('\\nBest Iter: %s' %",
"控制树的有用的分裂 min_child_weight=1, # 决定最小叶子节点样本权重和,使一个结点分裂的最小权值之和, 避免过拟合 subsample=0.8, colsample_bytree=0.8, # 每棵树的列数 colsample_bylevel=0.8, # 每一层的列数 reg_alpha=0.0,",
"y_true.get_label() return '1 / (1 + rmse)', 1 /(rmse(y_true, y_pred) + 1), True",
"else: _ = cv_rst['test-%s-mean' % self.metrics] self.best_iter = len(_) print('\\nBest Iter: %s' %",
"_ = cv_rst['test-%s-mean' % self.metrics] self.best_iter = len(_) print('\\nBest Iter: %s' % self.best_iter)",
"%s' % self.best_iter) print('Best Score: %s ' % _[-1]) else: _ = cv_rst['test-%s-mean'",
"' % _[-1]) self.params_sk['n_estimators'] = self.best_iter if return_model: print(\"\\nReturning Model ...\\n\") return xgb.train(self.params,",
"self.num_class def run(self, return_model=False, nfold=5, early_stopping_rounds=100, verbose_eval=50): print(\"XGB CV ...\\n\") try: cv_rst =",
"self.params_sk.copy() self.params['eta'] = self.params.pop('learning_rate') self.params['alpha'] = self.params.pop('reg_alpha') self.params['lambda'] = self.params.pop('reg_lambda') if self.objective ==",
":param objective: 'binary:logistic', 'multi:softmax', 'reg:linear' :param metrics: string, list of strings or None,",
"描述分裂的最小 gain, 控制树的有用的分裂 min_child_weight=1, # 决定最小叶子节点样本权重和,使一个结点分裂的最小权值之和, 避免过拟合 subsample=0.8, colsample_bytree=0.8, # 每棵树的列数 colsample_bylevel=0.8, #",
"objective='binary:logistic', scale_pos_weight=1, n_jobs=8, seed=0): # seed不能为None \"\"\" https://blog.csdn.net/fuqiuai/article/details/79495910 https://blog.csdn.net/fantacy10000/article/details/84504394 :param objective: 'binary:logistic', 'multi:softmax',",
"string, list of strings or None, optional (default=None) binary: 'auc', 'binary_error', 'binary_logloss' multiclass:",
"= self.params.pop('learning_rate') self.params['alpha'] = self.params.pop('reg_alpha') self.params['lambda'] = self.params.pop('reg_lambda') if self.objective == 'multi:softmax': self.num_class",
"= xgb.DMatrix(X, y, missing=missing) self.objective = objective self.metrics = metrics self.feval = feval",
"CV ...\\n\") try: cv_rst = xgb.cv( self.params, self.data, metrics=self.metrics, feval=self.feval, nfold=nfold, num_boost_round=2500, stratified=False",
"objective=objective, max_depth=7, learning_rate=learning_rate, gamma=0.0, # 描述分裂的最小 gain, 控制树的有用的分裂 min_child_weight=1, # 决定最小叶子节点样本权重和,使一个结点分裂的最小权值之和, 避免过拟合 subsample=0.8,",
"strings or None, optional (default=None) binary: 'auc', 'binary_error', 'binary_logloss' multiclass: 'multi_error', 'multi_logloss' https://lightgbm.readthedocs.io/en/latest/Parameters.html#metric-parameters",
":param feval: def feval(y_pred, y_true): y_true = y_true.get_label() return '1 / (1 +",
"...\\n\") try: cv_rst = xgb.cv( self.params, self.data, metrics=self.metrics, feval=self.feval, nfold=nfold, num_boost_round=2500, stratified=False if",
"feval=None, objective='binary:logistic', scale_pos_weight=1, n_jobs=8, seed=0): # seed不能为None \"\"\" https://blog.csdn.net/fuqiuai/article/details/79495910 https://blog.csdn.net/fantacy10000/article/details/84504394 :param objective: 'binary:logistic',",
"== 'multi:softmax': self.num_class = len(set(y)) self.params['objective'] = self.objective self.params['num_class'] = self.num_class def run(self,",
"\"\"\" self.data = xgb.DMatrix(X, y, missing=missing) self.objective = objective self.metrics = metrics self.feval",
"optional (default=None) binary: 'auc', 'binary_error', 'binary_logloss' multiclass: 'multi_error', 'multi_logloss' https://lightgbm.readthedocs.io/en/latest/Parameters.html#metric-parameters :param feval: def",
"self.best_iter) print('Best Score: %s ' % _[-1]) self.params_sk['n_estimators'] = self.best_iter if return_model: print(\"\\nReturning",
"isinstance(self.metrics, str): _ = cv_rst['test-%s-mean' % self.metrics] self.best_iter = len(_) print('\\nBest Iter: %s'",
"learning_rate=0.01) b_xgb.run() \"\"\" def __init__(self, X, y, learning_rate=0.01, missing=None, metrics='auc', feval=None, objective='binary:logistic', scale_pos_weight=1,",
"label=None, missing=None, feature_types=None)\") if isinstance(self.metrics, str): _ = cv_rst['test-%s-mean' % self.metrics] self.best_iter =",
"n_jobs=8, seed=0): # seed不能为None \"\"\" https://blog.csdn.net/fuqiuai/article/details/79495910 https://blog.csdn.net/fantacy10000/article/details/84504394 :param objective: 'binary:logistic', 'multi:softmax', 'reg:linear' :param",
"learning_rate=learning_rate, gamma=0.0, # 描述分裂的最小 gain, 控制树的有用的分裂 min_child_weight=1, # 决定最小叶子节点样本权重和,使一个结点分裂的最小权值之和, 避免过拟合 subsample=0.8, colsample_bytree=0.8, #",
"as_pandas=False ) except TypeError: print(\"Please: self.xgb_data = xgb.DMatrix(data, label=None, missing=None, feature_types=None)\") if isinstance(self.metrics,",
"% self.metrics] self.best_iter = len(_) print('\\nBest Iter: %s' % self.best_iter) print('Best Score: %s",
"missing=None, feature_types=None)\") if isinstance(self.metrics, str): _ = cv_rst['test-%s-mean' % self.metrics] self.best_iter = len(_)",
"每一层的列数 reg_alpha=0.0, reg_lambda=0.0, scale_pos_weight=scale_pos_weight, random_state=seed, n_jobs=n_jobs, silent=True ) self.params = self.params_sk.copy() self.params['eta'] =",
"except TypeError: print(\"Please: self.xgb_data = xgb.DMatrix(data, label=None, missing=None, feature_types=None)\") if isinstance(self.metrics, str): _",
"print('\\nBest Iter: %s' % self.best_iter) print('Best Score: %s ' % _[-1]) else: _",
"\"\"\" import xgboost as xgb class BaselineXGB(object): \"\"\" 待补充: https://xgboost.readthedocs.io/en/release_0.81/tutorials/feature_interaction_constraint.html 新版xgb支持交叉特征interaction_constraints tree_method='exact' b_xgb",
"待补充: https://xgboost.readthedocs.io/en/release_0.81/tutorials/feature_interaction_constraint.html 新版xgb支持交叉特征interaction_constraints tree_method='exact' b_xgb = BaselineXGB(X, y, learning_rate=0.01) b_xgb.run() \"\"\" def __init__(self,",
"scale_pos_weight: \"\"\" self.data = xgb.DMatrix(X, y, missing=missing) self.objective = objective self.metrics = metrics",
"self.objective self.params['num_class'] = self.num_class def run(self, return_model=False, nfold=5, early_stopping_rounds=100, verbose_eval=50): print(\"XGB CV ...\\n\")",
"https://blog.csdn.net/fantacy10000/article/details/84504394 :param objective: 'binary:logistic', 'multi:softmax', 'reg:linear' :param metrics: string, list of strings or",
"'multi_error', 'multi_logloss' https://lightgbm.readthedocs.io/en/latest/Parameters.html#metric-parameters :param feval: def feval(y_pred, y_true): y_true = y_true.get_label() return '1",
"gamma=0.0, # 描述分裂的最小 gain, 控制树的有用的分裂 min_child_weight=1, # 决定最小叶子节点样本权重和,使一个结点分裂的最小权值之和, 避免过拟合 subsample=0.8, colsample_bytree=0.8, # 每棵树的列数",
"= self.num_class def run(self, return_model=False, nfold=5, early_stopping_rounds=100, verbose_eval=50): print(\"XGB CV ...\\n\") try: cv_rst",
"y_true = y_true.get_label() return '1 / (1 + rmse)', 1 /(rmse(y_true, y_pred) +",
"verbose_eval=verbose_eval, as_pandas=False ) except TypeError: print(\"Please: self.xgb_data = xgb.DMatrix(data, label=None, missing=None, feature_types=None)\") if",
"n_jobs=n_jobs, silent=True ) self.params = self.params_sk.copy() self.params['eta'] = self.params.pop('learning_rate') self.params['alpha'] = self.params.pop('reg_alpha') self.params['lambda']",
"True, early_stopping_rounds=early_stopping_rounds, verbose_eval=verbose_eval, as_pandas=False ) except TypeError: print(\"Please: self.xgb_data = xgb.DMatrix(data, label=None, missing=None,",
"\"\"\" def __init__(self, X, y, learning_rate=0.01, missing=None, metrics='auc', feval=None, objective='binary:logistic', scale_pos_weight=1, n_jobs=8, seed=0):",
"len(_) print('\\nBest Iter: %s' % self.best_iter) print('Best Score: %s ' % _[-1]) else:",
"'multi:softmax', 'reg:linear' :param metrics: string, list of strings or None, optional (default=None) binary:",
"'1 / (1 + rmse)', 1 /(rmse(y_true, y_pred) + 1), True :param scale_pos_weight:",
"coding: utf-8 -*- \"\"\" __title__ = 'xgb' __author__ = 'JieYuan' __mtime__ = '19-1-2'",
"max_depth=7, learning_rate=learning_rate, gamma=0.0, # 描述分裂的最小 gain, 控制树的有用的分裂 min_child_weight=1, # 决定最小叶子节点样本权重和,使一个结点分裂的最小权值之和, 避免过拟合 subsample=0.8, colsample_bytree=0.8,",
"self.num_class = len(set(y)) self.params['objective'] = self.objective self.params['num_class'] = self.num_class def run(self, return_model=False, nfold=5,",
"__title__ = 'xgb' __author__ = 'JieYuan' __mtime__ = '19-1-2' \"\"\" import xgboost as",
"\"\"\" https://blog.csdn.net/fuqiuai/article/details/79495910 https://blog.csdn.net/fantacy10000/article/details/84504394 :param objective: 'binary:logistic', 'multi:softmax', 'reg:linear' :param metrics: string, list of",
"import xgboost as xgb class BaselineXGB(object): \"\"\" 待补充: https://xgboost.readthedocs.io/en/release_0.81/tutorials/feature_interaction_constraint.html 新版xgb支持交叉特征interaction_constraints tree_method='exact' b_xgb =",
"y, missing=missing) self.objective = objective self.metrics = metrics self.feval = feval self.best_iter =",
"= xgb.cv( self.params, self.data, metrics=self.metrics, feval=self.feval, nfold=nfold, num_boost_round=2500, stratified=False if 'reg' in self.objective",
"BaselineXGB(object): \"\"\" 待补充: https://xgboost.readthedocs.io/en/release_0.81/tutorials/feature_interaction_constraint.html 新版xgb支持交叉特征interaction_constraints tree_method='exact' b_xgb = BaselineXGB(X, y, learning_rate=0.01) b_xgb.run() \"\"\"",
"objective self.metrics = metrics self.feval = feval self.best_iter = None # sklearn params",
"utf-8 -*- \"\"\" __title__ = 'xgb' __author__ = 'JieYuan' __mtime__ = '19-1-2' \"\"\"",
"-*- coding: utf-8 -*- \"\"\" __title__ = 'xgb' __author__ = 'JieYuan' __mtime__ =",
"scale_pos_weight=1, n_jobs=8, seed=0): # seed不能为None \"\"\" https://blog.csdn.net/fuqiuai/article/details/79495910 https://blog.csdn.net/fantacy10000/article/details/84504394 :param objective: 'binary:logistic', 'multi:softmax', 'reg:linear'",
"self.objective else True, early_stopping_rounds=early_stopping_rounds, verbose_eval=verbose_eval, as_pandas=False ) except TypeError: print(\"Please: self.xgb_data = xgb.DMatrix(data,",
"early_stopping_rounds=100, verbose_eval=50): print(\"XGB CV ...\\n\") try: cv_rst = xgb.cv( self.params, self.data, metrics=self.metrics, feval=self.feval,",
"booster='gbtree', objective=objective, max_depth=7, learning_rate=learning_rate, gamma=0.0, # 描述分裂的最小 gain, 控制树的有用的分裂 min_child_weight=1, # 决定最小叶子节点样本权重和,使一个结点分裂的最小权值之和, 避免过拟合",
"silent=True ) self.params = self.params_sk.copy() self.params['eta'] = self.params.pop('learning_rate') self.params['alpha'] = self.params.pop('reg_alpha') self.params['lambda'] =",
"(default=None) binary: 'auc', 'binary_error', 'binary_logloss' multiclass: 'multi_error', 'multi_logloss' https://lightgbm.readthedocs.io/en/latest/Parameters.html#metric-parameters :param feval: def feval(y_pred,",
"\"\"\" 待补充: https://xgboost.readthedocs.io/en/release_0.81/tutorials/feature_interaction_constraint.html 新版xgb支持交叉特征interaction_constraints tree_method='exact' b_xgb = BaselineXGB(X, y, learning_rate=0.01) b_xgb.run() \"\"\" def",
"seed不能为None \"\"\" https://blog.csdn.net/fuqiuai/article/details/79495910 https://blog.csdn.net/fantacy10000/article/details/84504394 :param objective: 'binary:logistic', 'multi:softmax', 'reg:linear' :param metrics: string, list",
") except TypeError: print(\"Please: self.xgb_data = xgb.DMatrix(data, label=None, missing=None, feature_types=None)\") if isinstance(self.metrics, str):",
"%s ' % _[-1]) self.params_sk['n_estimators'] = self.best_iter if return_model: print(\"\\nReturning Model ...\\n\") return",
":param scale_pos_weight: \"\"\" self.data = xgb.DMatrix(X, y, missing=missing) self.objective = objective self.metrics =",
"y, learning_rate=0.01) b_xgb.run() \"\"\" def __init__(self, X, y, learning_rate=0.01, missing=None, metrics='auc', feval=None, objective='binary:logistic',",
"避免过拟合 subsample=0.8, colsample_bytree=0.8, # 每棵树的列数 colsample_bylevel=0.8, # 每一层的列数 reg_alpha=0.0, reg_lambda=0.0, scale_pos_weight=scale_pos_weight, random_state=seed, n_jobs=n_jobs,",
"class BaselineXGB(object): \"\"\" 待补充: https://xgboost.readthedocs.io/en/release_0.81/tutorials/feature_interaction_constraint.html 新版xgb支持交叉特征interaction_constraints tree_method='exact' b_xgb = BaselineXGB(X, y, learning_rate=0.01) b_xgb.run()",
"Score: %s ' % _[-1]) self.params_sk['n_estimators'] = self.best_iter if return_model: print(\"\\nReturning Model ...\\n\")",
"-*- \"\"\" __title__ = 'xgb' __author__ = 'JieYuan' __mtime__ = '19-1-2' \"\"\" import",
"X, y, learning_rate=0.01, missing=None, metrics='auc', feval=None, objective='binary:logistic', scale_pos_weight=1, n_jobs=8, seed=0): # seed不能为None \"\"\"",
"# 每棵树的列数 colsample_bylevel=0.8, # 每一层的列数 reg_alpha=0.0, reg_lambda=0.0, scale_pos_weight=scale_pos_weight, random_state=seed, n_jobs=n_jobs, silent=True ) self.params",
"self.objective == 'multi:softmax': self.num_class = len(set(y)) self.params['objective'] = self.objective self.params['num_class'] = self.num_class def",
"metrics=self.metrics, feval=self.feval, nfold=nfold, num_boost_round=2500, stratified=False if 'reg' in self.objective else True, early_stopping_rounds=early_stopping_rounds, verbose_eval=verbose_eval,",
"self.params.pop('reg_alpha') self.params['lambda'] = self.params.pop('reg_lambda') if self.objective == 'multi:softmax': self.num_class = len(set(y)) self.params['objective'] =",
"_[-1]) self.params_sk['n_estimators'] = self.best_iter if return_model: print(\"\\nReturning Model ...\\n\") return xgb.train(self.params, self.data, self.best_iter)",
"= cv_rst['test-%s-mean' % self.metrics] self.best_iter = len(_) print('\\nBest Iter: %s' % self.best_iter) print('Best",
"feval=self.feval, nfold=nfold, num_boost_round=2500, stratified=False if 'reg' in self.objective else True, early_stopping_rounds=early_stopping_rounds, verbose_eval=verbose_eval, as_pandas=False",
"self.params['lambda'] = self.params.pop('reg_lambda') if self.objective == 'multi:softmax': self.num_class = len(set(y)) self.params['objective'] = self.objective",
"b_xgb = BaselineXGB(X, y, learning_rate=0.01) b_xgb.run() \"\"\" def __init__(self, X, y, learning_rate=0.01, missing=None,",
"def feval(y_pred, y_true): y_true = y_true.get_label() return '1 / (1 + rmse)', 1",
"self.best_iter) print('Best Score: %s ' % _[-1]) else: _ = cv_rst['test-%s-mean' % self.metrics]",
"'binary_error', 'binary_logloss' multiclass: 'multi_error', 'multi_logloss' https://lightgbm.readthedocs.io/en/latest/Parameters.html#metric-parameters :param feval: def feval(y_pred, y_true): y_true =",
"multiclass: 'multi_error', 'multi_logloss' https://lightgbm.readthedocs.io/en/latest/Parameters.html#metric-parameters :param feval: def feval(y_pred, y_true): y_true = y_true.get_label() return",
"dict( booster='gbtree', objective=objective, max_depth=7, learning_rate=learning_rate, gamma=0.0, # 描述分裂的最小 gain, 控制树的有用的分裂 min_child_weight=1, # 决定最小叶子节点样本权重和,使一个结点分裂的最小权值之和,",
"try: cv_rst = xgb.cv( self.params, self.data, metrics=self.metrics, feval=self.feval, nfold=nfold, num_boost_round=2500, stratified=False if 'reg'",
"/ (1 + rmse)', 1 /(rmse(y_true, y_pred) + 1), True :param scale_pos_weight: \"\"\"",
"= dict( booster='gbtree', objective=objective, max_depth=7, learning_rate=learning_rate, gamma=0.0, # 描述分裂的最小 gain, 控制树的有用的分裂 min_child_weight=1, #",
"stratified=False if 'reg' in self.objective else True, early_stopping_rounds=early_stopping_rounds, verbose_eval=verbose_eval, as_pandas=False ) except TypeError:",
"= self.objective self.params['num_class'] = self.num_class def run(self, return_model=False, nfold=5, early_stopping_rounds=100, verbose_eval=50): print(\"XGB CV",
"%s' % self.best_iter) print('Best Score: %s ' % _[-1]) self.params_sk['n_estimators'] = self.best_iter if",
"objective: 'binary:logistic', 'multi:softmax', 'reg:linear' :param metrics: string, list of strings or None, optional",
"= feval self.best_iter = None # sklearn params self.params_sk = dict( booster='gbtree', objective=objective,",
"= len(set(y)) self.params['objective'] = self.objective self.params['num_class'] = self.num_class def run(self, return_model=False, nfold=5, early_stopping_rounds=100,",
"verbose_eval=50): print(\"XGB CV ...\\n\") try: cv_rst = xgb.cv( self.params, self.data, metrics=self.metrics, feval=self.feval, nfold=nfold,",
"1), True :param scale_pos_weight: \"\"\" self.data = xgb.DMatrix(X, y, missing=missing) self.objective = objective",
"binary: 'auc', 'binary_error', 'binary_logloss' multiclass: 'multi_error', 'multi_logloss' https://lightgbm.readthedocs.io/en/latest/Parameters.html#metric-parameters :param feval: def feval(y_pred, y_true):",
"scale_pos_weight=scale_pos_weight, random_state=seed, n_jobs=n_jobs, silent=True ) self.params = self.params_sk.copy() self.params['eta'] = self.params.pop('learning_rate') self.params['alpha'] =",
"in self.objective else True, early_stopping_rounds=early_stopping_rounds, verbose_eval=verbose_eval, as_pandas=False ) except TypeError: print(\"Please: self.xgb_data =",
"= objective self.metrics = metrics self.feval = feval self.best_iter = None # sklearn",
"early_stopping_rounds=early_stopping_rounds, verbose_eval=verbose_eval, as_pandas=False ) except TypeError: print(\"Please: self.xgb_data = xgb.DMatrix(data, label=None, missing=None, feature_types=None)\")",
"y_true): y_true = y_true.get_label() return '1 / (1 + rmse)', 1 /(rmse(y_true, y_pred)",
"learning_rate=0.01, missing=None, metrics='auc', feval=None, objective='binary:logistic', scale_pos_weight=1, n_jobs=8, seed=0): # seed不能为None \"\"\" https://blog.csdn.net/fuqiuai/article/details/79495910 https://blog.csdn.net/fantacy10000/article/details/84504394",
"'reg' in self.objective else True, early_stopping_rounds=early_stopping_rounds, verbose_eval=verbose_eval, as_pandas=False ) except TypeError: print(\"Please: self.xgb_data",
"BaselineXGB(X, y, learning_rate=0.01) b_xgb.run() \"\"\" def __init__(self, X, y, learning_rate=0.01, missing=None, metrics='auc', feval=None,",
"gain, 控制树的有用的分裂 min_child_weight=1, # 决定最小叶子节点样本权重和,使一个结点分裂的最小权值之和, 避免过拟合 subsample=0.8, colsample_bytree=0.8, # 每棵树的列数 colsample_bylevel=0.8, # 每一层的列数",
"Iter: %s' % self.best_iter) print('Best Score: %s ' % _[-1]) self.params_sk['n_estimators'] = self.best_iter",
"True :param scale_pos_weight: \"\"\" self.data = xgb.DMatrix(X, y, missing=missing) self.objective = objective self.metrics",
"= None # sklearn params self.params_sk = dict( booster='gbtree', objective=objective, max_depth=7, learning_rate=learning_rate, gamma=0.0,",
"metrics: string, list of strings or None, optional (default=None) binary: 'auc', 'binary_error', 'binary_logloss'",
"print(\"XGB CV ...\\n\") try: cv_rst = xgb.cv( self.params, self.data, metrics=self.metrics, feval=self.feval, nfold=nfold, num_boost_round=2500,",
"self.params_sk = dict( booster='gbtree', objective=objective, max_depth=7, learning_rate=learning_rate, gamma=0.0, # 描述分裂的最小 gain, 控制树的有用的分裂 min_child_weight=1,",
"nfold=5, early_stopping_rounds=100, verbose_eval=50): print(\"XGB CV ...\\n\") try: cv_rst = xgb.cv( self.params, self.data, metrics=self.metrics,",
"= 'xgb' __author__ = 'JieYuan' __mtime__ = '19-1-2' \"\"\" import xgboost as xgb",
"missing=None, metrics='auc', feval=None, objective='binary:logistic', scale_pos_weight=1, n_jobs=8, seed=0): # seed不能为None \"\"\" https://blog.csdn.net/fuqiuai/article/details/79495910 https://blog.csdn.net/fantacy10000/article/details/84504394 :param",
"'multi_logloss' https://lightgbm.readthedocs.io/en/latest/Parameters.html#metric-parameters :param feval: def feval(y_pred, y_true): y_true = y_true.get_label() return '1 /",
"self.best_iter = len(_) print('\\nBest Iter: %s' % self.best_iter) print('Best Score: %s ' %",
"feval self.best_iter = None # sklearn params self.params_sk = dict( booster='gbtree', objective=objective, max_depth=7,",
"self.params, self.data, metrics=self.metrics, feval=self.feval, nfold=nfold, num_boost_round=2500, stratified=False if 'reg' in self.objective else True,",
"self.params['objective'] = self.objective self.params['num_class'] = self.num_class def run(self, return_model=False, nfold=5, early_stopping_rounds=100, verbose_eval=50): print(\"XGB",
"self.metrics] self.best_iter = len(_) print('\\nBest Iter: %s' % self.best_iter) print('Best Score: %s '",
"def run(self, return_model=False, nfold=5, early_stopping_rounds=100, verbose_eval=50): print(\"XGB CV ...\\n\") try: cv_rst = xgb.cv(",
"as xgb class BaselineXGB(object): \"\"\" 待补充: https://xgboost.readthedocs.io/en/release_0.81/tutorials/feature_interaction_constraint.html 新版xgb支持交叉特征interaction_constraints tree_method='exact' b_xgb = BaselineXGB(X, y,",
"self.feval = feval self.best_iter = None # sklearn params self.params_sk = dict( booster='gbtree',",
"self.best_iter = None # sklearn params self.params_sk = dict( booster='gbtree', objective=objective, max_depth=7, learning_rate=learning_rate,",
"= xgb.DMatrix(data, label=None, missing=None, feature_types=None)\") if isinstance(self.metrics, str): _ = cv_rst['test-%s-mean' % self.metrics]",
"__author__ = 'JieYuan' __mtime__ = '19-1-2' \"\"\" import xgboost as xgb class BaselineXGB(object):",
"= 'JieYuan' __mtime__ = '19-1-2' \"\"\" import xgboost as xgb class BaselineXGB(object): \"\"\"",
"return_model=False, nfold=5, early_stopping_rounds=100, verbose_eval=50): print(\"XGB CV ...\\n\") try: cv_rst = xgb.cv( self.params, self.data,",
"+ rmse)', 1 /(rmse(y_true, y_pred) + 1), True :param scale_pos_weight: \"\"\" self.data =",
"metrics self.feval = feval self.best_iter = None # sklearn params self.params_sk = dict(",
"def __init__(self, X, y, learning_rate=0.01, missing=None, metrics='auc', feval=None, objective='binary:logistic', scale_pos_weight=1, n_jobs=8, seed=0): #",
"'xgb' __author__ = 'JieYuan' __mtime__ = '19-1-2' \"\"\" import xgboost as xgb class",
"Score: %s ' % _[-1]) else: _ = cv_rst['test-%s-mean' % self.metrics] self.best_iter =",
"https://lightgbm.readthedocs.io/en/latest/Parameters.html#metric-parameters :param feval: def feval(y_pred, y_true): y_true = y_true.get_label() return '1 / (1",
"xgb.DMatrix(X, y, missing=missing) self.objective = objective self.metrics = metrics self.feval = feval self.best_iter",
"print('Best Score: %s ' % _[-1]) self.params_sk['n_estimators'] = self.best_iter if return_model: print(\"\\nReturning Model",
"None, optional (default=None) binary: 'auc', 'binary_error', 'binary_logloss' multiclass: 'multi_error', 'multi_logloss' https://lightgbm.readthedocs.io/en/latest/Parameters.html#metric-parameters :param feval:",
"self.params.pop('reg_lambda') if self.objective == 'multi:softmax': self.num_class = len(set(y)) self.params['objective'] = self.objective self.params['num_class'] =",
"% _[-1]) else: _ = cv_rst['test-%s-mean' % self.metrics] self.best_iter = len(_) print('\\nBest Iter:",
"% _[-1]) self.params_sk['n_estimators'] = self.best_iter if return_model: print(\"\\nReturning Model ...\\n\") return xgb.train(self.params, self.data,",
"seed=0): # seed不能为None \"\"\" https://blog.csdn.net/fuqiuai/article/details/79495910 https://blog.csdn.net/fantacy10000/article/details/84504394 :param objective: 'binary:logistic', 'multi:softmax', 'reg:linear' :param metrics:",
"= self.params.pop('reg_lambda') if self.objective == 'multi:softmax': self.num_class = len(set(y)) self.params['objective'] = self.objective self.params['num_class']",
"if self.objective == 'multi:softmax': self.num_class = len(set(y)) self.params['objective'] = self.objective self.params['num_class'] = self.num_class",
"self.params = self.params_sk.copy() self.params['eta'] = self.params.pop('learning_rate') self.params['alpha'] = self.params.pop('reg_alpha') self.params['lambda'] = self.params.pop('reg_lambda') if",
"https://blog.csdn.net/fuqiuai/article/details/79495910 https://blog.csdn.net/fantacy10000/article/details/84504394 :param objective: 'binary:logistic', 'multi:softmax', 'reg:linear' :param metrics: string, list of strings",
"self.xgb_data = xgb.DMatrix(data, label=None, missing=None, feature_types=None)\") if isinstance(self.metrics, str): _ = cv_rst['test-%s-mean' %",
"len(_) print('\\nBest Iter: %s' % self.best_iter) print('Best Score: %s ' % _[-1]) self.params_sk['n_estimators']",
"每棵树的列数 colsample_bylevel=0.8, # 每一层的列数 reg_alpha=0.0, reg_lambda=0.0, scale_pos_weight=scale_pos_weight, random_state=seed, n_jobs=n_jobs, silent=True ) self.params =",
"'19-1-2' \"\"\" import xgboost as xgb class BaselineXGB(object): \"\"\" 待补充: https://xgboost.readthedocs.io/en/release_0.81/tutorials/feature_interaction_constraint.html 新版xgb支持交叉特征interaction_constraints tree_method='exact'",
"self.data, metrics=self.metrics, feval=self.feval, nfold=nfold, num_boost_round=2500, stratified=False if 'reg' in self.objective else True, early_stopping_rounds=early_stopping_rounds,",
"新版xgb支持交叉特征interaction_constraints tree_method='exact' b_xgb = BaselineXGB(X, y, learning_rate=0.01) b_xgb.run() \"\"\" def __init__(self, X, y,"
] |
[
"9.01218, 5: 10.806, 6: 12.0096, 7: 14.00643, 8: 15.99903, 9: 18.998403, 10: 20.1797,",
"'H', 2: 'He', 3: 'Li', 4: 'Be', 5: 'B', 6: 'C', 7: 'N',",
"# all values in Angstrom VDWRADII = {0: 0.00, 1: 1.20, 2: 1.43,",
"in Angstrom VDWRADII = {0: 0.00, 1: 1.20, 2: 1.43, 3: 2.12, 4:",
"3: 1.33, 4: 1.02, 5: 0.85, 6: 0.75, 7: 0.71, 8: 0.63, 9:",
"all values in Angstrom VDWRADII = {0: 0.00, 1: 1.20, 2: 1.43, 3:",
"16: 'S', 17: 'Cl', 18: 'Ar' } # converts an atomic label to",
"1.33, 4: 1.02, 5: 0.85, 6: 0.75, 7: 0.71, 8: 0.63, 9: 0.64,",
"value > v: idx = i v = value return idx def idamin(a):",
"10: 1, 11: 1, 12: 2, 13: 3, 14: 4, 15: 3, 16:",
"from Pykko and Atsumi (2009), DOI: 0.1002/chem.200800987 # all values in Angstrom COVALENTRADII",
"idx = i v = value return idx def idamin(a): \"\"\" Returns the",
"1, 10: 1, 11: 1, 12: 2, 13: 3, 14: 4, 15: 3,",
"5: 0.85, 6: 0.75, 7: 0.71, 8: 0.63, 9: 0.64, 10: 0.67, 11:",
"'He', 3: 'Li', 4: 'Be', 5: 'B', 6: 'C', 7: 'N', 8: 'O',",
"28.084, 15: 30.973, 16: 32.059, 17: 35.446, 18: 39.948 } # <NAME>al radii",
"GAMESS with the same name Arguments: a -- a numpy array where we",
"absolute value (positive or negative) in the input array a. Note: Loosely based",
"numpy array where we are to find the maximum value in (either positive",
"we are to find the maximum value in (either positive or negative) Returns:",
"def idamin(a): \"\"\" Returns the index of minimum absolute value (positive or negative)",
"0.75, 7: 0.71, 8: 0.63, 9: 0.64, 10: 0.67, 11: 1.55, 12: 1.39,",
"4: 1.02, 5: 0.85, 6: 0.75, 7: 0.71, 8: 0.63, 9: 0.64, 10:",
"9: 0.64, 10: 0.67, 11: 1.55, 12: 1.39, 13: 1.26, 14: 1.16, 15:",
"18: 'Ar' } # converts an atomic label to a nuclear charge LABEL2Z",
"input array a. Arguments: a -- a numpy array where we are to",
"1.91, 6: 1.77, 7: 1.66, 8: 1.50, 9: 1.46, 10: 1.58, 11: 2.50,",
"10: 'Ne', 11: 'NA', 12: 'Mg', 13: 'Al', 14: 'Si', 15: 'P', 16:",
"Coordination numbers from Pykko and Atsumi (2009), DOI: 0.1002/chem.200800987 COORDINATION = {0: 0,",
"3, 16: 2, 17: 1, 18: 1 } def idamax(a): \"\"\" Returns the",
"2: 0.46, 3: 1.33, 4: 1.02, 5: 0.85, 6: 0.75, 7: 0.71, 8:",
"1.90, 16: 1.89, 17: 1.82, 18: 1.83 } # Covalent radii from Pykko",
"for i, value in enumerate(numpy.abs(a)): if value > v: idx = i v",
"i, value in enumerate(numpy.abs(a)): if value > v: idx = i v =",
"18.998403, 10: 20.1797, 11: 22.9898, 12: 24.304, 13: 26.9815, 14: 28.084, 15: 30.973,",
"of a subroutine in GAMESS with the same name Arguments: a -- a",
"i, value in enumerate(numpy.abs(a)): if value < v: idx = i v =",
"key # masses from UIPAC: http://www.chem.qmul.ac.uk/iupac/AtWt/ MASSES = {0: 0.00, 1: 1.00784, 2:",
"20.1797, 11: 22.9898, 12: 24.304, 13: 26.9815, 14: 28.084, 15: 30.973, 16: 32.059,",
"3: 2.12, 4: 1.98, 5: 1.91, 6: 1.77, 7: 1.66, 8: 1.50, 9:",
"Atsumi (2009), DOI: 0.1002/chem.200800987 COORDINATION = {0: 0, 1: 1, 2: 1, 3:",
"nuclear charge to atom label Z2LABEL = { 1: 'H', 2: 'He', 3:",
"8: 0.63, 9: 0.64, 10: 0.67, 11: 1.55, 12: 1.39, 13: 1.26, 14:",
"0.00, 1: 1.00784, 2: 4.002602, 3: 6.938, 4: 9.01218, 5: 10.806, 6: 12.0096,",
"{0: 0, 1: 1, 2: 1, 3: 1, 4: 2, 5: 3, 6:",
"a nuclear charge LABEL2Z = {} for key in Z2LABEL: LABEL2Z[Z2LABEL[key]] = key",
"} def idamax(a): \"\"\" Returns the index of maximum absolute value (positive or",
"find the maximum value in (either positive or negative) Returns: the index in",
"same name Arguments: a -- a numpy array where we are to find",
"14: 2.19, 15: 1.90, 16: 1.89, 17: 1.82, 18: 1.83 } # Covalent",
"1.16, 15: 1.11, 16: 1.03, 17: 0.99, 18: 0.96 } # Coordination numbers",
"label Z2LABEL = { 1: 'H', 2: 'He', 3: 'Li', 4: 'Be', 5:",
"14: 'Si', 15: 'P', 16: 'S', 17: 'Cl', 18: 'Ar' } # converts",
"a numpy array where we are to find the minimum value in (either",
"maximum value is. \"\"\" idx = -1 v = 1.0e30 for i, value",
"'B', 6: 'C', 7: 'N', 8: 'O', 9: 'F', 10: 'Ne', 11: 'NA',",
"in the input array a. Arguments: a -- a numpy array where we",
"8: 1.50, 9: 1.46, 10: 1.58, 11: 2.50, 12: 2.51, 13: 2.25, 14:",
"in GAMESS with the same name Arguments: a -- a numpy array where",
"'C', 7: 'N', 8: 'O', 9: 'F', 10: 'Ne', 11: 'NA', 12: 'Mg',",
"9: 18.998403, 10: 20.1797, 11: 22.9898, 12: 24.304, 13: 26.9815, 14: 28.084, 15:",
"0.99, 18: 0.96 } # Coordination numbers from Pykko and Atsumi (2009), DOI:",
"'P', 16: 'S', 17: 'Cl', 18: 'Ar' } # converts an atomic label",
"30.973, 16: 32.059, 17: 35.446, 18: 39.948 } # <NAME>al radii from Alvarez",
"1: 1, 2: 1, 3: 1, 4: 2, 5: 3, 6: 4, 7:",
"1.50, 9: 1.46, 10: 1.58, 11: 2.50, 12: 2.51, 13: 2.25, 14: 2.19,",
"the minimum value in (either positive or negative) Returns: the index in the",
"1.55, 12: 1.39, 13: 1.26, 14: 1.16, 15: 1.11, 16: 1.03, 17: 0.99,",
"charge to atom label Z2LABEL = { 1: 'H', 2: 'He', 3: 'Li',",
"import numpy \"\"\" Utility variables and functions \"\"\" aa2au = 1.8897261249935897 # bohr",
"5: 1.91, 6: 1.77, 7: 1.66, 8: 1.50, 9: 1.46, 10: 1.58, 11:",
"3, 6: 4, 7: 3, 8: 2, 9: 1, 10: 1, 11: 1,",
"4: 1.98, 5: 1.91, 6: 1.77, 7: 1.66, 8: 1.50, 9: 1.46, 10:",
"minimum absolute value (positive or negative) in the input array a. Arguments: a",
"a. Arguments: a -- a numpy array where we are to find the",
"{} for key in Z2LABEL: LABEL2Z[Z2LABEL[key]] = key # masses from UIPAC: http://www.chem.qmul.ac.uk/iupac/AtWt/",
"= {0: 0.00, 1: 1.20, 2: 1.43, 3: 2.12, 4: 1.98, 5: 1.91,",
"0, 1: 1, 2: 1, 3: 1, 4: 2, 5: 3, 6: 4,",
"return idx def idamin(a): \"\"\" Returns the index of minimum absolute value (positive",
"find the minimum value in (either positive or negative) Returns: the index in",
"= {0: 0.00, 1: 1.00784, 2: 4.002602, 3: 6.938, 4: 9.01218, 5: 10.806,",
"9: 'F', 10: 'Ne', 11: 'NA', 12: 'Mg', 13: 'Al', 14: 'Si', 15:",
"{ 1: 'H', 2: 'He', 3: 'Li', 4: 'Be', 5: 'B', 6: 'C',",
"1.77, 7: 1.66, 8: 1.50, 9: 1.46, 10: 1.58, 11: 2.50, 12: 2.51,",
"masses from UIPAC: http://www.chem.qmul.ac.uk/iupac/AtWt/ MASSES = {0: 0.00, 1: 1.00784, 2: 4.002602, 3:",
"'N', 8: 'O', 9: 'F', 10: 'Ne', 11: 'NA', 12: 'Mg', 13: 'Al',",
"array where we are to find the minimum value in (either positive or",
"to atom label Z2LABEL = { 1: 'H', 2: 'He', 3: 'Li', 4:",
"in Z2LABEL: LABEL2Z[Z2LABEL[key]] = key # masses from UIPAC: http://www.chem.qmul.ac.uk/iupac/AtWt/ MASSES = {0:",
"18: 39.948 } # <NAME>al radii from Alvarez (2013), DOI: 2013/dt/c3dt50599e # all",
"where the maximum value is. \"\"\" idx = -1 v = 0.0 for",
"Pykko and Atsumi (2009), DOI: 0.1002/chem.200800987 # all values in Angstrom COVALENTRADII =",
"8: 2, 9: 1, 10: 1, 11: 1, 12: 2, 13: 3, 14:",
"are to find the maximum value in (either positive or negative) Returns: the",
"\"\"\" aa2au = 1.8897261249935897 # bohr / AA # converts nuclear charge to",
"2013/dt/c3dt50599e # all values in Angstrom VDWRADII = {0: 0.00, 1: 1.20, 2:",
"UIPAC: http://www.chem.qmul.ac.uk/iupac/AtWt/ MASSES = {0: 0.00, 1: 1.00784, 2: 4.002602, 3: 6.938, 4:",
"24.304, 13: 26.9815, 14: 28.084, 15: 30.973, 16: 32.059, 17: 35.446, 18: 39.948",
"0.0 for i, value in enumerate(numpy.abs(a)): if value > v: idx = i",
"} # <NAME>al radii from Alvarez (2013), DOI: 2013/dt/c3dt50599e # all values in",
"Utility variables and functions \"\"\" aa2au = 1.8897261249935897 # bohr / AA #",
"5: 'B', 6: 'C', 7: 'N', 8: 'O', 9: 'F', 10: 'Ne', 11:",
"LABEL2Z = {} for key in Z2LABEL: LABEL2Z[Z2LABEL[key]] = key # masses from",
"1: 'H', 2: 'He', 3: 'Li', 4: 'Be', 5: 'B', 6: 'C', 7:",
"7: 3, 8: 2, 9: 1, 10: 1, 11: 1, 12: 2, 13:",
"6.938, 4: 9.01218, 5: 10.806, 6: 12.0096, 7: 14.00643, 8: 15.99903, 9: 18.998403,",
"1.02, 5: 0.85, 6: 0.75, 7: 0.71, 8: 0.63, 9: 0.64, 10: 0.67,",
"1.39, 13: 1.26, 14: 1.16, 15: 1.11, 16: 1.03, 17: 0.99, 18: 0.96",
"index in the array where the maximum value is. \"\"\" idx = -1",
"array a. Note: Loosely based of a subroutine in GAMESS with the same",
"and Atsumi (2009), DOI: 0.1002/chem.200800987 # all values in Angstrom COVALENTRADII = {0:",
"value (positive or negative) in the input array a. Arguments: a -- a",
"nuclear charge LABEL2Z = {} for key in Z2LABEL: LABEL2Z[Z2LABEL[key]] = key #",
"22.9898, 12: 24.304, 13: 26.9815, 14: 28.084, 15: 30.973, 16: 32.059, 17: 35.446,",
"numbers from Pykko and Atsumi (2009), DOI: 0.1002/chem.200800987 COORDINATION = {0: 0, 1:",
"15: 3, 16: 2, 17: 1, 18: 1 } def idamax(a): \"\"\" Returns",
"in the array where the maximum value is. \"\"\" idx = -1 v",
"Atsumi (2009), DOI: 0.1002/chem.200800987 # all values in Angstrom COVALENTRADII = {0: 0.00,",
"numpy array where we are to find the minimum value in (either positive",
"array where we are to find the maximum value in (either positive or",
"0.00, 1: 1.20, 2: 1.43, 3: 2.12, 4: 1.98, 5: 1.91, 6: 1.77,",
"16: 1.89, 17: 1.82, 18: 1.83 } # Covalent radii from Pykko and",
"value in enumerate(numpy.abs(a)): if value > v: idx = i v = value",
"3: 6.938, 4: 9.01218, 5: 10.806, 6: 12.0096, 7: 14.00643, 8: 15.99903, 9:",
"bohr / AA # converts nuclear charge to atom label Z2LABEL = {",
"9: 1, 10: 1, 11: 1, 12: 2, 13: 3, 14: 4, 15:",
"18: 1 } def idamax(a): \"\"\" Returns the index of maximum absolute value",
"of maximum absolute value (positive or negative) in the input array a. Note:",
"2, 9: 1, 10: 1, 11: 1, 12: 2, 13: 3, 14: 4,",
"1.03, 17: 0.99, 18: 0.96 } # Coordination numbers from Pykko and Atsumi",
"is. \"\"\" idx = -1 v = 1.0e30 for i, value in enumerate(numpy.abs(a)):",
"where the maximum value is. \"\"\" idx = -1 v = 1.0e30 for",
"# <NAME>al radii from Alvarez (2013), DOI: 2013/dt/c3dt50599e # all values in Angstrom",
"\"\"\" idx = -1 v = 0.0 for i, value in enumerate(numpy.abs(a)): if",
"Note: Loosely based of a subroutine in GAMESS with the same name Arguments:",
"if value > v: idx = i v = value return idx def",
"9: 1.46, 10: 1.58, 11: 2.50, 12: 2.51, 13: 2.25, 14: 2.19, 15:",
"17: 1, 18: 1 } def idamax(a): \"\"\" Returns the index of maximum",
"{0: 0.00, 1: 1.20, 2: 1.43, 3: 2.12, 4: 1.98, 5: 1.91, 6:",
"<NAME>al radii from Alvarez (2013), DOI: 2013/dt/c3dt50599e # all values in Angstrom VDWRADII",
"and Atsumi (2009), DOI: 0.1002/chem.200800987 COORDINATION = {0: 0, 1: 1, 2: 1,",
"a numpy array where we are to find the maximum value in (either",
"39.948 } # <NAME>al radii from Alvarez (2013), DOI: 2013/dt/c3dt50599e # all values",
"16: 1.03, 17: 0.99, 18: 0.96 } # Coordination numbers from Pykko and",
"negative) Returns: the index in the array where the maximum value is. \"\"\"",
"14: 1.16, 15: 1.11, 16: 1.03, 17: 0.99, 18: 0.96 } # Coordination",
"AA # converts nuclear charge to atom label Z2LABEL = { 1: 'H',",
"0.64, 10: 0.67, 11: 1.55, 12: 1.39, 13: 1.26, 14: 1.16, 15: 1.11,",
"1.66, 8: 1.50, 9: 1.46, 10: 1.58, 11: 2.50, 12: 2.51, 13: 2.25,",
"from UIPAC: http://www.chem.qmul.ac.uk/iupac/AtWt/ MASSES = {0: 0.00, 1: 1.00784, 2: 4.002602, 3: 6.938,",
"17: 1.82, 18: 1.83 } # Covalent radii from Pykko and Atsumi (2009),",
"= {0: 0, 1: 1, 2: 1, 3: 1, 4: 2, 5: 3,",
"32.059, 17: 35.446, 18: 39.948 } # <NAME>al radii from Alvarez (2013), DOI:",
"the array where the maximum value is. \"\"\" idx = -1 v =",
"an atomic label to a nuclear charge LABEL2Z = {} for key in",
"name Arguments: a -- a numpy array where we are to find the",
"# converts an atomic label to a nuclear charge LABEL2Z = {} for",
"from Alvarez (2013), DOI: 2013/dt/c3dt50599e # all values in Angstrom VDWRADII = {0:",
"1, 12: 2, 13: 3, 14: 4, 15: 3, 16: 2, 17: 1,",
"def idamax(a): \"\"\" Returns the index of maximum absolute value (positive or negative)",
"converts an atomic label to a nuclear charge LABEL2Z = {} for key",
"and functions \"\"\" aa2au = 1.8897261249935897 # bohr / AA # converts nuclear",
"-- a numpy array where we are to find the minimum value in",
"value return idx def idamin(a): \"\"\" Returns the index of minimum absolute value",
"1.43, 3: 2.12, 4: 1.98, 5: 1.91, 6: 1.77, 7: 1.66, 8: 1.50,",
"0.67, 11: 1.55, 12: 1.39, 13: 1.26, 14: 1.16, 15: 1.11, 16: 1.03,",
"Returns the index of minimum absolute value (positive or negative) in the input",
"the maximum value in (either positive or negative) Returns: the index in the",
"17: 0.99, 18: 0.96 } # Coordination numbers from Pykko and Atsumi (2009),",
"= -1 v = 0.0 for i, value in enumerate(numpy.abs(a)): if value >",
"the maximum value is. \"\"\" idx = -1 v = 0.0 for i,",
"8: 15.99903, 9: 18.998403, 10: 20.1797, 11: 22.9898, 12: 24.304, 13: 26.9815, 14:",
"array where the maximum value is. \"\"\" idx = -1 v = 1.0e30",
"= 1.0e30 for i, value in enumerate(numpy.abs(a)): if value < v: idx =",
"# masses from UIPAC: http://www.chem.qmul.ac.uk/iupac/AtWt/ MASSES = {0: 0.00, 1: 1.00784, 2: 4.002602,",
"or negative) in the input array a. Note: Loosely based of a subroutine",
"15.99903, 9: 18.998403, 10: 20.1797, 11: 22.9898, 12: 24.304, 13: 26.9815, 14: 28.084,",
"negative) in the input array a. Note: Loosely based of a subroutine in",
"'Cl', 18: 'Ar' } # converts an atomic label to a nuclear charge",
"Covalent radii from Pykko and Atsumi (2009), DOI: 0.1002/chem.200800987 # all values in",
"where we are to find the maximum value in (either positive or negative)",
"(either positive or negative) Returns: the index in the array where the maximum",
"8: 'O', 9: 'F', 10: 'Ne', 11: 'NA', 12: 'Mg', 13: 'Al', 14:",
"'Mg', 13: 'Al', 14: 'Si', 15: 'P', 16: 'S', 17: 'Cl', 18: 'Ar'",
"in enumerate(numpy.abs(a)): if value < v: idx = i v = value return",
"idamin(a): \"\"\" Returns the index of minimum absolute value (positive or negative) in",
"6: 'C', 7: 'N', 8: 'O', 9: 'F', 10: 'Ne', 11: 'NA', 12:",
"1.98, 5: 1.91, 6: 1.77, 7: 1.66, 8: 1.50, 9: 1.46, 10: 1.58,",
"a -- a numpy array where we are to find the minimum value",
"functions \"\"\" aa2au = 1.8897261249935897 # bohr / AA # converts nuclear charge",
"12: 'Mg', 13: 'Al', 14: 'Si', 15: 'P', 16: 'S', 17: 'Cl', 18:",
"17: 'Cl', 18: 'Ar' } # converts an atomic label to a nuclear",
"DOI: 2013/dt/c3dt50599e # all values in Angstrom VDWRADII = {0: 0.00, 1: 1.20,",
"# converts nuclear charge to atom label Z2LABEL = { 1: 'H', 2:",
"for key in Z2LABEL: LABEL2Z[Z2LABEL[key]] = key # masses from UIPAC: http://www.chem.qmul.ac.uk/iupac/AtWt/ MASSES",
"http://www.chem.qmul.ac.uk/iupac/AtWt/ MASSES = {0: 0.00, 1: 1.00784, 2: 4.002602, 3: 6.938, 4: 9.01218,",
"1.46, 10: 1.58, 11: 2.50, 12: 2.51, 13: 2.25, 14: 2.19, 15: 1.90,",
"Alvarez (2013), DOI: 2013/dt/c3dt50599e # all values in Angstrom VDWRADII = {0: 0.00,",
"12: 1.39, 13: 1.26, 14: 1.16, 15: 1.11, 16: 1.03, 17: 0.99, 18:",
"label to a nuclear charge LABEL2Z = {} for key in Z2LABEL: LABEL2Z[Z2LABEL[key]]",
"= { 1: 'H', 2: 'He', 3: 'Li', 4: 'Be', 5: 'B', 6:",
"Pykko and Atsumi (2009), DOI: 0.1002/chem.200800987 COORDINATION = {0: 0, 1: 1, 2:",
"14.00643, 8: 15.99903, 9: 18.998403, 10: 20.1797, 11: 22.9898, 12: 24.304, 13: 26.9815,",
"in Angstrom COVALENTRADII = {0: 0.00, 1: 0.32, 2: 0.46, 3: 1.33, 4:",
"} # Coordination numbers from Pykko and Atsumi (2009), DOI: 0.1002/chem.200800987 COORDINATION =",
"1, 11: 1, 12: 2, 13: 3, 14: 4, 15: 3, 16: 2,",
"v: idx = i v = value return idx def idamin(a): \"\"\" Returns",
"4, 7: 3, 8: 2, 9: 1, 10: 1, 11: 1, 12: 2,",
"a subroutine in GAMESS with the same name Arguments: a -- a numpy",
"(positive or negative) in the input array a. Arguments: a -- a numpy",
"idamax(a): \"\"\" Returns the index of maximum absolute value (positive or negative) in",
"the index in the array where the maximum value is. \"\"\" idx =",
"negative) in the input array a. Arguments: a -- a numpy array where",
"0.46, 3: 1.33, 4: 1.02, 5: 0.85, 6: 0.75, 7: 0.71, 8: 0.63,",
"13: 1.26, 14: 1.16, 15: 1.11, 16: 1.03, 17: 0.99, 18: 0.96 }",
"15: 1.90, 16: 1.89, 17: 1.82, 18: 1.83 } # Covalent radii from",
"{0: 0.00, 1: 0.32, 2: 0.46, 3: 1.33, 4: 1.02, 5: 0.85, 6:",
"-1 v = 0.0 for i, value in enumerate(numpy.abs(a)): if value > v:",
"0.1002/chem.200800987 COORDINATION = {0: 0, 1: 1, 2: 1, 3: 1, 4: 2,",
"10: 20.1797, 11: 22.9898, 12: 24.304, 13: 26.9815, 14: 28.084, 15: 30.973, 16:",
"10: 1.58, 11: 2.50, 12: 2.51, 13: 2.25, 14: 2.19, 15: 1.90, 16:",
"array a. Arguments: a -- a numpy array where we are to find",
"value is. \"\"\" idx = -1 v = 0.0 for i, value in",
"v = value return idx def idamin(a): \"\"\" Returns the index of minimum",
"\"\"\" Returns the index of minimum absolute value (positive or negative) in the",
"\"\"\" Utility variables and functions \"\"\" aa2au = 1.8897261249935897 # bohr / AA",
"1.00784, 2: 4.002602, 3: 6.938, 4: 9.01218, 5: 10.806, 6: 12.0096, 7: 14.00643,",
"6: 1.77, 7: 1.66, 8: 1.50, 9: 1.46, 10: 1.58, 11: 2.50, 12:",
"atomic label to a nuclear charge LABEL2Z = {} for key in Z2LABEL:",
"'Si', 15: 'P', 16: 'S', 17: 'Cl', 18: 'Ar' } # converts an",
"0.1002/chem.200800987 # all values in Angstrom COVALENTRADII = {0: 0.00, 1: 0.32, 2:",
"6: 12.0096, 7: 14.00643, 8: 15.99903, 9: 18.998403, 10: 20.1797, 11: 22.9898, 12:",
"the same name Arguments: a -- a numpy array where we are to",
"15: 1.11, 16: 1.03, 17: 0.99, 18: 0.96 } # Coordination numbers from",
"/ AA # converts nuclear charge to atom label Z2LABEL = { 1:",
"2.12, 4: 1.98, 5: 1.91, 6: 1.77, 7: 1.66, 8: 1.50, 9: 1.46,",
"> v: idx = i v = value return idx def idamin(a): \"\"\"",
"15: 'P', 16: 'S', 17: 'Cl', 18: 'Ar' } # converts an atomic",
"aa2au = 1.8897261249935897 # bohr / AA # converts nuclear charge to atom",
"value (positive or negative) in the input array a. Note: Loosely based of",
"4: 2, 5: 3, 6: 4, 7: 3, 8: 2, 9: 1, 10:",
"i v = value return idx def idamin(a): \"\"\" Returns the index of",
"14: 28.084, 15: 30.973, 16: 32.059, 17: 35.446, 18: 39.948 } # <NAME>al",
"are to find the minimum value in (either positive or negative) Returns: the",
"12: 2.51, 13: 2.25, 14: 2.19, 15: 1.90, 16: 1.89, 17: 1.82, 18:",
"(2009), DOI: 0.1002/chem.200800987 # all values in Angstrom COVALENTRADII = {0: 0.00, 1:",
"Angstrom VDWRADII = {0: 0.00, 1: 1.20, 2: 1.43, 3: 2.12, 4: 1.98,",
"1.0e30 for i, value in enumerate(numpy.abs(a)): if value < v: idx = i",
"values in Angstrom COVALENTRADII = {0: 0.00, 1: 0.32, 2: 0.46, 3: 1.33,",
"2.51, 13: 2.25, 14: 2.19, 15: 1.90, 16: 1.89, 17: 1.82, 18: 1.83",
"from Pykko and Atsumi (2009), DOI: 0.1002/chem.200800987 COORDINATION = {0: 0, 1: 1,",
"1: 0.32, 2: 0.46, 3: 1.33, 4: 1.02, 5: 0.85, 6: 0.75, 7:",
"11: 'NA', 12: 'Mg', 13: 'Al', 14: 'Si', 15: 'P', 16: 'S', 17:",
"12: 24.304, 13: 26.9815, 14: 28.084, 15: 30.973, 16: 32.059, 17: 35.446, 18:",
"based of a subroutine in GAMESS with the same name Arguments: a --",
"4.002602, 3: 6.938, 4: 9.01218, 5: 10.806, 6: 12.0096, 7: 14.00643, 8: 15.99903,",
"13: 26.9815, 14: 28.084, 15: 30.973, 16: 32.059, 17: 35.446, 18: 39.948 }",
"3: 1, 4: 2, 5: 3, 6: 4, 7: 3, 8: 2, 9:",
"\"\"\" idx = -1 v = 1.0e30 for i, value in enumerate(numpy.abs(a)): if",
"16: 32.059, 17: 35.446, 18: 39.948 } # <NAME>al radii from Alvarez (2013),",
"(positive or negative) in the input array a. Note: Loosely based of a",
"3: 'Li', 4: 'Be', 5: 'B', 6: 'C', 7: 'N', 8: 'O', 9:",
"Returns: the index in the array where the maximum value is. \"\"\" idx",
"'NA', 12: 'Mg', 13: 'Al', 14: 'Si', 15: 'P', 16: 'S', 17: 'Cl',",
"-- a numpy array where we are to find the maximum value in",
"v = 1.0e30 for i, value in enumerate(numpy.abs(a)): if value < v: idx",
"1.83 } # Covalent radii from Pykko and Atsumi (2009), DOI: 0.1002/chem.200800987 #",
"6: 4, 7: 3, 8: 2, 9: 1, 10: 1, 11: 1, 12:",
"7: 1.66, 8: 1.50, 9: 1.46, 10: 1.58, 11: 2.50, 12: 2.51, 13:",
"10.806, 6: 12.0096, 7: 14.00643, 8: 15.99903, 9: 18.998403, 10: 20.1797, 11: 22.9898,",
"Angstrom COVALENTRADII = {0: 0.00, 1: 0.32, 2: 0.46, 3: 1.33, 4: 1.02,",
"= -1 v = 1.0e30 for i, value in enumerate(numpy.abs(a)): if value <",
"Arguments: a -- a numpy array where we are to find the minimum",
"(2009), DOI: 0.1002/chem.200800987 COORDINATION = {0: 0, 1: 1, 2: 1, 3: 1,",
"subroutine in GAMESS with the same name Arguments: a -- a numpy array",
"1: 1.00784, 2: 4.002602, 3: 6.938, 4: 9.01218, 5: 10.806, 6: 12.0096, 7:",
"= 0.0 for i, value in enumerate(numpy.abs(a)): if value > v: idx =",
"2.19, 15: 1.90, 16: 1.89, 17: 1.82, 18: 1.83 } # Covalent radii",
"value in (either positive or negative) Returns: the index in the array where",
"13: 2.25, 14: 2.19, 15: 1.90, 16: 1.89, 17: 1.82, 18: 1.83 }",
"Returns the index of maximum absolute value (positive or negative) in the input",
"1.20, 2: 1.43, 3: 2.12, 4: 1.98, 5: 1.91, 6: 1.77, 7: 1.66,",
"# Coordination numbers from Pykko and Atsumi (2009), DOI: 0.1002/chem.200800987 COORDINATION = {0:",
"value in enumerate(numpy.abs(a)): if value < v: idx = i v = value",
"'Ar' } # converts an atomic label to a nuclear charge LABEL2Z =",
"7: 'N', 8: 'O', 9: 'F', 10: 'Ne', 11: 'NA', 12: 'Mg', 13:",
"COORDINATION = {0: 0, 1: 1, 2: 1, 3: 1, 4: 2, 5:",
"5: 3, 6: 4, 7: 3, 8: 2, 9: 1, 10: 1, 11:",
"in (either positive or negative) Returns: the index in the array where the",
"2: 1.43, 3: 2.12, 4: 1.98, 5: 1.91, 6: 1.77, 7: 1.66, 8:",
"-1 v = 1.0e30 for i, value in enumerate(numpy.abs(a)): if value < v:",
"0.32, 2: 0.46, 3: 1.33, 4: 1.02, 5: 0.85, 6: 0.75, 7: 0.71,",
"= {0: 0.00, 1: 0.32, 2: 0.46, 3: 1.33, 4: 1.02, 5: 0.85,",
"the index of maximum absolute value (positive or negative) in the input array",
"# bohr / AA # converts nuclear charge to atom label Z2LABEL =",
"7: 0.71, 8: 0.63, 9: 0.64, 10: 0.67, 11: 1.55, 12: 1.39, 13:",
"2, 13: 3, 14: 4, 15: 3, 16: 2, 17: 1, 18: 1",
"radii from Pykko and Atsumi (2009), DOI: 0.1002/chem.200800987 # all values in Angstrom",
"17: 35.446, 18: 39.948 } # <NAME>al radii from Alvarez (2013), DOI: 2013/dt/c3dt50599e",
"or negative) in the input array a. Arguments: a -- a numpy array",
"or negative) Returns: the index in the array where the maximum value is.",
"enumerate(numpy.abs(a)): if value < v: idx = i v = value return idx",
"converts nuclear charge to atom label Z2LABEL = { 1: 'H', 2: 'He',",
"1.26, 14: 1.16, 15: 1.11, 16: 1.03, 17: 0.99, 18: 0.96 } #",
"12.0096, 7: 14.00643, 8: 15.99903, 9: 18.998403, 10: 20.1797, 11: 22.9898, 12: 24.304,",
"the input array a. Note: Loosely based of a subroutine in GAMESS with",
"atom label Z2LABEL = { 1: 'H', 2: 'He', 3: 'Li', 4: 'Be',",
"# all values in Angstrom COVALENTRADII = {0: 0.00, 1: 0.32, 2: 0.46,",
"1.11, 16: 1.03, 17: 0.99, 18: 0.96 } # Coordination numbers from Pykko",
"2, 17: 1, 18: 1 } def idamax(a): \"\"\" Returns the index of",
"0.63, 9: 0.64, 10: 0.67, 11: 1.55, 12: 1.39, 13: 1.26, 14: 1.16,",
"= value return idx def idamin(a): \"\"\" Returns the index of minimum absolute",
"in the input array a. Note: Loosely based of a subroutine in GAMESS",
"0.71, 8: 0.63, 9: 0.64, 10: 0.67, 11: 1.55, 12: 1.39, 13: 1.26,",
"= 1.8897261249935897 # bohr / AA # converts nuclear charge to atom label",
"Z2LABEL = { 1: 'H', 2: 'He', 3: 'Li', 4: 'Be', 5: 'B',",
"a -- a numpy array where we are to find the maximum value",
"COVALENTRADII = {0: 0.00, 1: 0.32, 2: 0.46, 3: 1.33, 4: 1.02, 5:",
"12: 2, 13: 3, 14: 4, 15: 3, 16: 2, 17: 1, 18:",
"11: 2.50, 12: 2.51, 13: 2.25, 14: 2.19, 15: 1.90, 16: 1.89, 17:",
"1.82, 18: 1.83 } # Covalent radii from Pykko and Atsumi (2009), DOI:",
"13: 3, 14: 4, 15: 3, 16: 2, 17: 1, 18: 1 }",
"'S', 17: 'Cl', 18: 'Ar' } # converts an atomic label to a",
"# Covalent radii from Pykko and Atsumi (2009), DOI: 0.1002/chem.200800987 # all values",
"2: 'He', 3: 'Li', 4: 'Be', 5: 'B', 6: 'C', 7: 'N', 8:",
"with the same name Arguments: a -- a numpy array where we are",
"for i, value in enumerate(numpy.abs(a)): if value < v: idx = i v",
"Arguments: a -- a numpy array where we are to find the maximum",
"'O', 9: 'F', 10: 'Ne', 11: 'NA', 12: 'Mg', 13: 'Al', 14: 'Si',",
"we are to find the minimum value in (either positive or negative) Returns:",
"1, 18: 1 } def idamax(a): \"\"\" Returns the index of maximum absolute",
"{0: 0.00, 1: 1.00784, 2: 4.002602, 3: 6.938, 4: 9.01218, 5: 10.806, 6:",
"7: 14.00643, 8: 15.99903, 9: 18.998403, 10: 20.1797, 11: 22.9898, 12: 24.304, 13:",
"a. Note: Loosely based of a subroutine in GAMESS with the same name",
"is. \"\"\" idx = -1 v = 0.0 for i, value in enumerate(numpy.abs(a)):",
"3, 8: 2, 9: 1, 10: 1, 11: 1, 12: 2, 13: 3,",
"idx = -1 v = 1.0e30 for i, value in enumerate(numpy.abs(a)): if value",
"= key # masses from UIPAC: http://www.chem.qmul.ac.uk/iupac/AtWt/ MASSES = {0: 0.00, 1: 1.00784,",
"input array a. Note: Loosely based of a subroutine in GAMESS with the",
"where we are to find the minimum value in (either positive or negative)",
"2: 4.002602, 3: 6.938, 4: 9.01218, 5: 10.806, 6: 12.0096, 7: 14.00643, 8:",
"1 } def idamax(a): \"\"\" Returns the index of maximum absolute value (positive",
"10: 0.67, 11: 1.55, 12: 1.39, 13: 1.26, 14: 1.16, 15: 1.11, 16:",
"11: 1.55, 12: 1.39, 13: 1.26, 14: 1.16, 15: 1.11, 16: 1.03, 17:",
"6: 0.75, 7: 0.71, 8: 0.63, 9: 0.64, 10: 0.67, 11: 1.55, 12:",
"= {} for key in Z2LABEL: LABEL2Z[Z2LABEL[key]] = key # masses from UIPAC:",
"charge LABEL2Z = {} for key in Z2LABEL: LABEL2Z[Z2LABEL[key]] = key # masses",
"MASSES = {0: 0.00, 1: 1.00784, 2: 4.002602, 3: 6.938, 4: 9.01218, 5:",
"of minimum absolute value (positive or negative) in the input array a. Arguments:",
"11: 1, 12: 2, 13: 3, 14: 4, 15: 3, 16: 2, 17:",
"} # converts an atomic label to a nuclear charge LABEL2Z = {}",
"idx def idamin(a): \"\"\" Returns the index of minimum absolute value (positive or",
"in enumerate(numpy.abs(a)): if value > v: idx = i v = value return",
"1, 4: 2, 5: 3, 6: 4, 7: 3, 8: 2, 9: 1,",
"1: 1.20, 2: 1.43, 3: 2.12, 4: 1.98, 5: 1.91, 6: 1.77, 7:",
"0.96 } # Coordination numbers from Pykko and Atsumi (2009), DOI: 0.1002/chem.200800987 COORDINATION",
"VDWRADII = {0: 0.00, 1: 1.20, 2: 1.43, 3: 2.12, 4: 1.98, 5:",
"1, 3: 1, 4: 2, 5: 3, 6: 4, 7: 3, 8: 2,",
"values in Angstrom VDWRADII = {0: 0.00, 1: 1.20, 2: 1.43, 3: 2.12,",
"'Li', 4: 'Be', 5: 'B', 6: 'C', 7: 'N', 8: 'O', 9: 'F',",
"DOI: 0.1002/chem.200800987 # all values in Angstrom COVALENTRADII = {0: 0.00, 1: 0.32,",
"35.446, 18: 39.948 } # <NAME>al radii from Alvarez (2013), DOI: 2013/dt/c3dt50599e #",
"to a nuclear charge LABEL2Z = {} for key in Z2LABEL: LABEL2Z[Z2LABEL[key]] =",
"key in Z2LABEL: LABEL2Z[Z2LABEL[key]] = key # masses from UIPAC: http://www.chem.qmul.ac.uk/iupac/AtWt/ MASSES =",
"idx = -1 v = 0.0 for i, value in enumerate(numpy.abs(a)): if value",
"positive or negative) Returns: the index in the array where the maximum value",
"18: 0.96 } # Coordination numbers from Pykko and Atsumi (2009), DOI: 0.1002/chem.200800987",
"minimum value in (either positive or negative) Returns: the index in the array",
"radii from Alvarez (2013), DOI: 2013/dt/c3dt50599e # all values in Angstrom VDWRADII =",
"26.9815, 14: 28.084, 15: 30.973, 16: 32.059, 17: 35.446, 18: 39.948 } #",
"= i v = value return idx def idamin(a): \"\"\" Returns the index",
"3, 14: 4, 15: 3, 16: 2, 17: 1, 18: 1 } def",
"LABEL2Z[Z2LABEL[key]] = key # masses from UIPAC: http://www.chem.qmul.ac.uk/iupac/AtWt/ MASSES = {0: 0.00, 1:",
"1.8897261249935897 # bohr / AA # converts nuclear charge to atom label Z2LABEL",
"'F', 10: 'Ne', 11: 'NA', 12: 'Mg', 13: 'Al', 14: 'Si', 15: 'P',",
"'Al', 14: 'Si', 15: 'P', 16: 'S', 17: 'Cl', 18: 'Ar' } #",
"to find the minimum value in (either positive or negative) Returns: the index",
"(2013), DOI: 2013/dt/c3dt50599e # all values in Angstrom VDWRADII = {0: 0.00, 1:",
"4, 15: 3, 16: 2, 17: 1, 18: 1 } def idamax(a): \"\"\"",
"variables and functions \"\"\" aa2au = 1.8897261249935897 # bohr / AA # converts",
"the maximum value is. \"\"\" idx = -1 v = 1.0e30 for i,",
"index of minimum absolute value (positive or negative) in the input array a.",
"maximum value is. \"\"\" idx = -1 v = 0.0 for i, value",
"all values in Angstrom COVALENTRADII = {0: 0.00, 1: 0.32, 2: 0.46, 3:",
"value is. \"\"\" idx = -1 v = 1.0e30 for i, value in",
"Z2LABEL: LABEL2Z[Z2LABEL[key]] = key # masses from UIPAC: http://www.chem.qmul.ac.uk/iupac/AtWt/ MASSES = {0: 0.00,",
"array where the maximum value is. \"\"\" idx = -1 v = 0.0",
"13: 'Al', 14: 'Si', 15: 'P', 16: 'S', 17: 'Cl', 18: 'Ar' }",
"} # Covalent radii from Pykko and Atsumi (2009), DOI: 0.1002/chem.200800987 # all",
"0.00, 1: 0.32, 2: 0.46, 3: 1.33, 4: 1.02, 5: 0.85, 6: 0.75,",
"1.89, 17: 1.82, 18: 1.83 } # Covalent radii from Pykko and Atsumi",
"the index of minimum absolute value (positive or negative) in the input array",
"to find the maximum value in (either positive or negative) Returns: the index",
"1, 2: 1, 3: 1, 4: 2, 5: 3, 6: 4, 7: 3,",
"16: 2, 17: 1, 18: 1 } def idamax(a): \"\"\" Returns the index",
"DOI: 0.1002/chem.200800987 COORDINATION = {0: 0, 1: 1, 2: 1, 3: 1, 4:",
"Loosely based of a subroutine in GAMESS with the same name Arguments: a",
"14: 4, 15: 3, 16: 2, 17: 1, 18: 1 } def idamax(a):",
"v = 0.0 for i, value in enumerate(numpy.abs(a)): if value > v: idx",
"enumerate(numpy.abs(a)): if value > v: idx = i v = value return idx",
"maximum absolute value (positive or negative) in the input array a. Note: Loosely",
"5: 10.806, 6: 12.0096, 7: 14.00643, 8: 15.99903, 9: 18.998403, 10: 20.1797, 11:",
"numpy \"\"\" Utility variables and functions \"\"\" aa2au = 1.8897261249935897 # bohr /",
"maximum value in (either positive or negative) Returns: the index in the array",
"2.25, 14: 2.19, 15: 1.90, 16: 1.89, 17: 1.82, 18: 1.83 } #",
"4: 'Be', 5: 'B', 6: 'C', 7: 'N', 8: 'O', 9: 'F', 10:",
"2, 5: 3, 6: 4, 7: 3, 8: 2, 9: 1, 10: 1,",
"\"\"\" Returns the index of maximum absolute value (positive or negative) in the",
"'Be', 5: 'B', 6: 'C', 7: 'N', 8: 'O', 9: 'F', 10: 'Ne',",
"15: 30.973, 16: 32.059, 17: 35.446, 18: 39.948 } # <NAME>al radii from",
"0.85, 6: 0.75, 7: 0.71, 8: 0.63, 9: 0.64, 10: 0.67, 11: 1.55,",
"'Ne', 11: 'NA', 12: 'Mg', 13: 'Al', 14: 'Si', 15: 'P', 16: 'S',",
"4: 9.01218, 5: 10.806, 6: 12.0096, 7: 14.00643, 8: 15.99903, 9: 18.998403, 10:",
"1.58, 11: 2.50, 12: 2.51, 13: 2.25, 14: 2.19, 15: 1.90, 16: 1.89,",
"18: 1.83 } # Covalent radii from Pykko and Atsumi (2009), DOI: 0.1002/chem.200800987",
"index of maximum absolute value (positive or negative) in the input array a.",
"absolute value (positive or negative) in the input array a. Arguments: a --",
"2.50, 12: 2.51, 13: 2.25, 14: 2.19, 15: 1.90, 16: 1.89, 17: 1.82,",
"the input array a. Arguments: a -- a numpy array where we are",
"11: 22.9898, 12: 24.304, 13: 26.9815, 14: 28.084, 15: 30.973, 16: 32.059, 17:",
"2: 1, 3: 1, 4: 2, 5: 3, 6: 4, 7: 3, 8:"
] |
[
"if not os.path.exists(reload_file): continue if len(self._readFile(reload_file)) == 1: break else: self.assertTrue(False) self._call_cid(['service', 'stop',",
"KIND, either express or implied. # See the License for the specific language",
"Unless required by applicable law or agreed to in writing, software # distributed",
"'master', '--deployDir=dst', ]) for i in range(10): time.sleep(1) if not os.path.exists(start_file): continue if",
"\"\"\"#!/bin/bash flock data/lock -c 'echo -n \"1\" >>data/start.txt; echo -n \"1\" >>cache/start.txt' trap",
"{ 'scalable': True, 'reloadable': True, 'maxInstances' : 4, }, } }, }) self._call_cid(['package'])",
"'app', '0', '--deployDir=dst', ]) pid2 = os.fork() if not pid2: self._redirectAsyncStdIO() os.execv(self.CIDTEST_BIN, [",
"\"unlock; exit 0\" SIGTERM # high load while true; do dd if=/dev/urandom bs=64k",
"self._call_cid(['package']) self._call_cid(['promote', 'Releases'] + glob.glob('*.txz')) def test02_deploy(self): self._call_cid(['deploy', 'rms', 'Releases', '--deployDir=dst', '--rmsRepo=scp:'+self._rms_dir, '--limit-cpus=4'])",
"'3', '--deployDir=dst', ]) self._call_cid(['service', 'exec', 'app', '4', '--deployDir=dst'], returncode=1) for i in range(10):",
"if not os.path.exists(start_file): continue if len(self._readFile(start_file)) == 4: break else: self.assertTrue(False) for i",
"self.assertTrue(False) self._call_cid(['service', 'reload', 'app', '4', str(pid2), '--deployDir=dst'], returncode=1) self._call_cid(['service', 'reload', 'app', '3', str(pid2),",
"os.path.exists(cache_file): continue if len(self._readFile(cache_file)) == 4: break else: self.assertTrue(False) os.kill(pid, signal.SIGUSR1) for i",
"len(self._readFile(start_file)) == 4: break else: self.assertTrue(False) for i in range(10): time.sleep(1) if not",
"this file except in compliance with the License. # You may obtain a",
"break; fi sleep 0.1 done } function unlock() { rmdir data/lock } function",
"flock data/lock -c 'echo -n \"1\" >>data/start.txt; echo -n \"1\" >>cache/start.txt' trap \"flock",
"glob.glob('*.txz')) def test02_deploy(self): self._call_cid(['deploy', 'rms', 'Releases', '--deployDir=dst', '--rmsRepo=scp:'+self._rms_dir, '--limit-cpus=4']) deploy_conf = self._readJSON(os.path.join('dst', 'futoin.json'))",
"requests from .cid_utbase import cid_UTBase class cid_service_Test( cid_UTBase ) : __test__ = True",
"; done \"\"\") os.chmod('app.sh', stat.S_IRWXU) self._writeJSON('futoin.json', { 'name' : 'service-test', 'rms' : 'scp',",
"'--deployDir=dst', '--redeploy']) self.assertTrue(os.path.exists(keep_file)) def test05_master(self): start_file = 'dst/persistent/data/start.txt' reload_file = 'dst/persistent/data/reload.txt' cache_file =",
"trap \"flock data/lock -c 'echo -n 1 >>data/reload.txt'\" SIGHUP trap \"exit 0\" SIGTERM",
"import sys import time import signal import stat import pwd import grp import",
"ANY KIND, either express or implied. # See the License for the specific",
"-n 1 >>data/reload.txt unlock } lock touch data/start.txt touch data/reload.txt echo -n \"1\"",
"SIGTERM # high load while true; do dd if=/dev/urandom bs=64K count=1024 status=none |",
"'app', '3', str(pid2), '--deployDir=dst']) for i in range(10): time.sleep(1) if not os.path.exists(reload_file): continue",
"load while true; do dd if=/dev/urandom bs=64K count=1024 status=none | sha256sum >/dev/null ;",
"for i in range(10): time.sleep(1) if not os.path.exists(reload_file): continue if len(self._readFile(reload_file)) == 1:",
"else: self.assertTrue(False) self._call_cid(['service', 'reload', 'app', '4', str(pid2), '--deployDir=dst'], returncode=1) self._call_cid(['service', 'reload', 'app', '3',",
"time.sleep(1) if not os.path.exists(cache_file): continue if len(self._readFile(cache_file)) == 2: break else: self.assertTrue(False) self._call_cid(['service',",
"break else: self.assertTrue(False) os.kill(pid, signal.SIGUSR1) for i in range(30): time.sleep(1) if not os.path.exists(reload_file):",
"os.waitpid(pid2, 0) self._call_cid(['service', 'stop', 'app', '0', str(pid1), '--deployDir=dst']) os.waitpid(pid1, 0) def test04_redeploy(self): keep_file",
"True, 'maxInstances' : 4, }, } }, }) self._call_cid(['package']) self._call_cid(['promote', 'Releases'] + glob.glob('*.txz'))",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See",
"'writable' : [ 'cache', ], 'entryPoints' : { 'app' : { 'tool' :",
"pwd >&2 function lock() { while :; do if mkdir data/lock; then break;",
"\"\"\"#!/bin/bash pwd >&2 function lock() { while :; do if mkdir data/lock; then",
"IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"\"1\" >>cache/start.txt unlock trap \"on_reload\" SIGHUP trap \"unlock; exit 0\" SIGTERM # high",
"for i in range(10): time.sleep(1) if not os.path.exists(cache_file): continue if len(self._readFile(cache_file)) == 4:",
"i in range(30): time.sleep(1) if not os.path.exists(reload_file): continue if len(self._readFile(reload_file)) == 4: break",
"not os.path.exists(reload_file): continue if len(self._readFile(reload_file)) == 4: break else: self.assertTrue(False) os.kill(pid, signal.SIGTERM) os.waitpid(pid,",
") : __test__ = True TEST_DIR = os.path.join(cid_UTBase.TEST_RUN_DIR, 'servicecmd') _create_test_dir = True _rms_dir",
": 'Releases', 'persistent' : [ 'data', ], 'writable' : [ 'cache', ], 'entryPoints'",
"], 'writable' : [ 'cache', ], 'entryPoints' : { 'app' : { 'tool'",
"len(self._readFile(reload_file)) == 1: break else: self.assertTrue(False) self._call_cid(['service', 'stop', 'app', '4', str(pid2), '--deployDir=dst'], returncode=1)",
"pass try: os.unlink(reload_file) except: pass self.assertFalse(os.path.exists(cache_file)) pid = os.fork() if not pid: self._redirectAsyncStdIO()",
"unlock trap \"on_reload\" SIGHUP trap \"unlock; exit 0\" SIGTERM # high load while",
"test03_exec(self): start_file = 'dst/persistent/data/start.txt' reload_file = 'dst/persistent/data/reload.txt' cache_file = 'dst/current/cache/start.txt' try: os.unlink(start_file) except:",
"OF ANY KIND, either express or implied. # See the License for the",
"_rms_dir = os.path.join(TEST_DIR, 'rms') def test01_prepare(self): os.makedirs(os.path.join(self._rms_dir, 'Releases')) os.makedirs('src') os.chdir('src') os.mkdir('data') os.mkdir('cache') if",
"'dst/persistent/data/reload.txt' cache_file = 'dst/current/cache/start.txt' try: os.unlink(start_file) except: pass try: os.unlink(reload_file) except: pass self.assertFalse(os.path.exists(cache_file))",
"continue if len(self._readFile(start_file)) == 4: break else: self.assertTrue(False) for i in range(10): time.sleep(1)",
"len(self._readFile(cache_file)) == 4: break else: self.assertTrue(False) os.kill(pid, signal.SIGUSR1) for i in range(30): time.sleep(1)",
"'futoin.json')) self.assertEqual(4, len(deploy_conf['deploy']['autoServices']['app'])) def test03_exec(self): start_file = 'dst/persistent/data/start.txt' reload_file = 'dst/persistent/data/reload.txt' cache_file =",
"mkdir data/lock; then break; fi sleep 0.1 done } function unlock() { rmdir",
"fi sleep 0.1 done } function unlock() { rmdir data/lock } function on_reload()",
"if not os.path.exists(cache_file): continue if len(self._readFile(cache_file)) == 2: break else: self.assertTrue(False) self._call_cid(['service', 'reload',",
"import cid_UTBase class cid_service_Test( cid_UTBase ) : __test__ = True TEST_DIR = os.path.join(cid_UTBase.TEST_RUN_DIR,",
"True TEST_DIR = os.path.join(cid_UTBase.TEST_RUN_DIR, 'servicecmd') _create_test_dir = True _rms_dir = os.path.join(TEST_DIR, 'rms') def",
"str(pid2), '--deployDir=dst']) for i in range(10): time.sleep(1) if not os.path.exists(reload_file): continue if len(self._readFile(reload_file))",
"'3', str(pid2), '--deployDir=dst']) for i in range(10): time.sleep(1) if not os.path.exists(reload_file): continue if",
"self.CIDTEST_BIN, 'service', 'master', '--deployDir=dst', ]) for i in range(10): time.sleep(1) if not os.path.exists(start_file):",
"len(deploy_conf['deploy']['autoServices']['app'])) def test03_exec(self): start_file = 'dst/persistent/data/start.txt' reload_file = 'dst/persistent/data/reload.txt' cache_file = 'dst/current/cache/start.txt' try:",
"pid = os.fork() if not pid: self._redirectAsyncStdIO() os.execv(self.CIDTEST_BIN, [ self.CIDTEST_BIN, 'service', 'master', '--deployDir=dst',",
"'--deployDir=dst']) os.waitpid(pid2, 0) self._call_cid(['service', 'stop', 'app', '0', str(pid1), '--deployDir=dst']) os.waitpid(pid1, 0) def test04_redeploy(self):",
": 4, }, } }, }) self._call_cid(['package']) self._call_cid(['promote', 'Releases'] + glob.glob('*.txz')) def test02_deploy(self):",
"try: os.unlink(reload_file) except: pass self.assertFalse(os.path.exists(cache_file)) pid = os.fork() if not pid: self._redirectAsyncStdIO() os.execv(self.CIDTEST_BIN,",
"self._call_cid(['deploy', 'rms', 'Releases', '--deployDir=dst', '--redeploy']) self.assertTrue(os.path.exists(keep_file)) def test05_master(self): start_file = 'dst/persistent/data/start.txt' reload_file =",
"_create_test_dir = True _rms_dir = os.path.join(TEST_DIR, 'rms') def test01_prepare(self): os.makedirs(os.path.join(self._rms_dir, 'Releases')) os.makedirs('src') os.chdir('src')",
"]) pid2 = os.fork() if not pid2: self._redirectAsyncStdIO() os.execv(self.CIDTEST_BIN, [ self.CIDTEST_BIN, 'service', 'exec',",
"continue if len(self._readFile(cache_file)) == 2: break else: self.assertTrue(False) self._call_cid(['service', 'reload', 'app', '4', str(pid2),",
"+ glob.glob('*.txz')) def test02_deploy(self): self._call_cid(['deploy', 'rms', 'Releases', '--deployDir=dst', '--rmsRepo=scp:'+self._rms_dir, '--limit-cpus=4']) deploy_conf = self._readJSON(os.path.join('dst',",
">/dev/null; done \"\"\") else: self._writeFile('app.sh', \"\"\"#!/bin/bash flock data/lock -c 'echo -n \"1\" >>data/start.txt;",
"'tool' : 'exe', 'path' : 'app.sh', 'tune' : { 'scalable': True, 'reloadable': True,",
"sleep 0.1 done } function unlock() { rmdir data/lock } function on_reload() {",
"software # distributed under the License is distributed on an \"AS IS\" BASIS,",
"for i in range(10): time.sleep(1) if not os.path.exists(start_file): continue if len(self._readFile(start_file)) == 2:",
"pass try: os.unlink(reload_file) except: pass pid1 = os.fork() if not pid1: self._redirectAsyncStdIO() os.execv(self.CIDTEST_BIN,",
"'echo -n 1 >>data/reload.txt'\" SIGHUP trap \"exit 0\" SIGTERM # high load while",
"echo -n 1 >>data/reload.txt unlock } lock touch data/start.txt touch data/reload.txt echo -n",
"while :; do if mkdir data/lock; then break; fi sleep 0.1 done }",
"0) self._call_cid(['service', 'stop', 'app', '0', str(pid1), '--deployDir=dst']) os.waitpid(pid1, 0) def test04_redeploy(self): keep_file =",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to",
"permissions and # limitations under the License. # import os import sys import",
"do dd if=/dev/urandom bs=64k count=1024 2>/dev/null | shasum -a 256 >/dev/null; done \"\"\")",
"time.sleep(1) if not os.path.exists(start_file): continue if len(self._readFile(start_file)) == 2: break else: self.assertTrue(False) for",
"under the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES",
"returncode=1) self._call_cid(['service', 'stop', 'app', '3', str(pid2), '--deployDir=dst']) os.waitpid(pid2, 0) self._call_cid(['service', 'stop', 'app', '0',",
"cid_UTBase class cid_service_Test( cid_UTBase ) : __test__ = True TEST_DIR = os.path.join(cid_UTBase.TEST_RUN_DIR, 'servicecmd')",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"cache_file = 'dst/current/cache/start.txt' try: os.unlink(start_file) except: pass try: os.unlink(reload_file) except: pass pid1 =",
">>data/start.txt echo -n \"1\" >>cache/start.txt unlock trap \"on_reload\" SIGHUP trap \"unlock; exit 0\"",
"\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"continue if len(self._readFile(reload_file)) == 1: break else: self.assertTrue(False) self._call_cid(['service', 'stop', 'app', '4', str(pid2),",
"range(10): time.sleep(1) if not os.path.exists(cache_file): continue if len(self._readFile(cache_file)) == 2: break else: self.assertTrue(False)",
"'rms', 'Releases', '--deployDir=dst', '--redeploy']) self.assertTrue(os.path.exists(keep_file)) def test05_master(self): start_file = 'dst/persistent/data/start.txt' reload_file = 'dst/persistent/data/reload.txt'",
"} function on_reload() { lock echo -n 1 >>data/reload.txt unlock } lock touch",
"required by applicable law or agreed to in writing, software # distributed under",
":; do if mkdir data/lock; then break; fi sleep 0.1 done } function",
"applicable law or agreed to in writing, software # distributed under the License",
"# # Copyright 2015-2020 <NAME> <<EMAIL>> # # Licensed under the Apache License,",
"true; do dd if=/dev/urandom bs=64K count=1024 status=none | sha256sum >/dev/null ; done \"\"\")",
"i in range(10): time.sleep(1) if not os.path.exists(cache_file): continue if len(self._readFile(cache_file)) == 4: break",
"{ while :; do if mkdir data/lock; then break; fi sleep 0.1 done",
"echo -n \"1\" >>data/start.txt echo -n \"1\" >>cache/start.txt unlock trap \"on_reload\" SIGHUP trap",
"self._call_cid(['service', 'reload', 'app', '3', str(pid2), '--deployDir=dst']) for i in range(10): time.sleep(1) if not",
">>data/reload.txt unlock } lock touch data/start.txt touch data/reload.txt echo -n \"1\" >>data/start.txt echo",
"dd if=/dev/urandom bs=64K count=1024 status=none | sha256sum >/dev/null ; done \"\"\") os.chmod('app.sh', stat.S_IRWXU)",
"or agreed to in writing, software # distributed under the License is distributed",
"self.assertTrue(os.path.exists(keep_file)) def test05_master(self): start_file = 'dst/persistent/data/start.txt' reload_file = 'dst/persistent/data/reload.txt' cache_file = 'dst/current/cache/start.txt' try:",
"if not os.path.exists(start_file): continue if len(self._readFile(start_file)) == 2: break else: self.assertTrue(False) for i",
">>data/start.txt; echo -n \"1\" >>cache/start.txt' trap \"flock data/lock -c 'echo -n 1 >>data/reload.txt'\"",
"data/start.txt touch data/reload.txt echo -n \"1\" >>data/start.txt echo -n \"1\" >>cache/start.txt unlock trap",
"test04_redeploy(self): keep_file = 'dst/persistent/data/keep.txt' self._call_cid(['deploy', 'rms', 'Releases', '--deployDir=dst', '--redeploy']) self._writeFile(keep_file, 'KEEP') self._call_cid(['deploy', 'rms',",
"CONDITIONS OF ANY KIND, either express or implied. # See the License for",
"4: break else: self.assertTrue(False) os.kill(pid, signal.SIGUSR1) for i in range(30): time.sleep(1) if not",
"import requests from .cid_utbase import cid_UTBase class cid_service_Test( cid_UTBase ) : __test__ =",
"1 >>data/reload.txt'\" SIGHUP trap \"exit 0\" SIGTERM # high load while true; do",
"'app', '4', str(pid2), '--deployDir=dst'], returncode=1) self._call_cid(['service', 'stop', 'app', '3', str(pid2), '--deployDir=dst']) os.waitpid(pid2, 0)",
"count=1024 2>/dev/null | shasum -a 256 >/dev/null; done \"\"\") else: self._writeFile('app.sh', \"\"\"#!/bin/bash flock",
"under the Apache License, Version 2.0 (the \"License\"); # you may not use",
"test02_deploy(self): self._call_cid(['deploy', 'rms', 'Releases', '--deployDir=dst', '--rmsRepo=scp:'+self._rms_dir, '--limit-cpus=4']) deploy_conf = self._readJSON(os.path.join('dst', 'futoin.json')) self.assertEqual(4, len(deploy_conf['deploy']['autoServices']['app']))",
"writing, software # distributed under the License is distributed on an \"AS IS\"",
"You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"License. # You may obtain a copy of the License at # #",
"os.unlink(start_file) except: pass try: os.unlink(reload_file) except: pass pid1 = os.fork() if not pid1:",
"SIGHUP trap \"exit 0\" SIGTERM # high load while true; do dd if=/dev/urandom",
"import signal import stat import pwd import grp import glob import requests from",
"} function unlock() { rmdir data/lock } function on_reload() { lock echo -n",
"unlock() { rmdir data/lock } function on_reload() { lock echo -n 1 >>data/reload.txt",
"2: break else: self.assertTrue(False) for i in range(10): time.sleep(1) if not os.path.exists(cache_file): continue",
"signal.SIGUSR1) for i in range(30): time.sleep(1) if not os.path.exists(reload_file): continue if len(self._readFile(reload_file)) ==",
"'app', '3', '--deployDir=dst', ]) self._call_cid(['service', 'exec', 'app', '4', '--deployDir=dst'], returncode=1) for i in",
"in range(10): time.sleep(1) if not os.path.exists(cache_file): continue if len(self._readFile(cache_file)) == 4: break else:",
"compliance with the License. # You may obtain a copy of the License",
"not os.path.exists(start_file): continue if len(self._readFile(start_file)) == 4: break else: self.assertTrue(False) for i in",
"'Releases'] + glob.glob('*.txz')) def test02_deploy(self): self._call_cid(['deploy', 'rms', 'Releases', '--deployDir=dst', '--rmsRepo=scp:'+self._rms_dir, '--limit-cpus=4']) deploy_conf =",
"except: pass pid1 = os.fork() if not pid1: self._redirectAsyncStdIO() os.execv(self.CIDTEST_BIN, [ self.CIDTEST_BIN, 'service',",
"= os.fork() if not pid: self._redirectAsyncStdIO() os.execv(self.CIDTEST_BIN, [ self.CIDTEST_BIN, 'service', 'master', '--deployDir=dst', ])",
"self._call_cid(['deploy', 'rms', 'Releases', '--deployDir=dst', '--redeploy']) self._writeFile(keep_file, 'KEEP') self._call_cid(['deploy', 'rms', 'Releases', '--deployDir=dst', '--redeploy']) self.assertTrue(os.path.exists(keep_file))",
"-n 1 >>data/reload.txt'\" SIGHUP trap \"exit 0\" SIGTERM # high load while true;",
"trap \"exit 0\" SIGTERM # high load while true; do dd if=/dev/urandom bs=64K",
"self._redirectAsyncStdIO() os.execv(self.CIDTEST_BIN, [ self.CIDTEST_BIN, 'service', 'exec', 'app', '3', '--deployDir=dst', ]) self._call_cid(['service', 'exec', 'app',",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"for i in range(30): time.sleep(1) if not os.path.exists(reload_file): continue if len(self._readFile(reload_file)) == 4:",
"specific language governing permissions and # limitations under the License. # import os",
"data/reload.txt echo -n \"1\" >>data/start.txt echo -n \"1\" >>cache/start.txt unlock trap \"on_reload\" SIGHUP",
"def test02_deploy(self): self._call_cid(['deploy', 'rms', 'Releases', '--deployDir=dst', '--rmsRepo=scp:'+self._rms_dir, '--limit-cpus=4']) deploy_conf = self._readJSON(os.path.join('dst', 'futoin.json')) self.assertEqual(4,",
"== 1: break else: self.assertTrue(False) self._call_cid(['service', 'stop', 'app', '4', str(pid2), '--deployDir=dst'], returncode=1) self._call_cid(['service',",
"'3', str(pid2), '--deployDir=dst']) os.waitpid(pid2, 0) self._call_cid(['service', 'stop', 'app', '0', str(pid1), '--deployDir=dst']) os.waitpid(pid1, 0)",
"\"\"\") os.chmod('app.sh', stat.S_IRWXU) self._writeJSON('futoin.json', { 'name' : 'service-test', 'rms' : 'scp', 'rmsRepo' :",
"import stat import pwd import grp import glob import requests from .cid_utbase import",
"= os.fork() if not pid2: self._redirectAsyncStdIO() os.execv(self.CIDTEST_BIN, [ self.CIDTEST_BIN, 'service', 'exec', 'app', '3',",
"'stop', 'app', '4', str(pid2), '--deployDir=dst'], returncode=1) self._call_cid(['service', 'stop', 'app', '3', str(pid2), '--deployDir=dst']) os.waitpid(pid2,",
"256 >/dev/null; done \"\"\") else: self._writeFile('app.sh', \"\"\"#!/bin/bash flock data/lock -c 'echo -n \"1\"",
"try: os.unlink(reload_file) except: pass pid1 = os.fork() if not pid1: self._redirectAsyncStdIO() os.execv(self.CIDTEST_BIN, [",
"i in range(10): time.sleep(1) if not os.path.exists(reload_file): continue if len(self._readFile(reload_file)) == 1: break",
"self.CIDTEST_BIN, 'service', 'exec', 'app', '3', '--deployDir=dst', ]) self._call_cid(['service', 'exec', 'app', '4', '--deployDir=dst'], returncode=1)",
"trap \"on_reload\" SIGHUP trap \"unlock; exit 0\" SIGTERM # high load while true;",
"else: self.assertTrue(False) for i in range(10): time.sleep(1) if not os.path.exists(cache_file): continue if len(self._readFile(cache_file))",
"'--rmsRepo=scp:'+self._rms_dir, '--limit-cpus=4']) deploy_conf = self._readJSON(os.path.join('dst', 'futoin.json')) self.assertEqual(4, len(deploy_conf['deploy']['autoServices']['app'])) def test03_exec(self): start_file = 'dst/persistent/data/start.txt'",
"= 'dst/current/cache/start.txt' try: os.unlink(start_file) except: pass try: os.unlink(reload_file) except: pass self.assertFalse(os.path.exists(cache_file)) pid =",
"not use this file except in compliance with the License. # You may",
"'service', 'exec', 'app', '0', '--deployDir=dst', ]) pid2 = os.fork() if not pid2: self._redirectAsyncStdIO()",
"pass self.assertFalse(os.path.exists(cache_file)) pid = os.fork() if not pid: self._redirectAsyncStdIO() os.execv(self.CIDTEST_BIN, [ self.CIDTEST_BIN, 'service',",
"i in range(10): time.sleep(1) if not os.path.exists(start_file): continue if len(self._readFile(start_file)) == 2: break",
"if self.IS_MACOS: self._writeFile('app.sh', \"\"\"#!/bin/bash pwd >&2 function lock() { while :; do if",
"'entryPoints' : { 'app' : { 'tool' : 'exe', 'path' : 'app.sh', 'tune'",
"self._writeFile('app.sh', \"\"\"#!/bin/bash flock data/lock -c 'echo -n \"1\" >>data/start.txt; echo -n \"1\" >>cache/start.txt'",
"License, Version 2.0 (the \"License\"); # you may not use this file except",
"then break; fi sleep 0.1 done } function unlock() { rmdir data/lock }",
"'4', '--deployDir=dst'], returncode=1) for i in range(10): time.sleep(1) if not os.path.exists(start_file): continue if",
"start_file = 'dst/persistent/data/start.txt' reload_file = 'dst/persistent/data/reload.txt' cache_file = 'dst/current/cache/start.txt' try: os.unlink(start_file) except: pass",
"distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"cid_UTBase ) : __test__ = True TEST_DIR = os.path.join(cid_UTBase.TEST_RUN_DIR, 'servicecmd') _create_test_dir = True",
"2015-2020 <NAME> <<EMAIL>> # # Licensed under the Apache License, Version 2.0 (the",
"high load while true; do dd if=/dev/urandom bs=64K count=1024 status=none | sha256sum >/dev/null",
"'app', '3', str(pid2), '--deployDir=dst']) os.waitpid(pid2, 0) self._call_cid(['service', 'stop', 'app', '0', str(pid1), '--deployDir=dst']) os.waitpid(pid1,",
"<reponame>futoin/citool<gh_stars>10-100 # # Copyright 2015-2020 <NAME> <<EMAIL>> # # Licensed under the Apache",
"in range(30): time.sleep(1) if not os.path.exists(reload_file): continue if len(self._readFile(reload_file)) == 4: break else:",
"os.path.exists(reload_file): continue if len(self._readFile(reload_file)) == 1: break else: self.assertTrue(False) self._call_cid(['service', 'stop', 'app', '4',",
"i in range(10): time.sleep(1) if not os.path.exists(cache_file): continue if len(self._readFile(cache_file)) == 2: break",
"-n \"1\" >>data/start.txt echo -n \"1\" >>cache/start.txt unlock trap \"on_reload\" SIGHUP trap \"unlock;",
"0.1 done } function unlock() { rmdir data/lock } function on_reload() { lock",
"self._call_cid(['service', 'stop', 'app', '4', str(pid2), '--deployDir=dst'], returncode=1) self._call_cid(['service', 'stop', 'app', '3', str(pid2), '--deployDir=dst'])",
"-c 'echo -n \"1\" >>data/start.txt; echo -n \"1\" >>cache/start.txt' trap \"flock data/lock -c",
"# you may not use this file except in compliance with the License.",
"os.execv(self.CIDTEST_BIN, [ self.CIDTEST_BIN, 'service', 'master', '--deployDir=dst', ]) for i in range(10): time.sleep(1) if",
": { 'app' : { 'tool' : 'exe', 'path' : 'app.sh', 'tune' :",
"on_reload() { lock echo -n 1 >>data/reload.txt unlock } lock touch data/start.txt touch",
"agreed to in writing, software # distributed under the License is distributed on",
"-n \"1\" >>data/start.txt; echo -n \"1\" >>cache/start.txt' trap \"flock data/lock -c 'echo -n",
"for i in range(10): time.sleep(1) if not os.path.exists(cache_file): continue if len(self._readFile(cache_file)) == 2:",
"'--limit-cpus=4']) deploy_conf = self._readJSON(os.path.join('dst', 'futoin.json')) self.assertEqual(4, len(deploy_conf['deploy']['autoServices']['app'])) def test03_exec(self): start_file = 'dst/persistent/data/start.txt' reload_file",
"'persistent' : [ 'data', ], 'writable' : [ 'cache', ], 'entryPoints' : {",
"(the \"License\"); # you may not use this file except in compliance with",
"def test04_redeploy(self): keep_file = 'dst/persistent/data/keep.txt' self._call_cid(['deploy', 'rms', 'Releases', '--deployDir=dst', '--redeploy']) self._writeFile(keep_file, 'KEEP') self._call_cid(['deploy',",
": __test__ = True TEST_DIR = os.path.join(cid_UTBase.TEST_RUN_DIR, 'servicecmd') _create_test_dir = True _rms_dir =",
"} lock touch data/start.txt touch data/reload.txt echo -n \"1\" >>data/start.txt echo -n \"1\"",
"os.execv(self.CIDTEST_BIN, [ self.CIDTEST_BIN, 'service', 'exec', 'app', '0', '--deployDir=dst', ]) pid2 = os.fork() if",
"# Unless required by applicable law or agreed to in writing, software #",
"{ lock echo -n 1 >>data/reload.txt unlock } lock touch data/start.txt touch data/reload.txt",
"range(10): time.sleep(1) if not os.path.exists(reload_file): continue if len(self._readFile(reload_file)) == 1: break else: self.assertTrue(False)",
"by applicable law or agreed to in writing, software # distributed under the",
"os.unlink(reload_file) except: pass self.assertFalse(os.path.exists(cache_file)) pid = os.fork() if not pid: self._redirectAsyncStdIO() os.execv(self.CIDTEST_BIN, [",
"self._writeFile(keep_file, 'KEEP') self._call_cid(['deploy', 'rms', 'Releases', '--deployDir=dst', '--redeploy']) self.assertTrue(os.path.exists(keep_file)) def test05_master(self): start_file = 'dst/persistent/data/start.txt'",
"'app.sh', 'tune' : { 'scalable': True, 'reloadable': True, 'maxInstances' : 4, }, }",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"= 'dst/persistent/data/start.txt' reload_file = 'dst/persistent/data/reload.txt' cache_file = 'dst/current/cache/start.txt' try: os.unlink(start_file) except: pass try:",
"self._redirectAsyncStdIO() os.execv(self.CIDTEST_BIN, [ self.CIDTEST_BIN, 'service', 'master', '--deployDir=dst', ]) for i in range(10): time.sleep(1)",
"os.path.exists(reload_file): continue if len(self._readFile(reload_file)) == 4: break else: self.assertTrue(False) os.kill(pid, signal.SIGTERM) os.waitpid(pid, 0)",
"def test01_prepare(self): os.makedirs(os.path.join(self._rms_dir, 'Releases')) os.makedirs('src') os.chdir('src') os.mkdir('data') os.mkdir('cache') if self.IS_MACOS: self._writeFile('app.sh', \"\"\"#!/bin/bash pwd",
"if not os.path.exists(reload_file): continue if len(self._readFile(reload_file)) == 4: break else: self.assertTrue(False) os.kill(pid, signal.SIGTERM)",
": [ 'cache', ], 'entryPoints' : { 'app' : { 'tool' : 'exe',",
"self._rms_dir, 'rmsPool' : 'Releases', 'persistent' : [ 'data', ], 'writable' : [ 'cache',",
"'data', ], 'writable' : [ 'cache', ], 'entryPoints' : { 'app' : {",
"len(self._readFile(start_file)) == 2: break else: self.assertTrue(False) for i in range(10): time.sleep(1) if not",
"file except in compliance with the License. # You may obtain a copy",
"data/lock -c 'echo -n \"1\" >>data/start.txt; echo -n \"1\" >>cache/start.txt' trap \"flock data/lock",
"glob import requests from .cid_utbase import cid_UTBase class cid_service_Test( cid_UTBase ) : __test__",
"\"1\" >>data/start.txt; echo -n \"1\" >>cache/start.txt' trap \"flock data/lock -c 'echo -n 1",
"License. # import os import sys import time import signal import stat import",
"'--deployDir=dst']) for i in range(10): time.sleep(1) if not os.path.exists(reload_file): continue if len(self._readFile(reload_file)) ==",
"else: self.assertTrue(False) self._call_cid(['service', 'stop', 'app', '4', str(pid2), '--deployDir=dst'], returncode=1) self._call_cid(['service', 'stop', 'app', '3',",
"limitations under the License. # import os import sys import time import signal",
"# high load while true; do dd if=/dev/urandom bs=64K count=1024 status=none | sha256sum",
"if not os.path.exists(cache_file): continue if len(self._readFile(cache_file)) == 4: break else: self.assertTrue(False) os.kill(pid, signal.SIGUSR1)",
"License for the specific language governing permissions and # limitations under the License.",
"-n \"1\" >>cache/start.txt unlock trap \"on_reload\" SIGHUP trap \"unlock; exit 0\" SIGTERM #",
"to in writing, software # distributed under the License is distributed on an",
"'cache', ], 'entryPoints' : { 'app' : { 'tool' : 'exe', 'path' :",
"implied. # See the License for the specific language governing permissions and #",
"'Releases', '--deployDir=dst', '--redeploy']) self.assertTrue(os.path.exists(keep_file)) def test05_master(self): start_file = 'dst/persistent/data/start.txt' reload_file = 'dst/persistent/data/reload.txt' cache_file",
"returncode=1) for i in range(10): time.sleep(1) if not os.path.exists(start_file): continue if len(self._readFile(start_file)) ==",
"\"License\"); # you may not use this file except in compliance with the",
"# high load while true; do dd if=/dev/urandom bs=64k count=1024 2>/dev/null | shasum",
"obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"from .cid_utbase import cid_UTBase class cid_service_Test( cid_UTBase ) : __test__ = True TEST_DIR",
"'dst/current/cache/start.txt' try: os.unlink(start_file) except: pass try: os.unlink(reload_file) except: pass self.assertFalse(os.path.exists(cache_file)) pid = os.fork()",
"self._call_cid(['service', 'reload', 'app', '4', str(pid2), '--deployDir=dst'], returncode=1) self._call_cid(['service', 'reload', 'app', '3', str(pid2), '--deployDir=dst'])",
"lock echo -n 1 >>data/reload.txt unlock } lock touch data/start.txt touch data/reload.txt echo",
"[ 'data', ], 'writable' : [ 'cache', ], 'entryPoints' : { 'app' :",
"data/lock } function on_reload() { lock echo -n 1 >>data/reload.txt unlock } lock",
"self.assertEqual(4, len(deploy_conf['deploy']['autoServices']['app'])) def test03_exec(self): start_file = 'dst/persistent/data/start.txt' reload_file = 'dst/persistent/data/reload.txt' cache_file = 'dst/current/cache/start.txt'",
"= True TEST_DIR = os.path.join(cid_UTBase.TEST_RUN_DIR, 'servicecmd') _create_test_dir = True _rms_dir = os.path.join(TEST_DIR, 'rms')",
">>data/reload.txt'\" SIGHUP trap \"exit 0\" SIGTERM # high load while true; do dd",
"self._redirectAsyncStdIO() os.execv(self.CIDTEST_BIN, [ self.CIDTEST_BIN, 'service', 'exec', 'app', '0', '--deployDir=dst', ]) pid2 = os.fork()",
"pid2: self._redirectAsyncStdIO() os.execv(self.CIDTEST_BIN, [ self.CIDTEST_BIN, 'service', 'exec', 'app', '3', '--deployDir=dst', ]) self._call_cid(['service', 'exec',",
"[ self.CIDTEST_BIN, 'service', 'exec', 'app', '3', '--deployDir=dst', ]) self._call_cid(['service', 'exec', 'app', '4', '--deployDir=dst'],",
"]) self._call_cid(['service', 'exec', 'app', '4', '--deployDir=dst'], returncode=1) for i in range(10): time.sleep(1) if",
": { 'scalable': True, 'reloadable': True, 'maxInstances' : 4, }, } }, })",
"os.path.exists(cache_file): continue if len(self._readFile(cache_file)) == 2: break else: self.assertTrue(False) self._call_cid(['service', 'reload', 'app', '4',",
"else: self.assertTrue(False) os.kill(pid, signal.SIGUSR1) for i in range(30): time.sleep(1) if not os.path.exists(reload_file): continue",
"in range(10): time.sleep(1) if not os.path.exists(reload_file): continue if len(self._readFile(reload_file)) == 1: break else:",
"or implied. # See the License for the specific language governing permissions and",
"self._call_cid(['service', 'stop', 'app', '0', str(pid1), '--deployDir=dst']) os.waitpid(pid1, 0) def test04_redeploy(self): keep_file = 'dst/persistent/data/keep.txt'",
"= os.fork() if not pid1: self._redirectAsyncStdIO() os.execv(self.CIDTEST_BIN, [ self.CIDTEST_BIN, 'service', 'exec', 'app', '0',",
"Apache License, Version 2.0 (the \"License\"); # you may not use this file",
"'rms', 'Releases', '--deployDir=dst', '--rmsRepo=scp:'+self._rms_dir, '--limit-cpus=4']) deploy_conf = self._readJSON(os.path.join('dst', 'futoin.json')) self.assertEqual(4, len(deploy_conf['deploy']['autoServices']['app'])) def test03_exec(self):",
"pid2 = os.fork() if not pid2: self._redirectAsyncStdIO() os.execv(self.CIDTEST_BIN, [ self.CIDTEST_BIN, 'service', 'exec', 'app',",
"OR CONDITIONS OF ANY KIND, either express or implied. # See the License",
"may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"2>/dev/null | shasum -a 256 >/dev/null; done \"\"\") else: self._writeFile('app.sh', \"\"\"#!/bin/bash flock data/lock",
"| sha256sum >/dev/null ; done \"\"\") os.chmod('app.sh', stat.S_IRWXU) self._writeJSON('futoin.json', { 'name' : 'service-test',",
"if=/dev/urandom bs=64k count=1024 2>/dev/null | shasum -a 256 >/dev/null; done \"\"\") else: self._writeFile('app.sh',",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,",
"in writing, software # distributed under the License is distributed on an \"AS",
"<NAME> <<EMAIL>> # # Licensed under the Apache License, Version 2.0 (the \"License\");",
"}, } }, }) self._call_cid(['package']) self._call_cid(['promote', 'Releases'] + glob.glob('*.txz')) def test02_deploy(self): self._call_cid(['deploy', 'rms',",
"-a 256 >/dev/null; done \"\"\") else: self._writeFile('app.sh', \"\"\"#!/bin/bash flock data/lock -c 'echo -n",
"in range(10): time.sleep(1) if not os.path.exists(start_file): continue if len(self._readFile(start_file)) == 4: break else:",
"sys import time import signal import stat import pwd import grp import glob",
"{ 'tool' : 'exe', 'path' : 'app.sh', 'tune' : { 'scalable': True, 'reloadable':",
"SIGTERM # high load while true; do dd if=/dev/urandom bs=64k count=1024 2>/dev/null |",
"# See the License for the specific language governing permissions and # limitations",
"the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR",
"0\" SIGTERM # high load while true; do dd if=/dev/urandom bs=64k count=1024 2>/dev/null",
"function on_reload() { lock echo -n 1 >>data/reload.txt unlock } lock touch data/start.txt",
"not pid1: self._redirectAsyncStdIO() os.execv(self.CIDTEST_BIN, [ self.CIDTEST_BIN, 'service', 'exec', 'app', '0', '--deployDir=dst', ]) pid2",
"self.assertTrue(False) self._call_cid(['service', 'stop', 'app', '4', str(pid2), '--deployDir=dst'], returncode=1) self._call_cid(['service', 'stop', 'app', '3', str(pid2),",
"0) def test04_redeploy(self): keep_file = 'dst/persistent/data/keep.txt' self._call_cid(['deploy', 'rms', 'Releases', '--deployDir=dst', '--redeploy']) self._writeFile(keep_file, 'KEEP')",
"os.mkdir('data') os.mkdir('cache') if self.IS_MACOS: self._writeFile('app.sh', \"\"\"#!/bin/bash pwd >&2 function lock() { while :;",
"'4', str(pid2), '--deployDir=dst'], returncode=1) self._call_cid(['service', 'stop', 'app', '3', str(pid2), '--deployDir=dst']) os.waitpid(pid2, 0) self._call_cid(['service',",
"'--deployDir=dst', ]) for i in range(10): time.sleep(1) if not os.path.exists(start_file): continue if len(self._readFile(start_file))",
"governing permissions and # limitations under the License. # import os import sys",
"if not pid: self._redirectAsyncStdIO() os.execv(self.CIDTEST_BIN, [ self.CIDTEST_BIN, 'service', 'master', '--deployDir=dst', ]) for i",
"while true; do dd if=/dev/urandom bs=64k count=1024 2>/dev/null | shasum -a 256 >/dev/null;",
"i in range(10): time.sleep(1) if not os.path.exists(start_file): continue if len(self._readFile(start_file)) == 4: break",
": 'scp', 'rmsRepo' : self._rms_dir, 'rmsPool' : 'Releases', 'persistent' : [ 'data', ],",
"try: os.unlink(start_file) except: pass try: os.unlink(reload_file) except: pass self.assertFalse(os.path.exists(cache_file)) pid = os.fork() if",
"'scalable': True, 'reloadable': True, 'maxInstances' : 4, }, } }, }) self._call_cid(['package']) self._call_cid(['promote',",
"'reload', 'app', '4', str(pid2), '--deployDir=dst'], returncode=1) self._call_cid(['service', 'reload', 'app', '3', str(pid2), '--deployDir=dst']) for",
"TEST_DIR = os.path.join(cid_UTBase.TEST_RUN_DIR, 'servicecmd') _create_test_dir = True _rms_dir = os.path.join(TEST_DIR, 'rms') def test01_prepare(self):",
"time.sleep(1) if not os.path.exists(start_file): continue if len(self._readFile(start_file)) == 4: break else: self.assertTrue(False) for",
"keep_file = 'dst/persistent/data/keep.txt' self._call_cid(['deploy', 'rms', 'Releases', '--deployDir=dst', '--redeploy']) self._writeFile(keep_file, 'KEEP') self._call_cid(['deploy', 'rms', 'Releases',",
"the Apache License, Version 2.0 (the \"License\"); # you may not use this",
"self.CIDTEST_BIN, 'service', 'exec', 'app', '0', '--deployDir=dst', ]) pid2 = os.fork() if not pid2:",
"'4', str(pid2), '--deployDir=dst'], returncode=1) self._call_cid(['service', 'reload', 'app', '3', str(pid2), '--deployDir=dst']) for i in",
"you may not use this file except in compliance with the License. #",
"not os.path.exists(cache_file): continue if len(self._readFile(cache_file)) == 2: break else: self.assertTrue(False) self._call_cid(['service', 'reload', 'app',",
"self.IS_MACOS: self._writeFile('app.sh', \"\"\"#!/bin/bash pwd >&2 function lock() { while :; do if mkdir",
"status=none | sha256sum >/dev/null ; done \"\"\") os.chmod('app.sh', stat.S_IRWXU) self._writeJSON('futoin.json', { 'name' :",
"function unlock() { rmdir data/lock } function on_reload() { lock echo -n 1",
"4: break else: self.assertTrue(False) for i in range(10): time.sleep(1) if not os.path.exists(cache_file): continue",
"time.sleep(1) if not os.path.exists(reload_file): continue if len(self._readFile(reload_file)) == 4: break else: self.assertTrue(False) os.kill(pid,",
"and # limitations under the License. # import os import sys import time",
"bs=64K count=1024 status=none | sha256sum >/dev/null ; done \"\"\") os.chmod('app.sh', stat.S_IRWXU) self._writeJSON('futoin.json', {",
"'exec', 'app', '4', '--deployDir=dst'], returncode=1) for i in range(10): time.sleep(1) if not os.path.exists(start_file):",
"count=1024 status=none | sha256sum >/dev/null ; done \"\"\") os.chmod('app.sh', stat.S_IRWXU) self._writeJSON('futoin.json', { 'name'",
"self._call_cid(['promote', 'Releases'] + glob.glob('*.txz')) def test02_deploy(self): self._call_cid(['deploy', 'rms', 'Releases', '--deployDir=dst', '--rmsRepo=scp:'+self._rms_dir, '--limit-cpus=4']) deploy_conf",
"'--deployDir=dst', '--redeploy']) self._writeFile(keep_file, 'KEEP') self._call_cid(['deploy', 'rms', 'Releases', '--deployDir=dst', '--redeploy']) self.assertTrue(os.path.exists(keep_file)) def test05_master(self): start_file",
"os.chdir('src') os.mkdir('data') os.mkdir('cache') if self.IS_MACOS: self._writeFile('app.sh', \"\"\"#!/bin/bash pwd >&2 function lock() { while",
"os.path.exists(start_file): continue if len(self._readFile(start_file)) == 4: break else: self.assertTrue(False) for i in range(10):",
"if=/dev/urandom bs=64K count=1024 status=none | sha256sum >/dev/null ; done \"\"\") os.chmod('app.sh', stat.S_IRWXU) self._writeJSON('futoin.json',",
"use this file except in compliance with the License. # You may obtain",
"# limitations under the License. # import os import sys import time import",
"done } function unlock() { rmdir data/lock } function on_reload() { lock echo",
"if len(self._readFile(start_file)) == 2: break else: self.assertTrue(False) for i in range(10): time.sleep(1) if",
"\"\"\") else: self._writeFile('app.sh', \"\"\"#!/bin/bash flock data/lock -c 'echo -n \"1\" >>data/start.txt; echo -n",
"self.assertTrue(False) for i in range(10): time.sleep(1) if not os.path.exists(cache_file): continue if len(self._readFile(cache_file)) ==",
"except: pass try: os.unlink(reload_file) except: pass self.assertFalse(os.path.exists(cache_file)) pid = os.fork() if not pid:",
"os.unlink(start_file) except: pass try: os.unlink(reload_file) except: pass self.assertFalse(os.path.exists(cache_file)) pid = os.fork() if not",
"touch data/reload.txt echo -n \"1\" >>data/start.txt echo -n \"1\" >>cache/start.txt unlock trap \"on_reload\"",
"sha256sum >/dev/null ; done \"\"\") os.chmod('app.sh', stat.S_IRWXU) self._writeJSON('futoin.json', { 'name' : 'service-test', 'rms'",
"# Licensed under the Apache License, Version 2.0 (the \"License\"); # you may",
"range(10): time.sleep(1) if not os.path.exists(start_file): continue if len(self._readFile(start_file)) == 4: break else: self.assertTrue(False)",
"do dd if=/dev/urandom bs=64K count=1024 status=none | sha256sum >/dev/null ; done \"\"\") os.chmod('app.sh',",
"'path' : 'app.sh', 'tune' : { 'scalable': True, 'reloadable': True, 'maxInstances' : 4,",
"language governing permissions and # limitations under the License. # import os import",
"lock touch data/start.txt touch data/reload.txt echo -n \"1\" >>data/start.txt echo -n \"1\" >>cache/start.txt",
"bs=64k count=1024 2>/dev/null | shasum -a 256 >/dev/null; done \"\"\") else: self._writeFile('app.sh', \"\"\"#!/bin/bash",
"except: pass try: os.unlink(reload_file) except: pass pid1 = os.fork() if not pid1: self._redirectAsyncStdIO()",
"shasum -a 256 >/dev/null; done \"\"\") else: self._writeFile('app.sh', \"\"\"#!/bin/bash flock data/lock -c 'echo",
"range(10): time.sleep(1) if not os.path.exists(cache_file): continue if len(self._readFile(cache_file)) == 4: break else: self.assertTrue(False)",
"2.0 (the \"License\"); # you may not use this file except in compliance",
"'0', str(pid1), '--deployDir=dst']) os.waitpid(pid1, 0) def test04_redeploy(self): keep_file = 'dst/persistent/data/keep.txt' self._call_cid(['deploy', 'rms', 'Releases',",
">>cache/start.txt' trap \"flock data/lock -c 'echo -n 1 >>data/reload.txt'\" SIGHUP trap \"exit 0\"",
"os.mkdir('cache') if self.IS_MACOS: self._writeFile('app.sh', \"\"\"#!/bin/bash pwd >&2 function lock() { while :; do",
"for the specific language governing permissions and # limitations under the License. #",
"range(30): time.sleep(1) if not os.path.exists(reload_file): continue if len(self._readFile(reload_file)) == 4: break else: self.assertTrue(False)",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the",
"'service-test', 'rms' : 'scp', 'rmsRepo' : self._rms_dir, 'rmsPool' : 'Releases', 'persistent' : [",
"'Releases', '--deployDir=dst', '--rmsRepo=scp:'+self._rms_dir, '--limit-cpus=4']) deploy_conf = self._readJSON(os.path.join('dst', 'futoin.json')) self.assertEqual(4, len(deploy_conf['deploy']['autoServices']['app'])) def test03_exec(self): start_file",
": 'service-test', 'rms' : 'scp', 'rmsRepo' : self._rms_dir, 'rmsPool' : 'Releases', 'persistent' :",
"'scp', 'rmsRepo' : self._rms_dir, 'rmsPool' : 'Releases', 'persistent' : [ 'data', ], 'writable'",
"# # Unless required by applicable law or agreed to in writing, software",
"if not pid1: self._redirectAsyncStdIO() os.execv(self.CIDTEST_BIN, [ self.CIDTEST_BIN, 'service', 'exec', 'app', '0', '--deployDir=dst', ])",
"SIGHUP trap \"unlock; exit 0\" SIGTERM # high load while true; do dd",
"express or implied. # See the License for the specific language governing permissions",
"import os import sys import time import signal import stat import pwd import",
"os import sys import time import signal import stat import pwd import grp",
"[ self.CIDTEST_BIN, 'service', 'exec', 'app', '0', '--deployDir=dst', ]) pid2 = os.fork() if not",
"__test__ = True TEST_DIR = os.path.join(cid_UTBase.TEST_RUN_DIR, 'servicecmd') _create_test_dir = True _rms_dir = os.path.join(TEST_DIR,",
"4, }, } }, }) self._call_cid(['package']) self._call_cid(['promote', 'Releases'] + glob.glob('*.txz')) def test02_deploy(self): self._call_cid(['deploy',",
"done \"\"\") os.chmod('app.sh', stat.S_IRWXU) self._writeJSON('futoin.json', { 'name' : 'service-test', 'rms' : 'scp', 'rmsRepo'",
": 'exe', 'path' : 'app.sh', 'tune' : { 'scalable': True, 'reloadable': True, 'maxInstances'",
"= True _rms_dir = os.path.join(TEST_DIR, 'rms') def test01_prepare(self): os.makedirs(os.path.join(self._rms_dir, 'Releases')) os.makedirs('src') os.chdir('src') os.mkdir('data')",
"either express or implied. # See the License for the specific language governing",
"break else: self.assertTrue(False) self._call_cid(['service', 'stop', 'app', '4', str(pid2), '--deployDir=dst'], returncode=1) self._call_cid(['service', 'stop', 'app',",
"\"flock data/lock -c 'echo -n 1 >>data/reload.txt'\" SIGHUP trap \"exit 0\" SIGTERM #",
"dd if=/dev/urandom bs=64k count=1024 2>/dev/null | shasum -a 256 >/dev/null; done \"\"\") else:",
"os.unlink(reload_file) except: pass pid1 = os.fork() if not pid1: self._redirectAsyncStdIO() os.execv(self.CIDTEST_BIN, [ self.CIDTEST_BIN,",
"'--deployDir=dst'], returncode=1) self._call_cid(['service', 'stop', 'app', '3', str(pid2), '--deployDir=dst']) os.waitpid(pid2, 0) self._call_cid(['service', 'stop', 'app',",
"data/lock; then break; fi sleep 0.1 done } function unlock() { rmdir data/lock",
"while true; do dd if=/dev/urandom bs=64K count=1024 status=none | sha256sum >/dev/null ; done",
"| shasum -a 256 >/dev/null; done \"\"\") else: self._writeFile('app.sh', \"\"\"#!/bin/bash flock data/lock -c",
"[ 'cache', ], 'entryPoints' : { 'app' : { 'tool' : 'exe', 'path'",
"Licensed under the Apache License, Version 2.0 (the \"License\"); # you may not",
"an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"reload_file = 'dst/persistent/data/reload.txt' cache_file = 'dst/current/cache/start.txt' try: os.unlink(start_file) except: pass try: os.unlink(reload_file) except:",
"# import os import sys import time import signal import stat import pwd",
"'exec', 'app', '0', '--deployDir=dst', ]) pid2 = os.fork() if not pid2: self._redirectAsyncStdIO() os.execv(self.CIDTEST_BIN,",
"load while true; do dd if=/dev/urandom bs=64k count=1024 2>/dev/null | shasum -a 256",
"not os.path.exists(cache_file): continue if len(self._readFile(cache_file)) == 4: break else: self.assertTrue(False) os.kill(pid, signal.SIGUSR1) for",
"== 4: break else: self.assertTrue(False) for i in range(10): time.sleep(1) if not os.path.exists(cache_file):",
"trap \"unlock; exit 0\" SIGTERM # high load while true; do dd if=/dev/urandom",
"deploy_conf = self._readJSON(os.path.join('dst', 'futoin.json')) self.assertEqual(4, len(deploy_conf['deploy']['autoServices']['app'])) def test03_exec(self): start_file = 'dst/persistent/data/start.txt' reload_file =",
"data/lock -c 'echo -n 1 >>data/reload.txt'\" SIGHUP trap \"exit 0\" SIGTERM # high",
"'tune' : { 'scalable': True, 'reloadable': True, 'maxInstances' : 4, }, } },",
"for i in range(10): time.sleep(1) if not os.path.exists(start_file): continue if len(self._readFile(start_file)) == 4:",
"the License. # You may obtain a copy of the License at #",
"def test03_exec(self): start_file = 'dst/persistent/data/start.txt' reload_file = 'dst/persistent/data/reload.txt' cache_file = 'dst/current/cache/start.txt' try: os.unlink(start_file)",
"if mkdir data/lock; then break; fi sleep 0.1 done } function unlock() {",
"os.chmod('app.sh', stat.S_IRWXU) self._writeJSON('futoin.json', { 'name' : 'service-test', 'rms' : 'scp', 'rmsRepo' : self._rms_dir,",
"import pwd import grp import glob import requests from .cid_utbase import cid_UTBase class",
"'Releases', 'persistent' : [ 'data', ], 'writable' : [ 'cache', ], 'entryPoints' :",
"# distributed under the License is distributed on an \"AS IS\" BASIS, #",
"{ 'name' : 'service-test', 'rms' : 'scp', 'rmsRepo' : self._rms_dir, 'rmsPool' : 'Releases',",
"is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF",
"'stop', 'app', '3', str(pid2), '--deployDir=dst']) os.waitpid(pid2, 0) self._call_cid(['service', 'stop', 'app', '0', str(pid1), '--deployDir=dst'])",
"time.sleep(1) if not os.path.exists(cache_file): continue if len(self._readFile(cache_file)) == 4: break else: self.assertTrue(False) os.kill(pid,",
"'rms' : 'scp', 'rmsRepo' : self._rms_dir, 'rmsPool' : 'Releases', 'persistent' : [ 'data',",
"in range(10): time.sleep(1) if not os.path.exists(start_file): continue if len(self._readFile(start_file)) == 2: break else:",
"unlock } lock touch data/start.txt touch data/reload.txt echo -n \"1\" >>data/start.txt echo -n",
"not os.path.exists(reload_file): continue if len(self._readFile(reload_file)) == 1: break else: self.assertTrue(False) self._call_cid(['service', 'stop', 'app',",
"str(pid2), '--deployDir=dst'], returncode=1) self._call_cid(['service', 'stop', 'app', '3', str(pid2), '--deployDir=dst']) os.waitpid(pid2, 0) self._call_cid(['service', 'stop',",
"os.makedirs(os.path.join(self._rms_dir, 'Releases')) os.makedirs('src') os.chdir('src') os.mkdir('data') os.mkdir('cache') if self.IS_MACOS: self._writeFile('app.sh', \"\"\"#!/bin/bash pwd >&2 function",
"'Releases')) os.makedirs('src') os.chdir('src') os.mkdir('data') os.mkdir('cache') if self.IS_MACOS: self._writeFile('app.sh', \"\"\"#!/bin/bash pwd >&2 function lock()",
"Copyright 2015-2020 <NAME> <<EMAIL>> # # Licensed under the Apache License, Version 2.0",
"pass pid1 = os.fork() if not pid1: self._redirectAsyncStdIO() os.execv(self.CIDTEST_BIN, [ self.CIDTEST_BIN, 'service', 'exec',",
"= 'dst/persistent/data/keep.txt' self._call_cid(['deploy', 'rms', 'Releases', '--deployDir=dst', '--redeploy']) self._writeFile(keep_file, 'KEEP') self._call_cid(['deploy', 'rms', 'Releases', '--deployDir=dst',",
": { 'tool' : 'exe', 'path' : 'app.sh', 'tune' : { 'scalable': True,",
"'--redeploy']) self.assertTrue(os.path.exists(keep_file)) def test05_master(self): start_file = 'dst/persistent/data/start.txt' reload_file = 'dst/persistent/data/reload.txt' cache_file = 'dst/current/cache/start.txt'",
"self._call_cid(['service', 'exec', 'app', '4', '--deployDir=dst'], returncode=1) for i in range(10): time.sleep(1) if not",
">>cache/start.txt unlock trap \"on_reload\" SIGHUP trap \"unlock; exit 0\" SIGTERM # high load",
"{ rmdir data/lock } function on_reload() { lock echo -n 1 >>data/reload.txt unlock",
"rmdir data/lock } function on_reload() { lock echo -n 1 >>data/reload.txt unlock }",
"= self._readJSON(os.path.join('dst', 'futoin.json')) self.assertEqual(4, len(deploy_conf['deploy']['autoServices']['app'])) def test03_exec(self): start_file = 'dst/persistent/data/start.txt' reload_file = 'dst/persistent/data/reload.txt'",
"the License. # import os import sys import time import signal import stat",
"'app' : { 'tool' : 'exe', 'path' : 'app.sh', 'tune' : { 'scalable':",
"len(self._readFile(cache_file)) == 2: break else: self.assertTrue(False) self._call_cid(['service', 'reload', 'app', '4', str(pid2), '--deployDir=dst'], returncode=1)",
"<<EMAIL>> # # Licensed under the Apache License, Version 2.0 (the \"License\"); #",
"'servicecmd') _create_test_dir = True _rms_dir = os.path.join(TEST_DIR, 'rms') def test01_prepare(self): os.makedirs(os.path.join(self._rms_dir, 'Releases')) os.makedirs('src')",
"with the License. # You may obtain a copy of the License at",
"'dst/persistent/data/keep.txt' self._call_cid(['deploy', 'rms', 'Releases', '--deployDir=dst', '--redeploy']) self._writeFile(keep_file, 'KEEP') self._call_cid(['deploy', 'rms', 'Releases', '--deployDir=dst', '--redeploy'])",
"self._writeFile('app.sh', \"\"\"#!/bin/bash pwd >&2 function lock() { while :; do if mkdir data/lock;",
"not os.path.exists(start_file): continue if len(self._readFile(start_file)) == 2: break else: self.assertTrue(False) for i in",
"{ 'app' : { 'tool' : 'exe', 'path' : 'app.sh', 'tune' : {",
"pid: self._redirectAsyncStdIO() os.execv(self.CIDTEST_BIN, [ self.CIDTEST_BIN, 'service', 'master', '--deployDir=dst', ]) for i in range(10):",
"time.sleep(1) if not os.path.exists(reload_file): continue if len(self._readFile(reload_file)) == 1: break else: self.assertTrue(False) self._call_cid(['service',",
"if len(self._readFile(cache_file)) == 4: break else: self.assertTrue(False) os.kill(pid, signal.SIGUSR1) for i in range(30):",
"# # Licensed under the Apache License, Version 2.0 (the \"License\"); # you",
"'app', '0', str(pid1), '--deployDir=dst']) os.waitpid(pid1, 0) def test04_redeploy(self): keep_file = 'dst/persistent/data/keep.txt' self._call_cid(['deploy', 'rms',",
"= 'dst/current/cache/start.txt' try: os.unlink(start_file) except: pass try: os.unlink(reload_file) except: pass pid1 = os.fork()",
"stat import pwd import grp import glob import requests from .cid_utbase import cid_UTBase",
": [ 'data', ], 'writable' : [ 'cache', ], 'entryPoints' : { 'app'",
"lock() { while :; do if mkdir data/lock; then break; fi sleep 0.1",
"# Copyright 2015-2020 <NAME> <<EMAIL>> # # Licensed under the Apache License, Version",
"True, 'reloadable': True, 'maxInstances' : 4, }, } }, }) self._call_cid(['package']) self._call_cid(['promote', 'Releases']",
"pid1 = os.fork() if not pid1: self._redirectAsyncStdIO() os.execv(self.CIDTEST_BIN, [ self.CIDTEST_BIN, 'service', 'exec', 'app',",
"os.kill(pid, signal.SIGUSR1) for i in range(30): time.sleep(1) if not os.path.exists(reload_file): continue if len(self._readFile(reload_file))",
"os.path.join(TEST_DIR, 'rms') def test01_prepare(self): os.makedirs(os.path.join(self._rms_dir, 'Releases')) os.makedirs('src') os.chdir('src') os.mkdir('data') os.mkdir('cache') if self.IS_MACOS: self._writeFile('app.sh',",
"test05_master(self): start_file = 'dst/persistent/data/start.txt' reload_file = 'dst/persistent/data/reload.txt' cache_file = 'dst/current/cache/start.txt' try: os.unlink(start_file) except:",
"'exe', 'path' : 'app.sh', 'tune' : { 'scalable': True, 'reloadable': True, 'maxInstances' :",
"law or agreed to in writing, software # distributed under the License is",
"str(pid2), '--deployDir=dst'], returncode=1) self._call_cid(['service', 'reload', 'app', '3', str(pid2), '--deployDir=dst']) for i in range(10):",
"the License for the specific language governing permissions and # limitations under the",
"'dst/current/cache/start.txt' try: os.unlink(start_file) except: pass try: os.unlink(reload_file) except: pass pid1 = os.fork() if",
"'dst/persistent/data/reload.txt' cache_file = 'dst/current/cache/start.txt' try: os.unlink(start_file) except: pass try: os.unlink(reload_file) except: pass pid1",
"os.path.exists(start_file): continue if len(self._readFile(start_file)) == 2: break else: self.assertTrue(False) for i in range(10):",
"in range(10): time.sleep(1) if not os.path.exists(cache_file): continue if len(self._readFile(cache_file)) == 2: break else:",
"cid_service_Test( cid_UTBase ) : __test__ = True TEST_DIR = os.path.join(cid_UTBase.TEST_RUN_DIR, 'servicecmd') _create_test_dir =",
"time import signal import stat import pwd import grp import glob import requests",
"on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"'stop', 'app', '0', str(pid1), '--deployDir=dst']) os.waitpid(pid1, 0) def test04_redeploy(self): keep_file = 'dst/persistent/data/keep.txt' self._call_cid(['deploy',",
"'Releases', '--deployDir=dst', '--redeploy']) self._writeFile(keep_file, 'KEEP') self._call_cid(['deploy', 'rms', 'Releases', '--deployDir=dst', '--redeploy']) self.assertTrue(os.path.exists(keep_file)) def test05_master(self):",
"1 >>data/reload.txt unlock } lock touch data/start.txt touch data/reload.txt echo -n \"1\" >>data/start.txt",
"str(pid2), '--deployDir=dst']) os.waitpid(pid2, 0) self._call_cid(['service', 'stop', 'app', '0', str(pid1), '--deployDir=dst']) os.waitpid(pid1, 0) def",
"returncode=1) self._call_cid(['service', 'reload', 'app', '3', str(pid2), '--deployDir=dst']) for i in range(10): time.sleep(1) if",
"test01_prepare(self): os.makedirs(os.path.join(self._rms_dir, 'Releases')) os.makedirs('src') os.chdir('src') os.mkdir('data') os.mkdir('cache') if self.IS_MACOS: self._writeFile('app.sh', \"\"\"#!/bin/bash pwd >&2",
"-n \"1\" >>cache/start.txt' trap \"flock data/lock -c 'echo -n 1 >>data/reload.txt'\" SIGHUP trap",
"grp import glob import requests from .cid_utbase import cid_UTBase class cid_service_Test( cid_UTBase )",
"'--deployDir=dst']) os.waitpid(pid1, 0) def test04_redeploy(self): keep_file = 'dst/persistent/data/keep.txt' self._call_cid(['deploy', 'rms', 'Releases', '--deployDir=dst', '--redeploy'])",
": 'app.sh', 'tune' : { 'scalable': True, 'reloadable': True, 'maxInstances' : 4, },",
"os.fork() if not pid: self._redirectAsyncStdIO() os.execv(self.CIDTEST_BIN, [ self.CIDTEST_BIN, 'service', 'master', '--deployDir=dst', ]) for",
"in compliance with the License. # You may obtain a copy of the",
"1: break else: self.assertTrue(False) self._call_cid(['service', 'stop', 'app', '4', str(pid2), '--deployDir=dst'], returncode=1) self._call_cid(['service', 'stop',",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #",
".cid_utbase import cid_UTBase class cid_service_Test( cid_UTBase ) : __test__ = True TEST_DIR =",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"'rms') def test01_prepare(self): os.makedirs(os.path.join(self._rms_dir, 'Releases')) os.makedirs('src') os.chdir('src') os.mkdir('data') os.mkdir('cache') if self.IS_MACOS: self._writeFile('app.sh', \"\"\"#!/bin/bash",
"2: break else: self.assertTrue(False) self._call_cid(['service', 'reload', 'app', '4', str(pid2), '--deployDir=dst'], returncode=1) self._call_cid(['service', 'reload',",
"if len(self._readFile(start_file)) == 4: break else: self.assertTrue(False) for i in range(10): time.sleep(1) if",
"}) self._call_cid(['package']) self._call_cid(['promote', 'Releases'] + glob.glob('*.txz')) def test02_deploy(self): self._call_cid(['deploy', 'rms', 'Releases', '--deployDir=dst', '--rmsRepo=scp:'+self._rms_dir,",
"'app', '4', str(pid2), '--deployDir=dst'], returncode=1) self._call_cid(['service', 'reload', 'app', '3', str(pid2), '--deployDir=dst']) for i",
"== 4: break else: self.assertTrue(False) os.kill(pid, signal.SIGUSR1) for i in range(30): time.sleep(1) if",
"See the License for the specific language governing permissions and # limitations under",
"BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"= 'dst/persistent/data/reload.txt' cache_file = 'dst/current/cache/start.txt' try: os.unlink(start_file) except: pass try: os.unlink(reload_file) except: pass",
"== 2: break else: self.assertTrue(False) self._call_cid(['service', 'reload', 'app', '4', str(pid2), '--deployDir=dst'], returncode=1) self._call_cid(['service',",
"0\" SIGTERM # high load while true; do dd if=/dev/urandom bs=64K count=1024 status=none",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"}, }) self._call_cid(['package']) self._call_cid(['promote', 'Releases'] + glob.glob('*.txz')) def test02_deploy(self): self._call_cid(['deploy', 'rms', 'Releases', '--deployDir=dst',",
"'--deployDir=dst'], returncode=1) for i in range(10): time.sleep(1) if not os.path.exists(start_file): continue if len(self._readFile(start_file))",
"self._call_cid(['service', 'stop', 'app', '3', str(pid2), '--deployDir=dst']) os.waitpid(pid2, 0) self._call_cid(['service', 'stop', 'app', '0', str(pid1),",
"done \"\"\") else: self._writeFile('app.sh', \"\"\"#!/bin/bash flock data/lock -c 'echo -n \"1\" >>data/start.txt; echo",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in",
"'dst/persistent/data/start.txt' reload_file = 'dst/persistent/data/reload.txt' cache_file = 'dst/current/cache/start.txt' try: os.unlink(start_file) except: pass try: os.unlink(reload_file)",
"break else: self.assertTrue(False) self._call_cid(['service', 'reload', 'app', '4', str(pid2), '--deployDir=dst'], returncode=1) self._call_cid(['service', 'reload', 'app',",
"'reloadable': True, 'maxInstances' : 4, }, } }, }) self._call_cid(['package']) self._call_cid(['promote', 'Releases'] +",
"continue if len(self._readFile(cache_file)) == 4: break else: self.assertTrue(False) os.kill(pid, signal.SIGUSR1) for i in",
": self._rms_dir, 'rmsPool' : 'Releases', 'persistent' : [ 'data', ], 'writable' : [",
"try: os.unlink(start_file) except: pass try: os.unlink(reload_file) except: pass pid1 = os.fork() if not",
"def test05_master(self): start_file = 'dst/persistent/data/start.txt' reload_file = 'dst/persistent/data/reload.txt' cache_file = 'dst/current/cache/start.txt' try: os.unlink(start_file)",
"'rms', 'Releases', '--deployDir=dst', '--redeploy']) self._writeFile(keep_file, 'KEEP') self._call_cid(['deploy', 'rms', 'Releases', '--deployDir=dst', '--redeploy']) self.assertTrue(os.path.exists(keep_file)) def",
"'rmsPool' : 'Releases', 'persistent' : [ 'data', ], 'writable' : [ 'cache', ],",
"'0', '--deployDir=dst', ]) pid2 = os.fork() if not pid2: self._redirectAsyncStdIO() os.execv(self.CIDTEST_BIN, [ self.CIDTEST_BIN,",
"high load while true; do dd if=/dev/urandom bs=64k count=1024 2>/dev/null | shasum -a",
"not pid2: self._redirectAsyncStdIO() os.execv(self.CIDTEST_BIN, [ self.CIDTEST_BIN, 'service', 'exec', 'app', '3', '--deployDir=dst', ]) self._call_cid(['service',",
"else: self._writeFile('app.sh', \"\"\"#!/bin/bash flock data/lock -c 'echo -n \"1\" >>data/start.txt; echo -n \"1\"",
"the specific language governing permissions and # limitations under the License. # import",
"continue if len(self._readFile(start_file)) == 2: break else: self.assertTrue(False) for i in range(10): time.sleep(1)",
"str(pid1), '--deployDir=dst']) os.waitpid(pid1, 0) def test04_redeploy(self): keep_file = 'dst/persistent/data/keep.txt' self._call_cid(['deploy', 'rms', 'Releases', '--deployDir=dst',",
"import grp import glob import requests from .cid_utbase import cid_UTBase class cid_service_Test( cid_UTBase",
"echo -n \"1\" >>cache/start.txt unlock trap \"on_reload\" SIGHUP trap \"unlock; exit 0\" SIGTERM",
"os.execv(self.CIDTEST_BIN, [ self.CIDTEST_BIN, 'service', 'exec', 'app', '3', '--deployDir=dst', ]) self._call_cid(['service', 'exec', 'app', '4',",
"if len(self._readFile(reload_file)) == 1: break else: self.assertTrue(False) self._call_cid(['service', 'stop', 'app', '4', str(pid2), '--deployDir=dst'],",
"except: pass self.assertFalse(os.path.exists(cache_file)) pid = os.fork() if not pid: self._redirectAsyncStdIO() os.execv(self.CIDTEST_BIN, [ self.CIDTEST_BIN,",
"'--deployDir=dst', '--rmsRepo=scp:'+self._rms_dir, '--limit-cpus=4']) deploy_conf = self._readJSON(os.path.join('dst', 'futoin.json')) self.assertEqual(4, len(deploy_conf['deploy']['autoServices']['app'])) def test03_exec(self): start_file =",
"= os.path.join(TEST_DIR, 'rms') def test01_prepare(self): os.makedirs(os.path.join(self._rms_dir, 'Releases')) os.makedirs('src') os.chdir('src') os.mkdir('data') os.mkdir('cache') if self.IS_MACOS:",
"touch data/start.txt touch data/reload.txt echo -n \"1\" >>data/start.txt echo -n \"1\" >>cache/start.txt unlock",
"'name' : 'service-test', 'rms' : 'scp', 'rmsRepo' : self._rms_dir, 'rmsPool' : 'Releases', 'persistent'",
"Version 2.0 (the \"License\"); # you may not use this file except in",
"\"1\" >>cache/start.txt' trap \"flock data/lock -c 'echo -n 1 >>data/reload.txt'\" SIGHUP trap \"exit",
"except in compliance with the License. # You may obtain a copy of",
"-c 'echo -n 1 >>data/reload.txt'\" SIGHUP trap \"exit 0\" SIGTERM # high load",
"'reload', 'app', '3', str(pid2), '--deployDir=dst']) for i in range(10): time.sleep(1) if not os.path.exists(reload_file):",
"True _rms_dir = os.path.join(TEST_DIR, 'rms') def test01_prepare(self): os.makedirs(os.path.join(self._rms_dir, 'Releases')) os.makedirs('src') os.chdir('src') os.mkdir('data') os.mkdir('cache')",
"== 2: break else: self.assertTrue(False) for i in range(10): time.sleep(1) if not os.path.exists(cache_file):",
"'echo -n \"1\" >>data/start.txt; echo -n \"1\" >>cache/start.txt' trap \"flock data/lock -c 'echo",
"\"1\" >>data/start.txt echo -n \"1\" >>cache/start.txt unlock trap \"on_reload\" SIGHUP trap \"unlock; exit",
"'service', 'exec', 'app', '3', '--deployDir=dst', ]) self._call_cid(['service', 'exec', 'app', '4', '--deployDir=dst'], returncode=1) for",
"not pid: self._redirectAsyncStdIO() os.execv(self.CIDTEST_BIN, [ self.CIDTEST_BIN, 'service', 'master', '--deployDir=dst', ]) for i in",
"# You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"may not use this file except in compliance with the License. # You",
"License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS",
"break else: self.assertTrue(False) for i in range(10): time.sleep(1) if not os.path.exists(cache_file): continue if",
"'--deployDir=dst'], returncode=1) self._call_cid(['service', 'reload', 'app', '3', str(pid2), '--deployDir=dst']) for i in range(10): time.sleep(1)",
"= os.path.join(cid_UTBase.TEST_RUN_DIR, 'servicecmd') _create_test_dir = True _rms_dir = os.path.join(TEST_DIR, 'rms') def test01_prepare(self): os.makedirs(os.path.join(self._rms_dir,",
"self._readJSON(os.path.join('dst', 'futoin.json')) self.assertEqual(4, len(deploy_conf['deploy']['autoServices']['app'])) def test03_exec(self): start_file = 'dst/persistent/data/start.txt' reload_file = 'dst/persistent/data/reload.txt' cache_file",
"os.fork() if not pid1: self._redirectAsyncStdIO() os.execv(self.CIDTEST_BIN, [ self.CIDTEST_BIN, 'service', 'exec', 'app', '0', '--deployDir=dst',",
">&2 function lock() { while :; do if mkdir data/lock; then break; fi",
"cache_file = 'dst/current/cache/start.txt' try: os.unlink(start_file) except: pass try: os.unlink(reload_file) except: pass self.assertFalse(os.path.exists(cache_file)) pid",
"'--deployDir=dst', ]) pid2 = os.fork() if not pid2: self._redirectAsyncStdIO() os.execv(self.CIDTEST_BIN, [ self.CIDTEST_BIN, 'service',",
"[ self.CIDTEST_BIN, 'service', 'master', '--deployDir=dst', ]) for i in range(10): time.sleep(1) if not",
"pwd import grp import glob import requests from .cid_utbase import cid_UTBase class cid_service_Test(",
"'KEEP') self._call_cid(['deploy', 'rms', 'Releases', '--deployDir=dst', '--redeploy']) self.assertTrue(os.path.exists(keep_file)) def test05_master(self): start_file = 'dst/persistent/data/start.txt' reload_file",
"stat.S_IRWXU) self._writeJSON('futoin.json', { 'name' : 'service-test', 'rms' : 'scp', 'rmsRepo' : self._rms_dir, 'rmsPool'",
"pid1: self._redirectAsyncStdIO() os.execv(self.CIDTEST_BIN, [ self.CIDTEST_BIN, 'service', 'exec', 'app', '0', '--deployDir=dst', ]) pid2 =",
"under the License. # import os import sys import time import signal import",
">/dev/null ; done \"\"\") os.chmod('app.sh', stat.S_IRWXU) self._writeJSON('futoin.json', { 'name' : 'service-test', 'rms' :",
"self.assertTrue(False) os.kill(pid, signal.SIGUSR1) for i in range(30): time.sleep(1) if not os.path.exists(reload_file): continue if",
"class cid_service_Test( cid_UTBase ) : __test__ = True TEST_DIR = os.path.join(cid_UTBase.TEST_RUN_DIR, 'servicecmd') _create_test_dir",
"self._writeJSON('futoin.json', { 'name' : 'service-test', 'rms' : 'scp', 'rmsRepo' : self._rms_dir, 'rmsPool' :",
"exit 0\" SIGTERM # high load while true; do dd if=/dev/urandom bs=64k count=1024",
"os.path.join(cid_UTBase.TEST_RUN_DIR, 'servicecmd') _create_test_dir = True _rms_dir = os.path.join(TEST_DIR, 'rms') def test01_prepare(self): os.makedirs(os.path.join(self._rms_dir, 'Releases'))",
"self._call_cid(['deploy', 'rms', 'Releases', '--deployDir=dst', '--rmsRepo=scp:'+self._rms_dir, '--limit-cpus=4']) deploy_conf = self._readJSON(os.path.join('dst', 'futoin.json')) self.assertEqual(4, len(deploy_conf['deploy']['autoServices']['app'])) def",
"echo -n \"1\" >>cache/start.txt' trap \"flock data/lock -c 'echo -n 1 >>data/reload.txt'\" SIGHUP",
"], 'entryPoints' : { 'app' : { 'tool' : 'exe', 'path' : 'app.sh',",
"'app', '4', '--deployDir=dst'], returncode=1) for i in range(10): time.sleep(1) if not os.path.exists(start_file): continue",
"'--redeploy']) self._writeFile(keep_file, 'KEEP') self._call_cid(['deploy', 'rms', 'Releases', '--deployDir=dst', '--redeploy']) self.assertTrue(os.path.exists(keep_file)) def test05_master(self): start_file =",
"os.makedirs('src') os.chdir('src') os.mkdir('data') os.mkdir('cache') if self.IS_MACOS: self._writeFile('app.sh', \"\"\"#!/bin/bash pwd >&2 function lock() {",
"signal import stat import pwd import grp import glob import requests from .cid_utbase",
"\"on_reload\" SIGHUP trap \"unlock; exit 0\" SIGTERM # high load while true; do",
"'maxInstances' : 4, }, } }, }) self._call_cid(['package']) self._call_cid(['promote', 'Releases'] + glob.glob('*.txz')) def",
"]) for i in range(10): time.sleep(1) if not os.path.exists(start_file): continue if len(self._readFile(start_file)) ==",
"os.waitpid(pid1, 0) def test04_redeploy(self): keep_file = 'dst/persistent/data/keep.txt' self._call_cid(['deploy', 'rms', 'Releases', '--deployDir=dst', '--redeploy']) self._writeFile(keep_file,",
"'--deployDir=dst', ]) self._call_cid(['service', 'exec', 'app', '4', '--deployDir=dst'], returncode=1) for i in range(10): time.sleep(1)",
"'exec', 'app', '3', '--deployDir=dst', ]) self._call_cid(['service', 'exec', 'app', '4', '--deployDir=dst'], returncode=1) for i",
"'service', 'master', '--deployDir=dst', ]) for i in range(10): time.sleep(1) if not os.path.exists(start_file): continue",
"function lock() { while :; do if mkdir data/lock; then break; fi sleep",
"range(10): time.sleep(1) if not os.path.exists(start_file): continue if len(self._readFile(start_file)) == 2: break else: self.assertTrue(False)",
"import time import signal import stat import pwd import grp import glob import",
"import glob import requests from .cid_utbase import cid_UTBase class cid_service_Test( cid_UTBase ) :",
"do if mkdir data/lock; then break; fi sleep 0.1 done } function unlock()",
"os.fork() if not pid2: self._redirectAsyncStdIO() os.execv(self.CIDTEST_BIN, [ self.CIDTEST_BIN, 'service', 'exec', 'app', '3', '--deployDir=dst',",
"distributed under the License is distributed on an \"AS IS\" BASIS, # WITHOUT",
"true; do dd if=/dev/urandom bs=64k count=1024 2>/dev/null | shasum -a 256 >/dev/null; done",
"} }, }) self._call_cid(['package']) self._call_cid(['promote', 'Releases'] + glob.glob('*.txz')) def test02_deploy(self): self._call_cid(['deploy', 'rms', 'Releases',",
"\"exit 0\" SIGTERM # high load while true; do dd if=/dev/urandom bs=64K count=1024",
"'rmsRepo' : self._rms_dir, 'rmsPool' : 'Releases', 'persistent' : [ 'data', ], 'writable' :",
"if not pid2: self._redirectAsyncStdIO() os.execv(self.CIDTEST_BIN, [ self.CIDTEST_BIN, 'service', 'exec', 'app', '3', '--deployDir=dst', ])",
"self.assertFalse(os.path.exists(cache_file)) pid = os.fork() if not pid: self._redirectAsyncStdIO() os.execv(self.CIDTEST_BIN, [ self.CIDTEST_BIN, 'service', 'master',",
"if len(self._readFile(cache_file)) == 2: break else: self.assertTrue(False) self._call_cid(['service', 'reload', 'app', '4', str(pid2), '--deployDir=dst'],"
] |
[
"2080\", \"VGA\", 5, 10000000), Invoice(\"Intel i9 10900K\", \"Processor\", 10, 8000000)] for item in",
"[Invoice(\"RTX 2080\", \"VGA\", 5, 10000000), Invoice(\"Intel i9 10900K\", \"Processor\", 10, 8000000)] for item",
"10, 8000000)] for item in items: print(item.part_num) print(item.part_desc) print(item.quantity) print(item.price) print(\"Total tagihanmu adalah\",",
"\"VGA\", 5, 10000000), Invoice(\"Intel i9 10900K\", \"Processor\", 10, 8000000)] for item in items:",
"Invoice def main(): items = [Invoice(\"RTX 2080\", \"VGA\", 5, 10000000), Invoice(\"Intel i9 10900K\",",
"Invoice(\"Intel i9 10900K\", \"Processor\", 10, 8000000)] for item in items: print(item.part_num) print(item.part_desc) print(item.quantity)",
"import Invoice def main(): items = [Invoice(\"RTX 2080\", \"VGA\", 5, 10000000), Invoice(\"Intel i9",
"item in items: print(item.part_num) print(item.part_desc) print(item.quantity) print(item.price) print(\"Total tagihanmu adalah\", item.get_invoice_amount(), end=\"\\n\\n\") if",
"in items: print(item.part_num) print(item.part_desc) print(item.quantity) print(item.price) print(\"Total tagihanmu adalah\", item.get_invoice_amount(), end=\"\\n\\n\") if __name__",
"Invoice import Invoice def main(): items = [Invoice(\"RTX 2080\", \"VGA\", 5, 10000000), Invoice(\"Intel",
"items: print(item.part_num) print(item.part_desc) print(item.quantity) print(item.price) print(\"Total tagihanmu adalah\", item.get_invoice_amount(), end=\"\\n\\n\") if __name__ ==",
"main(): items = [Invoice(\"RTX 2080\", \"VGA\", 5, 10000000), Invoice(\"Intel i9 10900K\", \"Processor\", 10,",
"8000000)] for item in items: print(item.part_num) print(item.part_desc) print(item.quantity) print(item.price) print(\"Total tagihanmu adalah\", item.get_invoice_amount(),",
"print(item.part_num) print(item.part_desc) print(item.quantity) print(item.price) print(\"Total tagihanmu adalah\", item.get_invoice_amount(), end=\"\\n\\n\") if __name__ == \"__main__\":",
"10000000), Invoice(\"Intel i9 10900K\", \"Processor\", 10, 8000000)] for item in items: print(item.part_num) print(item.part_desc)",
"5, 10000000), Invoice(\"Intel i9 10900K\", \"Processor\", 10, 8000000)] for item in items: print(item.part_num)",
"= [Invoice(\"RTX 2080\", \"VGA\", 5, 10000000), Invoice(\"Intel i9 10900K\", \"Processor\", 10, 8000000)] for",
"\"Processor\", 10, 8000000)] for item in items: print(item.part_num) print(item.part_desc) print(item.quantity) print(item.price) print(\"Total tagihanmu",
"items = [Invoice(\"RTX 2080\", \"VGA\", 5, 10000000), Invoice(\"Intel i9 10900K\", \"Processor\", 10, 8000000)]",
"10900K\", \"Processor\", 10, 8000000)] for item in items: print(item.part_num) print(item.part_desc) print(item.quantity) print(item.price) print(\"Total",
"from Invoice import Invoice def main(): items = [Invoice(\"RTX 2080\", \"VGA\", 5, 10000000),",
"for item in items: print(item.part_num) print(item.part_desc) print(item.quantity) print(item.price) print(\"Total tagihanmu adalah\", item.get_invoice_amount(), end=\"\\n\\n\")",
"def main(): items = [Invoice(\"RTX 2080\", \"VGA\", 5, 10000000), Invoice(\"Intel i9 10900K\", \"Processor\",",
"i9 10900K\", \"Processor\", 10, 8000000)] for item in items: print(item.part_num) print(item.part_desc) print(item.quantity) print(item.price)",
"print(item.part_desc) print(item.quantity) print(item.price) print(\"Total tagihanmu adalah\", item.get_invoice_amount(), end=\"\\n\\n\") if __name__ == \"__main__\": main()"
] |
[
"MIT License (MIT) #Copyright (c) 2016 Blockstack #Permission is hereby granted, free of",
"= quote_field(data, \"txt\") return process_rr(data_dup, \"TXT\", \"txt\", \"{txt}\", template) def process_srv(data, template): \"\"\"",
"is None: return template.replace(field, \"\") if type(record_keys) == list: pass elif type(record_keys) ==",
"soadat.append(\")\") soa_txt = \" \".join(soadat) record = record.replace(\"{soa}\", soa_txt) else: # clear all",
"Replace {cname} in template with the serialized CNAME records \"\"\" return process_rr(data, \"CNAME\",",
"and to permit persons to whom the Software is #furnished to do so,",
"in domain_fields: value = str(data[key]) soadat.append(value) soadat.append(\"(\") for key in param_fields: value =",
"record += \" \".join(record_data) + \"\\n\" return template.replace(field, record) def process_ns(data, template): \"\"\"",
"data.get('ttl') is not None: soadat.append( str(data['ttl']) ) soadat.append(\"IN\") soadat.append(\"SOA\") for key in domain_fields:",
"conditions: #The above copyright notice and this permission notice shall be included in",
"notice and this permission notice shall be included in all #copies or substantial",
"Replace {aaaa} in template with the serialized A records \"\"\" return process_rr(data, \"AAAA\",",
"field in a list of DNS records. Return the new data records. \"\"\"",
"<gh_stars>1-10 # -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed",
"not None: assert len(data) == 1, \"Only support one SOA RR at this",
"template): \"\"\" Replace {aaaa} in template with the serialized A records \"\"\" return",
"all SOA fields record = record.replace(\"{soa}\", \"\") return record def quote_field(data, field): \"\"\"",
"datum. \"\"\" if data is None: return template.replace(field, \"\") if type(record_keys) == list:",
"ANY KIND, EXPRESS OR #IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF",
"process_uri(data, template): \"\"\" Replace {uri} in templtae with the serialized URI records \"\"\"",
"data return template.replace(\"{$ttl}\", record) def process_soa(data, template): \"\"\" Replace {SOA} in template with",
"ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #OUT OF OR IN CONNECTION",
"information. # -------------------------------------------------------------------------------------------- #The MIT License (MIT) #Copyright (c) 2016 Blockstack #Permission is",
"domain_fields = ['mname', 'rname'] param_fields = ['serial', 'refresh', 'retry', 'expire', 'minimum'] for f",
"BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #FITNESS FOR A PARTICULAR PURPOSE",
"== str: record_keys = [record_keys] else: raise ValueError(\"Invalid record keys\") assert type(data) ==",
"template) def process_uri(data, template): \"\"\" Replace {uri} in templtae with the serialized URI",
"\"Missing '%s'\" % record_key record_data = [] record_data.append( str(data[i].get('name', '@')) ) if data[i].get('ttl')",
"serialized $TTL record \"\"\" record = \"\" if data is not None: record",
"range(0, len(data)): for record_key in record_keys: assert record_key in data[i].keys(), \"Missing '%s'\" %",
"not None: soadat.append( str(data['ttl']) ) soadat.append(\"IN\") soadat.append(\"SOA\") for key in domain_fields: value =",
"\"\") if type(record_keys) == list: pass elif type(record_keys) == str: record_keys = [record_keys]",
"pass elif type(record_keys) == str: record_keys = [record_keys] else: raise ValueError(\"Invalid record keys\")",
"\"{ptr}\", template) def process_txt(data, template): \"\"\" Replace {txt} in template with the serialized",
"in template with the serialized CNAME records \"\"\" return process_rr(data, \"CNAME\", \"alias\", \"{cname}\",",
"is not None: record_data.append( str(data[i]['ttl']) ) record_data.append(record_type) record_data += [str(data[i][record_key]) for record_key in",
"in template with the serialized A records \"\"\" return process_rr(data, \"AAAA\", \"ip\", \"{aaaa}\",",
"\"\"\" Replace {SOA} in template with a set of serialized SOA records \"\"\"",
"fields record = record.replace(\"{soa}\", \"\") return record def quote_field(data, field): \"\"\" Quote a",
"\"Missing '%s' (%s)\" % (f, data) data_name = str(data.get('name', '@')) soadat.append(data_name) if data.get('ttl')",
"assert f in data.keys(), \"Missing '%s' (%s)\" % (f, data) data_name = str(data.get('name',",
"portions of the Software. #THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF",
"FOR ANY CLAIM, DAMAGES OR OTHER #LIABILITY, WHETHER IN AN ACTION OF CONTRACT,",
"of charge, to any person obtaining a copy #of this software and associated",
"#copies of the Software, and to permit persons to whom the Software is",
"def process_srv(data, template): \"\"\" Replace {srv} in template with the serialized SRV records",
"param_fields: assert f in data.keys(), \"Missing '%s' (%s)\" % (f, data) data_name =",
"if data is None: return template.replace(field, \"\") if type(record_keys) == list: pass elif",
"a serialized $TTL record \"\"\" record = \"\" if data is not None:",
"{$ttl} in template with a serialized $TTL record \"\"\" record = \"\" if",
"USE OR OTHER DEALINGS IN THE #SOFTWARE. #pylint: skip-file import copy def process_origin(data,",
"time\" data = data[0] soadat = [] domain_fields = ['mname', 'rname'] param_fields =",
"(%s)\" % (f, data) data_name = str(data.get('name', '@')) soadat.append(data_name) if data.get('ttl') is not",
"granted, free of charge, to any person obtaining a copy #of this software",
"= [] domain_fields = ['mname', 'rname'] param_fields = ['serial', 'refresh', 'retry', 'expire', 'minimum']",
"[] domain_fields = ['mname', 'rname'] param_fields = ['serial', 'refresh', 'retry', 'expire', 'minimum'] for",
"the project root for license information. # -------------------------------------------------------------------------------------------- #The MIT License (MIT) #Copyright",
"record += \"$ORIGIN %s\" % data return template.replace(\"{$origin}\", record) def process_ttl(data, template): \"\"\"",
"template) def process_spf(data, template): \"\"\" Replace {spf} in template with the serialized SPF",
"-------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the",
"\"port\", \"target\"], \"{srv}\", template) def process_spf(data, template): \"\"\" Replace {spf} in template with",
"record_data.append( str(data[i].get('name', '@')) ) if data[i].get('ttl') is not None: record_data.append( str(data[i]['ttl']) ) record_data.append(record_type)",
"charge, to any person obtaining a copy #of this software and associated documentation",
"#LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #OUT",
"with a serialized $ORIGIN record \"\"\" record = \"\" if data is not",
"not None: record_data.append( str(data[i]['ttl']) ) record_data.append(record_type) record_data += [str(data[i][record_key]) for record_key in record_keys]",
"not None: record += \"$ORIGIN %s\" % data return template.replace(\"{$origin}\", record) def process_ttl(data,",
"\"\"\" return process_rr(data, \"AAAA\", \"ip\", \"{aaaa}\", template) def process_cname(data, template): \"\"\" Replace {cname}",
"%s\" % data return template.replace(\"{$origin}\", record) def process_ttl(data, template): \"\"\" Replace {$ttl} in",
"SOFTWARE OR THE USE OR OTHER DEALINGS IN THE #SOFTWARE. #pylint: skip-file import",
"in template with the serialized SPF records \"\"\" return process_rr(data, \"SPF\", \"data\", \"{spf}\",",
"domain_fields: value = str(data[key]) soadat.append(value) soadat.append(\"(\") for key in param_fields: value = str(data[key])",
"without limitation the rights #to use, copy, modify, merge, publish, distribute, sublicense, and/or",
"the Software without restriction, including without limitation the rights #to use, copy, modify,",
"field, template): \"\"\" Meta method: Replace $field in template with the serialized $record_type",
"serialized $record_type records, using @record_key from each datum. \"\"\" if data is None:",
"MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------------------------------",
"CONTRACT, TORT OR OTHERWISE, ARISING FROM, #OUT OF OR IN CONNECTION WITH THE",
"the rights #to use, copy, modify, merge, publish, distribute, sublicense, and/or sell #copies",
"the new data records. \"\"\" if data is None: return None data_dup =",
"a copy #of this software and associated documentation files (the \"Software\"), to deal",
"template): \"\"\" Replace {uri} in templtae with the serialized URI records \"\"\" #",
"serialized URI records \"\"\" # quote target data_dup = quote_field(data, \"target\") return process_rr(data_dup,",
"\"{cname}\", template) def process_mx(data, template): \"\"\" Replace {mx} in template with the serialized",
"\"\\;\") return data_dup def process_rr(data, record_type, record_keys, field, template): \"\"\" Meta method: Replace",
"# quote txt data_dup = quote_field(data, \"txt\") return process_rr(data_dup, \"TXT\", \"txt\", \"{txt}\", template)",
"% record_key record_data = [] record_data.append( str(data[i].get('name', '@')) ) if data[i].get('ttl') is not",
"is hereby granted, free of charge, to any person obtaining a copy #of",
") if data[i].get('ttl') is not None: record_data.append( str(data[i]['ttl']) ) record_data.append(record_type) record_data += [str(data[i][record_key])",
"% (f, data) data_name = str(data.get('name', '@')) soadat.append(data_name) if data.get('ttl') is not None:",
"FROM, #OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR",
"the serialized SRV records \"\"\" return process_rr(data, \"SRV\", [\"priority\", \"weight\", \"port\", \"target\"], \"{srv}\",",
"data_dup = copy.deepcopy(data) for i in range(0, len(data_dup)): data_dup[i][field] = '\"%s\"' % data_dup[i][field]",
"'%s' (%s)\" % (f, data) data_name = str(data.get('name', '@')) soadat.append(data_name) if data.get('ttl') is",
"is None: return None data_dup = copy.deepcopy(data) for i in range(0, len(data_dup)): data_dup[i][field]",
"root for license information. # -------------------------------------------------------------------------------------------- #The MIT License (MIT) #Copyright (c) 2016",
"template): \"\"\" Meta method: Replace $field in template with the serialized $record_type records,",
"OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #LIABILITY, WHETHER",
"set of serialized SOA records \"\"\" record = template[:] if data is not",
"None: record += \"$TTL %s\" % data return template.replace(\"{$ttl}\", record) def process_soa(data, template):",
"def quote_field(data, field): \"\"\" Quote a field in a list of DNS records.",
"\"\"\" Replace {ptr} in template with the serialized PTR records \"\"\" return process_rr(data,",
"None: record += \"$ORIGIN %s\" % data return template.replace(\"{$origin}\", record) def process_ttl(data, template):",
"in range(0, len(data)): for record_key in record_keys: assert record_key in data[i].keys(), \"Missing '%s'\"",
"\"{mx}\", template) def process_ptr(data, template): \"\"\" Replace {ptr} in template with the serialized",
"to permit persons to whom the Software is #furnished to do so, subject",
"PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #AUTHORS OR COPYRIGHT HOLDERS BE",
"\"\"\" Replace {a} in template with the serialized A records \"\"\" return process_rr(data,",
"= \"\" if data is not None: record += \"$TTL %s\" % data",
"record keys\") assert type(data) == list, \"Data must be a list\" record =",
"CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE #SOFTWARE.",
"A records \"\"\" return process_rr(data, \"A\", \"ip\", \"{a}\", template) def process_aaaa(data, template): \"\"\"",
"= record.replace(\"{soa}\", soa_txt) else: # clear all SOA fields record = record.replace(\"{soa}\", \"\")",
"def process_origin(data, template): \"\"\" Replace {$origin} in template with a serialized $ORIGIN record",
"records \"\"\" return process_rr(data, \"NS\", \"host\", \"{ns}\", template) def process_a(data, template): \"\"\" Replace",
"each datum. \"\"\" if data is None: return template.replace(field, \"\") if type(record_keys) ==",
"Replace {mx} in template with the serialized MX records \"\"\" return process_rr(data, \"MX\",",
"serialized TXT records \"\"\" # quote txt data_dup = quote_field(data, \"txt\") return process_rr(data_dup,",
"distribute, sublicense, and/or sell #copies of the Software, and to permit persons to",
"process_rr(data, \"NS\", \"host\", \"{ns}\", template) def process_a(data, template): \"\"\" Replace {a} in template",
"{srv} in template with the serialized SRV records \"\"\" return process_rr(data, \"SRV\", [\"priority\",",
"template with a serialized $ORIGIN record \"\"\" record = \"\" if data is",
"in range(0, len(data_dup)): data_dup[i][field] = '\"%s\"' % data_dup[i][field] data_dup[i][field] = data_dup[i][field].replace(\";\", \"\\;\") return",
"Software, and to permit persons to whom the Software is #furnished to do",
"in data.keys(), \"Missing '%s' (%s)\" % (f, data) data_name = str(data.get('name', '@')) soadat.append(data_name)",
") record_data.append(record_type) record_data += [str(data[i][record_key]) for record_key in record_keys] record += \" \".join(record_data)",
"# Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT",
"and associated documentation files (the \"Software\"), to deal #in the Software without restriction,",
"\"Software\"), to deal #in the Software without restriction, including without limitation the rights",
"copyright notice and this permission notice shall be included in all #copies or",
"= str(data[key]) soadat.append(value) soadat.append(\")\") soa_txt = \" \".join(soadat) record = record.replace(\"{soa}\", soa_txt) else:",
"% data return template.replace(\"{$origin}\", record) def process_ttl(data, template): \"\"\" Replace {$ttl} in template",
"soa_txt) else: # clear all SOA fields record = record.replace(\"{soa}\", \"\") return record",
"\"\"\" return process_rr(data, \"CNAME\", \"alias\", \"{cname}\", template) def process_mx(data, template): \"\"\" Replace {mx}",
"to deal #in the Software without restriction, including without limitation the rights #to",
"of the Software, and to permit persons to whom the Software is #furnished",
"restriction, including without limitation the rights #to use, copy, modify, merge, publish, distribute,",
"'@')) ) if data[i].get('ttl') is not None: record_data.append( str(data[i]['ttl']) ) record_data.append(record_type) record_data +=",
"str(data[key]) soadat.append(value) soadat.append(\")\") soa_txt = \" \".join(soadat) record = record.replace(\"{soa}\", soa_txt) else: #",
"Quote a field in a list of DNS records. Return the new data",
"Blockstack #Permission is hereby granted, free of charge, to any person obtaining a",
"records \"\"\" return process_rr(data, \"AAAA\", \"ip\", \"{aaaa}\", template) def process_cname(data, template): \"\"\" Replace",
"{txt} in template with the serialized TXT records \"\"\" # quote txt data_dup",
"def process_soa(data, template): \"\"\" Replace {SOA} in template with a set of serialized",
"in template with a serialized $TTL record \"\"\" record = \"\" if data",
"record_keys = [record_keys] else: raise ValueError(\"Invalid record keys\") assert type(data) == list, \"Data",
"#furnished to do so, subject to the following conditions: #The above copyright notice",
"OTHER #LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,",
"data[i].keys(), \"Missing '%s'\" % record_key record_data = [] record_data.append( str(data[i].get('name', '@')) ) if",
"License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- #The MIT License",
"type(record_keys) == list: pass elif type(record_keys) == str: record_keys = [record_keys] else: raise",
"+= \"$TTL %s\" % data return template.replace(\"{$ttl}\", record) def process_soa(data, template): \"\"\" Replace",
"OF MERCHANTABILITY, #FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL",
"this software and associated documentation files (the \"Software\"), to deal #in the Software",
"@record_key from each datum. \"\"\" if data is None: return template.replace(field, \"\") if",
"# clear all SOA fields record = record.replace(\"{soa}\", \"\") return record def quote_field(data,",
"2016 Blockstack #Permission is hereby granted, free of charge, to any person obtaining",
"in record_keys] record += \" \".join(record_data) + \"\\n\" return template.replace(field, record) def process_ns(data,",
"records \"\"\" return process_rr(data, \"A\", \"ip\", \"{a}\", template) def process_aaaa(data, template): \"\"\" Replace",
"{a} in template with the serialized A records \"\"\" return process_rr(data, \"A\", \"ip\",",
"the serialized SPF records \"\"\" return process_rr(data, \"SPF\", \"data\", \"{spf}\", template) def process_uri(data,",
"OF ANY KIND, EXPRESS OR #IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES",
"serialized A records \"\"\" return process_rr(data, \"A\", \"ip\", \"{a}\", template) def process_aaaa(data, template):",
"\"\"\" return process_rr(data, \"PTR\", \"host\", \"{ptr}\", template) def process_txt(data, template): \"\"\" Replace {txt}",
"persons to whom the Software is #furnished to do so, subject to the",
"\"Only support one SOA RR at this time\" data = data[0] soadat =",
"template): \"\"\" Replace {ns} in template with the serialized NS records \"\"\" return",
"process_rr(data, \"PTR\", \"host\", \"{ptr}\", template) def process_txt(data, template): \"\"\" Replace {txt} in template",
"in the project root for license information. # -------------------------------------------------------------------------------------------- #The MIT License (MIT)",
"record.replace(\"{soa}\", \"\") return record def quote_field(data, field): \"\"\" Quote a field in a",
"\"PTR\", \"host\", \"{ptr}\", template) def process_txt(data, template): \"\"\" Replace {txt} in template with",
"the MIT License. See License.txt in the project root for license information. #",
"License. See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- #The",
"#to use, copy, modify, merge, publish, distribute, sublicense, and/or sell #copies of the",
"process_ptr(data, template): \"\"\" Replace {ptr} in template with the serialized PTR records \"\"\"",
"records \"\"\" return process_rr(data, \"CNAME\", \"alias\", \"{cname}\", template) def process_mx(data, template): \"\"\" Replace",
"type(data) == list, \"Data must be a list\" record = \"\" for i",
"template with a set of serialized SOA records \"\"\" record = template[:] if",
"if data.get('ttl') is not None: soadat.append( str(data['ttl']) ) soadat.append(\"IN\") soadat.append(\"SOA\") for key in",
"software and associated documentation files (the \"Software\"), to deal #in the Software without",
"\"SPF\", \"data\", \"{spf}\", template) def process_uri(data, template): \"\"\" Replace {uri} in templtae with",
"to whom the Software is #furnished to do so, subject to the following",
"is not None: record += \"$ORIGIN %s\" % data return template.replace(\"{$origin}\", record) def",
"Replace {$ttl} in template with a serialized $TTL record \"\"\" record = \"\"",
"DAMAGES OR OTHER #LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,",
"be a list\" record = \"\" for i in range(0, len(data)): for record_key",
"\"\"\" Replace {aaaa} in template with the serialized A records \"\"\" return process_rr(data,",
"\"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #IMPLIED, INCLUDING BUT NOT",
"OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN",
"substantial portions of the Software. #THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY",
"\"MX\", [\"preference\", \"host\"], \"{mx}\", template) def process_ptr(data, template): \"\"\" Replace {ptr} in template",
"None: record_data.append( str(data[i]['ttl']) ) record_data.append(record_type) record_data += [str(data[i][record_key]) for record_key in record_keys] record",
"return template.replace(field, \"\") if type(record_keys) == list: pass elif type(record_keys) == str: record_keys",
"project root for license information. # -------------------------------------------------------------------------------------------- #The MIT License (MIT) #Copyright (c)",
"template): \"\"\" Replace {$ttl} in template with a serialized $TTL record \"\"\" record",
"this permission notice shall be included in all #copies or substantial portions of",
"#AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #LIABILITY,",
"any person obtaining a copy #of this software and associated documentation files (the",
"Replace {a} in template with the serialized A records \"\"\" return process_rr(data, \"A\",",
"\"\"\" if data is None: return template.replace(field, \"\") if type(record_keys) == list: pass",
"record_type, record_keys, field, template): \"\"\" Meta method: Replace $field in template with the",
"template) def process_srv(data, template): \"\"\" Replace {srv} in template with the serialized SRV",
"== 1, \"Only support one SOA RR at this time\" data = data[0]",
"soadat.append(\"IN\") soadat.append(\"SOA\") for key in domain_fields: value = str(data[key]) soadat.append(value) soadat.append(\"(\") for key",
"use, copy, modify, merge, publish, distribute, sublicense, and/or sell #copies of the Software,",
"a list of DNS records. Return the new data records. \"\"\" if data",
"= ['mname', 'rname'] param_fields = ['serial', 'refresh', 'retry', 'expire', 'minimum'] for f in",
"SOA RR at this time\" data = data[0] soadat = [] domain_fields =",
"is not None: assert len(data) == 1, \"Only support one SOA RR at",
"a serialized $ORIGIN record \"\"\" record = \"\" if data is not None:",
"list\" record = \"\" for i in range(0, len(data)): for record_key in record_keys:",
"data[i].get('ttl') is not None: record_data.append( str(data[i]['ttl']) ) record_data.append(record_type) record_data += [str(data[i][record_key]) for record_key",
"process_rr(data, \"MX\", [\"preference\", \"host\"], \"{mx}\", template) def process_ptr(data, template): \"\"\" Replace {ptr} in",
"with the serialized SPF records \"\"\" return process_rr(data, \"SPF\", \"data\", \"{spf}\", template) def",
"i in range(0, len(data_dup)): data_dup[i][field] = '\"%s\"' % data_dup[i][field] data_dup[i][field] = data_dup[i][field].replace(\";\", \"\\;\")",
"a field in a list of DNS records. Return the new data records.",
"== list: pass elif type(record_keys) == str: record_keys = [record_keys] else: raise ValueError(\"Invalid",
"in template with the serialized MX records \"\"\" return process_rr(data, \"MX\", [\"preference\", \"host\"],",
"template with the serialized MX records \"\"\" return process_rr(data, \"MX\", [\"preference\", \"host\"], \"{mx}\",",
"FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #AUTHORS OR",
"Replace {$origin} in template with a serialized $ORIGIN record \"\"\" record = \"\"",
"{$origin} in template with a serialized $ORIGIN record \"\"\" record = \"\" if",
"value = str(data[key]) soadat.append(value) soadat.append(\")\") soa_txt = \" \".join(soadat) record = record.replace(\"{soa}\", soa_txt)",
"support one SOA RR at this time\" data = data[0] soadat = []",
"+= \" \".join(record_data) + \"\\n\" return template.replace(field, record) def process_ns(data, template): \"\"\" Replace",
"reserved. # Licensed under the MIT License. See License.txt in the project root",
"person obtaining a copy #of this software and associated documentation files (the \"Software\"),",
"See License.txt in the project root for license information. # -------------------------------------------------------------------------------------------- #The MIT",
"all #copies or substantial portions of the Software. #THE SOFTWARE IS PROVIDED \"AS",
"THE WARRANTIES OF MERCHANTABILITY, #FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO",
"template): \"\"\" Replace {SOA} in template with a set of serialized SOA records",
"quote_field(data, field): \"\"\" Quote a field in a list of DNS records. Return",
"record_data += [str(data[i][record_key]) for record_key in record_keys] record += \" \".join(record_data) + \"\\n\"",
"= [record_keys] else: raise ValueError(\"Invalid record keys\") assert type(data) == list, \"Data must",
"template.replace(\"{$origin}\", record) def process_ttl(data, template): \"\"\" Replace {$ttl} in template with a serialized",
"\"\"\" Meta method: Replace $field in template with the serialized $record_type records, using",
"f in data.keys(), \"Missing '%s' (%s)\" % (f, data) data_name = str(data.get('name', '@'))",
"['mname', 'rname'] param_fields = ['serial', 'refresh', 'retry', 'expire', 'minimum'] for f in domain_fields",
"serialized MX records \"\"\" return process_rr(data, \"MX\", [\"preference\", \"host\"], \"{mx}\", template) def process_ptr(data,",
"permission notice shall be included in all #copies or substantial portions of the",
"template) def process_txt(data, template): \"\"\" Replace {txt} in template with the serialized TXT",
"records. \"\"\" if data is None: return None data_dup = copy.deepcopy(data) for i",
"template with the serialized SPF records \"\"\" return process_rr(data, \"SPF\", \"data\", \"{spf}\", template)",
"\"\"\" Replace {$origin} in template with a serialized $ORIGIN record \"\"\" record =",
"Replace {spf} in template with the serialized SPF records \"\"\" return process_rr(data, \"SPF\",",
"AND NONINFRINGEMENT. IN NO EVENT SHALL THE #AUTHORS OR COPYRIGHT HOLDERS BE LIABLE",
"return data_dup def process_rr(data, record_type, record_keys, field, template): \"\"\" Meta method: Replace $field",
"\"\"\" Replace {srv} in template with the serialized SRV records \"\"\" return process_rr(data,",
"txt data_dup = quote_field(data, \"txt\") return process_rr(data_dup, \"TXT\", \"txt\", \"{txt}\", template) def process_srv(data,",
"data) data_name = str(data.get('name', '@')) soadat.append(data_name) if data.get('ttl') is not None: soadat.append( str(data['ttl'])",
"= copy.deepcopy(data) for i in range(0, len(data_dup)): data_dup[i][field] = '\"%s\"' % data_dup[i][field] data_dup[i][field]",
"THE USE OR OTHER DEALINGS IN THE #SOFTWARE. #pylint: skip-file import copy def",
"NS records \"\"\" return process_rr(data, \"NS\", \"host\", \"{ns}\", template) def process_a(data, template): \"\"\"",
"[\"preference\", \"host\"], \"{mx}\", template) def process_ptr(data, template): \"\"\" Replace {ptr} in template with",
"#copies or substantial portions of the Software. #THE SOFTWARE IS PROVIDED \"AS IS\",",
"None data_dup = copy.deepcopy(data) for i in range(0, len(data_dup)): data_dup[i][field] = '\"%s\"' %",
"the serialized MX records \"\"\" return process_rr(data, \"MX\", [\"preference\", \"host\"], \"{mx}\", template) def",
"#pylint: skip-file import copy def process_origin(data, template): \"\"\" Replace {$origin} in template with",
"data_dup[i][field] data_dup[i][field] = data_dup[i][field].replace(\";\", \"\\;\") return data_dup def process_rr(data, record_type, record_keys, field, template):",
"\"{srv}\", template) def process_spf(data, template): \"\"\" Replace {spf} in template with the serialized",
"template.replace(field, record) def process_ns(data, template): \"\"\" Replace {ns} in template with the serialized",
"process_txt(data, template): \"\"\" Replace {txt} in template with the serialized TXT records \"\"\"",
"\"txt\", \"{txt}\", template) def process_srv(data, template): \"\"\" Replace {srv} in template with the",
"\"host\"], \"{mx}\", template) def process_ptr(data, template): \"\"\" Replace {ptr} in template with the",
"return process_rr(data, \"A\", \"ip\", \"{a}\", template) def process_aaaa(data, template): \"\"\" Replace {aaaa} in",
"\"\"\" record = template[:] if data is not None: assert len(data) == 1,",
"Replace {SOA} in template with a set of serialized SOA records \"\"\" record",
"def process_mx(data, template): \"\"\" Replace {mx} in template with the serialized MX records",
"WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #OUT OF",
"template with the serialized A records \"\"\" return process_rr(data, \"AAAA\", \"ip\", \"{aaaa}\", template)",
"record) def process_ttl(data, template): \"\"\" Replace {$ttl} in template with a serialized $TTL",
"$ORIGIN record \"\"\" record = \"\" if data is not None: record +=",
"process_soa(data, template): \"\"\" Replace {SOA} in template with a set of serialized SOA",
"\".join(record_data) + \"\\n\" return template.replace(field, record) def process_ns(data, template): \"\"\" Replace {ns} in",
"hereby granted, free of charge, to any person obtaining a copy #of this",
"data is None: return template.replace(field, \"\") if type(record_keys) == list: pass elif type(record_keys)",
"template) def process_cname(data, template): \"\"\" Replace {cname} in template with the serialized CNAME",
"\"\") return record def quote_field(data, field): \"\"\" Quote a field in a list",
"\"\" if data is not None: record += \"$ORIGIN %s\" % data return",
"'%s'\" % record_key record_data = [] record_data.append( str(data[i].get('name', '@')) ) if data[i].get('ttl') is",
"\"\"\" Replace {mx} in template with the serialized MX records \"\"\" return process_rr(data,",
"the serialized CNAME records \"\"\" return process_rr(data, \"CNAME\", \"alias\", \"{cname}\", template) def process_mx(data,",
"process_srv(data, template): \"\"\" Replace {srv} in template with the serialized SRV records \"\"\"",
"\"SRV\", [\"priority\", \"weight\", \"port\", \"target\"], \"{srv}\", template) def process_spf(data, template): \"\"\" Replace {spf}",
"NO EVENT SHALL THE #AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,",
"BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #LIABILITY, WHETHER IN AN ACTION",
"process_mx(data, template): \"\"\" Replace {mx} in template with the serialized MX records \"\"\"",
"in template with a set of serialized SOA records \"\"\" record = template[:]",
"{cname} in template with the serialized CNAME records \"\"\" return process_rr(data, \"CNAME\", \"alias\",",
"\"\"\" # quote target data_dup = quote_field(data, \"target\") return process_rr(data_dup, \"URI\", [\"priority\", \"weight\",",
"soadat = [] domain_fields = ['mname', 'rname'] param_fields = ['serial', 'refresh', 'retry', 'expire',",
"the serialized A records \"\"\" return process_rr(data, \"A\", \"ip\", \"{a}\", template) def process_aaaa(data,",
"{ns} in template with the serialized NS records \"\"\" return process_rr(data, \"NS\", \"host\",",
"process_rr(data, \"A\", \"ip\", \"{a}\", template) def process_aaaa(data, template): \"\"\" Replace {aaaa} in template",
"shall be included in all #copies or substantial portions of the Software. #THE",
"AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #OUT OF OR IN",
"records. Return the new data records. \"\"\" if data is None: return None",
"record = \"\" if data is not None: record += \"$TTL %s\" %",
"assert len(data) == 1, \"Only support one SOA RR at this time\" data",
"publish, distribute, sublicense, and/or sell #copies of the Software, and to permit persons",
"\"\"\" Replace {$ttl} in template with a serialized $TTL record \"\"\" record =",
"{aaaa} in template with the serialized A records \"\"\" return process_rr(data, \"AAAA\", \"ip\",",
"PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #AUTHORS OR COPYRIGHT HOLDERS",
"process_rr(data, \"SPF\", \"data\", \"{spf}\", template) def process_uri(data, template): \"\"\" Replace {uri} in templtae",
"limitation the rights #to use, copy, modify, merge, publish, distribute, sublicense, and/or sell",
"[] record_data.append( str(data[i].get('name', '@')) ) if data[i].get('ttl') is not None: record_data.append( str(data[i]['ttl']) )",
"Replace {ptr} in template with the serialized PTR records \"\"\" return process_rr(data, \"PTR\",",
"None: soadat.append( str(data['ttl']) ) soadat.append(\"IN\") soadat.append(\"SOA\") for key in domain_fields: value = str(data[key])",
"subject to the following conditions: #The above copyright notice and this permission notice",
"in record_keys: assert record_key in data[i].keys(), \"Missing '%s'\" % record_key record_data = []",
"None: return None data_dup = copy.deepcopy(data) for i in range(0, len(data_dup)): data_dup[i][field] =",
"None: assert len(data) == 1, \"Only support one SOA RR at this time\"",
"using @record_key from each datum. \"\"\" if data is None: return template.replace(field, \"\")",
"def process_ptr(data, template): \"\"\" Replace {ptr} in template with the serialized PTR records",
"return process_rr(data, \"CNAME\", \"alias\", \"{cname}\", template) def process_mx(data, template): \"\"\" Replace {mx} in",
"%s\" % data return template.replace(\"{$ttl}\", record) def process_soa(data, template): \"\"\" Replace {SOA} in",
"\".join(soadat) record = record.replace(\"{soa}\", soa_txt) else: # clear all SOA fields record =",
"'rname'] param_fields = ['serial', 'refresh', 'retry', 'expire', 'minimum'] for f in domain_fields +",
"process_rr(data, record_type, record_keys, field, template): \"\"\" Meta method: Replace $field in template with",
"{SOA} in template with a set of serialized SOA records \"\"\" record =",
"files (the \"Software\"), to deal #in the Software without restriction, including without limitation",
"\"ip\", \"{aaaa}\", template) def process_cname(data, template): \"\"\" Replace {cname} in template with the",
"{mx} in template with the serialized MX records \"\"\" return process_rr(data, \"MX\", [\"preference\",",
"(the \"Software\"), to deal #in the Software without restriction, including without limitation the",
"of serialized SOA records \"\"\" record = template[:] if data is not None:",
"license information. # -------------------------------------------------------------------------------------------- #The MIT License (MIT) #Copyright (c) 2016 Blockstack #Permission",
"process_cname(data, template): \"\"\" Replace {cname} in template with the serialized CNAME records \"\"\"",
"for f in domain_fields + param_fields: assert f in data.keys(), \"Missing '%s' (%s)\"",
"clear all SOA fields record = record.replace(\"{soa}\", \"\") return record def quote_field(data, field):",
"serialized $ORIGIN record \"\"\" record = \"\" if data is not None: record",
"MX records \"\"\" return process_rr(data, \"MX\", [\"preference\", \"host\"], \"{mx}\", template) def process_ptr(data, template):",
"All rights reserved. # Licensed under the MIT License. See License.txt in the",
"\"\"\" if data is None: return None data_dup = copy.deepcopy(data) for i in",
"CNAME records \"\"\" return process_rr(data, \"CNAME\", \"alias\", \"{cname}\", template) def process_mx(data, template): \"\"\"",
"Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt",
"OR OTHER DEALINGS IN THE #SOFTWARE. #pylint: skip-file import copy def process_origin(data, template):",
"serialized SPF records \"\"\" return process_rr(data, \"SPF\", \"data\", \"{spf}\", template) def process_uri(data, template):",
"#Permission is hereby granted, free of charge, to any person obtaining a copy",
"PTR records \"\"\" return process_rr(data, \"PTR\", \"host\", \"{ptr}\", template) def process_txt(data, template): \"\"\"",
"with the serialized CNAME records \"\"\" return process_rr(data, \"CNAME\", \"alias\", \"{cname}\", template) def",
"permit persons to whom the Software is #furnished to do so, subject to",
"(c) 2016 Blockstack #Permission is hereby granted, free of charge, to any person",
"SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #IMPLIED,",
"template): \"\"\" Replace {cname} in template with the serialized CNAME records \"\"\" return",
"template with the serialized CNAME records \"\"\" return process_rr(data, \"CNAME\", \"alias\", \"{cname}\", template)",
"process_rr(data_dup, \"TXT\", \"txt\", \"{txt}\", template) def process_srv(data, template): \"\"\" Replace {srv} in template",
"if data is None: return None data_dup = copy.deepcopy(data) for i in range(0,",
"without restriction, including without limitation the rights #to use, copy, modify, merge, publish,",
"EXPRESS OR #IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #FITNESS",
"f in domain_fields + param_fields: assert f in data.keys(), \"Missing '%s' (%s)\" %",
"else: # clear all SOA fields record = record.replace(\"{soa}\", \"\") return record def",
"records \"\"\" record = template[:] if data is not None: assert len(data) ==",
"rights #to use, copy, modify, merge, publish, distribute, sublicense, and/or sell #copies of",
"\"{a}\", template) def process_aaaa(data, template): \"\"\" Replace {aaaa} in template with the serialized",
"NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #FITNESS FOR A PARTICULAR PURPOSE AND",
"records \"\"\" return process_rr(data, \"PTR\", \"host\", \"{ptr}\", template) def process_txt(data, template): \"\"\" Replace",
"\"\"\" Replace {spf} in template with the serialized SPF records \"\"\" return process_rr(data,",
"copy, modify, merge, publish, distribute, sublicense, and/or sell #copies of the Software, and",
"= [] record_data.append( str(data[i].get('name', '@')) ) if data[i].get('ttl') is not None: record_data.append( str(data[i]['ttl'])",
"record = \"\" if data is not None: record += \"$ORIGIN %s\" %",
"in template with the serialized $record_type records, using @record_key from each datum. \"\"\"",
"if data is not None: record += \"$ORIGIN %s\" % data return template.replace(\"{$origin}\",",
"with the serialized URI records \"\"\" # quote target data_dup = quote_field(data, \"target\")",
"of the Software. #THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY",
"with a serialized $TTL record \"\"\" record = \"\" if data is not",
"record_data.append(record_type) record_data += [str(data[i][record_key]) for record_key in record_keys] record += \" \".join(record_data) +",
"\"{ns}\", template) def process_a(data, template): \"\"\" Replace {a} in template with the serialized",
"the serialized $record_type records, using @record_key from each datum. \"\"\" if data is",
"#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #FITNESS FOR A",
"soadat.append(\"SOA\") for key in domain_fields: value = str(data[key]) soadat.append(value) soadat.append(\"(\") for key in",
"\"\"\" return process_rr(data, \"SRV\", [\"priority\", \"weight\", \"port\", \"target\"], \"{srv}\", template) def process_spf(data, template):",
"\"\"\" # quote txt data_dup = quote_field(data, \"txt\") return process_rr(data_dup, \"TXT\", \"txt\", \"{txt}\",",
"new data records. \"\"\" if data is None: return None data_dup = copy.deepcopy(data)",
"(MIT) #Copyright (c) 2016 Blockstack #Permission is hereby granted, free of charge, to",
"with the serialized A records \"\"\" return process_rr(data, \"AAAA\", \"ip\", \"{aaaa}\", template) def",
"soadat.append(value) soadat.append(\"(\") for key in param_fields: value = str(data[key]) soadat.append(value) soadat.append(\")\") soa_txt =",
"including without limitation the rights #to use, copy, modify, merge, publish, distribute, sublicense,",
"if data[i].get('ttl') is not None: record_data.append( str(data[i]['ttl']) ) record_data.append(record_type) record_data += [str(data[i][record_key]) for",
"WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE #SOFTWARE. #pylint:",
"+= [str(data[i][record_key]) for record_key in record_keys] record += \" \".join(record_data) + \"\\n\" return",
"OR OTHER #LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING",
"'retry', 'expire', 'minimum'] for f in domain_fields + param_fields: assert f in data.keys(),",
"is #furnished to do so, subject to the following conditions: #The above copyright",
"in templtae with the serialized URI records \"\"\" # quote target data_dup =",
"DEALINGS IN THE #SOFTWARE. #pylint: skip-file import copy def process_origin(data, template): \"\"\" Replace",
"return template.replace(\"{$ttl}\", record) def process_soa(data, template): \"\"\" Replace {SOA} in template with a",
"== list, \"Data must be a list\" record = \"\" for i in",
"serialized SRV records \"\"\" return process_rr(data, \"SRV\", [\"priority\", \"weight\", \"port\", \"target\"], \"{srv}\", template)",
"str(data[i].get('name', '@')) ) if data[i].get('ttl') is not None: record_data.append( str(data[i]['ttl']) ) record_data.append(record_type) record_data",
"associated documentation files (the \"Software\"), to deal #in the Software without restriction, including",
"SPF records \"\"\" return process_rr(data, \"SPF\", \"data\", \"{spf}\", template) def process_uri(data, template): \"\"\"",
"in template with the serialized TXT records \"\"\" # quote txt data_dup =",
"= \"\" for i in range(0, len(data)): for record_key in record_keys: assert record_key",
"= \"\" if data is not None: record += \"$ORIGIN %s\" % data",
"return process_rr(data, \"SRV\", [\"priority\", \"weight\", \"port\", \"target\"], \"{srv}\", template) def process_spf(data, template): \"\"\"",
"soadat.append(value) soadat.append(\")\") soa_txt = \" \".join(soadat) record = record.replace(\"{soa}\", soa_txt) else: # clear",
"IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #OUT OF OR",
"template): \"\"\" Replace {$origin} in template with a serialized $ORIGIN record \"\"\" record",
"return process_rr(data, \"AAAA\", \"ip\", \"{aaaa}\", template) def process_cname(data, template): \"\"\" Replace {cname} in",
"list of DNS records. Return the new data records. \"\"\" if data is",
"IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #IMPLIED, INCLUDING",
"# Licensed under the MIT License. See License.txt in the project root for",
"obtaining a copy #of this software and associated documentation files (the \"Software\"), to",
"#FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #AUTHORS",
"in template with the serialized A records \"\"\" return process_rr(data, \"A\", \"ip\", \"{a}\",",
"= str(data.get('name', '@')) soadat.append(data_name) if data.get('ttl') is not None: soadat.append( str(data['ttl']) ) soadat.append(\"IN\")",
"param_fields: value = str(data[key]) soadat.append(value) soadat.append(\")\") soa_txt = \" \".join(soadat) record = record.replace(\"{soa}\",",
"copy def process_origin(data, template): \"\"\" Replace {$origin} in template with a serialized $ORIGIN",
"% data return template.replace(\"{$ttl}\", record) def process_soa(data, template): \"\"\" Replace {SOA} in template",
"sell #copies of the Software, and to permit persons to whom the Software",
"'@')) soadat.append(data_name) if data.get('ttl') is not None: soadat.append( str(data['ttl']) ) soadat.append(\"IN\") soadat.append(\"SOA\") for",
"so, subject to the following conditions: #The above copyright notice and this permission",
"def process_aaaa(data, template): \"\"\" Replace {aaaa} in template with the serialized A records",
"Software is #furnished to do so, subject to the following conditions: #The above",
"of DNS records. Return the new data records. \"\"\" if data is None:",
"serialized CNAME records \"\"\" return process_rr(data, \"CNAME\", \"alias\", \"{cname}\", template) def process_mx(data, template):",
"process_ns(data, template): \"\"\" Replace {ns} in template with the serialized NS records \"\"\"",
"\"\"\" return process_rr(data, \"SPF\", \"data\", \"{spf}\", template) def process_uri(data, template): \"\"\" Replace {uri}",
"in all #copies or substantial portions of the Software. #THE SOFTWARE IS PROVIDED",
"#Copyright (c) 2016 Blockstack #Permission is hereby granted, free of charge, to any",
"\"host\", \"{ptr}\", template) def process_txt(data, template): \"\"\" Replace {txt} in template with the",
"\"data\", \"{spf}\", template) def process_uri(data, template): \"\"\" Replace {uri} in templtae with the",
"quote target data_dup = quote_field(data, \"target\") return process_rr(data_dup, \"URI\", [\"priority\", \"weight\", \"target\"], \"{uri}\",",
"\"{aaaa}\", template) def process_cname(data, template): \"\"\" Replace {cname} in template with the serialized",
"serialized PTR records \"\"\" return process_rr(data, \"PTR\", \"host\", \"{ptr}\", template) def process_txt(data, template):",
"soadat.append(data_name) if data.get('ttl') is not None: soadat.append( str(data['ttl']) ) soadat.append(\"IN\") soadat.append(\"SOA\") for key",
"soa_txt = \" \".join(soadat) record = record.replace(\"{soa}\", soa_txt) else: # clear all SOA",
"data_dup[i][field] = data_dup[i][field].replace(\";\", \"\\;\") return data_dup def process_rr(data, record_type, record_keys, field, template): \"\"\"",
"quote txt data_dup = quote_field(data, \"txt\") return process_rr(data_dup, \"TXT\", \"txt\", \"{txt}\", template) def",
"data_dup def process_rr(data, record_type, record_keys, field, template): \"\"\" Meta method: Replace $field in",
"template with the serialized NS records \"\"\" return process_rr(data, \"NS\", \"host\", \"{ns}\", template)",
"\"\"\" return process_rr(data, \"A\", \"ip\", \"{a}\", template) def process_aaaa(data, template): \"\"\" Replace {aaaa}",
"LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.",
"in domain_fields + param_fields: assert f in data.keys(), \"Missing '%s' (%s)\" % (f,",
"Return the new data records. \"\"\" if data is None: return None data_dup",
"records \"\"\" return process_rr(data, \"SRV\", [\"priority\", \"weight\", \"port\", \"target\"], \"{srv}\", template) def process_spf(data,",
"in param_fields: value = str(data[key]) soadat.append(value) soadat.append(\")\") soa_txt = \" \".join(soadat) record =",
"raise ValueError(\"Invalid record keys\") assert type(data) == list, \"Data must be a list\"",
"TO THE WARRANTIES OF MERCHANTABILITY, #FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN",
"THE #AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER",
"Replace {uri} in templtae with the serialized URI records \"\"\" # quote target",
"record = record.replace(\"{soa}\", \"\") return record def quote_field(data, field): \"\"\" Quote a field",
"return process_rr(data, \"MX\", [\"preference\", \"host\"], \"{mx}\", template) def process_ptr(data, template): \"\"\" Replace {ptr}",
"IN THE #SOFTWARE. #pylint: skip-file import copy def process_origin(data, template): \"\"\" Replace {$origin}",
"return template.replace(\"{$origin}\", record) def process_ttl(data, template): \"\"\" Replace {$ttl} in template with a",
"the serialized PTR records \"\"\" return process_rr(data, \"PTR\", \"host\", \"{ptr}\", template) def process_txt(data,",
"\"\" for i in range(0, len(data)): for record_key in record_keys: assert record_key in",
"\"alias\", \"{cname}\", template) def process_mx(data, template): \"\"\" Replace {mx} in template with the",
"\"\"\" Replace {uri} in templtae with the serialized URI records \"\"\" # quote",
"process_ttl(data, template): \"\"\" Replace {$ttl} in template with a serialized $TTL record \"\"\"",
"PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #IMPLIED, INCLUDING BUT",
"WARRANTIES OF MERCHANTABILITY, #FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT",
"SOA records \"\"\" record = template[:] if data is not None: assert len(data)",
"record += \"$TTL %s\" % data return template.replace(\"{$ttl}\", record) def process_soa(data, template): \"\"\"",
"len(data) == 1, \"Only support one SOA RR at this time\" data =",
"in template with the serialized SRV records \"\"\" return process_rr(data, \"SRV\", [\"priority\", \"weight\",",
"whom the Software is #furnished to do so, subject to the following conditions:",
"documentation files (the \"Software\"), to deal #in the Software without restriction, including without",
"\"$ORIGIN %s\" % data return template.replace(\"{$origin}\", record) def process_ttl(data, template): \"\"\" Replace {$ttl}",
"\"\" if data is not None: record += \"$TTL %s\" % data return",
"$field in template with the serialized $record_type records, using @record_key from each datum.",
"process_aaaa(data, template): \"\"\" Replace {aaaa} in template with the serialized A records \"\"\"",
"records \"\"\" # quote target data_dup = quote_field(data, \"target\") return process_rr(data_dup, \"URI\", [\"priority\",",
"RR at this time\" data = data[0] soadat = [] domain_fields = ['mname',",
"= data[0] soadat = [] domain_fields = ['mname', 'rname'] param_fields = ['serial', 'refresh',",
"Replace {srv} in template with the serialized SRV records \"\"\" return process_rr(data, \"SRV\",",
"records \"\"\" return process_rr(data, \"MX\", [\"preference\", \"host\"], \"{mx}\", template) def process_ptr(data, template): \"\"\"",
"is not None: soadat.append( str(data['ttl']) ) soadat.append(\"IN\") soadat.append(\"SOA\") for key in domain_fields: value",
"\"target\"], \"{srv}\", template) def process_spf(data, template): \"\"\" Replace {spf} in template with the",
"serialized A records \"\"\" return process_rr(data, \"AAAA\", \"ip\", \"{aaaa}\", template) def process_cname(data, template):",
"list, \"Data must be a list\" record = \"\" for i in range(0,",
"LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #LIABILITY, WHETHER IN AN ACTION OF",
"= '\"%s\"' % data_dup[i][field] data_dup[i][field] = data_dup[i][field].replace(\";\", \"\\;\") return data_dup def process_rr(data, record_type,",
"process_rr(data, \"SRV\", [\"priority\", \"weight\", \"port\", \"target\"], \"{srv}\", template) def process_spf(data, template): \"\"\" Replace",
"a set of serialized SOA records \"\"\" record = template[:] if data is",
"data is not None: record += \"$TTL %s\" % data return template.replace(\"{$ttl}\", record)",
"record_data.append( str(data[i]['ttl']) ) record_data.append(record_type) record_data += [str(data[i][record_key]) for record_key in record_keys] record +=",
"\"ip\", \"{a}\", template) def process_aaaa(data, template): \"\"\" Replace {aaaa} in template with the",
"following conditions: #The above copyright notice and this permission notice shall be included",
"\"host\", \"{ns}\", template) def process_a(data, template): \"\"\" Replace {a} in template with the",
"TORT OR OTHERWISE, ARISING FROM, #OUT OF OR IN CONNECTION WITH THE SOFTWARE",
"not None: record += \"$TTL %s\" % data return template.replace(\"{$ttl}\", record) def process_soa(data,",
"$TTL record \"\"\" record = \"\" if data is not None: record +=",
"template) def process_a(data, template): \"\"\" Replace {a} in template with the serialized A",
"return None data_dup = copy.deepcopy(data) for i in range(0, len(data_dup)): data_dup[i][field] = '\"%s\"'",
"data_dup[i][field] = '\"%s\"' % data_dup[i][field] data_dup[i][field] = data_dup[i][field].replace(\";\", \"\\;\") return data_dup def process_rr(data,",
"key in domain_fields: value = str(data[key]) soadat.append(value) soadat.append(\"(\") for key in param_fields: value",
"if data is not None: record += \"$TTL %s\" % data return template.replace(\"{$ttl}\",",
"ARISING FROM, #OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE",
"'\"%s\"' % data_dup[i][field] data_dup[i][field] = data_dup[i][field].replace(\";\", \"\\;\") return data_dup def process_rr(data, record_type, record_keys,",
"records, using @record_key from each datum. \"\"\" if data is None: return template.replace(field,",
"record_keys, field, template): \"\"\" Meta method: Replace $field in template with the serialized",
"the serialized URI records \"\"\" # quote target data_dup = quote_field(data, \"target\") return",
"THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE #SOFTWARE. #pylint: skip-file",
"KIND, EXPRESS OR #IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,",
"soadat.append(\"(\") for key in param_fields: value = str(data[key]) soadat.append(value) soadat.append(\")\") soa_txt = \"",
"assert type(data) == list, \"Data must be a list\" record = \"\" for",
"(c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See",
"(f, data) data_name = str(data.get('name', '@')) soadat.append(data_name) if data.get('ttl') is not None: soadat.append(",
"A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE #AUTHORS OR COPYRIGHT",
"template.replace(\"{$ttl}\", record) def process_soa(data, template): \"\"\" Replace {SOA} in template with a set",
"'refresh', 'retry', 'expire', 'minimum'] for f in domain_fields + param_fields: assert f in",
"template with the serialized PTR records \"\"\" return process_rr(data, \"PTR\", \"host\", \"{ptr}\", template)",
"data = data[0] soadat = [] domain_fields = ['mname', 'rname'] param_fields = ['serial',",
"#of this software and associated documentation files (the \"Software\"), to deal #in the",
"range(0, len(data_dup)): data_dup[i][field] = '\"%s\"' % data_dup[i][field] data_dup[i][field] = data_dup[i][field].replace(\";\", \"\\;\") return data_dup",
"'expire', 'minimum'] for f in domain_fields + param_fields: assert f in data.keys(), \"Missing",
"Software without restriction, including without limitation the rights #to use, copy, modify, merge,",
"copy.deepcopy(data) for i in range(0, len(data_dup)): data_dup[i][field] = '\"%s\"' % data_dup[i][field] data_dup[i][field] =",
"+= \"$ORIGIN %s\" % data return template.replace(\"{$origin}\", record) def process_ttl(data, template): \"\"\" Replace",
"the serialized NS records \"\"\" return process_rr(data, \"NS\", \"host\", \"{ns}\", template) def process_a(data,",
"be included in all #copies or substantial portions of the Software. #THE SOFTWARE",
"value = str(data[key]) soadat.append(value) soadat.append(\"(\") for key in param_fields: value = str(data[key]) soadat.append(value)",
"sublicense, and/or sell #copies of the Software, and to permit persons to whom",
"def process_ttl(data, template): \"\"\" Replace {$ttl} in template with a serialized $TTL record",
"at this time\" data = data[0] soadat = [] domain_fields = ['mname', 'rname']",
"# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under",
"the Software is #furnished to do so, subject to the following conditions: #The",
"\"\"\" record = \"\" if data is not None: record += \"$ORIGIN %s\"",
"for record_key in record_keys: assert record_key in data[i].keys(), \"Missing '%s'\" % record_key record_data",
"record_key record_data = [] record_data.append( str(data[i].get('name', '@')) ) if data[i].get('ttl') is not None:",
"[str(data[i][record_key]) for record_key in record_keys] record += \" \".join(record_data) + \"\\n\" return template.replace(field,",
"\"\\n\" return template.replace(field, record) def process_ns(data, template): \"\"\" Replace {ns} in template with",
"\"\"\" Replace {cname} in template with the serialized CNAME records \"\"\" return process_rr(data,",
"A records \"\"\" return process_rr(data, \"AAAA\", \"ip\", \"{aaaa}\", template) def process_cname(data, template): \"\"\"",
"\" \".join(record_data) + \"\\n\" return template.replace(field, record) def process_ns(data, template): \"\"\" Replace {ns}",
"Meta method: Replace $field in template with the serialized $record_type records, using @record_key",
"\"weight\", \"port\", \"target\"], \"{srv}\", template) def process_spf(data, template): \"\"\" Replace {spf} in template",
"WARRANTY OF ANY KIND, EXPRESS OR #IMPLIED, INCLUDING BUT NOT LIMITED TO THE",
"record) def process_ns(data, template): \"\"\" Replace {ns} in template with the serialized NS",
"len(data_dup)): data_dup[i][field] = '\"%s\"' % data_dup[i][field] data_dup[i][field] = data_dup[i][field].replace(\";\", \"\\;\") return data_dup def",
"return process_rr(data_dup, \"TXT\", \"txt\", \"{txt}\", template) def process_srv(data, template): \"\"\" Replace {srv} in",
"do so, subject to the following conditions: #The above copyright notice and this",
"process_origin(data, template): \"\"\" Replace {$origin} in template with a serialized $ORIGIN record \"\"\"",
"param_fields = ['serial', 'refresh', 'retry', 'expire', 'minimum'] for f in domain_fields + param_fields:",
"record = template[:] if data is not None: assert len(data) == 1, \"Only",
"in data[i].keys(), \"Missing '%s'\" % record_key record_data = [] record_data.append( str(data[i].get('name', '@')) )",
"must be a list\" record = \"\" for i in range(0, len(data)): for",
"'minimum'] for f in domain_fields + param_fields: assert f in data.keys(), \"Missing '%s'",
"record = record.replace(\"{soa}\", soa_txt) else: # clear all SOA fields record = record.replace(\"{soa}\",",
"\"A\", \"ip\", \"{a}\", template) def process_aaaa(data, template): \"\"\" Replace {aaaa} in template with",
"OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, #OUT OF OR IN CONNECTION WITH",
"data is None: return None data_dup = copy.deepcopy(data) for i in range(0, len(data_dup)):",
"record.replace(\"{soa}\", soa_txt) else: # clear all SOA fields record = record.replace(\"{soa}\", \"\") return",
"#The MIT License (MIT) #Copyright (c) 2016 Blockstack #Permission is hereby granted, free",
"THE #SOFTWARE. #pylint: skip-file import copy def process_origin(data, template): \"\"\" Replace {$origin} in",
"serialized SOA records \"\"\" record = template[:] if data is not None: assert",
"i in range(0, len(data)): for record_key in record_keys: assert record_key in data[i].keys(), \"Missing",
"free of charge, to any person obtaining a copy #of this software and",
"\"NS\", \"host\", \"{ns}\", template) def process_a(data, template): \"\"\" Replace {a} in template with",
"quote_field(data, \"txt\") return process_rr(data_dup, \"TXT\", \"txt\", \"{txt}\", template) def process_srv(data, template): \"\"\" Replace",
"HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #LIABILITY, WHETHER IN AN",
"Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License.",
"one SOA RR at this time\" data = data[0] soadat = [] domain_fields",
"for i in range(0, len(data)): for record_key in record_keys: assert record_key in data[i].keys(),",
"templtae with the serialized URI records \"\"\" # quote target data_dup = quote_field(data,",
"\"TXT\", \"txt\", \"{txt}\", template) def process_srv(data, template): \"\"\" Replace {srv} in template with",
"= template[:] if data is not None: assert len(data) == 1, \"Only support",
"1, \"Only support one SOA RR at this time\" data = data[0] soadat",
"deal #in the Software without restriction, including without limitation the rights #to use,",
"in a list of DNS records. Return the new data records. \"\"\" if",
"from each datum. \"\"\" if data is None: return template.replace(field, \"\") if type(record_keys)",
"if data is not None: assert len(data) == 1, \"Only support one SOA",
"import copy def process_origin(data, template): \"\"\" Replace {$origin} in template with a serialized",
"return record def quote_field(data, field): \"\"\" Quote a field in a list of",
"template): \"\"\" Replace {mx} in template with the serialized MX records \"\"\" return",
"template): \"\"\" Replace {ptr} in template with the serialized PTR records \"\"\" return",
"URI records \"\"\" # quote target data_dup = quote_field(data, \"target\") return process_rr(data_dup, \"URI\",",
"EVENT SHALL THE #AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES",
"in template with a serialized $ORIGIN record \"\"\" record = \"\" if data",
") soadat.append(\"IN\") soadat.append(\"SOA\") for key in domain_fields: value = str(data[key]) soadat.append(value) soadat.append(\"(\") for",
"= record.replace(\"{soa}\", \"\") return record def quote_field(data, field): \"\"\" Quote a field in",
"elif type(record_keys) == str: record_keys = [record_keys] else: raise ValueError(\"Invalid record keys\") assert",
"serialized NS records \"\"\" return process_rr(data, \"NS\", \"host\", \"{ns}\", template) def process_a(data, template):",
"str(data.get('name', '@')) soadat.append(data_name) if data.get('ttl') is not None: soadat.append( str(data['ttl']) ) soadat.append(\"IN\") soadat.append(\"SOA\")",
"for key in param_fields: value = str(data[key]) soadat.append(value) soadat.append(\")\") soa_txt = \" \".join(soadat)",
"\"AAAA\", \"ip\", \"{aaaa}\", template) def process_cname(data, template): \"\"\" Replace {cname} in template with",
"record_key in record_keys: assert record_key in data[i].keys(), \"Missing '%s'\" % record_key record_data =",
"OTHER DEALINGS IN THE #SOFTWARE. #pylint: skip-file import copy def process_origin(data, template): \"\"\"",
"TXT records \"\"\" # quote txt data_dup = quote_field(data, \"txt\") return process_rr(data_dup, \"TXT\",",
"template.replace(field, \"\") if type(record_keys) == list: pass elif type(record_keys) == str: record_keys =",
"Replace {ns} in template with the serialized NS records \"\"\" return process_rr(data, \"NS\",",
"OR THE USE OR OTHER DEALINGS IN THE #SOFTWARE. #pylint: skip-file import copy",
"\"Data must be a list\" record = \"\" for i in range(0, len(data)):",
"{ptr} in template with the serialized PTR records \"\"\" return process_rr(data, \"PTR\", \"host\",",
"\"\"\" record = \"\" if data is not None: record += \"$TTL %s\"",
"data.keys(), \"Missing '%s' (%s)\" % (f, data) data_name = str(data.get('name', '@')) soadat.append(data_name) if",
"= ['serial', 'refresh', 'retry', 'expire', 'minimum'] for f in domain_fields + param_fields: assert",
"skip-file import copy def process_origin(data, template): \"\"\" Replace {$origin} in template with a",
"% data_dup[i][field] data_dup[i][field] = data_dup[i][field].replace(\";\", \"\\;\") return data_dup def process_rr(data, record_type, record_keys, field,",
"template with the serialized TXT records \"\"\" # quote txt data_dup = quote_field(data,",
"record = \"\" for i in range(0, len(data)): for record_key in record_keys: assert",
"copy #of this software and associated documentation files (the \"Software\"), to deal #in",
"the following conditions: #The above copyright notice and this permission notice shall be",
"[record_keys] else: raise ValueError(\"Invalid record keys\") assert type(data) == list, \"Data must be",
"template with a serialized $TTL record \"\"\" record = \"\" if data is",
"= data_dup[i][field].replace(\";\", \"\\;\") return data_dup def process_rr(data, record_type, record_keys, field, template): \"\"\" Meta",
"the Software. #THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND,",
"under the MIT License. See License.txt in the project root for license information.",
"\"\"\" Quote a field in a list of DNS records. Return the new",
"\"$TTL %s\" % data return template.replace(\"{$ttl}\", record) def process_soa(data, template): \"\"\" Replace {SOA}",
"the serialized A records \"\"\" return process_rr(data, \"AAAA\", \"ip\", \"{aaaa}\", template) def process_cname(data,",
"{spf} in template with the serialized SPF records \"\"\" return process_rr(data, \"SPF\", \"data\",",
"to the following conditions: #The above copyright notice and this permission notice shall",
"record_keys: assert record_key in data[i].keys(), \"Missing '%s'\" % record_key record_data = [] record_data.append(",
"str: record_keys = [record_keys] else: raise ValueError(\"Invalid record keys\") assert type(data) == list,",
"return process_rr(data, \"NS\", \"host\", \"{ns}\", template) def process_a(data, template): \"\"\" Replace {a} in",
"# -------------------------------------------------------------------------------------------- #The MIT License (MIT) #Copyright (c) 2016 Blockstack #Permission is hereby",
"template with the serialized SRV records \"\"\" return process_rr(data, \"SRV\", [\"priority\", \"weight\", \"port\",",
"notice shall be included in all #copies or substantial portions of the Software.",
"with the serialized $record_type records, using @record_key from each datum. \"\"\" if data",
"return template.replace(field, record) def process_ns(data, template): \"\"\" Replace {ns} in template with the",
"included in all #copies or substantial portions of the Software. #THE SOFTWARE IS",
"CLAIM, DAMAGES OR OTHER #LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR",
"def process_cname(data, template): \"\"\" Replace {cname} in template with the serialized CNAME records",
"\"txt\") return process_rr(data_dup, \"TXT\", \"txt\", \"{txt}\", template) def process_srv(data, template): \"\"\" Replace {srv}",
"record) def process_soa(data, template): \"\"\" Replace {SOA} in template with a set of",
"template): \"\"\" Replace {srv} in template with the serialized SRV records \"\"\" return",
"data_dup[i][field].replace(\";\", \"\\;\") return data_dup def process_rr(data, record_type, record_keys, field, template): \"\"\" Meta method:",
"the serialized TXT records \"\"\" # quote txt data_dup = quote_field(data, \"txt\") return",
"in template with the serialized NS records \"\"\" return process_rr(data, \"NS\", \"host\", \"{ns}\",",
"record \"\"\" record = \"\" if data is not None: record += \"$ORIGIN",
"template) def process_mx(data, template): \"\"\" Replace {mx} in template with the serialized MX",
"data_dup = quote_field(data, \"txt\") return process_rr(data_dup, \"TXT\", \"txt\", \"{txt}\", template) def process_srv(data, template):",
"\"{txt}\", template) def process_srv(data, template): \"\"\" Replace {srv} in template with the serialized",
"= str(data[key]) soadat.append(value) soadat.append(\"(\") for key in param_fields: value = str(data[key]) soadat.append(value) soadat.append(\")\")",
"str(data[i]['ttl']) ) record_data.append(record_type) record_data += [str(data[i][record_key]) for record_key in record_keys] record += \"",
"or substantial portions of the Software. #THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT",
"template): \"\"\" Replace {a} in template with the serialized A records \"\"\" return",
"def process_uri(data, template): \"\"\" Replace {uri} in templtae with the serialized URI records",
"data is not None: record += \"$ORIGIN %s\" % data return template.replace(\"{$origin}\", record)",
"key in param_fields: value = str(data[key]) soadat.append(value) soadat.append(\")\") soa_txt = \" \".join(soadat) record",
"process_rr(data, \"CNAME\", \"alias\", \"{cname}\", template) def process_mx(data, template): \"\"\" Replace {mx} in template",
"INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #FITNESS FOR A PARTICULAR",
"assert record_key in data[i].keys(), \"Missing '%s'\" % record_key record_data = [] record_data.append( str(data[i].get('name',",
"list: pass elif type(record_keys) == str: record_keys = [record_keys] else: raise ValueError(\"Invalid record",
"return process_rr(data, \"SPF\", \"data\", \"{spf}\", template) def process_uri(data, template): \"\"\" Replace {uri} in",
"template) def process_aaaa(data, template): \"\"\" Replace {aaaa} in template with the serialized A",
"#in the Software without restriction, including without limitation the rights #to use, copy,",
"+ param_fields: assert f in data.keys(), \"Missing '%s' (%s)\" % (f, data) data_name",
"\"\"\" Replace {txt} in template with the serialized TXT records \"\"\" # quote",
"\"CNAME\", \"alias\", \"{cname}\", template) def process_mx(data, template): \"\"\" Replace {mx} in template with",
"return process_rr(data, \"PTR\", \"host\", \"{ptr}\", template) def process_txt(data, template): \"\"\" Replace {txt} in",
"OTHERWISE, ARISING FROM, #OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE",
"process_rr(data, \"AAAA\", \"ip\", \"{aaaa}\", template) def process_cname(data, template): \"\"\" Replace {cname} in template",
"# quote target data_dup = quote_field(data, \"target\") return process_rr(data_dup, \"URI\", [\"priority\", \"weight\", \"target\"],",
"with the serialized NS records \"\"\" return process_rr(data, \"NS\", \"host\", \"{ns}\", template) def",
"if type(record_keys) == list: pass elif type(record_keys) == str: record_keys = [record_keys] else:",
"domain_fields + param_fields: assert f in data.keys(), \"Missing '%s' (%s)\" % (f, data)",
"\"\"\" return process_rr(data, \"NS\", \"host\", \"{ns}\", template) def process_a(data, template): \"\"\" Replace {a}",
"process_spf(data, template): \"\"\" Replace {spf} in template with the serialized SPF records \"\"\"",
"Licensed under the MIT License. See License.txt in the project root for license",
"record def quote_field(data, field): \"\"\" Quote a field in a list of DNS",
"+ \"\\n\" return template.replace(field, record) def process_ns(data, template): \"\"\" Replace {ns} in template",
"OR #IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, #FITNESS FOR",
"this time\" data = data[0] soadat = [] domain_fields = ['mname', 'rname'] param_fields",
"data[0] soadat = [] domain_fields = ['mname', 'rname'] param_fields = ['serial', 'refresh', 'retry',",
"to do so, subject to the following conditions: #The above copyright notice and",
"type(record_keys) == str: record_keys = [record_keys] else: raise ValueError(\"Invalid record keys\") assert type(data)",
"template) def process_ptr(data, template): \"\"\" Replace {ptr} in template with the serialized PTR",
"record_data = [] record_data.append( str(data[i].get('name', '@')) ) if data[i].get('ttl') is not None: record_data.append(",
"with the serialized TXT records \"\"\" # quote txt data_dup = quote_field(data, \"txt\")",
"with the serialized PTR records \"\"\" return process_rr(data, \"PTR\", \"host\", \"{ptr}\", template) def",
"Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in",
"DNS records. Return the new data records. \"\"\" if data is None: return",
"and/or sell #copies of the Software, and to permit persons to whom the",
"IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE",
"is not None: record += \"$TTL %s\" % data return template.replace(\"{$ttl}\", record) def",
"and this permission notice shall be included in all #copies or substantial portions",
"data_name = str(data.get('name', '@')) soadat.append(data_name) if data.get('ttl') is not None: soadat.append( str(data['ttl']) )",
"str(data['ttl']) ) soadat.append(\"IN\") soadat.append(\"SOA\") for key in domain_fields: value = str(data[key]) soadat.append(value) soadat.append(\"(\")",
"a list\" record = \"\" for i in range(0, len(data)): for record_key in",
"\"\"\" return process_rr(data, \"MX\", [\"preference\", \"host\"], \"{mx}\", template) def process_ptr(data, template): \"\"\" Replace",
"for license information. # -------------------------------------------------------------------------------------------- #The MIT License (MIT) #Copyright (c) 2016 Blockstack",
"rights reserved. # Licensed under the MIT License. See License.txt in the project",
"method: Replace $field in template with the serialized $record_type records, using @record_key from",
"License (MIT) #Copyright (c) 2016 Blockstack #Permission is hereby granted, free of charge,",
"record_key in record_keys] record += \" \".join(record_data) + \"\\n\" return template.replace(field, record) def",
"the Software, and to permit persons to whom the Software is #furnished to",
"OR OTHERWISE, ARISING FROM, #OUT OF OR IN CONNECTION WITH THE SOFTWARE OR",
"SRV records \"\"\" return process_rr(data, \"SRV\", [\"priority\", \"weight\", \"port\", \"target\"], \"{srv}\", template) def",
"\"\"\" Replace {ns} in template with the serialized NS records \"\"\" return process_rr(data,",
"SOA fields record = record.replace(\"{soa}\", \"\") return record def quote_field(data, field): \"\"\" Quote",
"def process_spf(data, template): \"\"\" Replace {spf} in template with the serialized SPF records",
"\"{spf}\", template) def process_uri(data, template): \"\"\" Replace {uri} in templtae with the serialized",
"['serial', 'refresh', 'retry', 'expire', 'minimum'] for f in domain_fields + param_fields: assert f",
"#The above copyright notice and this permission notice shall be included in all",
"records \"\"\" # quote txt data_dup = quote_field(data, \"txt\") return process_rr(data_dup, \"TXT\", \"txt\",",
"ANY CLAIM, DAMAGES OR OTHER #LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT",
"[\"priority\", \"weight\", \"port\", \"target\"], \"{srv}\", template) def process_spf(data, template): \"\"\" Replace {spf} in",
"def process_ns(data, template): \"\"\" Replace {ns} in template with the serialized NS records",
"def process_rr(data, record_type, record_keys, field, template): \"\"\" Meta method: Replace $field in template",
"template): \"\"\" Replace {txt} in template with the serialized TXT records \"\"\" #",
"for i in range(0, len(data_dup)): data_dup[i][field] = '\"%s\"' % data_dup[i][field] data_dup[i][field] = data_dup[i][field].replace(\";\",",
"with the serialized MX records \"\"\" return process_rr(data, \"MX\", [\"preference\", \"host\"], \"{mx}\", template)",
"data records. \"\"\" if data is None: return None data_dup = copy.deepcopy(data) for",
"field): \"\"\" Quote a field in a list of DNS records. Return the",
"target data_dup = quote_field(data, \"target\") return process_rr(data_dup, \"URI\", [\"priority\", \"weight\", \"target\"], \"{uri}\", template)",
"records \"\"\" return process_rr(data, \"SPF\", \"data\", \"{spf}\", template) def process_uri(data, template): \"\"\" Replace",
"def process_txt(data, template): \"\"\" Replace {txt} in template with the serialized TXT records",
"Replace {txt} in template with the serialized TXT records \"\"\" # quote txt",
"= \" \".join(soadat) record = record.replace(\"{soa}\", soa_txt) else: # clear all SOA fields",
"-------------------------------------------------------------------------------------------- #The MIT License (MIT) #Copyright (c) 2016 Blockstack #Permission is hereby granted,",
"NONINFRINGEMENT. IN NO EVENT SHALL THE #AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR",
"with a set of serialized SOA records \"\"\" record = template[:] if data",
"MERCHANTABILITY, #FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE",
"merge, publish, distribute, sublicense, and/or sell #copies of the Software, and to permit",
"Replace $field in template with the serialized $record_type records, using @record_key from each",
"soadat.append( str(data['ttl']) ) soadat.append(\"IN\") soadat.append(\"SOA\") for key in domain_fields: value = str(data[key]) soadat.append(value)",
"WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #IMPLIED, INCLUDING BUT NOT LIMITED TO",
"str(data[key]) soadat.append(value) soadat.append(\"(\") for key in param_fields: value = str(data[key]) soadat.append(value) soadat.append(\")\") soa_txt",
"above copyright notice and this permission notice shall be included in all #copies",
"{uri} in templtae with the serialized URI records \"\"\" # quote target data_dup",
"modify, merge, publish, distribute, sublicense, and/or sell #copies of the Software, and to",
"else: raise ValueError(\"Invalid record keys\") assert type(data) == list, \"Data must be a",
"template): \"\"\" Replace {spf} in template with the serialized SPF records \"\"\" return",
"template with the serialized $record_type records, using @record_key from each datum. \"\"\" if",
"record_key in data[i].keys(), \"Missing '%s'\" % record_key record_data = [] record_data.append( str(data[i].get('name', '@'))",
"data return template.replace(\"{$origin}\", record) def process_ttl(data, template): \"\"\" Replace {$ttl} in template with",
"data is not None: assert len(data) == 1, \"Only support one SOA RR",
"keys\") assert type(data) == list, \"Data must be a list\" record = \"\"",
"for record_key in record_keys] record += \" \".join(record_data) + \"\\n\" return template.replace(field, record)",
"#SOFTWARE. #pylint: skip-file import copy def process_origin(data, template): \"\"\" Replace {$origin} in template",
"IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR #IMPLIED, INCLUDING BUT NOT LIMITED",
"def process_a(data, template): \"\"\" Replace {a} in template with the serialized A records",
"to any person obtaining a copy #of this software and associated documentation files",
"OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS",
"#OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER",
"process_a(data, template): \"\"\" Replace {a} in template with the serialized A records \"\"\"",
"$record_type records, using @record_key from each datum. \"\"\" if data is None: return",
"record_keys] record += \" \".join(record_data) + \"\\n\" return template.replace(field, record) def process_ns(data, template):",
"template with the serialized A records \"\"\" return process_rr(data, \"A\", \"ip\", \"{a}\", template)",
"#THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR",
"None: return template.replace(field, \"\") if type(record_keys) == list: pass elif type(record_keys) == str:",
"template[:] if data is not None: assert len(data) == 1, \"Only support one",
"record \"\"\" record = \"\" if data is not None: record += \"$TTL",
"\" \".join(soadat) record = record.replace(\"{soa}\", soa_txt) else: # clear all SOA fields record",
"SHALL THE #AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR",
"ValueError(\"Invalid record keys\") assert type(data) == list, \"Data must be a list\" record",
"in template with the serialized PTR records \"\"\" return process_rr(data, \"PTR\", \"host\", \"{ptr}\",",
"COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER #LIABILITY, WHETHER IN",
"IN NO EVENT SHALL THE #AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY",
"with the serialized SRV records \"\"\" return process_rr(data, \"SRV\", [\"priority\", \"weight\", \"port\", \"target\"],",
"len(data)): for record_key in record_keys: assert record_key in data[i].keys(), \"Missing '%s'\" % record_key",
"for key in domain_fields: value = str(data[key]) soadat.append(value) soadat.append(\"(\") for key in param_fields:",
"Software. #THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS",
"with the serialized A records \"\"\" return process_rr(data, \"A\", \"ip\", \"{a}\", template) def"
] |
[
"= list(input()) c = 0 if l[0] == '1': c+=1 if l[1] ==",
"l = list(input()) c = 0 if l[0] == '1': c+=1 if l[1]",
"c = 0 if l[0] == '1': c+=1 if l[1] == '1': c+=1",
"if l[0] == '1': c+=1 if l[1] == '1': c+=1 if l[2] ==",
"list(input()) c = 0 if l[0] == '1': c+=1 if l[1] == '1':",
"= 0 if l[0] == '1': c+=1 if l[1] == '1': c+=1 if",
"0 if l[0] == '1': c+=1 if l[1] == '1': c+=1 if l[2]",
"'1': c+=1 if l[1] == '1': c+=1 if l[2] == '1': c+=1 print(c)",
"l[0] == '1': c+=1 if l[1] == '1': c+=1 if l[2] == '1':",
"<filename>python/PlacingMarbles.py l = list(input()) c = 0 if l[0] == '1': c+=1 if",
"== '1': c+=1 if l[1] == '1': c+=1 if l[2] == '1': c+=1"
] |
[
"'completed', 'temporary', 'status') admin.site.register(models.AcquisitionSessionConfig, AcquisitionSessionConfigAdmin) class DataCollectorConfigAdmin(PolymorphicChildModelAdmin): base_model = models.DataCollectorConfig class GenericDataCollectorConfigAdmin(PolymorphicParentModelAdmin): list_display",
"import PolymorphicChildModelAdmin from csat.acquisition import get_collectors, models class AcquisitionSessionConfigAdmin(admin.ModelAdmin): list_display = ('id', 'name',",
"models.DataCollectorConfig class GenericDataCollectorConfigAdmin(PolymorphicParentModelAdmin): list_display = ('id', 'name', 'session_config') base_model = models.DataCollectorConfig def get_child_models(self):",
"class AcquisitionSessionConfigAdmin(admin.ModelAdmin): list_display = ('id', 'name', 'started', 'completed', 'temporary', 'status') admin.site.register(models.AcquisitionSessionConfig, AcquisitionSessionConfigAdmin) class",
"class GenericDataCollectorConfigAdmin(PolymorphicParentModelAdmin): list_display = ('id', 'name', 'session_config') base_model = models.DataCollectorConfig def get_child_models(self): def",
"= ('id', 'name', 'started', 'completed', 'temporary', 'status') admin.site.register(models.AcquisitionSessionConfig, AcquisitionSessionConfigAdmin) class DataCollectorConfigAdmin(PolymorphicChildModelAdmin): base_model =",
"'name', 'session_config') base_model = models.DataCollectorConfig def get_child_models(self): def iter_chldren(): for collector in get_collectors():",
"'started', 'completed', 'temporary', 'status') admin.site.register(models.AcquisitionSessionConfig, AcquisitionSessionConfigAdmin) class DataCollectorConfigAdmin(PolymorphicChildModelAdmin): base_model = models.DataCollectorConfig class GenericDataCollectorConfigAdmin(PolymorphicParentModelAdmin):",
"= models.DataCollectorConfig def get_child_models(self): def iter_chldren(): for collector in get_collectors(): yield (collector.get_model(), DataCollectorConfigAdmin)",
"PolymorphicParentModelAdmin from polymorphic.admin import PolymorphicChildModelAdmin from csat.acquisition import get_collectors, models class AcquisitionSessionConfigAdmin(admin.ModelAdmin): list_display",
"AcquisitionSessionConfigAdmin(admin.ModelAdmin): list_display = ('id', 'name', 'started', 'completed', 'temporary', 'status') admin.site.register(models.AcquisitionSessionConfig, AcquisitionSessionConfigAdmin) class DataCollectorConfigAdmin(PolymorphicChildModelAdmin):",
"list_display = ('id', 'name', 'session_config') base_model = models.DataCollectorConfig def get_child_models(self): def iter_chldren(): for",
"GenericDataCollectorConfigAdmin(PolymorphicParentModelAdmin): list_display = ('id', 'name', 'session_config') base_model = models.DataCollectorConfig def get_child_models(self): def iter_chldren():",
"polymorphic.admin import PolymorphicParentModelAdmin from polymorphic.admin import PolymorphicChildModelAdmin from csat.acquisition import get_collectors, models class",
"csat.acquisition import get_collectors, models class AcquisitionSessionConfigAdmin(admin.ModelAdmin): list_display = ('id', 'name', 'started', 'completed', 'temporary',",
"import PolymorphicParentModelAdmin from polymorphic.admin import PolymorphicChildModelAdmin from csat.acquisition import get_collectors, models class AcquisitionSessionConfigAdmin(admin.ModelAdmin):",
"get_collectors, models class AcquisitionSessionConfigAdmin(admin.ModelAdmin): list_display = ('id', 'name', 'started', 'completed', 'temporary', 'status') admin.site.register(models.AcquisitionSessionConfig,",
"base_model = models.DataCollectorConfig class GenericDataCollectorConfigAdmin(PolymorphicParentModelAdmin): list_display = ('id', 'name', 'session_config') base_model = models.DataCollectorConfig",
"from csat.acquisition import get_collectors, models class AcquisitionSessionConfigAdmin(admin.ModelAdmin): list_display = ('id', 'name', 'started', 'completed',",
"'name', 'started', 'completed', 'temporary', 'status') admin.site.register(models.AcquisitionSessionConfig, AcquisitionSessionConfigAdmin) class DataCollectorConfigAdmin(PolymorphicChildModelAdmin): base_model = models.DataCollectorConfig class",
"models class AcquisitionSessionConfigAdmin(admin.ModelAdmin): list_display = ('id', 'name', 'started', 'completed', 'temporary', 'status') admin.site.register(models.AcquisitionSessionConfig, AcquisitionSessionConfigAdmin)",
"= ('id', 'name', 'session_config') base_model = models.DataCollectorConfig def get_child_models(self): def iter_chldren(): for collector",
"import get_collectors, models class AcquisitionSessionConfigAdmin(admin.ModelAdmin): list_display = ('id', 'name', 'started', 'completed', 'temporary', 'status')",
"import admin from polymorphic.admin import PolymorphicParentModelAdmin from polymorphic.admin import PolymorphicChildModelAdmin from csat.acquisition import",
"('id', 'name', 'session_config') base_model = models.DataCollectorConfig def get_child_models(self): def iter_chldren(): for collector in",
"= models.DataCollectorConfig class GenericDataCollectorConfigAdmin(PolymorphicParentModelAdmin): list_display = ('id', 'name', 'session_config') base_model = models.DataCollectorConfig def",
"DataCollectorConfigAdmin(PolymorphicChildModelAdmin): base_model = models.DataCollectorConfig class GenericDataCollectorConfigAdmin(PolymorphicParentModelAdmin): list_display = ('id', 'name', 'session_config') base_model =",
"PolymorphicChildModelAdmin from csat.acquisition import get_collectors, models class AcquisitionSessionConfigAdmin(admin.ModelAdmin): list_display = ('id', 'name', 'started',",
"'status') admin.site.register(models.AcquisitionSessionConfig, AcquisitionSessionConfigAdmin) class DataCollectorConfigAdmin(PolymorphicChildModelAdmin): base_model = models.DataCollectorConfig class GenericDataCollectorConfigAdmin(PolymorphicParentModelAdmin): list_display = ('id',",
"admin from polymorphic.admin import PolymorphicParentModelAdmin from polymorphic.admin import PolymorphicChildModelAdmin from csat.acquisition import get_collectors,",
"list_display = ('id', 'name', 'started', 'completed', 'temporary', 'status') admin.site.register(models.AcquisitionSessionConfig, AcquisitionSessionConfigAdmin) class DataCollectorConfigAdmin(PolymorphicChildModelAdmin): base_model",
"def iter_chldren(): for collector in get_collectors(): yield (collector.get_model(), DataCollectorConfigAdmin) return tuple(iter_chldren()) admin.site.register(models.DataCollectorConfig, GenericDataCollectorConfigAdmin)",
"from django.contrib import admin from polymorphic.admin import PolymorphicParentModelAdmin from polymorphic.admin import PolymorphicChildModelAdmin from",
"django.contrib import admin from polymorphic.admin import PolymorphicParentModelAdmin from polymorphic.admin import PolymorphicChildModelAdmin from csat.acquisition",
"from polymorphic.admin import PolymorphicParentModelAdmin from polymorphic.admin import PolymorphicChildModelAdmin from csat.acquisition import get_collectors, models",
"polymorphic.admin import PolymorphicChildModelAdmin from csat.acquisition import get_collectors, models class AcquisitionSessionConfigAdmin(admin.ModelAdmin): list_display = ('id',",
"'session_config') base_model = models.DataCollectorConfig def get_child_models(self): def iter_chldren(): for collector in get_collectors(): yield",
"get_child_models(self): def iter_chldren(): for collector in get_collectors(): yield (collector.get_model(), DataCollectorConfigAdmin) return tuple(iter_chldren()) admin.site.register(models.DataCollectorConfig,",
"models.DataCollectorConfig def get_child_models(self): def iter_chldren(): for collector in get_collectors(): yield (collector.get_model(), DataCollectorConfigAdmin) return",
"'temporary', 'status') admin.site.register(models.AcquisitionSessionConfig, AcquisitionSessionConfigAdmin) class DataCollectorConfigAdmin(PolymorphicChildModelAdmin): base_model = models.DataCollectorConfig class GenericDataCollectorConfigAdmin(PolymorphicParentModelAdmin): list_display =",
"admin.site.register(models.AcquisitionSessionConfig, AcquisitionSessionConfigAdmin) class DataCollectorConfigAdmin(PolymorphicChildModelAdmin): base_model = models.DataCollectorConfig class GenericDataCollectorConfigAdmin(PolymorphicParentModelAdmin): list_display = ('id', 'name',",
"from polymorphic.admin import PolymorphicChildModelAdmin from csat.acquisition import get_collectors, models class AcquisitionSessionConfigAdmin(admin.ModelAdmin): list_display =",
"base_model = models.DataCollectorConfig def get_child_models(self): def iter_chldren(): for collector in get_collectors(): yield (collector.get_model(),",
"AcquisitionSessionConfigAdmin) class DataCollectorConfigAdmin(PolymorphicChildModelAdmin): base_model = models.DataCollectorConfig class GenericDataCollectorConfigAdmin(PolymorphicParentModelAdmin): list_display = ('id', 'name', 'session_config')",
"('id', 'name', 'started', 'completed', 'temporary', 'status') admin.site.register(models.AcquisitionSessionConfig, AcquisitionSessionConfigAdmin) class DataCollectorConfigAdmin(PolymorphicChildModelAdmin): base_model = models.DataCollectorConfig",
"def get_child_models(self): def iter_chldren(): for collector in get_collectors(): yield (collector.get_model(), DataCollectorConfigAdmin) return tuple(iter_chldren())",
"class DataCollectorConfigAdmin(PolymorphicChildModelAdmin): base_model = models.DataCollectorConfig class GenericDataCollectorConfigAdmin(PolymorphicParentModelAdmin): list_display = ('id', 'name', 'session_config') base_model"
] |
[
"collections import OrderedDict from lib.model import ImMatchNet from lib.pf_willow_dataset import PFDataset from lib.normalization",
"PF Willow dataset') use_cuda = torch.cuda.is_available() # Argument parsing parser = argparse.ArgumentParser(description='Compute PF",
"division import os from os.path import exists import numpy as np import torch",
"os from os.path import exists import numpy as np import torch import torch.nn",
"to PF Willow dataset') args = parser.parse_args() # Create model print('Creating CNN model...')",
"np.zeros((len(dataset), 1)) # Compute for i, batch in enumerate(dataloader): batch = batch_tnf(batch) batch_start_idx",
"default_collate from lib.torch_util import collate_custom import argparse print('NCNet evaluation script - PF Willow",
"args.image_size) dataset = Dataset(csv_file=os.path.join(args.eval_dataset_path, csv_file), dataset_path=args.eval_dataset_path, transform=NormalizeImageDict(['source_image', 'target_image']), output_size=cnn_image_size) dataset.pck_procedure = 'scnet' #",
"= corr_to_matches(corr4d, do_softmax=True) matches = (xA, yA, xB, yB) stats = pck_metric(batch, batch_start_idx,",
"i / len(dataloader))) # Print results results = stats['point_tnf']['pck'] good_idx = np.flatnonzero((results !=",
"import pck_metric from lib.dataloader import default_collate from lib.torch_util import collate_custom import argparse print('NCNet",
"# Compute for i, batch in enumerate(dataloader): batch = batch_tnf(batch) batch_start_idx = batch_size",
"args, use_cuda) print('Batch: [{}/{} ({:.0f}%)]'.format(i, len(dataloader), 100. * i / len(dataloader))) # Print",
"stats, args, use_cuda) print('Batch: [{}/{} ({:.0f}%)]'.format(i, len(dataloader), 100. * i / len(dataloader))) #",
"parser.add_argument('--checkpoint', type=str, default='') parser.add_argument('--image_size', type=int, default=400) parser.add_argument('--eval_dataset_path', type=str, default='datasets/', help='path to PF Willow",
"for storing results stats = {} stats['point_tnf'] = {} stats['point_tnf']['pck'] = np.zeros((len(dataset), 1))",
"= argparse.ArgumentParser(description='Compute PF Willow matches') parser.add_argument('--checkpoint', type=str, default='') parser.add_argument('--image_size', type=int, default=400) parser.add_argument('--eval_dataset_path', type=str,",
"= (args.image_size, args.image_size) dataset = Dataset(csv_file=os.path.join(args.eval_dataset_path, csv_file), dataset_path=args.eval_dataset_path, transform=NormalizeImageDict(['source_image', 'target_image']), output_size=cnn_image_size) dataset.pck_procedure =",
"default='') parser.add_argument('--image_size', type=int, default=400) parser.add_argument('--eval_dataset_path', type=str, default='datasets/', help='path to PF Willow dataset') args",
"CNN model...') model = ImMatchNet(use_cuda=use_cuda, checkpoint=args.checkpoint) # Dataset and dataloader Dataset = PFDataset",
"OrderedDict from lib.model import ImMatchNet from lib.pf_willow_dataset import PFDataset from lib.normalization import NormalizeImageDict",
"batch_size=1 is supported for evaluation batch_size = 1 dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=False,",
"# Argument parsing parser = argparse.ArgumentParser(description='Compute PF Willow matches') parser.add_argument('--checkpoint', type=str, default='') parser.add_argument('--image_size',",
"BatchTensorToVars(use_cuda=use_cuda) model.eval() # initialize vector for storing results stats = {} stats['point_tnf'] =",
"matches = (xA, yA, xB, yB) stats = pck_metric(batch, batch_start_idx, matches, stats, args,",
"yB) stats = pck_metric(batch, batch_start_idx, matches, stats, args, use_cuda) print('Batch: [{}/{} ({:.0f}%)]'.format(i, len(dataloader),",
"= torch.cuda.is_available() # Argument parsing parser = argparse.ArgumentParser(description='Compute PF Willow matches') parser.add_argument('--checkpoint', type=str,",
"i, batch in enumerate(dataloader): batch = batch_tnf(batch) batch_start_idx = batch_size * i corr4d",
"{} stats['point_tnf']['pck'] = np.zeros((len(dataset), 1)) # Compute for i, batch in enumerate(dataloader): batch",
"and dataloader Dataset = PFDataset collate_fn = default_collate csv_file = 'PF-dataset/test_pairs_pf.csv' cnn_image_size =",
"dataset = Dataset(csv_file=os.path.join(args.eval_dataset_path, csv_file), dataset_path=args.eval_dataset_path, transform=NormalizeImageDict(['source_image', 'target_image']), output_size=cnn_image_size) dataset.pck_procedure = 'scnet' # Only",
"= batch_tnf(batch) batch_start_idx = batch_size * i corr4d = model(batch) # get matches",
"# Only batch_size=1 is supported for evaluation batch_size = 1 dataloader = DataLoader(dataset,",
"batch_size=batch_size, shuffle=False, num_workers=0, collate_fn=collate_fn) batch_tnf = BatchTensorToVars(use_cuda=use_cuda) model.eval() # initialize vector for storing",
"= Dataset(csv_file=os.path.join(args.eval_dataset_path, csv_file), dataset_path=args.eval_dataset_path, transform=NormalizeImageDict(['source_image', 'target_image']), output_size=cnn_image_size) dataset.pck_procedure = 'scnet' # Only batch_size=1",
"as nn from torch.utils.data import Dataset, DataLoader from collections import OrderedDict from lib.model",
"dataset') args = parser.parse_args() # Create model print('Creating CNN model...') model = ImMatchNet(use_cuda=use_cuda,",
"dataset_path=args.eval_dataset_path, transform=NormalizeImageDict(['source_image', 'target_image']), output_size=cnn_image_size) dataset.pck_procedure = 'scnet' # Only batch_size=1 is supported for",
"xB, yB) stats = pck_metric(batch, batch_start_idx, matches, stats, args, use_cuda) print('Batch: [{}/{} ({:.0f}%)]'.format(i,",
"({:.0f}%)]'.format(i, len(dataloader), 100. * i / len(dataloader))) # Print results results = stats['point_tnf']['pck']",
"DataLoader(dataset, batch_size=batch_size, shuffle=False, num_workers=0, collate_fn=collate_fn) batch_tnf = BatchTensorToVars(use_cuda=use_cuda) model.eval() # initialize vector for",
"Willow dataset') use_cuda = torch.cuda.is_available() # Argument parsing parser = argparse.ArgumentParser(description='Compute PF Willow",
"= 'scnet' # Only batch_size=1 is supported for evaluation batch_size = 1 dataloader",
"good_idx = np.flatnonzero((results != -1) * ~np.isnan(results)) print('Total: ' + str(results.size)) print('Valid: '",
"for i, batch in enumerate(dataloader): batch = batch_tnf(batch) batch_start_idx = batch_size * i",
"import os from os.path import exists import numpy as np import torch import",
"shuffle=False, num_workers=0, collate_fn=collate_fn) batch_tnf = BatchTensorToVars(use_cuda=use_cuda) model.eval() # initialize vector for storing results",
"is supported for evaluation batch_size = 1 dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=False, num_workers=0,",
"transform=NormalizeImageDict(['source_image', 'target_image']), output_size=cnn_image_size) dataset.pck_procedure = 'scnet' # Only batch_size=1 is supported for evaluation",
"do_softmax=True) matches = (xA, yA, xB, yB) stats = pck_metric(batch, batch_start_idx, matches, stats,",
"use_cuda = torch.cuda.is_available() # Argument parsing parser = argparse.ArgumentParser(description='Compute PF Willow matches') parser.add_argument('--checkpoint',",
"results stats = {} stats['point_tnf'] = {} stats['point_tnf']['pck'] = np.zeros((len(dataset), 1)) # Compute",
"lib.normalization import NormalizeImageDict from lib.torch_util import BatchTensorToVars, str_to_bool from lib.point_tnf import corr_to_matches from",
"= model(batch) # get matches xA, yA, xB, yB, sB = corr_to_matches(corr4d, do_softmax=True)",
"in enumerate(dataloader): batch = batch_tnf(batch) batch_start_idx = batch_size * i corr4d = model(batch)",
"type=int, default=400) parser.add_argument('--eval_dataset_path', type=str, default='datasets/', help='path to PF Willow dataset') args = parser.parse_args()",
"BatchTensorToVars, str_to_bool from lib.point_tnf import corr_to_matches from lib.eval_util import pck_metric from lib.dataloader import",
"Print results results = stats['point_tnf']['pck'] good_idx = np.flatnonzero((results != -1) * ~np.isnan(results)) print('Total:",
"= parser.parse_args() # Create model print('Creating CNN model...') model = ImMatchNet(use_cuda=use_cuda, checkpoint=args.checkpoint) #",
"results = stats['point_tnf']['pck'] good_idx = np.flatnonzero((results != -1) * ~np.isnan(results)) print('Total: ' +",
"- PF Willow dataset') use_cuda = torch.cuda.is_available() # Argument parsing parser = argparse.ArgumentParser(description='Compute",
"cnn_image_size = (args.image_size, args.image_size) dataset = Dataset(csv_file=os.path.join(args.eval_dataset_path, csv_file), dataset_path=args.eval_dataset_path, transform=NormalizeImageDict(['source_image', 'target_image']), output_size=cnn_image_size) dataset.pck_procedure",
"help='path to PF Willow dataset') args = parser.parse_args() # Create model print('Creating CNN",
"Willow matches') parser.add_argument('--checkpoint', type=str, default='') parser.add_argument('--image_size', type=int, default=400) parser.add_argument('--eval_dataset_path', type=str, default='datasets/', help='path to",
"Argument parsing parser = argparse.ArgumentParser(description='Compute PF Willow matches') parser.add_argument('--checkpoint', type=str, default='') parser.add_argument('--image_size', type=int,",
"default_collate csv_file = 'PF-dataset/test_pairs_pf.csv' cnn_image_size = (args.image_size, args.image_size) dataset = Dataset(csv_file=os.path.join(args.eval_dataset_path, csv_file), dataset_path=args.eval_dataset_path,",
"model = ImMatchNet(use_cuda=use_cuda, checkpoint=args.checkpoint) # Dataset and dataloader Dataset = PFDataset collate_fn =",
"from torch.utils.data import Dataset, DataLoader from collections import OrderedDict from lib.model import ImMatchNet",
"!= -1) * ~np.isnan(results)) print('Total: ' + str(results.size)) print('Valid: ' + str(good_idx.size)) filtered_results",
"lib.dataloader import default_collate from lib.torch_util import collate_custom import argparse print('NCNet evaluation script -",
"= (xA, yA, xB, yB) stats = pck_metric(batch, batch_start_idx, matches, stats, args, use_cuda)",
"lib.eval_util import pck_metric from lib.dataloader import default_collate from lib.torch_util import collate_custom import argparse",
"from lib.dataloader import default_collate from lib.torch_util import collate_custom import argparse print('NCNet evaluation script",
"torch import torch.nn as nn from torch.utils.data import Dataset, DataLoader from collections import",
"= 'PF-dataset/test_pairs_pf.csv' cnn_image_size = (args.image_size, args.image_size) dataset = Dataset(csv_file=os.path.join(args.eval_dataset_path, csv_file), dataset_path=args.eval_dataset_path, transform=NormalizeImageDict(['source_image', 'target_image']),",
"Willow dataset') args = parser.parse_args() # Create model print('Creating CNN model...') model =",
"= batch_size * i corr4d = model(batch) # get matches xA, yA, xB,",
"from lib.pf_willow_dataset import PFDataset from lib.normalization import NormalizeImageDict from lib.torch_util import BatchTensorToVars, str_to_bool",
"as np import torch import torch.nn as nn from torch.utils.data import Dataset, DataLoader",
"= BatchTensorToVars(use_cuda=use_cuda) model.eval() # initialize vector for storing results stats = {} stats['point_tnf']",
"# initialize vector for storing results stats = {} stats['point_tnf'] = {} stats['point_tnf']['pck']",
"ImMatchNet from lib.pf_willow_dataset import PFDataset from lib.normalization import NormalizeImageDict from lib.torch_util import BatchTensorToVars,",
"lib.pf_willow_dataset import PFDataset from lib.normalization import NormalizeImageDict from lib.torch_util import BatchTensorToVars, str_to_bool from",
"PFDataset from lib.normalization import NormalizeImageDict from lib.torch_util import BatchTensorToVars, str_to_bool from lib.point_tnf import",
"batch_start_idx = batch_size * i corr4d = model(batch) # get matches xA, yA,",
"import PFDataset from lib.normalization import NormalizeImageDict from lib.torch_util import BatchTensorToVars, str_to_bool from lib.point_tnf",
"matches, stats, args, use_cuda) print('Batch: [{}/{} ({:.0f}%)]'.format(i, len(dataloader), 100. * i / len(dataloader)))",
"type=str, default='') parser.add_argument('--image_size', type=int, default=400) parser.add_argument('--eval_dataset_path', type=str, default='datasets/', help='path to PF Willow dataset')",
"storing results stats = {} stats['point_tnf'] = {} stats['point_tnf']['pck'] = np.zeros((len(dataset), 1)) #",
"[{}/{} ({:.0f}%)]'.format(i, len(dataloader), 100. * i / len(dataloader))) # Print results results =",
"100. * i / len(dataloader))) # Print results results = stats['point_tnf']['pck'] good_idx =",
"matches') parser.add_argument('--checkpoint', type=str, default='') parser.add_argument('--image_size', type=int, default=400) parser.add_argument('--eval_dataset_path', type=str, default='datasets/', help='path to PF",
"from lib.torch_util import BatchTensorToVars, str_to_bool from lib.point_tnf import corr_to_matches from lib.eval_util import pck_metric",
"1 dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=False, num_workers=0, collate_fn=collate_fn) batch_tnf = BatchTensorToVars(use_cuda=use_cuda) model.eval() #",
"import BatchTensorToVars, str_to_bool from lib.point_tnf import corr_to_matches from lib.eval_util import pck_metric from lib.dataloader",
"model(batch) # get matches xA, yA, xB, yB, sB = corr_to_matches(corr4d, do_softmax=True) matches",
"np.flatnonzero((results != -1) * ~np.isnan(results)) print('Total: ' + str(results.size)) print('Valid: ' + str(good_idx.size))",
"Compute for i, batch in enumerate(dataloader): batch = batch_tnf(batch) batch_start_idx = batch_size *",
"print('Batch: [{}/{} ({:.0f}%)]'.format(i, len(dataloader), 100. * i / len(dataloader))) # Print results results",
"results results = stats['point_tnf']['pck'] good_idx = np.flatnonzero((results != -1) * ~np.isnan(results)) print('Total: '",
"= DataLoader(dataset, batch_size=batch_size, shuffle=False, num_workers=0, collate_fn=collate_fn) batch_tnf = BatchTensorToVars(use_cuda=use_cuda) model.eval() # initialize vector",
"import torch.nn as nn from torch.utils.data import Dataset, DataLoader from collections import OrderedDict",
"model...') model = ImMatchNet(use_cuda=use_cuda, checkpoint=args.checkpoint) # Dataset and dataloader Dataset = PFDataset collate_fn",
"parser.add_argument('--image_size', type=int, default=400) parser.add_argument('--eval_dataset_path', type=str, default='datasets/', help='path to PF Willow dataset') args =",
"enumerate(dataloader): batch = batch_tnf(batch) batch_start_idx = batch_size * i corr4d = model(batch) #",
"'PF-dataset/test_pairs_pf.csv' cnn_image_size = (args.image_size, args.image_size) dataset = Dataset(csv_file=os.path.join(args.eval_dataset_path, csv_file), dataset_path=args.eval_dataset_path, transform=NormalizeImageDict(['source_image', 'target_image']), output_size=cnn_image_size)",
"args = parser.parse_args() # Create model print('Creating CNN model...') model = ImMatchNet(use_cuda=use_cuda, checkpoint=args.checkpoint)",
"default=400) parser.add_argument('--eval_dataset_path', type=str, default='datasets/', help='path to PF Willow dataset') args = parser.parse_args() #",
"csv_file = 'PF-dataset/test_pairs_pf.csv' cnn_image_size = (args.image_size, args.image_size) dataset = Dataset(csv_file=os.path.join(args.eval_dataset_path, csv_file), dataset_path=args.eval_dataset_path, transform=NormalizeImageDict(['source_image',",
"lib.torch_util import BatchTensorToVars, str_to_bool from lib.point_tnf import corr_to_matches from lib.eval_util import pck_metric from",
"Only batch_size=1 is supported for evaluation batch_size = 1 dataloader = DataLoader(dataset, batch_size=batch_size,",
"= np.zeros((len(dataset), 1)) # Compute for i, batch in enumerate(dataloader): batch = batch_tnf(batch)",
"batch in enumerate(dataloader): batch = batch_tnf(batch) batch_start_idx = batch_size * i corr4d =",
"from lib.eval_util import pck_metric from lib.dataloader import default_collate from lib.torch_util import collate_custom import",
"pck_metric from lib.dataloader import default_collate from lib.torch_util import collate_custom import argparse print('NCNet evaluation",
"batch_size * i corr4d = model(batch) # get matches xA, yA, xB, yB,",
"corr_to_matches from lib.eval_util import pck_metric from lib.dataloader import default_collate from lib.torch_util import collate_custom",
"DataLoader from collections import OrderedDict from lib.model import ImMatchNet from lib.pf_willow_dataset import PFDataset",
"nn from torch.utils.data import Dataset, DataLoader from collections import OrderedDict from lib.model import",
"# Dataset and dataloader Dataset = PFDataset collate_fn = default_collate csv_file = 'PF-dataset/test_pairs_pf.csv'",
"evaluation batch_size = 1 dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=False, num_workers=0, collate_fn=collate_fn) batch_tnf =",
"for evaluation batch_size = 1 dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=False, num_workers=0, collate_fn=collate_fn) batch_tnf",
"torch.cuda.is_available() # Argument parsing parser = argparse.ArgumentParser(description='Compute PF Willow matches') parser.add_argument('--checkpoint', type=str, default='')",
"matches xA, yA, xB, yB, sB = corr_to_matches(corr4d, do_softmax=True) matches = (xA, yA,",
"yA, xB, yB, sB = corr_to_matches(corr4d, do_softmax=True) matches = (xA, yA, xB, yB)",
"# Print results results = stats['point_tnf']['pck'] good_idx = np.flatnonzero((results != -1) * ~np.isnan(results))",
"exists import numpy as np import torch import torch.nn as nn from torch.utils.data",
"from lib.torch_util import collate_custom import argparse print('NCNet evaluation script - PF Willow dataset')",
"num_workers=0, collate_fn=collate_fn) batch_tnf = BatchTensorToVars(use_cuda=use_cuda) model.eval() # initialize vector for storing results stats",
"get matches xA, yA, xB, yB, sB = corr_to_matches(corr4d, do_softmax=True) matches = (xA,",
"corr_to_matches(corr4d, do_softmax=True) matches = (xA, yA, xB, yB) stats = pck_metric(batch, batch_start_idx, matches,",
"str_to_bool from lib.point_tnf import corr_to_matches from lib.eval_util import pck_metric from lib.dataloader import default_collate",
"script - PF Willow dataset') use_cuda = torch.cuda.is_available() # Argument parsing parser =",
"import torch import torch.nn as nn from torch.utils.data import Dataset, DataLoader from collections",
"ImMatchNet(use_cuda=use_cuda, checkpoint=args.checkpoint) # Dataset and dataloader Dataset = PFDataset collate_fn = default_collate csv_file",
"collate_fn = default_collate csv_file = 'PF-dataset/test_pairs_pf.csv' cnn_image_size = (args.image_size, args.image_size) dataset = Dataset(csv_file=os.path.join(args.eval_dataset_path,",
"numpy as np import torch import torch.nn as nn from torch.utils.data import Dataset,",
"import NormalizeImageDict from lib.torch_util import BatchTensorToVars, str_to_bool from lib.point_tnf import corr_to_matches from lib.eval_util",
"dataloader Dataset = PFDataset collate_fn = default_collate csv_file = 'PF-dataset/test_pairs_pf.csv' cnn_image_size = (args.image_size,",
"batch = batch_tnf(batch) batch_start_idx = batch_size * i corr4d = model(batch) # get",
"yB, sB = corr_to_matches(corr4d, do_softmax=True) matches = (xA, yA, xB, yB) stats =",
"batch_tnf(batch) batch_start_idx = batch_size * i corr4d = model(batch) # get matches xA,",
"# get matches xA, yA, xB, yB, sB = corr_to_matches(corr4d, do_softmax=True) matches =",
"batch_start_idx, matches, stats, args, use_cuda) print('Batch: [{}/{} ({:.0f}%)]'.format(i, len(dataloader), 100. * i /",
"PF Willow matches') parser.add_argument('--checkpoint', type=str, default='') parser.add_argument('--image_size', type=int, default=400) parser.add_argument('--eval_dataset_path', type=str, default='datasets/', help='path",
"'scnet' # Only batch_size=1 is supported for evaluation batch_size = 1 dataloader =",
"dataset.pck_procedure = 'scnet' # Only batch_size=1 is supported for evaluation batch_size = 1",
"print_function, division import os from os.path import exists import numpy as np import",
"= 1 dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=False, num_workers=0, collate_fn=collate_fn) batch_tnf = BatchTensorToVars(use_cuda=use_cuda) model.eval()",
"output_size=cnn_image_size) dataset.pck_procedure = 'scnet' # Only batch_size=1 is supported for evaluation batch_size =",
"= pck_metric(batch, batch_start_idx, matches, stats, args, use_cuda) print('Batch: [{}/{} ({:.0f}%)]'.format(i, len(dataloader), 100. *",
"= stats['point_tnf']['pck'] good_idx = np.flatnonzero((results != -1) * ~np.isnan(results)) print('Total: ' + str(results.size))",
"* ~np.isnan(results)) print('Total: ' + str(results.size)) print('Valid: ' + str(good_idx.size)) filtered_results = results[good_idx]",
"# Create model print('Creating CNN model...') model = ImMatchNet(use_cuda=use_cuda, checkpoint=args.checkpoint) # Dataset and",
"(args.image_size, args.image_size) dataset = Dataset(csv_file=os.path.join(args.eval_dataset_path, csv_file), dataset_path=args.eval_dataset_path, transform=NormalizeImageDict(['source_image', 'target_image']), output_size=cnn_image_size) dataset.pck_procedure = 'scnet'",
"{} stats['point_tnf'] = {} stats['point_tnf']['pck'] = np.zeros((len(dataset), 1)) # Compute for i, batch",
"__future__ import print_function, division import os from os.path import exists import numpy as",
"import numpy as np import torch import torch.nn as nn from torch.utils.data import",
"supported for evaluation batch_size = 1 dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=False, num_workers=0, collate_fn=collate_fn)",
"argparse.ArgumentParser(description='Compute PF Willow matches') parser.add_argument('--checkpoint', type=str, default='') parser.add_argument('--image_size', type=int, default=400) parser.add_argument('--eval_dataset_path', type=str, default='datasets/',",
"* i corr4d = model(batch) # get matches xA, yA, xB, yB, sB",
"from __future__ import print_function, division import os from os.path import exists import numpy",
"Dataset = PFDataset collate_fn = default_collate csv_file = 'PF-dataset/test_pairs_pf.csv' cnn_image_size = (args.image_size, args.image_size)",
"parser = argparse.ArgumentParser(description='Compute PF Willow matches') parser.add_argument('--checkpoint', type=str, default='') parser.add_argument('--image_size', type=int, default=400) parser.add_argument('--eval_dataset_path',",
"vector for storing results stats = {} stats['point_tnf'] = {} stats['point_tnf']['pck'] = np.zeros((len(dataset),",
"len(dataloader))) # Print results results = stats['point_tnf']['pck'] good_idx = np.flatnonzero((results != -1) *",
"from lib.point_tnf import corr_to_matches from lib.eval_util import pck_metric from lib.dataloader import default_collate from",
"import collate_custom import argparse print('NCNet evaluation script - PF Willow dataset') use_cuda =",
"import Dataset, DataLoader from collections import OrderedDict from lib.model import ImMatchNet from lib.pf_willow_dataset",
"xA, yA, xB, yB, sB = corr_to_matches(corr4d, do_softmax=True) matches = (xA, yA, xB,",
"yA, xB, yB) stats = pck_metric(batch, batch_start_idx, matches, stats, args, use_cuda) print('Batch: [{}/{}",
"import ImMatchNet from lib.pf_willow_dataset import PFDataset from lib.normalization import NormalizeImageDict from lib.torch_util import",
"= ImMatchNet(use_cuda=use_cuda, checkpoint=args.checkpoint) # Dataset and dataloader Dataset = PFDataset collate_fn = default_collate",
"import default_collate from lib.torch_util import collate_custom import argparse print('NCNet evaluation script - PF",
"= {} stats['point_tnf']['pck'] = np.zeros((len(dataset), 1)) # Compute for i, batch in enumerate(dataloader):",
"corr4d = model(batch) # get matches xA, yA, xB, yB, sB = corr_to_matches(corr4d,",
"stats['point_tnf'] = {} stats['point_tnf']['pck'] = np.zeros((len(dataset), 1)) # Compute for i, batch in",
"lib.model import ImMatchNet from lib.pf_willow_dataset import PFDataset from lib.normalization import NormalizeImageDict from lib.torch_util",
"xB, yB, sB = corr_to_matches(corr4d, do_softmax=True) matches = (xA, yA, xB, yB) stats",
"pck_metric(batch, batch_start_idx, matches, stats, args, use_cuda) print('Batch: [{}/{} ({:.0f}%)]'.format(i, len(dataloader), 100. * i",
"len(dataloader), 100. * i / len(dataloader))) # Print results results = stats['point_tnf']['pck'] good_idx",
"use_cuda) print('Batch: [{}/{} ({:.0f}%)]'.format(i, len(dataloader), 100. * i / len(dataloader))) # Print results",
"import argparse print('NCNet evaluation script - PF Willow dataset') use_cuda = torch.cuda.is_available() #",
"parser.parse_args() # Create model print('Creating CNN model...') model = ImMatchNet(use_cuda=use_cuda, checkpoint=args.checkpoint) # Dataset",
"checkpoint=args.checkpoint) # Dataset and dataloader Dataset = PFDataset collate_fn = default_collate csv_file =",
"print('Creating CNN model...') model = ImMatchNet(use_cuda=use_cuda, checkpoint=args.checkpoint) # Dataset and dataloader Dataset =",
"from os.path import exists import numpy as np import torch import torch.nn as",
"default='datasets/', help='path to PF Willow dataset') args = parser.parse_args() # Create model print('Creating",
"Dataset, DataLoader from collections import OrderedDict from lib.model import ImMatchNet from lib.pf_willow_dataset import",
"dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=False, num_workers=0, collate_fn=collate_fn) batch_tnf = BatchTensorToVars(use_cuda=use_cuda) model.eval() # initialize",
"batch_tnf = BatchTensorToVars(use_cuda=use_cuda) model.eval() # initialize vector for storing results stats = {}",
"i corr4d = model(batch) # get matches xA, yA, xB, yB, sB =",
"type=str, default='datasets/', help='path to PF Willow dataset') args = parser.parse_args() # Create model",
"from lib.model import ImMatchNet from lib.pf_willow_dataset import PFDataset from lib.normalization import NormalizeImageDict from",
"import corr_to_matches from lib.eval_util import pck_metric from lib.dataloader import default_collate from lib.torch_util import",
"stats = pck_metric(batch, batch_start_idx, matches, stats, args, use_cuda) print('Batch: [{}/{} ({:.0f}%)]'.format(i, len(dataloader), 100.",
"NormalizeImageDict from lib.torch_util import BatchTensorToVars, str_to_bool from lib.point_tnf import corr_to_matches from lib.eval_util import",
"argparse print('NCNet evaluation script - PF Willow dataset') use_cuda = torch.cuda.is_available() # Argument",
"model print('Creating CNN model...') model = ImMatchNet(use_cuda=use_cuda, checkpoint=args.checkpoint) # Dataset and dataloader Dataset",
"np import torch import torch.nn as nn from torch.utils.data import Dataset, DataLoader from",
"collate_custom import argparse print('NCNet evaluation script - PF Willow dataset') use_cuda = torch.cuda.is_available()",
"dataset') use_cuda = torch.cuda.is_available() # Argument parsing parser = argparse.ArgumentParser(description='Compute PF Willow matches')",
"import exists import numpy as np import torch import torch.nn as nn from",
"parsing parser = argparse.ArgumentParser(description='Compute PF Willow matches') parser.add_argument('--checkpoint', type=str, default='') parser.add_argument('--image_size', type=int, default=400)",
"Dataset(csv_file=os.path.join(args.eval_dataset_path, csv_file), dataset_path=args.eval_dataset_path, transform=NormalizeImageDict(['source_image', 'target_image']), output_size=cnn_image_size) dataset.pck_procedure = 'scnet' # Only batch_size=1 is",
"batch_size = 1 dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=False, num_workers=0, collate_fn=collate_fn) batch_tnf = BatchTensorToVars(use_cuda=use_cuda)",
"(xA, yA, xB, yB) stats = pck_metric(batch, batch_start_idx, matches, stats, args, use_cuda) print('Batch:",
"import print_function, division import os from os.path import exists import numpy as np",
"stats['point_tnf']['pck'] good_idx = np.flatnonzero((results != -1) * ~np.isnan(results)) print('Total: ' + str(results.size)) print('Valid:",
"= default_collate csv_file = 'PF-dataset/test_pairs_pf.csv' cnn_image_size = (args.image_size, args.image_size) dataset = Dataset(csv_file=os.path.join(args.eval_dataset_path, csv_file),",
"PFDataset collate_fn = default_collate csv_file = 'PF-dataset/test_pairs_pf.csv' cnn_image_size = (args.image_size, args.image_size) dataset =",
"torch.utils.data import Dataset, DataLoader from collections import OrderedDict from lib.model import ImMatchNet from",
"sB = corr_to_matches(corr4d, do_softmax=True) matches = (xA, yA, xB, yB) stats = pck_metric(batch,",
"torch.nn as nn from torch.utils.data import Dataset, DataLoader from collections import OrderedDict from",
"= {} stats['point_tnf'] = {} stats['point_tnf']['pck'] = np.zeros((len(dataset), 1)) # Compute for i,",
"initialize vector for storing results stats = {} stats['point_tnf'] = {} stats['point_tnf']['pck'] =",
"* i / len(dataloader))) # Print results results = stats['point_tnf']['pck'] good_idx = np.flatnonzero((results",
"-1) * ~np.isnan(results)) print('Total: ' + str(results.size)) print('Valid: ' + str(good_idx.size)) filtered_results =",
"'target_image']), output_size=cnn_image_size) dataset.pck_procedure = 'scnet' # Only batch_size=1 is supported for evaluation batch_size",
"from lib.normalization import NormalizeImageDict from lib.torch_util import BatchTensorToVars, str_to_bool from lib.point_tnf import corr_to_matches",
"evaluation script - PF Willow dataset') use_cuda = torch.cuda.is_available() # Argument parsing parser",
"1)) # Compute for i, batch in enumerate(dataloader): batch = batch_tnf(batch) batch_start_idx =",
"model.eval() # initialize vector for storing results stats = {} stats['point_tnf'] = {}",
"print('Total: ' + str(results.size)) print('Valid: ' + str(good_idx.size)) filtered_results = results[good_idx] print('PCK:', '{:.2%}'.format(np.mean(filtered_results)))",
"parser.add_argument('--eval_dataset_path', type=str, default='datasets/', help='path to PF Willow dataset') args = parser.parse_args() # Create",
"os.path import exists import numpy as np import torch import torch.nn as nn",
"= PFDataset collate_fn = default_collate csv_file = 'PF-dataset/test_pairs_pf.csv' cnn_image_size = (args.image_size, args.image_size) dataset",
"Create model print('Creating CNN model...') model = ImMatchNet(use_cuda=use_cuda, checkpoint=args.checkpoint) # Dataset and dataloader",
"collate_fn=collate_fn) batch_tnf = BatchTensorToVars(use_cuda=use_cuda) model.eval() # initialize vector for storing results stats =",
"print('NCNet evaluation script - PF Willow dataset') use_cuda = torch.cuda.is_available() # Argument parsing",
"Dataset and dataloader Dataset = PFDataset collate_fn = default_collate csv_file = 'PF-dataset/test_pairs_pf.csv' cnn_image_size",
"csv_file), dataset_path=args.eval_dataset_path, transform=NormalizeImageDict(['source_image', 'target_image']), output_size=cnn_image_size) dataset.pck_procedure = 'scnet' # Only batch_size=1 is supported",
"import OrderedDict from lib.model import ImMatchNet from lib.pf_willow_dataset import PFDataset from lib.normalization import",
"stats['point_tnf']['pck'] = np.zeros((len(dataset), 1)) # Compute for i, batch in enumerate(dataloader): batch =",
"/ len(dataloader))) # Print results results = stats['point_tnf']['pck'] good_idx = np.flatnonzero((results != -1)",
"from collections import OrderedDict from lib.model import ImMatchNet from lib.pf_willow_dataset import PFDataset from",
"~np.isnan(results)) print('Total: ' + str(results.size)) print('Valid: ' + str(good_idx.size)) filtered_results = results[good_idx] print('PCK:',",
"PF Willow dataset') args = parser.parse_args() # Create model print('Creating CNN model...') model",
"lib.point_tnf import corr_to_matches from lib.eval_util import pck_metric from lib.dataloader import default_collate from lib.torch_util",
"= np.flatnonzero((results != -1) * ~np.isnan(results)) print('Total: ' + str(results.size)) print('Valid: ' +",
"stats = {} stats['point_tnf'] = {} stats['point_tnf']['pck'] = np.zeros((len(dataset), 1)) # Compute for",
"lib.torch_util import collate_custom import argparse print('NCNet evaluation script - PF Willow dataset') use_cuda"
] |
[
"return self._sectorCodeTable.updateAll(startDate, endDate) def getTradeDays(self, startDate, endDate): return self._tradeDayTable.get(startDate, endDate) def getLatestDateInDb(self): return",
"self._codeTable.stockSectors @property def stockCodesFunds(self): return self._codeTable.stockCodesFunds @property def stockAllCodesFunds(self): return self._codeTable.stockAllCodesFunds @property def",
"self._tradeDayTable.get(start, end) def tDaysCountInDb(self, start, end): return self._tradeDayTable.tDaysCountInDb(start, end) def tLatestDay(self): return self._tradeDayTable.tLatestDay()",
"@property def szIndex(self): return self._codeTable.szIndex @property def cybIndex(self): return self._codeTable.cybIndex @property def zxbIndex(self):",
"self._codeTable.szIndex @property def cybIndex(self): return self._codeTable.cybIndex @property def zxbIndex(self): return self._codeTable.zxbIndex @property def",
"return self._codeTable.etf50 @property def etf300(self): return self._codeTable.etf300 @property def etf500(self): return self._codeTable.etf500 @property",
"def tLatestDay(self): return self._tradeDayTable.tLatestDay() def tOldestDay(self): return self._tradeDayTable.tOldestDay() def isInTradeDayTable(self, startDate, endDate): return",
"self._tradeDayTable.tDaysOffset(base, n) def tDaysOffsetInDb(self, base, n=0): return self._tradeDayTable.tDaysOffsetInDb(base, n) def tDays(self, start, end):",
"def updateCodes(self): return self._codeTable.update() def updateTradeDays(self, startDate, endDate): return self._tradeDayTable.update(startDate, endDate) def updateSectorCodes(self,",
"@property def stockCodesFunds(self): return self._codeTable.stockCodesFunds @property def stockAllCodesFunds(self): return self._codeTable.stockAllCodesFunds @property def stockAllCodesFundsSectors(self):",
"@property def etf50(self): return self._codeTable.etf50 @property def etf300(self): return self._codeTable.etf300 @property def etf500(self):",
"self._codeTable.shIndex @property def szIndex(self): return self._codeTable.szIndex @property def cybIndex(self): return self._codeTable.cybIndex @property def",
"DyStockDataCommonEngine(object): \"\"\" 代码表和交易日数据引擎 \"\"\" def __init__(self, mongoDbEngine, gateway, info): self._mongoDbEngine = mongoDbEngine self._gateway",
"return self._codeTable.zxbIndex @property def etf50(self): return self._codeTable.etf50 @property def etf300(self): return self._codeTable.etf300 @property",
"self._codeTable.getIndex(code) def getCode(self, name): return self._codeTable.getCode(name) def getIndexStockCodes(self, index=None): return self._codeTable.getIndexStockCodes(index) def getIndexSectorStockCodes(self,",
"self._codeTable.stockFunds @property def stockSectors(self): return self._codeTable.stockSectors @property def stockCodesFunds(self): return self._codeTable.stockCodesFunds @property def",
"dates, codes=None): if not self._codeTable.load(codes): return False return self._tradeDayTable.load(dates) def loadCodeTable(self, codes=None): return",
"def loadTradeDays(self, dates): return self._tradeDayTable.load(dates) def loadSectorCodeTable(self, sectorCode, date, codes=None): return self._sectorCodeTable.load(sectorCode, date,",
"shIndex(self): return self._codeTable.shIndex @property def szIndex(self): return self._codeTable.szIndex @property def cybIndex(self): return self._codeTable.cybIndex",
"* from .DyStockDataTradeDayTable import * from .DyStockDataSectorCodeTable import * class DyStockDataCommonEngine(object): \"\"\" 代码表和交易日数据引擎",
"self._info) def updateCodes(self): return self._codeTable.update() def updateTradeDays(self, startDate, endDate): return self._tradeDayTable.update(startDate, endDate) def",
"getLatestDateInDb(self): return self._tradeDayTable.getLatestDateInDb() def getLatestTradeDayInDb(self): return self._tradeDayTable.getLatestTradeDayInDb() def getIndex(self, code): return self._codeTable.getIndex(code) def",
"stockSectors(self): return self._codeTable.stockSectors @property def stockCodesFunds(self): return self._codeTable.stockCodesFunds @property def stockAllCodesFunds(self): return self._codeTable.stockAllCodesFunds",
"self._info = info self._codeTable = DyStockDataCodeTable(self._mongoDbEngine, self._gateway, self._info) self._tradeDayTable = DyStockDataTradeDayTable(self._mongoDbEngine, self._gateway, self._info)",
"= mongoDbEngine self._gateway = gateway self._info = info self._codeTable = DyStockDataCodeTable(self._mongoDbEngine, self._gateway, self._info)",
"self._tradeDayTable = DyStockDataTradeDayTable(self._mongoDbEngine, self._gateway, self._info) self._sectorCodeTable = DyStockDataSectorCodeTable(self._mongoDbEngine, self._gateway, self._info) def updateCodes(self): return",
"def stockAllCodesFunds(self): return self._codeTable.stockAllCodesFunds @property def stockAllCodesFundsSectors(self): return self._codeTable.stockAllCodesFundsSectors @property def stockAllCodes(self): return",
"tOldestDay(self): return self._tradeDayTable.tOldestDay() def isInTradeDayTable(self, startDate, endDate): return self._tradeDayTable.isIn(startDate, endDate) def load(self, dates,",
"tDaysOffsetInDb(self, base, n=0): return self._tradeDayTable.tDaysOffsetInDb(base, n) def tDays(self, start, end): return self._tradeDayTable.get(start, end)",
"return self._sectorCodeTable.getSectorStockCodes(index) return self._codeTable.getIndexStockCodes(index) @property def shIndex(self): return self._codeTable.shIndex @property def szIndex(self): return",
"self._tradeDayTable.load(dates) def loadCodeTable(self, codes=None): return self._codeTable.load(codes) def loadTradeDays(self, dates): return self._tradeDayTable.load(dates) def loadSectorCodeTable(self,",
"return self._codeTable.shIndex @property def szIndex(self): return self._codeTable.szIndex @property def cybIndex(self): return self._codeTable.cybIndex @property",
"end) def tDaysCountInDb(self, start, end): return self._tradeDayTable.tDaysCountInDb(start, end) def tLatestDay(self): return self._tradeDayTable.tLatestDay() def",
"n) def tDaysOffsetInDb(self, base, n=0): return self._tradeDayTable.tDaysOffsetInDb(base, n) def tDays(self, start, end): return",
"def etf300(self): return self._codeTable.etf300 @property def etf500(self): return self._codeTable.etf500 @property def stockFunds(self): return",
"etf300(self): return self._codeTable.etf300 @property def etf500(self): return self._codeTable.etf500 @property def stockFunds(self): return self._codeTable.stockFunds",
"self._codeTable.load(codes): return False return self._tradeDayTable.load(dates) def loadCodeTable(self, codes=None): return self._codeTable.load(codes) def loadTradeDays(self, dates):",
"self._codeTable.stockCodes @property def stockIndexes(self): return self._codeTable.stockIndexes @property def stockIndexesSectors(self): return self._codeTable.stockIndexesSectors def tDaysOffset(self,",
"code): return self._codeTable.getIndex(code) def getCode(self, name): return self._codeTable.getCode(name) def getIndexStockCodes(self, index=None): return self._codeTable.getIndexStockCodes(index)",
"self._codeTable.getIndexStockCodes(index) @property def shIndex(self): return self._codeTable.shIndex @property def szIndex(self): return self._codeTable.szIndex @property def",
"DyStockDataSectorCodeTable(self._mongoDbEngine, self._gateway, self._info) def updateCodes(self): return self._codeTable.update() def updateTradeDays(self, startDate, endDate): return self._tradeDayTable.update(startDate,",
"def getCode(self, name): return self._codeTable.getCode(name) def getIndexStockCodes(self, index=None): return self._codeTable.getIndexStockCodes(index) def getIndexSectorStockCodes(self, index=None):",
"@property def zxbIndex(self): return self._codeTable.zxbIndex @property def etf50(self): return self._codeTable.etf50 @property def etf300(self):",
"return self._codeTable.szIndex @property def cybIndex(self): return self._codeTable.cybIndex @property def zxbIndex(self): return self._codeTable.zxbIndex @property",
"def loadCodeTable(self, codes=None): return self._codeTable.load(codes) def loadTradeDays(self, dates): return self._tradeDayTable.load(dates) def loadSectorCodeTable(self, sectorCode,",
"endDate): return self._tradeDayTable.get(startDate, endDate) def getLatestDateInDb(self): return self._tradeDayTable.getLatestDateInDb() def getLatestTradeDayInDb(self): return self._tradeDayTable.getLatestTradeDayInDb() def",
"return self._codeTable.stockCodes @property def stockIndexes(self): return self._codeTable.stockIndexes @property def stockIndexesSectors(self): return self._codeTable.stockIndexesSectors def",
"self._tradeDayTable.tDaysOffsetInDb(base, n) def tDays(self, start, end): return self._tradeDayTable.get(start, end) def tDaysCountInDb(self, start, end):",
"def tDaysOffset(self, base, n): return self._tradeDayTable.tDaysOffset(base, n) def tDaysOffsetInDb(self, base, n=0): return self._tradeDayTable.tDaysOffsetInDb(base,",
"return self._tradeDayTable.load(dates) def loadSectorCodeTable(self, sectorCode, date, codes=None): return self._sectorCodeTable.load(sectorCode, date, codes) def getSectorCodes(self,",
"return self._tradeDayTable.getLatestDateInDb() def getLatestTradeDayInDb(self): return self._tradeDayTable.getLatestTradeDayInDb() def getIndex(self, code): return self._codeTable.getIndex(code) def getCode(self,",
"cybIndex(self): return self._codeTable.cybIndex @property def zxbIndex(self): return self._codeTable.zxbIndex @property def etf50(self): return self._codeTable.etf50",
"return self._codeTable.stockAllCodesFundsSectors @property def stockAllCodes(self): return self._codeTable.stockAllCodes @property def stockCodes(self): return self._codeTable.stockCodes @property",
"return self._codeTable.getIndex(code) def getCode(self, name): return self._codeTable.getCode(name) def getIndexStockCodes(self, index=None): return self._codeTable.getIndexStockCodes(index) def",
"def stockIndexesSectors(self): return self._codeTable.stockIndexesSectors def tDaysOffset(self, base, n): return self._tradeDayTable.tDaysOffset(base, n) def tDaysOffsetInDb(self,",
"self._gateway, self._info) def updateCodes(self): return self._codeTable.update() def updateTradeDays(self, startDate, endDate): return self._tradeDayTable.update(startDate, endDate)",
"def stockAllCodes(self): return self._codeTable.stockAllCodes @property def stockCodes(self): return self._codeTable.stockCodes @property def stockIndexes(self): return",
"def loadSectorCodeTable(self, sectorCode, date, codes=None): return self._sectorCodeTable.load(sectorCode, date, codes) def getSectorCodes(self, sectorCode): return",
"stockCodes(self): return self._codeTable.stockCodes @property def stockIndexes(self): return self._codeTable.stockIndexes @property def stockIndexesSectors(self): return self._codeTable.stockIndexesSectors",
"self._codeTable.load(codes) def loadTradeDays(self, dates): return self._tradeDayTable.load(dates) def loadSectorCodeTable(self, sectorCode, date, codes=None): return self._sectorCodeTable.load(sectorCode,",
"updateCodes(self): return self._codeTable.update() def updateTradeDays(self, startDate, endDate): return self._tradeDayTable.update(startDate, endDate) def updateSectorCodes(self, sectorCode,",
"self._codeTable.cybIndex @property def zxbIndex(self): return self._codeTable.zxbIndex @property def etf50(self): return self._codeTable.etf50 @property def",
"endDate) def getTradeDays(self, startDate, endDate): return self._tradeDayTable.get(startDate, endDate) def getLatestDateInDb(self): return self._tradeDayTable.getLatestDateInDb() def",
"stockCodesFunds(self): return self._codeTable.stockCodesFunds @property def stockAllCodesFunds(self): return self._codeTable.stockAllCodesFunds @property def stockAllCodesFundsSectors(self): return self._codeTable.stockAllCodesFundsSectors",
".DyStockDataTradeDayTable import * from .DyStockDataSectorCodeTable import * class DyStockDataCommonEngine(object): \"\"\" 代码表和交易日数据引擎 \"\"\" def",
"if not self._codeTable.load(codes): return False return self._tradeDayTable.load(dates) def loadCodeTable(self, codes=None): return self._codeTable.load(codes) def",
"self._tradeDayTable.update(startDate, endDate) def updateSectorCodes(self, sectorCode, startDate, endDate): return self._sectorCodeTable.update(sectorCode, startDate, endDate) def updateAllSectorCodes(self,",
"return self._codeTable.getIndexStockCodes(index) def getIndexSectorStockCodes(self, index=None): if index in DyStockCommon.sectors: return self._sectorCodeTable.getSectorStockCodes(index) return self._codeTable.getIndexStockCodes(index)",
"index=None): return self._codeTable.getIndexStockCodes(index) def getIndexSectorStockCodes(self, index=None): if index in DyStockCommon.sectors: return self._sectorCodeTable.getSectorStockCodes(index) return",
"base, n=0): return self._tradeDayTable.tDaysOffsetInDb(base, n) def tDays(self, start, end): return self._tradeDayTable.get(start, end) def",
"gateway self._info = info self._codeTable = DyStockDataCodeTable(self._mongoDbEngine, self._gateway, self._info) self._tradeDayTable = DyStockDataTradeDayTable(self._mongoDbEngine, self._gateway,",
"def load(self, dates, codes=None): if not self._codeTable.load(codes): return False return self._tradeDayTable.load(dates) def loadCodeTable(self,",
"def tDays(self, start, end): return self._tradeDayTable.get(start, end) def tDaysCountInDb(self, start, end): return self._tradeDayTable.tDaysCountInDb(start,",
"stockIndexes(self): return self._codeTable.stockIndexes @property def stockIndexesSectors(self): return self._codeTable.stockIndexesSectors def tDaysOffset(self, base, n): return",
"return self._tradeDayTable.load(dates) def loadCodeTable(self, codes=None): return self._codeTable.load(codes) def loadTradeDays(self, dates): return self._tradeDayTable.load(dates) def",
"DyStockDataCodeTable(self._mongoDbEngine, self._gateway, self._info) self._tradeDayTable = DyStockDataTradeDayTable(self._mongoDbEngine, self._gateway, self._info) self._sectorCodeTable = DyStockDataSectorCodeTable(self._mongoDbEngine, self._gateway, self._info)",
"= DyStockDataSectorCodeTable(self._mongoDbEngine, self._gateway, self._info) def updateCodes(self): return self._codeTable.update() def updateTradeDays(self, startDate, endDate): return",
"return self._codeTable.stockSectors @property def stockCodesFunds(self): return self._codeTable.stockCodesFunds @property def stockAllCodesFunds(self): return self._codeTable.stockAllCodesFunds @property",
"n) def tDays(self, start, end): return self._tradeDayTable.get(start, end) def tDaysCountInDb(self, start, end): return",
"end): return self._tradeDayTable.tDaysCountInDb(start, end) def tLatestDay(self): return self._tradeDayTable.tLatestDay() def tOldestDay(self): return self._tradeDayTable.tOldestDay() def",
"self._tradeDayTable.tOldestDay() def isInTradeDayTable(self, startDate, endDate): return self._tradeDayTable.isIn(startDate, endDate) def load(self, dates, codes=None): if",
"* from .DyStockDataSectorCodeTable import * class DyStockDataCommonEngine(object): \"\"\" 代码表和交易日数据引擎 \"\"\" def __init__(self, mongoDbEngine,",
"self._tradeDayTable.isIn(startDate, endDate) def load(self, dates, codes=None): if not self._codeTable.load(codes): return False return self._tradeDayTable.load(dates)",
"startDate, endDate) def updateAllSectorCodes(self, startDate, endDate): return self._sectorCodeTable.updateAll(startDate, endDate) def getTradeDays(self, startDate, endDate):",
"end) def tLatestDay(self): return self._tradeDayTable.tLatestDay() def tOldestDay(self): return self._tradeDayTable.tOldestDay() def isInTradeDayTable(self, startDate, endDate):",
"return self._tradeDayTable.get(start, end) def tDaysCountInDb(self, start, end): return self._tradeDayTable.tDaysCountInDb(start, end) def tLatestDay(self): return",
"self._codeTable.stockAllCodes @property def stockCodes(self): return self._codeTable.stockCodes @property def stockIndexes(self): return self._codeTable.stockIndexes @property def",
"@property def etf300(self): return self._codeTable.etf300 @property def etf500(self): return self._codeTable.etf500 @property def stockFunds(self):",
"tLatestDay(self): return self._tradeDayTable.tLatestDay() def tOldestDay(self): return self._tradeDayTable.tOldestDay() def isInTradeDayTable(self, startDate, endDate): return self._tradeDayTable.isIn(startDate,",
"getCode(self, name): return self._codeTable.getCode(name) def getIndexStockCodes(self, index=None): return self._codeTable.getIndexStockCodes(index) def getIndexSectorStockCodes(self, index=None): if",
"return self._tradeDayTable.tOldestDay() def isInTradeDayTable(self, startDate, endDate): return self._tradeDayTable.isIn(startDate, endDate) def load(self, dates, codes=None):",
"getLatestTradeDayInDb(self): return self._tradeDayTable.getLatestTradeDayInDb() def getIndex(self, code): return self._codeTable.getIndex(code) def getCode(self, name): return self._codeTable.getCode(name)",
"代码表和交易日数据引擎 \"\"\" def __init__(self, mongoDbEngine, gateway, info): self._mongoDbEngine = mongoDbEngine self._gateway = gateway",
"def getLatestDateInDb(self): return self._tradeDayTable.getLatestDateInDb() def getLatestTradeDayInDb(self): return self._tradeDayTable.getLatestTradeDayInDb() def getIndex(self, code): return self._codeTable.getIndex(code)",
"info): self._mongoDbEngine = mongoDbEngine self._gateway = gateway self._info = info self._codeTable = DyStockDataCodeTable(self._mongoDbEngine,",
"n=0): return self._tradeDayTable.tDaysOffsetInDb(base, n) def tDays(self, start, end): return self._tradeDayTable.get(start, end) def tDaysCountInDb(self,",
"= info self._codeTable = DyStockDataCodeTable(self._mongoDbEngine, self._gateway, self._info) self._tradeDayTable = DyStockDataTradeDayTable(self._mongoDbEngine, self._gateway, self._info) self._sectorCodeTable",
"from .DyStockDataCodeTable import * from .DyStockDataTradeDayTable import * from .DyStockDataSectorCodeTable import * class",
"stockFunds(self): return self._codeTable.stockFunds @property def stockSectors(self): return self._codeTable.stockSectors @property def stockCodesFunds(self): return self._codeTable.stockCodesFunds",
"return self._tradeDayTable.update(startDate, endDate) def updateSectorCodes(self, sectorCode, startDate, endDate): return self._sectorCodeTable.update(sectorCode, startDate, endDate) def",
"updateSectorCodes(self, sectorCode, startDate, endDate): return self._sectorCodeTable.update(sectorCode, startDate, endDate) def updateAllSectorCodes(self, startDate, endDate): return",
"self._codeTable.stockCodesFunds @property def stockAllCodesFunds(self): return self._codeTable.stockAllCodesFunds @property def stockAllCodesFundsSectors(self): return self._codeTable.stockAllCodesFundsSectors @property def",
"startDate, endDate): return self._tradeDayTable.get(startDate, endDate) def getLatestDateInDb(self): return self._tradeDayTable.getLatestDateInDb() def getLatestTradeDayInDb(self): return self._tradeDayTable.getLatestTradeDayInDb()",
"def getIndexSectorStockCodes(self, index=None): if index in DyStockCommon.sectors: return self._sectorCodeTable.getSectorStockCodes(index) return self._codeTable.getIndexStockCodes(index) @property def",
"return self._tradeDayTable.tDaysOffset(base, n) def tDaysOffsetInDb(self, base, n=0): return self._tradeDayTable.tDaysOffsetInDb(base, n) def tDays(self, start,",
"zxbIndex(self): return self._codeTable.zxbIndex @property def etf50(self): return self._codeTable.etf50 @property def etf300(self): return self._codeTable.etf300",
"self._codeTable.stockIndexesSectors def tDaysOffset(self, base, n): return self._tradeDayTable.tDaysOffset(base, n) def tDaysOffsetInDb(self, base, n=0): return",
"return self._sectorCodeTable.update(sectorCode, startDate, endDate) def updateAllSectorCodes(self, startDate, endDate): return self._sectorCodeTable.updateAll(startDate, endDate) def getTradeDays(self,",
"loadCodeTable(self, codes=None): return self._codeTable.load(codes) def loadTradeDays(self, dates): return self._tradeDayTable.load(dates) def loadSectorCodeTable(self, sectorCode, date,",
"self._gateway, self._info) self._sectorCodeTable = DyStockDataSectorCodeTable(self._mongoDbEngine, self._gateway, self._info) def updateCodes(self): return self._codeTable.update() def updateTradeDays(self,",
"def stockSectors(self): return self._codeTable.stockSectors @property def stockCodesFunds(self): return self._codeTable.stockCodesFunds @property def stockAllCodesFunds(self): return",
"return self._codeTable.stockIndexes @property def stockIndexesSectors(self): return self._codeTable.stockIndexesSectors def tDaysOffset(self, base, n): return self._tradeDayTable.tDaysOffset(base,",
"self._codeTable.zxbIndex @property def etf50(self): return self._codeTable.etf50 @property def etf300(self): return self._codeTable.etf300 @property def",
"codes=None): return self._codeTable.load(codes) def loadTradeDays(self, dates): return self._tradeDayTable.load(dates) def loadSectorCodeTable(self, sectorCode, date, codes=None):",
"\"\"\" def __init__(self, mongoDbEngine, gateway, info): self._mongoDbEngine = mongoDbEngine self._gateway = gateway self._info",
"= gateway self._info = info self._codeTable = DyStockDataCodeTable(self._mongoDbEngine, self._gateway, self._info) self._tradeDayTable = DyStockDataTradeDayTable(self._mongoDbEngine,",
"self._codeTable.etf50 @property def etf300(self): return self._codeTable.etf300 @property def etf500(self): return self._codeTable.etf500 @property def",
"endDate) def updateSectorCodes(self, sectorCode, startDate, endDate): return self._sectorCodeTable.update(sectorCode, startDate, endDate) def updateAllSectorCodes(self, startDate,",
"in DyStockCommon.sectors: return self._sectorCodeTable.getSectorStockCodes(index) return self._codeTable.getIndexStockCodes(index) @property def shIndex(self): return self._codeTable.shIndex @property def",
"return self._codeTable.getIndexStockCodes(index) @property def shIndex(self): return self._codeTable.shIndex @property def szIndex(self): return self._codeTable.szIndex @property",
"return self._codeTable.stockCodesFunds @property def stockAllCodesFunds(self): return self._codeTable.stockAllCodesFunds @property def stockAllCodesFundsSectors(self): return self._codeTable.stockAllCodesFundsSectors @property",
"isInTradeDayTable(self, startDate, endDate): return self._tradeDayTable.isIn(startDate, endDate) def load(self, dates, codes=None): if not self._codeTable.load(codes):",
"updateTradeDays(self, startDate, endDate): return self._tradeDayTable.update(startDate, endDate) def updateSectorCodes(self, sectorCode, startDate, endDate): return self._sectorCodeTable.update(sectorCode,",
"import * class DyStockDataCommonEngine(object): \"\"\" 代码表和交易日数据引擎 \"\"\" def __init__(self, mongoDbEngine, gateway, info): self._mongoDbEngine",
"def cybIndex(self): return self._codeTable.cybIndex @property def zxbIndex(self): return self._codeTable.zxbIndex @property def etf50(self): return",
"@property def shIndex(self): return self._codeTable.shIndex @property def szIndex(self): return self._codeTable.szIndex @property def cybIndex(self):",
"def etf50(self): return self._codeTable.etf50 @property def etf300(self): return self._codeTable.etf300 @property def etf500(self): return",
"updateAllSectorCodes(self, startDate, endDate): return self._sectorCodeTable.updateAll(startDate, endDate) def getTradeDays(self, startDate, endDate): return self._tradeDayTable.get(startDate, endDate)",
"def stockIndexes(self): return self._codeTable.stockIndexes @property def stockIndexesSectors(self): return self._codeTable.stockIndexesSectors def tDaysOffset(self, base, n):",
"def tOldestDay(self): return self._tradeDayTable.tOldestDay() def isInTradeDayTable(self, startDate, endDate): return self._tradeDayTable.isIn(startDate, endDate) def load(self,",
"not self._codeTable.load(codes): return False return self._tradeDayTable.load(dates) def loadCodeTable(self, codes=None): return self._codeTable.load(codes) def loadTradeDays(self,",
"endDate): return self._sectorCodeTable.update(sectorCode, startDate, endDate) def updateAllSectorCodes(self, startDate, endDate): return self._sectorCodeTable.updateAll(startDate, endDate) def",
"@property def stockAllCodesFundsSectors(self): return self._codeTable.stockAllCodesFundsSectors @property def stockAllCodes(self): return self._codeTable.stockAllCodes @property def stockCodes(self):",
"return False return self._tradeDayTable.load(dates) def loadCodeTable(self, codes=None): return self._codeTable.load(codes) def loadTradeDays(self, dates): return",
"def tDaysCountInDb(self, start, end): return self._tradeDayTable.tDaysCountInDb(start, end) def tLatestDay(self): return self._tradeDayTable.tLatestDay() def tOldestDay(self):",
"codes=None): if not self._codeTable.load(codes): return False return self._tradeDayTable.load(dates) def loadCodeTable(self, codes=None): return self._codeTable.load(codes)",
"@property def stockAllCodesFunds(self): return self._codeTable.stockAllCodesFunds @property def stockAllCodesFundsSectors(self): return self._codeTable.stockAllCodesFundsSectors @property def stockAllCodes(self):",
"@property def etf500(self): return self._codeTable.etf500 @property def stockFunds(self): return self._codeTable.stockFunds @property def stockSectors(self):",
"getIndexStockCodes(self, index=None): return self._codeTable.getIndexStockCodes(index) def getIndexSectorStockCodes(self, index=None): if index in DyStockCommon.sectors: return self._sectorCodeTable.getSectorStockCodes(index)",
"base, n): return self._tradeDayTable.tDaysOffset(base, n) def tDaysOffsetInDb(self, base, n=0): return self._tradeDayTable.tDaysOffsetInDb(base, n) def",
".DyStockDataSectorCodeTable import * class DyStockDataCommonEngine(object): \"\"\" 代码表和交易日数据引擎 \"\"\" def __init__(self, mongoDbEngine, gateway, info):",
"return self._codeTable.stockAllCodes @property def stockCodes(self): return self._codeTable.stockCodes @property def stockIndexes(self): return self._codeTable.stockIndexes @property",
"return self._tradeDayTable.tLatestDay() def tOldestDay(self): return self._tradeDayTable.tOldestDay() def isInTradeDayTable(self, startDate, endDate): return self._tradeDayTable.isIn(startDate, endDate)",
"mongoDbEngine self._gateway = gateway self._info = info self._codeTable = DyStockDataCodeTable(self._mongoDbEngine, self._gateway, self._info) self._tradeDayTable",
"return self._tradeDayTable.tDaysOffsetInDb(base, n) def tDays(self, start, end): return self._tradeDayTable.get(start, end) def tDaysCountInDb(self, start,",
"load(self, dates, codes=None): if not self._codeTable.load(codes): return False return self._tradeDayTable.load(dates) def loadCodeTable(self, codes=None):",
"return self._tradeDayTable.getLatestTradeDayInDb() def getIndex(self, code): return self._codeTable.getIndex(code) def getCode(self, name): return self._codeTable.getCode(name) def",
"start, end): return self._tradeDayTable.get(start, end) def tDaysCountInDb(self, start, end): return self._tradeDayTable.tDaysCountInDb(start, end) def",
"def tDaysOffsetInDb(self, base, n=0): return self._tradeDayTable.tDaysOffsetInDb(base, n) def tDays(self, start, end): return self._tradeDayTable.get(start,",
"info self._codeTable = DyStockDataCodeTable(self._mongoDbEngine, self._gateway, self._info) self._tradeDayTable = DyStockDataTradeDayTable(self._mongoDbEngine, self._gateway, self._info) self._sectorCodeTable =",
"from .DyStockDataTradeDayTable import * from .DyStockDataSectorCodeTable import * class DyStockDataCommonEngine(object): \"\"\" 代码表和交易日数据引擎 \"\"\"",
"stockAllCodesFundsSectors(self): return self._codeTable.stockAllCodesFundsSectors @property def stockAllCodes(self): return self._codeTable.stockAllCodes @property def stockCodes(self): return self._codeTable.stockCodes",
"return self._codeTable.etf500 @property def stockFunds(self): return self._codeTable.stockFunds @property def stockSectors(self): return self._codeTable.stockSectors @property",
"self._tradeDayTable.tLatestDay() def tOldestDay(self): return self._tradeDayTable.tOldestDay() def isInTradeDayTable(self, startDate, endDate): return self._tradeDayTable.isIn(startDate, endDate) def",
"endDate) def getLatestDateInDb(self): return self._tradeDayTable.getLatestDateInDb() def getLatestTradeDayInDb(self): return self._tradeDayTable.getLatestTradeDayInDb() def getIndex(self, code): return",
"@property def stockCodes(self): return self._codeTable.stockCodes @property def stockIndexes(self): return self._codeTable.stockIndexes @property def stockIndexesSectors(self):",
"@property def stockAllCodes(self): return self._codeTable.stockAllCodes @property def stockCodes(self): return self._codeTable.stockCodes @property def stockIndexes(self):",
"index=None): if index in DyStockCommon.sectors: return self._sectorCodeTable.getSectorStockCodes(index) return self._codeTable.getIndexStockCodes(index) @property def shIndex(self): return",
"tDaysCountInDb(self, start, end): return self._tradeDayTable.tDaysCountInDb(start, end) def tLatestDay(self): return self._tradeDayTable.tLatestDay() def tOldestDay(self): return",
"self._gateway = gateway self._info = info self._codeTable = DyStockDataCodeTable(self._mongoDbEngine, self._gateway, self._info) self._tradeDayTable =",
".DyStockDataCodeTable import * from .DyStockDataTradeDayTable import * from .DyStockDataSectorCodeTable import * class DyStockDataCommonEngine(object):",
"def isInTradeDayTable(self, startDate, endDate): return self._tradeDayTable.isIn(startDate, endDate) def load(self, dates, codes=None): if not",
"@property def cybIndex(self): return self._codeTable.cybIndex @property def zxbIndex(self): return self._codeTable.zxbIndex @property def etf50(self):",
"def updateAllSectorCodes(self, startDate, endDate): return self._sectorCodeTable.updateAll(startDate, endDate) def getTradeDays(self, startDate, endDate): return self._tradeDayTable.get(startDate,",
"etf50(self): return self._codeTable.etf50 @property def etf300(self): return self._codeTable.etf300 @property def etf500(self): return self._codeTable.etf500",
"self._tradeDayTable.load(dates) def loadSectorCodeTable(self, sectorCode, date, codes=None): return self._sectorCodeTable.load(sectorCode, date, codes) def getSectorCodes(self, sectorCode):",
"self._codeTable.stockAllCodesFundsSectors @property def stockAllCodes(self): return self._codeTable.stockAllCodes @property def stockCodes(self): return self._codeTable.stockCodes @property def",
"self._sectorCodeTable.update(sectorCode, startDate, endDate) def updateAllSectorCodes(self, startDate, endDate): return self._sectorCodeTable.updateAll(startDate, endDate) def getTradeDays(self, startDate,",
"self._tradeDayTable.get(startDate, endDate) def getLatestDateInDb(self): return self._tradeDayTable.getLatestDateInDb() def getLatestTradeDayInDb(self): return self._tradeDayTable.getLatestTradeDayInDb() def getIndex(self, code):",
"self._tradeDayTable.getLatestTradeDayInDb() def getIndex(self, code): return self._codeTable.getIndex(code) def getCode(self, name): return self._codeTable.getCode(name) def getIndexStockCodes(self,",
"return self._codeTable.load(codes) def loadTradeDays(self, dates): return self._tradeDayTable.load(dates) def loadSectorCodeTable(self, sectorCode, date, codes=None): return",
"@property def stockIndexes(self): return self._codeTable.stockIndexes @property def stockIndexesSectors(self): return self._codeTable.stockIndexesSectors def tDaysOffset(self, base,",
"loadSectorCodeTable(self, sectorCode, date, codes=None): return self._sectorCodeTable.load(sectorCode, date, codes) def getSectorCodes(self, sectorCode): return self._sectorCodeTable.getSectorStockCodes(sectorCode)",
"endDate) def updateAllSectorCodes(self, startDate, endDate): return self._sectorCodeTable.updateAll(startDate, endDate) def getTradeDays(self, startDate, endDate): return",
"self._sectorCodeTable.updateAll(startDate, endDate) def getTradeDays(self, startDate, endDate): return self._tradeDayTable.get(startDate, endDate) def getLatestDateInDb(self): return self._tradeDayTable.getLatestDateInDb()",
"DyStockCommon.sectors: return self._sectorCodeTable.getSectorStockCodes(index) return self._codeTable.getIndexStockCodes(index) @property def shIndex(self): return self._codeTable.shIndex @property def szIndex(self):",
"endDate) def load(self, dates, codes=None): if not self._codeTable.load(codes): return False return self._tradeDayTable.load(dates) def",
"@property def stockFunds(self): return self._codeTable.stockFunds @property def stockSectors(self): return self._codeTable.stockSectors @property def stockCodesFunds(self):",
"self._sectorCodeTable = DyStockDataSectorCodeTable(self._mongoDbEngine, self._gateway, self._info) def updateCodes(self): return self._codeTable.update() def updateTradeDays(self, startDate, endDate):",
"= DyStockDataCodeTable(self._mongoDbEngine, self._gateway, self._info) self._tradeDayTable = DyStockDataTradeDayTable(self._mongoDbEngine, self._gateway, self._info) self._sectorCodeTable = DyStockDataSectorCodeTable(self._mongoDbEngine, self._gateway,",
"return self._codeTable.update() def updateTradeDays(self, startDate, endDate): return self._tradeDayTable.update(startDate, endDate) def updateSectorCodes(self, sectorCode, startDate,",
"def stockFunds(self): return self._codeTable.stockFunds @property def stockSectors(self): return self._codeTable.stockSectors @property def stockCodesFunds(self): return",
"False return self._tradeDayTable.load(dates) def loadCodeTable(self, codes=None): return self._codeTable.load(codes) def loadTradeDays(self, dates): return self._tradeDayTable.load(dates)",
"\"\"\" 代码表和交易日数据引擎 \"\"\" def __init__(self, mongoDbEngine, gateway, info): self._mongoDbEngine = mongoDbEngine self._gateway =",
"__init__(self, mongoDbEngine, gateway, info): self._mongoDbEngine = mongoDbEngine self._gateway = gateway self._info = info",
"endDate): return self._tradeDayTable.update(startDate, endDate) def updateSectorCodes(self, sectorCode, startDate, endDate): return self._sectorCodeTable.update(sectorCode, startDate, endDate)",
"return self._codeTable.getCode(name) def getIndexStockCodes(self, index=None): return self._codeTable.getIndexStockCodes(index) def getIndexSectorStockCodes(self, index=None): if index in",
"self._codeTable.getIndexStockCodes(index) def getIndexSectorStockCodes(self, index=None): if index in DyStockCommon.sectors: return self._sectorCodeTable.getSectorStockCodes(index) return self._codeTable.getIndexStockCodes(index) @property",
"stockAllCodesFunds(self): return self._codeTable.stockAllCodesFunds @property def stockAllCodesFundsSectors(self): return self._codeTable.stockAllCodesFundsSectors @property def stockAllCodes(self): return self._codeTable.stockAllCodes",
"stockAllCodes(self): return self._codeTable.stockAllCodes @property def stockCodes(self): return self._codeTable.stockCodes @property def stockIndexes(self): return self._codeTable.stockIndexes",
"mongoDbEngine, gateway, info): self._mongoDbEngine = mongoDbEngine self._gateway = gateway self._info = info self._codeTable",
"startDate, endDate): return self._sectorCodeTable.update(sectorCode, startDate, endDate) def updateAllSectorCodes(self, startDate, endDate): return self._sectorCodeTable.updateAll(startDate, endDate)",
"return self._tradeDayTable.isIn(startDate, endDate) def load(self, dates, codes=None): if not self._codeTable.load(codes): return False return",
"return self._codeTable.stockIndexesSectors def tDaysOffset(self, base, n): return self._tradeDayTable.tDaysOffset(base, n) def tDaysOffsetInDb(self, base, n=0):",
"class DyStockDataCommonEngine(object): \"\"\" 代码表和交易日数据引擎 \"\"\" def __init__(self, mongoDbEngine, gateway, info): self._mongoDbEngine = mongoDbEngine",
"self._codeTable.etf500 @property def stockFunds(self): return self._codeTable.stockFunds @property def stockSectors(self): return self._codeTable.stockSectors @property def",
"= DyStockDataTradeDayTable(self._mongoDbEngine, self._gateway, self._info) self._sectorCodeTable = DyStockDataSectorCodeTable(self._mongoDbEngine, self._gateway, self._info) def updateCodes(self): return self._codeTable.update()",
"name): return self._codeTable.getCode(name) def getIndexStockCodes(self, index=None): return self._codeTable.getIndexStockCodes(index) def getIndexSectorStockCodes(self, index=None): if index",
"@property def stockIndexesSectors(self): return self._codeTable.stockIndexesSectors def tDaysOffset(self, base, n): return self._tradeDayTable.tDaysOffset(base, n) def",
"def getTradeDays(self, startDate, endDate): return self._tradeDayTable.get(startDate, endDate) def getLatestDateInDb(self): return self._tradeDayTable.getLatestDateInDb() def getLatestTradeDayInDb(self):",
"def getIndexStockCodes(self, index=None): return self._codeTable.getIndexStockCodes(index) def getIndexSectorStockCodes(self, index=None): if index in DyStockCommon.sectors: return",
"self._codeTable.update() def updateTradeDays(self, startDate, endDate): return self._tradeDayTable.update(startDate, endDate) def updateSectorCodes(self, sectorCode, startDate, endDate):",
"index in DyStockCommon.sectors: return self._sectorCodeTable.getSectorStockCodes(index) return self._codeTable.getIndexStockCodes(index) @property def shIndex(self): return self._codeTable.shIndex @property",
"def getIndex(self, code): return self._codeTable.getIndex(code) def getCode(self, name): return self._codeTable.getCode(name) def getIndexStockCodes(self, index=None):",
"def stockCodesFunds(self): return self._codeTable.stockCodesFunds @property def stockAllCodesFunds(self): return self._codeTable.stockAllCodesFunds @property def stockAllCodesFundsSectors(self): return",
"self._tradeDayTable.getLatestDateInDb() def getLatestTradeDayInDb(self): return self._tradeDayTable.getLatestTradeDayInDb() def getIndex(self, code): return self._codeTable.getIndex(code) def getCode(self, name):",
"tDays(self, start, end): return self._tradeDayTable.get(start, end) def tDaysCountInDb(self, start, end): return self._tradeDayTable.tDaysCountInDb(start, end)",
"def shIndex(self): return self._codeTable.shIndex @property def szIndex(self): return self._codeTable.szIndex @property def cybIndex(self): return",
"def updateTradeDays(self, startDate, endDate): return self._tradeDayTable.update(startDate, endDate) def updateSectorCodes(self, sectorCode, startDate, endDate): return",
"@property def stockSectors(self): return self._codeTable.stockSectors @property def stockCodesFunds(self): return self._codeTable.stockCodesFunds @property def stockAllCodesFunds(self):",
"sectorCode, startDate, endDate): return self._sectorCodeTable.update(sectorCode, startDate, endDate) def updateAllSectorCodes(self, startDate, endDate): return self._sectorCodeTable.updateAll(startDate,",
"etf500(self): return self._codeTable.etf500 @property def stockFunds(self): return self._codeTable.stockFunds @property def stockSectors(self): return self._codeTable.stockSectors",
"def szIndex(self): return self._codeTable.szIndex @property def cybIndex(self): return self._codeTable.cybIndex @property def zxbIndex(self): return",
"return self._codeTable.stockFunds @property def stockSectors(self): return self._codeTable.stockSectors @property def stockCodesFunds(self): return self._codeTable.stockCodesFunds @property",
"<filename>Stock/Data/Engine/Common/DyStockDataCommonEngine.py from .DyStockDataCodeTable import * from .DyStockDataTradeDayTable import * from .DyStockDataSectorCodeTable import *",
"def stockAllCodesFundsSectors(self): return self._codeTable.stockAllCodesFundsSectors @property def stockAllCodes(self): return self._codeTable.stockAllCodes @property def stockCodes(self): return",
"return self._codeTable.cybIndex @property def zxbIndex(self): return self._codeTable.zxbIndex @property def etf50(self): return self._codeTable.etf50 @property",
"getTradeDays(self, startDate, endDate): return self._tradeDayTable.get(startDate, endDate) def getLatestDateInDb(self): return self._tradeDayTable.getLatestDateInDb() def getLatestTradeDayInDb(self): return",
"self._info) self._tradeDayTable = DyStockDataTradeDayTable(self._mongoDbEngine, self._gateway, self._info) self._sectorCodeTable = DyStockDataSectorCodeTable(self._mongoDbEngine, self._gateway, self._info) def updateCodes(self):",
"DyStockDataTradeDayTable(self._mongoDbEngine, self._gateway, self._info) self._sectorCodeTable = DyStockDataSectorCodeTable(self._mongoDbEngine, self._gateway, self._info) def updateCodes(self): return self._codeTable.update() def",
"self._codeTable.etf300 @property def etf500(self): return self._codeTable.etf500 @property def stockFunds(self): return self._codeTable.stockFunds @property def",
"startDate, endDate): return self._tradeDayTable.update(startDate, endDate) def updateSectorCodes(self, sectorCode, startDate, endDate): return self._sectorCodeTable.update(sectorCode, startDate,",
"n): return self._tradeDayTable.tDaysOffset(base, n) def tDaysOffsetInDb(self, base, n=0): return self._tradeDayTable.tDaysOffsetInDb(base, n) def tDays(self,",
"self._codeTable.stockAllCodesFunds @property def stockAllCodesFundsSectors(self): return self._codeTable.stockAllCodesFundsSectors @property def stockAllCodes(self): return self._codeTable.stockAllCodes @property def",
"self._codeTable = DyStockDataCodeTable(self._mongoDbEngine, self._gateway, self._info) self._tradeDayTable = DyStockDataTradeDayTable(self._mongoDbEngine, self._gateway, self._info) self._sectorCodeTable = DyStockDataSectorCodeTable(self._mongoDbEngine,",
"def etf500(self): return self._codeTable.etf500 @property def stockFunds(self): return self._codeTable.stockFunds @property def stockSectors(self): return",
"return self._codeTable.stockAllCodesFunds @property def stockAllCodesFundsSectors(self): return self._codeTable.stockAllCodesFundsSectors @property def stockAllCodes(self): return self._codeTable.stockAllCodes @property",
"return self._tradeDayTable.tDaysCountInDb(start, end) def tLatestDay(self): return self._tradeDayTable.tLatestDay() def tOldestDay(self): return self._tradeDayTable.tOldestDay() def isInTradeDayTable(self,",
"start, end): return self._tradeDayTable.tDaysCountInDb(start, end) def tLatestDay(self): return self._tradeDayTable.tLatestDay() def tOldestDay(self): return self._tradeDayTable.tOldestDay()",
"getIndex(self, code): return self._codeTable.getIndex(code) def getCode(self, name): return self._codeTable.getCode(name) def getIndexStockCodes(self, index=None): return",
"startDate, endDate): return self._tradeDayTable.isIn(startDate, endDate) def load(self, dates, codes=None): if not self._codeTable.load(codes): return",
"getIndexSectorStockCodes(self, index=None): if index in DyStockCommon.sectors: return self._sectorCodeTable.getSectorStockCodes(index) return self._codeTable.getIndexStockCodes(index) @property def shIndex(self):",
"def stockCodes(self): return self._codeTable.stockCodes @property def stockIndexes(self): return self._codeTable.stockIndexes @property def stockIndexesSectors(self): return",
"end): return self._tradeDayTable.get(start, end) def tDaysCountInDb(self, start, end): return self._tradeDayTable.tDaysCountInDb(start, end) def tLatestDay(self):",
"def zxbIndex(self): return self._codeTable.zxbIndex @property def etf50(self): return self._codeTable.etf50 @property def etf300(self): return",
"import * from .DyStockDataSectorCodeTable import * class DyStockDataCommonEngine(object): \"\"\" 代码表和交易日数据引擎 \"\"\" def __init__(self,",
"gateway, info): self._mongoDbEngine = mongoDbEngine self._gateway = gateway self._info = info self._codeTable =",
"self._gateway, self._info) self._tradeDayTable = DyStockDataTradeDayTable(self._mongoDbEngine, self._gateway, self._info) self._sectorCodeTable = DyStockDataSectorCodeTable(self._mongoDbEngine, self._gateway, self._info) def",
"startDate, endDate): return self._sectorCodeTable.updateAll(startDate, endDate) def getTradeDays(self, startDate, endDate): return self._tradeDayTable.get(startDate, endDate) def",
"if index in DyStockCommon.sectors: return self._sectorCodeTable.getSectorStockCodes(index) return self._codeTable.getIndexStockCodes(index) @property def shIndex(self): return self._codeTable.shIndex",
"self._codeTable.stockIndexes @property def stockIndexesSectors(self): return self._codeTable.stockIndexesSectors def tDaysOffset(self, base, n): return self._tradeDayTable.tDaysOffset(base, n)",
"self._tradeDayTable.tDaysCountInDb(start, end) def tLatestDay(self): return self._tradeDayTable.tLatestDay() def tOldestDay(self): return self._tradeDayTable.tOldestDay() def isInTradeDayTable(self, startDate,",
"self._mongoDbEngine = mongoDbEngine self._gateway = gateway self._info = info self._codeTable = DyStockDataCodeTable(self._mongoDbEngine, self._gateway,",
"loadTradeDays(self, dates): return self._tradeDayTable.load(dates) def loadSectorCodeTable(self, sectorCode, date, codes=None): return self._sectorCodeTable.load(sectorCode, date, codes)",
"endDate): return self._sectorCodeTable.updateAll(startDate, endDate) def getTradeDays(self, startDate, endDate): return self._tradeDayTable.get(startDate, endDate) def getLatestDateInDb(self):",
"* class DyStockDataCommonEngine(object): \"\"\" 代码表和交易日数据引擎 \"\"\" def __init__(self, mongoDbEngine, gateway, info): self._mongoDbEngine =",
"endDate): return self._tradeDayTable.isIn(startDate, endDate) def load(self, dates, codes=None): if not self._codeTable.load(codes): return False",
"tDaysOffset(self, base, n): return self._tradeDayTable.tDaysOffset(base, n) def tDaysOffsetInDb(self, base, n=0): return self._tradeDayTable.tDaysOffsetInDb(base, n)",
"self._sectorCodeTable.getSectorStockCodes(index) return self._codeTable.getIndexStockCodes(index) @property def shIndex(self): return self._codeTable.shIndex @property def szIndex(self): return self._codeTable.szIndex",
"return self._tradeDayTable.get(startDate, endDate) def getLatestDateInDb(self): return self._tradeDayTable.getLatestDateInDb() def getLatestTradeDayInDb(self): return self._tradeDayTable.getLatestTradeDayInDb() def getIndex(self,",
"stockIndexesSectors(self): return self._codeTable.stockIndexesSectors def tDaysOffset(self, base, n): return self._tradeDayTable.tDaysOffset(base, n) def tDaysOffsetInDb(self, base,",
"def __init__(self, mongoDbEngine, gateway, info): self._mongoDbEngine = mongoDbEngine self._gateway = gateway self._info =",
"return self._codeTable.etf300 @property def etf500(self): return self._codeTable.etf500 @property def stockFunds(self): return self._codeTable.stockFunds @property",
"def updateSectorCodes(self, sectorCode, startDate, endDate): return self._sectorCodeTable.update(sectorCode, startDate, endDate) def updateAllSectorCodes(self, startDate, endDate):",
"self._codeTable.getCode(name) def getIndexStockCodes(self, index=None): return self._codeTable.getIndexStockCodes(index) def getIndexSectorStockCodes(self, index=None): if index in DyStockCommon.sectors:",
"dates): return self._tradeDayTable.load(dates) def loadSectorCodeTable(self, sectorCode, date, codes=None): return self._sectorCodeTable.load(sectorCode, date, codes) def",
"from .DyStockDataSectorCodeTable import * class DyStockDataCommonEngine(object): \"\"\" 代码表和交易日数据引擎 \"\"\" def __init__(self, mongoDbEngine, gateway,",
"szIndex(self): return self._codeTable.szIndex @property def cybIndex(self): return self._codeTable.cybIndex @property def zxbIndex(self): return self._codeTable.zxbIndex",
"def getLatestTradeDayInDb(self): return self._tradeDayTable.getLatestTradeDayInDb() def getIndex(self, code): return self._codeTable.getIndex(code) def getCode(self, name): return",
"self._info) self._sectorCodeTable = DyStockDataSectorCodeTable(self._mongoDbEngine, self._gateway, self._info) def updateCodes(self): return self._codeTable.update() def updateTradeDays(self, startDate,",
"import * from .DyStockDataTradeDayTable import * from .DyStockDataSectorCodeTable import * class DyStockDataCommonEngine(object): \"\"\""
] |
[
"lengthOfLongestSubstring(self, s: str) -> int: #Leetcode 3 - Longest substring without repeating characters",
"if s[i] not in temp: temp += s[i] else: if maxlen < len(temp):",
"i in range(len(s)): if s[i] not in temp: temp += s[i] else: if",
"temp += s[i] if maxlen < len(temp): maxlen = len(temp) substr = temp",
"def lengthOfLongestSubstring(self, s: str) -> int: #Leetcode 3 - Longest substring without repeating",
"temp[1:] poi = poi + i temp += s[i] if maxlen < len(temp):",
"st = en = poi = 0 substr = temp = '' maxlen",
"substr = temp st = poi en = i - 1 while s[i]",
"= poi + i temp += s[i] if maxlen < len(temp): maxlen =",
"s[i] not in temp: temp += s[i] else: if maxlen < len(temp): maxlen",
"#Leetcode 3 - Longest substring without repeating characters st = en = poi",
"if maxlen < len(temp): maxlen = len(temp) substr = temp #print(f\"Longest substring is",
"= temp[1:] poi = poi + i temp += s[i] if maxlen <",
"-> int: #Leetcode 3 - Longest substring without repeating characters st = en",
"characters st = en = poi = 0 substr = temp = ''",
"maxlen = len(temp) substr = temp st = poi en = i -",
"while s[i] in temp: temp = temp[1:] poi = poi + i temp",
"temp #print(f\"Longest substring is {substr} and length is {maxlen} and from {st} to",
"0 for i in range(len(s)): if s[i] not in temp: temp += s[i]",
"poi = 0 substr = temp = '' maxlen = 0 for i",
"st = poi en = i - 1 while s[i] in temp: temp",
"Solution: def lengthOfLongestSubstring(self, s: str) -> int: #Leetcode 3 - Longest substring without",
"= len(temp) substr = temp st = poi en = i - 1",
"not in temp: temp += s[i] else: if maxlen < len(temp): maxlen =",
"without repeating characters st = en = poi = 0 substr = temp",
"- Longest substring without repeating characters st = en = poi = 0",
"temp += s[i] else: if maxlen < len(temp): maxlen = len(temp) substr =",
"str) -> int: #Leetcode 3 - Longest substring without repeating characters st =",
"substr = temp #print(f\"Longest substring is {substr} and length is {maxlen} and from",
"maxlen < len(temp): maxlen = len(temp) substr = temp #print(f\"Longest substring is {substr}",
"= temp #print(f\"Longest substring is {substr} and length is {maxlen} and from {st}",
"temp st = poi en = i - 1 while s[i] in temp:",
"< len(temp): maxlen = len(temp) substr = temp st = poi en =",
"len(temp): maxlen = len(temp) substr = temp st = poi en = i",
"+= s[i] if maxlen < len(temp): maxlen = len(temp) substr = temp #print(f\"Longest",
"maxlen = len(temp) substr = temp #print(f\"Longest substring is {substr} and length is",
"else: if maxlen < len(temp): maxlen = len(temp) substr = temp st =",
"len(temp) substr = temp st = poi en = i - 1 while",
"temp: temp = temp[1:] poi = poi + i temp += s[i] if",
"0 substr = temp = '' maxlen = 0 for i in range(len(s)):",
"i - 1 while s[i] in temp: temp = temp[1:] poi = poi",
"temp = '' maxlen = 0 for i in range(len(s)): if s[i] not",
"en = poi = 0 substr = temp = '' maxlen = 0",
"Repeating Characters.py class Solution: def lengthOfLongestSubstring(self, s: str) -> int: #Leetcode 3 -",
"substring without repeating characters st = en = poi = 0 substr =",
"- 1 while s[i] in temp: temp = temp[1:] poi = poi +",
"+ i temp += s[i] if maxlen < len(temp): maxlen = len(temp) substr",
"3 - Longest substring without repeating characters st = en = poi =",
"'' maxlen = 0 for i in range(len(s)): if s[i] not in temp:",
"in temp: temp += s[i] else: if maxlen < len(temp): maxlen = len(temp)",
"= en = poi = 0 substr = temp = '' maxlen =",
"= temp st = poi en = i - 1 while s[i] in",
"Without Repeating Characters.py class Solution: def lengthOfLongestSubstring(self, s: str) -> int: #Leetcode 3",
"len(temp): maxlen = len(temp) substr = temp #print(f\"Longest substring is {substr} and length",
"= poi en = i - 1 while s[i] in temp: temp =",
"range(len(s)): if s[i] not in temp: temp += s[i] else: if maxlen <",
"= temp = '' maxlen = 0 for i in range(len(s)): if s[i]",
"len(temp) substr = temp #print(f\"Longest substring is {substr} and length is {maxlen} and",
"s[i] else: if maxlen < len(temp): maxlen = len(temp) substr = temp st",
"Substring Without Repeating Characters.py class Solution: def lengthOfLongestSubstring(self, s: str) -> int: #Leetcode",
"temp: temp += s[i] else: if maxlen < len(temp): maxlen = len(temp) substr",
"poi en = i - 1 while s[i] in temp: temp = temp[1:]",
"temp = temp[1:] poi = poi + i temp += s[i] if maxlen",
"#print(f\"Longest substring is {substr} and length is {maxlen} and from {st} to {en}\")",
"maxlen < len(temp): maxlen = len(temp) substr = temp st = poi en",
"poi = poi + i temp += s[i] if maxlen < len(temp): maxlen",
"1 while s[i] in temp: temp = temp[1:] poi = poi + i",
"in temp: temp = temp[1:] poi = poi + i temp += s[i]",
"s[i] if maxlen < len(temp): maxlen = len(temp) substr = temp #print(f\"Longest substring",
"= '' maxlen = 0 for i in range(len(s)): if s[i] not in",
"s[i] in temp: temp = temp[1:] poi = poi + i temp +=",
"repeating characters st = en = poi = 0 substr = temp =",
"= len(temp) substr = temp #print(f\"Longest substring is {substr} and length is {maxlen}",
"for i in range(len(s)): if s[i] not in temp: temp += s[i] else:",
"+= s[i] else: if maxlen < len(temp): maxlen = len(temp) substr = temp",
"<filename>LC3-Longest Substring Without Repeating Characters.py class Solution: def lengthOfLongestSubstring(self, s: str) -> int:",
"= i - 1 while s[i] in temp: temp = temp[1:] poi =",
"poi + i temp += s[i] if maxlen < len(temp): maxlen = len(temp)",
"substring is {substr} and length is {maxlen} and from {st} to {en}\") return(maxlen)",
"substr = temp = '' maxlen = 0 for i in range(len(s)): if",
"< len(temp): maxlen = len(temp) substr = temp #print(f\"Longest substring is {substr} and",
"= 0 substr = temp = '' maxlen = 0 for i in",
"= 0 for i in range(len(s)): if s[i] not in temp: temp +=",
"Longest substring without repeating characters st = en = poi = 0 substr",
"= poi = 0 substr = temp = '' maxlen = 0 for",
"in range(len(s)): if s[i] not in temp: temp += s[i] else: if maxlen",
"s: str) -> int: #Leetcode 3 - Longest substring without repeating characters st",
"int: #Leetcode 3 - Longest substring without repeating characters st = en =",
"en = i - 1 while s[i] in temp: temp = temp[1:] poi",
"class Solution: def lengthOfLongestSubstring(self, s: str) -> int: #Leetcode 3 - Longest substring",
"i temp += s[i] if maxlen < len(temp): maxlen = len(temp) substr =",
"maxlen = 0 for i in range(len(s)): if s[i] not in temp: temp",
"Characters.py class Solution: def lengthOfLongestSubstring(self, s: str) -> int: #Leetcode 3 - Longest",
"if maxlen < len(temp): maxlen = len(temp) substr = temp st = poi"
] |
[
"[] self.post_order = [] self.pre_counter = 0 self.post_counter = 0 for v in",
"self.marked[v]: self.dfs(graph, v) def dfs(self, graph, v): self.marked[v] = True self.pre[v] = self.pre_counter",
"d.add_edge(2, 3) d.add_edge(3, 5) d.add_edge(5, 4) d.add_edge(6, 4) d.add_edge(6, 9) d.add_edge(7, 6) d.add_edge(8,",
"_ in range(graph.v)] self.pre_order = [] self.post_order = [] self.pre_counter = 0 self.post_counter",
"import Digraph d = Digraph(13) d.add_edge(0, 6) d.add_edge(0, 1) d.add_edge(0, 5) d.add_edge(2, 0)",
"= [] self.post_order = [] self.pre_counter = 0 self.post_counter = 0 for v",
"for v in range(graph.v): if not self.marked[v]: self.dfs(graph, v) def dfs(self, graph, v):",
"digraph import Digraph d = Digraph(13) d.add_edge(0, 6) d.add_edge(0, 1) d.add_edge(0, 5) d.add_edge(2,",
"for _ in range(graph.v)] self.post = [0 for _ in range(graph.v)] self.pre_order =",
"w in graph.get_siblings(v): if not self.marked[w]: self.dfs(graph, w) self.post[v] = self.post_counter self.post_counter +=",
"range(graph.v)] self.pre_order = [] self.post_order = [] self.pre_counter = 0 self.post_counter = 0",
"v) def dfs(self, graph, v): self.marked[v] = True self.pre[v] = self.pre_counter self.pre_counter +=",
"6) d.add_edge(8, 7) d.add_edge(9, 10) d.add_edge(9, 11) d.add_edge(9, 12) d.add_edge(11, 12) d.pprint() order",
"+= 1 self.post_order.append(v) if __name__ == '__main__': from digraph import Digraph d =",
"= 0 self.post_counter = 0 for v in range(graph.v): if not self.marked[v]: self.dfs(graph,",
"range(graph.v): if not self.marked[v]: self.dfs(graph, v) def dfs(self, graph, v): self.marked[v] = True",
"graph, v): self.marked[v] = True self.pre[v] = self.pre_counter self.pre_counter += 1 self.pre_order.append(v) for",
"range(graph.v)] self.pre = [0 for _ in range(graph.v)] self.post = [0 for _",
"self.post_counter self.post_counter += 1 self.post_order.append(v) if __name__ == '__main__': from digraph import Digraph",
"self.post_order.append(v) if __name__ == '__main__': from digraph import Digraph d = Digraph(13) d.add_edge(0,",
"d.add_edge(2, 0) d.add_edge(2, 3) d.add_edge(3, 5) d.add_edge(5, 4) d.add_edge(6, 4) d.add_edge(6, 9) d.add_edge(7,",
"self.post_counter = 0 for v in range(graph.v): if not self.marked[v]: self.dfs(graph, v) def",
"True self.pre[v] = self.pre_counter self.pre_counter += 1 self.pre_order.append(v) for w in graph.get_siblings(v): if",
"for _ in range(graph.v)] self.pre_order = [] self.post_order = [] self.pre_counter = 0",
"= Digraph(13) d.add_edge(0, 6) d.add_edge(0, 1) d.add_edge(0, 5) d.add_edge(2, 0) d.add_edge(2, 3) d.add_edge(3,",
"self.pre_counter self.pre_counter += 1 self.pre_order.append(v) for w in graph.get_siblings(v): if not self.marked[w]: self.dfs(graph,",
"def __init__(self, graph): self.marked = [False for _ in range(graph.v)] self.pre = [0",
"self.marked[w]: self.dfs(graph, w) self.post[v] = self.post_counter self.post_counter += 1 self.post_order.append(v) if __name__ ==",
"0 for v in range(graph.v): if not self.marked[v]: self.dfs(graph, v) def dfs(self, graph,",
"self.post_counter += 1 self.post_order.append(v) if __name__ == '__main__': from digraph import Digraph d",
"range(graph.v)] self.post = [0 for _ in range(graph.v)] self.pre_order = [] self.post_order =",
"_ in range(graph.v)] self.post = [0 for _ in range(graph.v)] self.pre_order = []",
"d.add_edge(6, 9) d.add_edge(7, 6) d.add_edge(8, 7) d.add_edge(9, 10) d.add_edge(9, 11) d.add_edge(9, 12) d.add_edge(11,",
"[False for _ in range(graph.v)] self.pre = [0 for _ in range(graph.v)] self.post",
"in range(graph.v)] self.pre = [0 for _ in range(graph.v)] self.post = [0 for",
"'__main__': from digraph import Digraph d = Digraph(13) d.add_edge(0, 6) d.add_edge(0, 1) d.add_edge(0,",
"if not self.marked[w]: self.dfs(graph, w) self.post[v] = self.post_counter self.post_counter += 1 self.post_order.append(v) if",
"d.add_edge(7, 6) d.add_edge(8, 7) d.add_edge(9, 10) d.add_edge(9, 11) d.add_edge(9, 12) d.add_edge(11, 12) d.pprint()",
"5) d.add_edge(2, 0) d.add_edge(2, 3) d.add_edge(3, 5) d.add_edge(5, 4) d.add_edge(6, 4) d.add_edge(6, 9)",
"11) d.add_edge(9, 12) d.add_edge(11, 12) d.pprint() order = DFSOrder(d) print(order.pre) print(order.post) print(order.pre_order) print(order.post_order)",
"d.add_edge(0, 6) d.add_edge(0, 1) d.add_edge(0, 5) d.add_edge(2, 0) d.add_edge(2, 3) d.add_edge(3, 5) d.add_edge(5,",
"7) d.add_edge(9, 10) d.add_edge(9, 11) d.add_edge(9, 12) d.add_edge(11, 12) d.pprint() order = DFSOrder(d)",
"= [False for _ in range(graph.v)] self.pre = [0 for _ in range(graph.v)]",
"graph.get_siblings(v): if not self.marked[w]: self.dfs(graph, w) self.post[v] = self.post_counter self.post_counter += 1 self.post_order.append(v)",
"self.marked = [False for _ in range(graph.v)] self.pre = [0 for _ in",
"5) d.add_edge(5, 4) d.add_edge(6, 4) d.add_edge(6, 9) d.add_edge(7, 6) d.add_edge(8, 7) d.add_edge(9, 10)",
"4) d.add_edge(6, 9) d.add_edge(7, 6) d.add_edge(8, 7) d.add_edge(9, 10) d.add_edge(9, 11) d.add_edge(9, 12)",
"d.add_edge(3, 5) d.add_edge(5, 4) d.add_edge(6, 4) d.add_edge(6, 9) d.add_edge(7, 6) d.add_edge(8, 7) d.add_edge(9,",
"from digraph import Digraph d = Digraph(13) d.add_edge(0, 6) d.add_edge(0, 1) d.add_edge(0, 5)",
"Digraph d = Digraph(13) d.add_edge(0, 6) d.add_edge(0, 1) d.add_edge(0, 5) d.add_edge(2, 0) d.add_edge(2,",
"def dfs(self, graph, v): self.marked[v] = True self.pre[v] = self.pre_counter self.pre_counter += 1",
"d.add_edge(9, 10) d.add_edge(9, 11) d.add_edge(9, 12) d.add_edge(11, 12) d.pprint() order = DFSOrder(d) print(order.pre)",
"<reponame>caser789/libcollection class DFSOrder(object): def __init__(self, graph): self.marked = [False for _ in range(graph.v)]",
"= 0 for v in range(graph.v): if not self.marked[v]: self.dfs(graph, v) def dfs(self,",
"self.post = [0 for _ in range(graph.v)] self.pre_order = [] self.post_order = []",
"if __name__ == '__main__': from digraph import Digraph d = Digraph(13) d.add_edge(0, 6)",
"_ in range(graph.v)] self.pre = [0 for _ in range(graph.v)] self.post = [0",
"in range(graph.v)] self.pre_order = [] self.post_order = [] self.pre_counter = 0 self.post_counter =",
"in graph.get_siblings(v): if not self.marked[w]: self.dfs(graph, w) self.post[v] = self.post_counter self.post_counter += 1",
"self.pre_counter = 0 self.post_counter = 0 for v in range(graph.v): if not self.marked[v]:",
"3) d.add_edge(3, 5) d.add_edge(5, 4) d.add_edge(6, 4) d.add_edge(6, 9) d.add_edge(7, 6) d.add_edge(8, 7)",
"not self.marked[w]: self.dfs(graph, w) self.post[v] = self.post_counter self.post_counter += 1 self.post_order.append(v) if __name__",
"class DFSOrder(object): def __init__(self, graph): self.marked = [False for _ in range(graph.v)] self.pre",
"self.marked[v] = True self.pre[v] = self.pre_counter self.pre_counter += 1 self.pre_order.append(v) for w in",
"= True self.pre[v] = self.pre_counter self.pre_counter += 1 self.pre_order.append(v) for w in graph.get_siblings(v):",
"if not self.marked[v]: self.dfs(graph, v) def dfs(self, graph, v): self.marked[v] = True self.pre[v]",
"d.add_edge(5, 4) d.add_edge(6, 4) d.add_edge(6, 9) d.add_edge(7, 6) d.add_edge(8, 7) d.add_edge(9, 10) d.add_edge(9,",
"self.pre = [0 for _ in range(graph.v)] self.post = [0 for _ in",
"w) self.post[v] = self.post_counter self.post_counter += 1 self.post_order.append(v) if __name__ == '__main__': from",
"self.post_order = [] self.pre_counter = 0 self.post_counter = 0 for v in range(graph.v):",
"v in range(graph.v): if not self.marked[v]: self.dfs(graph, v) def dfs(self, graph, v): self.marked[v]",
"1) d.add_edge(0, 5) d.add_edge(2, 0) d.add_edge(2, 3) d.add_edge(3, 5) d.add_edge(5, 4) d.add_edge(6, 4)",
"self.pre_order.append(v) for w in graph.get_siblings(v): if not self.marked[w]: self.dfs(graph, w) self.post[v] = self.post_counter",
"0 self.post_counter = 0 for v in range(graph.v): if not self.marked[v]: self.dfs(graph, v)",
"d.add_edge(0, 5) d.add_edge(2, 0) d.add_edge(2, 3) d.add_edge(3, 5) d.add_edge(5, 4) d.add_edge(6, 4) d.add_edge(6,",
"in range(graph.v)] self.post = [0 for _ in range(graph.v)] self.pre_order = [] self.post_order",
"= [0 for _ in range(graph.v)] self.post = [0 for _ in range(graph.v)]",
"d.add_edge(6, 4) d.add_edge(6, 9) d.add_edge(7, 6) d.add_edge(8, 7) d.add_edge(9, 10) d.add_edge(9, 11) d.add_edge(9,",
"in range(graph.v): if not self.marked[v]: self.dfs(graph, v) def dfs(self, graph, v): self.marked[v] =",
"self.dfs(graph, v) def dfs(self, graph, v): self.marked[v] = True self.pre[v] = self.pre_counter self.pre_counter",
"= self.pre_counter self.pre_counter += 1 self.pre_order.append(v) for w in graph.get_siblings(v): if not self.marked[w]:",
"self.dfs(graph, w) self.post[v] = self.post_counter self.post_counter += 1 self.post_order.append(v) if __name__ == '__main__':",
"10) d.add_edge(9, 11) d.add_edge(9, 12) d.add_edge(11, 12) d.pprint() order = DFSOrder(d) print(order.pre) print(order.post)",
"for _ in range(graph.v)] self.pre = [0 for _ in range(graph.v)] self.post =",
"[0 for _ in range(graph.v)] self.post = [0 for _ in range(graph.v)] self.pre_order",
"d.add_edge(0, 1) d.add_edge(0, 5) d.add_edge(2, 0) d.add_edge(2, 3) d.add_edge(3, 5) d.add_edge(5, 4) d.add_edge(6,",
"4) d.add_edge(6, 4) d.add_edge(6, 9) d.add_edge(7, 6) d.add_edge(8, 7) d.add_edge(9, 10) d.add_edge(9, 11)",
"9) d.add_edge(7, 6) d.add_edge(8, 7) d.add_edge(9, 10) d.add_edge(9, 11) d.add_edge(9, 12) d.add_edge(11, 12)",
"6) d.add_edge(0, 1) d.add_edge(0, 5) d.add_edge(2, 0) d.add_edge(2, 3) d.add_edge(3, 5) d.add_edge(5, 4)",
"v): self.marked[v] = True self.pre[v] = self.pre_counter self.pre_counter += 1 self.pre_order.append(v) for w",
"self.pre_counter += 1 self.pre_order.append(v) for w in graph.get_siblings(v): if not self.marked[w]: self.dfs(graph, w)",
"[0 for _ in range(graph.v)] self.pre_order = [] self.post_order = [] self.pre_counter =",
"not self.marked[v]: self.dfs(graph, v) def dfs(self, graph, v): self.marked[v] = True self.pre[v] =",
"= [] self.pre_counter = 0 self.post_counter = 0 for v in range(graph.v): if",
"d.add_edge(8, 7) d.add_edge(9, 10) d.add_edge(9, 11) d.add_edge(9, 12) d.add_edge(11, 12) d.pprint() order =",
"dfs(self, graph, v): self.marked[v] = True self.pre[v] = self.pre_counter self.pre_counter += 1 self.pre_order.append(v)",
"self.pre_order = [] self.post_order = [] self.pre_counter = 0 self.post_counter = 0 for",
"1 self.pre_order.append(v) for w in graph.get_siblings(v): if not self.marked[w]: self.dfs(graph, w) self.post[v] =",
"Digraph(13) d.add_edge(0, 6) d.add_edge(0, 1) d.add_edge(0, 5) d.add_edge(2, 0) d.add_edge(2, 3) d.add_edge(3, 5)",
"DFSOrder(object): def __init__(self, graph): self.marked = [False for _ in range(graph.v)] self.pre =",
"+= 1 self.pre_order.append(v) for w in graph.get_siblings(v): if not self.marked[w]: self.dfs(graph, w) self.post[v]",
"graph): self.marked = [False for _ in range(graph.v)] self.pre = [0 for _",
"__init__(self, graph): self.marked = [False for _ in range(graph.v)] self.pre = [0 for",
"= [0 for _ in range(graph.v)] self.pre_order = [] self.post_order = [] self.pre_counter",
"self.pre[v] = self.pre_counter self.pre_counter += 1 self.pre_order.append(v) for w in graph.get_siblings(v): if not",
"__name__ == '__main__': from digraph import Digraph d = Digraph(13) d.add_edge(0, 6) d.add_edge(0,",
"d.add_edge(9, 11) d.add_edge(9, 12) d.add_edge(11, 12) d.pprint() order = DFSOrder(d) print(order.pre) print(order.post) print(order.pre_order)",
"= self.post_counter self.post_counter += 1 self.post_order.append(v) if __name__ == '__main__': from digraph import",
"== '__main__': from digraph import Digraph d = Digraph(13) d.add_edge(0, 6) d.add_edge(0, 1)",
"1 self.post_order.append(v) if __name__ == '__main__': from digraph import Digraph d = Digraph(13)",
"0) d.add_edge(2, 3) d.add_edge(3, 5) d.add_edge(5, 4) d.add_edge(6, 4) d.add_edge(6, 9) d.add_edge(7, 6)",
"self.post[v] = self.post_counter self.post_counter += 1 self.post_order.append(v) if __name__ == '__main__': from digraph",
"for w in graph.get_siblings(v): if not self.marked[w]: self.dfs(graph, w) self.post[v] = self.post_counter self.post_counter",
"d = Digraph(13) d.add_edge(0, 6) d.add_edge(0, 1) d.add_edge(0, 5) d.add_edge(2, 0) d.add_edge(2, 3)",
"[] self.pre_counter = 0 self.post_counter = 0 for v in range(graph.v): if not"
] |
[
"from typing import Union from ..is_float import is_float def to_float(input: str) -> Union[float,",
"import Union from ..is_float import is_float def to_float(input: str) -> Union[float, None]: if",
"from ..is_float import is_float def to_float(input: str) -> Union[float, None]: if not is_float(input):",
"Union from ..is_float import is_float def to_float(input: str) -> Union[float, None]: if not",
"..is_float import is_float def to_float(input: str) -> Union[float, None]: if not is_float(input): return",
"is_float def to_float(input: str) -> Union[float, None]: if not is_float(input): return None else:",
"to_float(input: str) -> Union[float, None]: if not is_float(input): return None else: return float(input)",
"def to_float(input: str) -> Union[float, None]: if not is_float(input): return None else: return",
"typing import Union from ..is_float import is_float def to_float(input: str) -> Union[float, None]:",
"import is_float def to_float(input: str) -> Union[float, None]: if not is_float(input): return None"
] |
[] |
[
"in self.dhcp_data.values(): if v.get('ipv6'): if isinstance(v['ipv6'], IPv6Address): ipv6_count += 1 self.assertEqual(1, ipv6_count) @patch.object(ConfigData,",
"for v in self.dhcp_data.values(): if v.get('ipv4'): if isinstance(v['ipv4'], IPv4Address): ipv4_count += 1 self.assertEqual(3,",
"+= 1 self.assertEqual(1, ipv6_count) @patch.object(ConfigData, 'get_dhcp_info', config_file_with_black_list) def test_ignore_host(self): dhcp_data = parse_dhcp_lease_file('./dhcp_leases_test') self.assertEqual(",
"'./dhcp_leases_test', 'ignore_hosts': ['orion'] } } class TestDHCP(unittest.TestCase): def setUp(self): dhcp_lease_file = './dhcp_leases_test' self.dhcp_data",
"@patch.object(ConfigData, 'get_dhcp_info', config_file_with_black_list) def test_ignore_host(self): dhcp_data = parse_dhcp_lease_file('./dhcp_leases_test') self.assertEqual( '58:40:4e:b9:08:f0' in dhcp_data.keys(), False",
"ipaddress import IPv4Address, IPv6Address from unittest.mock import patch from utils.dhcp import parse_dhcp_lease_file from",
"import parse_dhcp_lease_file from utils.config_reader import ConfigData def config_file_with_black_list(self): return { 'dhcp': { 'lease_file':",
"v in self.dhcp_data.values(): if v.get('ipv6'): if isinstance(v['ipv6'], IPv6Address): ipv6_count += 1 self.assertEqual(1, ipv6_count)",
"IPv6Address from unittest.mock import patch from utils.dhcp import parse_dhcp_lease_file from utils.config_reader import ConfigData",
"= parse_dhcp_lease_file(dhcp_lease_file) def test_data_parsing(self): self.assertEqual(3, len(self.dhcp_data.keys())) def test_ipv4_parsing(self): ipv4_count = 0 for v",
"in self.dhcp_data.values(): if v.get('ipv4'): if isinstance(v['ipv4'], IPv4Address): ipv4_count += 1 self.assertEqual(3, ipv4_count) def",
"{ 'dhcp': { 'lease_file': './dhcp_leases_test', 'ignore_hosts': ['orion'] } } class TestDHCP(unittest.TestCase): def setUp(self):",
"from utils.dhcp import parse_dhcp_lease_file from utils.config_reader import ConfigData def config_file_with_black_list(self): return { 'dhcp':",
"def setUp(self): dhcp_lease_file = './dhcp_leases_test' self.dhcp_data = parse_dhcp_lease_file(dhcp_lease_file) def test_data_parsing(self): self.assertEqual(3, len(self.dhcp_data.keys())) def",
"ipv6_count += 1 self.assertEqual(1, ipv6_count) @patch.object(ConfigData, 'get_dhcp_info', config_file_with_black_list) def test_ignore_host(self): dhcp_data = parse_dhcp_lease_file('./dhcp_leases_test')",
"IPv6Address): ipv6_count += 1 self.assertEqual(1, ipv6_count) @patch.object(ConfigData, 'get_dhcp_info', config_file_with_black_list) def test_ignore_host(self): dhcp_data =",
"v.get('ipv4'): if isinstance(v['ipv4'], IPv4Address): ipv4_count += 1 self.assertEqual(3, ipv4_count) def test_ipv6_parsing(self): ipv6_count =",
"ipv6_count) @patch.object(ConfigData, 'get_dhcp_info', config_file_with_black_list) def test_ignore_host(self): dhcp_data = parse_dhcp_lease_file('./dhcp_leases_test') self.assertEqual( '58:40:4e:b9:08:f0' in dhcp_data.keys(),",
"import IPv4Address, IPv6Address from unittest.mock import patch from utils.dhcp import parse_dhcp_lease_file from utils.config_reader",
"'get_dhcp_info', config_file_with_black_list) def test_ignore_host(self): dhcp_data = parse_dhcp_lease_file('./dhcp_leases_test') self.assertEqual( '58:40:4e:b9:08:f0' in dhcp_data.keys(), False )",
"} class TestDHCP(unittest.TestCase): def setUp(self): dhcp_lease_file = './dhcp_leases_test' self.dhcp_data = parse_dhcp_lease_file(dhcp_lease_file) def test_data_parsing(self):",
"def config_file_with_black_list(self): return { 'dhcp': { 'lease_file': './dhcp_leases_test', 'ignore_hosts': ['orion'] } } class",
"if v.get('ipv6'): if isinstance(v['ipv6'], IPv6Address): ipv6_count += 1 self.assertEqual(1, ipv6_count) @patch.object(ConfigData, 'get_dhcp_info', config_file_with_black_list)",
"IPv4Address, IPv6Address from unittest.mock import patch from utils.dhcp import parse_dhcp_lease_file from utils.config_reader import",
"utils.dhcp import parse_dhcp_lease_file from utils.config_reader import ConfigData def config_file_with_black_list(self): return { 'dhcp': {",
"return { 'dhcp': { 'lease_file': './dhcp_leases_test', 'ignore_hosts': ['orion'] } } class TestDHCP(unittest.TestCase): def",
"setUp(self): dhcp_lease_file = './dhcp_leases_test' self.dhcp_data = parse_dhcp_lease_file(dhcp_lease_file) def test_data_parsing(self): self.assertEqual(3, len(self.dhcp_data.keys())) def test_ipv4_parsing(self):",
"test_ipv4_parsing(self): ipv4_count = 0 for v in self.dhcp_data.values(): if v.get('ipv4'): if isinstance(v['ipv4'], IPv4Address):",
"config_file_with_black_list(self): return { 'dhcp': { 'lease_file': './dhcp_leases_test', 'ignore_hosts': ['orion'] } } class TestDHCP(unittest.TestCase):",
"self.assertEqual(3, len(self.dhcp_data.keys())) def test_ipv4_parsing(self): ipv4_count = 0 for v in self.dhcp_data.values(): if v.get('ipv4'):",
"if isinstance(v['ipv4'], IPv4Address): ipv4_count += 1 self.assertEqual(3, ipv4_count) def test_ipv6_parsing(self): ipv6_count = 0",
"from utils.config_reader import ConfigData def config_file_with_black_list(self): return { 'dhcp': { 'lease_file': './dhcp_leases_test', 'ignore_hosts':",
"= 0 for v in self.dhcp_data.values(): if v.get('ipv4'): if isinstance(v['ipv4'], IPv4Address): ipv4_count +=",
"unittest.mock import patch from utils.dhcp import parse_dhcp_lease_file from utils.config_reader import ConfigData def config_file_with_black_list(self):",
"self.dhcp_data.values(): if v.get('ipv6'): if isinstance(v['ipv6'], IPv6Address): ipv6_count += 1 self.assertEqual(1, ipv6_count) @patch.object(ConfigData, 'get_dhcp_info',",
"self.assertEqual(1, ipv6_count) @patch.object(ConfigData, 'get_dhcp_info', config_file_with_black_list) def test_ignore_host(self): dhcp_data = parse_dhcp_lease_file('./dhcp_leases_test') self.assertEqual( '58:40:4e:b9:08:f0' in",
"dhcp_lease_file = './dhcp_leases_test' self.dhcp_data = parse_dhcp_lease_file(dhcp_lease_file) def test_data_parsing(self): self.assertEqual(3, len(self.dhcp_data.keys())) def test_ipv4_parsing(self): ipv4_count",
"self.dhcp_data = parse_dhcp_lease_file(dhcp_lease_file) def test_data_parsing(self): self.assertEqual(3, len(self.dhcp_data.keys())) def test_ipv4_parsing(self): ipv4_count = 0 for",
"['orion'] } } class TestDHCP(unittest.TestCase): def setUp(self): dhcp_lease_file = './dhcp_leases_test' self.dhcp_data = parse_dhcp_lease_file(dhcp_lease_file)",
"if v.get('ipv4'): if isinstance(v['ipv4'], IPv4Address): ipv4_count += 1 self.assertEqual(3, ipv4_count) def test_ipv6_parsing(self): ipv6_count",
"import unittest from ipaddress import IPv4Address, IPv6Address from unittest.mock import patch from utils.dhcp",
"ipv4_count = 0 for v in self.dhcp_data.values(): if v.get('ipv4'): if isinstance(v['ipv4'], IPv4Address): ipv4_count",
"ipv4_count += 1 self.assertEqual(3, ipv4_count) def test_ipv6_parsing(self): ipv6_count = 0 for v in",
"import ConfigData def config_file_with_black_list(self): return { 'dhcp': { 'lease_file': './dhcp_leases_test', 'ignore_hosts': ['orion'] }",
"ipv6_count = 0 for v in self.dhcp_data.values(): if v.get('ipv6'): if isinstance(v['ipv6'], IPv6Address): ipv6_count",
"0 for v in self.dhcp_data.values(): if v.get('ipv6'): if isinstance(v['ipv6'], IPv6Address): ipv6_count += 1",
"ipv4_count) def test_ipv6_parsing(self): ipv6_count = 0 for v in self.dhcp_data.values(): if v.get('ipv6'): if",
"parse_dhcp_lease_file from utils.config_reader import ConfigData def config_file_with_black_list(self): return { 'dhcp': { 'lease_file': './dhcp_leases_test',",
"unittest from ipaddress import IPv4Address, IPv6Address from unittest.mock import patch from utils.dhcp import",
"ConfigData def config_file_with_black_list(self): return { 'dhcp': { 'lease_file': './dhcp_leases_test', 'ignore_hosts': ['orion'] } }",
"'lease_file': './dhcp_leases_test', 'ignore_hosts': ['orion'] } } class TestDHCP(unittest.TestCase): def setUp(self): dhcp_lease_file = './dhcp_leases_test'",
"import patch from utils.dhcp import parse_dhcp_lease_file from utils.config_reader import ConfigData def config_file_with_black_list(self): return",
"'ignore_hosts': ['orion'] } } class TestDHCP(unittest.TestCase): def setUp(self): dhcp_lease_file = './dhcp_leases_test' self.dhcp_data =",
"= './dhcp_leases_test' self.dhcp_data = parse_dhcp_lease_file(dhcp_lease_file) def test_data_parsing(self): self.assertEqual(3, len(self.dhcp_data.keys())) def test_ipv4_parsing(self): ipv4_count =",
"isinstance(v['ipv4'], IPv4Address): ipv4_count += 1 self.assertEqual(3, ipv4_count) def test_ipv6_parsing(self): ipv6_count = 0 for",
"TestDHCP(unittest.TestCase): def setUp(self): dhcp_lease_file = './dhcp_leases_test' self.dhcp_data = parse_dhcp_lease_file(dhcp_lease_file) def test_data_parsing(self): self.assertEqual(3, len(self.dhcp_data.keys()))",
"if isinstance(v['ipv6'], IPv6Address): ipv6_count += 1 self.assertEqual(1, ipv6_count) @patch.object(ConfigData, 'get_dhcp_info', config_file_with_black_list) def test_ignore_host(self):",
"} } class TestDHCP(unittest.TestCase): def setUp(self): dhcp_lease_file = './dhcp_leases_test' self.dhcp_data = parse_dhcp_lease_file(dhcp_lease_file) def",
"IPv4Address): ipv4_count += 1 self.assertEqual(3, ipv4_count) def test_ipv6_parsing(self): ipv6_count = 0 for v",
"utils.config_reader import ConfigData def config_file_with_black_list(self): return { 'dhcp': { 'lease_file': './dhcp_leases_test', 'ignore_hosts': ['orion']",
"for v in self.dhcp_data.values(): if v.get('ipv6'): if isinstance(v['ipv6'], IPv6Address): ipv6_count += 1 self.assertEqual(1,",
"v in self.dhcp_data.values(): if v.get('ipv4'): if isinstance(v['ipv4'], IPv4Address): ipv4_count += 1 self.assertEqual(3, ipv4_count)",
"from unittest.mock import patch from utils.dhcp import parse_dhcp_lease_file from utils.config_reader import ConfigData def",
"{ 'lease_file': './dhcp_leases_test', 'ignore_hosts': ['orion'] } } class TestDHCP(unittest.TestCase): def setUp(self): dhcp_lease_file =",
"len(self.dhcp_data.keys())) def test_ipv4_parsing(self): ipv4_count = 0 for v in self.dhcp_data.values(): if v.get('ipv4'): if",
"test_ipv6_parsing(self): ipv6_count = 0 for v in self.dhcp_data.values(): if v.get('ipv6'): if isinstance(v['ipv6'], IPv6Address):",
"'./dhcp_leases_test' self.dhcp_data = parse_dhcp_lease_file(dhcp_lease_file) def test_data_parsing(self): self.assertEqual(3, len(self.dhcp_data.keys())) def test_ipv4_parsing(self): ipv4_count = 0",
"self.assertEqual(3, ipv4_count) def test_ipv6_parsing(self): ipv6_count = 0 for v in self.dhcp_data.values(): if v.get('ipv6'):",
"+= 1 self.assertEqual(3, ipv4_count) def test_ipv6_parsing(self): ipv6_count = 0 for v in self.dhcp_data.values():",
"1 self.assertEqual(1, ipv6_count) @patch.object(ConfigData, 'get_dhcp_info', config_file_with_black_list) def test_ignore_host(self): dhcp_data = parse_dhcp_lease_file('./dhcp_leases_test') self.assertEqual( '58:40:4e:b9:08:f0'",
"test_data_parsing(self): self.assertEqual(3, len(self.dhcp_data.keys())) def test_ipv4_parsing(self): ipv4_count = 0 for v in self.dhcp_data.values(): if",
"'dhcp': { 'lease_file': './dhcp_leases_test', 'ignore_hosts': ['orion'] } } class TestDHCP(unittest.TestCase): def setUp(self): dhcp_lease_file",
"self.dhcp_data.values(): if v.get('ipv4'): if isinstance(v['ipv4'], IPv4Address): ipv4_count += 1 self.assertEqual(3, ipv4_count) def test_ipv6_parsing(self):",
"def test_data_parsing(self): self.assertEqual(3, len(self.dhcp_data.keys())) def test_ipv4_parsing(self): ipv4_count = 0 for v in self.dhcp_data.values():",
"1 self.assertEqual(3, ipv4_count) def test_ipv6_parsing(self): ipv6_count = 0 for v in self.dhcp_data.values(): if",
"def test_ipv6_parsing(self): ipv6_count = 0 for v in self.dhcp_data.values(): if v.get('ipv6'): if isinstance(v['ipv6'],",
"v.get('ipv6'): if isinstance(v['ipv6'], IPv6Address): ipv6_count += 1 self.assertEqual(1, ipv6_count) @patch.object(ConfigData, 'get_dhcp_info', config_file_with_black_list) def",
"parse_dhcp_lease_file(dhcp_lease_file) def test_data_parsing(self): self.assertEqual(3, len(self.dhcp_data.keys())) def test_ipv4_parsing(self): ipv4_count = 0 for v in",
"isinstance(v['ipv6'], IPv6Address): ipv6_count += 1 self.assertEqual(1, ipv6_count) @patch.object(ConfigData, 'get_dhcp_info', config_file_with_black_list) def test_ignore_host(self): dhcp_data",
"patch from utils.dhcp import parse_dhcp_lease_file from utils.config_reader import ConfigData def config_file_with_black_list(self): return {",
"from ipaddress import IPv4Address, IPv6Address from unittest.mock import patch from utils.dhcp import parse_dhcp_lease_file",
"0 for v in self.dhcp_data.values(): if v.get('ipv4'): if isinstance(v['ipv4'], IPv4Address): ipv4_count += 1",
"= 0 for v in self.dhcp_data.values(): if v.get('ipv6'): if isinstance(v['ipv6'], IPv6Address): ipv6_count +=",
"def test_ipv4_parsing(self): ipv4_count = 0 for v in self.dhcp_data.values(): if v.get('ipv4'): if isinstance(v['ipv4'],",
"class TestDHCP(unittest.TestCase): def setUp(self): dhcp_lease_file = './dhcp_leases_test' self.dhcp_data = parse_dhcp_lease_file(dhcp_lease_file) def test_data_parsing(self): self.assertEqual(3,"
] |
[
"`LICENSE` at the project root. \"\"\"sent when the user receives a Rich Presence",
"in `LICENSE` at the project root. \"\"\"sent when the user receives a Rich",
"found in `LICENSE` at the project root. \"\"\"sent when the user receives a",
"be found in `LICENSE` at the project root. \"\"\"sent when the user receives",
"the user receives a Rich Presence Ask to Join request\"\"\" # TODO: Implement",
"# Full MIT License can be found in `LICENSE` at the project root.",
"<reponame>ashu96902/Pincer # Copyright Pincer 2021-Present # Full MIT License can be found in",
"MIT License can be found in `LICENSE` at the project root. \"\"\"sent when",
"Pincer 2021-Present # Full MIT License can be found in `LICENSE` at the",
"# Copyright Pincer 2021-Present # Full MIT License can be found in `LICENSE`",
"project root. \"\"\"sent when the user receives a Rich Presence Ask to Join",
"can be found in `LICENSE` at the project root. \"\"\"sent when the user",
"the project root. \"\"\"sent when the user receives a Rich Presence Ask to",
"Copyright Pincer 2021-Present # Full MIT License can be found in `LICENSE` at",
"user receives a Rich Presence Ask to Join request\"\"\" # TODO: Implement event",
"when the user receives a Rich Presence Ask to Join request\"\"\" # TODO:",
"\"\"\"sent when the user receives a Rich Presence Ask to Join request\"\"\" #",
"2021-Present # Full MIT License can be found in `LICENSE` at the project",
"root. \"\"\"sent when the user receives a Rich Presence Ask to Join request\"\"\"",
"Full MIT License can be found in `LICENSE` at the project root. \"\"\"sent",
"License can be found in `LICENSE` at the project root. \"\"\"sent when the",
"at the project root. \"\"\"sent when the user receives a Rich Presence Ask"
] |
[
"algo import numpy as np import scipy as sp import networkx as nx",
"# Command line inputs # # --------------------------- # network_name = str(sys.argv[1]) exp_type =",
"str(sys.argv[2]) # random, uniform if exp_type == \"uniform\": k = int(sys.argv[3]) # k-uniform",
"# -------------------------- # threshold_file_obj = open(threshold_path, 'r') tau = np.array([0] * n) for",
"# Set all diagonal entries to 1, very important since we consider the",
"')[0]) t = int(line.split(' ')[1]) tau[u] = t threshold_file_obj.close() # ------------------------ # #",
"The path to the network file edgelist_path = \"../networks/real/\" + network_name + \"/\"",
"if exp_type == \"random\": threshold_path = \"../networks/real/\" + network_name + \"/\" + network_name",
"Run the solver # # ------------------------ # x = algo.ip_nmin_fpe(A, tau) nmin_fpe =",
"int(line.split(' ')[1]) tau[u] = t threshold_file_obj.close() # ------------------------ # # Run the solver",
"+ network_name + \".txt\" elif exp_type == \"uniform\": threshold_path = \"../networks/real/\" + network_name",
"in the matrix (THIS IS VERY VERY IMPORTNAT) node_order = [str(i) for i",
"== \"uniform\": k = int(sys.argv[3]) # k-uniform threshold # ---------------------- # # Path",
"+ str(k) + \"_uniform_thresh.txt\" result_file = \"results/\" + exp_type + \"_threshold/\" + network_name",
"range(n)] # The adjacency matrix A = nx.to_scipy_sparse_matrix(G, nodelist = node_order) A.setdiag(1) #",
"ordering for u in range(n): if(G.degree(str(u)) + 1 != A[u].count_nonzero()): print(\"wrong\") print(G.degree(str(u)), A[u].count_nonzero())",
"exp_type + \"_threshold/\" + network_name + \".txt\" elif exp_type == \"uniform\": threshold_path =",
"as sp import networkx as nx import sys if __name__ == \"__main__\": #",
"node_order) A.setdiag(1) # Set all diagonal entries to 1, very important since we",
"threshold_file_obj = open(threshold_path, 'r') tau = np.array([0] * n) for line in threshold_file_obj:",
"np import scipy as sp import networkx as nx import sys if __name__",
"result_file = \"results/\" + exp_type + \"_threshold/\" + network_name + \".txt\" elif exp_type",
"# # Extract thresholds # # -------------------------- # threshold_file_obj = open(threshold_path, 'r') tau",
"n) for line in threshold_file_obj: u = int(line.split(' ')[0]) t = int(line.split(' ')[1])",
"+ network_name + \"/\" + network_name + \".edges\" print(\"Network: {}\".format(network_name)) if exp_type ==",
"= \"results/\" + exp_type + \"_threshold/\" + network_name + \".txt\" elif exp_type ==",
"IMPORTNAT) node_order = [str(i) for i in range(n)] # The adjacency matrix A",
"+ \"_random_thresh.txt\" result_file = \"results/\" + exp_type + \"_threshold/\" + network_name + \".txt\"",
"= [u for u, s in enumerate(x) if s != 0] f =",
"print(\"unknown type\") # ------------------------------- # # Network preporcessing # # ------------------------------- # #",
"adjacency matrix A = nx.to_scipy_sparse_matrix(G, nodelist = node_order) A.setdiag(1) # Set all diagonal",
"exp_type == \"uniform\": threshold_path = \"../networks/real/\" + network_name + \"/\" + network_name +",
"exp_type == \"random\": threshold_path = \"../networks/real/\" + network_name + \"/\" + network_name +",
"node_order = [str(i) for i in range(n)] # The adjacency matrix A =",
"thresholds # # -------------------------- # threshold_file_obj = open(threshold_path, 'r') tau = np.array([0] *",
"solver # # ------------------------ # x = algo.ip_nmin_fpe(A, tau) nmin_fpe = [u for",
"!= A[u].count_nonzero()): print(\"wrong\") print(G.degree(str(u)), A[u].count_nonzero()) # -------------------------- # # Extract thresholds # #",
"= algo.ip_nmin_fpe(A, tau) nmin_fpe = [u for u, s in enumerate(x) if s",
"scipy as sp import networkx as nx import sys if __name__ == \"__main__\":",
"elif exp_type == \"uniform\": threshold_path = \"../networks/real/\" + network_name + \"/\" + network_name",
"------------------------------- # # Network preporcessing # # ------------------------------- # # Read in the",
"str(k) + \"_uniform_thresh.txt\" result_file = \"results/\" + exp_type + \"_threshold/\" + network_name +",
"# random, uniform if exp_type == \"uniform\": k = int(sys.argv[3]) # k-uniform threshold",
"all diagonal entries to 1, very important since we consider the closed neighborhood",
"import algo import numpy as np import scipy as sp import networkx as",
"\"_random_thresh.txt\" result_file = \"results/\" + exp_type + \"_threshold/\" + network_name + \".txt\" elif",
"# --------------------------- # # Command line inputs # # --------------------------- # network_name =",
"# Read in the network G = nx.read_edgelist(edgelist_path) n = G.number_of_nodes() # the",
"+ \".txt\" elif exp_type == \"uniform\": threshold_path = \"../networks/real/\" + network_name + \"/\"",
"A[u].count_nonzero()) # -------------------------- # # Extract thresholds # # -------------------------- # threshold_file_obj =",
"the solver # # ------------------------ # x = algo.ip_nmin_fpe(A, tau) nmin_fpe = [u",
"import numpy as np import scipy as sp import networkx as nx import",
"\"uniform\": threshold_path = \"../networks/real/\" + network_name + \"/\" + network_name + \"_\" +",
"\"../networks/real/\" + network_name + \"/\" + network_name + \"_\" + str(k) + \"_uniform_thresh.txt\"",
"str(k) + \".txt\" else: print(\"unknown type\") # ------------------------------- # # Network preporcessing #",
"= int(line.split(' ')[0]) t = int(line.split(' ')[1]) tau[u] = t threshold_file_obj.close() # ------------------------",
"as nx import sys if __name__ == \"__main__\": # --------------------------- # # Command",
"\"results/\" + exp_type + \"_threshold/\" + network_name + \"_uniform_\" + str(k) + \".txt\"",
"double check the ordering for u in range(n): if(G.degree(str(u)) + 1 != A[u].count_nonzero()):",
"# ------------------------ # x = algo.ip_nmin_fpe(A, tau) nmin_fpe = [u for u, s",
"threshold_file_obj: u = int(line.split(' ')[0]) t = int(line.split(' ')[1]) tau[u] = t threshold_file_obj.close()",
"\"/\" + network_name + \"_random_thresh.txt\" result_file = \"results/\" + exp_type + \"_threshold/\" +",
"A[u].count_nonzero()): print(\"wrong\") print(G.degree(str(u)), A[u].count_nonzero()) # -------------------------- # # Extract thresholds # # --------------------------",
"+ \"/\" + network_name + \".edges\" print(\"Network: {}\".format(network_name)) if exp_type == \"random\": threshold_path",
"ordering of the node in the matrix (THIS IS VERY VERY IMPORTNAT) node_order",
"the matrix (THIS IS VERY VERY IMPORTNAT) node_order = [str(i) for i in",
"--------------------------- # # Command line inputs # # --------------------------- # network_name = str(sys.argv[1])",
"= node_order) A.setdiag(1) # Set all diagonal entries to 1, very important since",
"\"_threshold/\" + network_name + \".txt\" elif exp_type == \"uniform\": threshold_path = \"../networks/real/\" +",
"# # ---------------------- # # The path to the network file edgelist_path =",
"threshold_file_obj.close() # ------------------------ # # Run the solver # # ------------------------ # x",
"# ---------------------- # # The path to the network file edgelist_path = \"../networks/real/\"",
"uniform if exp_type == \"uniform\": k = int(sys.argv[3]) # k-uniform threshold # ----------------------",
"to data # # ---------------------- # # The path to the network file",
"+ \"_uniform_\" + str(k) + \".txt\" else: print(\"unknown type\") # ------------------------------- # #",
"= int(line.split(' ')[1]) tau[u] = t threshold_file_obj.close() # ------------------------ # # Run the",
"# Path to data # # ---------------------- # # The path to the",
"# ------------------------ # # Run the solver # # ------------------------ # x =",
"-------------------------- # # Extract thresholds # # -------------------------- # threshold_file_obj = open(threshold_path, 'r')",
"# # ------------------------ # x = algo.ip_nmin_fpe(A, tau) nmin_fpe = [u for u,",
"# # Network preporcessing # # ------------------------------- # # Read in the network",
"A.setdiag(1) # Set all diagonal entries to 1, very important since we consider",
"import scipy as sp import networkx as nx import sys if __name__ ==",
"__name__ == \"__main__\": # --------------------------- # # Command line inputs # # ---------------------------",
"# # --------------------------- # network_name = str(sys.argv[1]) exp_type = str(sys.argv[2]) # random, uniform",
"+ \"/\" + network_name + \"_\" + str(k) + \"_uniform_thresh.txt\" result_file = \"results/\"",
"exp_type + \"_threshold/\" + network_name + \"_uniform_\" + str(k) + \".txt\" else: print(\"unknown",
"= nx.to_scipy_sparse_matrix(G, nodelist = node_order) A.setdiag(1) # Set all diagonal entries to 1,",
"matrix (THIS IS VERY VERY IMPORTNAT) node_order = [str(i) for i in range(n)]",
"= t threshold_file_obj.close() # ------------------------ # # Run the solver # # ------------------------",
"network_name + \".edges\" print(\"Network: {}\".format(network_name)) if exp_type == \"random\": threshold_path = \"../networks/real/\" +",
"= \"../networks/real/\" + network_name + \"/\" + network_name + \"_random_thresh.txt\" result_file = \"results/\"",
"exp_type = str(sys.argv[2]) # random, uniform if exp_type == \"uniform\": k = int(sys.argv[3])",
"+ exp_type + \"_threshold/\" + network_name + \"_uniform_\" + str(k) + \".txt\" else:",
"\".txt\" else: print(\"unknown type\") # ------------------------------- # # Network preporcessing # # -------------------------------",
"# Network preporcessing # # ------------------------------- # # Read in the network G",
"network_name + \"/\" + network_name + \".edges\" print(\"Network: {}\".format(network_name)) if exp_type == \"random\":",
"# # Command line inputs # # --------------------------- # network_name = str(sys.argv[1]) exp_type",
"the network file edgelist_path = \"../networks/real/\" + network_name + \"/\" + network_name +",
"network_name + \".txt\" elif exp_type == \"uniform\": threshold_path = \"../networks/real/\" + network_name +",
"# network_name = str(sys.argv[1]) exp_type = str(sys.argv[2]) # random, uniform if exp_type ==",
"of the node in the matrix (THIS IS VERY VERY IMPORTNAT) node_order =",
"')[1]) tau[u] = t threshold_file_obj.close() # ------------------------ # # Run the solver #",
"print(\"Network: {}\".format(network_name)) if exp_type == \"random\": threshold_path = \"../networks/real/\" + network_name + \"/\"",
"import networkx as nx import sys if __name__ == \"__main__\": # --------------------------- #",
"\"results/\" + exp_type + \"_threshold/\" + network_name + \".txt\" elif exp_type == \"uniform\":",
"the network G = nx.read_edgelist(edgelist_path) n = G.number_of_nodes() # the ordering of the",
"the closed neighborhood # double check the ordering for u in range(n): if(G.degree(str(u))",
"preporcessing # # ------------------------------- # # Read in the network G = nx.read_edgelist(edgelist_path)",
"neighborhood # double check the ordering for u in range(n): if(G.degree(str(u)) + 1",
"if(G.degree(str(u)) + 1 != A[u].count_nonzero()): print(\"wrong\") print(G.degree(str(u)), A[u].count_nonzero()) # -------------------------- # # Extract",
"Extract thresholds # # -------------------------- # threshold_file_obj = open(threshold_path, 'r') tau = np.array([0]",
"== \"__main__\": # --------------------------- # # Command line inputs # # --------------------------- #",
"nmin_fpe = [u for u, s in enumerate(x) if s != 0] f",
"# the ordering of the node in the matrix (THIS IS VERY VERY",
"1 != A[u].count_nonzero()): print(\"wrong\") print(G.degree(str(u)), A[u].count_nonzero()) # -------------------------- # # Extract thresholds #",
"int(line.split(' ')[0]) t = int(line.split(' ')[1]) tau[u] = t threshold_file_obj.close() # ------------------------ #",
"IS VERY VERY IMPORTNAT) node_order = [str(i) for i in range(n)] # The",
"for i in range(n)] # The adjacency matrix A = nx.to_scipy_sparse_matrix(G, nodelist =",
"# The path to the network file edgelist_path = \"../networks/real/\" + network_name +",
"nx import sys if __name__ == \"__main__\": # --------------------------- # # Command line",
"check the ordering for u in range(n): if(G.degree(str(u)) + 1 != A[u].count_nonzero()): print(\"wrong\")",
"for u in range(n): if(G.degree(str(u)) + 1 != A[u].count_nonzero()): print(\"wrong\") print(G.degree(str(u)), A[u].count_nonzero()) #",
"if exp_type == \"uniform\": k = int(sys.argv[3]) # k-uniform threshold # ---------------------- #",
"u = int(line.split(' ')[0]) t = int(line.split(' ')[1]) tau[u] = t threshold_file_obj.close() #",
"------------------------ # x = algo.ip_nmin_fpe(A, tau) nmin_fpe = [u for u, s in",
"1, very important since we consider the closed neighborhood # double check the",
"edgelist_path = \"../networks/real/\" + network_name + \"/\" + network_name + \".edges\" print(\"Network: {}\".format(network_name))",
"# --------------------------- # network_name = str(sys.argv[1]) exp_type = str(sys.argv[2]) # random, uniform if",
"tau[u] = t threshold_file_obj.close() # ------------------------ # # Run the solver # #",
"in range(n)] # The adjacency matrix A = nx.to_scipy_sparse_matrix(G, nodelist = node_order) A.setdiag(1)",
"# threshold_file_obj = open(threshold_path, 'r') tau = np.array([0] * n) for line in",
"the ordering for u in range(n): if(G.degree(str(u)) + 1 != A[u].count_nonzero()): print(\"wrong\") print(G.degree(str(u)),",
"------------------------ # # Run the solver # # ------------------------ # x = algo.ip_nmin_fpe(A,",
"{}\".format(network_name)) if exp_type == \"random\": threshold_path = \"../networks/real/\" + network_name + \"/\" +",
"+ network_name + \"/\" + network_name + \"_\" + str(k) + \"_uniform_thresh.txt\" result_file",
"# ---------------------- # # Path to data # # ---------------------- # # The",
"network file edgelist_path = \"../networks/real/\" + network_name + \"/\" + network_name + \".edges\"",
"+ \".txt\" else: print(\"unknown type\") # ------------------------------- # # Network preporcessing # #",
"(THIS IS VERY VERY IMPORTNAT) node_order = [str(i) for i in range(n)] #",
"Network preporcessing # # ------------------------------- # # Read in the network G =",
"[str(i) for i in range(n)] # The adjacency matrix A = nx.to_scipy_sparse_matrix(G, nodelist",
"+ \".edges\" print(\"Network: {}\".format(network_name)) if exp_type == \"random\": threshold_path = \"../networks/real/\" + network_name",
"VERY IMPORTNAT) node_order = [str(i) for i in range(n)] # The adjacency matrix",
"very important since we consider the closed neighborhood # double check the ordering",
"consider the closed neighborhood # double check the ordering for u in range(n):",
"algo.ip_nmin_fpe(A, tau) nmin_fpe = [u for u, s in enumerate(x) if s !=",
"= open(threshold_path, 'r') tau = np.array([0] * n) for line in threshold_file_obj: u",
"path to the network file edgelist_path = \"../networks/real/\" + network_name + \"/\" +",
"\"../networks/real/\" + network_name + \"/\" + network_name + \".edges\" print(\"Network: {}\".format(network_name)) if exp_type",
"+ \"_uniform_thresh.txt\" result_file = \"results/\" + exp_type + \"_threshold/\" + network_name + \"_uniform_\"",
"# The adjacency matrix A = nx.to_scipy_sparse_matrix(G, nodelist = node_order) A.setdiag(1) # Set",
"result_file = \"results/\" + exp_type + \"_threshold/\" + network_name + \"_uniform_\" + str(k)",
"# ------------------------------- # # Network preporcessing # # ------------------------------- # # Read in",
"network_name + \"_uniform_\" + str(k) + \".txt\" else: print(\"unknown type\") # ------------------------------- #",
"[u for u, s in enumerate(x) if s != 0] f = open(result_file,",
"Read in the network G = nx.read_edgelist(edgelist_path) n = G.number_of_nodes() # the ordering",
"exp_type == \"uniform\": k = int(sys.argv[3]) # k-uniform threshold # ---------------------- # #",
"# # Read in the network G = nx.read_edgelist(edgelist_path) n = G.number_of_nodes() #",
"in the network G = nx.read_edgelist(edgelist_path) n = G.number_of_nodes() # the ordering of",
"in threshold_file_obj: u = int(line.split(' ')[0]) t = int(line.split(' ')[1]) tau[u] = t",
"i in range(n)] # The adjacency matrix A = nx.to_scipy_sparse_matrix(G, nodelist = node_order)",
"+ network_name + \"_uniform_\" + str(k) + \".txt\" else: print(\"unknown type\") # -------------------------------",
"\"/\" + network_name + \"_\" + str(k) + \"_uniform_thresh.txt\" result_file = \"results/\" +",
"open(threshold_path, 'r') tau = np.array([0] * n) for line in threshold_file_obj: u =",
"sys if __name__ == \"__main__\": # --------------------------- # # Command line inputs #",
"\"_uniform_thresh.txt\" result_file = \"results/\" + exp_type + \"_threshold/\" + network_name + \"_uniform_\" +",
"nx.to_scipy_sparse_matrix(G, nodelist = node_order) A.setdiag(1) # Set all diagonal entries to 1, very",
"# k-uniform threshold # ---------------------- # # Path to data # # ----------------------",
"# Extract thresholds # # -------------------------- # threshold_file_obj = open(threshold_path, 'r') tau =",
"<filename>ip/ip_solver.py import algo import numpy as np import scipy as sp import networkx",
"= np.array([0] * n) for line in threshold_file_obj: u = int(line.split(' ')[0]) t",
"# Run the solver # # ------------------------ # x = algo.ip_nmin_fpe(A, tau) nmin_fpe",
"network_name + \"_\" + str(k) + \"_uniform_thresh.txt\" result_file = \"results/\" + exp_type +",
"\".edges\" print(\"Network: {}\".format(network_name)) if exp_type == \"random\": threshold_path = \"../networks/real/\" + network_name +",
"Command line inputs # # --------------------------- # network_name = str(sys.argv[1]) exp_type = str(sys.argv[2])",
"inputs # # --------------------------- # network_name = str(sys.argv[1]) exp_type = str(sys.argv[2]) # random,",
"str(sys.argv[1]) exp_type = str(sys.argv[2]) # random, uniform if exp_type == \"uniform\": k =",
"+ \"_threshold/\" + network_name + \"_uniform_\" + str(k) + \".txt\" else: print(\"unknown type\")",
"important since we consider the closed neighborhood # double check the ordering for",
"since we consider the closed neighborhood # double check the ordering for u",
"---------------------- # # Path to data # # ---------------------- # # The path",
"threshold_path = \"../networks/real/\" + network_name + \"/\" + network_name + \"_\" + str(k)",
"= [str(i) for i in range(n)] # The adjacency matrix A = nx.to_scipy_sparse_matrix(G,",
"np.array([0] * n) for line in threshold_file_obj: u = int(line.split(' ')[0]) t =",
"u in range(n): if(G.degree(str(u)) + 1 != A[u].count_nonzero()): print(\"wrong\") print(G.degree(str(u)), A[u].count_nonzero()) # --------------------------",
"+ str(k) + \".txt\" else: print(\"unknown type\") # ------------------------------- # # Network preporcessing",
"'r') tau = np.array([0] * n) for line in threshold_file_obj: u = int(line.split('",
"---------------------- # # The path to the network file edgelist_path = \"../networks/real/\" +",
"file edgelist_path = \"../networks/real/\" + network_name + \"/\" + network_name + \".edges\" print(\"Network:",
"random, uniform if exp_type == \"uniform\": k = int(sys.argv[3]) # k-uniform threshold #",
"--------------------------- # network_name = str(sys.argv[1]) exp_type = str(sys.argv[2]) # random, uniform if exp_type",
"= str(sys.argv[2]) # random, uniform if exp_type == \"uniform\": k = int(sys.argv[3]) #",
"VERY VERY IMPORTNAT) node_order = [str(i) for i in range(n)] # The adjacency",
"network_name + \"/\" + network_name + \"_random_thresh.txt\" result_file = \"results/\" + exp_type +",
"enumerate(x) if s != 0] f = open(result_file, 'w') f.write(str(len(nmin_fpe)) + '\\n') f.close()",
"import sys if __name__ == \"__main__\": # --------------------------- # # Command line inputs",
"# # The path to the network file edgelist_path = \"../networks/real/\" + network_name",
"\".txt\" elif exp_type == \"uniform\": threshold_path = \"../networks/real/\" + network_name + \"/\" +",
"numpy as np import scipy as sp import networkx as nx import sys",
"line in threshold_file_obj: u = int(line.split(' ')[0]) t = int(line.split(' ')[1]) tau[u] =",
"for u, s in enumerate(x) if s != 0] f = open(result_file, 'w')",
"network_name + \"/\" + network_name + \"_\" + str(k) + \"_uniform_thresh.txt\" result_file =",
"nx.read_edgelist(edgelist_path) n = G.number_of_nodes() # the ordering of the node in the matrix",
"+ exp_type + \"_threshold/\" + network_name + \".txt\" elif exp_type == \"uniform\": threshold_path",
"the ordering of the node in the matrix (THIS IS VERY VERY IMPORTNAT)",
"print(\"wrong\") print(G.degree(str(u)), A[u].count_nonzero()) # -------------------------- # # Extract thresholds # # -------------------------- #",
"diagonal entries to 1, very important since we consider the closed neighborhood #",
"in range(n): if(G.degree(str(u)) + 1 != A[u].count_nonzero()): print(\"wrong\") print(G.degree(str(u)), A[u].count_nonzero()) # -------------------------- #",
"node in the matrix (THIS IS VERY VERY IMPORTNAT) node_order = [str(i) for",
"+ network_name + \".edges\" print(\"Network: {}\".format(network_name)) if exp_type == \"random\": threshold_path = \"../networks/real/\"",
"x = algo.ip_nmin_fpe(A, tau) nmin_fpe = [u for u, s in enumerate(x) if",
"+ network_name + \"_\" + str(k) + \"_uniform_thresh.txt\" result_file = \"results/\" + exp_type",
"Set all diagonal entries to 1, very important since we consider the closed",
"to 1, very important since we consider the closed neighborhood # double check",
"tau = np.array([0] * n) for line in threshold_file_obj: u = int(line.split(' ')[0])",
"tau) nmin_fpe = [u for u, s in enumerate(x) if s != 0]",
"u, s in enumerate(x) if s != 0] f = open(result_file, 'w') f.write(str(len(nmin_fpe))",
"\"random\": threshold_path = \"../networks/real/\" + network_name + \"/\" + network_name + \"_random_thresh.txt\" result_file",
"+ network_name + \"_random_thresh.txt\" result_file = \"results/\" + exp_type + \"_threshold/\" + network_name",
"k = int(sys.argv[3]) # k-uniform threshold # ---------------------- # # Path to data",
"= int(sys.argv[3]) # k-uniform threshold # ---------------------- # # Path to data #",
"G.number_of_nodes() # the ordering of the node in the matrix (THIS IS VERY",
"== \"uniform\": threshold_path = \"../networks/real/\" + network_name + \"/\" + network_name + \"_\"",
"# x = algo.ip_nmin_fpe(A, tau) nmin_fpe = [u for u, s in enumerate(x)",
"\"__main__\": # --------------------------- # # Command line inputs # # --------------------------- # network_name",
"print(G.degree(str(u)), A[u].count_nonzero()) # -------------------------- # # Extract thresholds # # -------------------------- # threshold_file_obj",
"+ 1 != A[u].count_nonzero()): print(\"wrong\") print(G.degree(str(u)), A[u].count_nonzero()) # -------------------------- # # Extract thresholds",
"+ network_name + \"/\" + network_name + \"_random_thresh.txt\" result_file = \"results/\" + exp_type",
"data # # ---------------------- # # The path to the network file edgelist_path",
"t threshold_file_obj.close() # ------------------------ # # Run the solver # # ------------------------ #",
"network_name = str(sys.argv[1]) exp_type = str(sys.argv[2]) # random, uniform if exp_type == \"uniform\":",
"= str(sys.argv[1]) exp_type = str(sys.argv[2]) # random, uniform if exp_type == \"uniform\": k",
"# # ------------------------------- # # Read in the network G = nx.read_edgelist(edgelist_path) n",
"for line in threshold_file_obj: u = int(line.split(' ')[0]) t = int(line.split(' ')[1]) tau[u]",
"\"uniform\": k = int(sys.argv[3]) # k-uniform threshold # ---------------------- # # Path to",
"= \"../networks/real/\" + network_name + \"/\" + network_name + \".edges\" print(\"Network: {}\".format(network_name)) if",
"# ------------------------------- # # Read in the network G = nx.read_edgelist(edgelist_path) n =",
"network G = nx.read_edgelist(edgelist_path) n = G.number_of_nodes() # the ordering of the node",
"# # Path to data # # ---------------------- # # The path to",
"# double check the ordering for u in range(n): if(G.degree(str(u)) + 1 !=",
"+ \"_threshold/\" + network_name + \".txt\" elif exp_type == \"uniform\": threshold_path = \"../networks/real/\"",
"# -------------------------- # # Extract thresholds # # -------------------------- # threshold_file_obj = open(threshold_path,",
"# # Run the solver # # ------------------------ # x = algo.ip_nmin_fpe(A, tau)",
"in enumerate(x) if s != 0] f = open(result_file, 'w') f.write(str(len(nmin_fpe)) + '\\n')",
"matrix A = nx.to_scipy_sparse_matrix(G, nodelist = node_order) A.setdiag(1) # Set all diagonal entries",
"sp import networkx as nx import sys if __name__ == \"__main__\": # ---------------------------",
"n = G.number_of_nodes() # the ordering of the node in the matrix (THIS",
"network_name + \"_random_thresh.txt\" result_file = \"results/\" + exp_type + \"_threshold/\" + network_name +",
"as np import scipy as sp import networkx as nx import sys if",
"G = nx.read_edgelist(edgelist_path) n = G.number_of_nodes() # the ordering of the node in",
"s in enumerate(x) if s != 0] f = open(result_file, 'w') f.write(str(len(nmin_fpe)) +",
"+ \"/\" + network_name + \"_random_thresh.txt\" result_file = \"results/\" + exp_type + \"_threshold/\"",
"k-uniform threshold # ---------------------- # # Path to data # # ---------------------- #",
"the node in the matrix (THIS IS VERY VERY IMPORTNAT) node_order = [str(i)",
"closed neighborhood # double check the ordering for u in range(n): if(G.degree(str(u)) +",
"networkx as nx import sys if __name__ == \"__main__\": # --------------------------- # #",
"to the network file edgelist_path = \"../networks/real/\" + network_name + \"/\" + network_name",
"nodelist = node_order) A.setdiag(1) # Set all diagonal entries to 1, very important",
"A = nx.to_scipy_sparse_matrix(G, nodelist = node_order) A.setdiag(1) # Set all diagonal entries to",
"-------------------------- # threshold_file_obj = open(threshold_path, 'r') tau = np.array([0] * n) for line",
"entries to 1, very important since we consider the closed neighborhood # double",
"type\") # ------------------------------- # # Network preporcessing # # ------------------------------- # # Read",
"threshold_path = \"../networks/real/\" + network_name + \"/\" + network_name + \"_random_thresh.txt\" result_file =",
"= nx.read_edgelist(edgelist_path) n = G.number_of_nodes() # the ordering of the node in the",
"* n) for line in threshold_file_obj: u = int(line.split(' ')[0]) t = int(line.split('",
"else: print(\"unknown type\") # ------------------------------- # # Network preporcessing # # ------------------------------- #",
"= G.number_of_nodes() # the ordering of the node in the matrix (THIS IS",
"t = int(line.split(' ')[1]) tau[u] = t threshold_file_obj.close() # ------------------------ # # Run",
"= \"results/\" + exp_type + \"_threshold/\" + network_name + \"_uniform_\" + str(k) +",
"we consider the closed neighborhood # double check the ordering for u in",
"range(n): if(G.degree(str(u)) + 1 != A[u].count_nonzero()): print(\"wrong\") print(G.degree(str(u)), A[u].count_nonzero()) # -------------------------- # #",
"= \"../networks/real/\" + network_name + \"/\" + network_name + \"_\" + str(k) +",
"\"/\" + network_name + \".edges\" print(\"Network: {}\".format(network_name)) if exp_type == \"random\": threshold_path =",
"\"_uniform_\" + str(k) + \".txt\" else: print(\"unknown type\") # ------------------------------- # # Network",
"\"_\" + str(k) + \"_uniform_thresh.txt\" result_file = \"results/\" + exp_type + \"_threshold/\" +",
"+ \"_\" + str(k) + \"_uniform_thresh.txt\" result_file = \"results/\" + exp_type + \"_threshold/\"",
"\"_threshold/\" + network_name + \"_uniform_\" + str(k) + \".txt\" else: print(\"unknown type\") #",
"------------------------------- # # Read in the network G = nx.read_edgelist(edgelist_path) n = G.number_of_nodes()",
"# # -------------------------- # threshold_file_obj = open(threshold_path, 'r') tau = np.array([0] * n)",
"int(sys.argv[3]) # k-uniform threshold # ---------------------- # # Path to data # #",
"line inputs # # --------------------------- # network_name = str(sys.argv[1]) exp_type = str(sys.argv[2]) #",
"The adjacency matrix A = nx.to_scipy_sparse_matrix(G, nodelist = node_order) A.setdiag(1) # Set all",
"Path to data # # ---------------------- # # The path to the network",
"\"../networks/real/\" + network_name + \"/\" + network_name + \"_random_thresh.txt\" result_file = \"results/\" +",
"if __name__ == \"__main__\": # --------------------------- # # Command line inputs # #",
"== \"random\": threshold_path = \"../networks/real/\" + network_name + \"/\" + network_name + \"_random_thresh.txt\"",
"threshold # ---------------------- # # Path to data # # ---------------------- # #"
] |
[
"= p.ShapeFilter() assert f.group == 0 assert f.categories == 0xFFFFFFFF assert f.mask ==",
"pickle.dumps(x, 2) actual = pickle.loads(s) assert x == actual class TestContactPoint: pass class",
"assert f.group == 0 assert f.categories == 0xFFFFFFFF assert f.mask == 0xFFFFFFFF f",
"class TestShapeFilter: def test_init(self) -> None: f = p.ShapeFilter() assert f.group == 0",
"f.group == 0 assert f.categories == 0xFFFFFFFF assert f.mask == 0xFFFFFFFF f =",
"== 3 def test_constants(self) -> None: assert p.ShapeFilter.ALL_MASKS() == 0xFFFFFFFF assert p.ShapeFilter.ALL_CATEGORIES() ==",
"def test_eq(self) -> None: f1 = p.ShapeFilter(1, 2, 3) f2 = p.ShapeFilter(1, 2,",
"s = pickle.dumps(x, 2) actual = pickle.loads(s) assert x == actual class TestContactPoint:",
"f2 = p.ShapeFilter(1, 2, 3) f3 = p.ShapeFilter(2, 3, 4) assert f1 ==",
"assert f.group == 1 assert f.categories == 2 assert f.mask == 3 def",
"== 0xFFFFFFFF f = p.ShapeFilter(1, 2, 3) assert f.group == 1 assert f.categories",
"None: f = p.ShapeFilter() assert f.group == 0 assert f.categories == 0xFFFFFFFF assert",
"1 assert f.categories == 2 assert f.mask == 3 def test_constants(self) -> None:",
"p.ShapeFilter(1, 2, 3) assert f.group == 1 assert f.categories == 2 assert f.mask",
"0 assert f.categories == 0xFFFFFFFF assert f.mask == 0xFFFFFFFF f = p.ShapeFilter(1, 2,",
"3 def test_constants(self) -> None: assert p.ShapeFilter.ALL_MASKS() == 0xFFFFFFFF assert p.ShapeFilter.ALL_CATEGORIES() == 0xFFFFFFFF",
"= p.ShapeFilter(1, 2, 3) s = pickle.dumps(x, 2) actual = pickle.loads(s) assert x",
"3, 4) assert f1 == f2 assert f1 != f3 def test_pickle(self) ->",
"None: f1 = p.ShapeFilter(1, 2, 3) f2 = p.ShapeFilter(1, 2, 3) f3 =",
"assert p.ShapeFilter.ALL_CATEGORIES() == 0xFFFFFFFF def test_eq(self) -> None: f1 = p.ShapeFilter(1, 2, 3)",
"f3 = p.ShapeFilter(2, 3, 4) assert f1 == f2 assert f1 != f3",
"pickle import easymunk as p class TestShapeFilter: def test_init(self) -> None: f =",
"p class TestShapeFilter: def test_init(self) -> None: f = p.ShapeFilter() assert f.group ==",
"p.ShapeFilter() assert f.group == 0 assert f.categories == 0xFFFFFFFF assert f.mask == 0xFFFFFFFF",
"-> None: x = p.ShapeFilter(1, 2, 3) s = pickle.dumps(x, 2) actual =",
"p.ShapeFilter(1, 2, 3) s = pickle.dumps(x, 2) actual = pickle.loads(s) assert x ==",
"-> None: f = p.ShapeFilter() assert f.group == 0 assert f.categories == 0xFFFFFFFF",
"2, 3) s = pickle.dumps(x, 2) actual = pickle.loads(s) assert x == actual",
"p.ShapeFilter(1, 2, 3) f3 = p.ShapeFilter(2, 3, 4) assert f1 == f2 assert",
"2 assert f.mask == 3 def test_constants(self) -> None: assert p.ShapeFilter.ALL_MASKS() == 0xFFFFFFFF",
"f3 def test_pickle(self) -> None: x = p.ShapeFilter(1, 2, 3) s = pickle.dumps(x,",
"= p.ShapeFilter(1, 2, 3) f2 = p.ShapeFilter(1, 2, 3) f3 = p.ShapeFilter(2, 3,",
"0xFFFFFFFF assert p.ShapeFilter.ALL_CATEGORIES() == 0xFFFFFFFF def test_eq(self) -> None: f1 = p.ShapeFilter(1, 2,",
"== 0xFFFFFFFF assert p.ShapeFilter.ALL_CATEGORIES() == 0xFFFFFFFF def test_eq(self) -> None: f1 = p.ShapeFilter(1,",
"f = p.ShapeFilter() assert f.group == 0 assert f.categories == 0xFFFFFFFF assert f.mask",
"p.ShapeFilter(2, 3, 4) assert f1 == f2 assert f1 != f3 def test_pickle(self)",
"assert f.mask == 0xFFFFFFFF f = p.ShapeFilter(1, 2, 3) assert f.group == 1",
"test_eq(self) -> None: f1 = p.ShapeFilter(1, 2, 3) f2 = p.ShapeFilter(1, 2, 3)",
"f = p.ShapeFilter(1, 2, 3) assert f.group == 1 assert f.categories == 2",
"def test_init(self) -> None: f = p.ShapeFilter() assert f.group == 0 assert f.categories",
"assert f1 != f3 def test_pickle(self) -> None: x = p.ShapeFilter(1, 2, 3)",
"0xFFFFFFFF assert f.mask == 0xFFFFFFFF f = p.ShapeFilter(1, 2, 3) assert f.group ==",
"import pickle import easymunk as p class TestShapeFilter: def test_init(self) -> None: f",
"0xFFFFFFFF def test_eq(self) -> None: f1 = p.ShapeFilter(1, 2, 3) f2 = p.ShapeFilter(1,",
"def test_pickle(self) -> None: x = p.ShapeFilter(1, 2, 3) s = pickle.dumps(x, 2)",
"test_pickle(self) -> None: x = p.ShapeFilter(1, 2, 3) s = pickle.dumps(x, 2) actual",
"assert f.mask == 3 def test_constants(self) -> None: assert p.ShapeFilter.ALL_MASKS() == 0xFFFFFFFF assert",
"f.mask == 0xFFFFFFFF f = p.ShapeFilter(1, 2, 3) assert f.group == 1 assert",
"3) s = pickle.dumps(x, 2) actual = pickle.loads(s) assert x == actual class",
"== 0xFFFFFFFF def test_eq(self) -> None: f1 = p.ShapeFilter(1, 2, 3) f2 =",
"== 0 assert f.categories == 0xFFFFFFFF assert f.mask == 0xFFFFFFFF f = p.ShapeFilter(1,",
"p.ShapeFilter.ALL_CATEGORIES() == 0xFFFFFFFF def test_eq(self) -> None: f1 = p.ShapeFilter(1, 2, 3) f2",
"f2 assert f1 != f3 def test_pickle(self) -> None: x = p.ShapeFilter(1, 2,",
"3) assert f.group == 1 assert f.categories == 2 assert f.mask == 3",
"= pickle.dumps(x, 2) actual = pickle.loads(s) assert x == actual class TestContactPoint: pass",
"!= f3 def test_pickle(self) -> None: x = p.ShapeFilter(1, 2, 3) s =",
"TestShapeFilter: def test_init(self) -> None: f = p.ShapeFilter() assert f.group == 0 assert",
"assert p.ShapeFilter.ALL_MASKS() == 0xFFFFFFFF assert p.ShapeFilter.ALL_CATEGORIES() == 0xFFFFFFFF def test_eq(self) -> None: f1",
"f1 != f3 def test_pickle(self) -> None: x = p.ShapeFilter(1, 2, 3) s",
"= p.ShapeFilter(1, 2, 3) f3 = p.ShapeFilter(2, 3, 4) assert f1 == f2",
"== 1 assert f.categories == 2 assert f.mask == 3 def test_constants(self) ->",
"== f2 assert f1 != f3 def test_pickle(self) -> None: x = p.ShapeFilter(1,",
"f.categories == 0xFFFFFFFF assert f.mask == 0xFFFFFFFF f = p.ShapeFilter(1, 2, 3) assert",
"2, 3) assert f.group == 1 assert f.categories == 2 assert f.mask ==",
"f1 = p.ShapeFilter(1, 2, 3) f2 = p.ShapeFilter(1, 2, 3) f3 = p.ShapeFilter(2,",
"p.ShapeFilter(1, 2, 3) f2 = p.ShapeFilter(1, 2, 3) f3 = p.ShapeFilter(2, 3, 4)",
"f.categories == 2 assert f.mask == 3 def test_constants(self) -> None: assert p.ShapeFilter.ALL_MASKS()",
"assert f1 == f2 assert f1 != f3 def test_pickle(self) -> None: x",
"== 0xFFFFFFFF assert f.mask == 0xFFFFFFFF f = p.ShapeFilter(1, 2, 3) assert f.group",
"f1 == f2 assert f1 != f3 def test_pickle(self) -> None: x =",
"0xFFFFFFFF f = p.ShapeFilter(1, 2, 3) assert f.group == 1 assert f.categories ==",
"def test_constants(self) -> None: assert p.ShapeFilter.ALL_MASKS() == 0xFFFFFFFF assert p.ShapeFilter.ALL_CATEGORIES() == 0xFFFFFFFF def",
"-> None: f1 = p.ShapeFilter(1, 2, 3) f2 = p.ShapeFilter(1, 2, 3) f3",
"3) f2 = p.ShapeFilter(1, 2, 3) f3 = p.ShapeFilter(2, 3, 4) assert f1",
"f.mask == 3 def test_constants(self) -> None: assert p.ShapeFilter.ALL_MASKS() == 0xFFFFFFFF assert p.ShapeFilter.ALL_CATEGORIES()",
"f.group == 1 assert f.categories == 2 assert f.mask == 3 def test_constants(self)",
"== 2 assert f.mask == 3 def test_constants(self) -> None: assert p.ShapeFilter.ALL_MASKS() ==",
"None: assert p.ShapeFilter.ALL_MASKS() == 0xFFFFFFFF assert p.ShapeFilter.ALL_CATEGORIES() == 0xFFFFFFFF def test_eq(self) -> None:",
"= p.ShapeFilter(1, 2, 3) assert f.group == 1 assert f.categories == 2 assert",
"= p.ShapeFilter(2, 3, 4) assert f1 == f2 assert f1 != f3 def",
"3) f3 = p.ShapeFilter(2, 3, 4) assert f1 == f2 assert f1 !=",
"p.ShapeFilter.ALL_MASKS() == 0xFFFFFFFF assert p.ShapeFilter.ALL_CATEGORIES() == 0xFFFFFFFF def test_eq(self) -> None: f1 =",
"2, 3) f2 = p.ShapeFilter(1, 2, 3) f3 = p.ShapeFilter(2, 3, 4) assert",
"-> None: assert p.ShapeFilter.ALL_MASKS() == 0xFFFFFFFF assert p.ShapeFilter.ALL_CATEGORIES() == 0xFFFFFFFF def test_eq(self) ->",
"import easymunk as p class TestShapeFilter: def test_init(self) -> None: f = p.ShapeFilter()",
"test_init(self) -> None: f = p.ShapeFilter() assert f.group == 0 assert f.categories ==",
"test_constants(self) -> None: assert p.ShapeFilter.ALL_MASKS() == 0xFFFFFFFF assert p.ShapeFilter.ALL_CATEGORIES() == 0xFFFFFFFF def test_eq(self)",
"assert f.categories == 2 assert f.mask == 3 def test_constants(self) -> None: assert",
"2) actual = pickle.loads(s) assert x == actual class TestContactPoint: pass class TestContactPointSet:",
"2, 3) f3 = p.ShapeFilter(2, 3, 4) assert f1 == f2 assert f1",
"easymunk as p class TestShapeFilter: def test_init(self) -> None: f = p.ShapeFilter() assert",
"assert f.categories == 0xFFFFFFFF assert f.mask == 0xFFFFFFFF f = p.ShapeFilter(1, 2, 3)",
"as p class TestShapeFilter: def test_init(self) -> None: f = p.ShapeFilter() assert f.group",
"actual = pickle.loads(s) assert x == actual class TestContactPoint: pass class TestContactPointSet: pass",
"4) assert f1 == f2 assert f1 != f3 def test_pickle(self) -> None:",
"None: x = p.ShapeFilter(1, 2, 3) s = pickle.dumps(x, 2) actual = pickle.loads(s)",
"x = p.ShapeFilter(1, 2, 3) s = pickle.dumps(x, 2) actual = pickle.loads(s) assert"
] |
[
"-Xmx4g -jar \" + codePath + \"/\" + \"igvtools.jar sort \" + bismarkFileName",
"= sys.argv[1] suffix = sys.argv[2] scriptFileName = sys.argv[3] codePath = sys.argv[4] # Should",
"write a line in the script for each for each population bismarkFileName =",
"suffix = sys.argv[2] scriptFileName = sys.argv[3] codePath = sys.argv[4] # Should not contain",
"-jar \" + codePath + \"/\" + \"igvtools.jar sort \" + bismarkFileName +",
"sys.argv[1] suffix = sys.argv[2] scriptFileName = sys.argv[3] codePath = sys.argv[4] # Should not",
"+ \"/\" + \"igvtools.jar sort \" + bismarkFileName + \" \" + outputFileName",
"suffix scriptFile.write(\"java -Xmx4g -jar \" + codePath + \"/\" + \"igvtools.jar sort \"",
"to convert Hapmap files to VCF files bismarkFileNameListFile = open(bismarkFileNameListFileName) scriptFile = open(scriptFileName,",
"VCF files bismarkFileNameListFile = open(bismarkFileNameListFileName) scriptFile = open(scriptFileName, 'w+') for line in bismarkFileNameListFile:",
"bismarkFileNameListFileName = sys.argv[1] suffix = sys.argv[2] scriptFileName = sys.argv[3] codePath = sys.argv[4] #",
"makeIGVToolsSortScript(bismarkFileNameListFileName, suffix, scriptFileName, codePath): # Make a script that will use gatk to",
"bismarkFileNameElements = bismarkFileName.split(\".\") fileTypeLength = len(bismarkFileNameElements[-1]) outputFileName = bismarkFileName[0:len(bismarkFileName) - fileTypeLength] + suffix",
"sys.argv[2] scriptFileName = sys.argv[3] codePath = sys.argv[4] # Should not contain a /",
"- fileTypeLength] + suffix scriptFile.write(\"java -Xmx4g -jar \" + codePath + \"/\" +",
"script that will use gatk to convert Hapmap files to VCF files bismarkFileNameListFile",
"line in bismarkFileNameListFile: # Iterate through the chromosomes and write a line in",
"sys.argv[4] # Should not contain a / at the end makeIGVToolsSortScript(bismarkFileNameListFileName, suffix, scriptFileName,",
"+ \" \" + outputFileName + \"\\n\") bismarkFileNameListFile.close() scriptFile.close() if __name__==\"__main__\": import sys",
"\"/\" + \"igvtools.jar sort \" + bismarkFileName + \" \" + outputFileName +",
"that will use gatk to convert Hapmap files to VCF files bismarkFileNameListFile =",
"Make a script that will use gatk to convert Hapmap files to VCF",
"codePath): # Make a script that will use gatk to convert Hapmap files",
"bismarkFileNameListFile: # Iterate through the chromosomes and write a line in the script",
"scriptFile.close() if __name__==\"__main__\": import sys bismarkFileNameListFileName = sys.argv[1] suffix = sys.argv[2] scriptFileName =",
"each for each population bismarkFileName = line.strip() bismarkFileNameElements = bismarkFileName.split(\".\") fileTypeLength = len(bismarkFileNameElements[-1])",
"# Make a script that will use gatk to convert Hapmap files to",
"to VCF files bismarkFileNameListFile = open(bismarkFileNameListFileName) scriptFile = open(scriptFileName, 'w+') for line in",
"+ outputFileName + \"\\n\") bismarkFileNameListFile.close() scriptFile.close() if __name__==\"__main__\": import sys bismarkFileNameListFileName = sys.argv[1]",
"import sys bismarkFileNameListFileName = sys.argv[1] suffix = sys.argv[2] scriptFileName = sys.argv[3] codePath =",
"for line in bismarkFileNameListFile: # Iterate through the chromosomes and write a line",
"+ bismarkFileName + \" \" + outputFileName + \"\\n\") bismarkFileNameListFile.close() scriptFile.close() if __name__==\"__main__\":",
"\" + outputFileName + \"\\n\") bismarkFileNameListFile.close() scriptFile.close() if __name__==\"__main__\": import sys bismarkFileNameListFileName =",
"bismarkFileNameListFile.close() scriptFile.close() if __name__==\"__main__\": import sys bismarkFileNameListFileName = sys.argv[1] suffix = sys.argv[2] scriptFileName",
"def makeIGVToolsSortScript(bismarkFileNameListFileName, suffix, scriptFileName, codePath): # Make a script that will use gatk",
"bismarkFileNameListFile = open(bismarkFileNameListFileName) scriptFile = open(scriptFileName, 'w+') for line in bismarkFileNameListFile: # Iterate",
"\"igvtools.jar sort \" + bismarkFileName + \" \" + outputFileName + \"\\n\") bismarkFileNameListFile.close()",
"in the script for each for each population bismarkFileName = line.strip() bismarkFileNameElements =",
"= sys.argv[2] scriptFileName = sys.argv[3] codePath = sys.argv[4] # Should not contain a",
"the script for each for each population bismarkFileName = line.strip() bismarkFileNameElements = bismarkFileName.split(\".\")",
"= open(bismarkFileNameListFileName) scriptFile = open(scriptFileName, 'w+') for line in bismarkFileNameListFile: # Iterate through",
"codePath = sys.argv[4] # Should not contain a / at the end makeIGVToolsSortScript(bismarkFileNameListFileName,",
"outputFileName + \"\\n\") bismarkFileNameListFile.close() scriptFile.close() if __name__==\"__main__\": import sys bismarkFileNameListFileName = sys.argv[1] suffix",
"= sys.argv[3] codePath = sys.argv[4] # Should not contain a / at the",
"a line in the script for each for each population bismarkFileName = line.strip()",
"for each for each population bismarkFileName = line.strip() bismarkFileNameElements = bismarkFileName.split(\".\") fileTypeLength =",
"line in the script for each for each population bismarkFileName = line.strip() bismarkFileNameElements",
"population bismarkFileName = line.strip() bismarkFileNameElements = bismarkFileName.split(\".\") fileTypeLength = len(bismarkFileNameElements[-1]) outputFileName = bismarkFileName[0:len(bismarkFileName)",
"fileTypeLength] + suffix scriptFile.write(\"java -Xmx4g -jar \" + codePath + \"/\" + \"igvtools.jar",
"+ \"igvtools.jar sort \" + bismarkFileName + \" \" + outputFileName + \"\\n\")",
"open(bismarkFileNameListFileName) scriptFile = open(scriptFileName, 'w+') for line in bismarkFileNameListFile: # Iterate through the",
"sort \" + bismarkFileName + \" \" + outputFileName + \"\\n\") bismarkFileNameListFile.close() scriptFile.close()",
"sys.argv[3] codePath = sys.argv[4] # Should not contain a / at the end",
"\" + bismarkFileName + \" \" + outputFileName + \"\\n\") bismarkFileNameListFile.close() scriptFile.close() if",
"len(bismarkFileNameElements[-1]) outputFileName = bismarkFileName[0:len(bismarkFileName) - fileTypeLength] + suffix scriptFile.write(\"java -Xmx4g -jar \" +",
"files bismarkFileNameListFile = open(bismarkFileNameListFileName) scriptFile = open(scriptFileName, 'w+') for line in bismarkFileNameListFile: #",
"bismarkFileName + \" \" + outputFileName + \"\\n\") bismarkFileNameListFile.close() scriptFile.close() if __name__==\"__main__\": import",
"open(scriptFileName, 'w+') for line in bismarkFileNameListFile: # Iterate through the chromosomes and write",
"= bismarkFileName[0:len(bismarkFileName) - fileTypeLength] + suffix scriptFile.write(\"java -Xmx4g -jar \" + codePath +",
"bismarkFileName[0:len(bismarkFileName) - fileTypeLength] + suffix scriptFile.write(\"java -Xmx4g -jar \" + codePath + \"/\"",
"= len(bismarkFileNameElements[-1]) outputFileName = bismarkFileName[0:len(bismarkFileName) - fileTypeLength] + suffix scriptFile.write(\"java -Xmx4g -jar \"",
"a script that will use gatk to convert Hapmap files to VCF files",
"will use gatk to convert Hapmap files to VCF files bismarkFileNameListFile = open(bismarkFileNameListFileName)",
"+ suffix scriptFile.write(\"java -Xmx4g -jar \" + codePath + \"/\" + \"igvtools.jar sort",
"each population bismarkFileName = line.strip() bismarkFileNameElements = bismarkFileName.split(\".\") fileTypeLength = len(bismarkFileNameElements[-1]) outputFileName =",
"# Should not contain a / at the end makeIGVToolsSortScript(bismarkFileNameListFileName, suffix, scriptFileName, codePath)",
"\" + codePath + \"/\" + \"igvtools.jar sort \" + bismarkFileName + \"",
"+ \"\\n\") bismarkFileNameListFile.close() scriptFile.close() if __name__==\"__main__\": import sys bismarkFileNameListFileName = sys.argv[1] suffix =",
"outputFileName = bismarkFileName[0:len(bismarkFileName) - fileTypeLength] + suffix scriptFile.write(\"java -Xmx4g -jar \" + codePath",
"the chromosomes and write a line in the script for each for each",
"bismarkFileName = line.strip() bismarkFileNameElements = bismarkFileName.split(\".\") fileTypeLength = len(bismarkFileNameElements[-1]) outputFileName = bismarkFileName[0:len(bismarkFileName) -",
"= line.strip() bismarkFileNameElements = bismarkFileName.split(\".\") fileTypeLength = len(bismarkFileNameElements[-1]) outputFileName = bismarkFileName[0:len(bismarkFileName) - fileTypeLength]",
"line.strip() bismarkFileNameElements = bismarkFileName.split(\".\") fileTypeLength = len(bismarkFileNameElements[-1]) outputFileName = bismarkFileName[0:len(bismarkFileName) - fileTypeLength] +",
"use gatk to convert Hapmap files to VCF files bismarkFileNameListFile = open(bismarkFileNameListFileName) scriptFile",
"bismarkFileName.split(\".\") fileTypeLength = len(bismarkFileNameElements[-1]) outputFileName = bismarkFileName[0:len(bismarkFileName) - fileTypeLength] + suffix scriptFile.write(\"java -Xmx4g",
"\" \" + outputFileName + \"\\n\") bismarkFileNameListFile.close() scriptFile.close() if __name__==\"__main__\": import sys bismarkFileNameListFileName",
"through the chromosomes and write a line in the script for each for",
"convert Hapmap files to VCF files bismarkFileNameListFile = open(bismarkFileNameListFileName) scriptFile = open(scriptFileName, 'w+')",
"suffix, scriptFileName, codePath): # Make a script that will use gatk to convert",
"codePath + \"/\" + \"igvtools.jar sort \" + bismarkFileName + \" \" +",
"scriptFile.write(\"java -Xmx4g -jar \" + codePath + \"/\" + \"igvtools.jar sort \" +",
"+ codePath + \"/\" + \"igvtools.jar sort \" + bismarkFileName + \" \"",
"gatk to convert Hapmap files to VCF files bismarkFileNameListFile = open(bismarkFileNameListFileName) scriptFile =",
"if __name__==\"__main__\": import sys bismarkFileNameListFileName = sys.argv[1] suffix = sys.argv[2] scriptFileName = sys.argv[3]",
"scriptFileName = sys.argv[3] codePath = sys.argv[4] # Should not contain a / at",
"fileTypeLength = len(bismarkFileNameElements[-1]) outputFileName = bismarkFileName[0:len(bismarkFileName) - fileTypeLength] + suffix scriptFile.write(\"java -Xmx4g -jar",
"<reponame>imk1/MethylationQTLCode def makeIGVToolsSortScript(bismarkFileNameListFileName, suffix, scriptFileName, codePath): # Make a script that will use",
"script for each for each population bismarkFileName = line.strip() bismarkFileNameElements = bismarkFileName.split(\".\") fileTypeLength",
"= sys.argv[4] # Should not contain a / at the end makeIGVToolsSortScript(bismarkFileNameListFileName, suffix,",
"= open(scriptFileName, 'w+') for line in bismarkFileNameListFile: # Iterate through the chromosomes and",
"sys bismarkFileNameListFileName = sys.argv[1] suffix = sys.argv[2] scriptFileName = sys.argv[3] codePath = sys.argv[4]",
"# Iterate through the chromosomes and write a line in the script for",
"__name__==\"__main__\": import sys bismarkFileNameListFileName = sys.argv[1] suffix = sys.argv[2] scriptFileName = sys.argv[3] codePath",
"and write a line in the script for each for each population bismarkFileName",
"\"\\n\") bismarkFileNameListFile.close() scriptFile.close() if __name__==\"__main__\": import sys bismarkFileNameListFileName = sys.argv[1] suffix = sys.argv[2]",
"files to VCF files bismarkFileNameListFile = open(bismarkFileNameListFileName) scriptFile = open(scriptFileName, 'w+') for line",
"scriptFile = open(scriptFileName, 'w+') for line in bismarkFileNameListFile: # Iterate through the chromosomes",
"in bismarkFileNameListFile: # Iterate through the chromosomes and write a line in the",
"Hapmap files to VCF files bismarkFileNameListFile = open(bismarkFileNameListFileName) scriptFile = open(scriptFileName, 'w+') for",
"chromosomes and write a line in the script for each for each population",
"for each population bismarkFileName = line.strip() bismarkFileNameElements = bismarkFileName.split(\".\") fileTypeLength = len(bismarkFileNameElements[-1]) outputFileName",
"scriptFileName, codePath): # Make a script that will use gatk to convert Hapmap",
"= bismarkFileName.split(\".\") fileTypeLength = len(bismarkFileNameElements[-1]) outputFileName = bismarkFileName[0:len(bismarkFileName) - fileTypeLength] + suffix scriptFile.write(\"java",
"'w+') for line in bismarkFileNameListFile: # Iterate through the chromosomes and write a",
"Iterate through the chromosomes and write a line in the script for each"
] |
[] |
[
"continue else: logging.warn(f\"Manifest missing {field}\") else: output[field] = result[0].text.strip() # Use first value",
"shape=None, npartitions=len(self._records), extra_metadata={}, ) def read(self): self._load_metadata() return pd.concat([self.read_partition(i) for i in range(self.npartitions)])",
"{}).items(): paths[name] = info return paths # TODO: Ask/Investigate (with jnelson) what the",
"output = {} for field in self._path_expressions: path = self._path_expressions[field]['path'] namespace = self._path_expressions[field]['namespace']",
"for field in self._path_expressions: path = self._path_expressions[field]['path'] namespace = self._path_expressions[field]['namespace'] optional = self._path_expressions[field]['optional']",
"import logging import pandas as pd from sickle import Sickle from lxml import",
"self._path_expressions = self._get_path_expressions() self._records = [] def _open_set(self): oai_records = self._collection.ListRecords(metadataPrefix='oai_dc', set=self.set, ignore_deleted=True)",
"if nsmap[key] in value: return value.replace(nsmap[key], \"\").replace(\"{}\", \"\") # TODO: Discuss if this",
"TODO: Discuss if this output shoould be an array (line 63) or a",
"datashape=None, dtype=self.dtype, shape=None, npartitions=len(self._records), extra_metadata={}, ) def read(self): self._load_metadata() return pd.concat([self.read_partition(i) for i",
"metadata.nsmap) output[tag] = metadata.text.strip() return output def _get_partition(self, i) -> pd.DataFrame: return pd.DataFrame(self._records)",
"def _get_partition(self, i) -> pd.DataFrame: return pd.DataFrame(self._records) def _get_path_expressions(self): paths = {} for",
"NS = {'oai_dc': \"http://www.openarchives.org/OAI/2.0/oai_dc/\"} oai_block = manifest.xpath(\"//oai_dc:dc\", namespaces=NS)[0] # we want the first",
"\"http://www.openarchives.org/OAI/2.0/oai_dc/\"} oai_block = manifest.xpath(\"//oai_dc:dc\", namespaces=NS)[0] # we want the first result for metadata",
"= Sickle(self.collection_url) self._path_expressions = self._get_path_expressions() self._records = [] def _open_set(self): oai_records = self._collection.ListRecords(metadataPrefix='oai_dc',",
"OAIXmlSource(intake.source.base.DataSource): container = \"dataframe\" name = \"oai_xml\" version = \"0.0.1\" partition_access = True",
"_get_schema(self): self._open_set() return intake.source.base.Schema( datashape=None, dtype=self.dtype, shape=None, npartitions=len(self._records), extra_metadata={}, ) def read(self): self._load_metadata()",
"Use first value return output def uri2label(self, value: str, nsmap: dict): for key",
"= info return paths # TODO: Ask/Investigate (with jnelson) what the purpose of",
"self.metadata.get(\"fields\", {}).items(): paths[name] = info return paths # TODO: Ask/Investigate (with jnelson) what",
"= [] def _open_set(self): oai_records = self._collection.ListRecords(metadataPrefix='oai_dc', set=self.set, ignore_deleted=True) for oai_record in oai_records:",
"self._get_path_expressions() self._records = [] def _open_set(self): oai_records = self._collection.ListRecords(metadataPrefix='oai_dc', set=self.set, ignore_deleted=True) for oai_record",
"name = \"oai_xml\" version = \"0.0.1\" partition_access = True def __init__(self, collection_url, set,",
"= self._path_expressions[field]['namespace'] optional = self._path_expressions[field]['optional'] result = manifest.xpath(path, namespaces=namespace) if len(result) < 1:",
"output[field] = result[0].text.strip() # Use first value return output def uri2label(self, value: str,",
"tag = self.uri2label(metadata.tag, metadata.nsmap) output[tag] = metadata.text.strip() return output def _get_partition(self, i) ->",
"purpose of dtyle=self.dtype def _get_schema(self): self._open_set() return intake.source.base.Schema( datashape=None, dtype=self.dtype, shape=None, npartitions=len(self._records), extra_metadata={},",
"{} for field in self._path_expressions: path = self._path_expressions[field]['path'] namespace = self._path_expressions[field]['namespace'] optional =",
"record = self._construct_fields(xtree) record.update(self._from_metadata(xtree)) self._records.append(record) def _construct_fields(self, manifest: etree) -> dict: output =",
"or a string def _from_metadata(self, manifest: etree) -> dict: output = {} NS",
"an array (line 63) or a string def _from_metadata(self, manifest: etree) -> dict:",
"pd.DataFrame: return pd.DataFrame(self._records) def _get_path_expressions(self): paths = {} for name, info in self.metadata.get(\"fields\",",
"pd.DataFrame(self._records) def _get_path_expressions(self): paths = {} for name, info in self.metadata.get(\"fields\", {}).items(): paths[name]",
"string def _from_metadata(self, manifest: etree) -> dict: output = {} NS = {'oai_dc':",
"(with jnelson) what the purpose of dtyle=self.dtype def _get_schema(self): self._open_set() return intake.source.base.Schema( datashape=None,",
"def _get_schema(self): self._open_set() return intake.source.base.Schema( datashape=None, dtype=self.dtype, shape=None, npartitions=len(self._records), extra_metadata={}, ) def read(self):",
"self._path_expressions[field]['optional'] result = manifest.xpath(path, namespaces=namespace) if len(result) < 1: if optional is True:",
"import Sickle from lxml import etree class OAIXmlSource(intake.source.base.DataSource): container = \"dataframe\" name =",
"{} for name, info in self.metadata.get(\"fields\", {}).items(): paths[name] = info return paths #",
"container = \"dataframe\" name = \"oai_xml\" version = \"0.0.1\" partition_access = True def",
"oai_record in oai_records: xtree = etree.fromstring(oai_record.raw) record = self._construct_fields(xtree) record.update(self._from_metadata(xtree)) self._records.append(record) def _construct_fields(self,",
"etree) -> dict: output = {} for field in self._path_expressions: path = self._path_expressions[field]['path']",
"{'oai_dc': \"http://www.openarchives.org/OAI/2.0/oai_dc/\"} oai_block = manifest.xpath(\"//oai_dc:dc\", namespaces=NS)[0] # we want the first result for",
"\"0.0.1\" partition_access = True def __init__(self, collection_url, set, dtype=None, metadata=None): super(OAIXmlSource, self).__init__(metadata=metadata) self.collection_url",
"continue continue else: logging.warn(f\"Manifest missing {field}\") else: output[field] = result[0].text.strip() # Use first",
"output def uri2label(self, value: str, nsmap: dict): for key in list(nsmap.keys()): if nsmap[key]",
"len(result) < 1: if optional is True: # Skip and continue continue else:",
"is True: # Skip and continue continue else: logging.warn(f\"Manifest missing {field}\") else: output[field]",
"info in self.metadata.get(\"fields\", {}).items(): paths[name] = info return paths # TODO: Ask/Investigate (with",
"= \"dataframe\" name = \"oai_xml\" version = \"0.0.1\" partition_access = True def __init__(self,",
"= {} for name, info in self.metadata.get(\"fields\", {}).items(): paths[name] = info return paths",
"for name, info in self.metadata.get(\"fields\", {}).items(): paths[name] = info return paths # TODO:",
"= set self._collection = Sickle(self.collection_url) self._path_expressions = self._get_path_expressions() self._records = [] def _open_set(self):",
"< 1: if optional is True: # Skip and continue continue else: logging.warn(f\"Manifest",
"manifest: etree) -> dict: output = {} for field in self._path_expressions: path =",
"\"oai_xml\" version = \"0.0.1\" partition_access = True def __init__(self, collection_url, set, dtype=None, metadata=None):",
"= \"oai_xml\" version = \"0.0.1\" partition_access = True def __init__(self, collection_url, set, dtype=None,",
"namespaces=NS)[0] # we want the first result for metadata in oai_block.getchildren(): tag =",
"63) or a string def _from_metadata(self, manifest: etree) -> dict: output = {}",
"_get_partition(self, i) -> pd.DataFrame: return pd.DataFrame(self._records) def _get_path_expressions(self): paths = {} for name,",
"manifest: etree) -> dict: output = {} NS = {'oai_dc': \"http://www.openarchives.org/OAI/2.0/oai_dc/\"} oai_block =",
"name, info in self.metadata.get(\"fields\", {}).items(): paths[name] = info return paths # TODO: Ask/Investigate",
"info return paths # TODO: Ask/Investigate (with jnelson) what the purpose of dtyle=self.dtype",
"list(nsmap.keys()): if nsmap[key] in value: return value.replace(nsmap[key], \"\").replace(\"{}\", \"\") # TODO: Discuss if",
"shoould be an array (line 63) or a string def _from_metadata(self, manifest: etree)",
"if len(result) < 1: if optional is True: # Skip and continue continue",
"in list(nsmap.keys()): if nsmap[key] in value: return value.replace(nsmap[key], \"\").replace(\"{}\", \"\") # TODO: Discuss",
"\"\").replace(\"{}\", \"\") # TODO: Discuss if this output shoould be an array (line",
"metadata.text.strip() return output def _get_partition(self, i) -> pd.DataFrame: return pd.DataFrame(self._records) def _get_path_expressions(self): paths",
"intake.source.base.Schema( datashape=None, dtype=self.dtype, shape=None, npartitions=len(self._records), extra_metadata={}, ) def read(self): self._load_metadata() return pd.concat([self.read_partition(i) for",
"for oai_record in oai_records: xtree = etree.fromstring(oai_record.raw) record = self._construct_fields(xtree) record.update(self._from_metadata(xtree)) self._records.append(record) def",
"uri2label(self, value: str, nsmap: dict): for key in list(nsmap.keys()): if nsmap[key] in value:",
"_construct_fields(self, manifest: etree) -> dict: output = {} for field in self._path_expressions: path",
"= collection_url self.set = set self._collection = Sickle(self.collection_url) self._path_expressions = self._get_path_expressions() self._records =",
"def _open_set(self): oai_records = self._collection.ListRecords(metadataPrefix='oai_dc', set=self.set, ignore_deleted=True) for oai_record in oai_records: xtree =",
"manifest.xpath(path, namespaces=namespace) if len(result) < 1: if optional is True: # Skip and",
"(line 63) or a string def _from_metadata(self, manifest: etree) -> dict: output =",
"# we want the first result for metadata in oai_block.getchildren(): tag = self.uri2label(metadata.tag,",
"output shoould be an array (line 63) or a string def _from_metadata(self, manifest:",
"missing {field}\") else: output[field] = result[0].text.strip() # Use first value return output def",
"if optional is True: # Skip and continue continue else: logging.warn(f\"Manifest missing {field}\")",
"self._open_set() return intake.source.base.Schema( datashape=None, dtype=self.dtype, shape=None, npartitions=len(self._records), extra_metadata={}, ) def read(self): self._load_metadata() return",
"we want the first result for metadata in oai_block.getchildren(): tag = self.uri2label(metadata.tag, metadata.nsmap)",
"and continue continue else: logging.warn(f\"Manifest missing {field}\") else: output[field] = result[0].text.strip() # Use",
"sickle import Sickle from lxml import etree class OAIXmlSource(intake.source.base.DataSource): container = \"dataframe\" name",
"metadata in oai_block.getchildren(): tag = self.uri2label(metadata.tag, metadata.nsmap) output[tag] = metadata.text.strip() return output def",
"self._records = [] def _open_set(self): oai_records = self._collection.ListRecords(metadataPrefix='oai_dc', set=self.set, ignore_deleted=True) for oai_record in",
"result[0].text.strip() # Use first value return output def uri2label(self, value: str, nsmap: dict):",
"want the first result for metadata in oai_block.getchildren(): tag = self.uri2label(metadata.tag, metadata.nsmap) output[tag]",
"etree class OAIXmlSource(intake.source.base.DataSource): container = \"dataframe\" name = \"oai_xml\" version = \"0.0.1\" partition_access",
"nsmap: dict): for key in list(nsmap.keys()): if nsmap[key] in value: return value.replace(nsmap[key], \"\").replace(\"{}\",",
"return pd.DataFrame(self._records) def _get_path_expressions(self): paths = {} for name, info in self.metadata.get(\"fields\", {}).items():",
"= self._construct_fields(xtree) record.update(self._from_metadata(xtree)) self._records.append(record) def _construct_fields(self, manifest: etree) -> dict: output = {}",
"self._collection = Sickle(self.collection_url) self._path_expressions = self._get_path_expressions() self._records = [] def _open_set(self): oai_records =",
"set, dtype=None, metadata=None): super(OAIXmlSource, self).__init__(metadata=metadata) self.collection_url = collection_url self.set = set self._collection =",
"# Use first value return output def uri2label(self, value: str, nsmap: dict): for",
"in oai_block.getchildren(): tag = self.uri2label(metadata.tag, metadata.nsmap) output[tag] = metadata.text.strip() return output def _get_partition(self,",
"paths = {} for name, info in self.metadata.get(\"fields\", {}).items(): paths[name] = info return",
"set self._collection = Sickle(self.collection_url) self._path_expressions = self._get_path_expressions() self._records = [] def _open_set(self): oai_records",
"of dtyle=self.dtype def _get_schema(self): self._open_set() return intake.source.base.Schema( datashape=None, dtype=self.dtype, shape=None, npartitions=len(self._records), extra_metadata={}, )",
"in self._path_expressions: path = self._path_expressions[field]['path'] namespace = self._path_expressions[field]['namespace'] optional = self._path_expressions[field]['optional'] result =",
"if this output shoould be an array (line 63) or a string def",
"a string def _from_metadata(self, manifest: etree) -> dict: output = {} NS =",
"def _construct_fields(self, manifest: etree) -> dict: output = {} for field in self._path_expressions:",
"str, nsmap: dict): for key in list(nsmap.keys()): if nsmap[key] in value: return value.replace(nsmap[key],",
"manifest.xpath(\"//oai_dc:dc\", namespaces=NS)[0] # we want the first result for metadata in oai_block.getchildren(): tag",
"# TODO: Discuss if this output shoould be an array (line 63) or",
"= self._path_expressions[field]['optional'] result = manifest.xpath(path, namespaces=namespace) if len(result) < 1: if optional is",
"dtype=self.dtype, shape=None, npartitions=len(self._records), extra_metadata={}, ) def read(self): self._load_metadata() return pd.concat([self.read_partition(i) for i in",
"key in list(nsmap.keys()): if nsmap[key] in value: return value.replace(nsmap[key], \"\").replace(\"{}\", \"\") # TODO:",
"-> pd.DataFrame: return pd.DataFrame(self._records) def _get_path_expressions(self): paths = {} for name, info in",
"\"\") # TODO: Discuss if this output shoould be an array (line 63)",
"logging import pandas as pd from sickle import Sickle from lxml import etree",
"Discuss if this output shoould be an array (line 63) or a string",
"be an array (line 63) or a string def _from_metadata(self, manifest: etree) ->",
"= result[0].text.strip() # Use first value return output def uri2label(self, value: str, nsmap:",
"oai_records = self._collection.ListRecords(metadataPrefix='oai_dc', set=self.set, ignore_deleted=True) for oai_record in oai_records: xtree = etree.fromstring(oai_record.raw) record",
"= {} NS = {'oai_dc': \"http://www.openarchives.org/OAI/2.0/oai_dc/\"} oai_block = manifest.xpath(\"//oai_dc:dc\", namespaces=NS)[0] # we want",
"True def __init__(self, collection_url, set, dtype=None, metadata=None): super(OAIXmlSource, self).__init__(metadata=metadata) self.collection_url = collection_url self.set",
"collection_url self.set = set self._collection = Sickle(self.collection_url) self._path_expressions = self._get_path_expressions() self._records = []",
"Sickle from lxml import etree class OAIXmlSource(intake.source.base.DataSource): container = \"dataframe\" name = \"oai_xml\"",
"value return output def uri2label(self, value: str, nsmap: dict): for key in list(nsmap.keys()):",
"the purpose of dtyle=self.dtype def _get_schema(self): self._open_set() return intake.source.base.Schema( datashape=None, dtype=self.dtype, shape=None, npartitions=len(self._records),",
"namespace = self._path_expressions[field]['namespace'] optional = self._path_expressions[field]['optional'] result = manifest.xpath(path, namespaces=namespace) if len(result) <",
"dtyle=self.dtype def _get_schema(self): self._open_set() return intake.source.base.Schema( datashape=None, dtype=self.dtype, shape=None, npartitions=len(self._records), extra_metadata={}, ) def",
"self._path_expressions[field]['path'] namespace = self._path_expressions[field]['namespace'] optional = self._path_expressions[field]['optional'] result = manifest.xpath(path, namespaces=namespace) if len(result)",
"__init__(self, collection_url, set, dtype=None, metadata=None): super(OAIXmlSource, self).__init__(metadata=metadata) self.collection_url = collection_url self.set = set",
"paths # TODO: Ask/Investigate (with jnelson) what the purpose of dtyle=self.dtype def _get_schema(self):",
"nsmap[key] in value: return value.replace(nsmap[key], \"\").replace(\"{}\", \"\") # TODO: Discuss if this output",
"record.update(self._from_metadata(xtree)) self._records.append(record) def _construct_fields(self, manifest: etree) -> dict: output = {} for field",
"def __init__(self, collection_url, set, dtype=None, metadata=None): super(OAIXmlSource, self).__init__(metadata=metadata) self.collection_url = collection_url self.set =",
"as pd from sickle import Sickle from lxml import etree class OAIXmlSource(intake.source.base.DataSource): container",
"in oai_records: xtree = etree.fromstring(oai_record.raw) record = self._construct_fields(xtree) record.update(self._from_metadata(xtree)) self._records.append(record) def _construct_fields(self, manifest:",
"return output def _get_partition(self, i) -> pd.DataFrame: return pd.DataFrame(self._records) def _get_path_expressions(self): paths =",
"paths[name] = info return paths # TODO: Ask/Investigate (with jnelson) what the purpose",
"= \"0.0.1\" partition_access = True def __init__(self, collection_url, set, dtype=None, metadata=None): super(OAIXmlSource, self).__init__(metadata=metadata)",
"in self.metadata.get(\"fields\", {}).items(): paths[name] = info return paths # TODO: Ask/Investigate (with jnelson)",
"oai_block = manifest.xpath(\"//oai_dc:dc\", namespaces=NS)[0] # we want the first result for metadata in",
"jnelson) what the purpose of dtyle=self.dtype def _get_schema(self): self._open_set() return intake.source.base.Schema( datashape=None, dtype=self.dtype,",
"collection_url, set, dtype=None, metadata=None): super(OAIXmlSource, self).__init__(metadata=metadata) self.collection_url = collection_url self.set = set self._collection",
"dict: output = {} NS = {'oai_dc': \"http://www.openarchives.org/OAI/2.0/oai_dc/\"} oai_block = manifest.xpath(\"//oai_dc:dc\", namespaces=NS)[0] #",
"= manifest.xpath(path, namespaces=namespace) if len(result) < 1: if optional is True: # Skip",
"namespaces=namespace) if len(result) < 1: if optional is True: # Skip and continue",
"else: logging.warn(f\"Manifest missing {field}\") else: output[field] = result[0].text.strip() # Use first value return",
"= self._get_path_expressions() self._records = [] def _open_set(self): oai_records = self._collection.ListRecords(metadataPrefix='oai_dc', set=self.set, ignore_deleted=True) for",
"this output shoould be an array (line 63) or a string def _from_metadata(self,",
"array (line 63) or a string def _from_metadata(self, manifest: etree) -> dict: output",
"_open_set(self): oai_records = self._collection.ListRecords(metadataPrefix='oai_dc', set=self.set, ignore_deleted=True) for oai_record in oai_records: xtree = etree.fromstring(oai_record.raw)",
"def _from_metadata(self, manifest: etree) -> dict: output = {} NS = {'oai_dc': \"http://www.openarchives.org/OAI/2.0/oai_dc/\"}",
"self._path_expressions: path = self._path_expressions[field]['path'] namespace = self._path_expressions[field]['namespace'] optional = self._path_expressions[field]['optional'] result = manifest.xpath(path,",
"self.uri2label(metadata.tag, metadata.nsmap) output[tag] = metadata.text.strip() return output def _get_partition(self, i) -> pd.DataFrame: return",
"import pandas as pd from sickle import Sickle from lxml import etree class",
"partition_access = True def __init__(self, collection_url, set, dtype=None, metadata=None): super(OAIXmlSource, self).__init__(metadata=metadata) self.collection_url =",
"result = manifest.xpath(path, namespaces=namespace) if len(result) < 1: if optional is True: #",
"from sickle import Sickle from lxml import etree class OAIXmlSource(intake.source.base.DataSource): container = \"dataframe\"",
"<reponame>sul-dlss/dlme-airflow import intake import logging import pandas as pd from sickle import Sickle",
"= self._collection.ListRecords(metadataPrefix='oai_dc', set=self.set, ignore_deleted=True) for oai_record in oai_records: xtree = etree.fromstring(oai_record.raw) record =",
"value: str, nsmap: dict): for key in list(nsmap.keys()): if nsmap[key] in value: return",
"dict): for key in list(nsmap.keys()): if nsmap[key] in value: return value.replace(nsmap[key], \"\").replace(\"{}\", \"\")",
"-> dict: output = {} NS = {'oai_dc': \"http://www.openarchives.org/OAI/2.0/oai_dc/\"} oai_block = manifest.xpath(\"//oai_dc:dc\", namespaces=NS)[0]",
"path = self._path_expressions[field]['path'] namespace = self._path_expressions[field]['namespace'] optional = self._path_expressions[field]['optional'] result = manifest.xpath(path, namespaces=namespace)",
"optional is True: # Skip and continue continue else: logging.warn(f\"Manifest missing {field}\") else:",
"True: # Skip and continue continue else: logging.warn(f\"Manifest missing {field}\") else: output[field] =",
"= etree.fromstring(oai_record.raw) record = self._construct_fields(xtree) record.update(self._from_metadata(xtree)) self._records.append(record) def _construct_fields(self, manifest: etree) -> dict:",
"self._construct_fields(xtree) record.update(self._from_metadata(xtree)) self._records.append(record) def _construct_fields(self, manifest: etree) -> dict: output = {} for",
"def _get_path_expressions(self): paths = {} for name, info in self.metadata.get(\"fields\", {}).items(): paths[name] =",
"what the purpose of dtyle=self.dtype def _get_schema(self): self._open_set() return intake.source.base.Schema( datashape=None, dtype=self.dtype, shape=None,",
"return output def uri2label(self, value: str, nsmap: dict): for key in list(nsmap.keys()): if",
"_get_path_expressions(self): paths = {} for name, info in self.metadata.get(\"fields\", {}).items(): paths[name] = info",
"self._collection.ListRecords(metadataPrefix='oai_dc', set=self.set, ignore_deleted=True) for oai_record in oai_records: xtree = etree.fromstring(oai_record.raw) record = self._construct_fields(xtree)",
"intake import logging import pandas as pd from sickle import Sickle from lxml",
"class OAIXmlSource(intake.source.base.DataSource): container = \"dataframe\" name = \"oai_xml\" version = \"0.0.1\" partition_access =",
"self.collection_url = collection_url self.set = set self._collection = Sickle(self.collection_url) self._path_expressions = self._get_path_expressions() self._records",
"import etree class OAIXmlSource(intake.source.base.DataSource): container = \"dataframe\" name = \"oai_xml\" version = \"0.0.1\"",
"the first result for metadata in oai_block.getchildren(): tag = self.uri2label(metadata.tag, metadata.nsmap) output[tag] =",
"[] def _open_set(self): oai_records = self._collection.ListRecords(metadataPrefix='oai_dc', set=self.set, ignore_deleted=True) for oai_record in oai_records: xtree",
"for key in list(nsmap.keys()): if nsmap[key] in value: return value.replace(nsmap[key], \"\").replace(\"{}\", \"\") #",
"= self.uri2label(metadata.tag, metadata.nsmap) output[tag] = metadata.text.strip() return output def _get_partition(self, i) -> pd.DataFrame:",
"value: return value.replace(nsmap[key], \"\").replace(\"{}\", \"\") # TODO: Discuss if this output shoould be",
"1: if optional is True: # Skip and continue continue else: logging.warn(f\"Manifest missing",
"first value return output def uri2label(self, value: str, nsmap: dict): for key in",
"dtype=None, metadata=None): super(OAIXmlSource, self).__init__(metadata=metadata) self.collection_url = collection_url self.set = set self._collection = Sickle(self.collection_url)",
"return value.replace(nsmap[key], \"\").replace(\"{}\", \"\") # TODO: Discuss if this output shoould be an",
"value.replace(nsmap[key], \"\").replace(\"{}\", \"\") # TODO: Discuss if this output shoould be an array",
"_from_metadata(self, manifest: etree) -> dict: output = {} NS = {'oai_dc': \"http://www.openarchives.org/OAI/2.0/oai_dc/\"} oai_block",
"# Skip and continue continue else: logging.warn(f\"Manifest missing {field}\") else: output[field] = result[0].text.strip()",
"output def _get_partition(self, i) -> pd.DataFrame: return pd.DataFrame(self._records) def _get_path_expressions(self): paths = {}",
"import intake import logging import pandas as pd from sickle import Sickle from",
"pandas as pd from sickle import Sickle from lxml import etree class OAIXmlSource(intake.source.base.DataSource):",
"set=self.set, ignore_deleted=True) for oai_record in oai_records: xtree = etree.fromstring(oai_record.raw) record = self._construct_fields(xtree) record.update(self._from_metadata(xtree))",
"result for metadata in oai_block.getchildren(): tag = self.uri2label(metadata.tag, metadata.nsmap) output[tag] = metadata.text.strip() return",
"\"dataframe\" name = \"oai_xml\" version = \"0.0.1\" partition_access = True def __init__(self, collection_url,",
"self._path_expressions[field]['namespace'] optional = self._path_expressions[field]['optional'] result = manifest.xpath(path, namespaces=namespace) if len(result) < 1: if",
"oai_block.getchildren(): tag = self.uri2label(metadata.tag, metadata.nsmap) output[tag] = metadata.text.strip() return output def _get_partition(self, i)",
"in value: return value.replace(nsmap[key], \"\").replace(\"{}\", \"\") # TODO: Discuss if this output shoould",
"etree) -> dict: output = {} NS = {'oai_dc': \"http://www.openarchives.org/OAI/2.0/oai_dc/\"} oai_block = manifest.xpath(\"//oai_dc:dc\",",
"-> dict: output = {} for field in self._path_expressions: path = self._path_expressions[field]['path'] namespace",
"dict: output = {} for field in self._path_expressions: path = self._path_expressions[field]['path'] namespace =",
"oai_records: xtree = etree.fromstring(oai_record.raw) record = self._construct_fields(xtree) record.update(self._from_metadata(xtree)) self._records.append(record) def _construct_fields(self, manifest: etree)",
"optional = self._path_expressions[field]['optional'] result = manifest.xpath(path, namespaces=namespace) if len(result) < 1: if optional",
"TODO: Ask/Investigate (with jnelson) what the purpose of dtyle=self.dtype def _get_schema(self): self._open_set() return",
"logging.warn(f\"Manifest missing {field}\") else: output[field] = result[0].text.strip() # Use first value return output",
"output[tag] = metadata.text.strip() return output def _get_partition(self, i) -> pd.DataFrame: return pd.DataFrame(self._records) def",
"super(OAIXmlSource, self).__init__(metadata=metadata) self.collection_url = collection_url self.set = set self._collection = Sickle(self.collection_url) self._path_expressions =",
"first result for metadata in oai_block.getchildren(): tag = self.uri2label(metadata.tag, metadata.nsmap) output[tag] = metadata.text.strip()",
"ignore_deleted=True) for oai_record in oai_records: xtree = etree.fromstring(oai_record.raw) record = self._construct_fields(xtree) record.update(self._from_metadata(xtree)) self._records.append(record)",
"return intake.source.base.Schema( datashape=None, dtype=self.dtype, shape=None, npartitions=len(self._records), extra_metadata={}, ) def read(self): self._load_metadata() return pd.concat([self.read_partition(i)",
"{} NS = {'oai_dc': \"http://www.openarchives.org/OAI/2.0/oai_dc/\"} oai_block = manifest.xpath(\"//oai_dc:dc\", namespaces=NS)[0] # we want the",
"xtree = etree.fromstring(oai_record.raw) record = self._construct_fields(xtree) record.update(self._from_metadata(xtree)) self._records.append(record) def _construct_fields(self, manifest: etree) ->",
"field in self._path_expressions: path = self._path_expressions[field]['path'] namespace = self._path_expressions[field]['namespace'] optional = self._path_expressions[field]['optional'] result",
"= {'oai_dc': \"http://www.openarchives.org/OAI/2.0/oai_dc/\"} oai_block = manifest.xpath(\"//oai_dc:dc\", namespaces=NS)[0] # we want the first result",
"= metadata.text.strip() return output def _get_partition(self, i) -> pd.DataFrame: return pd.DataFrame(self._records) def _get_path_expressions(self):",
"i) -> pd.DataFrame: return pd.DataFrame(self._records) def _get_path_expressions(self): paths = {} for name, info",
"= {} for field in self._path_expressions: path = self._path_expressions[field]['path'] namespace = self._path_expressions[field]['namespace'] optional",
"Skip and continue continue else: logging.warn(f\"Manifest missing {field}\") else: output[field] = result[0].text.strip() #",
"version = \"0.0.1\" partition_access = True def __init__(self, collection_url, set, dtype=None, metadata=None): super(OAIXmlSource,",
"self).__init__(metadata=metadata) self.collection_url = collection_url self.set = set self._collection = Sickle(self.collection_url) self._path_expressions = self._get_path_expressions()",
"= self._path_expressions[field]['path'] namespace = self._path_expressions[field]['namespace'] optional = self._path_expressions[field]['optional'] result = manifest.xpath(path, namespaces=namespace) if",
"# TODO: Ask/Investigate (with jnelson) what the purpose of dtyle=self.dtype def _get_schema(self): self._open_set()",
"Ask/Investigate (with jnelson) what the purpose of dtyle=self.dtype def _get_schema(self): self._open_set() return intake.source.base.Schema(",
"pd from sickle import Sickle from lxml import etree class OAIXmlSource(intake.source.base.DataSource): container =",
"def uri2label(self, value: str, nsmap: dict): for key in list(nsmap.keys()): if nsmap[key] in",
"from lxml import etree class OAIXmlSource(intake.source.base.DataSource): container = \"dataframe\" name = \"oai_xml\" version",
"= True def __init__(self, collection_url, set, dtype=None, metadata=None): super(OAIXmlSource, self).__init__(metadata=metadata) self.collection_url = collection_url",
"output = {} NS = {'oai_dc': \"http://www.openarchives.org/OAI/2.0/oai_dc/\"} oai_block = manifest.xpath(\"//oai_dc:dc\", namespaces=NS)[0] # we",
"return paths # TODO: Ask/Investigate (with jnelson) what the purpose of dtyle=self.dtype def",
"Sickle(self.collection_url) self._path_expressions = self._get_path_expressions() self._records = [] def _open_set(self): oai_records = self._collection.ListRecords(metadataPrefix='oai_dc', set=self.set,",
"self._records.append(record) def _construct_fields(self, manifest: etree) -> dict: output = {} for field in",
"= manifest.xpath(\"//oai_dc:dc\", namespaces=NS)[0] # we want the first result for metadata in oai_block.getchildren():",
"{field}\") else: output[field] = result[0].text.strip() # Use first value return output def uri2label(self,",
"for metadata in oai_block.getchildren(): tag = self.uri2label(metadata.tag, metadata.nsmap) output[tag] = metadata.text.strip() return output",
"metadata=None): super(OAIXmlSource, self).__init__(metadata=metadata) self.collection_url = collection_url self.set = set self._collection = Sickle(self.collection_url) self._path_expressions",
"else: output[field] = result[0].text.strip() # Use first value return output def uri2label(self, value:",
"lxml import etree class OAIXmlSource(intake.source.base.DataSource): container = \"dataframe\" name = \"oai_xml\" version =",
"self.set = set self._collection = Sickle(self.collection_url) self._path_expressions = self._get_path_expressions() self._records = [] def",
"etree.fromstring(oai_record.raw) record = self._construct_fields(xtree) record.update(self._from_metadata(xtree)) self._records.append(record) def _construct_fields(self, manifest: etree) -> dict: output"
] |
[
"from sqlalchemy.orm import Session from app.repository import user router = APIRouter(prefix=\"/auth\", tags=['Authentication']) get_db",
"app.hashing import Hash from sqlalchemy.orm import Session from app.repository import user router =",
"detail=f\"Incorrect password\") access_token = token.create_access_token(data={\"sub\": user.email}) return {\"access_token\": access_token, \"token_type\": \"bearer\"} @router.post('/signup', response_model=schemas.ShowUser)",
"Depends(database.get_db)): user = db.query(models.User).filter( models.User.username == request.username).first() if not user: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f\"Invalid",
"= token.create_access_token(data={\"sub\": user.email}) return {\"access_token\": access_token, \"token_type\": \"bearer\"} @router.post('/signup', response_model=schemas.ShowUser) def create_user(request: schemas.User,",
"login(request: schemas.Login, db: Session = Depends(database.get_db)): user = db.query(models.User).filter( models.User.username == request.username).first() if",
"Credentials\") if not Hash.verify(user.password, request.password): raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f\"Incorrect password\") access_token = token.create_access_token(data={\"sub\": user.email})",
"return {\"access_token\": access_token, \"token_type\": \"bearer\"} @router.post('/signup', response_model=schemas.ShowUser) def create_user(request: schemas.User, db: Session =",
"access_token, \"token_type\": \"bearer\"} @router.post('/signup', response_model=schemas.ShowUser) def create_user(request: schemas.User, db: Session = Depends(get_db)): return",
"import OAuth2PasswordRequestForm from app import schemas, database, models, token from app.hashing import Hash",
"@router.post('/login') def login(request: schemas.Login, db: Session = Depends(database.get_db)): user = db.query(models.User).filter( models.User.username ==",
"from app.hashing import Hash from sqlalchemy.orm import Session from app.repository import user router",
"Depends, status, HTTPException from fastapi.security import OAuth2PasswordRequestForm from app import schemas, database, models,",
"request.password): raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f\"Incorrect password\") access_token = token.create_access_token(data={\"sub\": user.email}) return {\"access_token\": access_token, \"token_type\":",
"from fastapi import APIRouter, Depends, status, HTTPException from fastapi.security import OAuth2PasswordRequestForm from app",
"APIRouter, Depends, status, HTTPException from fastapi.security import OAuth2PasswordRequestForm from app import schemas, database,",
"user = db.query(models.User).filter( models.User.username == request.username).first() if not user: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f\"Invalid Credentials\")",
"user: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f\"Invalid Credentials\") if not Hash.verify(user.password, request.password): raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f\"Incorrect password\")",
"detail=f\"Invalid Credentials\") if not Hash.verify(user.password, request.password): raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f\"Incorrect password\") access_token = token.create_access_token(data={\"sub\":",
"database, models, token from app.hashing import Hash from sqlalchemy.orm import Session from app.repository",
"sqlalchemy.orm import Session from app.repository import user router = APIRouter(prefix=\"/auth\", tags=['Authentication']) get_db =",
"OAuth2PasswordRequestForm from app import schemas, database, models, token from app.hashing import Hash from",
"app import schemas, database, models, token from app.hashing import Hash from sqlalchemy.orm import",
"Hash.verify(user.password, request.password): raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f\"Incorrect password\") access_token = token.create_access_token(data={\"sub\": user.email}) return {\"access_token\": access_token,",
"models, token from app.hashing import Hash from sqlalchemy.orm import Session from app.repository import",
"Session from app.repository import user router = APIRouter(prefix=\"/auth\", tags=['Authentication']) get_db = database.get_db @router.post('/login')",
"import Session from app.repository import user router = APIRouter(prefix=\"/auth\", tags=['Authentication']) get_db = database.get_db",
"user router = APIRouter(prefix=\"/auth\", tags=['Authentication']) get_db = database.get_db @router.post('/login') def login(request: schemas.Login, db:",
"= Depends(database.get_db)): user = db.query(models.User).filter( models.User.username == request.username).first() if not user: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,",
"request.username).first() if not user: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f\"Invalid Credentials\") if not Hash.verify(user.password, request.password): raise",
"= APIRouter(prefix=\"/auth\", tags=['Authentication']) get_db = database.get_db @router.post('/login') def login(request: schemas.Login, db: Session =",
"router = APIRouter(prefix=\"/auth\", tags=['Authentication']) get_db = database.get_db @router.post('/login') def login(request: schemas.Login, db: Session",
"{\"access_token\": access_token, \"token_type\": \"bearer\"} @router.post('/signup', response_model=schemas.ShowUser) def create_user(request: schemas.User, db: Session = Depends(get_db)):",
"schemas.Login, db: Session = Depends(database.get_db)): user = db.query(models.User).filter( models.User.username == request.username).first() if not",
"models.User.username == request.username).first() if not user: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f\"Invalid Credentials\") if not Hash.verify(user.password,",
"Hash from sqlalchemy.orm import Session from app.repository import user router = APIRouter(prefix=\"/auth\", tags=['Authentication'])",
"not user: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f\"Invalid Credentials\") if not Hash.verify(user.password, request.password): raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f\"Incorrect",
"fastapi import APIRouter, Depends, status, HTTPException from fastapi.security import OAuth2PasswordRequestForm from app import",
"status, HTTPException from fastapi.security import OAuth2PasswordRequestForm from app import schemas, database, models, token",
"HTTPException from fastapi.security import OAuth2PasswordRequestForm from app import schemas, database, models, token from",
"from app import schemas, database, models, token from app.hashing import Hash from sqlalchemy.orm",
"raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f\"Invalid Credentials\") if not Hash.verify(user.password, request.password): raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f\"Incorrect password\") access_token",
"user.email}) return {\"access_token\": access_token, \"token_type\": \"bearer\"} @router.post('/signup', response_model=schemas.ShowUser) def create_user(request: schemas.User, db: Session",
"database.get_db @router.post('/login') def login(request: schemas.Login, db: Session = Depends(database.get_db)): user = db.query(models.User).filter( models.User.username",
"\"bearer\"} @router.post('/signup', response_model=schemas.ShowUser) def create_user(request: schemas.User, db: Session = Depends(get_db)): return user.create(request, db)",
"Session = Depends(database.get_db)): user = db.query(models.User).filter( models.User.username == request.username).first() if not user: raise",
"import Hash from sqlalchemy.orm import Session from app.repository import user router = APIRouter(prefix=\"/auth\",",
"def login(request: schemas.Login, db: Session = Depends(database.get_db)): user = db.query(models.User).filter( models.User.username == request.username).first()",
"from fastapi.security import OAuth2PasswordRequestForm from app import schemas, database, models, token from app.hashing",
"import APIRouter, Depends, status, HTTPException from fastapi.security import OAuth2PasswordRequestForm from app import schemas,",
"= db.query(models.User).filter( models.User.username == request.username).first() if not user: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f\"Invalid Credentials\") if",
"token.create_access_token(data={\"sub\": user.email}) return {\"access_token\": access_token, \"token_type\": \"bearer\"} @router.post('/signup', response_model=schemas.ShowUser) def create_user(request: schemas.User, db:",
"import user router = APIRouter(prefix=\"/auth\", tags=['Authentication']) get_db = database.get_db @router.post('/login') def login(request: schemas.Login,",
"app.repository import user router = APIRouter(prefix=\"/auth\", tags=['Authentication']) get_db = database.get_db @router.post('/login') def login(request:",
"get_db = database.get_db @router.post('/login') def login(request: schemas.Login, db: Session = Depends(database.get_db)): user =",
"<reponame>maktoobgar/fastapi from fastapi import APIRouter, Depends, status, HTTPException from fastapi.security import OAuth2PasswordRequestForm from",
"fastapi.security import OAuth2PasswordRequestForm from app import schemas, database, models, token from app.hashing import",
"APIRouter(prefix=\"/auth\", tags=['Authentication']) get_db = database.get_db @router.post('/login') def login(request: schemas.Login, db: Session = Depends(database.get_db)):",
"tags=['Authentication']) get_db = database.get_db @router.post('/login') def login(request: schemas.Login, db: Session = Depends(database.get_db)): user",
"HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f\"Invalid Credentials\") if not Hash.verify(user.password, request.password): raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f\"Incorrect password\") access_token =",
"access_token = token.create_access_token(data={\"sub\": user.email}) return {\"access_token\": access_token, \"token_type\": \"bearer\"} @router.post('/signup', response_model=schemas.ShowUser) def create_user(request:",
"== request.username).first() if not user: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f\"Invalid Credentials\") if not Hash.verify(user.password, request.password):",
"db: Session = Depends(database.get_db)): user = db.query(models.User).filter( models.User.username == request.username).first() if not user:",
"not Hash.verify(user.password, request.password): raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f\"Incorrect password\") access_token = token.create_access_token(data={\"sub\": user.email}) return {\"access_token\":",
"password\") access_token = token.create_access_token(data={\"sub\": user.email}) return {\"access_token\": access_token, \"token_type\": \"bearer\"} @router.post('/signup', response_model=schemas.ShowUser) def",
"db.query(models.User).filter( models.User.username == request.username).first() if not user: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f\"Invalid Credentials\") if not",
"\"token_type\": \"bearer\"} @router.post('/signup', response_model=schemas.ShowUser) def create_user(request: schemas.User, db: Session = Depends(get_db)): return user.create(request,",
"schemas, database, models, token from app.hashing import Hash from sqlalchemy.orm import Session from",
"import schemas, database, models, token from app.hashing import Hash from sqlalchemy.orm import Session",
"from app.repository import user router = APIRouter(prefix=\"/auth\", tags=['Authentication']) get_db = database.get_db @router.post('/login') def",
"HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f\"Incorrect password\") access_token = token.create_access_token(data={\"sub\": user.email}) return {\"access_token\": access_token, \"token_type\": \"bearer\"} @router.post('/signup',",
"= database.get_db @router.post('/login') def login(request: schemas.Login, db: Session = Depends(database.get_db)): user = db.query(models.User).filter(",
"raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f\"Incorrect password\") access_token = token.create_access_token(data={\"sub\": user.email}) return {\"access_token\": access_token, \"token_type\": \"bearer\"}",
"if not user: raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f\"Invalid Credentials\") if not Hash.verify(user.password, request.password): raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,",
"if not Hash.verify(user.password, request.password): raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f\"Incorrect password\") access_token = token.create_access_token(data={\"sub\": user.email}) return",
"token from app.hashing import Hash from sqlalchemy.orm import Session from app.repository import user"
] |
[
"compose of digits from 0 to 9. ''' return re.match(r'^-?[0-9]+$', value) is not",
"return int.from_bytes(_bytes, 'big') def toBytes(self, value): '''Convert Integer to bytes using big endian'''",
"from .BaseType import BaseType from ..Manager import Register import re class Integer(BaseType): '''Integer",
"An Integer is only compose of digits from 0 to 9. ''' name",
"'int' def format(self, value): '''Format string to Integer''' return int(value) def detect(self, value):",
"bytes using big endian''' return value.to_bytes(max(1, (value.bit_length() + 7) // 8), 'big') def",
"'big') def toString(self, value): '''Return value as string''' return str(value) # Register the",
"can be written without a fractional component. An Integer is only compose of",
"bytes to Integer using big endian''' return int.from_bytes(_bytes, 'big') def toBytes(self, value): '''Convert",
"from 0 to 9. ''' return re.match(r'^-?[0-9]+$', value) is not None def fromBytes(self,",
"is not None def fromBytes(self, _bytes): '''Convert bytes to Integer using big endian'''",
"class Integer(BaseType): '''Integer type An Integer is a number that can be written",
"fromBytes(self, _bytes): '''Convert bytes to Integer using big endian''' return int.from_bytes(_bytes, 'big') def",
"component. An Integer is only compose of digits from 0 to 9. '''",
"_bytes): '''Convert bytes to Integer using big endian''' return int.from_bytes(_bytes, 'big') def toBytes(self,",
"None def fromBytes(self, _bytes): '''Convert bytes to Integer using big endian''' return int.from_bytes(_bytes,",
"def detect(self, value): '''Is value an Integer ? Test if value is only",
"compose of digits from 0 to 9. ''' name = 'int' def format(self,",
"'''Format string to Integer''' return int(value) def detect(self, value): '''Is value an Integer",
"be written without a fractional component. An Integer is only compose of digits",
"from ..Manager import Register import re class Integer(BaseType): '''Integer type An Integer is",
"9. ''' return re.match(r'^-?[0-9]+$', value) is not None def fromBytes(self, _bytes): '''Convert bytes",
"format(self, value): '''Format string to Integer''' return int(value) def detect(self, value): '''Is value",
"string to Integer''' return int(value) def detect(self, value): '''Is value an Integer ?",
"a number that can be written without a fractional component. An Integer is",
"toString(self, value): '''Return value as string''' return str(value) # Register the type Register.registerType(Integer())",
"type An Integer is a number that can be written without a fractional",
"number that can be written without a fractional component. An Integer is only",
"re.match(r'^-?[0-9]+$', value) is not None def fromBytes(self, _bytes): '''Convert bytes to Integer using",
"9. ''' name = 'int' def format(self, value): '''Format string to Integer''' return",
"value): '''Convert Integer to bytes using big endian''' return value.to_bytes(max(1, (value.bit_length() + 7)",
"Integer is only compose of digits from 0 to 9. ''' name =",
"using big endian''' return value.to_bytes(max(1, (value.bit_length() + 7) // 8), 'big') def toString(self,",
"import Register import re class Integer(BaseType): '''Integer type An Integer is a number",
"digits from 0 to 9. ''' return re.match(r'^-?[0-9]+$', value) is not None def",
"endian''' return int.from_bytes(_bytes, 'big') def toBytes(self, value): '''Convert Integer to bytes using big",
"= 'int' def format(self, value): '''Format string to Integer''' return int(value) def detect(self,",
"Integer ? Test if value is only compose of digits from 0 to",
"+ 7) // 8), 'big') def toString(self, value): '''Return value as string''' return",
"#!/usr/bin/env python3 # coding: utf-8 from .BaseType import BaseType from ..Manager import Register",
"def fromBytes(self, _bytes): '''Convert bytes to Integer using big endian''' return int.from_bytes(_bytes, 'big')",
"name = 'int' def format(self, value): '''Format string to Integer''' return int(value) def",
"if value is only compose of digits from 0 to 9. ''' return",
"int(value) def detect(self, value): '''Is value an Integer ? Test if value is",
"is only compose of digits from 0 to 9. ''' name = 'int'",
"to bytes using big endian''' return value.to_bytes(max(1, (value.bit_length() + 7) // 8), 'big')",
"import re class Integer(BaseType): '''Integer type An Integer is a number that can",
"value): '''Is value an Integer ? Test if value is only compose of",
"import BaseType from ..Manager import Register import re class Integer(BaseType): '''Integer type An",
"Integer''' return int(value) def detect(self, value): '''Is value an Integer ? Test if",
"value is only compose of digits from 0 to 9. ''' return re.match(r'^-?[0-9]+$',",
"to 9. ''' name = 'int' def format(self, value): '''Format string to Integer'''",
"is a number that can be written without a fractional component. An Integer",
"digits from 0 to 9. ''' name = 'int' def format(self, value): '''Format",
"only compose of digits from 0 to 9. ''' return re.match(r'^-?[0-9]+$', value) is",
"big endian''' return value.to_bytes(max(1, (value.bit_length() + 7) // 8), 'big') def toString(self, value):",
"'''Convert Integer to bytes using big endian''' return value.to_bytes(max(1, (value.bit_length() + 7) //",
"coding: utf-8 from .BaseType import BaseType from ..Manager import Register import re class",
"re class Integer(BaseType): '''Integer type An Integer is a number that can be",
"a fractional component. An Integer is only compose of digits from 0 to",
"endian''' return value.to_bytes(max(1, (value.bit_length() + 7) // 8), 'big') def toString(self, value): '''Return",
"'''Convert bytes to Integer using big endian''' return int.from_bytes(_bytes, 'big') def toBytes(self, value):",
"7) // 8), 'big') def toString(self, value): '''Return value as string''' return str(value)",
"without a fractional component. An Integer is only compose of digits from 0",
"python3 # coding: utf-8 from .BaseType import BaseType from ..Manager import Register import",
"fractional component. An Integer is only compose of digits from 0 to 9.",
"Integer using big endian''' return int.from_bytes(_bytes, 'big') def toBytes(self, value): '''Convert Integer to",
"not None def fromBytes(self, _bytes): '''Convert bytes to Integer using big endian''' return",
"Register import re class Integer(BaseType): '''Integer type An Integer is a number that",
"def format(self, value): '''Format string to Integer''' return int(value) def detect(self, value): '''Is",
"value): '''Format string to Integer''' return int(value) def detect(self, value): '''Is value an",
"only compose of digits from 0 to 9. ''' name = 'int' def",
"return value.to_bytes(max(1, (value.bit_length() + 7) // 8), 'big') def toString(self, value): '''Return value",
"Integer(BaseType): '''Integer type An Integer is a number that can be written without",
"value.to_bytes(max(1, (value.bit_length() + 7) // 8), 'big') def toString(self, value): '''Return value as",
"to Integer using big endian''' return int.from_bytes(_bytes, 'big') def toBytes(self, value): '''Convert Integer",
"Integer to bytes using big endian''' return value.to_bytes(max(1, (value.bit_length() + 7) // 8),",
"def toString(self, value): '''Return value as string''' return str(value) # Register the type",
"// 8), 'big') def toString(self, value): '''Return value as string''' return str(value) #",
"0 to 9. ''' name = 'int' def format(self, value): '''Format string to",
"written without a fractional component. An Integer is only compose of digits from",
"big endian''' return int.from_bytes(_bytes, 'big') def toBytes(self, value): '''Convert Integer to bytes using",
"BaseType from ..Manager import Register import re class Integer(BaseType): '''Integer type An Integer",
"8), 'big') def toString(self, value): '''Return value as string''' return str(value) # Register",
".BaseType import BaseType from ..Manager import Register import re class Integer(BaseType): '''Integer type",
"''' name = 'int' def format(self, value): '''Format string to Integer''' return int(value)",
"of digits from 0 to 9. ''' return re.match(r'^-?[0-9]+$', value) is not None",
"'''Integer type An Integer is a number that can be written without a",
"return re.match(r'^-?[0-9]+$', value) is not None def fromBytes(self, _bytes): '''Convert bytes to Integer",
"from 0 to 9. ''' name = 'int' def format(self, value): '''Format string",
"utf-8 from .BaseType import BaseType from ..Manager import Register import re class Integer(BaseType):",
"return int(value) def detect(self, value): '''Is value an Integer ? Test if value",
"detect(self, value): '''Is value an Integer ? Test if value is only compose",
"0 to 9. ''' return re.match(r'^-?[0-9]+$', value) is not None def fromBytes(self, _bytes):",
"int.from_bytes(_bytes, 'big') def toBytes(self, value): '''Convert Integer to bytes using big endian''' return",
"'big') def toBytes(self, value): '''Convert Integer to bytes using big endian''' return value.to_bytes(max(1,",
"value) is not None def fromBytes(self, _bytes): '''Convert bytes to Integer using big",
"(value.bit_length() + 7) // 8), 'big') def toString(self, value): '''Return value as string'''",
"Integer is a number that can be written without a fractional component. An",
"..Manager import Register import re class Integer(BaseType): '''Integer type An Integer is a",
"# coding: utf-8 from .BaseType import BaseType from ..Manager import Register import re",
"using big endian''' return int.from_bytes(_bytes, 'big') def toBytes(self, value): '''Convert Integer to bytes",
"''' return re.match(r'^-?[0-9]+$', value) is not None def fromBytes(self, _bytes): '''Convert bytes to",
"Test if value is only compose of digits from 0 to 9. '''",
"of digits from 0 to 9. ''' name = 'int' def format(self, value):",
"toBytes(self, value): '''Convert Integer to bytes using big endian''' return value.to_bytes(max(1, (value.bit_length() +",
"an Integer ? Test if value is only compose of digits from 0",
"to 9. ''' return re.match(r'^-?[0-9]+$', value) is not None def fromBytes(self, _bytes): '''Convert",
"value an Integer ? Test if value is only compose of digits from",
"that can be written without a fractional component. An Integer is only compose",
"An Integer is a number that can be written without a fractional component.",
"'''Is value an Integer ? Test if value is only compose of digits",
"is only compose of digits from 0 to 9. ''' return re.match(r'^-?[0-9]+$', value)",
"to Integer''' return int(value) def detect(self, value): '''Is value an Integer ? Test",
"def toBytes(self, value): '''Convert Integer to bytes using big endian''' return value.to_bytes(max(1, (value.bit_length()",
"? Test if value is only compose of digits from 0 to 9."
] |
[
"from database_management import Database, ResultSet import configparser DBINFO = configparser.ConfigParser() DBINFO.read('database.config') WMM_MAIN_DB =",
"import Database, ResultSet import configparser DBINFO = configparser.ConfigParser() DBINFO.read('database.config') WMM_MAIN_DB = Database(DBINFO['Database']['Name'], DBINFO['User']['Name'],",
"Database, ResultSet import configparser DBINFO = configparser.ConfigParser() DBINFO.read('database.config') WMM_MAIN_DB = Database(DBINFO['Database']['Name'], DBINFO['User']['Name'], DBINFO['Database']['Host'],",
"database_management import Database, ResultSet import configparser DBINFO = configparser.ConfigParser() DBINFO.read('database.config') WMM_MAIN_DB = Database(DBINFO['Database']['Name'],",
"ResultSet import configparser DBINFO = configparser.ConfigParser() DBINFO.read('database.config') WMM_MAIN_DB = Database(DBINFO['Database']['Name'], DBINFO['User']['Name'], DBINFO['Database']['Host'], DBINFO['Database']['Port'])",
"<reponame>Irsutoro/Where-is-my-money from database_management import Database, ResultSet import configparser DBINFO = configparser.ConfigParser() DBINFO.read('database.config') WMM_MAIN_DB"
] |
[
"class Todo(db.Model): __tablename__ = 'todo' id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String, nullable=False)",
"default=False, nullable=True) def __init__(self, title: str, contents: str) -> None: self.title = title",
"__repr__(self) -> str: return f'<Todo {self.title}>' class TodoSchema(ma.ModelSchema): class Meta: model = Todo",
"db.Column(db.DateTime, nullable=True) is_done = db.Column(db.Boolean, default=False, nullable=True) def __init__(self, title: str, contents: str)",
"import db, ma class Todo(db.Model): __tablename__ = 'todo' id = db.Column(db.Integer, primary_key=True) title",
"def __init__(self, title: str, contents: str) -> None: self.title = title self.contents =",
"str, contents: str) -> None: self.title = title self.contents = contents def __repr__(self)",
"is_done = db.Column(db.Boolean, default=False, nullable=True) def __init__(self, title: str, contents: str) -> None:",
"primary_key=True) title = db.Column(db.String, nullable=False) contents = db.Column(db.String, nullable=False) priority = db.Column(db.Integer, default=1,",
"default=1, nullable=False) deadline = db.Column(db.DateTime, nullable=True) is_done = db.Column(db.Boolean, default=False, nullable=True) def __init__(self,",
"-*- from app.extensions import db, ma class Todo(db.Model): __tablename__ = 'todo' id =",
"= db.Column(db.DateTime, nullable=True) is_done = db.Column(db.Boolean, default=False, nullable=True) def __init__(self, title: str, contents:",
"db, ma class Todo(db.Model): __tablename__ = 'todo' id = db.Column(db.Integer, primary_key=True) title =",
"title self.contents = contents def __repr__(self) -> str: return f'<Todo {self.title}>' class TodoSchema(ma.ModelSchema):",
"title = db.Column(db.String, nullable=False) contents = db.Column(db.String, nullable=False) priority = db.Column(db.Integer, default=1, nullable=False)",
"db.Column(db.Integer, default=1, nullable=False) deadline = db.Column(db.DateTime, nullable=True) is_done = db.Column(db.Boolean, default=False, nullable=True) def",
"= 'todo' id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String, nullable=False) contents = db.Column(db.String,",
"= db.Column(db.String, nullable=False) priority = db.Column(db.Integer, default=1, nullable=False) deadline = db.Column(db.DateTime, nullable=True) is_done",
"db.Column(db.Integer, primary_key=True) title = db.Column(db.String, nullable=False) contents = db.Column(db.String, nullable=False) priority = db.Column(db.Integer,",
"__init__(self, title: str, contents: str) -> None: self.title = title self.contents = contents",
"nullable=True) is_done = db.Column(db.Boolean, default=False, nullable=True) def __init__(self, title: str, contents: str) ->",
"priority = db.Column(db.Integer, default=1, nullable=False) deadline = db.Column(db.DateTime, nullable=True) is_done = db.Column(db.Boolean, default=False,",
"None: self.title = title self.contents = contents def __repr__(self) -> str: return f'<Todo",
"coding: utf-8 -*- from app.extensions import db, ma class Todo(db.Model): __tablename__ = 'todo'",
"title: str, contents: str) -> None: self.title = title self.contents = contents def",
"nullable=False) priority = db.Column(db.Integer, default=1, nullable=False) deadline = db.Column(db.DateTime, nullable=True) is_done = db.Column(db.Boolean,",
"= db.Column(db.String, nullable=False) contents = db.Column(db.String, nullable=False) priority = db.Column(db.Integer, default=1, nullable=False) deadline",
"= title self.contents = contents def __repr__(self) -> str: return f'<Todo {self.title}>' class",
"id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String, nullable=False) contents = db.Column(db.String, nullable=False) priority",
"app.extensions import db, ma class Todo(db.Model): __tablename__ = 'todo' id = db.Column(db.Integer, primary_key=True)",
"__tablename__ = 'todo' id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String, nullable=False) contents =",
"nullable=False) contents = db.Column(db.String, nullable=False) priority = db.Column(db.Integer, default=1, nullable=False) deadline = db.Column(db.DateTime,",
"deadline = db.Column(db.DateTime, nullable=True) is_done = db.Column(db.Boolean, default=False, nullable=True) def __init__(self, title: str,",
"'todo' id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String, nullable=False) contents = db.Column(db.String, nullable=False)",
"self.contents = contents def __repr__(self) -> str: return f'<Todo {self.title}>' class TodoSchema(ma.ModelSchema): class",
"contents def __repr__(self) -> str: return f'<Todo {self.title}>' class TodoSchema(ma.ModelSchema): class Meta: model",
"ma class Todo(db.Model): __tablename__ = 'todo' id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String,",
"<filename>server/app/models.py # -*- coding: utf-8 -*- from app.extensions import db, ma class Todo(db.Model):",
"-*- coding: utf-8 -*- from app.extensions import db, ma class Todo(db.Model): __tablename__ =",
"contents = db.Column(db.String, nullable=False) priority = db.Column(db.Integer, default=1, nullable=False) deadline = db.Column(db.DateTime, nullable=True)",
"= db.Column(db.Boolean, default=False, nullable=True) def __init__(self, title: str, contents: str) -> None: self.title",
"db.Column(db.Boolean, default=False, nullable=True) def __init__(self, title: str, contents: str) -> None: self.title =",
"utf-8 -*- from app.extensions import db, ma class Todo(db.Model): __tablename__ = 'todo' id",
"Todo(db.Model): __tablename__ = 'todo' id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String, nullable=False) contents",
"nullable=False) deadline = db.Column(db.DateTime, nullable=True) is_done = db.Column(db.Boolean, default=False, nullable=True) def __init__(self, title:",
"self.title = title self.contents = contents def __repr__(self) -> str: return f'<Todo {self.title}>'",
"db.Column(db.String, nullable=False) contents = db.Column(db.String, nullable=False) priority = db.Column(db.Integer, default=1, nullable=False) deadline =",
"= db.Column(db.Integer, default=1, nullable=False) deadline = db.Column(db.DateTime, nullable=True) is_done = db.Column(db.Boolean, default=False, nullable=True)",
"= contents def __repr__(self) -> str: return f'<Todo {self.title}>' class TodoSchema(ma.ModelSchema): class Meta:",
"= db.Column(db.Integer, primary_key=True) title = db.Column(db.String, nullable=False) contents = db.Column(db.String, nullable=False) priority =",
"str) -> None: self.title = title self.contents = contents def __repr__(self) -> str:",
"-> None: self.title = title self.contents = contents def __repr__(self) -> str: return",
"nullable=True) def __init__(self, title: str, contents: str) -> None: self.title = title self.contents",
"def __repr__(self) -> str: return f'<Todo {self.title}>' class TodoSchema(ma.ModelSchema): class Meta: model =",
"contents: str) -> None: self.title = title self.contents = contents def __repr__(self) ->",
"from app.extensions import db, ma class Todo(db.Model): __tablename__ = 'todo' id = db.Column(db.Integer,",
"db.Column(db.String, nullable=False) priority = db.Column(db.Integer, default=1, nullable=False) deadline = db.Column(db.DateTime, nullable=True) is_done =",
"# -*- coding: utf-8 -*- from app.extensions import db, ma class Todo(db.Model): __tablename__"
] |
[] |
[
"https://www.hackerrank.com/challenges/2d-array a=[0]*6 for i in range(6): a[i]=[int(x) for x in input().split()] c=-9*9 for",
"in range(6): a[i]=[int(x) for x in input().split()] c=-9*9 for i in range(1,5): for",
"in input().split()] c=-9*9 for i in range(1,5): for j in range(1,5): c=max(c,a[i-1][j-1]+a[i-1][j]+a[i-1][j+1]+a[i][j]+a[i+1][j-1]+a[i+1][j]+a[i+1][j+1]) print(c)",
"for i in range(6): a[i]=[int(x) for x in input().split()] c=-9*9 for i in",
"for x in input().split()] c=-9*9 for i in range(1,5): for j in range(1,5):",
"x in input().split()] c=-9*9 for i in range(1,5): for j in range(1,5): c=max(c,a[i-1][j-1]+a[i-1][j]+a[i-1][j+1]+a[i][j]+a[i+1][j-1]+a[i+1][j]+a[i+1][j+1])",
"python3 # https://www.hackerrank.com/challenges/2d-array a=[0]*6 for i in range(6): a[i]=[int(x) for x in input().split()]",
"a[i]=[int(x) for x in input().split()] c=-9*9 for i in range(1,5): for j in",
"i in range(6): a[i]=[int(x) for x in input().split()] c=-9*9 for i in range(1,5):",
"#!/usr/bin/env python3 # https://www.hackerrank.com/challenges/2d-array a=[0]*6 for i in range(6): a[i]=[int(x) for x in",
"range(6): a[i]=[int(x) for x in input().split()] c=-9*9 for i in range(1,5): for j",
"a=[0]*6 for i in range(6): a[i]=[int(x) for x in input().split()] c=-9*9 for i",
"# https://www.hackerrank.com/challenges/2d-array a=[0]*6 for i in range(6): a[i]=[int(x) for x in input().split()] c=-9*9"
] |
[
"def _handle_msg(self, msg) -> bool: super()._handle_msg(msg) if \"domain_id\" in msg.payload: idx = msg.payload[\"domain_id\"]",
"ATTR_UFH_SYSTEM: { d.id: d.status for d in sorted(self._ctl.devices) if d.type == \"02\" },",
"d.type != \"02\"] ) # devices without a parent zone, NB: CTL can",
"create_dhw(zone_idx) -> DhwZone: if self.dhw: raise LookupError(f\"Duplicate stored HW: {zone_idx}\") dhw = self._dhw",
"for z in self._zones}} class UfhSystem: @property def schema(self) -> dict: assert ATTR_UFH_SYSTEM",
"and msg.verb in (\" I\", \"RP\"): if \"domain_id\" in msg.payload and msg.payload[\"domain_id\"] ==",
"controller has already been allocated if len([z for z in self.zones if z.sensor",
"params[ATTR_HTG_SYSTEM] # TODO: removeme params[ATTR_HTG_SYSTEM][\"system_mode\"] = self.system_mode return params class StoredHw: MIN_SETPOINT =",
"controllers - a generic controller (e.g. ST9420C).\"\"\" # 0008|0009|1030|1100|2309|3B00 def __init__(self, gwy, ctl,",
"None and # if self.dhw.sensor is None: # find_dhw_sensor(msg) pass elif msg.code in",
"the RP/313F # await self.wait_for(Command(\"313F\", verb=\"RQ\")) # return self.datetime # async def set_datetime(self,",
"--:------ 3EF0 006 0000100000FF # noqa # 06:49:03.465 045 RQ --- 01:145038 13:237335",
"non-deterministic Data from the CTL is considered more authorative. The RQ is initiated",
"# self._api_lock.release() # async def get_datetime(self) -> str: # wait for the RP/313F",
"str: # wait for the RP/313F # await self.wait_for(Command(\"313F\", verb=\"RQ\")) # return self.datetime",
"= ( self.heating_control._get_msg_value(\"1100\") if self.heating_control else None ) return params @property def status(self)",
"self.heating_control else None # ) status[ATTR_HTG_SYSTEM][\"heat_demand\"] = self.heat_demand status[ATTR_DEVICES] = {d.id: d.status for",
"is dhw: return raise CorruptStateError(\"DHW shouldn't change: {self._dhw} to {dhw}\") if self._dhw is",
"ELE) self._send_cmd(\"0005\", payload=f\"00{zone_type}\") for zone_type in (\"08\", \"09\", \"0A\", \"0B\", \"11\") # CODE_0005_ZONE_TYPE",
"# if isinstance(msg.payload, list): # super()._handle_msg(msg) # [xxx(z) for z in msg.payload] #",
"self._htg_control = None def __repr__(self) -> str: return f\"{self._ctl.id} (sys_base)\" # def __str__(self)",
"@property def language(self) -> Optional[str]: # 0100 return self._msg_payload(self._language, \"language\") @property def params(self)",
"Optional[dict]: # 2E04 return self._msg_payload(self._system_mode) def set_mode(self, system_mode=None, until=None) -> Task: \"\"\"Set a",
"( self.heating_control.id if self.heating_control else None ) assert ATTR_ORPHANS not in schema[ATTR_HTG_SYSTEM] #",
"create_zone(zone_idx) -> Zone: if int(zone_idx, 16) >= self._gwy.config[MAX_ZONES]: raise ValueError(f\"Invalid zone idx: {zone_idx}",
"zone @property def dhw(self) -> DhwZone: return self._dhw def _set_dhw(self, dhw: DhwZone) ->",
"self.schema}) def _discover(self, discover_flag=DISCOVER_ALL) -> None: # super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_SCHEMA: [",
"= {ATTR_HTG_SYSTEM: {}} assert ATTR_HTG_SYSTEM in params # TODO: removeme # devices don't",
"removeme return {**super().status, ATTR_DHW_SYSTEM: self.dhw.status if self.dhw else {}} class MultiZone: # 0005",
"In particular, the controller may be a sensor for a zone, but unfortunately",
"- with unique/non-null temps (from 30C9), no sensor (from state): %s\", testable_zones, )",
"\"0B\", \"11\") # CODE_0005_ZONE_TYPE ] [ # 0005: find any others - as",
"# TODO: make a dt object # def wait_for(self, cmd, callback): # self._api_lock.acquire()",
"and actuators. \"\"\" def create_zone(zone_idx) -> Zone: if int(zone_idx, 16) >= self._gwy.config[MAX_ZONES]: raise",
"elif msg.code == \"0009\": self._relay_failsafes[idx] = msg elif msg.code == \"3150\": self._heat_demands[idx] =",
"msg.code @property def heat_demands(self) -> Optional[dict]: # 3150 if self._heat_demands: return {k: v.payload[\"heat_demand\"]",
"msg.code == \"0100\" and msg.verb in (\" I\", \"RP\"): self._language = msg @property",
"self._heat_demand = None self._htg_control = None def __repr__(self) -> str: return f\"{self._ctl.id} (sys_base)\"",
"self._relay_demands.items() } @property def relay_failsafes(self) -> Optional[dict]: # 0009 if self._relay_failsafes: return {}",
"# only if in monitor mode... secs = self._get_msg_value(\"1F09\", \"remaining_seconds\") if secs is",
"return zone if zone_idx == \"HW\": return super()._get_zone(zone_idx, sensor=sensor, **kwargs) if int(zone_idx, 16)",
"10A0 RQ/RP *from/to a 07:* (1x/4h) - reliable 2. Use sensor temp matching",
"ctl, **kwargs) -> None: # _LOGGER.debug(\"Creating a System: %s (%s)\", dev_addr.id, self.__class__) super().__init__(gwy,",
"] if discover_flag & DISCOVER_STATUS: self._send_cmd(\"0006\") def _handle_msg(self, msg, prev_msg=None): def OUT_find_zone_sensors() ->",
"= msg if msg.payload[\"domain_id\"] == \"F9\": device = self.dhw.heating_valve if self.dhw else None",
"class Hometronics(System): RQ_SUPPORTED = (\"0004\", \"000C\", \"2E04\", \"313F\") # TODO: WIP RQ_UNSUPPORTED =",
"- The evohome-compatible system.\"\"\" import logging from asyncio import Task from datetime import",
"if discover_flag & DISCOVER_SCHEMA: [ # 0005: find any zones + their type",
"authorative. The I/1260 is not to/from a controller, so is not useful. \"\"\"",
"\"04\", \"0C\", \"0F\", \"10\") ] if discover_flag & DISCOVER_STATUS: self._send_cmd(\"0006\") def _handle_msg(self, msg,",
"**kwargs) -> None: super().__init__(*args, **kwargs) self._dhw = None def _discover(self, discover_flag=DISCOVER_ALL) -> None:",
"CTL as a sensor... if len(matching_sensors) == 0: _LOGGER.debug(\" - matched sensor: %s",
"TODO: removeme assert ATTR_HTG_CONTROL not in schema[ATTR_HTG_SYSTEM] # TODO: removeme schema[ATTR_HTG_SYSTEM][ATTR_HTG_CONTROL] = (",
"I\" and prev is not None: if prev.code == this.code and prev.verb ==",
"object # def wait_for(self, cmd, callback): # self._api_lock.acquire() # self._send_cmd(\"313F\", verb=\"RQ\", callback=callback) #",
"set_auto(self) -> Task: \"\"\"Revert system to Auto, set non-PermanentOverride zones to FollowSchedule.\"\"\" return",
"if msg.code == \"0100\" and msg.verb in (\" I\", \"RP\"): self._language = msg",
"bool: def OUT_is_exchange(this, prev): # TODO:use is? return this.src is prev.dst and this.dst",
"bool: super()._handle_msg(msg) if \"domain_id\" in msg.payload: idx = msg.payload[\"domain_id\"] if msg.code == \"0008\":",
"force *all* zones to FollowSchedule.\"\"\" return self.set_mode(SystemMode.RESET) @property def params(self) -> dict: params",
"assert \"language\" not in params[ATTR_HTG_SYSTEM] # TODO: removeme params[ATTR_HTG_SYSTEM][\"language\"] = self.language return params",
"self._gwy.config[DISABLE_DISCOVERY]: # TODO: needs tidyup (ref #67) zone._discover() # discover_flag=DISCOVER_ALL) return zone if",
"# _LOGGER.debug(\"Creating a System: %s (%s)\", dev_addr.id, self.__class__) super().__init__(gwy, **kwargs) self.id = ctl.id",
"dhw(self) -> DhwZone: return self._dhw def _set_dhw(self, dhw: DhwZone) -> None: # self._dhw",
"None: super().__init__(*args, **kwargs) self.zones = [] self.zone_by_idx = {} # self.zone_by_name = {}",
"# if discover_flag & DISCOVER_PARAMS: # for domain_id in range(0xF8, 0x100): # self._send_cmd(\"0009\",",
"# if zone._temp is None: # return # TODO: should have a (not-None)",
"(10: or 13:).\"\"\" if not isinstance(device, Device) or device.type not in (\"10\", \"13\"):",
"{d.id: d.device_info for d in sorted(self._ctl.devices)} return schema @property def params(self) -> dict:",
"# zone._zone_config = zone_dict # elif msg.code == \"2309\": # zone._temp = zone_dict",
"def _discover(self, discover_flag=DISCOVER_ALL) -> None: super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_PARAMS: self._send_cmd(\"0100\") # language",
"= self._msgz[\" I\"].get(\"0418\") return status class SysDatetime: # 313F def __init__(self, *args, **kwargs)",
"RQ/07/01, RP/01/07: can get both parent controller & DHW sensor # 047 RQ",
"-> DhwZone: return self._dhw def _set_dhw(self, dhw: DhwZone) -> None: # self._dhw \"\"\"Set",
"parent zone, NB: CTL can be a sensor for a zones # TODO:",
"0004 if discover_flag & DISCOVER_STATUS: self._send_cmd(\"1F09\") class Programmer(Evohome): def __repr__(self) -> str: return",
"not in super().schema # TODO: removeme return {**super().schema, ATTR_ZONES: {z.idx: z.schema for z",
"with changed temps _LOGGER.debug(\"Changed zones (from 30C9): %s\", changed_zones) if not changed_zones: return",
"for this system. There's' 3 ways to find a controller's heat relay (in",
"heater = prev.src if heater is not None: self._set_htg_control(heater) if msg.code in (\"000A\",",
"# time_start = dt.now() # while not self._schedule_done: # await asyncio.sleep(TIMER_SHORT_SLEEP) # if",
"dict: status = super().status assert ATTR_HTG_SYSTEM in status # TODO: removeme assert \"datetime\"",
"RQ is initiated by the DHW, so is not authorative. The I/1260 is",
"-> Task: \"\"\"Revert system to Auto, force *all* zones to FollowSchedule.\"\"\" return self.set_mode(SystemMode.RESET)",
"discover_flag & DISCOVER_PARAMS: # for domain_id in range(0xF8, 0x100): # self._send_cmd(\"0009\", payload=f\"{domain_id:02X}00\") if",
"= ( self.heating_control.id if self.heating_control else None ) assert ATTR_ORPHANS not in schema[ATTR_HTG_SYSTEM]",
"evohome-compatible system.\"\"\" import logging from asyncio import Task from datetime import timedelta as",
"def _discover(self, discover_flag=DISCOVER_ALL) -> None: # super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_SCHEMA: [ #",
"(system)\" def _handle_msg(self, msg) -> bool: super()._handle_msg(msg) if \"domain_id\" in msg.payload: idx =",
"self._send_cmd(\"1100\", payload=\"FC\") # TPI params # # for code in (\"3B00\",): # 3EF0,",
"{self}\") zone = Zone(self, zone_idx) if not self._gwy.config[DISABLE_DISCOVERY]: # TODO: needs tidyup (ref",
"\"02\" }, } @property def params(self) -> dict: assert ATTR_UFH_SYSTEM not in super().params",
"assert \"fault_log\" not in status # TODO: removeme status[\"fault_log\"] = self._fault_log.fault_log status[\"last_fault\"] =",
"not in (\"10\", \"13\"): raise TypeError(f\"{ATTR_HTG_CONTROL} can't be: {device}\") if self._htg_control is not",
"return f\"{self._ctl.id} (system)\" def _handle_msg(self, msg) -> bool: super()._handle_msg(msg) if \"domain_id\" in msg.payload:",
"ATTR_CONTROLLER, ATTR_DHW_SYSTEM, ATTR_HTG_CONTROL, ATTR_HTG_SYSTEM, ATTR_ORPHANS, ATTR_UFH_SYSTEM, ATTR_ZONES, DISABLE_DISCOVERY, MAX_ZONES, ) from .zones import",
"no single zone without a sensor testable_zones = { z: t for z,",
"not None: zone._set_dhw_sensor(sensor) return zone @property def dhw(self) -> DhwZone: return self._dhw def",
"# zone = self.zone_by_idx[zone_idx] # if zone._temp is None: # return # TODO:",
"isinstance(msg.payload, list): for zone_idx in self.zone_by_idx: cmd = Command.get_zone_mode(self.id, zone_idx, priority=Priority.LOW) self._gwy.send_cmd(cmd) #",
"# TODO: WIP # return json.dumps({self._ctl.id: self.schema}) def _discover(self, discover_flag=DISCOVER_ALL) -> None: #",
"heat_demand(self) -> Optional[float]: # 3150/FC if self._heat_demand: return self._heat_demand[\"heat_demand\"] @property def is_calling_for_heat(self) ->",
"self.dhw else None elif msg.payload[\"domain_id\"] == \"FC\": device = self.heating_control else: device =",
"the DHW zone system.\"\"\" if not isinstance(dhw, DhwZone): raise TypeError(f\"stored_hw can't be: {dhw}\")",
"len(htg_control) == 1 else None # HACK for 10: def _set_htg_control(self, device: Device)",
"# self._htg_control \"\"\"Set the heating control relay for this system (10: or 13:).\"\"\"",
"sensor=sensor, **kwargs) if int(zone_idx, 16) >= self._gwy.config[MAX_ZONES]: raise ValueError(f\"Unknown zone_idx/domain_id: {zone_idx}\") zone =",
"self._schedule_done: # await asyncio.sleep(TIMER_SHORT_SLEEP) # if dt.now() > time_start + TIMER_LONG_TIMEOUT: # self._api_lock.release()",
"= self.dhw.hotwater_valve if self.dhw else None elif msg.payload[\"domain_id\"] == \"FC\": device = self.heating_control",
"= [ s for s in testable_sensors if s.temperature == temp and s._zone",
"dhw: DhwZone) -> None: # self._dhw \"\"\"Set the DHW zone system.\"\"\" if not",
"t for z, t in changed_zones.items() if self.zone_by_idx[z].sensor is None } # this",
"Can also set a zone's sensor, and zone_type, and actuators. \"\"\" def create_zone(zone_idx)",
"else None elif msg.payload[\"domain_id\"] == \"FA\": device = self.dhw.hotwater_valve if self.dhw else None",
"else None ) return params @property def status(self) -> dict: \"\"\"Return the system's",
".schema import ( ATTR_CONTROLLER, ATTR_DHW_SYSTEM, ATTR_HTG_CONTROL, ATTR_HTG_SYSTEM, ATTR_ORPHANS, ATTR_UFH_SYSTEM, ATTR_ZONES, DISABLE_DISCOVERY, MAX_ZONES, )",
"# self.heating_control.params if self.heating_control else None # ) assert \"tpi_params\" not in params[ATTR_HTG_SYSTEM]",
"000004FFFFFF1E060E0507E4 # 045 I --- 01:145038 --:------ 01:145038 1F41 006 000002FFFFFF sensor =",
"@property def tpi_params(self) -> Optional[float]: # 1100 return self._get_msg_value(\"1100\") @property def heat_demand(self) ->",
"true if ctl is sensor if not testable_zones: return # no testable zones",
"-> Zone: \"\"\"Return a zone (will create it if required). Can also set",
"-> str: return f\"{self._ctl.id} (chronotherm)\" class Hometronics(System): RQ_SUPPORTED = (\"0004\", \"000C\", \"2E04\", \"313F\")",
"if self.heating_control else None # ) status[ATTR_HTG_SYSTEM][\"heat_demand\"] = self.heat_demand status[ATTR_DEVICES] = {d.id: d.status",
"# TODO: W self._datetime = msg @property def datetime(self) -> Optional[str]: return self._msg_payload(self._datetime,",
"@property def hotwater_valve(self) -> Device: return self._dhw._dhw_valve if self._dhw else None @property def",
"(from state): %s\", testable_zones, ) if not testable_zones: return # no testable zones",
"but not: configured_zones # will RP to: 0004 if discover_flag & DISCOVER_STATUS: self._send_cmd(\"1F09\")",
"no testable zones zone_idx, temp = list(testable_zones.items())[0] _LOGGER.debug(\"Testing (sole remaining) zone %s, temp:",
"def schema(self) -> dict: assert ATTR_DHW_SYSTEM not in super().schema # TODO: removeme return",
"indefinitely.\"\"\" cmd = Command.set_system_mode(self.id, system_mode=system_mode, until=until) return self._gwy.send_cmd(cmd) def set_auto(self) -> Task: \"\"\"Revert",
"dict: assert ATTR_DHW_SYSTEM not in super().status # TODO: removeme return {**super().status, ATTR_DHW_SYSTEM: self.dhw.status",
"temp, ?also includes it's parent zone matching_sensors = [ s for s in",
"controller - need to match temps # 045 I --- 07:045960 --:------ 07:045960",
"RQ --- 01:145038 13:237335 --:------ 3EF0 001 00 # 06:49:07.468 045 RQ ---",
"v.payload[\"relay_demand\"] for k, v in self._relay_demands.items() } @property def relay_failsafes(self) -> Optional[dict]: #",
"045 I --- 07:045960 --:------ 07:045960 1260 003 000911 # 1F41: I/01: get",
"not isinstance(dhw, DhwZone): raise TypeError(f\"stored_hw can't be: {dhw}\") if self._dhw is not None:",
"discover_flag=DISCOVER_ALL) -> None: super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_STATUS: self._gwy._tasks.append(self._loop.create_task(self.get_fault_log())) async def get_fault_log(self, force_refresh=None)",
"if required). Can also set a DHW zone's sensor & valves?. \"\"\" def",
"z in self.zones if z.sensor is None]) != 1: return # no single",
"dict: status = super().status assert \"fault_log\" not in status # TODO: removeme status[\"fault_log\"]",
"return self._msg_payload(self._datetime, \"datetime\") # TODO: make a dt object # def wait_for(self, cmd,",
"the order: most to least reliable heater = None if this.code == \"3220\"",
"None elif msg.payload[\"domain_id\"] == \"FC\": device = self.heating_control else: device = None if",
"is None: zone = create_dhw(zone_idx) if kwargs.get(\"dhw_valve\"): zone._set_dhw_valve(kwargs[\"dhw_valve\"]) if kwargs.get(\"htg_valve\"): zone._set_dhw_valve(kwargs[\"htg_valve\"]) if sensor",
"\"09\", \"0A\", \"0B\", \"11\") # CODE_0005_ZONE_TYPE ] [ # 0005: find any others",
"# TODO: removeme params[ATTR_HTG_SYSTEM][\"system_mode\"] = self.system_mode return params class StoredHw: MIN_SETPOINT = 30.0",
"{ SystemType.CHRONOTHERM: Chronotherm, SystemType.EVOHOME: Evohome, SystemType.HOMETRONICS: Hometronics, SystemType.PROGRAMMER: Programmer, SystemType.SUNDIAL: Sundial, SystemType.GENERIC: System,",
"{zone_idx} for {self}\") zone = Zone(self, zone_idx) if not self._gwy.config[DISABLE_DISCOVERY]: # TODO: needs",
"gwy, ctl, **kwargs) -> None: super().__init__(gwy, ctl, **kwargs) def __repr__(self) -> str: return",
"-> str: # wait for the I/313F # await self.wait_for(Command(\"313F\", verb=\" W\", payload=f\"00{dtm_to_hex(dtm)}\"))",
"# TODO: removeme status[ATTR_HTG_SYSTEM][\"datetime\"] = self.datetime return status class SysLanguage: # 0100 def",
"coding: utf-8 -*- # \"\"\"Evohome RF - The evohome-compatible system.\"\"\" import logging from",
"001 00 # 06:49:07.468 045 RQ --- 01:145038 13:237335 --:------ 3EF0 001 00",
"SysDatetime: # 313F def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self._datetime =",
"idx = msg.payload[\"domain_id\"] if msg.code == \"0008\": self._relay_demands[idx] = msg elif msg.code ==",
"evohome # class Evohome(System): # evohome \"\"\"The Evohome system - some controllers are",
"= self.zone_by_idx[zone_idx] zone._set_sensor(matching_sensors[0]) zone.sensor._set_ctl(self) elif len(matching_sensors) == 0: _LOGGER.debug(\" - no matching sensor",
"else None @property def heating_valve(self) -> Device: return self._dhw._htg_valve if self._dhw else None",
"prev_msg, self._prev_30c9 = self._prev_30c9, msg if prev_msg is None: return if len([z for",
"13:* (3x/60min) 3. The 3B00 I/I exchange between a CTL & a 13:",
"noqa # 06:49:03.465 045 RQ --- 01:145038 13:237335 --:------ 3EF0 001 00 #",
"reliable heater = None if this.code == \"3220\" and this.verb == \"RQ\": if",
"zoneless)\", {d.id: d.temperature for d in testable_sensors}, ) if testable_sensors: # the main",
"@property def params(self) -> dict: \"\"\"Return the system's configuration.\"\"\" params = {ATTR_HTG_SYSTEM: {}}",
"[v for k, v in changed_zones.items() if k != z] + [None] }",
"return {**super().schema, ATTR_DHW_SYSTEM: self.dhw.schema if self.dhw else {}} @property def params(self) -> dict:",
"# CODE_0005_ZONE_TYPE ] [ # 0005: find any others - as per an",
"(same temp & not from another zone)\", [s.id for s in matching_sensors], )",
"if isinstance(msg.payload, list): # super()._handle_msg(msg) # [xxx(z) for z in msg.payload] # else:",
"msg.code in (\"1F41\",): # dhw_mode pass def _get_zone(self, zone_idx, sensor=None, **kwargs) -> DhwZone:",
"controller as a sensor. \"\"\" prev_msg, self._prev_30c9 = self._prev_30c9, msg if prev_msg is",
"!= z] + [None] } # ...with unique (non-null) temps, and no sensor",
"-> str: # TODO: WIP # return json.dumps({self._ctl.id: self.schema}) def _discover(self, discover_flag=DISCOVER_ALL) ->",
"status class Evohome(SysLanguage, SysMode, MultiZone, UfhSystem, System): # evohome # class Evohome(System): #",
"discover_flag=DISCOVER_ALL) -> None: super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_PARAMS: self._send_cmd(\"0100\") # language def _handle_msg(self,",
"self.system_mode return params class StoredHw: MIN_SETPOINT = 30.0 # NOTE: these may be",
"msg) -> bool: super()._handle_msg(msg) # def xxx(zone_dict): # zone = self.zone_by_idx[zone_dict.pop(\"zone_idx\")] # if",
"# for zone in self.zones: # zone._discover(discover_flags=DISCOVER_PARAMS) if msg.code in (\"000A\", \"2309\", \"30C9\"):",
"self._api_lock.release() # async def get_datetime(self) -> str: # wait for the RP/313F #",
"_LOGGER.debug(\"Testing zone %s, temp: %s\", zone_idx, temp) _LOGGER.debug( \" - matching sensor(s): %s",
"# ctl's 30C9 says no zones have changed temps during this cycle testable_zones",
"self._htg_control \"\"\"Set the heating control relay for this system (10: or 13:).\"\"\" if",
"zone._discover(discover_flags=DISCOVER_PARAMS) if msg.code in (\"000A\", \"2309\", \"30C9\"): pass # if isinstance(msg.payload, list): #",
"discover_flag & DISCOVER_SCHEMA: [ # 0005: find any zones + their type (RAD,",
"also set a DHW zone's sensor & valves?. \"\"\" def create_dhw(zone_idx) -> DhwZone:",
"this.src is self and this.dst.type == \"10\": heater = this.dst elif this.code ==",
"schema[ATTR_HTG_SYSTEM] # TODO: removeme schema[ATTR_ORPHANS] = sorted( [d.id for d in self._ctl.devices if",
"13:237335 3B00 002 00C8 # 09:04:02.667 045 I --- 01:145038 --:------ 01:145038 3B00",
"in self.zone_by_idx: cmd = Command.get_zone_mode(self.id, zone_idx, priority=Priority.LOW) self._gwy.send_cmd(cmd) # for zone in self.zones:",
"= logging.getLogger(__name__) if DEV_MODE: _LOGGER.setLevel(logging.DEBUG) class SysFaultLog: # 0418 def __init__(self, *args, **kwargs)",
"HW: {zone_idx}\") dhw = self._dhw = DhwZone(self) if not self._gwy.config[DISABLE_DISCOVERY]: dhw._discover() # discover_flag=DISCOVER_ALL)",
"@property def status(self) -> dict: status = super().status assert \"fault_log\" not in status",
"the heating control relay for this system (10: or 13:).\"\"\" if not isinstance(device,",
"{} self.zone_lock = Lock() self.zone_lock_idx = None # self._prev_30c9 = None # OUT:",
"put this? # assert \"devices\" not in schema # TODO: removeme # schema[\"devices\"]",
"# TODO: removeme assert \"datetime\" not in status[ATTR_HTG_SYSTEM] # TODO: removeme status[ATTR_HTG_SYSTEM][\"datetime\"] =",
"== \"FC\": self._heat_demand = msg.payload # if msg.code in (\"3220\", \"3B00\", \"3EF0\"): #",
"heating_valve(self) -> Device: return self._dhw._htg_valve if self._dhw else None @property def schema(self) ->",
"09:04:02.667 045 I --- 01:145038 --:------ 01:145038 3B00 002 FCC8 # note the",
"__init__(self, gwy, ctl, **kwargs) -> None: super().__init__(gwy, ctl, **kwargs) def __repr__(self) -> str:",
"# else: # xxx(msg.payload) if msg.code in (\"000A\", \"2309\", \"30C9\") and isinstance(msg.payload, list):",
"= __dev_mode__ _LOGGER = logging.getLogger(__name__) if DEV_MODE: _LOGGER.setLevel(logging.DEBUG) class SysFaultLog: # 0418 def",
"# for code in (\"3B00\",): # 3EF0, 3EF1 # # for payload in",
"None: # find_dhw_sensor(msg) pass elif msg.code in (\"1F41\",): # dhw_mode pass def _get_zone(self,",
"**kwargs) self.zones = [] self.zone_by_idx = {} # self.zone_by_name = {} self.zone_lock =",
"ctl's 30C9 says no zones have changed temps during this cycle testable_zones =",
"sensorless)\", testable_zones, ) _LOGGER.debug( \"Testable sensors: %s (non-null temps & orphans or zoneless)\",",
"this.src is self and this.dst.type in (\"10\", \"13\"): heater = this.dst elif this.code",
"# elif msg.code == \"000C\": # self._msgs[f\"{msg.code}\"] = msg # elif msg.code ==",
"utf-8 -*- # \"\"\"Evohome RF - The evohome-compatible system.\"\"\" import logging from asyncio",
"relays in DHW) self._send_cmd(\"000C\", payload=dev_type) for dev_type in (\"000D\", \"000F\") # CODE_000C_DEVICE_TYPE #",
"= self.heating_control else: device = None if False and device is not None:",
"def __repr__(self) -> str: return f\"{self._ctl.id} (sundial)\" SYSTEM_CLASSES = { SystemType.CHRONOTHERM: Chronotherm, SystemType.EVOHOME:",
"return # no single zone without a sensor testable_zones = { z: t",
"\"30C9\": # zone._temp = zone_dict # if msg.code in (\"000A\", \"2309\", \"30C9\"): #",
"matching sensor(s): %s (same temp & not from another zone)\", [s.id for s",
"sensor is not None: if self.dhw is None: self._get_zone(\"FA\") self.dhw._set_sensor(sensor) super()._handle_msg(msg) if msg.code",
"not isinstance(msg.payload, list): pass else: super()._handle_msg(msg) if msg.code == \"0008\" and msg.verb in",
"not self: # raise LookupError if self._htg_control is None: self._htg_control = device device._set_parent(self,",
"None: zone = create_zone(zone_idx) if kwargs.get(\"zone_type\"): zone._set_zone_type(kwargs[\"zone_type\"]) if kwargs.get(\"actuators\"): # TODO: check not",
"except ExpiredCallbackError: return @property def status(self) -> dict: status = super().status assert \"fault_log\"",
"# TODO: removeme return {**super().schema, ATTR_DHW_SYSTEM: self.dhw.schema if self.dhw else {}} @property def",
"sensor: %s (by exclusion)\", self._ctl.id) zone = self.zone_by_idx[zone_idx] zone._set_sensor(self) zone.sensor._set_ctl(self) _LOGGER.debug(\"System state (finally):",
"# elif msg.code == \"2309\": # zone._temp = zone_dict # elif msg.code ==",
"f\"{ATTR_HTG_CONTROL} shouldn't change: {self._htg_control} to {device}\" ) # if device.evo is not None",
"dhw_sensor(self) -> Device: return self._dhw._dhw_sensor if self._dhw else None @property def hotwater_valve(self) ->",
"using the CTL as a sensor... if len(matching_sensors) == 0: _LOGGER.debug(\" - matched",
"in (self, None) and d.addr.type in DEVICE_HAS_ZONE_SENSOR and d.temperature is not None and",
"str: return f\"{self._ctl.id} (evohome)\" def _discover(self, discover_flag=DISCOVER_ALL) -> None: super()._discover(discover_flag=discover_flag) if discover_flag &",
"maintain the system state.\"\"\" def OUT_find_dhw_sensor(this): \"\"\"Discover the stored HW this system (if",
"DISCOVER_STATUS: # self._send_cmd(\"2E04\", payload=\"FF\") # system mode self._gwy.send_cmd(Command.get_system_mode(self.id)) def _handle_msg(self, msg, prev_msg=None): super()._handle_msg(msg)",
"of exclusion as a means to determine which zone uses the controller as",
"**kwargs) self.id = ctl.id gwy.systems.append(self) gwy.system_by_id[self.id] = self self._ctl = ctl self._domain_id =",
"self._gwy.send_cmd(Command.get_system_mode(self.id)) def _handle_msg(self, msg, prev_msg=None): super()._handle_msg(msg) if msg.code == \"2E04\" and msg.verb in",
"matching - non-deterministic Data from the CTL is considered more authorative. The RQ",
"# return self.datetime @property def status(self) -> dict: status = super().status assert ATTR_HTG_SYSTEM",
"await self._fault_log.get_fault_log(force_refresh=force_refresh) except ExpiredCallbackError: return @property def status(self) -> dict: status = super().status",
">= self._gwy.config[MAX_ZONES]: raise ValueError(f\"Unknown zone_idx/domain_id: {zone_idx}\") zone = self.zone_by_idx.get(zone_idx) if zone is None:",
"f\"{self._ctl.id} (sys_base)\" # def __str__(self) -> str: # TODO: WIP # return json.dumps({self._ctl.id:",
"zone = self.zone_by_idx[zone_idx] # if zone._temp is None: # return # TODO: should",
"gwy, ctl, **kwargs) -> None: super().__init__(gwy, ctl, **kwargs) self._heat_demands = {} self._relay_demands =",
"30C9): %s\", changed_zones) if not changed_zones: return # ctl's 30C9 says no zones",
"DhwZone: return self._dhw def _set_dhw(self, dhw: DhwZone) -> None: # self._dhw \"\"\"Set the",
"Optional[float]: # 3150/FC if self._heat_demand: return self._heat_demand[\"heat_demand\"] @property def is_calling_for_heat(self) -> Optional[bool]: \"\"\"Return",
"sensor & valves?. \"\"\" def create_dhw(zone_idx) -> DhwZone: if self.dhw: raise LookupError(f\"Duplicate stored",
"too rare to be useful. \"\"\" # 18:14:14.025 066 RQ --- 01:078710 10:067219",
"not in super().schema # TODO: removeme return {**super().schema, ATTR_DHW_SYSTEM: self.dhw.schema if self.dhw else",
"self._ctl.id, ATTR_HTG_SYSTEM: {}} assert ATTR_HTG_SYSTEM in schema # TODO: removeme assert ATTR_HTG_CONTROL not",
"valves?. \"\"\" def create_dhw(zone_idx) -> DhwZone: if self.dhw: raise LookupError(f\"Duplicate stored HW: {zone_idx}\")",
"return f\"{self._ctl.id} (sys_base)\" # def __str__(self) -> str: # TODO: WIP # return",
"if msg.code in (\"000A\", \"2309\", \"30C9\") and isinstance(msg.payload, list): pass class Chronotherm(Evohome): def",
"if discover_flag & DISCOVER_STATUS: self._gwy._tasks.append(self._loop.create_task(self.get_fault_log())) async def get_fault_log(self, force_refresh=None) -> Optional[dict]: # 0418",
"{zone_idx} (exceeds max_zones)\") if zone_idx in self.zone_by_idx: raise LookupError(f\"Duplicated zone: {zone_idx} for {self}\")",
"in status[ATTR_HTG_SYSTEM] # TODO: removeme # status[ATTR_HTG_SYSTEM][ATTR_HTG_CONTROL] = ( # self.heating_control.status if self.heating_control",
"current state.\"\"\" status = {ATTR_HTG_SYSTEM: {}} assert ATTR_HTG_SYSTEM in status # TODO: removeme",
"priority=Priority.LOW) self._gwy.send_cmd(cmd) # for zone in self.zones: # zone._discover(discover_flags=DISCOVER_PARAMS) if msg.code in (\"000A\",",
"OUT_find_zone_sensors() -> None: \"\"\"Determine each zone's sensor by matching zone/sensor temperatures. The temperature",
"params[ATTR_HTG_SYSTEM] # TODO: removeme params[ATTR_HTG_SYSTEM][\"tpi_params\"] = ( self.heating_control._get_msg_value(\"1100\") if self.heating_control else None )",
"find a controller's heat relay (in order of reliability): 1. The 3220 RQ/RP",
"heating control relay for this system (10: or 13:).\"\"\" if not isinstance(device, Device)",
"\"1260\"): # self.dhw.sensor is None and # if self.dhw.sensor is None: # find_dhw_sensor(msg)",
"@property def status(self) -> dict: assert ATTR_DHW_SYSTEM not in super().status # TODO: removeme",
"removeme return { **super().params, ATTR_UFH_SYSTEM: { d.id: d.params for d in sorted(self._ctl.devices) if",
"a specified duration, or indefinitely.\"\"\" cmd = Command.set_system_mode(self.id, system_mode=system_mode, until=until) return self._gwy.send_cmd(cmd) def",
"*to/from a 10:* (1x/5min) 2a. The 3EF0 RQ/RP *to/from a 10:* (1x/1min) 2b.",
"sensor=None, **kwargs) -> Zone: \"\"\"Return a zone (will create it if required). Can",
"system_mode(self) -> Optional[dict]: # 2E04 return self._msg_payload(self._system_mode) def set_mode(self, system_mode=None, until=None) -> Task:",
"# self._send_cmd(\"0008\", payload=f\"{domain_id:02X}00\") pass def _handle_msg(self, msg) -> bool: def OUT_is_exchange(this, prev): #",
"removeme assert ATTR_HTG_CONTROL not in schema[ATTR_HTG_SYSTEM] # TODO: removeme schema[ATTR_HTG_SYSTEM][ATTR_HTG_CONTROL] = ( self.heating_control.id",
"{self._dhw} to {dhw}\") if self._dhw is None: # self._gwy._get_device(xxx) # self.add_device(dhw.sensor) # self.add_device(dhw.relay)",
"# 0418 try: return await self._fault_log.get_fault_log(force_refresh=force_refresh) except ExpiredCallbackError: return @property def status(self) ->",
"if self.zone_by_idx[z].sensor is None } # this will be true if ctl is",
"None: super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_PARAMS: self._send_cmd(\"0100\") # language def _handle_msg(self, msg, prev_msg=None):",
"self._msg_payload(self._language, \"language\") @property def params(self) -> dict: params = super().params assert ATTR_HTG_SYSTEM in",
"--- 13:237335 --:------ 13:237335 3B00 002 00C8 # 09:04:02.667 045 I --- 01:145038",
"= this.dst elif this.code == \"3B00\" and this.verb == \" I\" and prev",
"\"\"\"Eavesdrop packets, or pairs of packets, to maintain the system state.\"\"\" def OUT_find_dhw_sensor(this):",
"parent controller, but not DHW sensor # 045 I --- 01:145038 --:------ 01:145038",
"if self.zone_by_idx[z].sensor is None and t not in [v for k, v in",
"self.dhw.hotwater_valve if self.dhw else None elif msg.payload[\"domain_id\"] == \"FC\": device = self.heating_control else:",
"*args, **kwargs) -> None: super().__init__(*args, **kwargs) self._datetime = None def _discover(self, discover_flag=DISCOVER_ALL) ->",
"for z, t in changed_zones.items() if self.zone_by_idx[z].sensor is None } # this will",
"_discover(self, discover_flag=DISCOVER_ALL) -> None: super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_STATUS: self._send_cmd(\"1F09\") def _handle_msg(self, msg)",
"DISABLE_DISCOVERY, MAX_ZONES, ) from .zones import DhwZone, Zone DEV_MODE = __dev_mode__ _LOGGER =",
"a sensor... if self._zone is not None: return # the controller has already",
"# TODO: removeme params[ATTR_HTG_SYSTEM][\"tpi_params\"] = ( self.heating_control._get_msg_value(\"1100\") if self.heating_control else None ) return",
"not in schema[ATTR_HTG_SYSTEM] # TODO: removeme schema[ATTR_HTG_SYSTEM][ATTR_HTG_CONTROL] = ( self.heating_control.id if self.heating_control else",
"raise LookupError(f\"Duplicate stored HW: {zone_idx}\") dhw = self._dhw = DhwZone(self) if not self._gwy.config[DISABLE_DISCOVERY]:",
"== \"3150\": self._heat_demands[idx] = msg elif msg.code not in (\"0001\", \"000C\", \"0418\", \"1100\",",
"-> str: return f\"{self._ctl.id} (programmer)\" class Sundial(Evohome): def __repr__(self) -> str: return f\"{self._ctl.id}",
"for heat.\"\"\" if not self._htg_control: return if self._htg_control.actuator_state: return True @property def schema(self)",
"pass def _get_zone(self, zone_idx, sensor=None, **kwargs) -> DhwZone: \"\"\"Return a DHW zone (will",
"zone_idx/domain_id: {zone_idx}\") zone = self.zone_by_idx.get(zone_idx) if zone is None: zone = create_zone(zone_idx) if",
"@property def schema(self) -> dict: assert ATTR_DHW_SYSTEM not in super().schema # TODO: removeme",
"msg, prev_msg=None): super()._handle_msg(msg) if msg.code == \"313F\" and msg.verb in (\" I\", \"RP\"):",
"3B00 I/I exchange between a CTL & a 13: (TPI cycle rate, usu.",
"== \"313F\" and msg.verb in (\" I\", \"RP\"): # TODO: W self._datetime =",
"changed_zones = { z[\"zone_idx\"]: z[\"temperature\"] for z in msg.payload if z not in",
"00181F0003E4 # 062 RP --- 01:102458 07:030741 --:------ 10A0 006 0018380003E8 # 1260:",
"# TODO: removeme # devices don't have params # assert ATTR_HTG_CONTROL not in",
"not None: # zone_added = bool(prev_msg.code == \"0004\") # else zone_deleted # elif",
"async def get_fault_log(self, force_refresh=None) -> Optional[dict]: # 0418 try: return await self._fault_log.get_fault_log(force_refresh=force_refresh) except",
"-> str: return f\"{self._ctl.id} (sys_base)\" # def __str__(self) -> str: # TODO: WIP",
"if msg.code == \"313F\" and msg.verb in (\" I\", \"RP\"): # TODO: W",
"_discover(self, discover_flag=DISCOVER_ALL) -> None: super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_PARAMS: self._send_cmd(\"0100\") # language def",
"None: \"\"\"Determine each zone's sensor by matching zone/sensor temperatures. The temperature of each",
"Priority from .const import ( ATTR_DEVICES, DEVICE_HAS_ZONE_SENSOR, DISCOVER_ALL, DISCOVER_PARAMS, DISCOVER_SCHEMA, DISCOVER_STATUS, SystemMode, SystemType,",
"= None if this.code == \"10A0\" and this.verb == \"RP\": if this.src is",
"in (\"10A0\", \"1260\"): # self.dhw.sensor is None and # if self.dhw.sensor is None:",
"# TODO: removeme # params[ATTR_HTG_SYSTEM][ATTR_HTG_CONTROL] = ( # self.heating_control.params if self.heating_control else None",
"elif msg.code == \"30C9\": # zone._temp = zone_dict # if msg.code in (\"000A\",",
"self.zone_by_name = {} self.zone_lock = Lock() self.zone_lock_idx = None # self._prev_30c9 = None",
"Device: return self._dhw._htg_valve if self._dhw else None @property def schema(self) -> dict: assert",
"= create_zone(zone_idx) if kwargs.get(\"zone_type\"): zone._set_zone_type(kwargs[\"zone_type\"]) if kwargs.get(\"actuators\"): # TODO: check not an address",
"d in sorted(self._ctl.devices)} return status class System(StoredHw, SysDatetime, SystemBase): # , SysFaultLog \"\"\"The",
"status[ATTR_HTG_SYSTEM] # TODO: removeme status[ATTR_HTG_SYSTEM][\"datetime\"] = self.datetime return status class SysLanguage: # 0100",
"= None if False and device is not None: # TODO: FIXME qos",
"in super().schema # TODO: removeme return {**super().schema, ATTR_DHW_SYSTEM: self.dhw.schema if self.dhw else {}}",
"temp and s._zone in (zone_idx, None) ] _LOGGER.debug( \" - matching sensor(s): %s",
"msg.code in (\"3220\", \"3B00\", \"3EF0\"): # self.heating_control is None and # find_htg_relay(msg, prev=prev_msg)",
"# OUT: used to discover zone sensors def _discover(self, discover_flag=DISCOVER_ALL) -> None: super()._discover(discover_flag=discover_flag)",
"WIP RQ_UNSUPPORTED = (\"xxxx\",) # 10E0? def __repr__(self) -> str: return f\"{self._ctl.id} (hometronics)\"",
"prev=prev_msg) def _send_cmd(self, code, **kwargs) -> None: dest = kwargs.pop(\"dest_addr\", self._ctl.id) payload =",
"# self._send_cmd(\"2E04\", payload=\"FF\") # system mode self._gwy.send_cmd(Command.get_system_mode(self.id)) def _handle_msg(self, msg, prev_msg=None): super()._handle_msg(msg) if",
"in params[ATTR_HTG_SYSTEM] # TODO: removeme # params[ATTR_HTG_SYSTEM][ATTR_HTG_CONTROL] = ( # self.heating_control.params if self.heating_control",
"The evohome-compatible system.\"\"\" import logging from asyncio import Task from datetime import timedelta",
"= self.datetime return status class SysLanguage: # 0100 def __init__(self, *args, **kwargs) ->",
"Task from datetime import timedelta as td from threading import Lock from typing",
"dict: return sorted(self.zones, key=lambda x: x.idx) @property def schema(self) -> dict: assert ATTR_ZONES",
"case self._system_mode = msg @property def system_mode(self) -> Optional[dict]: # 2E04 return self._msg_payload(self._system_mode)",
"is not authorative. The I/1260 is not to/from a controller, so is not",
"removeme return {**super().status, ATTR_ZONES: {z.idx: z.status for z in self._zones}} class UfhSystem: @property",
"# 045 I --- 01:145038 --:------ 01:145038 1F41 012 000004FFFFFF1E060E0507E4 # 045 I",
"msg, prev_msg=None): def OUT_find_zone_sensors() -> None: \"\"\"Determine each zone's sensor by matching zone/sensor",
"@property def devices(self) -> List[Device]: return self._ctl.devices + [self._ctl] # TODO: to sort",
"-> str: return f\"{self._ctl.id} (sundial)\" SYSTEM_CLASSES = { SystemType.CHRONOTHERM: Chronotherm, SystemType.EVOHOME: Evohome, SystemType.HOMETRONICS:",
"-> dict: \"\"\"Return the system's schema.\"\"\" schema = {ATTR_CONTROLLER: self._ctl.id, ATTR_HTG_SYSTEM: {}} assert",
"self.zone_by_idx[zone_dict.pop(\"zone_idx\")] # if msg.code == \"000A\": # zone._zone_config = zone_dict # elif msg.code",
"this.dst if sensor is not None: if self.dhw is None: self._get_zone(\"FA\") self.dhw._set_sensor(sensor) super()._handle_msg(msg)",
"and isinstance(msg.payload, list): # msg.is_array: # find_zone_sensors() def _get_zone(self, zone_idx, sensor=None, **kwargs) ->",
"is None]) == 0: return # (currently) no zone without a sensor #",
"!= 1: return # no single zone without a sensor testable_zones = {",
"but not DHW sensor # 045 I --- 01:145038 --:------ 01:145038 1F41 012",
"%s (non-null temps & orphans or zoneless)\", {d.id: d.temperature for d in testable_sensors},",
"self._relay_demands = {} self._relay_failsafes = {} def __repr__(self) -> str: return f\"{self._ctl.id} (system)\"",
"dev_addr.id, self.__class__) super().__init__(gwy, **kwargs) self.id = ctl.id gwy.systems.append(self) gwy.system_by_id[self.id] = self self._ctl =",
"None: super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_STATUS: # self._send_cmd(\"2E04\", payload=\"FF\") # system mode self._gwy.send_cmd(Command.get_system_mode(self.id))",
"does not announce its sensor temperatures. In addition, there may be 'orphan' (e.g.",
"== 1: _LOGGER.debug(\" - matched sensor: %s\", matching_sensors[0].id) zone = self.zone_by_idx[zone_idx] zone._set_sensor(matching_sensors[0]) zone.sensor._set_ctl(self)",
"ATTR_DEVICES, DEVICE_HAS_ZONE_SENSOR, DISCOVER_ALL, DISCOVER_PARAMS, DISCOVER_SCHEMA, DISCOVER_STATUS, SystemMode, SystemType, __dev_mode__, ) from .devices import",
"045 RQ --- 01:145038 13:237335 --:------ 3EF0 001 00 # 06:49:05.467 045 RQ",
"msg.payload[\"domain_id\"] == \"F9\": device = self.dhw.heating_valve if self.dhw else None elif msg.payload[\"domain_id\"] ==",
"& DISCOVER_STATUS: self._send_cmd(\"1F09\") def _handle_msg(self, msg) -> bool: super()._handle_msg(msg) # def xxx(zone_dict): #",
"assert ATTR_HTG_SYSTEM in params # TODO: removeme assert \"system_mode\" not in params[ATTR_HTG_SYSTEM] #",
"return sorted(self.zones, key=lambda x: x.idx) @property def schema(self) -> dict: assert ATTR_ZONES not",
"is None and # if self.dhw.sensor is None: # find_dhw_sensor(msg) pass elif msg.code",
"CODE_000C_DEVICE_TYPE # for dev_type, description in CODE_000C_DEVICE_TYPE.items() fix payload # if description is",
"cmd, callback): # self._api_lock.acquire() # self._send_cmd(\"313F\", verb=\"RQ\", callback=callback) # time_start = dt.now() #",
"if d._domain_id == \"FC\"] return htg_control[0] if len(htg_control) == 1 else None #",
"await self.wait_for(Command(\"313F\", verb=\" W\", payload=f\"00{dtm_to_hex(dtm)}\")) # return self.datetime @property def status(self) -> dict:",
"params = super().params assert ATTR_HTG_SYSTEM in params # TODO: removeme assert \"system_mode\" not",
"__init__(self, gwy, ctl, **kwargs) -> None: super().__init__(gwy, ctl, **kwargs) self._heat_demands = {} self._relay_demands",
"(programmer)\" class Sundial(Evohome): def __repr__(self) -> str: return f\"{self._ctl.id} (sundial)\" SYSTEM_CLASSES = {",
"if self._dhw else None @property def heating_valve(self) -> Device: return self._dhw._htg_valve if self._dhw",
"return self._htg_control htg_control = [d for d in self._ctl.devices if d._domain_id == \"FC\"]",
"= self.zone_by_idx[zone_idx] # if zone._temp is None: # return # TODO: should have",
"def _get_zone(self, zone_idx, sensor=None, **kwargs) -> Zone: \"\"\"Return a zone (will create it",
"07:030741 01:102458 --:------ 10A0 006 00181F0003E4 # 062 RP --- 01:102458 07:030741 --:------",
"z in self._zones}} @property def status(self) -> dict: assert ATTR_ZONES not in super().status",
"is? return this.src is prev.dst and this.dst is prev.src.addr def OUT_find_htg_relay(this, prev=None): \"\"\"Discover",
"None: if self._dhw is dhw: return raise CorruptStateError(\"DHW shouldn't change: {self._dhw} to {dhw}\")",
"-> Device: return self._dhw._dhw_sensor if self._dhw else None @property def hotwater_valve(self) -> Device:",
"sensors: %s\", matching_sensors) _LOGGER.debug(\"System state (after): %s\", self) # now see if we",
"if self.heating_control else None # ) assert \"tpi_params\" not in params[ATTR_HTG_SYSTEM] # TODO:",
"def OUT_find_dhw_sensor(this): \"\"\"Discover the stored HW this system (if any). There is only",
"msg.code == \"30C9\" and isinstance(msg.payload, list): # msg.is_array: # find_zone_sensors() def _get_zone(self, zone_idx,",
"in self._zones}} @property def params(self) -> dict: assert ATTR_ZONES not in super().params #",
"# 10A0: RQ/07/01, RP/01/07: can get both parent controller & DHW sensor #",
"TODO:use is? return this.src is prev.dst and this.dst is prev.src.addr def OUT_find_htg_relay(this, prev=None):",
"- matching sensor(s): %s (excl. controller)\", [s.id for s in matching_sensors], ) #",
"testable_sensors if s.temperature == temp and s._zone in (zone_idx, None) ] _LOGGER.debug(\"Testing zone",
"ctl, **kwargs) def __repr__(self) -> str: return f\"{self._ctl.id} (evohome)\" def _discover(self, discover_flag=DISCOVER_ALL) ->",
"set a zone's sensor, and zone_type, and actuators. \"\"\" def create_zone(zone_idx) -> Zone:",
"not in super().params # TODO: removeme return { **super().params, ATTR_UFH_SYSTEM: { d.id: d.params",
"device.evo is not None and device.evo is not self: # raise LookupError if",
"\"13\": heater = prev.src if heater is not None: self._set_htg_control(heater) if msg.code in",
"in super().params # TODO: removeme return { **super().params, ATTR_UFH_SYSTEM: { d.id: d.params for",
"status class System(StoredHw, SysDatetime, SystemBase): # , SysFaultLog \"\"\"The Controller class.\"\"\" def __init__(self,",
"MAX_ZONES, ) from .zones import DhwZone, Zone DEV_MODE = __dev_mode__ _LOGGER = logging.getLogger(__name__)",
"\"10\": heater = this.dst elif this.code == \"3EF0\" and this.verb == \"RQ\": if",
"no zone without a sensor # if self._gwy.serial_port: # only if in monitor",
"self._gwy.devices # not: self.devices if d._ctl in (self, None) and d.addr.type in DEVICE_HAS_ZONE_SENSOR",
"= {} # self.zone_by_name = {} self.zone_lock = Lock() self.zone_lock_idx = None #",
"s.temperature == temp and s._zone in (zone_idx, None) ] _LOGGER.debug( \" - matching",
"000C: find the HTG relay and DHW sensor, if any (DHW relays in",
") if not testable_zones: return # no testable zones testable_sensors = [ d",
"MultiZone, UfhSystem, System): # evohome # class Evohome(System): # evohome \"\"\"The Evohome system",
"testable_sensors = [ d for d in self._gwy.devices # not: self.devices if d._ctl",
"not None ] if discover_flag & DISCOVER_PARAMS: self._send_cmd(\"1100\", payload=\"FC\") # TPI params #",
"__init__(self, gwy, ctl, **kwargs) -> None: # _LOGGER.debug(\"Creating a System: %s (%s)\", dev_addr.id,",
"zone's sensor & valves?. \"\"\" def create_dhw(zone_idx) -> DhwZone: if self.dhw: raise LookupError(f\"Duplicate",
"cycle ] if _LOGGER.isEnabledFor(logging.DEBUG): _LOGGER.debug( \"Testable zones: %s (unique/non-null temps & sensorless)\", testable_zones,",
"authorative. The RQ is initiated by the DHW, so is not authorative. The",
"--- 07:045960 --:------ 07:045960 1260 003 000911 # 1F41: I/01: get parent controller,",
"so is not useful. \"\"\" # 10A0: RQ/07/01, RP/01/07: can get both parent",
"# self.add_device(dhw.relay) self._dhw = dhw @property def dhw_sensor(self) -> Device: return self._dhw._dhw_sensor if",
"# ...with unique (non-null) temps, and no sensor _LOGGER.debug( \" - with unique/non-null",
"description is not None ] if discover_flag & DISCOVER_PARAMS: self._send_cmd(\"1100\", payload=\"FC\") # TPI",
"f\"{self._ctl.id} (system)\" def _handle_msg(self, msg) -> bool: super()._handle_msg(msg) if \"domain_id\" in msg.payload: idx",
"# find_zone_sensors() def _get_zone(self, zone_idx, sensor=None, **kwargs) -> Zone: \"\"\"Return a zone (will",
"discover_flag & DISCOVER_STATUS: pass def _handle_msg(self, msg, prev_msg=None): \"\"\"Eavesdrop packets, or pairs of",
"-> DhwZone: \"\"\"Return a DHW zone (will create it if required). Can also",
"\"2309\", \"30C9\"): pass # if isinstance(msg.payload, list): # elif msg.code == \"000C\": #",
"= create_dhw(zone_idx) if kwargs.get(\"dhw_valve\"): zone._set_dhw_valve(kwargs[\"dhw_valve\"]) if kwargs.get(\"htg_valve\"): zone._set_dhw_valve(kwargs[\"htg_valve\"]) if sensor is not None:",
"process of exclusion as a means to determine which zone uses the controller",
"= \"FF\" self._evo = None self._heat_demand = None self._htg_control = None def __repr__(self)",
"super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_SCHEMA: [ # 0005: find any zones + their",
"self._htg_control is not None: if self._htg_control is device: return raise CorruptStateError( f\"{ATTR_HTG_CONTROL} shouldn't",
"return zone = self.dhw # TODO: self.zone_by_idx.get(\"HW\") too? if zone is None: zone",
"None ) return params @property def status(self) -> dict: \"\"\"Return the system's current",
"Hometronics(System): RQ_SUPPORTED = (\"0004\", \"000C\", \"2E04\", \"313F\") # TODO: WIP RQ_UNSUPPORTED = (\"xxxx\",)",
"algorithm... for zone_idx, temp in testable_zones.items(): # TODO: when sensors announce temp, ?also",
"-> Optional[dict]: # 0418 try: return await self._fault_log.get_fault_log(force_refresh=force_refresh) except ExpiredCallbackError: return @property def",
"cycle _LOGGER.debug(\"System state (before): %s\", self) changed_zones = { z[\"zone_idx\"]: z[\"temperature\"] for z",
"be: {dhw}\") if self._dhw is not None: if self._dhw is dhw: return raise",
"ATTR_HTG_SYSTEM: {}} assert ATTR_HTG_SYSTEM in schema # TODO: removeme assert ATTR_HTG_CONTROL not in",
"return { k: v.payload[\"relay_demand\"] for k, v in self._relay_demands.items() } @property def relay_failsafes(self)",
"if this.src is self and this.dst.type in (\"10\", \"13\"): heater = this.dst elif",
"list): pass class Chronotherm(Evohome): def __repr__(self) -> str: return f\"{self._ctl.id} (chronotherm)\" class Hometronics(System):",
"v.payload[\"heat_demand\"] for k, v in self._heat_demands.items()} @property def relay_demands(self) -> Optional[dict]: # 0008",
"wait for the RP/313F # await self.wait_for(Command(\"313F\", verb=\"RQ\")) # return self.datetime # async",
"to match temps # 045 I --- 07:045960 --:------ 07:045960 1260 003 000911",
"heating_control(self) -> Device: if self._htg_control: return self._htg_control htg_control = [d for d in",
"no testable zones testable_sensors = [ d for d in self._gwy.devices # not:",
"if self._htg_control.actuator_state: return True @property def schema(self) -> dict: \"\"\"Return the system's schema.\"\"\"",
"if this.src is self and this.dst.type == \"10\": heater = this.dst elif this.code",
"else {}} class MultiZone: # 0005 (+/- 000C?) def __init__(self, *args, **kwargs) ->",
"change: {self._htg_control} to {device}\" ) # if device.evo is not None and device.evo",
"self._heat_demand: return self._heat_demand[\"heat_demand\"] @property def is_calling_for_heat(self) -> Optional[bool]: \"\"\"Return True is the system",
"if \"domain_id\" in msg.payload: idx = msg.payload[\"domain_id\"] if msg.code == \"0008\": self._relay_demands[idx] =",
"== \"13\": heater = prev.src if heater is not None: self._set_htg_control(heater) if msg.code",
"change: {self._dhw} to {dhw}\") if self._dhw is None: # self._gwy._get_device(xxx) # self.add_device(dhw.sensor) #",
"\"tpi_params\" not in params[ATTR_HTG_SYSTEM] # TODO: removeme params[ATTR_HTG_SYSTEM][\"tpi_params\"] = ( self.heating_control._get_msg_value(\"1100\") if self.heating_control",
"is a special case self._system_mode = msg @property def system_mode(self) -> Optional[dict]: #",
"self.add_device(dhw.relay) self._dhw = dhw @property def dhw_sensor(self) -> Device: return self._dhw._dhw_sensor if self._dhw",
"k != z] + [None] } # ...with unique (non-null) temps, and no",
"I\", \"RP\"): if \"domain_id\" in msg.payload: self._relay_demands[msg.payload[\"domain_id\"]] = msg if msg.payload[\"domain_id\"] == \"F9\":",
"zone)\", [s.id for s in matching_sensors], ) if len(matching_sensors) == 1: _LOGGER.debug(\" -",
"= self._dhw = DhwZone(self) if not self._gwy.config[DISABLE_DISCOVERY]: dhw._discover() # discover_flag=DISCOVER_ALL) return dhw if",
"= this.dst if sensor is not None: if self.dhw is None: self._get_zone(\"FA\") self.dhw._set_sensor(sensor)",
"zones (from 30C9): %s\", changed_zones) if not changed_zones: return # ctl's 30C9 says",
"= Zone(self, zone_idx) if not self._gwy.config[DISABLE_DISCOVERY]: # TODO: needs tidyup (ref #67) zone._discover()",
"DHW zone system.\"\"\" if not isinstance(dhw, DhwZone): raise TypeError(f\"stored_hw can't be: {dhw}\") if",
"--:------ 13:237335 3B00 002 00C8 # 09:04:02.667 045 I --- 01:145038 --:------ 01:145038",
"self._htg_control.actuator_state: return True @property def schema(self) -> dict: \"\"\"Return the system's schema.\"\"\" schema",
"code in (\"0008\", \"3EF1\"): device._send_cmd(code, qos) if msg.code == \"3150\" and msg.verb in",
"& DISCOVER_PARAMS: self._send_cmd(\"0100\") # language def _handle_msg(self, msg, prev_msg=None): super()._handle_msg(msg) if msg.code ==",
"Optional[str]: return self._msg_payload(self._datetime, \"datetime\") # TODO: make a dt object # def wait_for(self,",
"can't be: {dhw}\") if self._dhw is not None: if self._dhw is dhw: return",
"for {self}\") zone = Zone(self, zone_idx) if not self._gwy.config[DISABLE_DISCOVERY]: # TODO: needs tidyup",
"self.zone_by_idx[z].sensor is None } # this will be true if ctl is sensor",
"--- 10:067219 01:078710 --:------ 3EF0 006 0000100000FF # noqa # 06:49:03.465 045 RQ",
"def __repr__(self) -> str: return f\"{self._ctl.id} (sys_base)\" # def __str__(self) -> str: #",
"= ctl self._domain_id = \"FF\" self._evo = None self._heat_demand = None self._htg_control =",
"None: # _LOGGER.debug(\"Creating a System: %s (%s)\", dev_addr.id, self.__class__) super().__init__(gwy, **kwargs) self.id =",
"# now see if we can allocate the controller as a sensor... if",
"18:14:14.446 065 RP --- 10:067219 01:078710 --:------ 3220 005 00C00500FF # 14:41:46.599 064",
"params[ATTR_HTG_SYSTEM][ATTR_HTG_CONTROL] = ( # self.heating_control.params if self.heating_control else None # ) assert \"tpi_params\"",
"def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self._fault_log = FaultLog(self._ctl) def _discover(self,",
"avoid complexity of z._temp # zone = self.zone_by_idx[zone_idx] # if zone._temp is None:",
"Task: \"\"\"Set a system mode for a specified duration, or indefinitely.\"\"\" cmd =",
"return self._heat_demand[\"heat_demand\"] @property def is_calling_for_heat(self) -> Optional[bool]: \"\"\"Return True is the system is",
"\"2E04\", \"313F\") # TODO: WIP RQ_UNSUPPORTED = (\"xxxx\",) # 10E0? def __repr__(self) ->",
"\"000C\": # self._msgs[f\"{msg.code}\"] = msg # elif msg.code == \"0005\" and prev_msg is",
"Evohome(SysLanguage, SysMode, MultiZone, UfhSystem, System): # evohome # class Evohome(System): # evohome \"\"\"The",
"'orphan' (e.g. from a neighbour) sensors announcing temperatures with the same value. This",
"and this.dst.type == \"10\": heater = this.dst elif this.code == \"3EF0\" and this.verb",
"state (finally): %s\", self) super()._handle_msg(msg) if msg.code in (\"000A\",) and isinstance(msg.payload, list): for",
"super()._send_cmd(code, dest, payload, **kwargs) @property def devices(self) -> List[Device]: return self._ctl.devices + [self._ctl]",
"return params @property def status(self) -> dict: \"\"\"Return the system's current state.\"\"\" status",
"# 045 I --- 07:045960 --:------ 07:045960 1260 003 000911 # 1F41: I/01:",
"Task: \"\"\"Revert system to Auto, set non-PermanentOverride zones to FollowSchedule.\"\"\" return self.set_mode(SystemMode.AUTO) def",
"return self._dhw._htg_valve if self._dhw else None @property def schema(self) -> dict: assert ATTR_DHW_SYSTEM",
"(\"08\", \"09\", \"0A\", \"0B\", \"11\") # CODE_0005_ZONE_TYPE ] [ # 0005: find any",
"removeme params[ATTR_HTG_SYSTEM][\"language\"] = self.language return params class SysMode: # 2E04 def __init__(self, *args,",
"def _handle_msg(self, msg) -> bool: def OUT_is_exchange(this, prev): # TODO:use is? return this.src",
"the CTL is considered 'authorative'. The 1FC9 RQ/RP exchange to/from a CTL is",
"prev_msg.dtm # changed temp during last cycle ] if _LOGGER.isEnabledFor(logging.DEBUG): _LOGGER.debug( \"Testable zones:",
") if len(matching_sensors) == 1: _LOGGER.debug(\" - matched sensor: %s\", matching_sensors[0].id) zone =",
"ATTR_ZONES: {z.idx: z.status for z in self._zones}} class UfhSystem: @property def schema(self) ->",
"msg) -> bool: def OUT_is_exchange(this, prev): # TODO:use is? return this.src is prev.dst",
"in testable_zones.items(): # TODO: when sensors announce temp, ?also includes it's parent zone",
"06:49:03.465 045 RQ --- 01:145038 13:237335 --:------ 3EF0 001 00 # 06:49:05.467 045",
"# TODO: to sort out @property def heating_control(self) -> Device: if self._htg_control: return",
"# language def _handle_msg(self, msg, prev_msg=None): super()._handle_msg(msg) if msg.code == \"0100\" and msg.verb",
"= { z: t for z, t in changed_zones.items() if self.zone_by_idx[z].sensor is None",
"super()._handle_msg(msg) if msg.code == \"0008\" and msg.verb in (\" I\", \"RP\"): if \"domain_id\"",
"01:145038 13:237335 --:------ 3EF0 001 00 # 06:49:05.467 045 RQ --- 01:145038 13:237335",
"# 045 I --- 01:145038 --:------ 01:145038 1F41 006 000002FFFFFF sensor = None",
"not: self.devices if d._ctl in (self, None) and d.addr.type in DEVICE_HAS_ZONE_SENSOR and d.temperature",
"I --- 01:145038 --:------ 01:145038 1F41 012 000004FFFFFF1E060E0507E4 # 045 I --- 01:145038",
"self._send_cmd(\"0009\", payload=f\"{domain_id:02X}00\") if discover_flag & DISCOVER_STATUS: # for domain_id in range(0xF8, 0x100): #",
"if secs is None or msg.dtm > prev_msg.dtm + td(seconds=secs): return # only",
"self.heating_control else None # ) assert \"tpi_params\" not in params[ATTR_HTG_SYSTEM] # TODO: removeme",
"_LOGGER.debug(\" - matched sensor: %s (by exclusion)\", self._ctl.id) zone = self.zone_by_idx[zone_idx] zone._set_sensor(self) zone.sensor._set_ctl(self)",
"def heat_demands(self) -> Optional[dict]: # 3150 if self._heat_demands: return {k: v.payload[\"heat_demand\"] for k,",
"zone = self.zone_by_idx[zone_dict.pop(\"zone_idx\")] # if msg.code == \"000A\": # zone._zone_config = zone_dict #",
"super().__init__(*args, **kwargs) self._system_mode = None def _discover(self, discover_flag=DISCOVER_ALL) -> None: super()._discover(discover_flag=discover_flag) if discover_flag",
"01:078710 10:067219 --:------ 3EF0 001 00 # 14:41:46.631 063 RP --- 10:067219 01:078710",
"not to/from a controller, so is not useful. \"\"\" # 10A0: RQ/07/01, RP/01/07:",
"True @property def schema(self) -> dict: \"\"\"Return the system's schema.\"\"\" schema = {ATTR_CONTROLLER:",
"some controllers are evohome-compatible.\"\"\" def __init__(self, gwy, ctl, **kwargs) -> None: super().__init__(gwy, ctl,",
"None and t not in [v for k, v in changed_zones.items() if k",
"-> None: super().__init__(*args, **kwargs) self._language = None def _discover(self, discover_flag=DISCOVER_ALL) -> None: super()._discover(discover_flag=discover_flag)",
"if self._relay_failsafes: return {} # failsafe_enabled @property def status(self) -> dict: \"\"\"Return the",
"] [ # 0005: find any others - as per an RFG100 self._send_cmd(\"0005\",",
"zone.devices]: zone.devices.append(device) zone.device_by_id[device.id] = device if sensor is not None: zone._set_sensor(sensor) return zone",
"13:237335 --:------ 13:237335 3B00 002 00C8 # 09:04:02.667 045 I --- 01:145038 --:------",
"01:078710 --:------ 3220 005 00C00500FF # 14:41:46.599 064 RQ --- 01:078710 10:067219 --:------",
"isinstance(msg.payload, list): # super()._handle_msg(msg) # [xxx(z) for z in msg.payload] # else: #",
"from .devices import Device, Entity from .exceptions import CorruptStateError, ExpiredCallbackError from .schema import",
"or device.type not in (\"10\", \"13\"): raise TypeError(f\"{ATTR_HTG_CONTROL} can't be: {device}\") if self._htg_control",
"self._gwy._tasks.append(self._loop.create_task(self.get_fault_log())) async def get_fault_log(self, force_refresh=None) -> Optional[dict]: # 0418 try: return await self._fault_log.get_fault_log(force_refresh=force_refresh)",
"dtm: dt) -> str: # wait for the I/313F # await self.wait_for(Command(\"313F\", verb=\"",
"implmenting for device in [d for d in kwargs[\"actuators\"] if d not in",
"__init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self._language = None def _discover(self, discover_flag=DISCOVER_ALL)",
"to Auto, set non-PermanentOverride zones to FollowSchedule.\"\"\" return self.set_mode(SystemMode.AUTO) def reset_mode(self) -> Task:",
"{ATTR_HTG_SYSTEM: {}} assert ATTR_HTG_SYSTEM in params # TODO: removeme # devices don't have",
"z in self.zones if z.sensor is None]) == 0: return # (currently) no",
"-> Optional[float]: # 3150/FC if self._heat_demand: return self._heat_demand[\"heat_demand\"] @property def is_calling_for_heat(self) -> Optional[bool]:",
"return schema @property def params(self) -> dict: \"\"\"Return the system's configuration.\"\"\" params =",
"if d.type == \"02\" }, } @property def status(self) -> dict: assert ATTR_UFH_SYSTEM",
"# TODO: removeme return {**super().params, ATTR_ZONES: {z.idx: z.params for z in self._zones}} @property",
"testable_zones, ) _LOGGER.debug( \"Testable sensors: %s (non-null temps & orphans or zoneless)\", {d.id:",
"None: return if len([z for z in self.zones if z.sensor is None]) ==",
"(after): %s\", self) # now see if we can allocate the controller as",
"k: v.payload[\"relay_demand\"] for k, v in self._relay_demands.items() } @property def relay_failsafes(self) -> Optional[dict]:",
"return self.set_mode(SystemMode.RESET) @property def params(self) -> dict: params = super().params assert ATTR_HTG_SYSTEM in",
"(excl. controller)\", [s.id for s in matching_sensors], ) # can safely(?) assume this",
"self.zones if z.sensor is None]) != 1: return # no single zone without",
"assert ATTR_ORPHANS not in schema[ATTR_HTG_SYSTEM] # TODO: removeme schema[ATTR_ORPHANS] = sorted( [d.id for",
"self.dhw is None: self._get_zone(\"FA\") self.dhw._set_sensor(sensor) super()._handle_msg(msg) if msg.code in (\"10A0\", \"1260\"): # self.dhw.sensor",
"# self._send_cmd(\"313F\", verb=\"RQ\", callback=callback) # time_start = dt.now() # while not self._schedule_done: #",
"a 07:* (1x/4h) - reliable 2. Use sensor temp matching - non-deterministic Data",
"duration, or indefinitely.\"\"\" cmd = Command.set_system_mode(self.id, system_mode=system_mode, until=until) return self._gwy.send_cmd(cmd) def set_auto(self) ->",
"def is_calling_for_heat(self) -> Optional[bool]: \"\"\"Return True is the system is currently calling for",
"return status class SysLanguage: # 0100 def __init__(self, *args, **kwargs) -> None: super().__init__(*args,",
"-> str: return f\"{self._ctl.id} (hometronics)\" def _discover(self, discover_flag=DISCOVER_ALL) -> None: # super()._discover(discover_flag=discover_flag) #",
"# for dev_type, description in CODE_000C_DEVICE_TYPE.items() fix payload # if description is not",
"(zone_idx, None) ] _LOGGER.debug(\"Testing zone %s, temp: %s\", zone_idx, temp) _LOGGER.debug( \" -",
"\"30C9\"): pass # if isinstance(msg.payload, list): # elif msg.code == \"000C\": # self._msgs[f\"{msg.code}\"]",
"if this.code == \"10A0\" and this.verb == \"RP\": if this.src is self and",
"dev_type, description in CODE_000C_DEVICE_TYPE.items() fix payload # if description is not None ]",
"DISCOVER_STATUS, SystemMode, SystemType, __dev_mode__, ) from .devices import Device, Entity from .exceptions import",
"= self.language return params class SysMode: # 2E04 def __init__(self, *args, **kwargs) ->",
", SysFaultLog \"\"\"The Controller class.\"\"\" def __init__(self, gwy, ctl, **kwargs) -> None: super().__init__(gwy,",
"\"\"\"Return the system's schema.\"\"\" schema = {ATTR_CONTROLLER: self._ctl.id, ATTR_HTG_SYSTEM: {}} assert ATTR_HTG_SYSTEM in",
"return { **super().status, ATTR_UFH_SYSTEM: { d.id: d.status for d in sorted(self._ctl.devices) if d.type",
"@property def status(self) -> dict: \"\"\"Return the system's current state.\"\"\" status = {ATTR_HTG_SYSTEM:",
"# TODO: when sensors announce temp, ?also includes it's parent zone matching_sensors =",
"len(matching_sensors) == 0: _LOGGER.debug(\" - matched sensor: %s (by exclusion)\", self._ctl.id) zone =",
"# def xxx(zone_dict): # zone = self.zone_by_idx[zone_dict.pop(\"zone_idx\")] # if msg.code == \"000A\": #",
"\"2309\", \"30C9\") and isinstance(msg.payload, list): pass class Chronotherm(Evohome): def __repr__(self) -> str: return",
"cmd = Command.set_system_mode(self.id, system_mode=system_mode, until=until) return self._gwy.send_cmd(cmd) def set_auto(self) -> Task: \"\"\"Revert system",
"tidyup (ref #67) zone._discover() # discover_flag=DISCOVER_ALL) return zone if zone_idx == \"HW\": return",
"__repr__(self) -> str: return f\"{self._ctl.id} (evohome)\" def _discover(self, discover_flag=DISCOVER_ALL) -> None: super()._discover(discover_flag=discover_flag) if",
"= msg @property def datetime(self) -> Optional[str]: return self._msg_payload(self._datetime, \"datetime\") # TODO: make",
"= [] self.zone_by_idx = {} # self.zone_by_name = {} self.zone_lock = Lock() self.zone_lock_idx",
"discover_flag=DISCOVER_ALL) -> None: super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_STATUS: # self._send_cmd(\"2E04\", payload=\"FF\") # system",
"zones testable_sensors = [ d for d in self._gwy.devices # not: self.devices if",
"status[ATTR_HTG_SYSTEM][\"datetime\"] = self.datetime return status class SysLanguage: # 0100 def __init__(self, *args, **kwargs)",
"_LOGGER.isEnabledFor(logging.DEBUG): _LOGGER.debug( \"Testable zones: %s (unique/non-null temps & sensorless)\", testable_zones, ) _LOGGER.debug( \"Testable",
"== \"10\": heater = this.dst elif this.code == \"3EF0\" and this.verb == \"RQ\":",
"msg @property def system_mode(self) -> Optional[dict]: # 2E04 return self._msg_payload(self._system_mode) def set_mode(self, system_mode=None,",
"(30C9 array), but the sensor for each zone is not. In particular, the",
"ATTR_UFH_SYSTEM not in super().schema # TODO: removeme return { **super().schema, ATTR_UFH_SYSTEM: { d.id:",
"0100 def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self._language = None def",
"Programmer(Evohome): def __repr__(self) -> str: return f\"{self._ctl.id} (programmer)\" class Sundial(Evohome): def __repr__(self) ->",
"-> dict: params = super().params assert ATTR_HTG_SYSTEM in params # TODO: removeme assert",
"ways to find a controller's heat relay (in order of reliability): 1. The",
"not in super().schema # TODO: removeme return { **super().schema, ATTR_UFH_SYSTEM: { d.id: d.schema",
"\"\"\" # 18:14:14.025 066 RQ --- 01:078710 10:067219 --:------ 3220 005 0000050000 #",
"if self._dhw else None @property def hotwater_valve(self) -> Device: return self._dhw._dhw_valve if self._dhw",
"system is currently calling for heat.\"\"\" if not self._htg_control: return if self._htg_control.actuator_state: return",
"TODO: removeme params[ATTR_HTG_SYSTEM][\"tpi_params\"] = ( self.heating_control._get_msg_value(\"1100\") if self.heating_control else None ) return params",
"super().schema # TODO: removeme return {**super().schema, ATTR_DHW_SYSTEM: self.dhw.schema if self.dhw else {}} @property",
"CTL is considered more authorative. The RQ is initiated by the DHW, so",
"000C?) def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self.zones = [] self.zone_by_idx",
"schema[ATTR_ORPHANS] = sorted( [d.id for d in self._ctl.devices if not d._domain_id and d.type",
"assert \"system_mode\" not in params[ATTR_HTG_SYSTEM] # TODO: removeme params[ATTR_HTG_SYSTEM][\"system_mode\"] = self.system_mode return params",
"last cycle _LOGGER.debug(\"System state (before): %s\", self) changed_zones = { z[\"zone_idx\"]: z[\"temperature\"] for",
"list): # msg.is_array: # find_zone_sensors() def _get_zone(self, zone_idx, sensor=None, **kwargs) -> Zone: \"\"\"Return",
"def set_mode(self, system_mode=None, until=None) -> Task: \"\"\"Set a system mode for a specified",
"ATTR_HTG_CONTROL, ATTR_HTG_SYSTEM, ATTR_ORPHANS, ATTR_UFH_SYSTEM, ATTR_ZONES, DISABLE_DISCOVERY, MAX_ZONES, ) from .zones import DhwZone, Zone",
"= self.relay_failsafes return status class Evohome(SysLanguage, SysMode, MultiZone, UfhSystem, System): # evohome #",
"discover_flag=DISCOVER_ALL) return dhw if zone_idx != \"HW\": return zone = self.dhw # TODO:",
"controller)\", [s.id for s in matching_sensors], ) # can safely(?) assume this zone",
"# schema[\"devices\"] = {d.id: d.device_info for d in sorted(self._ctl.devices)} return schema @property def",
"in status # TODO: removeme status[\"fault_log\"] = self._fault_log.fault_log status[\"last_fault\"] = self._msgz[\" I\"].get(\"0418\") return",
"# if description is not None ] if discover_flag & DISCOVER_PARAMS: self._send_cmd(\"1100\", payload=\"FC\")",
"elif msg.code == \"3150\": self._heat_demands[idx] = msg elif msg.code not in (\"0001\", \"000C\",",
"self._dhw is None: # self._gwy._get_device(xxx) # self.add_device(dhw.sensor) # self.add_device(dhw.relay) self._dhw = dhw @property",
"MAX_SETPOINT = 85.0 DEFAULT_SETPOINT = 50.0 def __init__(self, *args, **kwargs) -> None: super().__init__(*args,",
"logging from asyncio import Task from datetime import timedelta as td from threading",
"# 0005: find any others - as per an RFG100 self._send_cmd(\"0005\", payload=f\"00{zone_type}\") for",
"\"domain_id\" in msg.payload and msg.payload[\"domain_id\"] == \"FC\": self._heat_demand = msg.payload # if msg.code",
"== \"0005\" and prev_msg is not None: # zone_added = bool(prev_msg.code == \"0004\")",
"# self.zone_by_name = {} self.zone_lock = Lock() self.zone_lock_idx = None # self._prev_30c9 =",
"@property def heat_demands(self) -> Optional[dict]: # 3150 if self._heat_demands: return {k: v.payload[\"heat_demand\"] for",
"# if msg.code in (\"000A\", \"2309\", \"30C9\"): # if isinstance(msg.payload, list): # super()._handle_msg(msg)",
"TPI params # # for code in (\"3B00\",): # 3EF0, 3EF1 # #",
"(\"xxxx\",) # 10E0? def __repr__(self) -> str: return f\"{self._ctl.id} (hometronics)\" def _discover(self, discover_flag=DISCOVER_ALL)",
"and this.verb == \" I\" and prev is not None: if prev.code ==",
"find_htg_relay(msg, prev=prev_msg) def _send_cmd(self, code, **kwargs) -> None: dest = kwargs.pop(\"dest_addr\", self._ctl.id) payload",
"kwargs.pop(\"payload\", \"00\") super()._send_cmd(code, dest, payload, **kwargs) @property def devices(self) -> List[Device]: return self._ctl.devices",
"DhwZone) -> None: # self._dhw \"\"\"Set the DHW zone system.\"\"\" if not isinstance(dhw,",
"def params(self) -> dict: assert ATTR_DHW_SYSTEM not in super().params # TODO: removeme return",
"sorted(self._ctl.devices) if d.type == \"02\" }, } class SystemBase(Entity): # 3B00 (multi-relay) \"\"\"The",
"& DISCOVER_SCHEMA: [ # 000C: find the HTG relay and DHW sensor, if",
"this.verb == \"RQ\": if this.src is self and this.dst.type == \"10\": heater =",
"I --- 01:145038 --:------ 01:145038 1F41 006 000002FFFFFF sensor = None if this.code",
"the system state.\"\"\" def OUT_find_dhw_sensor(this): \"\"\"Discover the stored HW this system (if any).",
"return params class StoredHw: MIN_SETPOINT = 30.0 # NOTE: these may be removed",
"logging.getLogger(__name__) if DEV_MODE: _LOGGER.setLevel(logging.DEBUG) class SysFaultLog: # 0418 def __init__(self, *args, **kwargs) ->",
"066 RQ --- 01:078710 10:067219 --:------ 3220 005 0000050000 # 18:14:14.446 065 RP",
"status # TODO: removeme status[ATTR_HTG_SYSTEM][\"heat_demands\"] = self.heat_demands status[ATTR_HTG_SYSTEM][\"relay_demands\"] = self.relay_demands status[ATTR_HTG_SYSTEM][\"relay_failsafes\"] = self.relay_failsafes",
"-> None: super().__init__(*args, **kwargs) self._system_mode = None def _discover(self, discover_flag=DISCOVER_ALL) -> None: super()._discover(discover_flag=discover_flag)",
"for 10: def _set_htg_control(self, device: Device) -> None: # self._htg_control \"\"\"Set the heating",
"temperature matching_sensors = [ s for s in testable_sensors if s.temperature == temp",
"0005 (+/- 000C?) def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self.zones =",
"# zone._temp = zone_dict # elif msg.code == \"30C9\": # zone._temp = zone_dict",
"a sensor. \"\"\" prev_msg, self._prev_30c9 = self._prev_30c9, msg if prev_msg is None: return",
"if self.dhw else {}} @property def params(self) -> dict: assert ATTR_DHW_SYSTEM not in",
"not testable_zones: return # no testable zones zone_idx, temp = list(testable_zones.items())[0] _LOGGER.debug(\"Testing (sole",
"exchange between a CTL & a 13: (TPI cycle rate, usu. 6x/hr) Data",
"which parent controller - need to match temps # 045 I --- 07:045960",
"or msg.dtm > prev_msg.dtm + td(seconds=secs): return # only compare against 30C9 (array)",
"# TODO: removeme schema[ATTR_HTG_SYSTEM][ATTR_HTG_CONTROL] = ( self.heating_control.id if self.heating_control else None ) assert",
"return self._gwy.send_cmd(cmd) def set_auto(self) -> Task: \"\"\"Revert system to Auto, set non-PermanentOverride zones",
"TODO: removeme # status[ATTR_HTG_SYSTEM][ATTR_HTG_CONTROL] = ( # self.heating_control.status if self.heating_control else None #",
"z: t for z, t in changed_zones.items() if self.zone_by_idx[z].sensor is None } #",
"is reliably known (30C9 array), but the sensor for each zone is not.",
"z] + [None] } # ...with unique (non-null) temps, and no sensor _LOGGER.debug(",
"before implmenting for device in [d for d in kwargs[\"actuators\"] if d not",
"Can also set a DHW zone's sensor & valves?. \"\"\" def create_dhw(zone_idx) ->",
"language(self) -> Optional[str]: # 0100 return self._msg_payload(self._language, \"language\") @property def params(self) -> dict:",
"the system's current state.\"\"\" status = super().status assert ATTR_HTG_SYSTEM in status # TODO:",
"3220 RQ/RP *to/from a 10:* (1x/5min) 2a. The 3EF0 RQ/RP *to/from a 10:*",
"01:078710 10:067219 --:------ 3220 005 0000050000 # 18:14:14.446 065 RP --- 10:067219 01:078710",
"0008 if self._relay_demands: return { k: v.payload[\"relay_demand\"] for k, v in self._relay_demands.items() }",
"SysMode, MultiZone, UfhSystem, System): # evohome # class Evohome(System): # evohome \"\"\"The Evohome",
"# NOTE: these may be removed MAX_SETPOINT = 85.0 DEFAULT_SETPOINT = 50.0 def",
"changed temp during last cycle ] if _LOGGER.isEnabledFor(logging.DEBUG): _LOGGER.debug( \"Testable zones: %s (unique/non-null",
"-> dict: assert ATTR_UFH_SYSTEM not in super().schema # TODO: removeme return { **super().schema,",
"Chronotherm(Evohome): def __repr__(self) -> str: return f\"{self._ctl.id} (chronotherm)\" class Hometronics(System): RQ_SUPPORTED = (\"0004\",",
"def create_zone(zone_idx) -> Zone: if int(zone_idx, 16) >= self._gwy.config[MAX_ZONES]: raise ValueError(f\"Invalid zone idx:",
"may be 'orphan' (e.g. from a neighbour) sensors announcing temperatures with the same",
"# assert \"devices\" not in schema # TODO: removeme # schema[\"devices\"] = {d.id:",
"verb=\"RQ\", callback=callback) # time_start = dt.now() # while not self._schedule_done: # await asyncio.sleep(TIMER_SHORT_SLEEP)",
"W self._datetime = msg @property def datetime(self) -> Optional[str]: return self._msg_payload(self._datetime, \"datetime\") #",
"# (currently) no zone without a sensor # if self._gwy.serial_port: # only if",
"d.params for d in sorted(self._ctl.devices) if d.type == \"02\" }, } @property def",
"if msg.code in (\"000A\", \"2309\", \"30C9\"): # if isinstance(msg.payload, list): # super()._handle_msg(msg) #",
"relay_demands(self) -> Optional[dict]: # 0008 if self._relay_demands: return { k: v.payload[\"relay_demand\"] for k,",
"not None: zone._set_sensor(sensor) return zone @property def _zones(self) -> dict: return sorted(self.zones, key=lambda",
"any). There is only 2 ways to to find a controller's DHW sensor:",
"f\"{self._ctl.id} (evohome)\" def _discover(self, discover_flag=DISCOVER_ALL) -> None: super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_STATUS: self._send_cmd(\"1F09\")",
"testable_zones, ) if not testable_zones: return # no testable zones testable_sensors = [",
"not in params[ATTR_HTG_SYSTEM] # TODO: removeme params[ATTR_HTG_SYSTEM][\"language\"] = self.language return params class SysMode:",
"removeme return {**super().params, ATTR_ZONES: {z.idx: z.params for z in self._zones}} @property def status(self)",
"not in status # TODO: removeme status[\"fault_log\"] = self._fault_log.fault_log status[\"last_fault\"] = self._msgz[\" I\"].get(\"0418\")",
"device.evo is not self: # raise LookupError if self._htg_control is None: self._htg_control =",
"= {} self._relay_demands = {} self._relay_failsafes = {} def __repr__(self) -> str: return",
"msg.code in (\"10A0\", \"1260\"): # self.dhw.sensor is None and # if self.dhw.sensor is",
"_LOGGER.debug( \" - with unique/non-null temps (from 30C9), no sensor (from state): %s\",",
"ATTR_UFH_SYSTEM not in super().params # TODO: removeme return { **super().params, ATTR_UFH_SYSTEM: { d.id:",
"0418 def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self._fault_log = FaultLog(self._ctl) def",
"in self.zones: # zone._discover(discover_flags=DISCOVER_PARAMS) if msg.code in (\"000A\", \"2309\", \"30C9\"): pass # if",
"_LOGGER = logging.getLogger(__name__) if DEV_MODE: _LOGGER.setLevel(logging.DEBUG) class SysFaultLog: # 0418 def __init__(self, *args,",
"prev is not None: if prev.code == this.code and prev.verb == this.verb: if",
"{\"priority\": Priority.LOW, \"retries\": 2} for code in (\"0008\", \"3EF1\"): device._send_cmd(code, qos) if msg.code",
"zone_idx, temp) # want to avoid complexity of z._temp # zone = self.zone_by_idx[zone_idx]",
"self self._ctl = ctl self._domain_id = \"FF\" self._evo = None self._heat_demand = None",
"\"0A\", \"0B\", \"11\") # CODE_0005_ZONE_TYPE ] [ # 0005: find any others -",
"schema[ATTR_HTG_SYSTEM] # TODO: removeme schema[ATTR_HTG_SYSTEM][ATTR_HTG_CONTROL] = ( self.heating_control.id if self.heating_control else None )",
"# no testable zones zone_idx, temp = list(testable_zones.items())[0] _LOGGER.debug(\"Testing (sole remaining) zone %s,",
"3220 005 00C00500FF # 14:41:46.599 064 RQ --- 01:078710 10:067219 --:------ 3EF0 001",
"be a sensor for a zone, but unfortunately it does not announce its",
"if msg.code in (\"000A\",) and isinstance(msg.payload, list): for zone_idx in self.zone_by_idx: cmd =",
"a System: %s (%s)\", dev_addr.id, self.__class__) super().__init__(gwy, **kwargs) self.id = ctl.id gwy.systems.append(self) gwy.system_by_id[self.id]",
"# raise LookupError if self._htg_control is None: self._htg_control = device device._set_parent(self, domain=\"FC\") @property",
"# 0100 return self._msg_payload(self._language, \"language\") @property def params(self) -> dict: params = super().params",
"(\"000A\", \"2309\", \"30C9\") and isinstance(msg.payload, list): pass class Chronotherm(Evohome): def __repr__(self) -> str:",
"controller, but not DHW sensor # 045 I --- 01:145038 --:------ 01:145038 1F41",
"if msg.code == \"0008\" and msg.verb in (\" I\", \"RP\"): if \"domain_id\" in",
"DHW zone (will create it if required). Can also set a DHW zone's",
"\"F8\", \"F9\", \"FA\", \"FB\", \"FC\", \"FF\"): # # self._send_cmd(code, payload=payload) # # TODO:",
"typing import List, Optional from .command import Command, FaultLog, Priority from .const import",
"language def _handle_msg(self, msg, prev_msg=None): super()._handle_msg(msg) if msg.code == \"0100\" and msg.verb in",
"# 1260: I/07: can't get which parent controller - need to match temps",
"= bool(prev_msg.code == \"0004\") # else zone_deleted # elif msg.code == \"30C9\" and",
"is not useful. \"\"\" # 10A0: RQ/07/01, RP/01/07: can get both parent controller",
"announce its sensor temperatures. In addition, there may be 'orphan' (e.g. from a",
"super().status # TODO: removeme return {**super().status, ATTR_DHW_SYSTEM: self.dhw.status if self.dhw else {}} class",
"== this.code and prev.verb == this.verb: if this.src is self and prev.src.type ==",
"10:067219 --:------ 3220 005 0000050000 # 18:14:14.446 065 RP --- 10:067219 01:078710 --:------",
"if self._htg_control: return self._htg_control htg_control = [d for d in self._ctl.devices if d._domain_id",
"d._domain_id and d.type != \"02\"] ) # devices without a parent zone, NB:",
"create it if required). Can also set a DHW zone's sensor & valves?.",
"to maintain the system state.\"\"\" def OUT_find_dhw_sensor(this): \"\"\"Discover the stored HW this system",
"__init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self.zones = [] self.zone_by_idx = {}",
"rare to be useful. \"\"\" # 18:14:14.025 066 RQ --- 01:078710 10:067219 --:------",
"devices don't have params # assert ATTR_HTG_CONTROL not in params[ATTR_HTG_SYSTEM] # TODO: removeme",
"{**super().status, ATTR_DHW_SYSTEM: self.dhw.status if self.dhw else {}} class MultiZone: # 0005 (+/- 000C?)",
"def _zones(self) -> dict: return sorted(self.zones, key=lambda x: x.idx) @property def schema(self) ->",
"def reset_mode(self) -> Task: \"\"\"Revert system to Auto, force *all* zones to FollowSchedule.\"\"\"",
"\"3220\" and this.verb == \"RQ\": if this.src is self and this.dst.type == \"10\":",
"z.sensor is None]) == 0: return # (currently) no zone without a sensor",
"be true if ctl is sensor if not testable_zones: return # no testable",
"00C00500FF # 14:41:46.599 064 RQ --- 01:078710 10:067219 --:------ 3EF0 001 00 #",
"%s, temp: %s\", zone_idx, temp) # want to avoid complexity of z._temp #",
"\"system_mode\" not in params[ATTR_HTG_SYSTEM] # TODO: removeme params[ATTR_HTG_SYSTEM][\"system_mode\"] = self.system_mode return params class",
"ATTR_ZONES: {z.idx: z.schema for z in self._zones}} @property def params(self) -> dict: assert",
"FollowSchedule.\"\"\" return self.set_mode(SystemMode.RESET) @property def params(self) -> dict: params = super().params assert ATTR_HTG_SYSTEM",
"removeme return {**super().schema, ATTR_DHW_SYSTEM: self.dhw.schema if self.dhw else {}} @property def params(self) ->",
"if we can allocate the controller as a sensor... if self._zone is not",
"RP --- 01:102458 07:030741 --:------ 10A0 006 0018380003E8 # 1260: I/07: can't get",
"is not None: # TODO: FIXME qos = {\"priority\": Priority.LOW, \"retries\": 2} for",
"exclusion as a means to determine which zone uses the controller as a",
"\"\"\" def create_zone(zone_idx) -> Zone: if int(zone_idx, 16) >= self._gwy.config[MAX_ZONES]: raise ValueError(f\"Invalid zone",
"# 14:41:46.599 064 RQ --- 01:078710 10:067219 --:------ 3EF0 001 00 # 14:41:46.631",
"== \"FA\": device = self.dhw.hotwater_valve if self.dhw else None elif msg.payload[\"domain_id\"] == \"FC\":",
"status = {ATTR_HTG_SYSTEM: {}} assert ATTR_HTG_SYSTEM in status # TODO: removeme # assert",
"state.\"\"\" status = super().status assert ATTR_HTG_SYSTEM in status # TODO: removeme status[ATTR_HTG_SYSTEM][\"heat_demands\"] =",
"params = super().params assert ATTR_HTG_SYSTEM in params # TODO: removeme assert \"language\" not",
"this.dst.type == \"07\": sensor = this.dst if sensor is not None: if self.dhw",
"# 3B00 (multi-relay) \"\"\"The most basic controllers - a generic controller (e.g. ST9420C).\"\"\"",
"def __repr__(self) -> str: return f\"{self._ctl.id} (hometronics)\" def _discover(self, discover_flag=DISCOVER_ALL) -> None: #",
"def status(self) -> dict: \"\"\"Return the system's current state.\"\"\" status = {ATTR_HTG_SYSTEM: {}}",
"13:237335 --:------ 3EF0 001 00 # 09:03:59.693 051 I --- 13:237335 --:------ 13:237335",
"Data from the CTL is considered more authorative. The RQ is initiated by",
"None def _discover(self, discover_flag=DISCOVER_ALL) -> None: super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_STATUS: self._gwy.send_cmd(Command.get_system_time(self.id)) #",
"FollowSchedule.\"\"\" return self.set_mode(SystemMode.AUTO) def reset_mode(self) -> Task: \"\"\"Revert system to Auto, force *all*",
"list): for zone_idx in self.zone_by_idx: cmd = Command.get_zone_mode(self.id, zone_idx, priority=Priority.LOW) self._gwy.send_cmd(cmd) # for",
"return self._get_msg_value(\"1100\") @property def heat_demand(self) -> Optional[float]: # 3150/FC if self._heat_demand: return self._heat_demand[\"heat_demand\"]",
"is not to/from a controller, so is not useful. \"\"\" # 10A0: RQ/07/01,",
"any zones + their type (RAD, UFH, VAL, MIX, ELE) self._send_cmd(\"0005\", payload=f\"00{zone_type}\") for",
"== \"RP\": if this.src is self and this.dst.type == \"07\": sensor = this.dst",
"# self._gwy._get_device(xxx) # self.add_device(dhw.sensor) # self.add_device(dhw.relay) self._dhw = dhw @property def dhw_sensor(self) ->",
"Device: return self._dhw._dhw_sensor if self._dhw else None @property def hotwater_valve(self) -> Device: return",
"NOTE: these may be removed MAX_SETPOINT = 85.0 DEFAULT_SETPOINT = 50.0 def __init__(self,",
"determine which zone uses the controller as a sensor. \"\"\" prev_msg, self._prev_30c9 =",
"\"000A\": # zone._zone_config = zone_dict # elif msg.code == \"2309\": # zone._temp =",
"# 06:49:03.465 045 RQ --- 01:145038 13:237335 --:------ 3EF0 001 00 # 06:49:05.467",
"# assert ATTR_HTG_CONTROL not in params[ATTR_HTG_SYSTEM] # TODO: removeme # params[ATTR_HTG_SYSTEM][ATTR_HTG_CONTROL] = (",
"status(self) -> dict: \"\"\"Return the system's current state.\"\"\" status = {ATTR_HTG_SYSTEM: {}} assert",
"{}} assert ATTR_HTG_SYSTEM in params # TODO: removeme # devices don't have params",
"else None ) assert ATTR_ORPHANS not in schema[ATTR_HTG_SYSTEM] # TODO: removeme schema[ATTR_ORPHANS] =",
"TODO: removeme schema[ATTR_ORPHANS] = sorted( [d.id for d in self._ctl.devices if not d._domain_id",
"@property def status(self) -> dict: assert ATTR_UFH_SYSTEM not in super().status # TODO: removeme",
"1260: I/07: can't get which parent controller - need to match temps #",
"-> None: super().__init__(*args, **kwargs) self._dhw = None def _discover(self, discover_flag=DISCOVER_ALL) -> None: super()._discover(discover_flag=discover_flag)",
"temps & sensorless)\", testable_zones, ) _LOGGER.debug( \"Testable sensors: %s (non-null temps & orphans",
"\"\"\"The Evohome system - some controllers are evohome-compatible.\"\"\" def __init__(self, gwy, ctl, **kwargs)",
"def _handle_msg(self, msg, prev_msg=None): super()._handle_msg(msg) if msg.code == \"313F\" and msg.verb in (\"",
"return f\"{self._ctl.id} (hometronics)\" def _discover(self, discover_flag=DISCOVER_ALL) -> None: # super()._discover(discover_flag=discover_flag) # will RP",
"DISCOVER_STATUS: self._gwy.send_cmd(Command.get_system_time(self.id)) # self._send_cmd(\"313F\") def _handle_msg(self, msg, prev_msg=None): super()._handle_msg(msg) if msg.code == \"313F\"",
"{ATTR_HTG_SYSTEM: {}} assert ATTR_HTG_SYSTEM in status # TODO: removeme # assert ATTR_HTG_CONTROL not",
"zone_idx, sensor=None, **kwargs) -> DhwZone: \"\"\"Return a DHW zone (will create it if",
"The RQ is initiated by the DHW, so is not authorative. The I/1260",
"There's' 3 ways to find a controller's heat relay (in order of reliability):",
"DISCOVER_STATUS: self._gwy._tasks.append(self._loop.create_task(self.get_fault_log())) async def get_fault_log(self, force_refresh=None) -> Optional[dict]: # 0418 try: return await",
"\"\"\"Set the heating control relay for this system (10: or 13:).\"\"\" if not",
"( # self.heating_control.status if self.heating_control else None # ) status[ATTR_HTG_SYSTEM][\"heat_demand\"] = self.heat_demand status[ATTR_DEVICES]",
"status = super().status assert ATTR_HTG_SYSTEM in status # TODO: removeme assert \"datetime\" not",
"list(testable_zones.items())[0] _LOGGER.debug(\"Testing (sole remaining) zone %s, temp: %s\", zone_idx, temp) # want to",
"if msg.code == \"3150\" and msg.verb in (\" I\", \"RP\"): if \"domain_id\" in",
"= self._prev_30c9, msg if prev_msg is None: return if len([z for z in",
"return if self._htg_control.actuator_state: return True @property def schema(self) -> dict: \"\"\"Return the system's",
"class SysDatetime: # 313F def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self._datetime",
"In addition, there may be 'orphan' (e.g. from a neighbour) sensors announcing temperatures",
"# note the order: most to least reliable heater = None if this.code",
"str: return f\"{self._ctl.id} (chronotherm)\" class Hometronics(System): RQ_SUPPORTED = (\"0004\", \"000C\", \"2E04\", \"313F\") #",
"RQ --- 01:145038 13:237335 --:------ 3EF0 001 00 # 06:49:05.467 045 RQ ---",
"s for s in testable_sensors if s.temperature == temp and s._zone in (zone_idx,",
"is too rare to be useful. \"\"\" # 18:14:14.025 066 RQ --- 01:078710",
"configuration.\"\"\" params = {ATTR_HTG_SYSTEM: {}} assert ATTR_HTG_SYSTEM in params # TODO: removeme #",
"-> dict: return sorted(self.zones, key=lambda x: x.idx) @property def schema(self) -> dict: assert",
"payload=f\"00{dtm_to_hex(dtm)}\")) # return self.datetime @property def status(self) -> dict: status = super().status assert",
"\"RP\"): if \"domain_id\" in msg.payload and msg.payload[\"domain_id\"] == \"FC\": self._heat_demand = msg.payload #",
"# async def get_datetime(self) -> str: # wait for the RP/313F # await",
"return raise CorruptStateError(\"DHW shouldn't change: {self._dhw} to {dhw}\") if self._dhw is None: #",
"msg.is_array: # find_zone_sensors() def _get_zone(self, zone_idx, sensor=None, **kwargs) -> Zone: \"\"\"Return a zone",
"changed_zones.items() if self.zone_by_idx[z].sensor is None } # this will be true if ctl",
"= self.dhw # TODO: self.zone_by_idx.get(\"HW\") too? if zone is None: zone = create_dhw(zone_idx)",
"msg.code == \"2309\": # zone._temp = zone_dict # elif msg.code == \"30C9\": #",
"# zone = self.zone_by_idx[zone_dict.pop(\"zone_idx\")] # if msg.code == \"000A\": # zone._zone_config = zone_dict",
"return self._msg_payload(self._language, \"language\") @property def params(self) -> dict: params = super().params assert ATTR_HTG_SYSTEM",
"in [d for d in kwargs[\"actuators\"] if d not in zone.devices]: zone.devices.append(device) zone.device_by_id[device.id]",
"= FaultLog(self._ctl) def _discover(self, discover_flag=DISCOVER_ALL) -> None: super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_STATUS: self._gwy._tasks.append(self._loop.create_task(self.get_fault_log()))",
"[self._ctl] # TODO: to sort out @property def heating_control(self) -> Device: if self._htg_control:",
"LookupError(f\"Duplicated zone: {zone_idx} for {self}\") zone = Zone(self, zone_idx) if not self._gwy.config[DISABLE_DISCOVERY]: #",
"sensors announcing temperatures with the same value. This leaves only a process of",
"d.type == \"02\" }, } @property def params(self) -> dict: assert ATTR_UFH_SYSTEM not",
"065 RP --- 10:067219 01:078710 --:------ 3220 005 00C00500FF # 14:41:46.599 064 RQ",
"zone_type in (\"08\", \"09\", \"0A\", \"0B\", \"11\") # CODE_0005_ZONE_TYPE ] [ # 0005:",
"DISCOVER_ALL, DISCOVER_PARAMS, DISCOVER_SCHEMA, DISCOVER_STATUS, SystemMode, SystemType, __dev_mode__, ) from .devices import Device, Entity",
"required). Can also set a DHW zone's sensor & valves?. \"\"\" def create_dhw(zone_idx)",
"to avoid complexity of z._temp # zone = self.zone_by_idx[zone_idx] # if zone._temp is",
"= None if this.code == \"3220\" and this.verb == \"RQ\": if this.src is",
"for z in msg.payload if z not in prev_msg.payload } # zones with",
"raise LookupError if self._htg_control is None: self._htg_control = device device._set_parent(self, domain=\"FC\") @property def",
"= ( # self.heating_control.params if self.heating_control else None # ) assert \"tpi_params\" not",
"import ( ATTR_CONTROLLER, ATTR_DHW_SYSTEM, ATTR_HTG_CONTROL, ATTR_HTG_SYSTEM, ATTR_ORPHANS, ATTR_UFH_SYSTEM, ATTR_ZONES, DISABLE_DISCOVERY, MAX_ZONES, ) from",
"003 000911 # 1F41: I/01: get parent controller, but not DHW sensor #",
"System(StoredHw, SysDatetime, SystemBase): # , SysFaultLog \"\"\"The Controller class.\"\"\" def __init__(self, gwy, ctl,",
"DISCOVER_PARAMS, DISCOVER_SCHEMA, DISCOVER_STATUS, SystemMode, SystemType, __dev_mode__, ) from .devices import Device, Entity from",
"None: super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_STATUS: self._gwy.send_cmd(Command.get_system_time(self.id)) # self._send_cmd(\"313F\") def _handle_msg(self, msg, prev_msg=None):",
"None: super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_STATUS: pass def _handle_msg(self, msg, prev_msg=None): \"\"\"Eavesdrop packets,",
"can't get which parent controller - need to match temps # 045 I",
"zone's sensor by matching zone/sensor temperatures. The temperature of each zone is reliably",
"006 0018380003E8 # 1260: I/07: can't get which parent controller - need to",
"zone_type in (\"00\", \"04\", \"0C\", \"0F\", \"10\") ] if discover_flag & DISCOVER_STATUS: self._send_cmd(\"0006\")",
"in (\"10\", \"13\"): raise TypeError(f\"{ATTR_HTG_CONTROL} can't be: {device}\") if self._htg_control is not None:",
"= [ d for d in self._gwy.devices # not: self.devices if d._ctl in",
"def _handle_msg(self, msg, prev_msg=None): super()._handle_msg(msg) if msg.code == \"0100\" and msg.verb in (\"",
"None def _discover(self, discover_flag=DISCOVER_ALL) -> None: super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_PARAMS: self._send_cmd(\"0100\") #",
"None and # find_htg_relay(msg, prev=prev_msg) def _send_cmd(self, code, **kwargs) -> None: dest =",
"# [xxx(z) for z in msg.payload] # else: # xxx(msg.payload) if msg.code in",
"ATTR_UFH_SYSTEM not in super().status # TODO: removeme return { **super().status, ATTR_UFH_SYSTEM: { d.id:",
"@property def status(self) -> dict: \"\"\"Return the system's current state.\"\"\" status = super().status",
"def hotwater_valve(self) -> Device: return self._dhw._dhw_valve if self._dhw else None @property def heating_valve(self)",
"ATTR_ZONES: {z.idx: z.params for z in self._zones}} @property def status(self) -> dict: assert",
"self.datetime # async def set_datetime(self, dtm: dt) -> str: # wait for the",
"( # self.heating_control.params if self.heating_control else None # ) assert \"tpi_params\" not in",
"sensor=None, **kwargs) -> DhwZone: \"\"\"Return a DHW zone (will create it if required).",
"and not isinstance(msg.payload, list): pass else: super()._handle_msg(msg) if msg.code == \"0008\" and msg.verb",
"return self._ctl.devices + [self._ctl] # TODO: to sort out @property def heating_control(self) ->",
"a zones # TODO: where to put this? # assert \"devices\" not in",
"orphans or zoneless)\", {d.id: d.temperature for d in testable_sensors}, ) if testable_sensors: #",
"pass def _handle_msg(self, msg, prev_msg=None): \"\"\"Eavesdrop packets, or pairs of packets, to maintain",
"zone system.\"\"\" if not isinstance(dhw, DhwZone): raise TypeError(f\"stored_hw can't be: {dhw}\") if self._dhw",
"TODO: removeme return {**super().schema, ATTR_ZONES: {z.idx: z.schema for z in self._zones}} @property def",
"prev_msg=None): super()._handle_msg(msg) if msg.code == \"2E04\" and msg.verb in (\" I\", \"RP\"): #",
"for z in self.zones if z.sensor is None]) == 0: return # (currently)",
"# ) status[ATTR_HTG_SYSTEM][\"heat_demand\"] = self.heat_demand status[ATTR_DEVICES] = {d.id: d.status for d in sorted(self._ctl.devices)}",
"in (\"00\", \"04\", \"0C\", \"0F\", \"10\") ] if discover_flag & DISCOVER_STATUS: self._send_cmd(\"0006\") def",
"ExpiredCallbackError from .schema import ( ATTR_CONTROLLER, ATTR_DHW_SYSTEM, ATTR_HTG_CONTROL, ATTR_HTG_SYSTEM, ATTR_ORPHANS, ATTR_UFH_SYSTEM, ATTR_ZONES, DISABLE_DISCOVERY,",
"-> dict: assert ATTR_ZONES not in super().params # TODO: removeme return {**super().params, ATTR_ZONES:",
"device.type not in (\"10\", \"13\"): raise TypeError(f\"{ATTR_HTG_CONTROL} can't be: {device}\") if self._htg_control is",
"else None # ) assert \"tpi_params\" not in params[ATTR_HTG_SYSTEM] # TODO: removeme params[ATTR_HTG_SYSTEM][\"tpi_params\"]",
"and zone_type, and actuators. \"\"\" def create_zone(zone_idx) -> Zone: if int(zone_idx, 16) >=",
"msg.payload # if msg.code in (\"3220\", \"3B00\", \"3EF0\"): # self.heating_control is None and",
"ATTR_DHW_SYSTEM not in super().params # TODO: removeme return {**super().params, ATTR_DHW_SYSTEM: self.dhw.params if self.dhw",
"1260 003 000911 # 1F41: I/01: get parent controller, but not DHW sensor",
"time_start + TIMER_LONG_TIMEOUT: # self._api_lock.release() # raise ExpiredCallbackError(\"failed to set schedule\") # self._api_lock.release()",
"the controller has already been allocated if len([z for z in self.zones if",
"= self.dhw.heating_valve if self.dhw else None elif msg.payload[\"domain_id\"] == \"FA\": device = self.dhw.hotwater_valve",
"z, t in changed_zones.items() if self.zone_by_idx[z].sensor is None and t not in [v",
"= (\"xxxx\",) # 10E0? def __repr__(self) -> str: return f\"{self._ctl.id} (hometronics)\" def _discover(self,",
"if required). Can also set a zone's sensor, and zone_type, and actuators. \"\"\"",
"== \"000C\": # self._msgs[f\"{msg.code}\"] = msg # elif msg.code == \"0005\" and prev_msg",
"{ **super().status, ATTR_UFH_SYSTEM: { d.id: d.status for d in sorted(self._ctl.devices) if d.type ==",
"I --- 13:237335 --:------ 13:237335 3B00 002 00C8 # 09:04:02.667 045 I ---",
"if self.dhw.sensor is None: # find_dhw_sensor(msg) pass elif msg.code in (\"1F41\",): # dhw_mode",
"for z in self._zones}} @property def params(self) -> dict: assert ATTR_ZONES not in",
"if d.type == \"02\" }, } class SystemBase(Entity): # 3B00 (multi-relay) \"\"\"The most",
"s._zone in (zone_idx, None) ] _LOGGER.debug(\"Testing zone %s, temp: %s\", zone_idx, temp) _LOGGER.debug(",
"for domain_id in range(0xF8, 0x100): # self._send_cmd(\"0008\", payload=f\"{domain_id:02X}00\") pass def _handle_msg(self, msg) ->",
"self._dhw else None @property def heating_valve(self) -> Device: return self._dhw._htg_valve if self._dhw else",
"return # only compare against 30C9 (array) pkt from the last cycle _LOGGER.debug(\"System",
"self._htg_control htg_control = [d for d in self._ctl.devices if d._domain_id == \"FC\"] return",
"not testable_zones: return # no testable zones testable_sensors = [ d for d",
"(in order of reliability): 1. The 3220 RQ/RP *to/from a 10:* (1x/5min) 2a.",
"-> bool: def OUT_is_exchange(this, prev): # TODO:use is? return this.src is prev.dst and",
"_handle_msg(self, msg, prev_msg=None): def OUT_find_zone_sensors() -> None: \"\"\"Determine each zone's sensor by matching",
"if msg.code in (\"000A\", \"2309\", \"30C9\"): pass # if isinstance(msg.payload, list): # elif",
"if discover_flag & DISCOVER_STATUS: # self._send_cmd(\"2E04\", payload=\"FF\") # system mode self._gwy.send_cmd(Command.get_system_mode(self.id)) def _handle_msg(self,",
"(\" I\", \"RP\"): if \"domain_id\" in msg.payload and msg.payload[\"domain_id\"] == \"FC\": self._heat_demand =",
"dict: assert ATTR_DHW_SYSTEM not in super().schema # TODO: removeme return {**super().schema, ATTR_DHW_SYSTEM: self.dhw.schema",
"d in self._gwy.devices # not: self.devices if d._ctl in (self, None) and d.addr.type",
"# super()._handle_msg(msg) # [xxx(z) for z in msg.payload] # else: # xxx(msg.payload) if",
"which zone uses the controller as a sensor. \"\"\" prev_msg, self._prev_30c9 = self._prev_30c9,",
"d._domain_id == \"FC\"] return htg_control[0] if len(htg_control) == 1 else None # HACK",
"opentherm: 1FD4, 22D9, 3220 # if discover_flag & DISCOVER_PARAMS: # for domain_id in",
"None: # self._htg_control \"\"\"Set the heating control relay for this system (10: or",
"gwy.systems.append(self) gwy.system_by_id[self.id] = self self._ctl = ctl self._domain_id = \"FF\" self._evo = None",
"kwargs.get(\"dhw_valve\"): zone._set_dhw_valve(kwargs[\"dhw_valve\"]) if kwargs.get(\"htg_valve\"): zone._set_dhw_valve(kwargs[\"htg_valve\"]) if sensor is not None: zone._set_dhw_sensor(sensor) return zone",
"@property def status(self) -> dict: status = super().status assert ATTR_HTG_SYSTEM in status #",
"if not isinstance(dhw, DhwZone): raise TypeError(f\"stored_hw can't be: {dhw}\") if self._dhw is not",
"msg.verb in (\" I\", \"RP\"): if \"domain_id\" in msg.payload: self._relay_demands[msg.payload[\"domain_id\"]] = msg if",
"state.\"\"\" def OUT_find_dhw_sensor(this): \"\"\"Discover the stored HW this system (if any). There is",
"particular, the controller may be a sensor for a zone, but unfortunately it",
"not in params[ATTR_HTG_SYSTEM] # TODO: removeme params[ATTR_HTG_SYSTEM][\"tpi_params\"] = ( self.heating_control._get_msg_value(\"1100\") if self.heating_control else",
"def OUT_is_exchange(this, prev): # TODO:use is? return this.src is prev.dst and this.dst is",
"for dev_type, description in CODE_000C_DEVICE_TYPE.items() fix payload # if description is not None",
"temp & not from another zone)\", [s.id for s in matching_sensors], ) if",
"None def _discover(self, discover_flag=DISCOVER_ALL) -> None: super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_STATUS: pass def",
"z, t in changed_zones.items() if self.zone_by_idx[z].sensor is None } # this will be",
"if msg.code == \"000A\": # zone._zone_config = zone_dict # elif msg.code == \"2309\":",
"# self.heating_control.status if self.heating_control else None # ) status[ATTR_HTG_SYSTEM][\"heat_demand\"] = self.heat_demand status[ATTR_DEVICES] =",
"Sundial(Evohome): def __repr__(self) -> str: return f\"{self._ctl.id} (sundial)\" SYSTEM_CLASSES = { SystemType.CHRONOTHERM: Chronotherm,",
"ATTR_HTG_SYSTEM, ATTR_ORPHANS, ATTR_UFH_SYSTEM, ATTR_ZONES, DISABLE_DISCOVERY, MAX_ZONES, ) from .zones import DhwZone, Zone DEV_MODE",
"== \"3220\" and this.verb == \"RQ\": if this.src is self and this.dst.type ==",
"async def get_datetime(self) -> str: # wait for the RP/313F # await self.wait_for(Command(\"313F\",",
"] if _LOGGER.isEnabledFor(logging.DEBUG): _LOGGER.debug( \"Testable zones: %s (unique/non-null temps & sensorless)\", testable_zones, )",
"if kwargs.get(\"actuators\"): # TODO: check not an address before implmenting for device in",
"f\"{self._ctl.id} (hometronics)\" def _discover(self, discover_flag=DISCOVER_ALL) -> None: # super()._discover(discover_flag=discover_flag) # will RP to:",
"params # TODO: removeme assert \"system_mode\" not in params[ATTR_HTG_SYSTEM] # TODO: removeme params[ATTR_HTG_SYSTEM][\"system_mode\"]",
"sensor. \"\"\" prev_msg, self._prev_30c9 = self._prev_30c9, msg if prev_msg is None: return if",
"if not d._domain_id and d.type != \"02\"] ) # devices without a parent",
"062 RP --- 01:102458 07:030741 --:------ 10A0 006 0018380003E8 # 1260: I/07: can't",
"ATTR_DHW_SYSTEM not in super().status # TODO: removeme return {**super().status, ATTR_DHW_SYSTEM: self.dhw.status if self.dhw",
"system's current state.\"\"\" status = super().status assert ATTR_HTG_SYSTEM in status # TODO: removeme",
"monitor mode... secs = self._get_msg_value(\"1F09\", \"remaining_seconds\") if secs is None or msg.dtm >",
"None: super().__init__(*args, **kwargs) self._fault_log = FaultLog(self._ctl) def _discover(self, discover_flag=DISCOVER_ALL) -> None: super()._discover(discover_flag=discover_flag) if",
"\"\"\"Set a system mode for a specified duration, or indefinitely.\"\"\" cmd = Command.set_system_mode(self.id,",
"where to put this? # assert \"devices\" not in schema # TODO: removeme",
"threading import Lock from typing import List, Optional from .command import Command, FaultLog,",
"msg.code == \"000C\": # self._msgs[f\"{msg.code}\"] = msg # elif msg.code == \"0005\" and",
"None @property def hotwater_valve(self) -> Device: return self._dhw._dhw_valve if self._dhw else None @property",
"in (\" I\", \"RP\"): if \"domain_id\" in msg.payload: self._relay_demands[msg.payload[\"domain_id\"]] = msg if msg.payload[\"domain_id\"]",
"Evohome system - some controllers are evohome-compatible.\"\"\" def __init__(self, gwy, ctl, **kwargs) ->",
"MultiZone: # 0005 (+/- 000C?) def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs)",
"= None # OUT: used to discover zone sensors def _discover(self, discover_flag=DISCOVER_ALL) ->",
"if discover_flag & DISCOVER_STATUS: # for domain_id in range(0xF8, 0x100): # self._send_cmd(\"0008\", payload=f\"{domain_id:02X}00\")",
"with unique/non-null temps (from 30C9), no sensor (from state): %s\", testable_zones, ) if",
"UFH, VAL, MIX, ELE) self._send_cmd(\"0005\", payload=f\"00{zone_type}\") for zone_type in (\"08\", \"09\", \"0A\", \"0B\",",
"payload=\"FF\") # system mode self._gwy.send_cmd(Command.get_system_mode(self.id)) def _handle_msg(self, msg, prev_msg=None): super()._handle_msg(msg) if msg.code ==",
"status class SysLanguage: # 0100 def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs)",
"System: %s (%s)\", dev_addr.id, self.__class__) super().__init__(gwy, **kwargs) self.id = ctl.id gwy.systems.append(self) gwy.system_by_id[self.id] =",
"None: super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_SCHEMA: [ # 0005: find any zones +",
"3EF0 006 0000100000FF # noqa # 06:49:03.465 045 RQ --- 01:145038 13:237335 --:------",
"self.language return params class SysMode: # 2E04 def __init__(self, *args, **kwargs) -> None:",
"(self, None) and d.addr.type in DEVICE_HAS_ZONE_SENSOR and d.temperature is not None and d._msgs[\"30C9\"].dtm",
"[ # 000C: find the HTG relay and DHW sensor, if any (DHW",
"-> None: super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_STATUS: pass def _handle_msg(self, msg, prev_msg=None): \"\"\"Eavesdrop",
"is not None and device.evo is not self: # raise LookupError if self._htg_control",
"k, v in self._heat_demands.items()} @property def relay_demands(self) -> Optional[dict]: # 0008 if self._relay_demands:",
"for z, t in changed_zones.items() if self.zone_by_idx[z].sensor is None and t not in",
"find_zone_sensors() def _get_zone(self, zone_idx, sensor=None, **kwargs) -> Zone: \"\"\"Return a zone (will create",
"from .command import Command, FaultLog, Priority from .const import ( ATTR_DEVICES, DEVICE_HAS_ZONE_SENSOR, DISCOVER_ALL,",
"return if len([z for z in self.zones if z.sensor is None]) == 0:",
"# TODO: removeme assert \"system_mode\" not in params[ATTR_HTG_SYSTEM] # TODO: removeme params[ATTR_HTG_SYSTEM][\"system_mode\"] =",
"set a DHW zone's sensor & valves?. \"\"\" def create_dhw(zone_idx) -> DhwZone: if",
"zone, but unfortunately it does not announce its sensor temperatures. In addition, there",
"self._dhw = dhw @property def dhw_sensor(self) -> Device: return self._dhw._dhw_sensor if self._dhw else",
"\"\"\"Determine each zone's sensor by matching zone/sensor temperatures. The temperature of each zone",
"== \"000A\": # zone._zone_config = zone_dict # elif msg.code == \"2309\": # zone._temp",
"class StoredHw: MIN_SETPOINT = 30.0 # NOTE: these may be removed MAX_SETPOINT =",
"} # this will be true if ctl is sensor if not testable_zones:",
"- matched sensor: %s (by exclusion)\", self._ctl.id) zone = self.zone_by_idx[zone_idx] zone._set_sensor(self) zone.sensor._set_ctl(self) _LOGGER.debug(\"System",
"params[ATTR_HTG_SYSTEM] # TODO: removeme # params[ATTR_HTG_SYSTEM][ATTR_HTG_CONTROL] = ( # self.heating_control.params if self.heating_control else",
"= Command.set_system_mode(self.id, system_mode=system_mode, until=until) return self._gwy.send_cmd(cmd) def set_auto(self) -> Task: \"\"\"Revert system to",
"\"FC\": self._heat_demand = msg.payload # if msg.code in (\"3220\", \"3B00\", \"3EF0\"): # self.heating_control",
"zone._zone_config = zone_dict # elif msg.code == \"2309\": # zone._temp = zone_dict #",
"not d._domain_id and d.type != \"02\"] ) # devices without a parent zone,",
"return True @property def schema(self) -> dict: \"\"\"Return the system's schema.\"\"\" schema =",
"msg.payload[\"domain_id\"] == \"FA\": device = self.dhw.hotwater_valve if self.dhw else None elif msg.payload[\"domain_id\"] ==",
"parent zone matching_sensors = [ s for s in testable_sensors if s.temperature ==",
"None: # self._dhw \"\"\"Set the DHW zone system.\"\"\" if not isinstance(dhw, DhwZone): raise",
"not in super().params # TODO: removeme return {**super().params, ATTR_DHW_SYSTEM: self.dhw.params if self.dhw else",
"zones zone_idx, temp = list(testable_zones.items())[0] _LOGGER.debug(\"Testing (sole remaining) zone %s, temp: %s\", zone_idx,",
"kwargs.get(\"actuators\"): # TODO: check not an address before implmenting for device in [d",
"zone without a sensor testable_zones = { z: t for z, t in",
"elif msg.code == \"000C\": # self._msgs[f\"{msg.code}\"] = msg # elif msg.code == \"0005\"",
"now see if we can allocate the controller as a sensor... if self._zone",
"this.code == \"3220\" and this.verb == \"RQ\": if this.src is self and this.dst.type",
"\"devices\" not in schema # TODO: removeme # schema[\"devices\"] = {d.id: d.device_info for",
"\"RQ\": if this.src is self and this.dst.type == \"10\": heater = this.dst elif",
"msg.payload] # else: # xxx(msg.payload) if msg.code in (\"000A\", \"2309\", \"30C9\") and isinstance(msg.payload,",
"sorted(self.zones, key=lambda x: x.idx) @property def schema(self) -> dict: assert ATTR_ZONES not in",
"(sundial)\" SYSTEM_CLASSES = { SystemType.CHRONOTHERM: Chronotherm, SystemType.EVOHOME: Evohome, SystemType.HOMETRONICS: Hometronics, SystemType.PROGRAMMER: Programmer, SystemType.SUNDIAL:",
"for d in self._ctl.devices if d._domain_id == \"FC\"] return htg_control[0] if len(htg_control) ==",
"schema # TODO: removeme # schema[\"devices\"] = {d.id: d.device_info for d in sorted(self._ctl.devices)}",
"\" - matching sensor(s): %s (same temp & not from another zone)\", [s.id",
"state (before): %s\", self) changed_zones = { z[\"zone_idx\"]: z[\"temperature\"] for z in msg.payload",
"# discover_flag=DISCOVER_ALL) return zone if zone_idx == \"HW\": return super()._get_zone(zone_idx, sensor=sensor, **kwargs) if",
"\"RP\": if this.src is self and this.dst.type == \"07\": sensor = this.dst if",
"3EF0 RQ (no RP) *to a 13:* (3x/60min) 3. The 3B00 I/I exchange",
"FaultLog, Priority from .const import ( ATTR_DEVICES, DEVICE_HAS_ZONE_SENSOR, DISCOVER_ALL, DISCOVER_PARAMS, DISCOVER_SCHEMA, DISCOVER_STATUS, SystemMode,",
"-> dict: \"\"\"Return the system's current state.\"\"\" status = {ATTR_HTG_SYSTEM: {}} assert ATTR_HTG_SYSTEM",
"%s\", self) super()._handle_msg(msg) if msg.code in (\"000A\",) and isinstance(msg.payload, list): for zone_idx in",
"HACK for 10: def _set_htg_control(self, device: Device) -> None: # self._htg_control \"\"\"Set the",
"self.datetime @property def status(self) -> dict: status = super().status assert ATTR_HTG_SYSTEM in status",
"self._htg_control: return if self._htg_control.actuator_state: return True @property def schema(self) -> dict: \"\"\"Return the",
"None: self._set_htg_control(heater) if msg.code in (\"000A\", \"2309\", \"30C9\") and not isinstance(msg.payload, list): pass",
"if zone is None: zone = create_dhw(zone_idx) if kwargs.get(\"dhw_valve\"): zone._set_dhw_valve(kwargs[\"dhw_valve\"]) if kwargs.get(\"htg_valve\"): zone._set_dhw_valve(kwargs[\"htg_valve\"])",
"this.code and prev.verb == this.verb: if this.src is self and prev.src.type == \"13\":",
"self._datetime = msg @property def datetime(self) -> Optional[str]: return self._msg_payload(self._datetime, \"datetime\") # TODO:",
"10:067219 01:078710 --:------ 3220 005 00C00500FF # 14:41:46.599 064 RQ --- 01:078710 10:067219",
"TODO: opentherm: 1FD4, 22D9, 3220 # if discover_flag & DISCOVER_PARAMS: # for domain_id",
"**kwargs) self._heat_demands = {} self._relay_demands = {} self._relay_failsafes = {} def __repr__(self) ->",
"super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_STATUS: # self._send_cmd(\"2E04\", payload=\"FF\") # system mode self._gwy.send_cmd(Command.get_system_mode(self.id)) def",
"%s\", zone_idx, temp) _LOGGER.debug( \" - matching sensor(s): %s (same temp & not",
"is not None: self._set_htg_control(heater) if msg.code in (\"000A\", \"2309\", \"30C9\") and not isinstance(msg.payload,",
"z in msg.payload] # else: # xxx(msg.payload) if msg.code in (\"000A\", \"2309\", \"30C9\")",
"# 047 RQ --- 07:030741 01:102458 --:------ 10A0 006 00181F0003E4 # 062 RP",
"\" I\" and prev is not None: if prev.code == this.code and prev.verb",
"a sensor # if self._gwy.serial_port: # only if in monitor mode... secs =",
"prev.src.type == \"13\": heater = prev.src if heater is not None: self._set_htg_control(heater) if",
"(array) pkt from the last cycle _LOGGER.debug(\"System state (before): %s\", self) changed_zones =",
"# for payload in (\"0000\", \"00\", \"F8\", \"F9\", \"FA\", \"FB\", \"FC\", \"FF\"): #",
"a zone's sensor, and zone_type, and actuators. \"\"\" def create_zone(zone_idx) -> Zone: if",
"# , SysFaultLog \"\"\"The Controller class.\"\"\" def __init__(self, gwy, ctl, **kwargs) -> None:",
"def status(self) -> dict: assert ATTR_UFH_SYSTEM not in super().status # TODO: removeme return",
"@property def dhw(self) -> DhwZone: return self._dhw def _set_dhw(self, dhw: DhwZone) -> None:",
"(\"000A\", \"2309\", \"30C9\"): pass # if isinstance(msg.payload, list): # elif msg.code == \"000C\":",
"None]) == 0: return # (currently) no zone without a sensor # if",
"and device is not None: # TODO: FIXME qos = {\"priority\": Priority.LOW, \"retries\":",
"not in params[ATTR_HTG_SYSTEM] # TODO: removeme # params[ATTR_HTG_SYSTEM][ATTR_HTG_CONTROL] = ( # self.heating_control.params if",
"bool: super()._handle_msg(msg) # def xxx(zone_dict): # zone = self.zone_by_idx[zone_dict.pop(\"zone_idx\")] # if msg.code ==",
"status = super().status assert \"fault_log\" not in status # TODO: removeme status[\"fault_log\"] =",
"self._get_zone(\"FA\") self.dhw._set_sensor(sensor) super()._handle_msg(msg) if msg.code in (\"10A0\", \"1260\"): # self.dhw.sensor is None and",
"d in sorted(self._ctl.devices) if d.type == \"02\" }, } @property def params(self) ->",
"assert ATTR_HTG_CONTROL not in params[ATTR_HTG_SYSTEM] # TODO: removeme # params[ATTR_HTG_SYSTEM][ATTR_HTG_CONTROL] = ( #",
"I --- 01:145038 --:------ 01:145038 3B00 002 FCC8 # note the order: most",
"asyncio.sleep(TIMER_SHORT_SLEEP) # if dt.now() > time_start + TIMER_LONG_TIMEOUT: # self._api_lock.release() # raise ExpiredCallbackError(\"failed",
"json.dumps({self._ctl.id: self.schema}) def _discover(self, discover_flag=DISCOVER_ALL) -> None: # super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_SCHEMA:",
"There is only 2 ways to to find a controller's DHW sensor: 1.",
"will RP to: 0004 if discover_flag & DISCOVER_STATUS: self._send_cmd(\"1F09\") class Programmer(Evohome): def __repr__(self)",
"and msg.verb in (\" I\", \"RP\"): self._language = msg @property def language(self) ->",
"current state.\"\"\" status = super().status assert ATTR_HTG_SYSTEM in status # TODO: removeme status[ATTR_HTG_SYSTEM][\"heat_demands\"]",
"in CODE_000C_DEVICE_TYPE.items() fix payload # if description is not None ] if discover_flag",
"_handle_msg(self, msg, prev_msg=None): super()._handle_msg(msg) if msg.code == \"0100\" and msg.verb in (\" I\",",
"for zone_type in (\"08\", \"09\", \"0A\", \"0B\", \"11\") # CODE_0005_ZONE_TYPE ] [ #",
"# self._msgs[f\"{msg.code}\"] = msg # elif msg.code == \"0005\" and prev_msg is not",
"system's configuration.\"\"\" params = {ATTR_HTG_SYSTEM: {}} assert ATTR_HTG_SYSTEM in params # TODO: removeme",
"zone._set_sensor(matching_sensors[0]) zone.sensor._set_ctl(self) elif len(matching_sensors) == 0: _LOGGER.debug(\" - no matching sensor (uses CTL?)\")",
"# zone._temp = zone_dict # if msg.code in (\"000A\", \"2309\", \"30C9\"): # if",
"{**super().schema, ATTR_DHW_SYSTEM: self.dhw.schema if self.dhw else {}} @property def params(self) -> dict: assert",
"in params[ATTR_HTG_SYSTEM] # TODO: removeme params[ATTR_HTG_SYSTEM][\"tpi_params\"] = ( self.heating_control._get_msg_value(\"1100\") if self.heating_control else None",
"be 'orphan' (e.g. from a neighbour) sensors announcing temperatures with the same value.",
"(\"000A\",) and isinstance(msg.payload, list): for zone_idx in self.zone_by_idx: cmd = Command.get_zone_mode(self.id, zone_idx, priority=Priority.LOW)",
"from .zones import DhwZone, Zone DEV_MODE = __dev_mode__ _LOGGER = logging.getLogger(__name__) if DEV_MODE:",
"self.dhw._set_sensor(sensor) super()._handle_msg(msg) if msg.code in (\"10A0\", \"1260\"): # self.dhw.sensor is None and #",
"a (not-None) temperature matching_sensors = [ s for s in testable_sensors if s.temperature",
"= msg @property def system_mode(self) -> Optional[dict]: # 2E04 return self._msg_payload(self._system_mode) def set_mode(self,",
"to FollowSchedule.\"\"\" return self.set_mode(SystemMode.RESET) @property def params(self) -> dict: params = super().params assert",
"SysDatetime, SystemBase): # , SysFaultLog \"\"\"The Controller class.\"\"\" def __init__(self, gwy, ctl, **kwargs)",
"return status class Evohome(SysLanguage, SysMode, MultiZone, UfhSystem, System): # evohome # class Evohome(System):",
"& DISCOVER_STATUS: self._send_cmd(\"0006\") def _handle_msg(self, msg, prev_msg=None): def OUT_find_zone_sensors() -> None: \"\"\"Determine each",
"address before implmenting for device in [d for d in kwargs[\"actuators\"] if d",
"@property def is_calling_for_heat(self) -> Optional[bool]: \"\"\"Return True is the system is currently calling",
"removeme params[ATTR_HTG_SYSTEM][\"system_mode\"] = self.system_mode return params class StoredHw: MIN_SETPOINT = 30.0 # NOTE:",
"1F41 012 000004FFFFFF1E060E0507E4 # 045 I --- 01:145038 --:------ 01:145038 1F41 006 000002FFFFFF",
"= None def _discover(self, discover_flag=DISCOVER_ALL) -> None: super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_STATUS: self._gwy.send_cmd(Command.get_system_time(self.id))",
"(DHW relays in DHW) self._send_cmd(\"000C\", payload=dev_type) for dev_type in (\"000D\", \"000F\") # CODE_000C_DEVICE_TYPE",
"CorruptStateError, ExpiredCallbackError from .schema import ( ATTR_CONTROLLER, ATTR_DHW_SYSTEM, ATTR_HTG_CONTROL, ATTR_HTG_SYSTEM, ATTR_ORPHANS, ATTR_UFH_SYSTEM, ATTR_ZONES,",
"[ # 0005: find any others - as per an RFG100 self._send_cmd(\"0005\", payload=f\"00{zone_type}\")",
"if s.temperature == temp and s._zone in (zone_idx, None) ] _LOGGER.debug( \" -",
"assume this zone is using the CTL as a sensor... if len(matching_sensors) ==",
"for a zone, but unfortunately it does not announce its sensor temperatures. In",
"ATTR_UFH_SYSTEM: { d.id: d.schema for d in sorted(self._ctl.devices) if d.type == \"02\" },",
"dev_type in (\"000D\", \"000F\") # CODE_000C_DEVICE_TYPE # for dev_type, description in CODE_000C_DEVICE_TYPE.items() fix",
"if discover_flag & DISCOVER_PARAMS: self._send_cmd(\"0100\") # language def _handle_msg(self, msg, prev_msg=None): super()._handle_msg(msg) if",
"10:067219 --:------ 3EF0 001 00 # 14:41:46.631 063 RP --- 10:067219 01:078710 --:------",
"is not None: if self._htg_control is device: return raise CorruptStateError( f\"{ATTR_HTG_CONTROL} shouldn't change:",
"-> Optional[dict]: # 3150 if self._heat_demands: return {k: v.payload[\"heat_demand\"] for k, v in",
"SystemType.CHRONOTHERM: Chronotherm, SystemType.EVOHOME: Evohome, SystemType.HOMETRONICS: Hometronics, SystemType.PROGRAMMER: Programmer, SystemType.SUNDIAL: Sundial, SystemType.GENERIC: System, }",
"zone_idx, sensor=None, **kwargs) -> Zone: \"\"\"Return a zone (will create it if required).",
"while not self._schedule_done: # await asyncio.sleep(TIMER_SHORT_SLEEP) # if dt.now() > time_start + TIMER_LONG_TIMEOUT:",
"None: zone._set_sensor(sensor) return zone @property def _zones(self) -> dict: return sorted(self.zones, key=lambda x:",
"def _discover(self, discover_flag=DISCOVER_ALL) -> None: # super()._discover(discover_flag=discover_flag) # will RP to: 0005/configured_zones_alt, but",
"def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self._datetime = None def _discover(self,",
"TODO: removeme assert \"system_mode\" not in params[ATTR_HTG_SYSTEM] # TODO: removeme params[ATTR_HTG_SYSTEM][\"system_mode\"] = self.system_mode",
"def devices(self) -> List[Device]: return self._ctl.devices + [self._ctl] # TODO: to sort out",
"prev_msg is not None: # zone_added = bool(prev_msg.code == \"0004\") # else zone_deleted",
"is self and this.dst.type in (\"10\", \"13\"): heater = this.dst elif this.code ==",
"_LOGGER.debug(\"System state (finally): %s\", self) super()._handle_msg(msg) if msg.code in (\"000A\",) and isinstance(msg.payload, list):",
"device._send_cmd(code, qos) if msg.code == \"3150\" and msg.verb in (\" I\", \"RP\"): if",
"return raise CorruptStateError( f\"{ATTR_HTG_CONTROL} shouldn't change: {self._htg_control} to {device}\" ) # if device.evo",
"_discover(self, discover_flag=DISCOVER_ALL) -> None: # super()._discover(discover_flag=discover_flag) # will RP to: 0005/configured_zones_alt, but not:",
"status(self) -> dict: status = super().status assert ATTR_HTG_SYSTEM in status # TODO: removeme",
"10A0 006 00181F0003E4 # 062 RP --- 01:102458 07:030741 --:------ 10A0 006 0018380003E8",
"ATTR_HTG_SYSTEM in params # TODO: removeme assert \"language\" not in params[ATTR_HTG_SYSTEM] # TODO:",
"super().__init__(*args, **kwargs) self._datetime = None def _discover(self, discover_flag=DISCOVER_ALL) -> None: super()._discover(discover_flag=discover_flag) if discover_flag",
"z[\"zone_idx\"]: z[\"temperature\"] for z in msg.payload if z not in prev_msg.payload } #",
"kwargs.pop(\"dest_addr\", self._ctl.id) payload = kwargs.pop(\"payload\", \"00\") super()._send_cmd(code, dest, payload, **kwargs) @property def devices(self)",
"x.idx) @property def schema(self) -> dict: assert ATTR_ZONES not in super().schema # TODO:",
"schema[ATTR_HTG_SYSTEM][ATTR_HTG_CONTROL] = ( self.heating_control.id if self.heating_control else None ) assert ATTR_ORPHANS not in",
"= dhw @property def dhw_sensor(self) -> Device: return self._dhw._dhw_sensor if self._dhw else None",
"self.relay_demands status[ATTR_HTG_SYSTEM][\"relay_failsafes\"] = self.relay_failsafes return status class Evohome(SysLanguage, SysMode, MultiZone, UfhSystem, System): #",
"testable_zones: return # no testable zones zone_idx, temp = list(testable_zones.items())[0] _LOGGER.debug(\"Testing (sole remaining)",
"controller's heat relay (in order of reliability): 1. The 3220 RQ/RP *to/from a",
"str: # wait for the I/313F # await self.wait_for(Command(\"313F\", verb=\" W\", payload=f\"00{dtm_to_hex(dtm)}\")) #",
"in msg.payload] # else: # xxx(msg.payload) if msg.code in (\"000A\", \"2309\", \"30C9\") and",
"= super().status assert ATTR_HTG_SYSTEM in status # TODO: removeme assert \"datetime\" not in",
"def params(self) -> dict: params = super().params assert ATTR_HTG_SYSTEM in params # TODO:",
"self.datetime return status class SysLanguage: # 0100 def __init__(self, *args, **kwargs) -> None:",
"# 09:04:02.667 045 I --- 01:145038 --:------ 01:145038 3B00 002 FCC8 # note",
"CorruptStateError( f\"{ATTR_HTG_CONTROL} shouldn't change: {self._htg_control} to {device}\" ) # if device.evo is not",
"**kwargs) -> None: super().__init__(*args, **kwargs) self._fault_log = FaultLog(self._ctl) def _discover(self, discover_flag=DISCOVER_ALL) -> None:",
"class SysLanguage: # 0100 def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self._language",
"== 0: return # (currently) no zone without a sensor # if self._gwy.serial_port:",
"known (30C9 array), but the sensor for each zone is not. In particular,",
"zone's sensor, and zone_type, and actuators. \"\"\" def create_zone(zone_idx) -> Zone: if int(zone_idx,",
"== \"2309\": # zone._temp = zone_dict # elif msg.code == \"30C9\": # zone._temp",
"1F41: I/01: get parent controller, but not DHW sensor # 045 I ---",
"== \"07\": sensor = this.dst if sensor is not None: if self.dhw is",
"== \"RQ\": if this.src is self and this.dst.type == \"10\": heater = this.dst",
"14:41:46.631 063 RP --- 10:067219 01:078710 --:------ 3EF0 006 0000100000FF # noqa #",
"status # TODO: removeme status[\"fault_log\"] = self._fault_log.fault_log status[\"last_fault\"] = self._msgz[\" I\"].get(\"0418\") return status",
"self.zones = [] self.zone_by_idx = {} # self.zone_by_name = {} self.zone_lock = Lock()",
"ATTR_HTG_SYSTEM in schema # TODO: removeme assert ATTR_HTG_CONTROL not in schema[ATTR_HTG_SYSTEM] # TODO:",
"(exceeds max_zones)\") if zone_idx in self.zone_by_idx: raise LookupError(f\"Duplicated zone: {zone_idx} for {self}\") zone",
"verb=\"RQ\")) # return self.datetime # async def set_datetime(self, dtm: dt) -> str: #",
"RQ --- 01:078710 10:067219 --:------ 3EF0 001 00 # 14:41:46.631 063 RP ---",
"code in (\"3B00\",): # 3EF0, 3EF1 # # for payload in (\"0000\", \"00\",",
"{ATTR_CONTROLLER: self._ctl.id, ATTR_HTG_SYSTEM: {}} assert ATTR_HTG_SYSTEM in schema # TODO: removeme assert ATTR_HTG_CONTROL",
"a generic controller (e.g. ST9420C).\"\"\" # 0008|0009|1030|1100|2309|3B00 def __init__(self, gwy, ctl, **kwargs) ->",
"None: return # the controller has already been allocated if len([z for z",
"{}} assert ATTR_HTG_SYSTEM in status # TODO: removeme # assert ATTR_HTG_CONTROL not in",
"= list(testable_zones.items())[0] _LOGGER.debug(\"Testing (sole remaining) zone %s, temp: %s\", zone_idx, temp) # want",
"045 I --- 01:145038 --:------ 01:145038 3B00 002 FCC8 # note the order:",
"kwargs.get(\"htg_valve\"): zone._set_dhw_valve(kwargs[\"htg_valve\"]) if sensor is not None: zone._set_dhw_sensor(sensor) return zone @property def dhw(self)",
"(e.g. from a neighbour) sensors announcing temperatures with the same value. This leaves",
"else None @property def schema(self) -> dict: assert ATTR_DHW_SYSTEM not in super().schema #",
"**kwargs) if int(zone_idx, 16) >= self._gwy.config[MAX_ZONES]: raise ValueError(f\"Unknown zone_idx/domain_id: {zone_idx}\") zone = self.zone_by_idx.get(zone_idx)",
"& DISCOVER_STATUS: # self._send_cmd(\"2E04\", payload=\"FF\") # system mode self._gwy.send_cmd(Command.get_system_mode(self.id)) def _handle_msg(self, msg, prev_msg=None):",
"-> Optional[dict]: # 0008 if self._relay_demands: return { k: v.payload[\"relay_demand\"] for k, v",
"# \"\"\"Evohome RF - The evohome-compatible system.\"\"\" import logging from asyncio import Task",
"self.heating_control else None ) assert ATTR_ORPHANS not in schema[ATTR_HTG_SYSTEM] # TODO: removeme schema[ATTR_ORPHANS]",
"__repr__(self) -> str: return f\"{self._ctl.id} (programmer)\" class Sundial(Evohome): def __repr__(self) -> str: return",
"# 09:03:59.693 051 I --- 13:237335 --:------ 13:237335 3B00 002 00C8 # 09:04:02.667",
"self._get_msg_value(\"1100\") @property def heat_demand(self) -> Optional[float]: # 3150/FC if self._heat_demand: return self._heat_demand[\"heat_demand\"] @property",
"testable_zones.items(): # TODO: when sensors announce temp, ?also includes it's parent zone matching_sensors",
"ATTR_HTG_SYSTEM in params # TODO: removeme # devices don't have params # assert",
"is not None: if self.dhw is None: self._get_zone(\"FA\") self.dhw._set_sensor(sensor) super()._handle_msg(msg) if msg.code in",
"Lock() self.zone_lock_idx = None # self._prev_30c9 = None # OUT: used to discover",
"is self and prev.src.type == \"13\": heater = prev.src if heater is not",
"= {} self._relay_failsafes = {} def __repr__(self) -> str: return f\"{self._ctl.id} (system)\" def",
"is not None ] if discover_flag & DISCOVER_PARAMS: self._send_cmd(\"1100\", payload=\"FC\") # TPI params",
"changed_zones.items() if k != z] + [None] } # ...with unique (non-null) temps,",
"not in super().status # TODO: removeme return {**super().status, ATTR_ZONES: {z.idx: z.status for z",
"# 0418 def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self._fault_log = FaultLog(self._ctl)",
"and this.dst is prev.src.addr def OUT_find_htg_relay(this, prev=None): \"\"\"Discover the heat relay (10: or",
"# 1100 return self._get_msg_value(\"1100\") @property def heat_demand(self) -> Optional[float]: # 3150/FC if self._heat_demand:",
"temp and s._zone in (zone_idx, None) ] _LOGGER.debug(\"Testing zone %s, temp: %s\", zone_idx,",
"# for domain_id in range(0xF8, 0x100): # self._send_cmd(\"0008\", payload=f\"{domain_id:02X}00\") pass def _handle_msg(self, msg)",
"= None def _discover(self, discover_flag=DISCOVER_ALL) -> None: super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_STATUS: pass",
"if len(matching_sensors) == 0: _LOGGER.debug(\" - matched sensor: %s (by exclusion)\", self._ctl.id) zone",
"DEV_MODE: _LOGGER.setLevel(logging.DEBUG) class SysFaultLog: # 0418 def __init__(self, *args, **kwargs) -> None: super().__init__(*args,",
"self._send_cmd(\"0100\") # language def _handle_msg(self, msg, prev_msg=None): super()._handle_msg(msg) if msg.code == \"0100\" and",
"@property def dhw_sensor(self) -> Device: return self._dhw._dhw_sensor if self._dhw else None @property def",
"msg.code == \"3150\": self._heat_demands[idx] = msg elif msg.code not in (\"0001\", \"000C\", \"0418\",",
"device if sensor is not None: zone._set_sensor(sensor) return zone @property def _zones(self) ->",
"not an address before implmenting for device in [d for d in kwargs[\"actuators\"]",
"can allocate the controller as a sensor... if self._zone is not None: return",
"d.temperature for d in testable_sensors}, ) if testable_sensors: # the main matching algorithm...",
"%s\", matching_sensors) _LOGGER.debug(\"System state (after): %s\", self) # now see if we can",
"if len([z for z in self.zones if z.sensor is None]) == 0: return",
"system.\"\"\" import logging from asyncio import Task from datetime import timedelta as td",
"params[ATTR_HTG_SYSTEM][\"tpi_params\"] = ( self.heating_control._get_msg_value(\"1100\") if self.heating_control else None ) return params @property def",
"_discover(self, discover_flag=DISCOVER_ALL) -> None: super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_SCHEMA: [ # 0005: find",
"SYSTEM_CLASSES = { SystemType.CHRONOTHERM: Chronotherm, SystemType.EVOHOME: Evohome, SystemType.HOMETRONICS: Hometronics, SystemType.PROGRAMMER: Programmer, SystemType.SUNDIAL: Sundial,",
"the I/313F # await self.wait_for(Command(\"313F\", verb=\" W\", payload=f\"00{dtm_to_hex(dtm)}\")) # return self.datetime @property def",
"= sorted( [d.id for d in self._ctl.devices if not d._domain_id and d.type !=",
"and d._msgs[\"30C9\"].dtm > prev_msg.dtm # changed temp during last cycle ] if _LOGGER.isEnabledFor(logging.DEBUG):",
"elif this.code == \"3B00\" and this.verb == \" I\" and prev is not",
"# zone_added = bool(prev_msg.code == \"0004\") # else zone_deleted # elif msg.code ==",
"this.code == \"3EF0\" and this.verb == \"RQ\": if this.src is self and this.dst.type",
"self.dhw.status if self.dhw else {}} class MultiZone: # 0005 (+/- 000C?) def __init__(self,",
") # devices without a parent zone, NB: CTL can be a sensor",
"( self.heating_control._get_msg_value(\"1100\") if self.heating_control else None ) return params @property def status(self) ->",
"len(matching_sensors) == 0: _LOGGER.debug(\" - no matching sensor (uses CTL?)\") else: _LOGGER.debug(\" -",
"pass class Chronotherm(Evohome): def __repr__(self) -> str: return f\"{self._ctl.id} (chronotherm)\" class Hometronics(System): RQ_SUPPORTED",
"msg, prev_msg=None): super()._handle_msg(msg) if msg.code == \"2E04\" and msg.verb in (\" I\", \"RP\"):",
"it does not announce its sensor temperatures. In addition, there may be 'orphan'",
"None: # super()._discover(discover_flag=discover_flag) # will RP to: 0005/configured_zones_alt, but not: configured_zones # will",
"}, } class SystemBase(Entity): # 3B00 (multi-relay) \"\"\"The most basic controllers - a",
"# # for payload in (\"0000\", \"00\", \"F8\", \"F9\", \"FA\", \"FB\", \"FC\", \"FF\"):",
"CODE_000C_DEVICE_TYPE.items() fix payload # if description is not None ] if discover_flag &",
"(\"10\", \"13\"): raise TypeError(f\"{ATTR_HTG_CONTROL} can't be: {device}\") if self._htg_control is not None: if",
"01:078710 --:------ 3EF0 006 0000100000FF # noqa # 06:49:03.465 045 RQ --- 01:145038",
"None if False and device is not None: # TODO: FIXME qos =",
"return dhw if zone_idx != \"HW\": return zone = self.dhw # TODO: self.zone_by_idx.get(\"HW\")",
"None: super().__init__(gwy, ctl, **kwargs) self._heat_demands = {} self._relay_demands = {} self._relay_failsafes = {}",
"self._relay_failsafes: return {} # failsafe_enabled @property def status(self) -> dict: \"\"\"Return the system's",
"} # zones with changed temps _LOGGER.debug(\"Changed zones (from 30C9): %s\", changed_zones) if",
"- as per an RFG100 self._send_cmd(\"0005\", payload=f\"00{zone_type}\") for zone_type in (\"00\", \"04\", \"0C\",",
"--:------ 01:145038 1F41 006 000002FFFFFF sensor = None if this.code == \"10A0\" and",
"TODO: removeme return {**super().status, ATTR_ZONES: {z.idx: z.status for z in self._zones}} class UfhSystem:",
"may be a sensor for a zone, but unfortunately it does not announce",
"super().__init__(*args, **kwargs) self._fault_log = FaultLog(self._ctl) def _discover(self, discover_flag=DISCOVER_ALL) -> None: super()._discover(discover_flag=discover_flag) if discover_flag",
"sensor by matching zone/sensor temperatures. The temperature of each zone is reliably known",
"d.id: d.params for d in sorted(self._ctl.devices) if d.type == \"02\" }, } @property",
"discover_flag & DISCOVER_STATUS: self._send_cmd(\"1F09\") class Programmer(Evohome): def __repr__(self) -> str: return f\"{self._ctl.id} (programmer)\"",
"self: # raise LookupError if self._htg_control is None: self._htg_control = device device._set_parent(self, domain=\"FC\")",
"python3 # -*- coding: utf-8 -*- # \"\"\"Evohome RF - The evohome-compatible system.\"\"\"",
"s in matching_sensors], ) # can safely(?) assume this zone is using the",
"in self.zones if z.sensor is None]) == 0: return # (currently) no zone",
"if d not in zone.devices]: zone.devices.append(device) zone.device_by_id[device.id] = device if sensor is not",
"[ # 0005: find any zones + their type (RAD, UFH, VAL, MIX,",
"matching sensor(s): %s (excl. controller)\", [s.id for s in matching_sensors], ) # can",
"create it if required). Can also set a zone's sensor, and zone_type, and",
"\"HW\": return zone = self.dhw # TODO: self.zone_by_idx.get(\"HW\") too? if zone is None:",
"CTL is considered 'authorative'. The 1FC9 RQ/RP exchange to/from a CTL is too",
"sorted(self._ctl.devices)} return status class System(StoredHw, SysDatetime, SystemBase): # , SysFaultLog \"\"\"The Controller class.\"\"\"",
"def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self.zones = [] self.zone_by_idx =",
"self._prev_30c9 = self._prev_30c9, msg if prev_msg is None: return if len([z for z",
"(\" I\", \"RP\"): self._language = msg @property def language(self) -> Optional[str]: # 0100",
"s in testable_sensors if s.temperature == temp and s._zone in (zone_idx, None) ]",
"description in CODE_000C_DEVICE_TYPE.items() fix payload # if description is not None ] if",
"@property def system_mode(self) -> Optional[dict]: # 2E04 return self._msg_payload(self._system_mode) def set_mode(self, system_mode=None, until=None)",
"0x100): # self._send_cmd(\"0009\", payload=f\"{domain_id:02X}00\") if discover_flag & DISCOVER_STATUS: # for domain_id in range(0xF8,",
"Task: \"\"\"Revert system to Auto, force *all* zones to FollowSchedule.\"\"\" return self.set_mode(SystemMode.RESET) @property",
"not from another zone)\", [s.id for s in matching_sensors], ) if len(matching_sensors) ==",
"# return # TODO: should have a (not-None) temperature matching_sensors = [ s",
"self._gwy.config[MAX_ZONES]: raise ValueError(f\"Invalid zone idx: {zone_idx} (exceeds max_zones)\") if zone_idx in self.zone_by_idx: raise",
"CODE_0005_ZONE_TYPE ] [ # 0005: find any others - as per an RFG100",
"this system (10: or 13:).\"\"\" if not isinstance(device, Device) or device.type not in",
"super().schema # TODO: removeme return {**super().schema, ATTR_ZONES: {z.idx: z.schema for z in self._zones}}",
"this.dst.type == \"10\": heater = this.dst elif this.code == \"3EF0\" and this.verb ==",
"{zone_idx}\") zone = self.zone_by_idx.get(zone_idx) if zone is None: zone = create_zone(zone_idx) if kwargs.get(\"zone_type\"):",
"__repr__(self) -> str: return f\"{self._ctl.id} (chronotherm)\" class Hometronics(System): RQ_SUPPORTED = (\"0004\", \"000C\", \"2E04\",",
"discover_flag & DISCOVER_STATUS: self._send_cmd(\"0006\") def _handle_msg(self, msg, prev_msg=None): def OUT_find_zone_sensors() -> None: \"\"\"Determine",
"-> dict: assert ATTR_DHW_SYSTEM not in super().schema # TODO: removeme return {**super().schema, ATTR_DHW_SYSTEM:",
"another zone)\", [s.id for s in matching_sensors], ) if len(matching_sensors) == 1: _LOGGER.debug(\"",
"and device.evo is not self: # raise LookupError if self._htg_control is None: self._htg_control",
"--- 01:078710 10:067219 --:------ 3220 005 0000050000 # 18:14:14.446 065 RP --- 10:067219",
"payload=payload) # # TODO: opentherm: 1FD4, 22D9, 3220 # if discover_flag & DISCOVER_PARAMS:",
"for a specified duration, or indefinitely.\"\"\" cmd = Command.set_system_mode(self.id, system_mode=system_mode, until=until) return self._gwy.send_cmd(cmd)",
"1F41 006 000002FFFFFF sensor = None if this.code == \"10A0\" and this.verb ==",
"s._zone in (zone_idx, None) ] _LOGGER.debug( \" - matching sensor(s): %s (excl. controller)\",",
"params[ATTR_HTG_SYSTEM][\"language\"] = self.language return params class SysMode: # 2E04 def __init__(self, *args, **kwargs)",
"from a neighbour) sensors announcing temperatures with the same value. This leaves only",
"# 06:49:05.467 045 RQ --- 01:145038 13:237335 --:------ 3EF0 001 00 # 06:49:07.468",
"self._relay_demands[idx] = msg elif msg.code == \"0009\": self._relay_failsafes[idx] = msg elif msg.code ==",
"means to determine which zone uses the controller as a sensor. \"\"\" prev_msg,",
"this cycle testable_zones = { z: t for z, t in changed_zones.items() if",
"{dhw}\") if self._dhw is None: # self._gwy._get_device(xxx) # self.add_device(dhw.sensor) # self.add_device(dhw.relay) self._dhw =",
"class.\"\"\" def __init__(self, gwy, ctl, **kwargs) -> None: super().__init__(gwy, ctl, **kwargs) self._heat_demands =",
"zone = create_dhw(zone_idx) if kwargs.get(\"dhw_valve\"): zone._set_dhw_valve(kwargs[\"dhw_valve\"]) if kwargs.get(\"htg_valve\"): zone._set_dhw_valve(kwargs[\"htg_valve\"]) if sensor is not",
"0000100000FF # noqa # 06:49:03.465 045 RQ --- 01:145038 13:237335 --:------ 3EF0 001",
"a CTL & a 13: (TPI cycle rate, usu. 6x/hr) Data from the",
"Optional from .command import Command, FaultLog, Priority from .const import ( ATTR_DEVICES, DEVICE_HAS_ZONE_SENSOR,",
"(multi-relay) \"\"\"The most basic controllers - a generic controller (e.g. ST9420C).\"\"\" # 0008|0009|1030|1100|2309|3B00",
"--:------ 01:145038 3B00 002 FCC8 # note the order: most to least reliable",
"for d in sorted(self._ctl.devices)} return status class System(StoredHw, SysDatetime, SystemBase): # , SysFaultLog",
"= (\"0004\", \"000C\", \"2E04\", \"313F\") # TODO: WIP RQ_UNSUPPORTED = (\"xxxx\",) # 10E0?",
"dhw if zone_idx != \"HW\": return zone = self.dhw # TODO: self.zone_by_idx.get(\"HW\") too?",
"rate, usu. 6x/hr) Data from the CTL is considered 'authorative'. The 1FC9 RQ/RP",
"status[ATTR_HTG_SYSTEM][\"heat_demands\"] = self.heat_demands status[ATTR_HTG_SYSTEM][\"relay_demands\"] = self.relay_demands status[ATTR_HTG_SYSTEM][\"relay_failsafes\"] = self.relay_failsafes return status class Evohome(SysLanguage,",
"self._gwy.send_cmd(cmd) def set_auto(self) -> Task: \"\"\"Revert system to Auto, set non-PermanentOverride zones to",
"await self.wait_for(Command(\"313F\", verb=\"RQ\")) # return self.datetime # async def set_datetime(self, dtm: dt) ->",
"zone = self.dhw # TODO: self.zone_by_idx.get(\"HW\") too? if zone is None: zone =",
"super().params # TODO: removeme return { **super().params, ATTR_UFH_SYSTEM: { d.id: d.params for d",
"the same value. This leaves only a process of exclusion as a means",
"in sorted(self._ctl.devices)} return schema @property def params(self) -> dict: \"\"\"Return the system's configuration.\"\"\"",
"# # self._send_cmd(code, payload=payload) # # TODO: opentherm: 1FD4, 22D9, 3220 # if",
"\"30C9\") and isinstance(msg.payload, list): pass class Chronotherm(Evohome): def __repr__(self) -> str: return f\"{self._ctl.id}",
"(\"10\", \"13\"): heater = this.dst elif this.code == \"3B00\" and this.verb == \"",
"zone/sensor temperatures. The temperature of each zone is reliably known (30C9 array), but",
"in (zone_idx, None) ] _LOGGER.debug( \" - matching sensor(s): %s (excl. controller)\", [s.id",
"**kwargs) -> None: dest = kwargs.pop(\"dest_addr\", self._ctl.id) payload = kwargs.pop(\"payload\", \"00\") super()._send_cmd(code, dest,",
"changed temps _LOGGER.debug(\"Changed zones (from 30C9): %s\", changed_zones) if not changed_zones: return #",
"def _handle_msg(self, msg, prev_msg=None): \"\"\"Eavesdrop packets, or pairs of packets, to maintain the",
"return {**super().schema, ATTR_ZONES: {z.idx: z.schema for z in self._zones}} @property def params(self) ->",
"it if required). Can also set a zone's sensor, and zone_type, and actuators.",
"zone._temp = zone_dict # elif msg.code == \"30C9\": # zone._temp = zone_dict #",
"\"\"\"Return a DHW zone (will create it if required). Can also set a",
"pkt from the last cycle _LOGGER.debug(\"System state (before): %s\", self) changed_zones = {",
"this will be true if ctl is sensor if not testable_zones: return #",
"sensor, and zone_type, and actuators. \"\"\" def create_zone(zone_idx) -> Zone: if int(zone_idx, 16)",
"self._send_cmd(\"2E04\", payload=\"FF\") # system mode self._gwy.send_cmd(Command.get_system_mode(self.id)) def _handle_msg(self, msg, prev_msg=None): super()._handle_msg(msg) if msg.code",
"verb=\" W\", payload=f\"00{dtm_to_hex(dtm)}\")) # return self.datetime @property def status(self) -> dict: status =",
"f\"{self._ctl.id} (programmer)\" class Sundial(Evohome): def __repr__(self) -> str: return f\"{self._ctl.id} (sundial)\" SYSTEM_CLASSES =",
"DISCOVER_SCHEMA: [ # 0005: find any zones + their type (RAD, UFH, VAL,",
"k, v in self._relay_demands.items() } @property def relay_failsafes(self) -> Optional[dict]: # 0009 if",
"%s (excl. controller)\", [s.id for s in matching_sensors], ) # can safely(?) assume",
"if int(zone_idx, 16) >= self._gwy.config[MAX_ZONES]: raise ValueError(f\"Invalid zone idx: {zone_idx} (exceeds max_zones)\") if",
"*args, **kwargs) -> None: super().__init__(*args, **kwargs) self._language = None def _discover(self, discover_flag=DISCOVER_ALL) ->",
"if \"domain_id\" in msg.payload and msg.payload[\"domain_id\"] == \"FC\": self._heat_demand = msg.payload # if",
"in DEVICE_HAS_ZONE_SENSOR and d.temperature is not None and d._msgs[\"30C9\"].dtm > prev_msg.dtm # changed",
"dest, payload, **kwargs) @property def devices(self) -> List[Device]: return self._ctl.devices + [self._ctl] #",
"and msg.verb in (\" I\", \"RP\"): # TODO: W self._datetime = msg @property",
"others - as per an RFG100 self._send_cmd(\"0005\", payload=f\"00{zone_type}\") for zone_type in (\"00\", \"04\",",
"unique/non-null temps (from 30C9), no sensor (from state): %s\", testable_zones, ) if not",
"super()._handle_msg(msg) if msg.code in (\"000A\",) and isinstance(msg.payload, list): for zone_idx in self.zone_by_idx: cmd",
"# super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_SCHEMA: [ # 000C: find the HTG relay",
"= zone_dict # if msg.code in (\"000A\", \"2309\", \"30C9\"): # if isinstance(msg.payload, list):",
"def schema(self) -> dict: assert ATTR_ZONES not in super().schema # TODO: removeme return",
"msg.code == \"2E04\" and msg.verb in (\" I\", \"RP\"): # this is a",
"Optional[bool]: \"\"\"Return True is the system is currently calling for heat.\"\"\" if not",
"any others - as per an RFG100 self._send_cmd(\"0005\", payload=f\"00{zone_type}\") for zone_type in (\"00\",",
"this.src is prev.dst and this.dst is prev.src.addr def OUT_find_htg_relay(this, prev=None): \"\"\"Discover the heat",
"msg.verb in (\" I\", \"RP\"): # this is a special case self._system_mode =",
"is using the CTL as a sensor... if len(matching_sensors) == 0: _LOGGER.debug(\" -",
"& sensorless)\", testable_zones, ) _LOGGER.debug( \"Testable sensors: %s (non-null temps & orphans or",
"# status[ATTR_HTG_SYSTEM][ATTR_HTG_CONTROL] = ( # self.heating_control.status if self.heating_control else None # ) status[ATTR_HTG_SYSTEM][\"heat_demand\"]",
"is None: # find_dhw_sensor(msg) pass elif msg.code in (\"1F41\",): # dhw_mode pass def",
"__repr__(self) -> str: return f\"{self._ctl.id} (sundial)\" SYSTEM_CLASSES = { SystemType.CHRONOTHERM: Chronotherm, SystemType.EVOHOME: Evohome,",
"# no single zone without a sensor testable_zones = { z: t for",
"the controller may be a sensor for a zone, but unfortunately it does",
"The 10A0 RQ/RP *from/to a 07:* (1x/4h) - reliable 2. Use sensor temp",
"payload=f\"00{zone_type}\") for zone_type in (\"00\", \"04\", \"0C\", \"0F\", \"10\") ] if discover_flag &",
"Optional[float]: # 1100 return self._get_msg_value(\"1100\") @property def heat_demand(self) -> Optional[float]: # 3150/FC if",
"class SystemBase(Entity): # 3B00 (multi-relay) \"\"\"The most basic controllers - a generic controller",
"for this system (10: or 13:).\"\"\" if not isinstance(device, Device) or device.type not",
"removeme status[\"fault_log\"] = self._fault_log.fault_log status[\"last_fault\"] = self._msgz[\" I\"].get(\"0418\") return status class SysDatetime: #",
"self._language = None def _discover(self, discover_flag=DISCOVER_ALL) -> None: super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_PARAMS:",
"the HTG relay and DHW sensor, if any (DHW relays in DHW) self._send_cmd(\"000C\",",
"3 ways to find a controller's heat relay (in order of reliability): 1.",
"== \"FC\"] return htg_control[0] if len(htg_control) == 1 else None # HACK for",
"def _handle_msg(self, msg, prev_msg=None): super()._handle_msg(msg) if msg.code == \"2E04\" and msg.verb in (\"",
"( ATTR_DEVICES, DEVICE_HAS_ZONE_SENSOR, DISCOVER_ALL, DISCOVER_PARAMS, DISCOVER_SCHEMA, DISCOVER_STATUS, SystemMode, SystemType, __dev_mode__, ) from .devices",
"--:------ 3EF0 001 00 # 09:03:59.693 051 I --- 13:237335 --:------ 13:237335 3B00",
"RP/313F # await self.wait_for(Command(\"313F\", verb=\"RQ\")) # return self.datetime # async def set_datetime(self, dtm:",
"Device) or device.type not in (\"10\", \"13\"): raise TypeError(f\"{ATTR_HTG_CONTROL} can't be: {device}\") if",
"d.schema for d in sorted(self._ctl.devices) if d.type == \"02\" }, } @property def",
"or 13:) for this system. There's' 3 ways to find a controller's heat",
"**kwargs) -> DhwZone: \"\"\"Return a DHW zone (will create it if required). Can",
"this.code == \"10A0\" and this.verb == \"RP\": if this.src is self and this.dst.type",
"super().__init__(gwy, ctl, **kwargs) def __repr__(self) -> str: return f\"{self._ctl.id} (evohome)\" def _discover(self, discover_flag=DISCOVER_ALL)",
"is the system is currently calling for heat.\"\"\" if not self._htg_control: return if",
"DEVICE_HAS_ZONE_SENSOR and d.temperature is not None and d._msgs[\"30C9\"].dtm > prev_msg.dtm # changed temp",
"\"2309\", \"30C9\") and not isinstance(msg.payload, list): pass else: super()._handle_msg(msg) if msg.code == \"0008\"",
"usu. 6x/hr) Data from the CTL is considered 'authorative'. The 1FC9 RQ/RP exchange",
"None: if prev.code == this.code and prev.verb == this.verb: if this.src is self",
"not in super().status # TODO: removeme return { **super().status, ATTR_UFH_SYSTEM: { d.id: d.status",
"13: (TPI cycle rate, usu. 6x/hr) Data from the CTL is considered 'authorative'.",
"-> None: super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_SCHEMA: [ # 0005: find any zones",
"zone_idx != \"HW\": return zone = self.dhw # TODO: self.zone_by_idx.get(\"HW\") too? if zone",
"RQ_SUPPORTED = (\"0004\", \"000C\", \"2E04\", \"313F\") # TODO: WIP RQ_UNSUPPORTED = (\"xxxx\",) #",
"z[\"temperature\"] for z in msg.payload if z not in prev_msg.payload } # zones",
"msg.payload[\"domain_id\"] == \"FC\": device = self.heating_control else: device = None if False and",
"else {}} @property def status(self) -> dict: assert ATTR_DHW_SYSTEM not in super().status #",
"get both parent controller & DHW sensor # 047 RQ --- 07:030741 01:102458",
"discover_flag & DISCOVER_STATUS: self._gwy.send_cmd(Command.get_system_time(self.id)) # self._send_cmd(\"313F\") def _handle_msg(self, msg, prev_msg=None): super()._handle_msg(msg) if msg.code",
"match temps # 045 I --- 07:045960 --:------ 07:045960 1260 003 000911 #",
"msg if msg.payload[\"domain_id\"] == \"F9\": device = self.dhw.heating_valve if self.dhw else None elif",
"self.dhw.schema if self.dhw else {}} @property def params(self) -> dict: assert ATTR_DHW_SYSTEM not",
"a 13:* (3x/60min) 3. The 3B00 I/I exchange between a CTL & a",
"between a CTL & a 13: (TPI cycle rate, usu. 6x/hr) Data from",
"msg.payload and msg.payload[\"domain_id\"] == \"FC\": self._heat_demand = msg.payload # if msg.code in (\"3220\",",
"FIXME qos = {\"priority\": Priority.LOW, \"retries\": 2} for code in (\"0008\", \"3EF1\"): device._send_cmd(code,",
"assert ATTR_HTG_SYSTEM in status # TODO: removeme status[ATTR_HTG_SYSTEM][\"heat_demands\"] = self.heat_demands status[ATTR_HTG_SYSTEM][\"relay_demands\"] = self.relay_demands",
"can't be: {device}\") if self._htg_control is not None: if self._htg_control is device: return",
"d in testable_sensors}, ) if testable_sensors: # the main matching algorithm... for zone_idx,",
"removeme status[ATTR_HTG_SYSTEM][\"datetime\"] = self.datetime return status class SysLanguage: # 0100 def __init__(self, *args,",
"not changed_zones: return # ctl's 30C9 says no zones have changed temps during",
"# dhw_mode pass def _get_zone(self, zone_idx, sensor=None, **kwargs) -> DhwZone: \"\"\"Return a DHW",
"gwy.system_by_id[self.id] = self self._ctl = ctl self._domain_id = \"FF\" self._evo = None self._heat_demand",
"= msg @property def language(self) -> Optional[str]: # 0100 return self._msg_payload(self._language, \"language\") @property",
"= msg elif msg.code == \"0009\": self._relay_failsafes[idx] = msg elif msg.code == \"3150\":",
"return {} # failsafe_enabled @property def status(self) -> dict: \"\"\"Return the system's current",
"_get_zone(self, zone_idx, sensor=None, **kwargs) -> DhwZone: \"\"\"Return a DHW zone (will create it",
"in super().status # TODO: removeme return {**super().status, ATTR_DHW_SYSTEM: self.dhw.status if self.dhw else {}}",
"it's parent zone matching_sensors = [ s for s in testable_sensors if s.temperature",
"def __repr__(self) -> str: return f\"{self._ctl.id} (system)\" def _handle_msg(self, msg) -> bool: super()._handle_msg(msg)",
"zone (will create it if required). Can also set a zone's sensor, and",
"[None] } # ...with unique (non-null) temps, and no sensor _LOGGER.debug( \" -",
"payload = kwargs.pop(\"payload\", \"00\") super()._send_cmd(code, dest, payload, **kwargs) @property def devices(self) -> List[Device]:",
"for d in self._gwy.devices # not: self.devices if d._ctl in (self, None) and",
"@property def _zones(self) -> dict: return sorted(self.zones, key=lambda x: x.idx) @property def schema(self)",
"10: def _set_htg_control(self, device: Device) -> None: # self._htg_control \"\"\"Set the heating control",
"# for domain_id in range(0xF8, 0x100): # self._send_cmd(\"0009\", payload=f\"{domain_id:02X}00\") if discover_flag & DISCOVER_STATUS:",
"mode... secs = self._get_msg_value(\"1F09\", \"remaining_seconds\") if secs is None or msg.dtm > prev_msg.dtm",
"to {device}\" ) # if device.evo is not None and device.evo is not",
"1. The 10A0 RQ/RP *from/to a 07:* (1x/4h) - reliable 2. Use sensor",
"zone_idx == \"HW\": return super()._get_zone(zone_idx, sensor=sensor, **kwargs) if int(zone_idx, 16) >= self._gwy.config[MAX_ZONES]: raise",
"dict: \"\"\"Return the system's schema.\"\"\" schema = {ATTR_CONTROLLER: self._ctl.id, ATTR_HTG_SYSTEM: {}} assert ATTR_HTG_SYSTEM",
"isinstance(dhw, DhwZone): raise TypeError(f\"stored_hw can't be: {dhw}\") if self._dhw is not None: if",
"discover_flag=DISCOVER_ALL) return zone if zone_idx == \"HW\": return super()._get_zone(zone_idx, sensor=sensor, **kwargs) if int(zone_idx,",
"MIX, ELE) self._send_cmd(\"0005\", payload=f\"00{zone_type}\") for zone_type in (\"08\", \"09\", \"0A\", \"0B\", \"11\") #",
"system_mode=None, until=None) -> Task: \"\"\"Set a system mode for a specified duration, or",
"_LOGGER.debug(\"Creating a System: %s (%s)\", dev_addr.id, self.__class__) super().__init__(gwy, **kwargs) self.id = ctl.id gwy.systems.append(self)",
"self._fault_log.fault_log status[\"last_fault\"] = self._msgz[\" I\"].get(\"0418\") return status class SysDatetime: # 313F def __init__(self,",
"not announce its sensor temperatures. In addition, there may be 'orphan' (e.g. from",
"status(self) -> dict: assert ATTR_ZONES not in super().status # TODO: removeme return {**super().status,",
"-> dict: assert ATTR_DHW_SYSTEM not in super().params # TODO: removeme return {**super().params, ATTR_DHW_SYSTEM:",
"return # no testable zones zone_idx, temp = list(testable_zones.items())[0] _LOGGER.debug(\"Testing (sole remaining) zone",
"matching_sensors], ) if len(matching_sensors) == 1: _LOGGER.debug(\" - matched sensor: %s\", matching_sensors[0].id) zone",
"controller (e.g. ST9420C).\"\"\" # 0008|0009|1030|1100|2309|3B00 def __init__(self, gwy, ctl, **kwargs) -> None: #",
"== \" I\" and prev is not None: if prev.code == this.code and",
"self._htg_control: return self._htg_control htg_control = [d for d in self._ctl.devices if d._domain_id ==",
"ATTR_HTG_CONTROL not in params[ATTR_HTG_SYSTEM] # TODO: removeme # params[ATTR_HTG_SYSTEM][ATTR_HTG_CONTROL] = ( # self.heating_control.params",
"leaves only a process of exclusion as a means to determine which zone",
"# 0008 if self._relay_demands: return { k: v.payload[\"relay_demand\"] for k, v in self._relay_demands.items()",
"\"\"\"Revert system to Auto, force *all* zones to FollowSchedule.\"\"\" return self.set_mode(SystemMode.RESET) @property def",
"elif msg.code == \"2309\": # zone._temp = zone_dict # elif msg.code == \"30C9\":",
"09:03:59.693 051 I --- 13:237335 --:------ 13:237335 3B00 002 00C8 # 09:04:02.667 045",
"--- 01:145038 13:237335 --:------ 3EF0 001 00 # 09:03:59.693 051 I --- 13:237335",
"(no RP) *to a 13:* (3x/60min) 3. The 3B00 I/I exchange between a",
"# 10E0? def __repr__(self) -> str: return f\"{self._ctl.id} (hometronics)\" def _discover(self, discover_flag=DISCOVER_ALL) ->",
"--:------ 3220 005 00C00500FF # 14:41:46.599 064 RQ --- 01:078710 10:067219 --:------ 3EF0",
"UfhSystem: @property def schema(self) -> dict: assert ATTR_UFH_SYSTEM not in super().schema # TODO:",
"self._evo = None self._heat_demand = None self._htg_control = None def __repr__(self) -> str:",
"DISCOVER_STATUS: # for domain_id in range(0xF8, 0x100): # self._send_cmd(\"0008\", payload=f\"{domain_id:02X}00\") pass def _handle_msg(self,",
"if int(zone_idx, 16) >= self._gwy.config[MAX_ZONES]: raise ValueError(f\"Unknown zone_idx/domain_id: {zone_idx}\") zone = self.zone_by_idx.get(zone_idx) if",
"remaining) zone %s, temp: %s\", zone_idx, temp) # want to avoid complexity of",
"TODO: removeme return { **super().status, ATTR_UFH_SYSTEM: { d.id: d.status for d in sorted(self._ctl.devices)",
"self.dhw.heating_valve if self.dhw else None elif msg.payload[\"domain_id\"] == \"FA\": device = self.dhw.hotwater_valve if",
"(by exclusion)\", self._ctl.id) zone = self.zone_by_idx[zone_idx] zone._set_sensor(self) zone.sensor._set_ctl(self) _LOGGER.debug(\"System state (finally): %s\", self)",
"# will RP to: 0005/configured_zones_alt, but not: configured_zones # will RP to: 0004",
"0005/configured_zones_alt, but not: configured_zones # will RP to: 0004 if discover_flag & DISCOVER_STATUS:",
"in (\" I\", \"RP\"): self._language = msg @property def language(self) -> Optional[str]: #",
"\"02\" }, } @property def status(self) -> dict: assert ATTR_UFH_SYSTEM not in super().status",
"class MultiZone: # 0005 (+/- 000C?) def __init__(self, *args, **kwargs) -> None: super().__init__(*args,",
"{d.id: d.status for d in sorted(self._ctl.devices)} return status class System(StoredHw, SysDatetime, SystemBase): #",
"removeme return { **super().status, ATTR_UFH_SYSTEM: { d.id: d.status for d in sorted(self._ctl.devices) if",
"005 00C00500FF # 14:41:46.599 064 RQ --- 01:078710 10:067219 --:------ 3EF0 001 00",
"*all* zones to FollowSchedule.\"\"\" return self.set_mode(SystemMode.RESET) @property def params(self) -> dict: params =",
"not None: if prev.code == this.code and prev.verb == this.verb: if this.src is",
"if self.dhw else {}} @property def status(self) -> dict: assert ATTR_DHW_SYSTEM not in",
"--- 10:067219 01:078710 --:------ 3220 005 00C00500FF # 14:41:46.599 064 RQ --- 01:078710",
"cycle rate, usu. 6x/hr) Data from the CTL is considered 'authorative'. The 1FC9",
"in kwargs[\"actuators\"] if d not in zone.devices]: zone.devices.append(device) zone.device_by_id[device.id] = device if sensor",
"\"RP\"): if \"domain_id\" in msg.payload: self._relay_demands[msg.payload[\"domain_id\"]] = msg if msg.payload[\"domain_id\"] == \"F9\": device",
"if discover_flag & DISCOVER_STATUS: self._send_cmd(\"1F09\") def _handle_msg(self, msg) -> bool: super()._handle_msg(msg) # def",
"in status # TODO: removeme # assert ATTR_HTG_CONTROL not in status[ATTR_HTG_SYSTEM] # TODO:",
"if not self._gwy.config[DISABLE_DISCOVERY]: # TODO: needs tidyup (ref #67) zone._discover() # discover_flag=DISCOVER_ALL) return",
"during this cycle testable_zones = { z: t for z, t in changed_zones.items()",
"is not. In particular, the controller may be a sensor for a zone,",
"= kwargs.pop(\"payload\", \"00\") super()._send_cmd(code, dest, payload, **kwargs) @property def devices(self) -> List[Device]: return",
"= ( # self.heating_control.status if self.heating_control else None # ) status[ATTR_HTG_SYSTEM][\"heat_demand\"] = self.heat_demand",
"in super().status # TODO: removeme return { **super().status, ATTR_UFH_SYSTEM: { d.id: d.status for",
"max_zones)\") if zone_idx in self.zone_by_idx: raise LookupError(f\"Duplicated zone: {zone_idx} for {self}\") zone =",
"RQ/RP exchange to/from a CTL is too rare to be useful. \"\"\" #",
"isinstance(device, Device) or device.type not in (\"10\", \"13\"): raise TypeError(f\"{ATTR_HTG_CONTROL} can't be: {device}\")",
"len([z for z in self.zones if z.sensor is None]) != 1: return #",
"len([z for z in self.zones if z.sensor is None]) == 0: return #",
"TODO: removeme # assert ATTR_HTG_CONTROL not in status[ATTR_HTG_SYSTEM] # TODO: removeme # status[ATTR_HTG_SYSTEM][ATTR_HTG_CONTROL]",
"def language(self) -> Optional[str]: # 0100 return self._msg_payload(self._language, \"language\") @property def params(self) ->",
"Optional[dict]: # 3150 if self._heat_demands: return {k: v.payload[\"heat_demand\"] for k, v in self._heat_demands.items()}",
"of z._temp # zone = self.zone_by_idx[zone_idx] # if zone._temp is None: # return",
"testable_sensors}, ) if testable_sensors: # the main matching algorithm... for zone_idx, temp in",
"if discover_flag & DISCOVER_STATUS: self._send_cmd(\"1F09\") class Programmer(Evohome): def __repr__(self) -> str: return f\"{self._ctl.id}",
"t for z, t in changed_zones.items() if self.zone_by_idx[z].sensor is None and t not",
"None def _discover(self, discover_flag=DISCOVER_ALL) -> None: super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_STATUS: # self._send_cmd(\"2E04\",",
"schema(self) -> dict: assert ATTR_ZONES not in super().schema # TODO: removeme return {**super().schema,",
"FaultLog(self._ctl) def _discover(self, discover_flag=DISCOVER_ALL) -> None: super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_STATUS: self._gwy._tasks.append(self._loop.create_task(self.get_fault_log())) async",
"= self._fault_log.fault_log status[\"last_fault\"] = self._msgz[\" I\"].get(\"0418\") return status class SysDatetime: # 313F def",
"_handle_msg(self, msg, prev_msg=None): super()._handle_msg(msg) if msg.code == \"2E04\" and msg.verb in (\" I\",",
"if discover_flag & DISCOVER_STATUS: pass def _handle_msg(self, msg, prev_msg=None): \"\"\"Eavesdrop packets, or pairs",
"**kwargs) -> None: super().__init__(*args, **kwargs) self.zones = [] self.zone_by_idx = {} # self.zone_by_name",
"CTL is too rare to be useful. \"\"\" # 18:14:14.025 066 RQ ---",
"def __init__(self, gwy, ctl, **kwargs) -> None: super().__init__(gwy, ctl, **kwargs) self._heat_demands = {}",
"{ k: v.payload[\"relay_demand\"] for k, v in self._relay_demands.items() } @property def relay_failsafes(self) ->",
"zone_type, and actuators. \"\"\" def create_zone(zone_idx) -> Zone: if int(zone_idx, 16) >= self._gwy.config[MAX_ZONES]:",
"temps (from 30C9), no sensor (from state): %s\", testable_zones, ) if not testable_zones:",
"initiated by the DHW, so is not authorative. The I/1260 is not to/from",
"is None or msg.dtm > prev_msg.dtm + td(seconds=secs): return # only compare against",
"# 313F def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self._datetime = None",
"+ [self._ctl] # TODO: to sort out @property def heating_control(self) -> Device: if",
"\"3150\": self._heat_demands[idx] = msg elif msg.code not in (\"0001\", \"000C\", \"0418\", \"1100\", \"3B00\"):",
"super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_STATUS: self._send_cmd(\"1F09\") def _handle_msg(self, msg) -> bool: super()._handle_msg(msg) #",
"def schema(self) -> dict: \"\"\"Return the system's schema.\"\"\" schema = {ATTR_CONTROLLER: self._ctl.id, ATTR_HTG_SYSTEM:",
">= self._gwy.config[MAX_ZONES]: raise ValueError(f\"Invalid zone idx: {zone_idx} (exceeds max_zones)\") if zone_idx in self.zone_by_idx:",
"(RAD, UFH, VAL, MIX, ELE) self._send_cmd(\"0005\", payload=f\"00{zone_type}\") for zone_type in (\"08\", \"09\", \"0A\",",
"\"\"\" def create_dhw(zone_idx) -> DhwZone: if self.dhw: raise LookupError(f\"Duplicate stored HW: {zone_idx}\") dhw",
"in testable_sensors if s.temperature == temp and s._zone in (zone_idx, None) ] _LOGGER.debug(",
"__dev_mode__ _LOGGER = logging.getLogger(__name__) if DEV_MODE: _LOGGER.setLevel(logging.DEBUG) class SysFaultLog: # 0418 def __init__(self,",
"and prev_msg is not None: # zone_added = bool(prev_msg.code == \"0004\") # else",
"if not changed_zones: return # ctl's 30C9 says no zones have changed temps",
"sensors def _discover(self, discover_flag=DISCOVER_ALL) -> None: super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_SCHEMA: [ #",
"def heating_valve(self) -> Device: return self._dhw._htg_valve if self._dhw else None @property def schema(self)",
"controller, so is not useful. \"\"\" # 10A0: RQ/07/01, RP/01/07: can get both",
"order of reliability): 1. The 3220 RQ/RP *to/from a 10:* (1x/5min) 2a. The",
"to to find a controller's DHW sensor: 1. The 10A0 RQ/RP *from/to a",
"removeme return { **super().schema, ATTR_UFH_SYSTEM: { d.id: d.schema for d in sorted(self._ctl.devices) if",
"10:* (1x/1min) 2b. The 3EF0 RQ (no RP) *to a 13:* (3x/60min) 3.",
"> prev_msg.dtm + td(seconds=secs): return # only compare against 30C9 (array) pkt from",
"useful. \"\"\" # 18:14:14.025 066 RQ --- 01:078710 10:067219 --:------ 3220 005 0000050000",
"# TODO: self.zone_by_idx.get(\"HW\") too? if zone is None: zone = create_dhw(zone_idx) if kwargs.get(\"dhw_valve\"):",
"ATTR_ORPHANS not in schema[ATTR_HTG_SYSTEM] # TODO: removeme schema[ATTR_ORPHANS] = sorted( [d.id for d",
"Auto, force *all* zones to FollowSchedule.\"\"\" return self.set_mode(SystemMode.RESET) @property def params(self) -> dict:",
"in status # TODO: removeme status[ATTR_HTG_SYSTEM][\"heat_demands\"] = self.heat_demands status[ATTR_HTG_SYSTEM][\"relay_demands\"] = self.relay_demands status[ATTR_HTG_SYSTEM][\"relay_failsafes\"] =",
"ATTR_ZONES, DISABLE_DISCOVERY, MAX_ZONES, ) from .zones import DhwZone, Zone DEV_MODE = __dev_mode__ _LOGGER",
"None and device.evo is not self: # raise LookupError if self._htg_control is None:",
"00C8 # 09:04:02.667 045 I --- 01:145038 --:------ 01:145038 3B00 002 FCC8 #",
"compare against 30C9 (array) pkt from the last cycle _LOGGER.debug(\"System state (before): %s\",",
"self.add_device(dhw.sensor) # self.add_device(dhw.relay) self._dhw = dhw @property def dhw_sensor(self) -> Device: return self._dhw._dhw_sensor",
"ATTR_HTG_SYSTEM in params # TODO: removeme assert \"system_mode\" not in params[ATTR_HTG_SYSTEM] # TODO:",
"but unfortunately it does not announce its sensor temperatures. In addition, there may",
"self.zone_by_idx[zone_idx] zone._set_sensor(matching_sensors[0]) zone.sensor._set_ctl(self) elif len(matching_sensors) == 0: _LOGGER.debug(\" - no matching sensor (uses",
"else: super()._handle_msg(msg) if msg.code == \"0008\" and msg.verb in (\" I\", \"RP\"): if",
"self) changed_zones = { z[\"zone_idx\"]: z[\"temperature\"] for z in msg.payload if z not",
"ATTR_ZONES not in super().status # TODO: removeme return {**super().status, ATTR_ZONES: {z.idx: z.status for",
"last cycle ] if _LOGGER.isEnabledFor(logging.DEBUG): _LOGGER.debug( \"Testable zones: %s (unique/non-null temps & sensorless)\",",
"NB: CTL can be a sensor for a zones # TODO: where to",
"is not None: # zone_added = bool(prev_msg.code == \"0004\") # else zone_deleted #",
"dict: assert ATTR_ZONES not in super().params # TODO: removeme return {**super().params, ATTR_ZONES: {z.idx:",
"a DHW zone (will create it if required). Can also set a DHW",
"22D9, 3220 # if discover_flag & DISCOVER_PARAMS: # for domain_id in range(0xF8, 0x100):",
"temperatures with the same value. This leaves only a process of exclusion as",
"def _handle_msg(self, msg, prev_msg=None): def OUT_find_zone_sensors() -> None: \"\"\"Determine each zone's sensor by",
"\"000C\", \"0418\", \"1100\", \"3B00\"): assert False, msg.code @property def heat_demands(self) -> Optional[dict]: #",
"range(0xF8, 0x100): # self._send_cmd(\"0008\", payload=f\"{domain_id:02X}00\") pass def _handle_msg(self, msg) -> bool: def OUT_is_exchange(this,",
"if zone_idx != \"HW\": return zone = self.dhw # TODO: self.zone_by_idx.get(\"HW\") too? if",
"dict: assert ATTR_UFH_SYSTEM not in super().params # TODO: removeme return { **super().params, ATTR_UFH_SYSTEM:",
"if msg.payload[\"domain_id\"] == \"F9\": device = self.dhw.heating_valve if self.dhw else None elif msg.payload[\"domain_id\"]",
"removeme # params[ATTR_HTG_SYSTEM][ATTR_HTG_CONTROL] = ( # self.heating_control.params if self.heating_control else None # )",
"is not None: if self._dhw is dhw: return raise CorruptStateError(\"DHW shouldn't change: {self._dhw}",
"@property def relay_demands(self) -> Optional[dict]: # 0008 if self._relay_demands: return { k: v.payload[\"relay_demand\"]",
"\"30C9\") and not isinstance(msg.payload, list): pass else: super()._handle_msg(msg) if msg.code == \"0008\" and",
"else: device = None if False and device is not None: # TODO:",
"I\", \"RP\"): if \"domain_id\" in msg.payload and msg.payload[\"domain_id\"] == \"FC\": self._heat_demand = msg.payload",
"-> None: # super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_SCHEMA: [ # 000C: find the",
"# -*- coding: utf-8 -*- # \"\"\"Evohome RF - The evohome-compatible system.\"\"\" import",
"matched sensor: %s\", matching_sensors[0].id) zone = self.zone_by_idx[zone_idx] zone._set_sensor(matching_sensors[0]) zone.sensor._set_ctl(self) elif len(matching_sensors) == 0:",
"from the CTL is considered more authorative. The RQ is initiated by the",
"in self._zones}} class UfhSystem: @property def schema(self) -> dict: assert ATTR_UFH_SYSTEM not in",
"in sorted(self._ctl.devices) if d.type == \"02\" }, } class SystemBase(Entity): # 3B00 (multi-relay)",
"removeme # schema[\"devices\"] = {d.id: d.device_info for d in sorted(self._ctl.devices)} return schema @property",
"%s\", matching_sensors[0].id) zone = self.zone_by_idx[zone_idx] zone._set_sensor(matching_sensors[0]) zone.sensor._set_ctl(self) elif len(matching_sensors) == 0: _LOGGER.debug(\" -",
"TODO: check not an address before implmenting for device in [d for d",
"system mode for a specified duration, or indefinitely.\"\"\" cmd = Command.set_system_mode(self.id, system_mode=system_mode, until=until)",
"0005: find any others - as per an RFG100 self._send_cmd(\"0005\", payload=f\"00{zone_type}\") for zone_type",
"and this.dst.type == \"07\": sensor = this.dst if sensor is not None: if",
"z._temp # zone = self.zone_by_idx[zone_idx] # if zone._temp is None: # return #",
"prev.dst and this.dst is prev.src.addr def OUT_find_htg_relay(this, prev=None): \"\"\"Discover the heat relay (10:",
"assert \"tpi_params\" not in params[ATTR_HTG_SYSTEM] # TODO: removeme params[ATTR_HTG_SYSTEM][\"tpi_params\"] = ( self.heating_control._get_msg_value(\"1100\") if",
"- multiple sensors: %s\", matching_sensors) _LOGGER.debug(\"System state (after): %s\", self) # now see",
"if zone_idx == \"HW\": return super()._get_zone(zone_idx, sensor=sensor, **kwargs) if int(zone_idx, 16) >= self._gwy.config[MAX_ZONES]:",
"_LOGGER.debug( \"Testable zones: %s (unique/non-null temps & sensorless)\", testable_zones, ) _LOGGER.debug( \"Testable sensors:",
"None self._heat_demand = None self._htg_control = None def __repr__(self) -> str: return f\"{self._ctl.id}",
"[d for d in self._ctl.devices if d._domain_id == \"FC\"] return htg_control[0] if len(htg_control)",
"schema[\"devices\"] = {d.id: d.device_info for d in sorted(self._ctl.devices)} return schema @property def params(self)",
"if discover_flag & DISCOVER_STATUS: self._send_cmd(\"0006\") def _handle_msg(self, msg, prev_msg=None): def OUT_find_zone_sensors() -> None:",
"least reliable heater = None if this.code == \"3220\" and this.verb == \"RQ\":",
"@property def relay_failsafes(self) -> Optional[dict]: # 0009 if self._relay_failsafes: return {} # failsafe_enabled",
"{ d.id: d.schema for d in sorted(self._ctl.devices) if d.type == \"02\" }, }",
"# if msg.code == \"000A\": # zone._zone_config = zone_dict # elif msg.code ==",
"\"remaining_seconds\") if secs is None or msg.dtm > prev_msg.dtm + td(seconds=secs): return #",
"002 00C8 # 09:04:02.667 045 I --- 01:145038 --:------ 01:145038 3B00 002 FCC8",
"to be useful. \"\"\" # 18:14:14.025 066 RQ --- 01:078710 10:067219 --:------ 3220",
"# # TODO: opentherm: 1FD4, 22D9, 3220 # if discover_flag & DISCOVER_PARAMS: #",
"if self._dhw else None @property def schema(self) -> dict: assert ATTR_DHW_SYSTEM not in",
"temp during last cycle ] if _LOGGER.isEnabledFor(logging.DEBUG): _LOGGER.debug( \"Testable zones: %s (unique/non-null temps",
"RQ (no RP) *to a 13:* (3x/60min) 3. The 3B00 I/I exchange between",
"\"3150\" and msg.verb in (\" I\", \"RP\"): if \"domain_id\" in msg.payload and msg.payload[\"domain_id\"]",
"elif msg.payload[\"domain_id\"] == \"FC\": device = self.heating_control else: device = None if False",
"\"RP\"): # this is a special case self._system_mode = msg @property def system_mode(self)",
"RFG100 self._send_cmd(\"0005\", payload=f\"00{zone_type}\") for zone_type in (\"00\", \"04\", \"0C\", \"0F\", \"10\") ] if",
"self._gwy.send_cmd(cmd) # for zone in self.zones: # zone._discover(discover_flags=DISCOVER_PARAMS) if msg.code in (\"000A\", \"2309\",",
"and msg.verb in (\" I\", \"RP\"): # this is a special case self._system_mode",
"== \"3B00\" and this.verb == \" I\" and prev is not None: if",
"= {d.id: d.status for d in sorted(self._ctl.devices)} return status class System(StoredHw, SysDatetime, SystemBase):",
"return htg_control[0] if len(htg_control) == 1 else None # HACK for 10: def",
"= None self._heat_demand = None self._htg_control = None def __repr__(self) -> str: return",
"in matching_sensors], ) if len(matching_sensors) == 1: _LOGGER.debug(\" - matched sensor: %s\", matching_sensors[0].id)",
"as a sensor... if len(matching_sensors) == 0: _LOGGER.debug(\" - matched sensor: %s (by",
"1FD4, 22D9, 3220 # if discover_flag & DISCOVER_PARAMS: # for domain_id in range(0xF8,",
"# 2E04 return self._msg_payload(self._system_mode) def set_mode(self, system_mode=None, until=None) -> Task: \"\"\"Set a system",
"10A0: RQ/07/01, RP/01/07: can get both parent controller & DHW sensor # 047",
"006 00181F0003E4 # 062 RP --- 01:102458 07:030741 --:------ 10A0 006 0018380003E8 #",
"d in sorted(self._ctl.devices) if d.type == \"02\" }, } @property def status(self) ->",
"(not-None) temperature matching_sensors = [ s for s in testable_sensors if s.temperature ==",
"more authorative. The RQ is initiated by the DHW, so is not authorative.",
"d in kwargs[\"actuators\"] if d not in zone.devices]: zone.devices.append(device) zone.device_by_id[device.id] = device if",
"and DHW sensor, if any (DHW relays in DHW) self._send_cmd(\"000C\", payload=dev_type) for dev_type",
"(sole remaining) zone %s, temp: %s\", zone_idx, temp) # want to avoid complexity",
"to find a controller's heat relay (in order of reliability): 1. The 3220",
"SystemBase): # , SysFaultLog \"\"\"The Controller class.\"\"\" def __init__(self, gwy, ctl, **kwargs) ->",
"allocated if len([z for z in self.zones if z.sensor is None]) != 1:",
"a 13: (TPI cycle rate, usu. 6x/hr) Data from the CTL is considered",
"status[ATTR_HTG_SYSTEM] # TODO: removeme # status[ATTR_HTG_SYSTEM][ATTR_HTG_CONTROL] = ( # self.heating_control.status if self.heating_control else",
"bool(prev_msg.code == \"0004\") # else zone_deleted # elif msg.code == \"30C9\" and isinstance(msg.payload,",
"@property def params(self) -> dict: assert ATTR_DHW_SYSTEM not in super().params # TODO: removeme",
".command import Command, FaultLog, Priority from .const import ( ATTR_DEVICES, DEVICE_HAS_ZONE_SENSOR, DISCOVER_ALL, DISCOVER_PARAMS,",
"== \"30C9\" and isinstance(msg.payload, list): # msg.is_array: # find_zone_sensors() def _get_zone(self, zone_idx, sensor=None,",
"--:------ 3220 005 0000050000 # 18:14:14.446 065 RP --- 10:067219 01:078710 --:------ 3220",
"2E04 return self._msg_payload(self._system_mode) def set_mode(self, system_mode=None, until=None) -> Task: \"\"\"Set a system mode",
"system mode self._gwy.send_cmd(Command.get_system_mode(self.id)) def _handle_msg(self, msg, prev_msg=None): super()._handle_msg(msg) if msg.code == \"2E04\" and",
"heat relay (in order of reliability): 1. The 3220 RQ/RP *to/from a 10:*",
"# self._prev_30c9 = None # OUT: used to discover zone sensors def _discover(self,",
"[d.id for d in self._ctl.devices if not d._domain_id and d.type != \"02\"] )",
"assert ATTR_HTG_SYSTEM in status # TODO: removeme # assert ATTR_HTG_CONTROL not in status[ATTR_HTG_SYSTEM]",
"self.zone_by_idx: raise LookupError(f\"Duplicated zone: {zone_idx} for {self}\") zone = Zone(self, zone_idx) if not",
"def relay_demands(self) -> Optional[dict]: # 0008 if self._relay_demands: return { k: v.payload[\"relay_demand\"] for",
"msg @property def datetime(self) -> Optional[str]: return self._msg_payload(self._datetime, \"datetime\") # TODO: make a",
"prev.verb == this.verb: if this.src is self and prev.src.type == \"13\": heater =",
"set non-PermanentOverride zones to FollowSchedule.\"\"\" return self.set_mode(SystemMode.AUTO) def reset_mode(self) -> Task: \"\"\"Revert system",
"zones to FollowSchedule.\"\"\" return self.set_mode(SystemMode.RESET) @property def params(self) -> dict: params = super().params",
"13:237335 --:------ 3EF0 001 00 # 06:49:07.468 045 RQ --- 01:145038 13:237335 --:------",
"self._zone is not None: return # the controller has already been allocated if",
"assert ATTR_DHW_SYSTEM not in super().params # TODO: removeme return {**super().params, ATTR_DHW_SYSTEM: self.dhw.params if",
"dt.now() # while not self._schedule_done: # await asyncio.sleep(TIMER_SHORT_SLEEP) # if dt.now() > time_start",
"set schedule\") # self._api_lock.release() # async def get_datetime(self) -> str: # wait for",
"is None: zone = create_zone(zone_idx) if kwargs.get(\"zone_type\"): zone._set_zone_type(kwargs[\"zone_type\"]) if kwargs.get(\"actuators\"): # TODO: check",
"no sensor (from state): %s\", testable_zones, ) if not testable_zones: return # no",
"sensor for a zone, but unfortunately it does not announce its sensor temperatures.",
"z in msg.payload if z not in prev_msg.payload } # zones with changed",
"matching algorithm... for zone_idx, temp in testable_zones.items(): # TODO: when sensors announce temp,",
"**kwargs) -> None: super().__init__(gwy, ctl, **kwargs) self._heat_demands = {} self._relay_demands = {} self._relay_failsafes",
"timedelta as td from threading import Lock from typing import List, Optional from",
"def set_datetime(self, dtm: dt) -> str: # wait for the I/313F # await",
"2. Use sensor temp matching - non-deterministic Data from the CTL is considered",
"& DISCOVER_PARAMS: # for domain_id in range(0xF8, 0x100): # self._send_cmd(\"0009\", payload=f\"{domain_id:02X}00\") if discover_flag",
"is considered 'authorative'. The 1FC9 RQ/RP exchange to/from a CTL is too rare",
"= [d for d in self._ctl.devices if d._domain_id == \"FC\"] return htg_control[0] if",
"# return json.dumps({self._ctl.id: self.schema}) def _discover(self, discover_flag=DISCOVER_ALL) -> None: # super()._discover(discover_flag=discover_flag) if discover_flag",
"msg.code == \"0005\" and prev_msg is not None: # zone_added = bool(prev_msg.code ==",
"Command.set_system_mode(self.id, system_mode=system_mode, until=until) return self._gwy.send_cmd(cmd) def set_auto(self) -> Task: \"\"\"Revert system to Auto,",
"z.params for z in self._zones}} @property def status(self) -> dict: assert ATTR_ZONES not",
"status(self) -> dict: \"\"\"Return the system's current state.\"\"\" status = super().status assert ATTR_HTG_SYSTEM",
"List, Optional from .command import Command, FaultLog, Priority from .const import ( ATTR_DEVICES,",
"(\" I\", \"RP\"): if \"domain_id\" in msg.payload: self._relay_demands[msg.payload[\"domain_id\"]] = msg if msg.payload[\"domain_id\"] ==",
"Command, FaultLog, Priority from .const import ( ATTR_DEVICES, DEVICE_HAS_ZONE_SENSOR, DISCOVER_ALL, DISCOVER_PARAMS, DISCOVER_SCHEMA, DISCOVER_STATUS,",
"# changed temp during last cycle ] if _LOGGER.isEnabledFor(logging.DEBUG): _LOGGER.debug( \"Testable zones: %s",
"(\"3B00\",): # 3EF0, 3EF1 # # for payload in (\"0000\", \"00\", \"F8\", \"F9\",",
"(unique/non-null temps & sensorless)\", testable_zones, ) _LOGGER.debug( \"Testable sensors: %s (non-null temps &",
"\"\"\"The most basic controllers - a generic controller (e.g. ST9420C).\"\"\" # 0008|0009|1030|1100|2309|3B00 def",
"schema(self) -> dict: \"\"\"Return the system's schema.\"\"\" schema = {ATTR_CONTROLLER: self._ctl.id, ATTR_HTG_SYSTEM: {}}",
"type (RAD, UFH, VAL, MIX, ELE) self._send_cmd(\"0005\", payload=f\"00{zone_type}\") for zone_type in (\"08\", \"09\",",
"\"1100\", \"3B00\"): assert False, msg.code @property def heat_demands(self) -> Optional[dict]: # 3150 if",
"# TODO: removeme status[\"fault_log\"] = self._fault_log.fault_log status[\"last_fault\"] = self._msgz[\" I\"].get(\"0418\") return status class",
"schema = {ATTR_CONTROLLER: self._ctl.id, ATTR_HTG_SYSTEM: {}} assert ATTR_HTG_SYSTEM in schema # TODO: removeme",
"create_zone(zone_idx) if kwargs.get(\"zone_type\"): zone._set_zone_type(kwargs[\"zone_type\"]) if kwargs.get(\"actuators\"): # TODO: check not an address before",
"This leaves only a process of exclusion as a means to determine which",
"TODO: removeme assert \"language\" not in params[ATTR_HTG_SYSTEM] # TODO: removeme params[ATTR_HTG_SYSTEM][\"language\"] = self.language",
"k, v in changed_zones.items() if k != z] + [None] } # ...with",
"for dev_type in (\"000D\", \"000F\") # CODE_000C_DEVICE_TYPE # for dev_type, description in CODE_000C_DEVICE_TYPE.items()",
"The 1FC9 RQ/RP exchange to/from a CTL is too rare to be useful.",
"self.set_mode(SystemMode.RESET) @property def params(self) -> dict: params = super().params assert ATTR_HTG_SYSTEM in params",
"--- 01:145038 --:------ 01:145038 1F41 006 000002FFFFFF sensor = None if this.code ==",
"zone_idx in self.zone_by_idx: cmd = Command.get_zone_mode(self.id, zone_idx, priority=Priority.LOW) self._gwy.send_cmd(cmd) # for zone in",
"a special case self._system_mode = msg @property def system_mode(self) -> Optional[dict]: # 2E04",
"status[ATTR_HTG_SYSTEM][\"heat_demand\"] = self.heat_demand status[ATTR_DEVICES] = {d.id: d.status for d in sorted(self._ctl.devices)} return status",
"assert ATTR_HTG_SYSTEM in status # TODO: removeme assert \"datetime\" not in status[ATTR_HTG_SYSTEM] #",
"in (\"3220\", \"3B00\", \"3EF0\"): # self.heating_control is None and # find_htg_relay(msg, prev=prev_msg) def",
"3150/FC if self._heat_demand: return self._heat_demand[\"heat_demand\"] @property def is_calling_for_heat(self) -> Optional[bool]: \"\"\"Return True is",
"[xxx(z) for z in msg.payload] # else: # xxx(msg.payload) if msg.code in (\"000A\",",
"discover zone sensors def _discover(self, discover_flag=DISCOVER_ALL) -> None: super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_SCHEMA:",
"see if we can allocate the controller as a sensor... if self._zone is",
"# this is a special case self._system_mode = msg @property def system_mode(self) ->",
"get_datetime(self) -> str: # wait for the RP/313F # await self.wait_for(Command(\"313F\", verb=\"RQ\")) #",
"_LOGGER.debug( \"Testable sensors: %s (non-null temps & orphans or zoneless)\", {d.id: d.temperature for",
"-> dict: assert ATTR_DHW_SYSTEM not in super().status # TODO: removeme return {**super().status, ATTR_DHW_SYSTEM:",
"device: return raise CorruptStateError( f\"{ATTR_HTG_CONTROL} shouldn't change: {self._htg_control} to {device}\" ) # if",
"ATTR_ZONES not in super().params # TODO: removeme return {**super().params, ATTR_ZONES: {z.idx: z.params for",
"from .exceptions import CorruptStateError, ExpiredCallbackError from .schema import ( ATTR_CONTROLLER, ATTR_DHW_SYSTEM, ATTR_HTG_CONTROL, ATTR_HTG_SYSTEM,",
"(\"0004\", \"000C\", \"2E04\", \"313F\") # TODO: WIP RQ_UNSUPPORTED = (\"xxxx\",) # 10E0? def",
"== this.verb: if this.src is self and prev.src.type == \"13\": heater = prev.src",
"} @property def params(self) -> dict: assert ATTR_UFH_SYSTEM not in super().params # TODO:",
"-> None: super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_STATUS: self._gwy.send_cmd(Command.get_system_time(self.id)) # self._send_cmd(\"313F\") def _handle_msg(self, msg,",
"the stored HW this system (if any). There is only 2 ways to",
"None: if self._htg_control is device: return raise CorruptStateError( f\"{ATTR_HTG_CONTROL} shouldn't change: {self._htg_control} to",
"self._system_mode = msg @property def system_mode(self) -> Optional[dict]: # 2E04 return self._msg_payload(self._system_mode) def",
"\"0005\" and prev_msg is not None: # zone_added = bool(prev_msg.code == \"0004\") #",
"(1x/4h) - reliable 2. Use sensor temp matching - non-deterministic Data from the",
"find a controller's DHW sensor: 1. The 10A0 RQ/RP *from/to a 07:* (1x/4h)",
"d._msgs[\"30C9\"].dtm > prev_msg.dtm # changed temp during last cycle ] if _LOGGER.isEnabledFor(logging.DEBUG): _LOGGER.debug(",
"set_mode(self, system_mode=None, until=None) -> Task: \"\"\"Set a system mode for a specified duration,",
"# self._send_cmd(code, payload=payload) # # TODO: opentherm: 1FD4, 22D9, 3220 # if discover_flag",
"def wait_for(self, cmd, callback): # self._api_lock.acquire() # self._send_cmd(\"313F\", verb=\"RQ\", callback=callback) # time_start =",
"if zone_idx in self.zone_by_idx: raise LookupError(f\"Duplicated zone: {zone_idx} for {self}\") zone = Zone(self,",
"return status class System(StoredHw, SysDatetime, SystemBase): # , SysFaultLog \"\"\"The Controller class.\"\"\" def",
"and isinstance(msg.payload, list): pass class Chronotherm(Evohome): def __repr__(self) -> str: return f\"{self._ctl.id} (chronotherm)\"",
"self._prev_30c9 = None # OUT: used to discover zone sensors def _discover(self, discover_flag=DISCOVER_ALL)",
"zone.device_by_id[device.id] = device if sensor is not None: zone._set_sensor(sensor) return zone @property def",
"= { z[\"zone_idx\"]: z[\"temperature\"] for z in msg.payload if z not in prev_msg.payload",
"self.heating_control else: device = None if False and device is not None: #",
"in (\"1F41\",): # dhw_mode pass def _get_zone(self, zone_idx, sensor=None, **kwargs) -> DhwZone: \"\"\"Return",
"_handle_msg(self, msg, prev_msg=None): \"\"\"Eavesdrop packets, or pairs of packets, to maintain the system",
"assert ATTR_HTG_SYSTEM in params # TODO: removeme # devices don't have params #",
"assert ATTR_UFH_SYSTEM not in super().schema # TODO: removeme return { **super().schema, ATTR_UFH_SYSTEM: {",
"6x/hr) Data from the CTL is considered 'authorative'. The 1FC9 RQ/RP exchange to/from",
"def _handle_msg(self, msg) -> bool: super()._handle_msg(msg) # def xxx(zone_dict): # zone = self.zone_by_idx[zone_dict.pop(\"zone_idx\")]",
"d in sorted(self._ctl.devices)} return schema @property def params(self) -> dict: \"\"\"Return the system's",
"matched sensor: %s (by exclusion)\", self._ctl.id) zone = self.zone_by_idx[zone_idx] zone._set_sensor(self) zone.sensor._set_ctl(self) _LOGGER.debug(\"System state",
"TypeError(f\"stored_hw can't be: {dhw}\") if self._dhw is not None: if self._dhw is dhw:",
"for d in sorted(self._ctl.devices) if d.type == \"02\" }, } @property def params(self)",
"for d in kwargs[\"actuators\"] if d not in zone.devices]: zone.devices.append(device) zone.device_by_id[device.id] = device",
"\"11\") # CODE_0005_ZONE_TYPE ] [ # 0005: find any others - as per",
"msg.payload if z not in prev_msg.payload } # zones with changed temps _LOGGER.debug(\"Changed",
"pass # if isinstance(msg.payload, list): # elif msg.code == \"000C\": # self._msgs[f\"{msg.code}\"] =",
"\"datetime\") # TODO: make a dt object # def wait_for(self, cmd, callback): #",
"if self._heat_demand: return self._heat_demand[\"heat_demand\"] @property def is_calling_for_heat(self) -> Optional[bool]: \"\"\"Return True is the",
"zone_dict # elif msg.code == \"2309\": # zone._temp = zone_dict # elif msg.code",
"testable_zones: return # no testable zones testable_sensors = [ d for d in",
"status # TODO: removeme assert \"datetime\" not in status[ATTR_HTG_SYSTEM] # TODO: removeme status[ATTR_HTG_SYSTEM][\"datetime\"]",
"if msg.code in (\"000A\", \"2309\", \"30C9\") and not isinstance(msg.payload, list): pass else: super()._handle_msg(msg)",
"# TODO: check not an address before implmenting for device in [d for",
"non-PermanentOverride zones to FollowSchedule.\"\"\" return self.set_mode(SystemMode.AUTO) def reset_mode(self) -> Task: \"\"\"Revert system to",
"assert \"devices\" not in schema # TODO: removeme # schema[\"devices\"] = {d.id: d.device_info",
"== \"0008\" and msg.verb in (\" I\", \"RP\"): if \"domain_id\" in msg.payload: self._relay_demands[msg.payload[\"domain_id\"]]",
"ways to to find a controller's DHW sensor: 1. The 10A0 RQ/RP *from/to",
"01:102458 07:030741 --:------ 10A0 006 0018380003E8 # 1260: I/07: can't get which parent",
"} # ...with unique (non-null) temps, and no sensor _LOGGER.debug( \" - with",
"if zone._temp is None: # return # TODO: should have a (not-None) temperature",
"msg.code in (\"000A\",) and isinstance(msg.payload, list): for zone_idx in self.zone_by_idx: cmd = Command.get_zone_mode(self.id,",
"\"domain_id\" in msg.payload: self._relay_demands[msg.payload[\"domain_id\"]] = msg if msg.payload[\"domain_id\"] == \"F9\": device = self.dhw.heating_valve",
"# elif msg.code == \"0005\" and prev_msg is not None: # zone_added =",
"RP to: 0004 if discover_flag & DISCOVER_STATUS: self._send_cmd(\"1F09\") class Programmer(Evohome): def __repr__(self) ->",
"TODO: removeme # devices don't have params # assert ATTR_HTG_CONTROL not in params[ATTR_HTG_SYSTEM]",
"{ z: t for z, t in changed_zones.items() if self.zone_by_idx[z].sensor is None }",
"10E0? def __repr__(self) -> str: return f\"{self._ctl.id} (hometronics)\" def _discover(self, discover_flag=DISCOVER_ALL) -> None:",
"None]) != 1: return # no single zone without a sensor testable_zones =",
"from asyncio import Task from datetime import timedelta as td from threading import",
"msg.verb in (\" I\", \"RP\"): self._language = msg @property def language(self) -> Optional[str]:",
"td from threading import Lock from typing import List, Optional from .command import",
"= Command.get_zone_mode(self.id, zone_idx, priority=Priority.LOW) self._gwy.send_cmd(cmd) # for zone in self.zones: # zone._discover(discover_flags=DISCOVER_PARAMS) if",
"self.heating_control else None ) return params @property def status(self) -> dict: \"\"\"Return the",
"Optional[dict]: # 0008 if self._relay_demands: return { k: v.payload[\"relay_demand\"] for k, v in",
"self.dhw.sensor is None and # if self.dhw.sensor is None: # find_dhw_sensor(msg) pass elif",
"= Lock() self.zone_lock_idx = None # self._prev_30c9 = None # OUT: used to",
"import Task from datetime import timedelta as td from threading import Lock from",
"def xxx(zone_dict): # zone = self.zone_by_idx[zone_dict.pop(\"zone_idx\")] # if msg.code == \"000A\": # zone._zone_config",
"zone._set_dhw_valve(kwargs[\"htg_valve\"]) if sensor is not None: zone._set_dhw_sensor(sensor) return zone @property def dhw(self) ->",
"self and this.dst.type == \"07\": sensor = this.dst if sensor is not None:",
"TODO: removeme return { **super().params, ATTR_UFH_SYSTEM: { d.id: d.params for d in sorted(self._ctl.devices)",
"failsafe_enabled @property def status(self) -> dict: \"\"\"Return the system's current state.\"\"\" status =",
"== 0: _LOGGER.debug(\" - no matching sensor (uses CTL?)\") else: _LOGGER.debug(\" - multiple",
"( ATTR_CONTROLLER, ATTR_DHW_SYSTEM, ATTR_HTG_CONTROL, ATTR_HTG_SYSTEM, ATTR_ORPHANS, ATTR_UFH_SYSTEM, ATTR_ZONES, DISABLE_DISCOVERY, MAX_ZONES, ) from .zones",
"if msg.code == \"0008\": self._relay_demands[idx] = msg elif msg.code == \"0009\": self._relay_failsafes[idx] =",
"return {k: v.payload[\"heat_demand\"] for k, v in self._heat_demands.items()} @property def relay_demands(self) -> Optional[dict]:",
"testable_sensors if s.temperature == temp and s._zone in (zone_idx, None) ] _LOGGER.debug( \"",
"import logging from asyncio import Task from datetime import timedelta as td from",
"The temperature of each zone is reliably known (30C9 array), but the sensor",
"[s.id for s in matching_sensors], ) if len(matching_sensors) == 1: _LOGGER.debug(\" - matched",
"no matching sensor (uses CTL?)\") else: _LOGGER.debug(\" - multiple sensors: %s\", matching_sensors) _LOGGER.debug(\"System",
"\"313F\") # TODO: WIP RQ_UNSUPPORTED = (\"xxxx\",) # 10E0? def __repr__(self) -> str:",
"TODO: W self._datetime = msg @property def datetime(self) -> Optional[str]: return self._msg_payload(self._datetime, \"datetime\")",
"def datetime(self) -> Optional[str]: return self._msg_payload(self._datetime, \"datetime\") # TODO: make a dt object",
"msg.verb in (\" I\", \"RP\"): if \"domain_id\" in msg.payload and msg.payload[\"domain_id\"] == \"FC\":",
"*args, **kwargs) -> None: super().__init__(*args, **kwargs) self.zones = [] self.zone_by_idx = {} #",
"def status(self) -> dict: assert ATTR_ZONES not in super().status # TODO: removeme return",
"assert ATTR_UFH_SYSTEM not in super().status # TODO: removeme return { **super().status, ATTR_UFH_SYSTEM: {",
"\"00\", \"F8\", \"F9\", \"FA\", \"FB\", \"FC\", \"FF\"): # # self._send_cmd(code, payload=payload) # #",
"in schema[ATTR_HTG_SYSTEM] # TODO: removeme schema[ATTR_ORPHANS] = sorted( [d.id for d in self._ctl.devices",
"= {ATTR_HTG_SYSTEM: {}} assert ATTR_HTG_SYSTEM in status # TODO: removeme # assert ATTR_HTG_CONTROL",
"z.sensor is None]) != 1: return # no single zone without a sensor",
"-> None: super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_STATUS: # self._send_cmd(\"2E04\", payload=\"FF\") # system mode",
"is self and this.dst.type == \"10\": heater = this.dst elif this.code == \"3EF0\"",
"parent controller & DHW sensor # 047 RQ --- 07:030741 01:102458 --:------ 10A0",
"if self.dhw is None: self._get_zone(\"FA\") self.dhw._set_sensor(sensor) super()._handle_msg(msg) if msg.code in (\"10A0\", \"1260\"): #",
"01:145038 13:237335 --:------ 3EF0 001 00 # 09:03:59.693 051 I --- 13:237335 --:------",
"def params(self) -> dict: \"\"\"Return the system's configuration.\"\"\" params = {ATTR_HTG_SYSTEM: {}} assert",
"CorruptStateError(\"DHW shouldn't change: {self._dhw} to {dhw}\") if self._dhw is None: # self._gwy._get_device(xxx) #",
"gwy, ctl, **kwargs) -> None: # _LOGGER.debug(\"Creating a System: %s (%s)\", dev_addr.id, self.__class__)",
"3EF0, 3EF1 # # for payload in (\"0000\", \"00\", \"F8\", \"F9\", \"FA\", \"FB\",",
"\"RP\"): # TODO: W self._datetime = msg @property def datetime(self) -> Optional[str]: return",
"this.dst elif this.code == \"3B00\" and this.verb == \" I\" and prev is",
"== \"10A0\" and this.verb == \"RP\": if this.src is self and this.dst.type ==",
"status class SysDatetime: # 313F def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs)",
"and no sensor _LOGGER.debug( \" - with unique/non-null temps (from 30C9), no sensor",
"self._ctl.id) payload = kwargs.pop(\"payload\", \"00\") super()._send_cmd(code, dest, payload, **kwargs) @property def devices(self) ->",
"_LOGGER.debug(\" - matched sensor: %s\", matching_sensors[0].id) zone = self.zone_by_idx[zone_idx] zone._set_sensor(matching_sensors[0]) zone.sensor._set_ctl(self) elif len(matching_sensors)",
"None @property def schema(self) -> dict: assert ATTR_DHW_SYSTEM not in super().schema # TODO:",
"__init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self._system_mode = None def _discover(self, discover_flag=DISCOVER_ALL)",
"-> None: super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_STATUS: self._send_cmd(\"1F09\") def _handle_msg(self, msg) -> bool:",
"assert ATTR_DHW_SYSTEM not in super().status # TODO: removeme return {**super().status, ATTR_DHW_SYSTEM: self.dhw.status if",
"temp) # want to avoid complexity of z._temp # zone = self.zone_by_idx[zone_idx] #",
"in msg.payload: idx = msg.payload[\"domain_id\"] if msg.code == \"0008\": self._relay_demands[idx] = msg elif",
"in (\"10\", \"13\"): heater = this.dst elif this.code == \"3B00\" and this.verb ==",
"in self._relay_demands.items() } @property def relay_failsafes(self) -> Optional[dict]: # 0009 if self._relay_failsafes: return",
"both parent controller & DHW sensor # 047 RQ --- 07:030741 01:102458 --:------",
"return self._msg_payload(self._system_mode) def set_mode(self, system_mode=None, until=None) -> Task: \"\"\"Set a system mode for",
"self._send_cmd(\"0005\", payload=f\"00{zone_type}\") for zone_type in (\"00\", \"04\", \"0C\", \"0F\", \"10\") ] if discover_flag",
"self.zones: # zone._discover(discover_flags=DISCOVER_PARAMS) if msg.code in (\"000A\", \"2309\", \"30C9\"): pass # if isinstance(msg.payload,",
"super()._get_zone(zone_idx, sensor=sensor, **kwargs) if int(zone_idx, 16) >= self._gwy.config[MAX_ZONES]: raise ValueError(f\"Unknown zone_idx/domain_id: {zone_idx}\") zone",
"in schema[ATTR_HTG_SYSTEM] # TODO: removeme schema[ATTR_HTG_SYSTEM][ATTR_HTG_CONTROL] = ( self.heating_control.id if self.heating_control else None",
"zone if zone_idx == \"HW\": return super()._get_zone(zone_idx, sensor=sensor, **kwargs) if int(zone_idx, 16) >=",
"1FC9 RQ/RP exchange to/from a CTL is too rare to be useful. \"\"\"",
"payload=f\"00{zone_type}\") for zone_type in (\"08\", \"09\", \"0A\", \"0B\", \"11\") # CODE_0005_ZONE_TYPE ] [",
"& DHW sensor # 047 RQ --- 07:030741 01:102458 --:------ 10A0 006 00181F0003E4",
"kwargs.get(\"zone_type\"): zone._set_zone_type(kwargs[\"zone_type\"]) if kwargs.get(\"actuators\"): # TODO: check not an address before implmenting for",
"def _get_zone(self, zone_idx, sensor=None, **kwargs) -> DhwZone: \"\"\"Return a DHW zone (will create",
"-> DhwZone: if self.dhw: raise LookupError(f\"Duplicate stored HW: {zone_idx}\") dhw = self._dhw =",
"{**super().params, ATTR_ZONES: {z.idx: z.params for z in self._zones}} @property def status(self) -> dict:",
"# class Evohome(System): # evohome \"\"\"The Evohome system - some controllers are evohome-compatible.\"\"\"",
"self._relay_failsafes = {} def __repr__(self) -> str: return f\"{self._ctl.id} (system)\" def _handle_msg(self, msg)",
"sensors: %s (non-null temps & orphans or zoneless)\", {d.id: d.temperature for d in",
"set_datetime(self, dtm: dt) -> str: # wait for the I/313F # await self.wait_for(Command(\"313F\",",
"super().__init__(*args, **kwargs) self._dhw = None def _discover(self, discover_flag=DISCOVER_ALL) -> None: super()._discover(discover_flag=discover_flag) if discover_flag",
"class Evohome(SysLanguage, SysMode, MultiZone, UfhSystem, System): # evohome # class Evohome(System): # evohome",
"the CTL is considered more authorative. The RQ is initiated by the DHW,",
"# self._send_cmd(\"313F\") def _handle_msg(self, msg, prev_msg=None): super()._handle_msg(msg) if msg.code == \"313F\" and msg.verb",
"if \"domain_id\" in msg.payload: self._relay_demands[msg.payload[\"domain_id\"]] = msg if msg.payload[\"domain_id\"] == \"F9\": device =",
"super()._handle_msg(msg) if msg.code == \"2E04\" and msg.verb in (\" I\", \"RP\"): # this",
"not: configured_zones # will RP to: 0004 if discover_flag & DISCOVER_STATUS: self._send_cmd(\"1F09\") class",
"each zone's sensor by matching zone/sensor temperatures. The temperature of each zone is",
"also set a zone's sensor, and zone_type, and actuators. \"\"\" def create_zone(zone_idx) ->",
"self._datetime = None def _discover(self, discover_flag=DISCOVER_ALL) -> None: super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_STATUS:",
"wait_for(self, cmd, callback): # self._api_lock.acquire() # self._send_cmd(\"313F\", verb=\"RQ\", callback=callback) # time_start = dt.now()",
"None: self._htg_control = device device._set_parent(self, domain=\"FC\") @property def tpi_params(self) -> Optional[float]: # 1100",
"= self.zone_by_idx[zone_dict.pop(\"zone_idx\")] # if msg.code == \"000A\": # zone._zone_config = zone_dict # elif",
"if not self._htg_control: return if self._htg_control.actuator_state: return True @property def schema(self) -> dict:",
"__repr__(self) -> str: return f\"{self._ctl.id} (hometronics)\" def _discover(self, discover_flag=DISCOVER_ALL) -> None: # super()._discover(discover_flag=discover_flag)",
"temps # 045 I --- 07:045960 --:------ 07:045960 1260 003 000911 # 1F41:",
"def status(self) -> dict: \"\"\"Return the system's current state.\"\"\" status = super().status assert",
"the system's schema.\"\"\" schema = {ATTR_CONTROLLER: self._ctl.id, ATTR_HTG_SYSTEM: {}} assert ATTR_HTG_SYSTEM in schema",
"as a sensor. \"\"\" prev_msg, self._prev_30c9 = self._prev_30c9, msg if prev_msg is None:",
"- no matching sensor (uses CTL?)\") else: _LOGGER.debug(\" - multiple sensors: %s\", matching_sensors)",
"\"3EF0\" and this.verb == \"RQ\": if this.src is self and this.dst.type in (\"10\",",
"or zoneless)\", {d.id: d.temperature for d in testable_sensors}, ) if testable_sensors: # the",
"in status # TODO: removeme assert \"datetime\" not in status[ATTR_HTG_SYSTEM] # TODO: removeme",
"from the last cycle _LOGGER.debug(\"System state (before): %s\", self) changed_zones = { z[\"zone_idx\"]:",
"for zone_type in (\"00\", \"04\", \"0C\", \"0F\", \"10\") ] if discover_flag & DISCOVER_STATUS:",
"raise LookupError(f\"Duplicated zone: {zone_idx} for {self}\") zone = Zone(self, zone_idx) if not self._gwy.config[DISABLE_DISCOVERY]:",
"\"02\" }, } class SystemBase(Entity): # 3B00 (multi-relay) \"\"\"The most basic controllers -",
"in DHW) self._send_cmd(\"000C\", payload=dev_type) for dev_type in (\"000D\", \"000F\") # CODE_000C_DEVICE_TYPE # for",
"find any others - as per an RFG100 self._send_cmd(\"0005\", payload=f\"00{zone_type}\") for zone_type in",
"mode for a specified duration, or indefinitely.\"\"\" cmd = Command.set_system_mode(self.id, system_mode=system_mode, until=until) return",
"return # no testable zones testable_sensors = [ d for d in self._gwy.devices",
"heater is not None: self._set_htg_control(heater) if msg.code in (\"000A\", \"2309\", \"30C9\") and not",
"\"\"\"The Controller class.\"\"\" def __init__(self, gwy, ctl, **kwargs) -> None: super().__init__(gwy, ctl, **kwargs)",
"-> None: \"\"\"Determine each zone's sensor by matching zone/sensor temperatures. The temperature of",
"for zone in self.zones: # zone._discover(discover_flags=DISCOVER_PARAMS) if msg.code in (\"000A\", \"2309\", \"30C9\"): pass",
"super().status assert ATTR_HTG_SYSTEM in status # TODO: removeme status[ATTR_HTG_SYSTEM][\"heat_demands\"] = self.heat_demands status[ATTR_HTG_SYSTEM][\"relay_demands\"] =",
"dict: assert ATTR_ZONES not in super().schema # TODO: removeme return {**super().schema, ATTR_ZONES: {z.idx:",
"if zone is None: zone = create_zone(zone_idx) if kwargs.get(\"zone_type\"): zone._set_zone_type(kwargs[\"zone_type\"]) if kwargs.get(\"actuators\"): #",
"= self.zone_by_idx.get(zone_idx) if zone is None: zone = create_zone(zone_idx) if kwargs.get(\"zone_type\"): zone._set_zone_type(kwargs[\"zone_type\"]) if",
"matching_sensors[0].id) zone = self.zone_by_idx[zone_idx] zone._set_sensor(matching_sensors[0]) zone.sensor._set_ctl(self) elif len(matching_sensors) == 0: _LOGGER.debug(\" - no",
"(\" I\", \"RP\"): # TODO: W self._datetime = msg @property def datetime(self) ->",
"in (zone_idx, None) ] _LOGGER.debug(\"Testing zone %s, temp: %s\", zone_idx, temp) _LOGGER.debug( \"",
"(1x/1min) 2b. The 3EF0 RQ (no RP) *to a 13:* (3x/60min) 3. The",
"# 14:41:46.631 063 RP --- 10:067219 01:078710 --:------ 3EF0 006 0000100000FF # noqa",
"changed temps during this cycle testable_zones = { z: t for z, t",
"3EF0 001 00 # 09:03:59.693 051 I --- 13:237335 --:------ 13:237335 3B00 002",
"in schema # TODO: removeme assert ATTR_HTG_CONTROL not in schema[ATTR_HTG_SYSTEM] # TODO: removeme",
"\"0009\": self._relay_failsafes[idx] = msg elif msg.code == \"3150\": self._heat_demands[idx] = msg elif msg.code",
"super().schema # TODO: removeme return { **super().schema, ATTR_UFH_SYSTEM: { d.id: d.schema for d",
"status(self) -> dict: assert ATTR_DHW_SYSTEM not in super().status # TODO: removeme return {**super().status,",
"*args, **kwargs) -> None: super().__init__(*args, **kwargs) self._fault_log = FaultLog(self._ctl) def _discover(self, discover_flag=DISCOVER_ALL) ->",
"return f\"{self._ctl.id} (sundial)\" SYSTEM_CLASSES = { SystemType.CHRONOTHERM: Chronotherm, SystemType.EVOHOME: Evohome, SystemType.HOMETRONICS: Hometronics, SystemType.PROGRAMMER:",
"if any (DHW relays in DHW) self._send_cmd(\"000C\", payload=dev_type) for dev_type in (\"000D\", \"000F\")",
"for d in sorted(self._ctl.devices) if d.type == \"02\" }, } class SystemBase(Entity): #",
"__repr__(self) -> str: return f\"{self._ctl.id} (system)\" def _handle_msg(self, msg) -> bool: super()._handle_msg(msg) if",
"# TODO: where to put this? # assert \"devices\" not in schema #",
"self.wait_for(Command(\"313F\", verb=\" W\", payload=f\"00{dtm_to_hex(dtm)}\")) # return self.datetime @property def status(self) -> dict: status",
"def dhw_sensor(self) -> Device: return self._dhw._dhw_sensor if self._dhw else None @property def hotwater_valve(self)",
"dest = kwargs.pop(\"dest_addr\", self._ctl.id) payload = kwargs.pop(\"payload\", \"00\") super()._send_cmd(code, dest, payload, **kwargs) @property",
"None # OUT: used to discover zone sensors def _discover(self, discover_flag=DISCOVER_ALL) -> None:",
"07:* (1x/4h) - reliable 2. Use sensor temp matching - non-deterministic Data from",
"(non-null) temps, and no sensor _LOGGER.debug( \" - with unique/non-null temps (from 30C9),",
"30.0 # NOTE: these may be removed MAX_SETPOINT = 85.0 DEFAULT_SETPOINT = 50.0",
"if len(matching_sensors) == 1: _LOGGER.debug(\" - matched sensor: %s\", matching_sensors[0].id) zone = self.zone_by_idx[zone_idx]",
"str: # TODO: WIP # return json.dumps({self._ctl.id: self.schema}) def _discover(self, discover_flag=DISCOVER_ALL) -> None:",
"want to avoid complexity of z._temp # zone = self.zone_by_idx[zone_idx] # if zone._temp",
"& DISCOVER_STATUS: pass def _handle_msg(self, msg, prev_msg=None): \"\"\"Eavesdrop packets, or pairs of packets,",
"the DHW, so is not authorative. The I/1260 is not to/from a controller,",
"no sensor _LOGGER.debug( \" - with unique/non-null temps (from 30C9), no sensor (from",
"zone.devices.append(device) zone.device_by_id[device.id] = device if sensor is not None: zone._set_sensor(sensor) return zone @property",
"def params(self) -> dict: assert ATTR_ZONES not in super().params # TODO: removeme return",
".devices import Device, Entity from .exceptions import CorruptStateError, ExpiredCallbackError from .schema import (",
"self.zone_lock_idx = None # self._prev_30c9 = None # OUT: used to discover zone",
"# 0005: find any zones + their type (RAD, UFH, VAL, MIX, ELE)",
"is None } # this will be true if ctl is sensor if",
".const import ( ATTR_DEVICES, DEVICE_HAS_ZONE_SENSOR, DISCOVER_ALL, DISCOVER_PARAMS, DISCOVER_SCHEMA, DISCOVER_STATUS, SystemMode, SystemType, __dev_mode__, )",
"in params[ATTR_HTG_SYSTEM] # TODO: removeme params[ATTR_HTG_SYSTEM][\"language\"] = self.language return params class SysMode: #",
"?also includes it's parent zone matching_sensors = [ s for s in testable_sensors",
"# self.dhw.sensor is None and # if self.dhw.sensor is None: # find_dhw_sensor(msg) pass",
"state (after): %s\", self) # now see if we can allocate the controller",
"LookupError(f\"Duplicate stored HW: {zone_idx}\") dhw = self._dhw = DhwZone(self) if not self._gwy.config[DISABLE_DISCOVERY]: dhw._discover()",
".exceptions import CorruptStateError, ExpiredCallbackError from .schema import ( ATTR_CONTROLLER, ATTR_DHW_SYSTEM, ATTR_HTG_CONTROL, ATTR_HTG_SYSTEM, ATTR_ORPHANS,",
"in msg.payload if z not in prev_msg.payload } # zones with changed temps",
"not in super().status # TODO: removeme return {**super().status, ATTR_DHW_SYSTEM: self.dhw.status if self.dhw else",
"is None and t not in [v for k, v in changed_zones.items() if",
"assert ATTR_ZONES not in super().schema # TODO: removeme return {**super().schema, ATTR_ZONES: {z.idx: z.schema",
"temp) _LOGGER.debug( \" - matching sensor(s): %s (same temp & not from another",
"the CTL as a sensor... if len(matching_sensors) == 0: _LOGGER.debug(\" - matched sensor:",
"single zone without a sensor testable_zones = { z: t for z, t",
"in (\" I\", \"RP\"): if \"domain_id\" in msg.payload and msg.payload[\"domain_id\"] == \"FC\": self._heat_demand",
"def heat_demand(self) -> Optional[float]: # 3150/FC if self._heat_demand: return self._heat_demand[\"heat_demand\"] @property def is_calling_for_heat(self)",
"a zone (will create it if required). Can also set a zone's sensor,",
"temp in testable_zones.items(): # TODO: when sensors announce temp, ?also includes it's parent",
"\"30C9\"): # if isinstance(msg.payload, list): # super()._handle_msg(msg) # [xxx(z) for z in msg.payload]",
"dhw._discover() # discover_flag=DISCOVER_ALL) return dhw if zone_idx != \"HW\": return zone = self.dhw",
"hotwater_valve(self) -> Device: return self._dhw._dhw_valve if self._dhw else None @property def heating_valve(self) ->",
"in range(0xF8, 0x100): # self._send_cmd(\"0009\", payload=f\"{domain_id:02X}00\") if discover_flag & DISCOVER_STATUS: # for domain_id",
"None # self._prev_30c9 = None # OUT: used to discover zone sensors def",
"removeme return {**super().params, ATTR_DHW_SYSTEM: self.dhw.params if self.dhw else {}} @property def status(self) ->",
"payload=\"FC\") # TPI params # # for code in (\"3B00\",): # 3EF0, 3EF1",
"for z in self.zones if z.sensor is None]) != 1: return # no",
"\"0418\", \"1100\", \"3B00\"): assert False, msg.code @property def heat_demands(self) -> Optional[dict]: # 3150",
"this.dst is prev.src.addr def OUT_find_htg_relay(this, prev=None): \"\"\"Discover the heat relay (10: or 13:)",
"system (10: or 13:).\"\"\" if not isinstance(device, Device) or device.type not in (\"10\",",
"if device.evo is not None and device.evo is not self: # raise LookupError",
"**kwargs) self._system_mode = None def _discover(self, discover_flag=DISCOVER_ALL) -> None: super()._discover(discover_flag=discover_flag) if discover_flag &",
"002 FCC8 # note the order: most to least reliable heater = None",
"WIP # return json.dumps({self._ctl.id: self.schema}) def _discover(self, discover_flag=DISCOVER_ALL) -> None: # super()._discover(discover_flag=discover_flag) if",
"# assert ATTR_HTG_CONTROL not in status[ATTR_HTG_SYSTEM] # TODO: removeme # status[ATTR_HTG_SYSTEM][ATTR_HTG_CONTROL] = (",
"heat_demands(self) -> Optional[dict]: # 3150 if self._heat_demands: return {k: v.payload[\"heat_demand\"] for k, v",
"prev_msg=None): super()._handle_msg(msg) if msg.code == \"0100\" and msg.verb in (\" I\", \"RP\"): self._language",
"system.\"\"\" if not isinstance(dhw, DhwZone): raise TypeError(f\"stored_hw can't be: {dhw}\") if self._dhw is",
"basic controllers - a generic controller (e.g. ST9420C).\"\"\" # 0008|0009|1030|1100|2309|3B00 def __init__(self, gwy,",
"and this.dst.type in (\"10\", \"13\"): heater = this.dst elif this.code == \"3B00\" and",
"self._send_cmd(\"313F\") def _handle_msg(self, msg, prev_msg=None): super()._handle_msg(msg) if msg.code == \"313F\" and msg.verb in",
"DHW sensor, if any (DHW relays in DHW) self._send_cmd(\"000C\", payload=dev_type) for dev_type in",
"during last cycle ] if _LOGGER.isEnabledFor(logging.DEBUG): _LOGGER.debug( \"Testable zones: %s (unique/non-null temps &",
"until=None) -> Task: \"\"\"Set a system mode for a specified duration, or indefinitely.\"\"\"",
"1100 return self._get_msg_value(\"1100\") @property def heat_demand(self) -> Optional[float]: # 3150/FC if self._heat_demand: return",
"x: x.idx) @property def schema(self) -> dict: assert ATTR_ZONES not in super().schema #",
"payload, **kwargs) @property def devices(self) -> List[Device]: return self._ctl.devices + [self._ctl] # TODO:",
"-> Optional[str]: return self._msg_payload(self._datetime, \"datetime\") # TODO: make a dt object # def",
"shouldn't change: {self._dhw} to {dhw}\") if self._dhw is None: # self._gwy._get_device(xxx) # self.add_device(dhw.sensor)",
"class Sundial(Evohome): def __repr__(self) -> str: return f\"{self._ctl.id} (sundial)\" SYSTEM_CLASSES = { SystemType.CHRONOTHERM:",
"removeme # assert ATTR_HTG_CONTROL not in status[ATTR_HTG_SYSTEM] # TODO: removeme # status[ATTR_HTG_SYSTEM][ATTR_HTG_CONTROL] =",
"v in self._heat_demands.items()} @property def relay_demands(self) -> Optional[dict]: # 0008 if self._relay_demands: return",
"temp = list(testable_zones.items())[0] _LOGGER.debug(\"Testing (sole remaining) zone %s, temp: %s\", zone_idx, temp) #",
"= zone_dict # elif msg.code == \"2309\": # zone._temp = zone_dict # elif",
"used to discover zone sensors def _discover(self, discover_flag=DISCOVER_ALL) -> None: super()._discover(discover_flag=discover_flag) if discover_flag",
"-> bool: super()._handle_msg(msg) # def xxx(zone_dict): # zone = self.zone_by_idx[zone_dict.pop(\"zone_idx\")] # if msg.code",
"18:14:14.025 066 RQ --- 01:078710 10:067219 --:------ 3220 005 0000050000 # 18:14:14.446 065",
"DHW sensor # 045 I --- 01:145038 --:------ 01:145038 1F41 012 000004FFFFFF1E060E0507E4 #",
"exclusion)\", self._ctl.id) zone = self.zone_by_idx[zone_idx] zone._set_sensor(self) zone.sensor._set_ctl(self) _LOGGER.debug(\"System state (finally): %s\", self) super()._handle_msg(msg)",
"if isinstance(msg.payload, list): # elif msg.code == \"000C\": # self._msgs[f\"{msg.code}\"] = msg #",
"else zone_deleted # elif msg.code == \"30C9\" and isinstance(msg.payload, list): # msg.is_array: #",
"in params # TODO: removeme assert \"system_mode\" not in params[ATTR_HTG_SYSTEM] # TODO: removeme",
"elif msg.payload[\"domain_id\"] == \"FA\": device = self.dhw.hotwater_valve if self.dhw else None elif msg.payload[\"domain_id\"]",
"List[Device]: return self._ctl.devices + [self._ctl] # TODO: to sort out @property def heating_control(self)",
"return {**super().status, ATTR_DHW_SYSTEM: self.dhw.status if self.dhw else {}} class MultiZone: # 0005 (+/-",
"any (DHW relays in DHW) self._send_cmd(\"000C\", payload=dev_type) for dev_type in (\"000D\", \"000F\") #",
"*to/from a 10:* (1x/1min) 2b. The 3EF0 RQ (no RP) *to a 13:*",
"if sensor is not None: if self.dhw is None: self._get_zone(\"FA\") self.dhw._set_sensor(sensor) super()._handle_msg(msg) if",
"3EF0 001 00 # 14:41:46.631 063 RP --- 10:067219 01:078710 --:------ 3EF0 006",
"the system is currently calling for heat.\"\"\" if not self._htg_control: return if self._htg_control.actuator_state:",
"None: super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_STATUS: self._send_cmd(\"1F09\") def _handle_msg(self, msg) -> bool: super()._handle_msg(msg)",
"RQ_UNSUPPORTED = (\"xxxx\",) # 10E0? def __repr__(self) -> str: return f\"{self._ctl.id} (hometronics)\" def",
"is currently calling for heat.\"\"\" if not self._htg_control: return if self._htg_control.actuator_state: return True",
"& valves?. \"\"\" def create_dhw(zone_idx) -> DhwZone: if self.dhw: raise LookupError(f\"Duplicate stored HW:",
"schema # TODO: removeme assert ATTR_HTG_CONTROL not in schema[ATTR_HTG_SYSTEM] # TODO: removeme schema[ATTR_HTG_SYSTEM][ATTR_HTG_CONTROL]",
"callback=callback) # time_start = dt.now() # while not self._schedule_done: # await asyncio.sleep(TIMER_SHORT_SLEEP) #",
"find any zones + their type (RAD, UFH, VAL, MIX, ELE) self._send_cmd(\"0005\", payload=f\"00{zone_type}\")",
"msg # elif msg.code == \"0005\" and prev_msg is not None: # zone_added",
"None: zone = create_dhw(zone_idx) if kwargs.get(\"dhw_valve\"): zone._set_dhw_valve(kwargs[\"dhw_valve\"]) if kwargs.get(\"htg_valve\"): zone._set_dhw_valve(kwargs[\"htg_valve\"]) if sensor is",
"zone._set_dhw_valve(kwargs[\"dhw_valve\"]) if kwargs.get(\"htg_valve\"): zone._set_dhw_valve(kwargs[\"htg_valve\"]) if sensor is not None: zone._set_dhw_sensor(sensor) return zone @property",
"in monitor mode... secs = self._get_msg_value(\"1F09\", \"remaining_seconds\") if secs is None or msg.dtm",
"super()._handle_msg(msg) if \"domain_id\" in msg.payload: idx = msg.payload[\"domain_id\"] if msg.code == \"0008\": self._relay_demands[idx]",
"**super().status, ATTR_UFH_SYSTEM: { d.id: d.status for d in sorted(self._ctl.devices) if d.type == \"02\"",
"self._fault_log = FaultLog(self._ctl) def _discover(self, discover_flag=DISCOVER_ALL) -> None: super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_STATUS:",
"is not None: return # the controller has already been allocated if len([z",
"\"0004\") # else zone_deleted # elif msg.code == \"30C9\" and isinstance(msg.payload, list): #",
"TODO: where to put this? # assert \"devices\" not in schema # TODO:",
"by the DHW, so is not authorative. The I/1260 is not to/from a",
"most basic controllers - a generic controller (e.g. ST9420C).\"\"\" # 0008|0009|1030|1100|2309|3B00 def __init__(self,",
"# zone._discover(discover_flags=DISCOVER_PARAMS) if msg.code in (\"000A\", \"2309\", \"30C9\"): pass # if isinstance(msg.payload, list):",
"dict: assert ATTR_UFH_SYSTEM not in super().schema # TODO: removeme return { **super().schema, ATTR_UFH_SYSTEM:",
"# find_htg_relay(msg, prev=prev_msg) def _send_cmd(self, code, **kwargs) -> None: dest = kwargs.pop(\"dest_addr\", self._ctl.id)",
"**kwargs) self._fault_log = FaultLog(self._ctl) def _discover(self, discover_flag=DISCOVER_ALL) -> None: super()._discover(discover_flag=discover_flag) if discover_flag &",
"(3x/60min) 3. The 3B00 I/I exchange between a CTL & a 13: (TPI",
"# 18:14:14.446 065 RP --- 10:067219 01:078710 --:------ 3220 005 00C00500FF # 14:41:46.599",
"is self and this.dst.type == \"07\": sensor = this.dst if sensor is not",
"to least reliable heater = None if this.code == \"3220\" and this.verb ==",
"calling for heat.\"\"\" if not self._htg_control: return if self._htg_control.actuator_state: return True @property def",
"zone @property def _zones(self) -> dict: return sorted(self.zones, key=lambda x: x.idx) @property def",
"status # TODO: removeme # assert ATTR_HTG_CONTROL not in status[ATTR_HTG_SYSTEM] # TODO: removeme",
"is sensor if not testable_zones: return # no testable zones zone_idx, temp =",
"schema.\"\"\" schema = {ATTR_CONTROLLER: self._ctl.id, ATTR_HTG_SYSTEM: {}} assert ATTR_HTG_SYSTEM in schema # TODO:",
"devices(self) -> List[Device]: return self._ctl.devices + [self._ctl] # TODO: to sort out @property",
"a dt object # def wait_for(self, cmd, callback): # self._api_lock.acquire() # self._send_cmd(\"313F\", verb=\"RQ\",",
"None: super().__init__(*args, **kwargs) self._language = None def _discover(self, discover_flag=DISCOVER_ALL) -> None: super()._discover(discover_flag=discover_flag) if",
"changed_zones) if not changed_zones: return # ctl's 30C9 says no zones have changed",
"RQ/RP *from/to a 07:* (1x/4h) - reliable 2. Use sensor temp matching -",
"zone._set_sensor(sensor) return zone @property def _zones(self) -> dict: return sorted(self.zones, key=lambda x: x.idx)",
"status[\"fault_log\"] = self._fault_log.fault_log status[\"last_fault\"] = self._msgz[\" I\"].get(\"0418\") return status class SysDatetime: # 313F",
"DHW sensor # 047 RQ --- 07:030741 01:102458 --:------ 10A0 006 00181F0003E4 #",
"_discover(self, discover_flag=DISCOVER_ALL) -> None: super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_STATUS: self._gwy.send_cmd(Command.get_system_time(self.id)) # self._send_cmd(\"313F\") def",
"assert ATTR_HTG_SYSTEM in params # TODO: removeme assert \"language\" not in params[ATTR_HTG_SYSTEM] #",
"dt) -> str: # wait for the I/313F # await self.wait_for(Command(\"313F\", verb=\" W\",",
".zones import DhwZone, Zone DEV_MODE = __dev_mode__ _LOGGER = logging.getLogger(__name__) if DEV_MODE: _LOGGER.setLevel(logging.DEBUG)",
"if msg.code in (\"10A0\", \"1260\"): # self.dhw.sensor is None and # if self.dhw.sensor",
"msg.code in (\"000A\", \"2309\", \"30C9\"): # if isinstance(msg.payload, list): # super()._handle_msg(msg) # [xxx(z)",
"return @property def status(self) -> dict: status = super().status assert \"fault_log\" not in",
"& DISCOVER_SCHEMA: [ # 0005: find any zones + their type (RAD, UFH,",
"and s._zone in (zone_idx, None) ] _LOGGER.debug( \" - matching sensor(s): %s (excl.",
"and d.type != \"02\"] ) # devices without a parent zone, NB: CTL",
"[s.id for s in matching_sensors], ) # can safely(?) assume this zone is",
"an address before implmenting for device in [d for d in kwargs[\"actuators\"] if",
"sensor temperatures. In addition, there may be 'orphan' (e.g. from a neighbour) sensors",
"ST9420C).\"\"\" # 0008|0009|1030|1100|2309|3B00 def __init__(self, gwy, ctl, **kwargs) -> None: # _LOGGER.debug(\"Creating a",
"in (\"3B00\",): # 3EF0, 3EF1 # # for payload in (\"0000\", \"00\", \"F8\",",
"- some controllers are evohome-compatible.\"\"\" def __init__(self, gwy, ctl, **kwargs) -> None: super().__init__(gwy,",
"self._msgs[f\"{msg.code}\"] = msg # elif msg.code == \"0005\" and prev_msg is not None:",
"_LOGGER.debug(\"Testing (sole remaining) zone %s, temp: %s\", zone_idx, temp) # want to avoid",
"# TODO: removeme return {**super().schema, ATTR_ZONES: {z.idx: z.schema for z in self._zones}} @property",
"= ctl.id gwy.systems.append(self) gwy.system_by_id[self.id] = self self._ctl = ctl self._domain_id = \"FF\" self._evo",
"\"\"\"Discover the heat relay (10: or 13:) for this system. There's' 3 ways",
"self._ctl.devices + [self._ctl] # TODO: to sort out @property def heating_control(self) -> Device:",
"from .schema import ( ATTR_CONTROLLER, ATTR_DHW_SYSTEM, ATTR_HTG_CONTROL, ATTR_HTG_SYSTEM, ATTR_ORPHANS, ATTR_UFH_SYSTEM, ATTR_ZONES, DISABLE_DISCOVERY, MAX_ZONES,",
"001 00 # 09:03:59.693 051 I --- 13:237335 --:------ 13:237335 3B00 002 00C8",
"system_mode=system_mode, until=until) return self._gwy.send_cmd(cmd) def set_auto(self) -> Task: \"\"\"Revert system to Auto, set",
"for code in (\"3B00\",): # 3EF0, 3EF1 # # for payload in (\"0000\",",
"313F def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self._datetime = None def",
"is_calling_for_heat(self) -> Optional[bool]: \"\"\"Return True is the system is currently calling for heat.\"\"\"",
"# else zone_deleted # elif msg.code == \"30C9\" and isinstance(msg.payload, list): # msg.is_array:",
"def status(self) -> dict: assert ATTR_DHW_SYSTEM not in super().status # TODO: removeme return",
"2b. The 3EF0 RQ (no RP) *to a 13:* (3x/60min) 3. The 3B00",
"-> Device: return self._dhw._dhw_valve if self._dhw else None @property def heating_valve(self) -> Device:",
"is None: # return # TODO: should have a (not-None) temperature matching_sensors =",
"in super().schema # TODO: removeme return { **super().schema, ATTR_UFH_SYSTEM: { d.id: d.schema for",
"# evohome # class Evohome(System): # evohome \"\"\"The Evohome system - some controllers",
"return params class SysMode: # 2E04 def __init__(self, *args, **kwargs) -> None: super().__init__(*args,",
"return self.datetime @property def status(self) -> dict: status = super().status assert ATTR_HTG_SYSTEM in",
"**kwargs) def __repr__(self) -> str: return f\"{self._ctl.id} (evohome)\" def _discover(self, discover_flag=DISCOVER_ALL) -> None:",
"device = self.dhw.hotwater_valve if self.dhw else None elif msg.payload[\"domain_id\"] == \"FC\": device =",
"The I/1260 is not to/from a controller, so is not useful. \"\"\" #",
"zones have changed temps during this cycle testable_zones = { z: t for",
"{ d.id: d.params for d in sorted(self._ctl.devices) if d.type == \"02\" }, }",
"if self._relay_demands: return { k: v.payload[\"relay_demand\"] for k, v in self._relay_demands.items() } @property",
"# async def set_datetime(self, dtm: dt) -> str: # wait for the I/313F",
"not self._gwy.config[DISABLE_DISCOVERY]: # TODO: needs tidyup (ref #67) zone._discover() # discover_flag=DISCOVER_ALL) return zone",
"@property def status(self) -> dict: assert ATTR_ZONES not in super().status # TODO: removeme",
"DISCOVER_STATUS: pass def _handle_msg(self, msg, prev_msg=None): \"\"\"Eavesdrop packets, or pairs of packets, to",
"1. The 3220 RQ/RP *to/from a 10:* (1x/5min) 2a. The 3EF0 RQ/RP *to/from",
"system to Auto, force *all* zones to FollowSchedule.\"\"\" return self.set_mode(SystemMode.RESET) @property def params(self)",
"secs = self._get_msg_value(\"1F09\", \"remaining_seconds\") if secs is None or msg.dtm > prev_msg.dtm +",
"in self._zones}} @property def status(self) -> dict: assert ATTR_ZONES not in super().status #",
"# TODO: removeme return { **super().schema, ATTR_UFH_SYSTEM: { d.id: d.schema for d in",
"The 3EF0 RQ/RP *to/from a 10:* (1x/1min) 2b. The 3EF0 RQ (no RP)",
"# self._api_lock.acquire() # self._send_cmd(\"313F\", verb=\"RQ\", callback=callback) # time_start = dt.now() # while not",
"raise ValueError(f\"Invalid zone idx: {zone_idx} (exceeds max_zones)\") if zone_idx in self.zone_by_idx: raise LookupError(f\"Duplicated",
"heater = this.dst elif this.code == \"3EF0\" and this.verb == \"RQ\": if this.src",
"else None # ) status[ATTR_HTG_SYSTEM][\"heat_demand\"] = self.heat_demand status[ATTR_DEVICES] = {d.id: d.status for d",
"been allocated if len([z for z in self.zones if z.sensor is None]) !=",
"zone is using the CTL as a sensor... if len(matching_sensors) == 0: _LOGGER.debug(\"",
"not in params[ATTR_HTG_SYSTEM] # TODO: removeme params[ATTR_HTG_SYSTEM][\"system_mode\"] = self.system_mode return params class StoredHw:",
"dict: assert ATTR_DHW_SYSTEM not in super().params # TODO: removeme return {**super().params, ATTR_DHW_SYSTEM: self.dhw.params",
"13:).\"\"\" if not isinstance(device, Device) or device.type not in (\"10\", \"13\"): raise TypeError(f\"{ATTR_HTG_CONTROL}",
"__str__(self) -> str: # TODO: WIP # return json.dumps({self._ctl.id: self.schema}) def _discover(self, discover_flag=DISCOVER_ALL)",
"} @property def status(self) -> dict: assert ATTR_UFH_SYSTEM not in super().status # TODO:",
"#!/usr/bin/env python3 # -*- coding: utf-8 -*- # \"\"\"Evohome RF - The evohome-compatible",
"__init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self._dhw = None def _discover(self, discover_flag=DISCOVER_ALL)",
"get parent controller, but not DHW sensor # 045 I --- 01:145038 --:------",
"msg) -> bool: super()._handle_msg(msg) if \"domain_id\" in msg.payload: idx = msg.payload[\"domain_id\"] if msg.code",
"it if required). Can also set a DHW zone's sensor & valves?. \"\"\"",
"# self._dhw \"\"\"Set the DHW zone system.\"\"\" if not isinstance(dhw, DhwZone): raise TypeError(f\"stored_hw",
"self._send_cmd(\"0006\") def _handle_msg(self, msg, prev_msg=None): def OUT_find_zone_sensors() -> None: \"\"\"Determine each zone's sensor",
"idx: {zone_idx} (exceeds max_zones)\") if zone_idx in self.zone_by_idx: raise LookupError(f\"Duplicated zone: {zone_idx} for",
"not None: self._set_htg_control(heater) if msg.code in (\"000A\", \"2309\", \"30C9\") and not isinstance(msg.payload, list):",
"temp: %s\", zone_idx, temp) # want to avoid complexity of z._temp # zone",
"0: return # (currently) no zone without a sensor # if self._gwy.serial_port: #",
"RQ/RP *to/from a 10:* (1x/1min) 2b. The 3EF0 RQ (no RP) *to a",
"in self._ctl.devices if d._domain_id == \"FC\"] return htg_control[0] if len(htg_control) == 1 else",
"dict: params = super().params assert ATTR_HTG_SYSTEM in params # TODO: removeme assert \"system_mode\"",
"assert ATTR_HTG_SYSTEM in schema # TODO: removeme assert ATTR_HTG_CONTROL not in schema[ATTR_HTG_SYSTEM] #",
"dt.now() > time_start + TIMER_LONG_TIMEOUT: # self._api_lock.release() # raise ExpiredCallbackError(\"failed to set schedule\")",
"& DISCOVER_PARAMS: self._send_cmd(\"1100\", payload=\"FC\") # TPI params # # for code in (\"3B00\",):",
"sensors announce temp, ?also includes it's parent zone matching_sensors = [ s for",
"in schema # TODO: removeme # schema[\"devices\"] = {d.id: d.device_info for d in",
"def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self._system_mode = None def _discover(self,",
"super().params # TODO: removeme return {**super().params, ATTR_ZONES: {z.idx: z.params for z in self._zones}}",
"self._gwy.send_cmd(Command.get_system_time(self.id)) # self._send_cmd(\"313F\") def _handle_msg(self, msg, prev_msg=None): super()._handle_msg(msg) if msg.code == \"313F\" and",
"None: super().__init__(*args, **kwargs) self._dhw = None def _discover(self, discover_flag=DISCOVER_ALL) -> None: super()._discover(discover_flag=discover_flag) if",
"self and this.dst.type in (\"10\", \"13\"): heater = this.dst elif this.code == \"3B00\"",
"_LOGGER.debug(\"System state (after): %s\", self) # now see if we can allocate the",
"False and device is not None: # TODO: FIXME qos = {\"priority\": Priority.LOW,",
"to sort out @property def heating_control(self) -> Device: if self._htg_control: return self._htg_control htg_control",
"-> dict: \"\"\"Return the system's configuration.\"\"\" params = {ATTR_HTG_SYSTEM: {}} assert ATTR_HTG_SYSTEM in",
"params # assert ATTR_HTG_CONTROL not in params[ATTR_HTG_SYSTEM] # TODO: removeme # params[ATTR_HTG_SYSTEM][ATTR_HTG_CONTROL] =",
"sensor # 047 RQ --- 07:030741 01:102458 --:------ 10A0 006 00181F0003E4 # 062",
"= self.heat_demand status[ATTR_DEVICES] = {d.id: d.status for d in sorted(self._ctl.devices)} return status class",
"_handle_msg(self, msg) -> bool: super()._handle_msg(msg) if \"domain_id\" in msg.payload: idx = msg.payload[\"domain_id\"] if",
"zone_idx, temp = list(testable_zones.items())[0] _LOGGER.debug(\"Testing (sole remaining) zone %s, temp: %s\", zone_idx, temp)",
"self.zone_by_idx = {} # self.zone_by_name = {} self.zone_lock = Lock() self.zone_lock_idx = None",
"# the controller has already been allocated if len([z for z in self.zones",
"\" - matching sensor(s): %s (excl. controller)\", [s.id for s in matching_sensors], )",
"{}} @property def status(self) -> dict: assert ATTR_DHW_SYSTEM not in super().status # TODO:",
"for the I/313F # await self.wait_for(Command(\"313F\", verb=\" W\", payload=f\"00{dtm_to_hex(dtm)}\")) # return self.datetime @property",
"{} self._relay_demands = {} self._relay_failsafes = {} def __repr__(self) -> str: return f\"{self._ctl.id}",
"matching sensor (uses CTL?)\") else: _LOGGER.debug(\" - multiple sensors: %s\", matching_sensors) _LOGGER.debug(\"System state",
"DISCOVER_SCHEMA: [ # 000C: find the HTG relay and DHW sensor, if any",
"return self.set_mode(SystemMode.AUTO) def reset_mode(self) -> Task: \"\"\"Revert system to Auto, force *all* zones",
"removeme return {**super().schema, ATTR_ZONES: {z.idx: z.schema for z in self._zones}} @property def params(self)",
"14:41:46.599 064 RQ --- 01:078710 10:067219 --:------ 3EF0 001 00 # 14:41:46.631 063",
"td(seconds=secs): return # only compare against 30C9 (array) pkt from the last cycle",
"I --- 07:045960 --:------ 07:045960 1260 003 000911 # 1F41: I/01: get parent",
"= zone_dict # elif msg.code == \"30C9\": # zone._temp = zone_dict # if",
"- matching sensor(s): %s (same temp & not from another zone)\", [s.id for",
"\"F9\": device = self.dhw.heating_valve if self.dhw else None elif msg.payload[\"domain_id\"] == \"FA\": device",
"zone idx: {zone_idx} (exceeds max_zones)\") if zone_idx in self.zone_by_idx: raise LookupError(f\"Duplicated zone: {zone_idx}",
"datetime(self) -> Optional[str]: return self._msg_payload(self._datetime, \"datetime\") # TODO: make a dt object #",
"# 3EF0, 3EF1 # # for payload in (\"0000\", \"00\", \"F8\", \"F9\", \"FA\",",
"a sensor for a zones # TODO: where to put this? # assert",
"be: {device}\") if self._htg_control is not None: if self._htg_control is device: return raise",
"return f\"{self._ctl.id} (chronotherm)\" class Hometronics(System): RQ_SUPPORTED = (\"0004\", \"000C\", \"2E04\", \"313F\") # TODO:",
"--- 01:102458 07:030741 --:------ 10A0 006 0018380003E8 # 1260: I/07: can't get which",
"a sensor testable_zones = { z: t for z, t in changed_zones.items() if",
"if self._heat_demands: return {k: v.payload[\"heat_demand\"] for k, v in self._heat_demands.items()} @property def relay_demands(self)",
"self._gwy.serial_port: # only if in monitor mode... secs = self._get_msg_value(\"1F09\", \"remaining_seconds\") if secs",
"= None def __repr__(self) -> str: return f\"{self._ctl.id} (sys_base)\" # def __str__(self) ->",
"CTL?)\") else: _LOGGER.debug(\" - multiple sensors: %s\", matching_sensors) _LOGGER.debug(\"System state (after): %s\", self)",
"None if this.code == \"10A0\" and this.verb == \"RP\": if this.src is self",
"None: # super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_SCHEMA: [ # 000C: find the HTG",
"# TODO: removeme status[ATTR_HTG_SYSTEM][\"heat_demands\"] = self.heat_demands status[ATTR_HTG_SYSTEM][\"relay_demands\"] = self.relay_demands status[ATTR_HTG_SYSTEM][\"relay_failsafes\"] = self.relay_failsafes return",
"if False and device is not None: # TODO: FIXME qos = {\"priority\":",
"-> None: super().__init__(gwy, ctl, **kwargs) def __repr__(self) -> str: return f\"{self._ctl.id} (evohome)\" def",
"try: return await self._fault_log.get_fault_log(force_refresh=force_refresh) except ExpiredCallbackError: return @property def status(self) -> dict: status",
"= 85.0 DEFAULT_SETPOINT = 50.0 def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs)",
"wait for the I/313F # await self.wait_for(Command(\"313F\", verb=\" W\", payload=f\"00{dtm_to_hex(dtm)}\")) # return self.datetime",
"is not None: if prev.code == this.code and prev.verb == this.verb: if this.src",
"removeme # devices don't have params # assert ATTR_HTG_CONTROL not in params[ATTR_HTG_SYSTEM] #",
"is None]) != 1: return # no single zone without a sensor testable_zones",
"if z not in prev_msg.payload } # zones with changed temps _LOGGER.debug(\"Changed zones",
"def get_datetime(self) -> str: # wait for the RP/313F # await self.wait_for(Command(\"313F\", verb=\"RQ\"))",
"if discover_flag & DISCOVER_PARAMS: # for domain_id in range(0xF8, 0x100): # self._send_cmd(\"0009\", payload=f\"{domain_id:02X}00\")",
"z.status for z in self._zones}} class UfhSystem: @property def schema(self) -> dict: assert",
"payload=f\"{domain_id:02X}00\") pass def _handle_msg(self, msg) -> bool: def OUT_is_exchange(this, prev): # TODO:use is?",
"be useful. \"\"\" # 18:14:14.025 066 RQ --- 01:078710 10:067219 --:------ 3220 005",
"# params[ATTR_HTG_SYSTEM][ATTR_HTG_CONTROL] = ( # self.heating_control.params if self.heating_control else None # ) assert",
"for each zone is not. In particular, the controller may be a sensor",
"msg.code in (\"000A\", \"2309\", \"30C9\"): pass # if isinstance(msg.payload, list): # elif msg.code",
"sensor (uses CTL?)\") else: _LOGGER.debug(\" - multiple sensors: %s\", matching_sensors) _LOGGER.debug(\"System state (after):",
"I/07: can't get which parent controller - need to match temps # 045",
"sensor(s): %s (same temp & not from another zone)\", [s.id for s in",
"not useful. \"\"\" # 10A0: RQ/07/01, RP/01/07: can get both parent controller &",
"is not None: zone._set_dhw_sensor(sensor) return zone @property def dhw(self) -> DhwZone: return self._dhw",
"super()._handle_msg(msg) if msg.code == \"0100\" and msg.verb in (\" I\", \"RP\"): self._language =",
"I\", \"RP\"): self._language = msg @property def language(self) -> Optional[str]: # 0100 return",
"sensor (from state): %s\", testable_zones, ) if not testable_zones: return # no testable",
"self._zones}} @property def status(self) -> dict: assert ATTR_ZONES not in super().status # TODO:",
"dt object # def wait_for(self, cmd, callback): # self._api_lock.acquire() # self._send_cmd(\"313F\", verb=\"RQ\", callback=callback)",
"System): # evohome # class Evohome(System): # evohome \"\"\"The Evohome system - some",
"list): # elif msg.code == \"000C\": # self._msgs[f\"{msg.code}\"] = msg # elif msg.code",
"DHW sensor: 1. The 10A0 RQ/RP *from/to a 07:* (1x/4h) - reliable 2.",
"for d in sorted(self._ctl.devices)} return schema @property def params(self) -> dict: \"\"\"Return the",
"\"\"\"Set the DHW zone system.\"\"\" if not isinstance(dhw, DhwZone): raise TypeError(f\"stored_hw can't be:",
"status[ATTR_HTG_SYSTEM][\"relay_demands\"] = self.relay_demands status[ATTR_HTG_SYSTEM][\"relay_failsafes\"] = self.relay_failsafes return status class Evohome(SysLanguage, SysMode, MultiZone, UfhSystem,",
"# msg.is_array: # find_zone_sensors() def _get_zone(self, zone_idx, sensor=None, **kwargs) -> Zone: \"\"\"Return a",
"# TODO: removeme schema[ATTR_ORPHANS] = sorted( [d.id for d in self._ctl.devices if not",
"super().status assert ATTR_HTG_SYSTEM in status # TODO: removeme assert \"datetime\" not in status[ATTR_HTG_SYSTEM]",
"msg.code == \"0008\": self._relay_demands[idx] = msg elif msg.code == \"0009\": self._relay_failsafes[idx] = msg",
"zone_added = bool(prev_msg.code == \"0004\") # else zone_deleted # elif msg.code == \"30C9\"",
"zone = self.zone_by_idx[zone_idx] zone._set_sensor(self) zone.sensor._set_ctl(self) _LOGGER.debug(\"System state (finally): %s\", self) super()._handle_msg(msg) if msg.code",
"sensor # 045 I --- 01:145038 --:------ 01:145038 1F41 012 000004FFFFFF1E060E0507E4 # 045",
"temperature of each zone is reliably known (30C9 array), but the sensor for",
"dict: assert ATTR_ZONES not in super().status # TODO: removeme return {**super().status, ATTR_ZONES: {z.idx:",
"\"\"\"Return the system's configuration.\"\"\" params = {ATTR_HTG_SYSTEM: {}} assert ATTR_HTG_SYSTEM in params #",
"= self.relay_demands status[ATTR_HTG_SYSTEM][\"relay_failsafes\"] = self.relay_failsafes return status class Evohome(SysLanguage, SysMode, MultiZone, UfhSystem, System):",
"-> Task: \"\"\"Set a system mode for a specified duration, or indefinitely.\"\"\" cmd",
"same value. This leaves only a process of exclusion as a means to",
"__init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self._datetime = None def _discover(self, discover_flag=DISCOVER_ALL)",
"in matching_sensors], ) # can safely(?) assume this zone is using the CTL",
"fix payload # if description is not None ] if discover_flag & DISCOVER_PARAMS:",
"None: super().__init__(gwy, ctl, **kwargs) def __repr__(self) -> str: return f\"{self._ctl.id} (evohome)\" def _discover(self,",
"- reliable 2. Use sensor temp matching - non-deterministic Data from the CTL",
"None: if self.dhw is None: self._get_zone(\"FA\") self.dhw._set_sensor(sensor) super()._handle_msg(msg) if msg.code in (\"10A0\", \"1260\"):",
"-> List[Device]: return self._ctl.devices + [self._ctl] # TODO: to sort out @property def",
"for z in msg.payload] # else: # xxx(msg.payload) if msg.code in (\"000A\", \"2309\",",
"1: return # no single zone without a sensor testable_zones = { z:",
"array), but the sensor for each zone is not. In particular, the controller",
"\"FA\", \"FB\", \"FC\", \"FF\"): # # self._send_cmd(code, payload=payload) # # TODO: opentherm: 1FD4,",
"@property def params(self) -> dict: assert ATTR_UFH_SYSTEM not in super().params # TODO: removeme",
"# TODO: removeme # assert ATTR_HTG_CONTROL not in status[ATTR_HTG_SYSTEM] # TODO: removeme #",
"The 3220 RQ/RP *to/from a 10:* (1x/5min) 2a. The 3EF0 RQ/RP *to/from a",
"# wait for the I/313F # await self.wait_for(Command(\"313F\", verb=\" W\", payload=f\"00{dtm_to_hex(dtm)}\")) # return",
"{self._htg_control} to {device}\" ) # if device.evo is not None and device.evo is",
"if in monitor mode... secs = self._get_msg_value(\"1F09\", \"remaining_seconds\") if secs is None or",
"Command.get_zone_mode(self.id, zone_idx, priority=Priority.LOW) self._gwy.send_cmd(cmd) # for zone in self.zones: # zone._discover(discover_flags=DISCOVER_PARAMS) if msg.code",
"this.src is self and prev.src.type == \"13\": heater = prev.src if heater is",
"zone matching_sensors = [ s for s in testable_sensors if s.temperature == temp",
"{ d.id: d.status for d in sorted(self._ctl.devices) if d.type == \"02\" }, }",
"# TODO: removeme return { **super().status, ATTR_UFH_SYSTEM: { d.id: d.status for d in",
"in changed_zones.items() if self.zone_by_idx[z].sensor is None } # this will be true if",
"def create_dhw(zone_idx) -> DhwZone: if self.dhw: raise LookupError(f\"Duplicate stored HW: {zone_idx}\") dhw =",
"return zone @property def dhw(self) -> DhwZone: return self._dhw def _set_dhw(self, dhw: DhwZone)",
"self._heat_demand = msg.payload # if msg.code in (\"3220\", \"3B00\", \"3EF0\"): # self.heating_control is",
"not in (\"0001\", \"000C\", \"0418\", \"1100\", \"3B00\"): assert False, msg.code @property def heat_demands(self)",
"prev.code == this.code and prev.verb == this.verb: if this.src is self and prev.src.type",
"{ **super().params, ATTR_UFH_SYSTEM: { d.id: d.params for d in sorted(self._ctl.devices) if d.type ==",
"zone._temp = zone_dict # if msg.code in (\"000A\", \"2309\", \"30C9\"): # if isinstance(msg.payload,",
"TODO: WIP RQ_UNSUPPORTED = (\"xxxx\",) # 10E0? def __repr__(self) -> str: return f\"{self._ctl.id}",
"actuators. \"\"\" def create_zone(zone_idx) -> Zone: if int(zone_idx, 16) >= self._gwy.config[MAX_ZONES]: raise ValueError(f\"Invalid",
"prev_msg=None): \"\"\"Eavesdrop packets, or pairs of packets, to maintain the system state.\"\"\" def",
"self.heating_control.status if self.heating_control else None # ) status[ATTR_HTG_SYSTEM][\"heat_demand\"] = self.heat_demand status[ATTR_DEVICES] = {d.id:",
"# TODO: should have a (not-None) temperature matching_sensors = [ s for s",
"elif len(matching_sensors) == 0: _LOGGER.debug(\" - no matching sensor (uses CTL?)\") else: _LOGGER.debug(\"",
"from another zone)\", [s.id for s in matching_sensors], ) if len(matching_sensors) == 1:",
"85.0 DEFAULT_SETPOINT = 50.0 def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self._dhw",
"s.temperature == temp and s._zone in (zone_idx, None) ] _LOGGER.debug(\"Testing zone %s, temp:",
"heat.\"\"\" if not self._htg_control: return if self._htg_control.actuator_state: return True @property def schema(self) ->",
"= device device._set_parent(self, domain=\"FC\") @property def tpi_params(self) -> Optional[float]: # 1100 return self._get_msg_value(\"1100\")",
"testable_sensors: # the main matching algorithm... for zone_idx, temp in testable_zones.items(): # TODO:",
"SystemBase(Entity): # 3B00 (multi-relay) \"\"\"The most basic controllers - a generic controller (e.g.",
"state): %s\", testable_zones, ) if not testable_zones: return # no testable zones testable_sensors",
"raise TypeError(f\"stored_hw can't be: {dhw}\") if self._dhw is not None: if self._dhw is",
"isinstance(msg.payload, list): # msg.is_array: # find_zone_sensors() def _get_zone(self, zone_idx, sensor=None, **kwargs) -> Zone:",
"str: return f\"{self._ctl.id} (sys_base)\" # def __str__(self) -> str: # TODO: WIP #",
"params(self) -> dict: \"\"\"Return the system's configuration.\"\"\" params = {ATTR_HTG_SYSTEM: {}} assert ATTR_HTG_SYSTEM",
"temp: %s\", zone_idx, temp) _LOGGER.debug( \" - matching sensor(s): %s (same temp &",
"callback): # self._api_lock.acquire() # self._send_cmd(\"313F\", verb=\"RQ\", callback=callback) # time_start = dt.now() # while",
"and d.temperature is not None and d._msgs[\"30C9\"].dtm > prev_msg.dtm # changed temp during",
"ctl.id gwy.systems.append(self) gwy.system_by_id[self.id] = self self._ctl = ctl self._domain_id = \"FF\" self._evo =",
"is device: return raise CorruptStateError( f\"{ATTR_HTG_CONTROL} shouldn't change: {self._htg_control} to {device}\" ) #",
"not in schema[ATTR_HTG_SYSTEM] # TODO: removeme schema[ATTR_ORPHANS] = sorted( [d.id for d in",
"says no zones have changed temps during this cycle testable_zones = { z:",
"t not in [v for k, v in changed_zones.items() if k != z]",
"1: _LOGGER.debug(\" - matched sensor: %s\", matching_sensors[0].id) zone = self.zone_by_idx[zone_idx] zone._set_sensor(matching_sensors[0]) zone.sensor._set_ctl(self) elif",
"@property def heating_valve(self) -> Device: return self._dhw._htg_valve if self._dhw else None @property def",
"DISCOVER_PARAMS: # for domain_id in range(0xF8, 0x100): # self._send_cmd(\"0009\", payload=f\"{domain_id:02X}00\") if discover_flag &",
"z in self._zones}} @property def params(self) -> dict: assert ATTR_ZONES not in super().params",
"# super()._discover(discover_flag=discover_flag) # will RP to: 0005/configured_zones_alt, but not: configured_zones # will RP",
"& DISCOVER_STATUS: self._gwy._tasks.append(self._loop.create_task(self.get_fault_log())) async def get_fault_log(self, force_refresh=None) -> Optional[dict]: # 0418 try: return",
"RP to: 0005/configured_zones_alt, but not: configured_zones # will RP to: 0004 if discover_flag",
"matching_sensors], ) # can safely(?) assume this zone is using the CTL as",
"as td from threading import Lock from typing import List, Optional from .command",
"relay for this system (10: or 13:).\"\"\" if not isinstance(device, Device) or device.type",
"zone.sensor._set_ctl(self) _LOGGER.debug(\"System state (finally): %s\", self) super()._handle_msg(msg) if msg.code in (\"000A\",) and isinstance(msg.payload,",
"d.status for d in sorted(self._ctl.devices)} return status class System(StoredHw, SysDatetime, SystemBase): # ,",
"{} # self.zone_by_name = {} self.zone_lock = Lock() self.zone_lock_idx = None # self._prev_30c9",
"\"\"\"Return the system's current state.\"\"\" status = super().status assert ATTR_HTG_SYSTEM in status #",
"DEFAULT_SETPOINT = 50.0 def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self._dhw =",
"parent controller - need to match temps # 045 I --- 07:045960 --:------",
"removeme # status[ATTR_HTG_SYSTEM][ATTR_HTG_CONTROL] = ( # self.heating_control.status if self.heating_control else None # )",
"discover_flag=DISCOVER_ALL) -> None: super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_STATUS: self._gwy.send_cmd(Command.get_system_time(self.id)) # self._send_cmd(\"313F\") def _handle_msg(self,",
"to FollowSchedule.\"\"\" return self.set_mode(SystemMode.AUTO) def reset_mode(self) -> Task: \"\"\"Revert system to Auto, force",
"will be true if ctl is sensor if not testable_zones: return # no",
"not None: # TODO: FIXME qos = {\"priority\": Priority.LOW, \"retries\": 2} for code",
"as per an RFG100 self._send_cmd(\"0005\", payload=f\"00{zone_type}\") for zone_type in (\"00\", \"04\", \"0C\", \"0F\",",
"a process of exclusion as a means to determine which zone uses the",
"== \"HW\": return super()._get_zone(zone_idx, sensor=sensor, **kwargs) if int(zone_idx, 16) >= self._gwy.config[MAX_ZONES]: raise ValueError(f\"Unknown",
"if self._dhw is not None: if self._dhw is dhw: return raise CorruptStateError(\"DHW shouldn't",
"051 I --- 13:237335 --:------ 13:237335 3B00 002 00C8 # 09:04:02.667 045 I",
"**kwargs) @property def devices(self) -> List[Device]: return self._ctl.devices + [self._ctl] # TODO: to",
"-> None: # self._htg_control \"\"\"Set the heating control relay for this system (10:",
"can be a sensor for a zones # TODO: where to put this?",
"return { **super().schema, ATTR_UFH_SYSTEM: { d.id: d.schema for d in sorted(self._ctl.devices) if d.type",
"RP --- 10:067219 01:078710 --:------ 3220 005 00C00500FF # 14:41:46.599 064 RQ ---",
"-> Task: \"\"\"Revert system to Auto, set non-PermanentOverride zones to FollowSchedule.\"\"\" return self.set_mode(SystemMode.AUTO)",
"sorted(self._ctl.devices) if d.type == \"02\" }, } @property def status(self) -> dict: assert",
"def __repr__(self) -> str: return f\"{self._ctl.id} (chronotherm)\" class Hometronics(System): RQ_SUPPORTED = (\"0004\", \"000C\",",
"these may be removed MAX_SETPOINT = 85.0 DEFAULT_SETPOINT = 50.0 def __init__(self, *args,",
"kwargs[\"actuators\"] if d not in zone.devices]: zone.devices.append(device) zone.device_by_id[device.id] = device if sensor is",
"a CTL is too rare to be useful. \"\"\" # 18:14:14.025 066 RQ",
"Optional[str]: # 0100 return self._msg_payload(self._language, \"language\") @property def params(self) -> dict: params =",
"announcing temperatures with the same value. This leaves only a process of exclusion",
"return # the controller has already been allocated if len([z for z in",
"DHW, so is not authorative. The I/1260 is not to/from a controller, so",
"def set_auto(self) -> Task: \"\"\"Revert system to Auto, set non-PermanentOverride zones to FollowSchedule.\"\"\"",
"# TODO: WIP RQ_UNSUPPORTED = (\"xxxx\",) # 10E0? def __repr__(self) -> str: return",
"int(zone_idx, 16) >= self._gwy.config[MAX_ZONES]: raise ValueError(f\"Invalid zone idx: {zone_idx} (exceeds max_zones)\") if zone_idx",
"== \"FC\": device = self.heating_control else: device = None if False and device",
"discover_flag=DISCOVER_ALL) -> None: super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_STATUS: pass def _handle_msg(self, msg, prev_msg=None):",
"discover_flag & DISCOVER_STATUS: self._send_cmd(\"1F09\") def _handle_msg(self, msg) -> bool: super()._handle_msg(msg) # def xxx(zone_dict):",
"if not testable_zones: return # no testable zones testable_sensors = [ d for",
"is not None and d._msgs[\"30C9\"].dtm > prev_msg.dtm # changed temp during last cycle",
"--- 01:145038 --:------ 01:145038 3B00 002 FCC8 # note the order: most to",
"specified duration, or indefinitely.\"\"\" cmd = Command.set_system_mode(self.id, system_mode=system_mode, until=until) return self._gwy.send_cmd(cmd) def set_auto(self)",
"there may be 'orphan' (e.g. from a neighbour) sensors announcing temperatures with the",
"# 06:49:07.468 045 RQ --- 01:145038 13:237335 --:------ 3EF0 001 00 # 09:03:59.693",
"payload=f\"{domain_id:02X}00\") if discover_flag & DISCOVER_STATUS: # for domain_id in range(0xF8, 0x100): # self._send_cmd(\"0008\",",
"zones # TODO: where to put this? # assert \"devices\" not in schema",
"raise CorruptStateError(\"DHW shouldn't change: {self._dhw} to {dhw}\") if self._dhw is None: # self._gwy._get_device(xxx)",
"(\"000A\", \"2309\", \"30C9\"): # if isinstance(msg.payload, list): # super()._handle_msg(msg) # [xxx(z) for z",
"== \"0100\" and msg.verb in (\" I\", \"RP\"): self._language = msg @property def",
"def system_mode(self) -> Optional[dict]: # 2E04 return self._msg_payload(self._system_mode) def set_mode(self, system_mode=None, until=None) ->",
"16) >= self._gwy.config[MAX_ZONES]: raise ValueError(f\"Invalid zone idx: {zone_idx} (exceeds max_zones)\") if zone_idx in",
"def tpi_params(self) -> Optional[float]: # 1100 return self._get_msg_value(\"1100\") @property def heat_demand(self) -> Optional[float]:",
"its sensor temperatures. In addition, there may be 'orphan' (e.g. from a neighbour)",
"01:145038 13:237335 --:------ 3EF0 001 00 # 06:49:07.468 045 RQ --- 01:145038 13:237335",
"sensor for each zone is not. In particular, the controller may be a",
"-> None: # self._dhw \"\"\"Set the DHW zone system.\"\"\" if not isinstance(dhw, DhwZone):",
"to discover zone sensors def _discover(self, discover_flag=DISCOVER_ALL) -> None: super()._discover(discover_flag=discover_flag) if discover_flag &",
"& DISCOVER_STATUS: self._gwy.send_cmd(Command.get_system_time(self.id)) # self._send_cmd(\"313F\") def _handle_msg(self, msg, prev_msg=None): super()._handle_msg(msg) if msg.code ==",
"the last cycle _LOGGER.debug(\"System state (before): %s\", self) changed_zones = { z[\"zone_idx\"]: z[\"temperature\"]",
"(ref #67) zone._discover() # discover_flag=DISCOVER_ALL) return zone if zone_idx == \"HW\": return super()._get_zone(zone_idx,",
"zones to FollowSchedule.\"\"\" return self.set_mode(SystemMode.AUTO) def reset_mode(self) -> Task: \"\"\"Revert system to Auto,",
"have a (not-None) temperature matching_sensors = [ s for s in testable_sensors if",
"}, } @property def params(self) -> dict: assert ATTR_UFH_SYSTEM not in super().params #",
"Zone DEV_MODE = __dev_mode__ _LOGGER = logging.getLogger(__name__) if DEV_MODE: _LOGGER.setLevel(logging.DEBUG) class SysFaultLog: #",
"self._api_lock.acquire() # self._send_cmd(\"313F\", verb=\"RQ\", callback=callback) # time_start = dt.now() # while not self._schedule_done:",
"super().__init__(*args, **kwargs) self._language = None def _discover(self, discover_flag=DISCOVER_ALL) -> None: super()._discover(discover_flag=discover_flag) if discover_flag",
"super().__init__(*args, **kwargs) self.zones = [] self.zone_by_idx = {} # self.zone_by_name = {} self.zone_lock",
"pass else: super()._handle_msg(msg) if msg.code == \"0008\" and msg.verb in (\" I\", \"RP\"):",
"device device._set_parent(self, domain=\"FC\") @property def tpi_params(self) -> Optional[float]: # 1100 return self._get_msg_value(\"1100\") @property",
"return self._dhw def _set_dhw(self, dhw: DhwZone) -> None: # self._dhw \"\"\"Set the DHW",
"# elif msg.code == \"30C9\": # zone._temp = zone_dict # if msg.code in",
"f\"{self._ctl.id} (sundial)\" SYSTEM_CLASSES = { SystemType.CHRONOTHERM: Chronotherm, SystemType.EVOHOME: Evohome, SystemType.HOMETRONICS: Hometronics, SystemType.PROGRAMMER: Programmer,",
"in sorted(self._ctl.devices)} return status class System(StoredHw, SysDatetime, SystemBase): # , SysFaultLog \"\"\"The Controller",
"ctl self._domain_id = \"FF\" self._evo = None self._heat_demand = None self._htg_control = None",
"\"3EF1\"): device._send_cmd(code, qos) if msg.code == \"3150\" and msg.verb in (\" I\", \"RP\"):",
"& orphans or zoneless)\", {d.id: d.temperature for d in testable_sensors}, ) if testable_sensors:",
"\"FC\": device = self.heating_control else: device = None if False and device is",
"__repr__(self) -> str: return f\"{self._ctl.id} (sys_base)\" # def __str__(self) -> str: # TODO:",
"else: # xxx(msg.payload) if msg.code in (\"000A\", \"2309\", \"30C9\") and isinstance(msg.payload, list): pass",
"discover_flag=DISCOVER_ALL) -> None: # super()._discover(discover_flag=discover_flag) # will RP to: 0005/configured_zones_alt, but not: configured_zones",
"a sensor... if len(matching_sensors) == 0: _LOGGER.debug(\" - matched sensor: %s (by exclusion)\",",
"in msg.payload and msg.payload[\"domain_id\"] == \"FC\": self._heat_demand = msg.payload # if msg.code in",
"return # TODO: should have a (not-None) temperature matching_sensors = [ s for",
"\"0008\" and msg.verb in (\" I\", \"RP\"): if \"domain_id\" in msg.payload: self._relay_demands[msg.payload[\"domain_id\"]] =",
"self.zones if z.sensor is None]) == 0: return # (currently) no zone without",
"= super().params assert ATTR_HTG_SYSTEM in params # TODO: removeme assert \"language\" not in",
"ATTR_ORPHANS, ATTR_UFH_SYSTEM, ATTR_ZONES, DISABLE_DISCOVERY, MAX_ZONES, ) from .zones import DhwZone, Zone DEV_MODE =",
"super().status # TODO: removeme return {**super().status, ATTR_ZONES: {z.idx: z.status for z in self._zones}}",
"have params # assert ATTR_HTG_CONTROL not in params[ATTR_HTG_SYSTEM] # TODO: removeme # params[ATTR_HTG_SYSTEM][ATTR_HTG_CONTROL]",
"and s._zone in (zone_idx, None) ] _LOGGER.debug(\"Testing zone %s, temp: %s\", zone_idx, temp)",
"considered more authorative. The RQ is initiated by the DHW, so is not",
"\"RQ\": if this.src is self and this.dst.type in (\"10\", \"13\"): heater = this.dst",
"[ s for s in testable_sensors if s.temperature == temp and s._zone in",
"-> dict: assert ATTR_ZONES not in super().schema # TODO: removeme return {**super().schema, ATTR_ZONES:",
"in self._ctl.devices if not d._domain_id and d.type != \"02\"] ) # devices without",
"(evohome)\" def _discover(self, discover_flag=DISCOVER_ALL) -> None: super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_STATUS: self._send_cmd(\"1F09\") def",
"in [v for k, v in changed_zones.items() if k != z] + [None]",
"await asyncio.sleep(TIMER_SHORT_SLEEP) # if dt.now() > time_start + TIMER_LONG_TIMEOUT: # self._api_lock.release() # raise",
"zone = self.zone_by_idx[zone_idx] zone._set_sensor(matching_sensors[0]) zone.sensor._set_ctl(self) elif len(matching_sensors) == 0: _LOGGER.debug(\" - no matching",
"{z.idx: z.schema for z in self._zones}} @property def params(self) -> dict: assert ATTR_ZONES",
"relay (10: or 13:) for this system. There's' 3 ways to find a",
"--:------ 10A0 006 00181F0003E4 # 062 RP --- 01:102458 07:030741 --:------ 10A0 006",
"DhwZone, Zone DEV_MODE = __dev_mode__ _LOGGER = logging.getLogger(__name__) if DEV_MODE: _LOGGER.setLevel(logging.DEBUG) class SysFaultLog:",
"if kwargs.get(\"htg_valve\"): zone._set_dhw_valve(kwargs[\"htg_valve\"]) if sensor is not None: zone._set_dhw_sensor(sensor) return zone @property def",
"sensor testable_zones = { z: t for z, t in changed_zones.items() if self.zone_by_idx[z].sensor",
"# TODO:use is? return this.src is prev.dst and this.dst is prev.src.addr def OUT_find_htg_relay(this,",
"sorted(self._ctl.devices)} return schema @property def params(self) -> dict: \"\"\"Return the system's configuration.\"\"\" params",
"msg.code == \"0009\": self._relay_failsafes[idx] = msg elif msg.code == \"3150\": self._heat_demands[idx] = msg",
"& DISCOVER_STATUS: self._send_cmd(\"1F09\") class Programmer(Evohome): def __repr__(self) -> str: return f\"{self._ctl.id} (programmer)\" class",
"**kwargs) -> None: super().__init__(*args, **kwargs) self._language = None def _discover(self, discover_flag=DISCOVER_ALL) -> None:",
"sorted(self._ctl.devices) if d.type == \"02\" }, } @property def params(self) -> dict: assert",
"return zone @property def _zones(self) -> dict: return sorted(self.zones, key=lambda x: x.idx) @property",
"for payload in (\"0000\", \"00\", \"F8\", \"F9\", \"FA\", \"FB\", \"FC\", \"FF\"): # #",
"(\" I\", \"RP\"): # this is a special case self._system_mode = msg @property",
"self._htg_control is None: self._htg_control = device device._set_parent(self, domain=\"FC\") @property def tpi_params(self) -> Optional[float]:",
"in params[ATTR_HTG_SYSTEM] # TODO: removeme params[ATTR_HTG_SYSTEM][\"system_mode\"] = self.system_mode return params class StoredHw: MIN_SETPOINT",
"_get_zone(self, zone_idx, sensor=None, **kwargs) -> Zone: \"\"\"Return a zone (will create it if",
"in zone.devices]: zone.devices.append(device) zone.device_by_id[device.id] = device if sensor is not None: zone._set_sensor(sensor) return",
"-> dict: assert ATTR_UFH_SYSTEM not in super().params # TODO: removeme return { **super().params,",
"# TODO: removeme assert ATTR_HTG_CONTROL not in schema[ATTR_HTG_SYSTEM] # TODO: removeme schema[ATTR_HTG_SYSTEM][ATTR_HTG_CONTROL] =",
"3B00 002 00C8 # 09:04:02.667 045 I --- 01:145038 --:------ 01:145038 3B00 002",
"super().params # TODO: removeme return {**super().params, ATTR_DHW_SYSTEM: self.dhw.params if self.dhw else {}} @property",
"self._send_cmd(\"0005\", payload=f\"00{zone_type}\") for zone_type in (\"08\", \"09\", \"0A\", \"0B\", \"11\") # CODE_0005_ZONE_TYPE ]",
"matching zone/sensor temperatures. The temperature of each zone is reliably known (30C9 array),",
"and this.verb == \"RQ\": if this.src is self and this.dst.type == \"10\": heater",
"{}} assert ATTR_HTG_SYSTEM in schema # TODO: removeme assert ATTR_HTG_CONTROL not in schema[ATTR_HTG_SYSTEM]",
"elif msg.code == \"0005\" and prev_msg is not None: # zone_added = bool(prev_msg.code",
"DHW zone's sensor & valves?. \"\"\" def create_dhw(zone_idx) -> DhwZone: if self.dhw: raise",
"from typing import List, Optional from .command import Command, FaultLog, Priority from .const",
"0005: find any zones + their type (RAD, UFH, VAL, MIX, ELE) self._send_cmd(\"0005\",",
"if sensor is not None: zone._set_dhw_sensor(sensor) return zone @property def dhw(self) -> DhwZone:",
"None: super().__init__(*args, **kwargs) self._system_mode = None def _discover(self, discover_flag=DISCOVER_ALL) -> None: super()._discover(discover_flag=discover_flag) if",
"None # HACK for 10: def _set_htg_control(self, device: Device) -> None: # self._htg_control",
"\"10A0\" and this.verb == \"RP\": if this.src is self and this.dst.type == \"07\":",
"== \"2E04\" and msg.verb in (\" I\", \"RP\"): # this is a special",
"in changed_zones.items() if self.zone_by_idx[z].sensor is None and t not in [v for k,",
"--:------ 10A0 006 0018380003E8 # 1260: I/07: can't get which parent controller -",
"dhw: return raise CorruptStateError(\"DHW shouldn't change: {self._dhw} to {dhw}\") if self._dhw is None:",
"Zone: if int(zone_idx, 16) >= self._gwy.config[MAX_ZONES]: raise ValueError(f\"Invalid zone idx: {zone_idx} (exceeds max_zones)\")",
"sensor # if self._gwy.serial_port: # only if in monitor mode... secs = self._get_msg_value(\"1F09\",",
"self._heat_demands: return {k: v.payload[\"heat_demand\"] for k, v in self._heat_demands.items()} @property def relay_demands(self) ->",
"for d in testable_sensors}, ) if testable_sensors: # the main matching algorithm... for",
"import List, Optional from .command import Command, FaultLog, Priority from .const import (",
"unique (non-null) temps, and no sensor _LOGGER.debug( \" - with unique/non-null temps (from",
"assert ATTR_HTG_CONTROL not in status[ATTR_HTG_SYSTEM] # TODO: removeme # status[ATTR_HTG_SYSTEM][ATTR_HTG_CONTROL] = ( #",
"this.verb == \" I\" and prev is not None: if prev.code == this.code",
"-> dict: assert ATTR_UFH_SYSTEM not in super().status # TODO: removeme return { **super().status,",
"if s.temperature == temp and s._zone in (zone_idx, None) ] _LOGGER.debug(\"Testing zone %s,",
"cycle testable_zones = { z: t for z, t in changed_zones.items() if self.zone_by_idx[z].sensor",
"if self._htg_control is None: self._htg_control = device device._set_parent(self, domain=\"FC\") @property def tpi_params(self) ->",
"temps during this cycle testable_zones = { z: t for z, t in",
"of reliability): 1. The 3220 RQ/RP *to/from a 10:* (1x/5min) 2a. The 3EF0",
"self._dhw def _set_dhw(self, dhw: DhwZone) -> None: # self._dhw \"\"\"Set the DHW zone",
"== 0: _LOGGER.debug(\" - matched sensor: %s (by exclusion)\", self._ctl.id) zone = self.zone_by_idx[zone_idx]",
"\"2309\": # zone._temp = zone_dict # elif msg.code == \"30C9\": # zone._temp =",
"3220 005 0000050000 # 18:14:14.446 065 RP --- 10:067219 01:078710 --:------ 3220 005",
"self._domain_id = \"FF\" self._evo = None self._heat_demand = None self._htg_control = None def",
"# TODO: opentherm: 1FD4, 22D9, 3220 # if discover_flag & DISCOVER_PARAMS: # for",
"== \"0004\") # else zone_deleted # elif msg.code == \"30C9\" and isinstance(msg.payload, list):",
"super().__init__(gwy, **kwargs) self.id = ctl.id gwy.systems.append(self) gwy.system_by_id[self.id] = self self._ctl = ctl self._domain_id",
"@property def heat_demand(self) -> Optional[float]: # 3150/FC if self._heat_demand: return self._heat_demand[\"heat_demand\"] @property def",
"prev): # TODO:use is? return this.src is prev.dst and this.dst is prev.src.addr def",
"_discover(self, discover_flag=DISCOVER_ALL) -> None: super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_STATUS: # self._send_cmd(\"2E04\", payload=\"FF\") #",
"2a. The 3EF0 RQ/RP *to/from a 10:* (1x/1min) 2b. The 3EF0 RQ (no",
"removeme assert \"datetime\" not in status[ATTR_HTG_SYSTEM] # TODO: removeme status[ATTR_HTG_SYSTEM][\"datetime\"] = self.datetime return",
"zone %s, temp: %s\", zone_idx, temp) _LOGGER.debug( \" - matching sensor(s): %s (same",
"self._msg_payload(self._datetime, \"datetime\") # TODO: make a dt object # def wait_for(self, cmd, callback):",
"announce temp, ?also includes it's parent zone matching_sensors = [ s for s",
"is not self: # raise LookupError if self._htg_control is None: self._htg_control = device",
"zone is reliably known (30C9 array), but the sensor for each zone is",
"zone_deleted # elif msg.code == \"30C9\" and isinstance(msg.payload, list): # msg.is_array: # find_zone_sensors()",
"RP/01/07: can get both parent controller & DHW sensor # 047 RQ ---",
"unfortunately it does not announce its sensor temperatures. In addition, there may be",
"int(zone_idx, 16) >= self._gwy.config[MAX_ZONES]: raise ValueError(f\"Unknown zone_idx/domain_id: {zone_idx}\") zone = self.zone_by_idx.get(zone_idx) if zone",
"discover_flag=DISCOVER_ALL) -> None: # super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_SCHEMA: [ # 000C: find",
"params @property def status(self) -> dict: \"\"\"Return the system's current state.\"\"\" status =",
"045 I --- 01:145038 --:------ 01:145038 1F41 012 000004FFFFFF1E060E0507E4 # 045 I ---",
"zone uses the controller as a sensor. \"\"\" prev_msg, self._prev_30c9 = self._prev_30c9, msg",
"\"\"\" prev_msg, self._prev_30c9 = self._prev_30c9, msg if prev_msg is None: return if len([z",
"(\"0000\", \"00\", \"F8\", \"F9\", \"FA\", \"FB\", \"FC\", \"FF\"): # # self._send_cmd(code, payload=payload) #",
"064 RQ --- 01:078710 10:067219 --:------ 3EF0 001 00 # 14:41:46.631 063 RP",
"params[ATTR_HTG_SYSTEM] # TODO: removeme params[ATTR_HTG_SYSTEM][\"language\"] = self.language return params class SysMode: # 2E04",
"{**super().status, ATTR_ZONES: {z.idx: z.status for z in self._zones}} class UfhSystem: @property def schema(self)",
"if self._dhw is None: # self._gwy._get_device(xxx) # self.add_device(dhw.sensor) # self.add_device(dhw.relay) self._dhw = dhw",
"zone sensors def _discover(self, discover_flag=DISCOVER_ALL) -> None: super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_SCHEMA: [",
"= None # self._prev_30c9 = None # OUT: used to discover zone sensors",
"self._dhw = DhwZone(self) if not self._gwy.config[DISABLE_DISCOVERY]: dhw._discover() # discover_flag=DISCOVER_ALL) return dhw if zone_idx",
"prev_msg.payload } # zones with changed temps _LOGGER.debug(\"Changed zones (from 30C9): %s\", changed_zones)",
"sensor(s): %s (excl. controller)\", [s.id for s in matching_sensors], ) # can safely(?)",
"== temp and s._zone in (zone_idx, None) ] _LOGGER.debug(\"Testing zone %s, temp: %s\",",
"\"HW\": return super()._get_zone(zone_idx, sensor=sensor, **kwargs) if int(zone_idx, 16) >= self._gwy.config[MAX_ZONES]: raise ValueError(f\"Unknown zone_idx/domain_id:",
"0: _LOGGER.debug(\" - no matching sensor (uses CTL?)\") else: _LOGGER.debug(\" - multiple sensors:",
"3EF0 001 00 # 06:49:05.467 045 RQ --- 01:145038 13:237335 --:------ 3EF0 001",
"ATTR_UFH_SYSTEM, ATTR_ZONES, DISABLE_DISCOVERY, MAX_ZONES, ) from .zones import DhwZone, Zone DEV_MODE = __dev_mode__",
"and this.verb == \"RP\": if this.src is self and this.dst.type == \"07\": sensor",
"their type (RAD, UFH, VAL, MIX, ELE) self._send_cmd(\"0005\", payload=f\"00{zone_type}\") for zone_type in (\"08\",",
"multiple sensors: %s\", matching_sensors) _LOGGER.debug(\"System state (after): %s\", self) # now see if",
"return {**super().params, ATTR_DHW_SYSTEM: self.dhw.params if self.dhw else {}} @property def status(self) -> dict:",
"} class SystemBase(Entity): # 3B00 (multi-relay) \"\"\"The most basic controllers - a generic",
"self._get_msg_value(\"1F09\", \"remaining_seconds\") if secs is None or msg.dtm > prev_msg.dtm + td(seconds=secs): return",
"configured_zones # will RP to: 0004 if discover_flag & DISCOVER_STATUS: self._send_cmd(\"1F09\") class Programmer(Evohome):",
"useful. \"\"\" # 10A0: RQ/07/01, RP/01/07: can get both parent controller & DHW",
"sensor _LOGGER.debug( \" - with unique/non-null temps (from 30C9), no sensor (from state):",
"for zone_idx in self.zone_by_idx: cmd = Command.get_zone_mode(self.id, zone_idx, priority=Priority.LOW) self._gwy.send_cmd(cmd) # for zone",
"(\"000A\", \"2309\", \"30C9\") and not isinstance(msg.payload, list): pass else: super()._handle_msg(msg) if msg.code ==",
"be a sensor for a zones # TODO: where to put this? #",
"06:49:07.468 045 RQ --- 01:145038 13:237335 --:------ 3EF0 001 00 # 09:03:59.693 051",
"sensor is not None: zone._set_sensor(sensor) return zone @property def _zones(self) -> dict: return",
"each zone is not. In particular, the controller may be a sensor for",
"(\"0008\", \"3EF1\"): device._send_cmd(code, qos) if msg.code == \"3150\" and msg.verb in (\" I\",",
"045 RQ --- 01:145038 13:237335 --:------ 3EF0 001 00 # 06:49:07.468 045 RQ",
"# devices without a parent zone, NB: CTL can be a sensor for",
"00 # 14:41:46.631 063 RP --- 10:067219 01:078710 --:------ 3EF0 006 0000100000FF #",
"sensor temp matching - non-deterministic Data from the CTL is considered more authorative.",
"params # # for code in (\"3B00\",): # 3EF0, 3EF1 # # for",
"TODO: removeme return { **super().schema, ATTR_UFH_SYSTEM: { d.id: d.schema for d in sorted(self._ctl.devices)",
"the controller as a sensor... if self._zone is not None: return # the",
"-> dict: status = super().status assert ATTR_HTG_SYSTEM in status # TODO: removeme assert",
"# will RP to: 0004 if discover_flag & DISCOVER_STATUS: self._send_cmd(\"1F09\") class Programmer(Evohome): def",
"is None: self._htg_control = device device._set_parent(self, domain=\"FC\") @property def tpi_params(self) -> Optional[float]: #",
") assert ATTR_ORPHANS not in schema[ATTR_HTG_SYSTEM] # TODO: removeme schema[ATTR_ORPHANS] = sorted( [d.id",
"= DhwZone(self) if not self._gwy.config[DISABLE_DISCOVERY]: dhw._discover() # discover_flag=DISCOVER_ALL) return dhw if zone_idx !=",
"zone._set_zone_type(kwargs[\"zone_type\"]) if kwargs.get(\"actuators\"): # TODO: check not an address before implmenting for device",
"but the sensor for each zone is not. In particular, the controller may",
"# 0005 (+/- 000C?) def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self.zones",
"006 0000100000FF # noqa # 06:49:03.465 045 RQ --- 01:145038 13:237335 --:------ 3EF0",
"in msg.payload: self._relay_demands[msg.payload[\"domain_id\"]] = msg if msg.payload[\"domain_id\"] == \"F9\": device = self.dhw.heating_valve if",
"\"Testable sensors: %s (non-null temps & orphans or zoneless)\", {d.id: d.temperature for d",
"# ) assert \"tpi_params\" not in params[ATTR_HTG_SYSTEM] # TODO: removeme params[ATTR_HTG_SYSTEM][\"tpi_params\"] = (",
"# failsafe_enabled @property def status(self) -> dict: \"\"\"Return the system's current state.\"\"\" status",
"= { SystemType.CHRONOTHERM: Chronotherm, SystemType.EVOHOME: Evohome, SystemType.HOMETRONICS: Hometronics, SystemType.PROGRAMMER: Programmer, SystemType.SUNDIAL: Sundial, SystemType.GENERIC:",
"is None: self._get_zone(\"FA\") self.dhw._set_sensor(sensor) super()._handle_msg(msg) if msg.code in (\"10A0\", \"1260\"): # self.dhw.sensor is",
"elif msg.code == \"30C9\" and isinstance(msg.payload, list): # msg.is_array: # find_zone_sensors() def _get_zone(self,",
"0x100): # self._send_cmd(\"0008\", payload=f\"{domain_id:02X}00\") pass def _handle_msg(self, msg) -> bool: def OUT_is_exchange(this, prev):",
"= super().params assert ATTR_HTG_SYSTEM in params # TODO: removeme assert \"system_mode\" not in",
"else None elif msg.payload[\"domain_id\"] == \"FC\": device = self.heating_control else: device = None",
"False, msg.code @property def heat_demands(self) -> Optional[dict]: # 3150 if self._heat_demands: return {k:",
"heater = None if this.code == \"3220\" and this.verb == \"RQ\": if this.src",
"need to match temps # 045 I --- 07:045960 --:------ 07:045960 1260 003",
"OUT_find_htg_relay(this, prev=None): \"\"\"Discover the heat relay (10: or 13:) for this system. There's'",
"if z.sensor is None]) == 0: return # (currently) no zone without a",
"--:------ 3EF0 001 00 # 14:41:46.631 063 RP --- 10:067219 01:078710 --:------ 3EF0",
"(hometronics)\" def _discover(self, discover_flag=DISCOVER_ALL) -> None: # super()._discover(discover_flag=discover_flag) # will RP to: 0005/configured_zones_alt,",
"0100 return self._msg_payload(self._language, \"language\") @property def params(self) -> dict: params = super().params assert",
"the system's current state.\"\"\" status = {ATTR_HTG_SYSTEM: {}} assert ATTR_HTG_SYSTEM in status #",
"in range(0xF8, 0x100): # self._send_cmd(\"0008\", payload=f\"{domain_id:02X}00\") pass def _handle_msg(self, msg) -> bool: def",
"- need to match temps # 045 I --- 07:045960 --:------ 07:045960 1260",
"+ TIMER_LONG_TIMEOUT: # self._api_lock.release() # raise ExpiredCallbackError(\"failed to set schedule\") # self._api_lock.release() #",
"@property def params(self) -> dict: params = super().params assert ATTR_HTG_SYSTEM in params #",
"@property def heating_control(self) -> Device: if self._htg_control: return self._htg_control htg_control = [d for",
"{device}\") if self._htg_control is not None: if self._htg_control is device: return raise CorruptStateError(",
"controller's DHW sensor: 1. The 10A0 RQ/RP *from/to a 07:* (1x/4h) - reliable",
"(10: or 13:) for this system. There's' 3 ways to find a controller's",
"-> dict: \"\"\"Return the system's current state.\"\"\" status = super().status assert ATTR_HTG_SYSTEM in",
"Lock from typing import List, Optional from .command import Command, FaultLog, Priority from",
"d for d in self._gwy.devices # not: self.devices if d._ctl in (self, None)",
") if testable_sensors: # the main matching algorithm... for zone_idx, temp in testable_zones.items():",
"if k != z] + [None] } # ...with unique (non-null) temps, and",
"the sensor for each zone is not. In particular, the controller may be",
"for s in matching_sensors], ) if len(matching_sensors) == 1: _LOGGER.debug(\" - matched sensor:",
"self._dhw \"\"\"Set the DHW zone system.\"\"\" if not isinstance(dhw, DhwZone): raise TypeError(f\"stored_hw can't",
"msg.code == \"0008\" and msg.verb in (\" I\", \"RP\"): if \"domain_id\" in msg.payload:",
"# TODO: removeme # schema[\"devices\"] = {d.id: d.device_info for d in sorted(self._ctl.devices)} return",
"Device: if self._htg_control: return self._htg_control htg_control = [d for d in self._ctl.devices if",
"cmd = Command.get_zone_mode(self.id, zone_idx, priority=Priority.LOW) self._gwy.send_cmd(cmd) # for zone in self.zones: # zone._discover(discover_flags=DISCOVER_PARAMS)",
"None @property def heating_valve(self) -> Device: return self._dhw._htg_valve if self._dhw else None @property",
"= super().status assert \"fault_log\" not in status # TODO: removeme status[\"fault_log\"] = self._fault_log.fault_log",
"RQ --- 01:078710 10:067219 --:------ 3220 005 0000050000 # 18:14:14.446 065 RP ---",
"prev_msg=None): super()._handle_msg(msg) if msg.code == \"313F\" and msg.verb in (\" I\", \"RP\"): #",
"and prev is not None: if prev.code == this.code and prev.verb == this.verb:",
"packets, or pairs of packets, to maintain the system state.\"\"\" def OUT_find_dhw_sensor(this): \"\"\"Discover",
"TODO: removeme # schema[\"devices\"] = {d.id: d.device_info for d in sorted(self._ctl.devices)} return schema",
"--:------ 07:045960 1260 003 000911 # 1F41: I/01: get parent controller, but not",
"return { **super().params, ATTR_UFH_SYSTEM: { d.id: d.params for d in sorted(self._ctl.devices) if d.type",
"shouldn't change: {self._htg_control} to {device}\" ) # if device.evo is not None and",
"if self._dhw is dhw: return raise CorruptStateError(\"DHW shouldn't change: {self._dhw} to {dhw}\") if",
"return {**super().params, ATTR_ZONES: {z.idx: z.params for z in self._zones}} @property def status(self) ->",
"ExpiredCallbackError: return @property def status(self) -> dict: status = super().status assert \"fault_log\" not",
"xxx(msg.payload) if msg.code in (\"000A\", \"2309\", \"30C9\") and isinstance(msg.payload, list): pass class Chronotherm(Evohome):",
"assert \"datetime\" not in status[ATTR_HTG_SYSTEM] # TODO: removeme status[ATTR_HTG_SYSTEM][\"datetime\"] = self.datetime return status",
"self._relay_demands: return { k: v.payload[\"relay_demand\"] for k, v in self._relay_demands.items() } @property def",
"for domain_id in range(0xF8, 0x100): # self._send_cmd(\"0009\", payload=f\"{domain_id:02X}00\") if discover_flag & DISCOVER_STATUS: #",
"%s\", testable_zones, ) if not testable_zones: return # no testable zones testable_sensors =",
"# # for code in (\"3B00\",): # 3EF0, 3EF1 # # for payload",
"discover_flag & DISCOVER_PARAMS: self._send_cmd(\"0100\") # language def _handle_msg(self, msg, prev_msg=None): super()._handle_msg(msg) if msg.code",
"(before): %s\", self) changed_zones = { z[\"zone_idx\"]: z[\"temperature\"] for z in msg.payload if",
"{} # failsafe_enabled @property def status(self) -> dict: \"\"\"Return the system's current state.\"\"\"",
"heat relay (10: or 13:) for this system. There's' 3 ways to find",
"TODO: removeme return {**super().params, ATTR_ZONES: {z.idx: z.params for z in self._zones}} @property def",
"ATTR_UFH_SYSTEM: { d.id: d.params for d in sorted(self._ctl.devices) if d.type == \"02\" },",
"__init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self._fault_log = FaultLog(self._ctl) def _discover(self, discover_flag=DISCOVER_ALL)",
"discover_flag & DISCOVER_SCHEMA: [ # 000C: find the HTG relay and DHW sensor,",
"prev.src.addr def OUT_find_htg_relay(this, prev=None): \"\"\"Discover the heat relay (10: or 13:) for this",
"Auto, set non-PermanentOverride zones to FollowSchedule.\"\"\" return self.set_mode(SystemMode.AUTO) def reset_mode(self) -> Task: \"\"\"Revert",
"_LOGGER.debug(\" - multiple sensors: %s\", matching_sensors) _LOGGER.debug(\"System state (after): %s\", self) # now",
"str: return f\"{self._ctl.id} (system)\" def _handle_msg(self, msg) -> bool: super()._handle_msg(msg) if \"domain_id\" in",
"class UfhSystem: @property def schema(self) -> dict: assert ATTR_UFH_SYSTEM not in super().schema #",
"(\"0001\", \"000C\", \"0418\", \"1100\", \"3B00\"): assert False, msg.code @property def heat_demands(self) -> Optional[dict]:",
"zone in self.zones: # zone._discover(discover_flags=DISCOVER_PARAMS) if msg.code in (\"000A\", \"2309\", \"30C9\"): pass #",
"**super().schema, ATTR_UFH_SYSTEM: { d.id: d.schema for d in sorted(self._ctl.devices) if d.type == \"02\"",
"if dt.now() > time_start + TIMER_LONG_TIMEOUT: # self._api_lock.release() # raise ExpiredCallbackError(\"failed to set",
"isinstance(msg.payload, list): # elif msg.code == \"000C\": # self._msgs[f\"{msg.code}\"] = msg # elif",
"# 3150 if self._heat_demands: return {k: v.payload[\"heat_demand\"] for k, v in self._heat_demands.items()} @property",
"find_dhw_sensor(msg) pass elif msg.code in (\"1F41\",): # dhw_mode pass def _get_zone(self, zone_idx, sensor=None,",
"not isinstance(device, Device) or device.type not in (\"10\", \"13\"): raise TypeError(f\"{ATTR_HTG_CONTROL} can't be:",
"not None: if self._dhw is dhw: return raise CorruptStateError(\"DHW shouldn't change: {self._dhw} to",
") return params @property def status(self) -> dict: \"\"\"Return the system's current state.\"\"\"",
"system to Auto, set non-PermanentOverride zones to FollowSchedule.\"\"\" return self.set_mode(SystemMode.AUTO) def reset_mode(self) ->",
"self and this.dst.type == \"10\": heater = this.dst elif this.code == \"3EF0\" and",
"\"FB\", \"FC\", \"FF\"): # # self._send_cmd(code, payload=payload) # # TODO: opentherm: 1FD4, 22D9,",
"temps, and no sensor _LOGGER.debug( \" - with unique/non-null temps (from 30C9), no",
"None def __repr__(self) -> str: return f\"{self._ctl.id} (sys_base)\" # def __str__(self) -> str:",
"True is the system is currently calling for heat.\"\"\" if not self._htg_control: return",
"assert ATTR_ZONES not in super().params # TODO: removeme return {**super().params, ATTR_ZONES: {z.idx: z.params",
"time_start = dt.now() # while not self._schedule_done: # await asyncio.sleep(TIMER_SHORT_SLEEP) # if dt.now()",
"Data from the CTL is considered 'authorative'. The 1FC9 RQ/RP exchange to/from a",
"if ctl is sensor if not testable_zones: return # no testable zones zone_idx,",
"complexity of z._temp # zone = self.zone_by_idx[zone_idx] # if zone._temp is None: #",
"*args, **kwargs) -> None: super().__init__(*args, **kwargs) self._dhw = None def _discover(self, discover_flag=DISCOVER_ALL) ->",
"# 18:14:14.025 066 RQ --- 01:078710 10:067219 --:------ 3220 005 0000050000 # 18:14:14.446",
"sensor for a zones # TODO: where to put this? # assert \"devices\"",
"# await self.wait_for(Command(\"313F\", verb=\" W\", payload=f\"00{dtm_to_hex(dtm)}\")) # return self.datetime @property def status(self) ->",
"a 10:* (1x/5min) 2a. The 3EF0 RQ/RP *to/from a 10:* (1x/1min) 2b. The",
"\"00\") super()._send_cmd(code, dest, payload, **kwargs) @property def devices(self) -> List[Device]: return self._ctl.devices +",
"from .const import ( ATTR_DEVICES, DEVICE_HAS_ZONE_SENSOR, DISCOVER_ALL, DISCOVER_PARAMS, DISCOVER_SCHEMA, DISCOVER_STATUS, SystemMode, SystemType, __dev_mode__,",
"controller may be a sensor for a zone, but unfortunately it does not",
"matching_sensors) _LOGGER.debug(\"System state (after): %s\", self) # now see if we can allocate",
"reliably known (30C9 array), but the sensor for each zone is not. In",
"and this.verb == \"RQ\": if this.src is self and this.dst.type in (\"10\", \"13\"):",
"def get_fault_log(self, force_refresh=None) -> Optional[dict]: # 0418 try: return await self._fault_log.get_fault_log(force_refresh=force_refresh) except ExpiredCallbackError:",
"if self.heating_control else None ) assert ATTR_ORPHANS not in schema[ATTR_HTG_SYSTEM] # TODO: removeme",
"can get both parent controller & DHW sensor # 047 RQ --- 07:030741",
"# xxx(msg.payload) if msg.code in (\"000A\", \"2309\", \"30C9\") and isinstance(msg.payload, list): pass class",
"(sys_base)\" # def __str__(self) -> str: # TODO: WIP # return json.dumps({self._ctl.id: self.schema})",
"Zone(self, zone_idx) if not self._gwy.config[DISABLE_DISCOVERY]: # TODO: needs tidyup (ref #67) zone._discover() #",
"# devices don't have params # assert ATTR_HTG_CONTROL not in params[ATTR_HTG_SYSTEM] # TODO:",
"self._heat_demands.items()} @property def relay_demands(self) -> Optional[dict]: # 0008 if self._relay_demands: return { k:",
"exchange to/from a CTL is too rare to be useful. \"\"\" # 18:14:14.025",
"\"FC\"] return htg_control[0] if len(htg_control) == 1 else None # HACK for 10:",
"in self.zone_by_idx: raise LookupError(f\"Duplicated zone: {zone_idx} for {self}\") zone = Zone(self, zone_idx) if",
"(TPI cycle rate, usu. 6x/hr) Data from the CTL is considered 'authorative'. The",
"params(self) -> dict: params = super().params assert ATTR_HTG_SYSTEM in params # TODO: removeme",
"find the HTG relay and DHW sensor, if any (DHW relays in DHW)",
"zone = self.zone_by_idx.get(zone_idx) if zone is None: zone = create_zone(zone_idx) if kwargs.get(\"zone_type\"): zone._set_zone_type(kwargs[\"zone_type\"])",
"-*- coding: utf-8 -*- # \"\"\"Evohome RF - The evohome-compatible system.\"\"\" import logging",
"may be removed MAX_SETPOINT = 85.0 DEFAULT_SETPOINT = 50.0 def __init__(self, *args, **kwargs)",
"payload in (\"0000\", \"00\", \"F8\", \"F9\", \"FA\", \"FB\", \"FC\", \"FF\"): # # self._send_cmd(code,",
"--- 01:145038 13:237335 --:------ 3EF0 001 00 # 06:49:07.468 045 RQ --- 01:145038",
"def _send_cmd(self, code, **kwargs) -> None: dest = kwargs.pop(\"dest_addr\", self._ctl.id) payload = kwargs.pop(\"payload\",",
"msg.code == \"30C9\": # zone._temp = zone_dict # if msg.code in (\"000A\", \"2309\",",
"if DEV_MODE: _LOGGER.setLevel(logging.DEBUG) class SysFaultLog: # 0418 def __init__(self, *args, **kwargs) -> None:",
"TODO: make a dt object # def wait_for(self, cmd, callback): # self._api_lock.acquire() #",
"to {dhw}\") if self._dhw is None: # self._gwy._get_device(xxx) # self.add_device(dhw.sensor) # self.add_device(dhw.relay) self._dhw",
"self.id = ctl.id gwy.systems.append(self) gwy.system_by_id[self.id] = self self._ctl = ctl self._domain_id = \"FF\"",
"= {} def __repr__(self) -> str: return f\"{self._ctl.id} (system)\" def _handle_msg(self, msg) ->",
"asyncio import Task from datetime import timedelta as td from threading import Lock",
"in status[ATTR_HTG_SYSTEM] # TODO: removeme status[ATTR_HTG_SYSTEM][\"datetime\"] = self.datetime return status class SysLanguage: #",
"of packets, to maintain the system state.\"\"\" def OUT_find_dhw_sensor(this): \"\"\"Discover the stored HW",
"sensor... if len(matching_sensors) == 0: _LOGGER.debug(\" - matched sensor: %s (by exclusion)\", self._ctl.id)",
") # if device.evo is not None and device.evo is not self: #",
"domain_id in range(0xF8, 0x100): # self._send_cmd(\"0008\", payload=f\"{domain_id:02X}00\") pass def _handle_msg(self, msg) -> bool:",
"self._zones}} @property def params(self) -> dict: assert ATTR_ZONES not in super().params # TODO:",
"16) >= self._gwy.config[MAX_ZONES]: raise ValueError(f\"Unknown zone_idx/domain_id: {zone_idx}\") zone = self.zone_by_idx.get(zone_idx) if zone is",
"to Auto, force *all* zones to FollowSchedule.\"\"\" return self.set_mode(SystemMode.RESET) @property def params(self) ->",
"if not self._gwy.config[DISABLE_DISCOVERY]: dhw._discover() # discover_flag=DISCOVER_ALL) return dhw if zone_idx != \"HW\": return",
"ATTR_HTG_SYSTEM in status # TODO: removeme # assert ATTR_HTG_CONTROL not in status[ATTR_HTG_SYSTEM] #",
"def __str__(self) -> str: # TODO: WIP # return json.dumps({self._ctl.id: self.schema}) def _discover(self,",
"as a sensor... if self._zone is not None: return # the controller has",
"raise CorruptStateError( f\"{ATTR_HTG_CONTROL} shouldn't change: {self._htg_control} to {device}\" ) # if device.evo is",
"07:045960 1260 003 000911 # 1F41: I/01: get parent controller, but not DHW",
"# TODO: needs tidyup (ref #67) zone._discover() # discover_flag=DISCOVER_ALL) return zone if zone_idx",
"raise ValueError(f\"Unknown zone_idx/domain_id: {zone_idx}\") zone = self.zone_by_idx.get(zone_idx) if zone is None: zone =",
"relay_failsafes(self) -> Optional[dict]: # 0009 if self._relay_failsafes: return {} # failsafe_enabled @property def",
"not in zone.devices]: zone.devices.append(device) zone.device_by_id[device.id] = device if sensor is not None: zone._set_sensor(sensor)",
"prev_msg is None: return if len([z for z in self.zones if z.sensor is",
"system's current state.\"\"\" status = {ATTR_HTG_SYSTEM: {}} assert ATTR_HTG_SYSTEM in status # TODO:",
"in params # TODO: removeme assert \"language\" not in params[ATTR_HTG_SYSTEM] # TODO: removeme",
"# while not self._schedule_done: # await asyncio.sleep(TIMER_SHORT_SLEEP) # if dt.now() > time_start +",
"# 0100 def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self._language = None",
"# if self._gwy.serial_port: # only if in monitor mode... secs = self._get_msg_value(\"1F09\", \"remaining_seconds\")",
"045 I --- 01:145038 --:------ 01:145038 1F41 006 000002FFFFFF sensor = None if",
"-> str: return f\"{self._ctl.id} (system)\" def _handle_msg(self, msg) -> bool: super()._handle_msg(msg) if \"domain_id\"",
"%s\", zone_idx, temp) # want to avoid complexity of z._temp # zone =",
"a neighbour) sensors announcing temperatures with the same value. This leaves only a",
"if len([z for z in self.zones if z.sensor is None]) != 1: return",
"in super().params # TODO: removeme return {**super().params, ATTR_ZONES: {z.idx: z.params for z in",
"v in self._relay_demands.items() } @property def relay_failsafes(self) -> Optional[dict]: # 0009 if self._relay_failsafes:",
"TODO: removeme status[ATTR_HTG_SYSTEM][\"datetime\"] = self.datetime return status class SysLanguage: # 0100 def __init__(self,",
"# system mode self._gwy.send_cmd(Command.get_system_mode(self.id)) def _handle_msg(self, msg, prev_msg=None): super()._handle_msg(msg) if msg.code == \"2E04\"",
"params class StoredHw: MIN_SETPOINT = 30.0 # NOTE: these may be removed MAX_SETPOINT",
"removeme status[ATTR_HTG_SYSTEM][\"heat_demands\"] = self.heat_demands status[ATTR_HTG_SYSTEM][\"relay_demands\"] = self.relay_demands status[ATTR_HTG_SYSTEM][\"relay_failsafes\"] = self.relay_failsafes return status class",
"def params(self) -> dict: assert ATTR_UFH_SYSTEM not in super().params # TODO: removeme return",
"secs is None or msg.dtm > prev_msg.dtm + td(seconds=secs): return # only compare",
"TODO: self.zone_by_idx.get(\"HW\") too? if zone is None: zone = create_dhw(zone_idx) if kwargs.get(\"dhw_valve\"): zone._set_dhw_valve(kwargs[\"dhw_valve\"])",
"== \"02\" }, } class SystemBase(Entity): # 3B00 (multi-relay) \"\"\"The most basic controllers",
"DISCOVER_PARAMS: self._send_cmd(\"0100\") # language def _handle_msg(self, msg, prev_msg=None): super()._handle_msg(msg) if msg.code == \"0100\"",
"-> str: return f\"{self._ctl.id} (evohome)\" def _discover(self, discover_flag=DISCOVER_ALL) -> None: super()._discover(discover_flag=discover_flag) if discover_flag",
"and prev.src.type == \"13\": heater = prev.src if heater is not None: self._set_htg_control(heater)",
"prev.src if heater is not None: self._set_htg_control(heater) if msg.code in (\"000A\", \"2309\", \"30C9\")",
"get which parent controller - need to match temps # 045 I ---",
"{}} class MultiZone: # 0005 (+/- 000C?) def __init__(self, *args, **kwargs) -> None:",
"None ] if discover_flag & DISCOVER_PARAMS: self._send_cmd(\"1100\", payload=\"FC\") # TPI params # #",
"--:------ 3EF0 001 00 # 06:49:05.467 045 RQ --- 01:145038 13:237335 --:------ 3EF0",
"if self.dhw: raise LookupError(f\"Duplicate stored HW: {zone_idx}\") dhw = self._dhw = DhwZone(self) if",
"DISCOVER_SCHEMA, DISCOVER_STATUS, SystemMode, SystemType, __dev_mode__, ) from .devices import Device, Entity from .exceptions",
"--- 01:145038 --:------ 01:145038 1F41 012 000004FFFFFF1E060E0507E4 # 045 I --- 01:145038 --:------",
"or indefinitely.\"\"\" cmd = Command.set_system_mode(self.id, system_mode=system_mode, until=until) return self._gwy.send_cmd(cmd) def set_auto(self) -> Task:",
"\"0008\": self._relay_demands[idx] = msg elif msg.code == \"0009\": self._relay_failsafes[idx] = msg elif msg.code",
"in self._gwy.devices # not: self.devices if d._ctl in (self, None) and d.addr.type in",
"\"FF\" self._evo = None self._heat_demand = None self._htg_control = None def __repr__(self) ->",
"zone_idx, priority=Priority.LOW) self._gwy.send_cmd(cmd) # for zone in self.zones: # zone._discover(discover_flags=DISCOVER_PARAMS) if msg.code in",
"(finally): %s\", self) super()._handle_msg(msg) if msg.code in (\"000A\",) and isinstance(msg.payload, list): for zone_idx",
"zone without a sensor # if self._gwy.serial_port: # only if in monitor mode...",
"= self.heat_demands status[ATTR_HTG_SYSTEM][\"relay_demands\"] = self.relay_demands status[ATTR_HTG_SYSTEM][\"relay_failsafes\"] = self.relay_failsafes return status class Evohome(SysLanguage, SysMode,",
"removeme assert \"language\" not in params[ATTR_HTG_SYSTEM] # TODO: removeme params[ATTR_HTG_SYSTEM][\"language\"] = self.language return",
"(zone_idx, None) ] _LOGGER.debug( \" - matching sensor(s): %s (excl. controller)\", [s.id for",
"\"2309\", \"30C9\"): # if isinstance(msg.payload, list): # super()._handle_msg(msg) # [xxx(z) for z in",
"in (\"000D\", \"000F\") # CODE_000C_DEVICE_TYPE # for dev_type, description in CODE_000C_DEVICE_TYPE.items() fix payload",
"None self._htg_control = None def __repr__(self) -> str: return f\"{self._ctl.id} (sys_base)\" # def",
"to: 0004 if discover_flag & DISCOVER_STATUS: self._send_cmd(\"1F09\") class Programmer(Evohome): def __repr__(self) -> str:",
"{**super().params, ATTR_DHW_SYSTEM: self.dhw.params if self.dhw else {}} @property def status(self) -> dict: assert",
"- non-deterministic Data from the CTL is considered more authorative. The RQ is",
"001 00 # 14:41:46.631 063 RP --- 10:067219 01:078710 --:------ 3EF0 006 0000100000FF",
"= {} self.zone_lock = Lock() self.zone_lock_idx = None # self._prev_30c9 = None #",
"if description is not None ] if discover_flag & DISCOVER_PARAMS: self._send_cmd(\"1100\", payload=\"FC\") #",
"self._htg_control is device: return raise CorruptStateError( f\"{ATTR_HTG_CONTROL} shouldn't change: {self._htg_control} to {device}\" )",
"== \"3150\" and msg.verb in (\" I\", \"RP\"): if \"domain_id\" in msg.payload and",
"_zones(self) -> dict: return sorted(self.zones, key=lambda x: x.idx) @property def schema(self) -> dict:",
"testable_zones = { z: t for z, t in changed_zones.items() if self.zone_by_idx[z].sensor is",
"HW this system (if any). There is only 2 ways to to find",
"- a generic controller (e.g. ST9420C).\"\"\" # 0008|0009|1030|1100|2309|3B00 def __init__(self, gwy, ctl, **kwargs)",
"in (\"000A\", \"2309\", \"30C9\") and not isinstance(msg.payload, list): pass else: super()._handle_msg(msg) if msg.code",
"**kwargs) -> Zone: \"\"\"Return a zone (will create it if required). Can also",
"TODO: removeme schema[ATTR_HTG_SYSTEM][ATTR_HTG_CONTROL] = ( self.heating_control.id if self.heating_control else None ) assert ATTR_ORPHANS",
"zone._discover() # discover_flag=DISCOVER_ALL) return zone if zone_idx == \"HW\": return super()._get_zone(zone_idx, sensor=sensor, **kwargs)",
"ExpiredCallbackError(\"failed to set schedule\") # self._api_lock.release() # async def get_datetime(self) -> str: #",
"{z.idx: z.params for z in self._zones}} @property def status(self) -> dict: assert ATTR_ZONES",
"for d in sorted(self._ctl.devices) if d.type == \"02\" }, } @property def status(self)",
"== \"RQ\": if this.src is self and this.dst.type in (\"10\", \"13\"): heater =",
"range(0xF8, 0x100): # self._send_cmd(\"0009\", payload=f\"{domain_id:02X}00\") if discover_flag & DISCOVER_STATUS: # for domain_id in",
"pass elif msg.code in (\"1F41\",): # dhw_mode pass def _get_zone(self, zone_idx, sensor=None, **kwargs)",
"for a zones # TODO: where to put this? # assert \"devices\" not",
"d.device_info for d in sorted(self._ctl.devices)} return schema @property def params(self) -> dict: \"\"\"Return",
"msg elif msg.code == \"0009\": self._relay_failsafes[idx] = msg elif msg.code == \"3150\": self._heat_demands[idx]",
"msg elif msg.code == \"3150\": self._heat_demands[idx] = msg elif msg.code not in (\"0001\",",
"only 2 ways to to find a controller's DHW sensor: 1. The 10A0",
"01:145038 1F41 012 000004FFFFFF1E060E0507E4 # 045 I --- 01:145038 --:------ 01:145038 1F41 006",
"%s (same temp & not from another zone)\", [s.id for s in matching_sensors],",
"controllers are evohome-compatible.\"\"\" def __init__(self, gwy, ctl, **kwargs) -> None: super().__init__(gwy, ctl, **kwargs)",
"super().params assert ATTR_HTG_SYSTEM in params # TODO: removeme assert \"language\" not in params[ATTR_HTG_SYSTEM]",
"(1x/5min) 2a. The 3EF0 RQ/RP *to/from a 10:* (1x/1min) 2b. The 3EF0 RQ",
"\" - with unique/non-null temps (from 30C9), no sensor (from state): %s\", testable_zones,",
"_handle_msg(self, msg) -> bool: super()._handle_msg(msg) # def xxx(zone_dict): # zone = self.zone_by_idx[zone_dict.pop(\"zone_idx\")] #",
"DISCOVER_STATUS: self._send_cmd(\"0006\") def _handle_msg(self, msg, prev_msg=None): def OUT_find_zone_sensors() -> None: \"\"\"Determine each zone's",
"= msg # elif msg.code == \"0005\" and prev_msg is not None: #",
"v in changed_zones.items() if k != z] + [None] } # ...with unique",
"SysMode: # 2E04 def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self._system_mode =",
"only if in monitor mode... secs = self._get_msg_value(\"1F09\", \"remaining_seconds\") if secs is None",
"this.dst elif this.code == \"3EF0\" and this.verb == \"RQ\": if this.src is self",
"in super().params # TODO: removeme return {**super().params, ATTR_DHW_SYSTEM: self.dhw.params if self.dhw else {}}",
"msg if prev_msg is None: return if len([z for z in self.zones if",
"discover_flag & DISCOVER_STATUS: # self._send_cmd(\"2E04\", payload=\"FF\") # system mode self._gwy.send_cmd(Command.get_system_mode(self.id)) def _handle_msg(self, msg,",
"check not an address before implmenting for device in [d for d in",
"\"FF\"): # # self._send_cmd(code, payload=payload) # # TODO: opentherm: 1FD4, 22D9, 3220 #",
"from threading import Lock from typing import List, Optional from .command import Command,",
"super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_STATUS: self._gwy._tasks.append(self._loop.create_task(self.get_fault_log())) async def get_fault_log(self, force_refresh=None) -> Optional[dict]: #",
"self.dhw.params if self.dhw else {}} @property def status(self) -> dict: assert ATTR_DHW_SYSTEM not",
"ValueError(f\"Unknown zone_idx/domain_id: {zone_idx}\") zone = self.zone_by_idx.get(zone_idx) if zone is None: zone = create_zone(zone_idx)",
"for code in (\"0008\", \"3EF1\"): device._send_cmd(code, qos) if msg.code == \"3150\" and msg.verb",
"return status class SysDatetime: # 313F def __init__(self, *args, **kwargs) -> None: super().__init__(*args,",
"class System(StoredHw, SysDatetime, SystemBase): # , SysFaultLog \"\"\"The Controller class.\"\"\" def __init__(self, gwy,",
"# TODO: removeme # status[ATTR_HTG_SYSTEM][ATTR_HTG_CONTROL] = ( # self.heating_control.status if self.heating_control else None",
"dhw = self._dhw = DhwZone(self) if not self._gwy.config[DISABLE_DISCOVERY]: dhw._discover() # discover_flag=DISCOVER_ALL) return dhw",
"MIN_SETPOINT = 30.0 # NOTE: these may be removed MAX_SETPOINT = 85.0 DEFAULT_SETPOINT",
"- matched sensor: %s\", matching_sensors[0].id) zone = self.zone_by_idx[zone_idx] zone._set_sensor(matching_sensors[0]) zone.sensor._set_ctl(self) elif len(matching_sensors) ==",
"06:49:05.467 045 RQ --- 01:145038 13:237335 --:------ 3EF0 001 00 # 06:49:07.468 045",
") assert \"tpi_params\" not in params[ATTR_HTG_SYSTEM] # TODO: removeme params[ATTR_HTG_SYSTEM][\"tpi_params\"] = ( self.heating_control._get_msg_value(\"1100\")",
"def dhw(self) -> DhwZone: return self._dhw def _set_dhw(self, dhw: DhwZone) -> None: #",
"-> None: dest = kwargs.pop(\"dest_addr\", self._ctl.id) payload = kwargs.pop(\"payload\", \"00\") super()._send_cmd(code, dest, payload,",
"evohome-compatible.\"\"\" def __init__(self, gwy, ctl, **kwargs) -> None: super().__init__(gwy, ctl, **kwargs) def __repr__(self)",
"\"2E04\" and msg.verb in (\" I\", \"RP\"): # this is a special case",
"this is a special case self._system_mode = msg @property def system_mode(self) -> Optional[dict]:",
"self._gwy.config[MAX_ZONES]: raise ValueError(f\"Unknown zone_idx/domain_id: {zone_idx}\") zone = self.zone_by_idx.get(zone_idx) if zone is None: zone",
"-> bool: super()._handle_msg(msg) if \"domain_id\" in msg.payload: idx = msg.payload[\"domain_id\"] if msg.code ==",
"self.devices if d._ctl in (self, None) and d.addr.type in DEVICE_HAS_ZONE_SENSOR and d.temperature is",
"is None: # self._gwy._get_device(xxx) # self.add_device(dhw.sensor) # self.add_device(dhw.relay) self._dhw = dhw @property def",
"already been allocated if len([z for z in self.zones if z.sensor is None])",
"self._send_cmd(\"0008\", payload=f\"{domain_id:02X}00\") pass def _handle_msg(self, msg) -> bool: def OUT_is_exchange(this, prev): # TODO:use",
"msg, prev_msg=None): \"\"\"Eavesdrop packets, or pairs of packets, to maintain the system state.\"\"\"",
"d.addr.type in DEVICE_HAS_ZONE_SENSOR and d.temperature is not None and d._msgs[\"30C9\"].dtm > prev_msg.dtm #",
"relay and DHW sensor, if any (DHW relays in DHW) self._send_cmd(\"000C\", payload=dev_type) for",
"zone %s, temp: %s\", zone_idx, temp) # want to avoid complexity of z._temp",
"removed MAX_SETPOINT = 85.0 DEFAULT_SETPOINT = 50.0 def __init__(self, *args, **kwargs) -> None:",
"\"datetime\" not in status[ATTR_HTG_SYSTEM] # TODO: removeme status[ATTR_HTG_SYSTEM][\"datetime\"] = self.datetime return status class",
"self) # now see if we can allocate the controller as a sensor...",
"005 0000050000 # 18:14:14.446 065 RP --- 10:067219 01:078710 --:------ 3220 005 00C00500FF",
"status = super().status assert ATTR_HTG_SYSTEM in status # TODO: removeme status[ATTR_HTG_SYSTEM][\"heat_demands\"] = self.heat_demands",
"discover_flag=DISCOVER_ALL) -> None: super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_STATUS: self._send_cmd(\"1F09\") def _handle_msg(self, msg) ->",
"+ td(seconds=secs): return # only compare against 30C9 (array) pkt from the last",
"%s (by exclusion)\", self._ctl.id) zone = self.zone_by_idx[zone_idx] zone._set_sensor(self) zone.sensor._set_ctl(self) _LOGGER.debug(\"System state (finally): %s\",",
"self._prev_30c9, msg if prev_msg is None: return if len([z for z in self.zones",
"HTG relay and DHW sensor, if any (DHW relays in DHW) self._send_cmd(\"000C\", payload=dev_type)",
"def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self._dhw = None def _discover(self,",
"status[\"last_fault\"] = self._msgz[\" I\"].get(\"0418\") return status class SysDatetime: # 313F def __init__(self, *args,",
"def _set_dhw(self, dhw: DhwZone) -> None: # self._dhw \"\"\"Set the DHW zone system.\"\"\"",
"\"0C\", \"0F\", \"10\") ] if discover_flag & DISCOVER_STATUS: self._send_cmd(\"0006\") def _handle_msg(self, msg, prev_msg=None):",
"self._dhw = None def _discover(self, discover_flag=DISCOVER_ALL) -> None: super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_STATUS:",
"= prev.src if heater is not None: self._set_htg_control(heater) if msg.code in (\"000A\", \"2309\",",
"30C9 (array) pkt from the last cycle _LOGGER.debug(\"System state (before): %s\", self) changed_zones",
"\"domain_id\" in msg.payload: idx = msg.payload[\"domain_id\"] if msg.code == \"0008\": self._relay_demands[idx] = msg",
"# 3150/FC if self._heat_demand: return self._heat_demand[\"heat_demand\"] @property def is_calling_for_heat(self) -> Optional[bool]: \"\"\"Return True",
"should have a (not-None) temperature matching_sensors = [ s for s in testable_sensors",
"# def __str__(self) -> str: # TODO: WIP # return json.dumps({self._ctl.id: self.schema}) def",
"0: _LOGGER.debug(\" - matched sensor: %s (by exclusion)\", self._ctl.id) zone = self.zone_by_idx[zone_idx] zone._set_sensor(self)",
"self._dhw._dhw_sensor if self._dhw else None @property def hotwater_valve(self) -> Device: return self._dhw._dhw_valve if",
"super().status # TODO: removeme return { **super().status, ATTR_UFH_SYSTEM: { d.id: d.status for d",
"import DhwZone, Zone DEV_MODE = __dev_mode__ _LOGGER = logging.getLogger(__name__) if DEV_MODE: _LOGGER.setLevel(logging.DEBUG) class",
"**kwargs) self._language = None def _discover(self, discover_flag=DISCOVER_ALL) -> None: super()._discover(discover_flag=discover_flag) if discover_flag &",
"# if self.dhw.sensor is None: # find_dhw_sensor(msg) pass elif msg.code in (\"1F41\",): #",
"# if dt.now() > time_start + TIMER_LONG_TIMEOUT: # self._api_lock.release() # raise ExpiredCallbackError(\"failed to",
"zone_idx, temp in testable_zones.items(): # TODO: when sensors announce temp, ?also includes it's",
"3150 if self._heat_demands: return {k: v.payload[\"heat_demand\"] for k, v in self._heat_demands.items()} @property def",
"if self._htg_control is device: return raise CorruptStateError( f\"{ATTR_HTG_CONTROL} shouldn't change: {self._htg_control} to {device}\"",
"not in schema # TODO: removeme # schema[\"devices\"] = {d.id: d.device_info for d",
") from .devices import Device, Entity from .exceptions import CorruptStateError, ExpiredCallbackError from .schema",
"def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self._language = None def _discover(self,",
"CTL & a 13: (TPI cycle rate, usu. 6x/hr) Data from the CTL",
"matching_sensors = [ s for s in testable_sensors if s.temperature == temp and",
"= msg.payload[\"domain_id\"] if msg.code == \"0008\": self._relay_demands[idx] = msg elif msg.code == \"0009\":",
"msg.code == \"313F\" and msg.verb in (\" I\", \"RP\"): # TODO: W self._datetime",
"dict: params = super().params assert ATTR_HTG_SYSTEM in params # TODO: removeme assert \"language\"",
"str: return f\"{self._ctl.id} (programmer)\" class Sundial(Evohome): def __repr__(self) -> str: return f\"{self._ctl.id} (sundial)\"",
"def _discover(self, discover_flag=DISCOVER_ALL) -> None: super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_STATUS: self._gwy.send_cmd(Command.get_system_time(self.id)) # self._send_cmd(\"313F\")",
"and msg.payload[\"domain_id\"] == \"FC\": self._heat_demand = msg.payload # if msg.code in (\"3220\", \"3B00\",",
"{**super().schema, ATTR_ZONES: {z.idx: z.schema for z in self._zones}} @property def params(self) -> dict:",
"self.dhw else None elif msg.payload[\"domain_id\"] == \"FA\": device = self.dhw.hotwater_valve if self.dhw else",
"= msg.payload # if msg.code in (\"3220\", \"3B00\", \"3EF0\"): # self.heating_control is None",
"-> dict: status = super().status assert \"fault_log\" not in status # TODO: removeme",
"self.heat_demands status[ATTR_HTG_SYSTEM][\"relay_demands\"] = self.relay_demands status[ATTR_HTG_SYSTEM][\"relay_failsafes\"] = self.relay_failsafes return status class Evohome(SysLanguage, SysMode, MultiZone,",
"force_refresh=None) -> Optional[dict]: # 0418 try: return await self._fault_log.get_fault_log(force_refresh=force_refresh) except ExpiredCallbackError: return @property",
"self._ctl = ctl self._domain_id = \"FF\" self._evo = None self._heat_demand = None self._htg_control",
"10:* (1x/5min) 2a. The 3EF0 RQ/RP *to/from a 10:* (1x/1min) 2b. The 3EF0",
"to/from a controller, so is not useful. \"\"\" # 10A0: RQ/07/01, RP/01/07: can",
"{device}\" ) # if device.evo is not None and device.evo is not self:",
"] if discover_flag & DISCOVER_PARAMS: self._send_cmd(\"1100\", payload=\"FC\") # TPI params # # for",
"self._relay_failsafes[idx] = msg elif msg.code == \"3150\": self._heat_demands[idx] = msg elif msg.code not",
"-> Device: return self._dhw._htg_valve if self._dhw else None @property def schema(self) -> dict:",
"TODO: removeme return {**super().status, ATTR_DHW_SYSTEM: self.dhw.status if self.dhw else {}} class MultiZone: #",
"dict: \"\"\"Return the system's current state.\"\"\" status = {ATTR_HTG_SYSTEM: {}} assert ATTR_HTG_SYSTEM in",
"super()._handle_msg(msg) # def xxx(zone_dict): # zone = self.zone_by_idx[zone_dict.pop(\"zone_idx\")] # if msg.code == \"000A\":",
"_discover(self, discover_flag=DISCOVER_ALL) -> None: super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_STATUS: self._gwy._tasks.append(self._loop.create_task(self.get_fault_log())) async def get_fault_log(self,",
"# discover_flag=DISCOVER_ALL) return dhw if zone_idx != \"HW\": return zone = self.dhw #",
"\"02\"] ) # devices without a parent zone, NB: CTL can be a",
"super()._discover(discover_flag=discover_flag) # will RP to: 0005/configured_zones_alt, but not: configured_zones # will RP to:",
"no zones have changed temps during this cycle testable_zones = { z: t",
"schema(self) -> dict: assert ATTR_UFH_SYSTEM not in super().schema # TODO: removeme return {",
"d.id: d.status for d in sorted(self._ctl.devices) if d.type == \"02\" }, } class",
"> prev_msg.dtm # changed temp during last cycle ] if _LOGGER.isEnabledFor(logging.DEBUG): _LOGGER.debug( \"Testable",
"not self._gwy.config[DISABLE_DISCOVERY]: dhw._discover() # discover_flag=DISCOVER_ALL) return dhw if zone_idx != \"HW\": return zone",
"-> None: super().__init__(*args, **kwargs) self._fault_log = FaultLog(self._ctl) def _discover(self, discover_flag=DISCOVER_ALL) -> None: super()._discover(discover_flag=discover_flag)",
"so is not authorative. The I/1260 is not to/from a controller, so is",
"params(self) -> dict: assert ATTR_UFH_SYSTEM not in super().params # TODO: removeme return {",
"30C9 says no zones have changed temps during this cycle testable_zones = {",
"ctl, **kwargs) -> None: super().__init__(gwy, ctl, **kwargs) self._heat_demands = {} self._relay_demands = {}",
"is not None: zone._set_sensor(sensor) return zone @property def _zones(self) -> dict: return sorted(self.zones,",
"code, **kwargs) -> None: dest = kwargs.pop(\"dest_addr\", self._ctl.id) payload = kwargs.pop(\"payload\", \"00\") super()._send_cmd(code,",
"DISCOVER_STATUS: self._send_cmd(\"1F09\") def _handle_msg(self, msg) -> bool: super()._handle_msg(msg) # def xxx(zone_dict): # zone",
"TODO: removeme return {**super().params, ATTR_DHW_SYSTEM: self.dhw.params if self.dhw else {}} @property def status(self)",
"self.set_mode(SystemMode.AUTO) def reset_mode(self) -> Task: \"\"\"Revert system to Auto, force *all* zones to",
"a parent zone, NB: CTL can be a sensor for a zones #",
"the heat relay (10: or 13:) for this system. There's' 3 ways to",
"= msg elif msg.code == \"3150\": self._heat_demands[idx] = msg elif msg.code not in",
"a system mode for a specified duration, or indefinitely.\"\"\" cmd = Command.set_system_mode(self.id, system_mode=system_mode,",
"def _discover(self, discover_flag=DISCOVER_ALL) -> None: super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_STATUS: # self._send_cmd(\"2E04\", payload=\"FF\")",
"**super().params, ATTR_UFH_SYSTEM: { d.id: d.params for d in sorted(self._ctl.devices) if d.type == \"02\"",
"isinstance(msg.payload, list): pass class Chronotherm(Evohome): def __repr__(self) -> str: return f\"{self._ctl.id} (chronotherm)\" class",
"I\", \"RP\"): # this is a special case self._system_mode = msg @property def",
"-> Zone: if int(zone_idx, 16) >= self._gwy.config[MAX_ZONES]: raise ValueError(f\"Invalid zone idx: {zone_idx} (exceeds",
"_handle_msg(self, msg) -> bool: def OUT_is_exchange(this, prev): # TODO:use is? return this.src is",
"TODO: FIXME qos = {\"priority\": Priority.LOW, \"retries\": 2} for code in (\"0008\", \"3EF1\"):",
"(\"10A0\", \"1260\"): # self.dhw.sensor is None and # if self.dhw.sensor is None: #",
"reliability): 1. The 3220 RQ/RP *to/from a 10:* (1x/5min) 2a. The 3EF0 RQ/RP",
"zone._set_dhw_sensor(sensor) return zone @property def dhw(self) -> DhwZone: return self._dhw def _set_dhw(self, dhw:",
"00 # 09:03:59.693 051 I --- 13:237335 --:------ 13:237335 3B00 002 00C8 #",
"device is not None: # TODO: FIXME qos = {\"priority\": Priority.LOW, \"retries\": 2}",
"msg.code not in (\"0001\", \"000C\", \"0418\", \"1100\", \"3B00\"): assert False, msg.code @property def",
"DEVICE_HAS_ZONE_SENSOR, DISCOVER_ALL, DISCOVER_PARAMS, DISCOVER_SCHEMA, DISCOVER_STATUS, SystemMode, SystemType, __dev_mode__, ) from .devices import Device,",
"super().__init__(gwy, ctl, **kwargs) self._heat_demands = {} self._relay_demands = {} self._relay_failsafes = {} def",
"TODO: removeme params[ATTR_HTG_SYSTEM][\"language\"] = self.language return params class SysMode: # 2E04 def __init__(self,",
"# wait for the RP/313F # await self.wait_for(Command(\"313F\", verb=\"RQ\")) # return self.datetime #",
"as a means to determine which zone uses the controller as a sensor.",
"this zone is using the CTL as a sensor... if len(matching_sensors) == 0:",
"%s\", changed_zones) if not changed_zones: return # ctl's 30C9 says no zones have",
"list): pass else: super()._handle_msg(msg) if msg.code == \"0008\" and msg.verb in (\" I\",",
"discover_flag=DISCOVER_ALL) -> None: super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_SCHEMA: [ # 0005: find any",
"\"\"\"Return True is the system is currently calling for heat.\"\"\" if not self._htg_control:",
"2E04 def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self._system_mode = None def",
"self._dhw is dhw: return raise CorruptStateError(\"DHW shouldn't change: {self._dhw} to {dhw}\") if self._dhw",
"system. There's' 3 ways to find a controller's heat relay (in order of",
"I\", \"RP\"): # TODO: W self._datetime = msg @property def datetime(self) -> Optional[str]:",
"self.heating_control is None and # find_htg_relay(msg, prev=prev_msg) def _send_cmd(self, code, **kwargs) -> None:",
"== \"0008\": self._relay_demands[idx] = msg elif msg.code == \"0009\": self._relay_failsafes[idx] = msg elif",
"CTL can be a sensor for a zones # TODO: where to put",
"devices without a parent zone, NB: CTL can be a sensor for a",
"import Device, Entity from .exceptions import CorruptStateError, ExpiredCallbackError from .schema import ( ATTR_CONTROLLER,",
"a controller, so is not useful. \"\"\" # 10A0: RQ/07/01, RP/01/07: can get",
"01:102458 --:------ 10A0 006 00181F0003E4 # 062 RP --- 01:102458 07:030741 --:------ 10A0",
"01:145038 1F41 006 000002FFFFFF sensor = None if this.code == \"10A0\" and this.verb",
"is considered more authorative. The RQ is initiated by the DHW, so is",
"# if msg.code in (\"3220\", \"3B00\", \"3EF0\"): # self.heating_control is None and #",
"return await self._fault_log.get_fault_log(force_refresh=force_refresh) except ExpiredCallbackError: return @property def status(self) -> dict: status =",
"# noqa # 06:49:03.465 045 RQ --- 01:145038 13:237335 --:------ 3EF0 001 00",
"control relay for this system (10: or 13:).\"\"\" if not isinstance(device, Device) or",
"0418 try: return await self._fault_log.get_fault_log(force_refresh=force_refresh) except ExpiredCallbackError: return @property def status(self) -> dict:",
"to: 0005/configured_zones_alt, but not: configured_zones # will RP to: 0004 if discover_flag &",
"self.dhw # TODO: self.zone_by_idx.get(\"HW\") too? if zone is None: zone = create_dhw(zone_idx) if",
"SystemMode, SystemType, __dev_mode__, ) from .devices import Device, Entity from .exceptions import CorruptStateError,",
"%s (unique/non-null temps & sensorless)\", testable_zones, ) _LOGGER.debug( \"Testable sensors: %s (non-null temps",
"self.heating_control._get_msg_value(\"1100\") if self.heating_control else None ) return params @property def status(self) -> dict:",
"\"3EF0\"): # self.heating_control is None and # find_htg_relay(msg, prev=prev_msg) def _send_cmd(self, code, **kwargs)",
"in sorted(self._ctl.devices) if d.type == \"02\" }, } @property def status(self) -> dict:",
"self.zone_by_idx.get(zone_idx) if zone is None: zone = create_zone(zone_idx) if kwargs.get(\"zone_type\"): zone._set_zone_type(kwargs[\"zone_type\"]) if kwargs.get(\"actuators\"):",
"# if isinstance(msg.payload, list): # elif msg.code == \"000C\": # self._msgs[f\"{msg.code}\"] = msg",
"a means to determine which zone uses the controller as a sensor. \"\"\"",
"in self.zones if z.sensor is None]) != 1: return # no single zone",
"self and prev.src.type == \"13\": heater = prev.src if heater is not None:",
"@property def datetime(self) -> Optional[str]: return self._msg_payload(self._datetime, \"datetime\") # TODO: make a dt",
"] _LOGGER.debug( \" - matching sensor(s): %s (excl. controller)\", [s.id for s in",
"to put this? # assert \"devices\" not in schema # TODO: removeme #",
"or pairs of packets, to maintain the system state.\"\"\" def OUT_find_dhw_sensor(this): \"\"\"Discover the",
"FCC8 # note the order: most to least reliable heater = None if",
"# self._send_cmd(\"0009\", payload=f\"{domain_id:02X}00\") if discover_flag & DISCOVER_STATUS: # for domain_id in range(0xF8, 0x100):",
"# TODO: removeme assert \"language\" not in params[ATTR_HTG_SYSTEM] # TODO: removeme params[ATTR_HTG_SYSTEM][\"language\"] =",
"temp matching - non-deterministic Data from the CTL is considered more authorative. The",
"note the order: most to least reliable heater = None if this.code ==",
"for the RP/313F # await self.wait_for(Command(\"313F\", verb=\"RQ\")) # return self.datetime # async def",
"{d.id: d.temperature for d in testable_sensors}, ) if testable_sensors: # the main matching",
"I/01: get parent controller, but not DHW sensor # 045 I --- 01:145038",
"return self._dhw._dhw_sensor if self._dhw else None @property def hotwater_valve(self) -> Device: return self._dhw._dhw_valve",
"00 # 06:49:07.468 045 RQ --- 01:145038 13:237335 --:------ 3EF0 001 00 #",
"**kwargs) self._datetime = None def _discover(self, discover_flag=DISCOVER_ALL) -> None: super()._discover(discover_flag=discover_flag) if discover_flag &",
"domain=\"FC\") @property def tpi_params(self) -> Optional[float]: # 1100 return self._get_msg_value(\"1100\") @property def heat_demand(self)",
"we can allocate the controller as a sensor... if self._zone is not None:",
"-> None: super().__init__(gwy, ctl, **kwargs) self._heat_demands = {} self._relay_demands = {} self._relay_failsafes =",
"and # if self.dhw.sensor is None: # find_dhw_sensor(msg) pass elif msg.code in (\"1F41\",):",
"(chronotherm)\" class Hometronics(System): RQ_SUPPORTED = (\"0004\", \"000C\", \"2E04\", \"313F\") # TODO: WIP RQ_UNSUPPORTED",
"if not isinstance(device, Device) or device.type not in (\"10\", \"13\"): raise TypeError(f\"{ATTR_HTG_CONTROL} can't",
"this.verb == \"RQ\": if this.src is self and this.dst.type in (\"10\", \"13\"): heater",
"system - some controllers are evohome-compatible.\"\"\" def __init__(self, gwy, ctl, **kwargs) -> None:",
"testable zones zone_idx, temp = list(testable_zones.items())[0] _LOGGER.debug(\"Testing (sole remaining) zone %s, temp: %s\",",
"{zone_idx}\") dhw = self._dhw = DhwZone(self) if not self._gwy.config[DISABLE_DISCOVERY]: dhw._discover() # discover_flag=DISCOVER_ALL) return",
"changed_zones: return # ctl's 30C9 says no zones have changed temps during this",
"30C9), no sensor (from state): %s\", testable_zones, ) if not testable_zones: return #",
"for z in self._zones}} @property def status(self) -> dict: assert ATTR_ZONES not in",
"if discover_flag & DISCOVER_STATUS: self._gwy.send_cmd(Command.get_system_time(self.id)) # self._send_cmd(\"313F\") def _handle_msg(self, msg, prev_msg=None): super()._handle_msg(msg) if",
"# 0009 if self._relay_failsafes: return {} # failsafe_enabled @property def status(self) -> dict:",
"params[ATTR_HTG_SYSTEM][\"system_mode\"] = self.system_mode return params class StoredHw: MIN_SETPOINT = 30.0 # NOTE: these",
"3. The 3B00 I/I exchange between a CTL & a 13: (TPI cycle",
"__dev_mode__, ) from .devices import Device, Entity from .exceptions import CorruptStateError, ExpiredCallbackError from",
"of each zone is reliably known (30C9 array), but the sensor for each",
"system state.\"\"\" def OUT_find_dhw_sensor(this): \"\"\"Discover the stored HW this system (if any). There",
"value. This leaves only a process of exclusion as a means to determine",
"in (\"000A\", \"2309\", \"30C9\") and isinstance(msg.payload, list): pass class Chronotherm(Evohome): def __repr__(self) ->",
"self._gwy.config[DISABLE_DISCOVERY]: dhw._discover() # discover_flag=DISCOVER_ALL) return dhw if zone_idx != \"HW\": return zone =",
"import CorruptStateError, ExpiredCallbackError from .schema import ( ATTR_CONTROLLER, ATTR_DHW_SYSTEM, ATTR_HTG_CONTROL, ATTR_HTG_SYSTEM, ATTR_ORPHANS, ATTR_UFH_SYSTEM,",
"addition, there may be 'orphan' (e.g. from a neighbour) sensors announcing temperatures with",
"# not: self.devices if d._ctl in (self, None) and d.addr.type in DEVICE_HAS_ZONE_SENSOR and",
"}, } @property def status(self) -> dict: assert ATTR_UFH_SYSTEM not in super().status #",
"\"000C\", \"2E04\", \"313F\") # TODO: WIP RQ_UNSUPPORTED = (\"xxxx\",) # 10E0? def __repr__(self)",
"self._fault_log.get_fault_log(force_refresh=force_refresh) except ExpiredCallbackError: return @property def status(self) -> dict: status = super().status assert",
"self.dhw else {}} class MultiZone: # 0005 (+/- 000C?) def __init__(self, *args, **kwargs)",
"13:) for this system. There's' 3 ways to find a controller's heat relay",
"d._ctl in (self, None) and d.addr.type in DEVICE_HAS_ZONE_SENSOR and d.temperature is not None",
"if sensor is not None: zone._set_sensor(sensor) return zone @property def _zones(self) -> dict:",
"domain_id in range(0xF8, 0x100): # self._send_cmd(\"0009\", payload=f\"{domain_id:02X}00\") if discover_flag & DISCOVER_STATUS: # for",
"removeme schema[ATTR_HTG_SYSTEM][ATTR_HTG_CONTROL] = ( self.heating_control.id if self.heating_control else None ) assert ATTR_ORPHANS not",
"{ z: t for z, t in changed_zones.items() if self.zone_by_idx[z].sensor is None and",
"order: most to least reliable heater = None if this.code == \"3220\" and",
"LookupError if self._htg_control is None: self._htg_control = device device._set_parent(self, domain=\"FC\") @property def tpi_params(self)",
"msg, prev_msg=None): super()._handle_msg(msg) if msg.code == \"0100\" and msg.verb in (\" I\", \"RP\"):",
"Controller class.\"\"\" def __init__(self, gwy, ctl, **kwargs) -> None: super().__init__(gwy, ctl, **kwargs) self._heat_demands",
"super().params assert ATTR_HTG_SYSTEM in params # TODO: removeme assert \"system_mode\" not in params[ATTR_HTG_SYSTEM]",
"def __repr__(self) -> str: return f\"{self._ctl.id} (programmer)\" class Sundial(Evohome): def __repr__(self) -> str:",
"self) super()._handle_msg(msg) if msg.code in (\"000A\",) and isinstance(msg.payload, list): for zone_idx in self.zone_by_idx:",
"(from 30C9), no sensor (from state): %s\", testable_zones, ) if not testable_zones: return",
"to/from a CTL is too rare to be useful. \"\"\" # 18:14:14.025 066",
"self.heat_demand status[ATTR_DEVICES] = {d.id: d.status for d in sorted(self._ctl.devices)} return status class System(StoredHw,",
"def __repr__(self) -> str: return f\"{self._ctl.id} (evohome)\" def _discover(self, discover_flag=DISCOVER_ALL) -> None: super()._discover(discover_flag=discover_flag)",
"self.zone_by_idx[z].sensor is None and t not in [v for k, v in changed_zones.items()",
"def heating_control(self) -> Device: if self._htg_control: return self._htg_control htg_control = [d for d",
"ctl, **kwargs) self._heat_demands = {} self._relay_demands = {} self._relay_failsafes = {} def __repr__(self)",
"def _discover(self, discover_flag=DISCOVER_ALL) -> None: super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_STATUS: self._send_cmd(\"1F09\") def _handle_msg(self,",
"%s (%s)\", dev_addr.id, self.__class__) super().__init__(gwy, **kwargs) self.id = ctl.id gwy.systems.append(self) gwy.system_by_id[self.id] = self",
"\"language\") @property def params(self) -> dict: params = super().params assert ATTR_HTG_SYSTEM in params",
"self._dhw._dhw_valve if self._dhw else None @property def heating_valve(self) -> Device: return self._dhw._htg_valve if",
"045 RQ --- 01:145038 13:237335 --:------ 3EF0 001 00 # 09:03:59.693 051 I",
"# can safely(?) assume this zone is using the CTL as a sensor...",
"in (\"000A\", \"2309\", \"30C9\"): pass # if isinstance(msg.payload, list): # elif msg.code ==",
"self._dhw else None @property def hotwater_valve(self) -> Device: return self._dhw._dhw_valve if self._dhw else",
"_LOGGER.debug(\"Changed zones (from 30C9): %s\", changed_zones) if not changed_zones: return # ctl's 30C9",
"ATTR_DHW_SYSTEM: self.dhw.schema if self.dhw else {}} @property def params(self) -> dict: assert ATTR_DHW_SYSTEM",
"class Evohome(System): # evohome \"\"\"The Evohome system - some controllers are evohome-compatible.\"\"\" def",
"def schema(self) -> dict: assert ATTR_UFH_SYSTEM not in super().schema # TODO: removeme return",
"'authorative'. The 1FC9 RQ/RP exchange to/from a CTL is too rare to be",
"@property def schema(self) -> dict: assert ATTR_ZONES not in super().schema # TODO: removeme",
"self._dhw else None @property def schema(self) -> dict: assert ATTR_DHW_SYSTEM not in super().schema",
"self._dhw._htg_valve if self._dhw else None @property def schema(self) -> dict: assert ATTR_DHW_SYSTEM not",
"= None def _discover(self, discover_flag=DISCOVER_ALL) -> None: super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_PARAMS: self._send_cmd(\"0100\")",
"the main matching algorithm... for zone_idx, temp in testable_zones.items(): # TODO: when sensors",
"None: # self._gwy._get_device(xxx) # self.add_device(dhw.sensor) # self.add_device(dhw.relay) self._dhw = dhw @property def dhw_sensor(self)",
"TypeError(f\"{ATTR_HTG_CONTROL} can't be: {device}\") if self._htg_control is not None: if self._htg_control is device:",
"# TODO: removeme return {**super().status, ATTR_ZONES: {z.idx: z.status for z in self._zones}} class",
"\"3B00\" and this.verb == \" I\" and prev is not None: if prev.code",
"qos = {\"priority\": Priority.LOW, \"retries\": 2} for code in (\"0008\", \"3EF1\"): device._send_cmd(code, qos)",
"012 000004FFFFFF1E060E0507E4 # 045 I --- 01:145038 --:------ 01:145038 1F41 006 000002FFFFFF sensor",
"and isinstance(msg.payload, list): for zone_idx in self.zone_by_idx: cmd = Command.get_zone_mode(self.id, zone_idx, priority=Priority.LOW) self._gwy.send_cmd(cmd)",
"payload=dev_type) for dev_type in (\"000D\", \"000F\") # CODE_000C_DEVICE_TYPE # for dev_type, description in",
"...with unique (non-null) temps, and no sensor _LOGGER.debug( \" - with unique/non-null temps",
"msg.verb in (\" I\", \"RP\"): # TODO: W self._datetime = msg @property def",
"063 RP --- 10:067219 01:078710 --:------ 3EF0 006 0000100000FF # noqa # 06:49:03.465",
"schema @property def params(self) -> dict: \"\"\"Return the system's configuration.\"\"\" params = {ATTR_HTG_SYSTEM:",
"3B00 (multi-relay) \"\"\"The most basic controllers - a generic controller (e.g. ST9420C).\"\"\" #",
"dict: assert ATTR_UFH_SYSTEM not in super().status # TODO: removeme return { **super().status, ATTR_UFH_SYSTEM:",
"(+/- 000C?) def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self.zones = []",
"without a sensor # if self._gwy.serial_port: # only if in monitor mode... secs",
"(non-null temps & orphans or zoneless)\", {d.id: d.temperature for d in testable_sensors}, )",
"_LOGGER.debug( \" - matching sensor(s): %s (same temp & not from another zone)\",",
"to set schedule\") # self._api_lock.release() # async def get_datetime(self) -> str: # wait",
"**kwargs) -> None: super().__init__(gwy, ctl, **kwargs) def __repr__(self) -> str: return f\"{self._ctl.id} (evohome)\"",
"super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_SCHEMA: [ # 000C: find the HTG relay and",
"\"\"\" # 10A0: RQ/07/01, RP/01/07: can get both parent controller & DHW sensor",
"from datetime import timedelta as td from threading import Lock from typing import",
"-> Optional[str]: # 0100 return self._msg_payload(self._language, \"language\") @property def params(self) -> dict: params",
"and msg.verb in (\" I\", \"RP\"): if \"domain_id\" in msg.payload: self._relay_demands[msg.payload[\"domain_id\"]] = msg",
"assert ATTR_UFH_SYSTEM not in super().params # TODO: removeme return { **super().params, ATTR_UFH_SYSTEM: {",
"= {d.id: d.device_info for d in sorted(self._ctl.devices)} return schema @property def params(self) ->",
"this system. There's' 3 ways to find a controller's heat relay (in order",
"[] self.zone_by_idx = {} # self.zone_by_name = {} self.zone_lock = Lock() self.zone_lock_idx =",
"z: t for z, t in changed_zones.items() if self.zone_by_idx[z].sensor is None and t",
"in (\"08\", \"09\", \"0A\", \"0B\", \"11\") # CODE_0005_ZONE_TYPE ] [ # 0005: find",
"msg.payload[\"domain_id\"] == \"FC\": self._heat_demand = msg.payload # if msg.code in (\"3220\", \"3B00\", \"3EF0\"):",
"self._htg_control = device device._set_parent(self, domain=\"FC\") @property def tpi_params(self) -> Optional[float]: # 1100 return",
"# 2E04 def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self._system_mode = None",
"if kwargs.get(\"zone_type\"): zone._set_zone_type(kwargs[\"zone_type\"]) if kwargs.get(\"actuators\"): # TODO: check not an address before implmenting",
"allocate the controller as a sensor... if self._zone is not None: return #",
"\"313F\" and msg.verb in (\" I\", \"RP\"): # TODO: W self._datetime = msg",
"in params # TODO: removeme # devices don't have params # assert ATTR_HTG_CONTROL",
"ATTR_HTG_SYSTEM in status # TODO: removeme assert \"datetime\" not in status[ATTR_HTG_SYSTEM] # TODO:",
"3EF1 # # for payload in (\"0000\", \"00\", \"F8\", \"F9\", \"FA\", \"FB\", \"FC\",",
"3EF0 001 00 # 06:49:07.468 045 RQ --- 01:145038 13:237335 --:------ 3EF0 001",
"prev=None): \"\"\"Discover the heat relay (10: or 13:) for this system. There's' 3",
"and d.addr.type in DEVICE_HAS_ZONE_SENSOR and d.temperature is not None and d._msgs[\"30C9\"].dtm > prev_msg.dtm",
"a zone, but unfortunately it does not announce its sensor temperatures. In addition,",
"return super()._get_zone(zone_idx, sensor=sensor, **kwargs) if int(zone_idx, 16) >= self._gwy.config[MAX_ZONES]: raise ValueError(f\"Unknown zone_idx/domain_id: {zone_idx}\")",
"else None # HACK for 10: def _set_htg_control(self, device: Device) -> None: #",
"*args, **kwargs) -> None: super().__init__(*args, **kwargs) self._system_mode = None def _discover(self, discover_flag=DISCOVER_ALL) ->",
"this system (if any). There is only 2 ways to to find a",
"Optional[dict]: # 0418 try: return await self._fault_log.get_fault_log(force_refresh=force_refresh) except ExpiredCallbackError: return @property def status(self)",
"zone is None: zone = create_zone(zone_idx) if kwargs.get(\"zone_type\"): zone._set_zone_type(kwargs[\"zone_type\"]) if kwargs.get(\"actuators\"): # TODO:",
"self._ctl.devices if not d._domain_id and d.type != \"02\"] ) # devices without a",
"None elif msg.payload[\"domain_id\"] == \"FA\": device = self.dhw.hotwater_valve if self.dhw else None elif",
"currently calling for heat.\"\"\" if not self._htg_control: return if self._htg_control.actuator_state: return True @property",
"= {\"priority\": Priority.LOW, \"retries\": 2} for code in (\"0008\", \"3EF1\"): device._send_cmd(code, qos) if",
"None: super().__init__(*args, **kwargs) self._datetime = None def _discover(self, discover_flag=DISCOVER_ALL) -> None: super()._discover(discover_flag=discover_flag) if",
"self._send_cmd(\"313F\", verb=\"RQ\", callback=callback) # time_start = dt.now() # while not self._schedule_done: # await",
"if discover_flag & DISCOVER_SCHEMA: [ # 000C: find the HTG relay and DHW",
"--- 01:078710 10:067219 --:------ 3EF0 001 00 # 14:41:46.631 063 RP --- 10:067219",
"to determine which zone uses the controller as a sensor. \"\"\" prev_msg, self._prev_30c9",
"this? # assert \"devices\" not in schema # TODO: removeme # schema[\"devices\"] =",
"can safely(?) assume this zone is using the CTL as a sensor... if",
"htg_control[0] if len(htg_control) == 1 else None # HACK for 10: def _set_htg_control(self,",
"s in matching_sensors], ) if len(matching_sensors) == 1: _LOGGER.debug(\" - matched sensor: %s\",",
"self._send_cmd(\"1F09\") def _handle_msg(self, msg) -> bool: super()._handle_msg(msg) # def xxx(zone_dict): # zone =",
"assert False, msg.code @property def heat_demands(self) -> Optional[dict]: # 3150 if self._heat_demands: return",
"if discover_flag & DISCOVER_PARAMS: self._send_cmd(\"1100\", payload=\"FC\") # TPI params # # for code",
"to find a controller's DHW sensor: 1. The 10A0 RQ/RP *from/to a 07:*",
"zone (will create it if required). Can also set a DHW zone's sensor",
"01:145038 --:------ 01:145038 1F41 012 000004FFFFFF1E060E0507E4 # 045 I --- 01:145038 --:------ 01:145038",
"for s in testable_sensors if s.temperature == temp and s._zone in (zone_idx, None)",
"from the CTL is considered 'authorative'. The 1FC9 RQ/RP exchange to/from a CTL",
"*to a 13:* (3x/60min) 3. The 3B00 I/I exchange between a CTL &",
"xxx(zone_dict): # zone = self.zone_by_idx[zone_dict.pop(\"zone_idx\")] # if msg.code == \"000A\": # zone._zone_config =",
"**kwargs) self._dhw = None def _discover(self, discover_flag=DISCOVER_ALL) -> None: super()._discover(discover_flag=discover_flag) if discover_flag &",
"temps _LOGGER.debug(\"Changed zones (from 30C9): %s\", changed_zones) if not changed_zones: return # ctl's",
"13:237335 --:------ 3EF0 001 00 # 06:49:05.467 045 RQ --- 01:145038 13:237335 --:------",
"{ **super().schema, ATTR_UFH_SYSTEM: { d.id: d.schema for d in sorted(self._ctl.devices) if d.type ==",
"msg elif msg.code not in (\"0001\", \"000C\", \"0418\", \"1100\", \"3B00\"): assert False, msg.code",
"params # TODO: removeme assert \"language\" not in params[ATTR_HTG_SYSTEM] # TODO: removeme params[ATTR_HTG_SYSTEM][\"language\"]",
"have changed temps during this cycle testable_zones = { z: t for z,",
"in (\" I\", \"RP\"): # this is a special case self._system_mode = msg",
"-> Optional[bool]: \"\"\"Return True is the system is currently calling for heat.\"\"\" if",
"DISCOVER_STATUS: self._send_cmd(\"1F09\") class Programmer(Evohome): def __repr__(self) -> str: return f\"{self._ctl.id} (programmer)\" class Sundial(Evohome):",
"self.zone_lock = Lock() self.zone_lock_idx = None # self._prev_30c9 = None # OUT: used",
"import ( ATTR_DEVICES, DEVICE_HAS_ZONE_SENSOR, DISCOVER_ALL, DISCOVER_PARAMS, DISCOVER_SCHEMA, DISCOVER_STATUS, SystemMode, SystemType, __dev_mode__, ) from",
"ATTR_HTG_SYSTEM in status # TODO: removeme status[ATTR_HTG_SYSTEM][\"heat_demands\"] = self.heat_demands status[ATTR_HTG_SYSTEM][\"relay_demands\"] = self.relay_demands status[ATTR_HTG_SYSTEM][\"relay_failsafes\"]",
"until=until) return self._gwy.send_cmd(cmd) def set_auto(self) -> Task: \"\"\"Revert system to Auto, set non-PermanentOverride",
"qos) if msg.code == \"3150\" and msg.verb in (\" I\", \"RP\"): if \"domain_id\"",
"DhwZone: if self.dhw: raise LookupError(f\"Duplicate stored HW: {zone_idx}\") dhw = self._dhw = DhwZone(self)",
"temperatures. The temperature of each zone is reliably known (30C9 array), but the",
"I/I exchange between a CTL & a 13: (TPI cycle rate, usu. 6x/hr)",
"ATTR_DHW_SYSTEM: self.dhw.status if self.dhw else {}} class MultiZone: # 0005 (+/- 000C?) def",
"== \"02\" }, } @property def params(self) -> dict: assert ATTR_UFH_SYSTEM not in",
"only a process of exclusion as a means to determine which zone uses",
"**kwargs) -> None: super().__init__(*args, **kwargs) self._datetime = None def _discover(self, discover_flag=DISCOVER_ALL) -> None:",
"-> Device: if self._htg_control: return self._htg_control htg_control = [d for d in self._ctl.devices",
"when sensors announce temp, ?also includes it's parent zone matching_sensors = [ s",
"[ d for d in self._gwy.devices # not: self.devices if d._ctl in (self,",
"I/313F # await self.wait_for(Command(\"313F\", verb=\" W\", payload=f\"00{dtm_to_hex(dtm)}\")) # return self.datetime @property def status(self)",
"047 RQ --- 07:030741 01:102458 --:------ 10A0 006 00181F0003E4 # 062 RP ---",
"changed_zones.items() if self.zone_by_idx[z].sensor is None and t not in [v for k, v",
"params # TODO: removeme # devices don't have params # assert ATTR_HTG_CONTROL not",
"controller & DHW sensor # 047 RQ --- 07:030741 01:102458 --:------ 10A0 006",
"None: self._get_zone(\"FA\") self.dhw._set_sensor(sensor) super()._handle_msg(msg) if msg.code in (\"10A0\", \"1260\"): # self.dhw.sensor is None",
"(\"1F41\",): # dhw_mode pass def _get_zone(self, zone_idx, sensor=None, **kwargs) -> DhwZone: \"\"\"Return a",
"TODO: needs tidyup (ref #67) zone._discover() # discover_flag=DISCOVER_ALL) return zone if zone_idx ==",
"in (\"0008\", \"3EF1\"): device._send_cmd(code, qos) if msg.code == \"3150\" and msg.verb in (\"",
"sensor... if self._zone is not None: return # the controller has already been",
"assert ATTR_ZONES not in super().status # TODO: removeme return {**super().status, ATTR_ZONES: {z.idx: z.status",
"\"\"\"Return a zone (will create it if required). Can also set a zone's",
"\"fault_log\" not in status # TODO: removeme status[\"fault_log\"] = self._fault_log.fault_log status[\"last_fault\"] = self._msgz[\"",
"import Command, FaultLog, Priority from .const import ( ATTR_DEVICES, DEVICE_HAS_ZONE_SENSOR, DISCOVER_ALL, DISCOVER_PARAMS, DISCOVER_SCHEMA,",
"= kwargs.pop(\"dest_addr\", self._ctl.id) payload = kwargs.pop(\"payload\", \"00\") super()._send_cmd(code, dest, payload, **kwargs) @property def",
"mode self._gwy.send_cmd(Command.get_system_mode(self.id)) def _handle_msg(self, msg, prev_msg=None): super()._handle_msg(msg) if msg.code == \"2E04\" and msg.verb",
"-> None: # _LOGGER.debug(\"Creating a System: %s (%s)\", dev_addr.id, self.__class__) super().__init__(gwy, **kwargs) self.id",
"relay (in order of reliability): 1. The 3220 RQ/RP *to/from a 10:* (1x/5min)",
"sorted( [d.id for d in self._ctl.devices if not d._domain_id and d.type != \"02\"]",
"RP --- 10:067219 01:078710 --:------ 3EF0 006 0000100000FF # noqa # 06:49:03.465 045",
"super().status assert \"fault_log\" not in status # TODO: removeme status[\"fault_log\"] = self._fault_log.fault_log status[\"last_fault\"]",
"0009 if self._relay_failsafes: return {} # failsafe_enabled @property def status(self) -> dict: \"\"\"Return",
"are evohome-compatible.\"\"\" def __init__(self, gwy, ctl, **kwargs) -> None: super().__init__(gwy, ctl, **kwargs) def",
"self.relay_failsafes return status class Evohome(SysLanguage, SysMode, MultiZone, UfhSystem, System): # evohome # class",
"(will create it if required). Can also set a zone's sensor, and zone_type,",
"status[ATTR_DEVICES] = {d.id: d.status for d in sorted(self._ctl.devices)} return status class System(StoredHw, SysDatetime,",
"-> None: # super()._discover(discover_flag=discover_flag) # will RP to: 0005/configured_zones_alt, but not: configured_zones #",
"def _discover(self, discover_flag=DISCOVER_ALL) -> None: super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_STATUS: pass def _handle_msg(self,",
"msg.dtm > prev_msg.dtm + td(seconds=secs): return # only compare against 30C9 (array) pkt",
"= self._get_msg_value(\"1F09\", \"remaining_seconds\") if secs is None or msg.dtm > prev_msg.dtm + td(seconds=secs):",
"testable zones testable_sensors = [ d for d in self._gwy.devices # not: self.devices",
"super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_STATUS: pass def _handle_msg(self, msg, prev_msg=None): \"\"\"Eavesdrop packets, or",
"None } # this will be true if ctl is sensor if not",
"params class SysMode: # 2E04 def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs)",
"for device in [d for d in kwargs[\"actuators\"] if d not in zone.devices]:",
"heater = this.dst elif this.code == \"3B00\" and this.verb == \" I\" and",
"# TODO: removeme return { **super().params, ATTR_UFH_SYSTEM: { d.id: d.params for d in",
"# elif msg.code == \"30C9\" and isinstance(msg.payload, list): # msg.is_array: # find_zone_sensors() def",
"None ) assert ATTR_ORPHANS not in schema[ATTR_HTG_SYSTEM] # TODO: removeme schema[ATTR_ORPHANS] = sorted(",
"return self._dhw._dhw_valve if self._dhw else None @property def heating_valve(self) -> Device: return self._dhw._htg_valve",
"zones: %s (unique/non-null temps & sensorless)\", testable_zones, ) _LOGGER.debug( \"Testable sensors: %s (non-null",
"zone_idx in self.zone_by_idx: raise LookupError(f\"Duplicated zone: {zone_idx} for {self}\") zone = Zone(self, zone_idx)",
"is prev.dst and this.dst is prev.src.addr def OUT_find_htg_relay(this, prev=None): \"\"\"Discover the heat relay",
"in super().schema # TODO: removeme return {**super().schema, ATTR_ZONES: {z.idx: z.schema for z in",
"# 0008|0009|1030|1100|2309|3B00 def __init__(self, gwy, ctl, **kwargs) -> None: # _LOGGER.debug(\"Creating a System:",
"self._zones}} class UfhSystem: @property def schema(self) -> dict: assert ATTR_UFH_SYSTEM not in super().schema",
"None or msg.dtm > prev_msg.dtm + td(seconds=secs): return # only compare against 30C9",
"Optional[dict]: # 0009 if self._relay_failsafes: return {} # failsafe_enabled @property def status(self) ->",
"for d in self._ctl.devices if not d._domain_id and d.type != \"02\"] ) #",
"01:145038 --:------ 01:145038 1F41 006 000002FFFFFF sensor = None if this.code == \"10A0\"",
"DHW) self._send_cmd(\"000C\", payload=dev_type) for dev_type in (\"000D\", \"000F\") # CODE_000C_DEVICE_TYPE # for dev_type,",
"in changed_zones.items() if k != z] + [None] } # ...with unique (non-null)",
"is None: return if len([z for z in self.zones if z.sensor is None])",
"zone.sensor._set_ctl(self) elif len(matching_sensors) == 0: _LOGGER.debug(\" - no matching sensor (uses CTL?)\") else:",
"super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_STATUS: self._gwy.send_cmd(Command.get_system_time(self.id)) # self._send_cmd(\"313F\") def _handle_msg(self, msg, prev_msg=None): super()._handle_msg(msg)",
"for k, v in self._relay_demands.items() } @property def relay_failsafes(self) -> Optional[dict]: # 0009",
"# TODO: removeme return {**super().params, ATTR_DHW_SYSTEM: self.dhw.params if self.dhw else {}} @property def",
"000911 # 1F41: I/01: get parent controller, but not DHW sensor # 045",
"self._send_cmd(\"000C\", payload=dev_type) for dev_type in (\"000D\", \"000F\") # CODE_000C_DEVICE_TYPE # for dev_type, description",
"return # ctl's 30C9 says no zones have changed temps during this cycle",
"zone = Zone(self, zone_idx) if not self._gwy.config[DISABLE_DISCOVERY]: # TODO: needs tidyup (ref #67)",
"@property def schema(self) -> dict: assert ATTR_UFH_SYSTEM not in super().schema # TODO: removeme",
"# TODO: FIXME qos = {\"priority\": Priority.LOW, \"retries\": 2} for code in (\"0008\",",
"# await self.wait_for(Command(\"313F\", verb=\"RQ\")) # return self.datetime # async def set_datetime(self, dtm: dt)",
"will RP to: 0005/configured_zones_alt, but not: configured_zones # will RP to: 0004 if",
"this.src is self and this.dst.type == \"07\": sensor = this.dst if sensor is",
"TODO: removeme return {**super().schema, ATTR_DHW_SYSTEM: self.dhw.schema if self.dhw else {}} @property def params(self)",
"not. In particular, the controller may be a sensor for a zone, but",
"\"0100\" and msg.verb in (\" I\", \"RP\"): self._language = msg @property def language(self)",
"None # ) assert \"tpi_params\" not in params[ATTR_HTG_SYSTEM] # TODO: removeme params[ATTR_HTG_SYSTEM][\"tpi_params\"] =",
"# TPI params # # for code in (\"3B00\",): # 3EF0, 3EF1 #",
"**kwargs) -> None: # _LOGGER.debug(\"Creating a System: %s (%s)\", dev_addr.id, self.__class__) super().__init__(gwy, **kwargs)",
"params(self) -> dict: assert ATTR_DHW_SYSTEM not in super().params # TODO: removeme return {**super().params,",
"def OUT_find_htg_relay(this, prev=None): \"\"\"Discover the heat relay (10: or 13:) for this system.",
"3B00 002 FCC8 # note the order: most to least reliable heater =",
"in super().status # TODO: removeme return {**super().status, ATTR_ZONES: {z.idx: z.status for z in",
"self._ctl.devices if d._domain_id == \"FC\"] return htg_control[0] if len(htg_control) == 1 else None",
"sensor = None if this.code == \"10A0\" and this.verb == \"RP\": if this.src",
") _LOGGER.debug( \"Testable sensors: %s (non-null temps & orphans or zoneless)\", {d.id: d.temperature",
"required). Can also set a zone's sensor, and zone_type, and actuators. \"\"\" def",
"def OUT_find_zone_sensors() -> None: \"\"\"Determine each zone's sensor by matching zone/sensor temperatures. The",
"+ their type (RAD, UFH, VAL, MIX, ELE) self._send_cmd(\"0005\", payload=f\"00{zone_type}\") for zone_type in",
"else: _LOGGER.debug(\" - multiple sensors: %s\", matching_sensors) _LOGGER.debug(\"System state (after): %s\", self) #",
"if d._ctl in (self, None) and d.addr.type in DEVICE_HAS_ZONE_SENSOR and d.temperature is not",
"Zone: \"\"\"Return a zone (will create it if required). Can also set a",
"00 # 06:49:05.467 045 RQ --- 01:145038 13:237335 --:------ 3EF0 001 00 #",
"d.temperature is not None and d._msgs[\"30C9\"].dtm > prev_msg.dtm # changed temp during last",
"key=lambda x: x.idx) @property def schema(self) -> dict: assert ATTR_ZONES not in super().schema",
"per an RFG100 self._send_cmd(\"0005\", payload=f\"00{zone_type}\") for zone_type in (\"00\", \"04\", \"0C\", \"0F\", \"10\")",
"sensor is not None: zone._set_dhw_sensor(sensor) return zone @property def dhw(self) -> DhwZone: return",
"def __init__(self, gwy, ctl, **kwargs) -> None: super().__init__(gwy, ctl, **kwargs) def __repr__(self) ->",
"+ [None] } # ...with unique (non-null) temps, and no sensor _LOGGER.debug( \"",
"# 062 RP --- 01:102458 07:030741 --:------ 10A0 006 0018380003E8 # 1260: I/07:",
"DhwZone(self) if not self._gwy.config[DISABLE_DISCOVERY]: dhw._discover() # discover_flag=DISCOVER_ALL) return dhw if zone_idx != \"HW\":",
"Device: return self._dhw._dhw_valve if self._dhw else None @property def heating_valve(self) -> Device: return",
"\"RP\"): self._language = msg @property def language(self) -> Optional[str]: # 0100 return self._msg_payload(self._language,",
"= self self._ctl = ctl self._domain_id = \"FF\" self._evo = None self._heat_demand =",
"UfhSystem, System): # evohome # class Evohome(System): # evohome \"\"\"The Evohome system -",
"TODO: when sensors announce temp, ?also includes it's parent zone matching_sensors = [",
"\"retries\": 2} for code in (\"0008\", \"3EF1\"): device._send_cmd(code, qos) if msg.code == \"3150\"",
"(\"3220\", \"3B00\", \"3EF0\"): # self.heating_control is None and # find_htg_relay(msg, prev=prev_msg) def _send_cmd(self,",
"is initiated by the DHW, so is not authorative. The I/1260 is not",
"not in prev_msg.payload } # zones with changed temps _LOGGER.debug(\"Changed zones (from 30C9):",
"sensor if not testable_zones: return # no testable zones zone_idx, temp = list(testable_zones.items())[0]",
"# find_dhw_sensor(msg) pass elif msg.code in (\"1F41\",): # dhw_mode pass def _get_zone(self, zone_idx,",
"if self.dhw else None elif msg.payload[\"domain_id\"] == \"FA\": device = self.dhw.hotwater_valve if self.dhw",
"{} def __repr__(self) -> str: return f\"{self._ctl.id} (system)\" def _handle_msg(self, msg) -> bool:",
"== temp and s._zone in (zone_idx, None) ] _LOGGER.debug( \" - matching sensor(s):",
"by matching zone/sensor temperatures. The temperature of each zone is reliably known (30C9",
"1 else None # HACK for 10: def _set_htg_control(self, device: Device) -> None:",
"Entity from .exceptions import CorruptStateError, ExpiredCallbackError from .schema import ( ATTR_CONTROLLER, ATTR_DHW_SYSTEM, ATTR_HTG_CONTROL,",
"not DHW sensor # 045 I --- 01:145038 --:------ 01:145038 1F41 012 000004FFFFFF1E060E0507E4",
"%s\", self) changed_zones = { z[\"zone_idx\"]: z[\"temperature\"] for z in msg.payload if z",
"elif this.code == \"3EF0\" and this.verb == \"RQ\": if this.src is self and",
"if self.heating_control else None ) return params @property def status(self) -> dict: \"\"\"Return",
"raise TypeError(f\"{ATTR_HTG_CONTROL} can't be: {device}\") if self._htg_control is not None: if self._htg_control is",
"\"\"\"Revert system to Auto, set non-PermanentOverride zones to FollowSchedule.\"\"\" return self.set_mode(SystemMode.AUTO) def reset_mode(self)",
"-> Optional[dict]: # 2E04 return self._msg_payload(self._system_mode) def set_mode(self, system_mode=None, until=None) -> Task: \"\"\"Set",
"-> None: super().__init__(*args, **kwargs) self._datetime = None def _discover(self, discover_flag=DISCOVER_ALL) -> None: super()._discover(discover_flag=discover_flag)",
"OUT: used to discover zone sensors def _discover(self, discover_flag=DISCOVER_ALL) -> None: super()._discover(discover_flag=discover_flag) if",
"in testable_sensors}, ) if testable_sensors: # the main matching algorithm... for zone_idx, temp",
"Device) -> None: # self._htg_control \"\"\"Set the heating control relay for this system",
"\"3B00\", \"3EF0\"): # self.heating_control is None and # find_htg_relay(msg, prev=prev_msg) def _send_cmd(self, code,",
"{} self._relay_failsafes = {} def __repr__(self) -> str: return f\"{self._ctl.id} (system)\" def _handle_msg(self,",
"0018380003E8 # 1260: I/07: can't get which parent controller - need to match",
"state.\"\"\" status = {ATTR_HTG_SYSTEM: {}} assert ATTR_HTG_SYSTEM in status # TODO: removeme #",
"{k: v.payload[\"heat_demand\"] for k, v in self._heat_demands.items()} @property def relay_demands(self) -> Optional[dict]: #",
"def _discover(self, discover_flag=DISCOVER_ALL) -> None: super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_SCHEMA: [ # 0005:",
"needs tidyup (ref #67) zone._discover() # discover_flag=DISCOVER_ALL) return zone if zone_idx == \"HW\":",
"t in changed_zones.items() if self.zone_by_idx[z].sensor is None } # this will be true",
"out @property def heating_control(self) -> Device: if self._htg_control: return self._htg_control htg_control = [d",
"d in self._ctl.devices if not d._domain_id and d.type != \"02\"] ) # devices",
"\"FA\": device = self.dhw.hotwater_valve if self.dhw else None elif msg.payload[\"domain_id\"] == \"FC\": device",
"not None: if self._htg_control is device: return raise CorruptStateError( f\"{ATTR_HTG_CONTROL} shouldn't change: {self._htg_control}",
"controller as a sensor... if self._zone is not None: return # the controller",
"== \"F9\": device = self.dhw.heating_valve if self.dhw else None elif msg.payload[\"domain_id\"] == \"FA\":",
"neighbour) sensors announcing temperatures with the same value. This leaves only a process",
"has already been allocated if len([z for z in self.zones if z.sensor is",
"self._heat_demands = {} self._relay_demands = {} self._relay_failsafes = {} def __repr__(self) -> str:",
"ATTR_HTG_CONTROL not in schema[ATTR_HTG_SYSTEM] # TODO: removeme schema[ATTR_HTG_SYSTEM][ATTR_HTG_CONTROL] = ( self.heating_control.id if self.heating_control",
"if self.dhw else {}} class MultiZone: # 0005 (+/- 000C?) def __init__(self, *args,",
"packets, to maintain the system state.\"\"\" def OUT_find_dhw_sensor(this): \"\"\"Discover the stored HW this",
"device = None if False and device is not None: # TODO: FIXME",
"\"FC\", \"FF\"): # # self._send_cmd(code, payload=payload) # # TODO: opentherm: 1FD4, 22D9, 3220",
"the system's configuration.\"\"\" params = {ATTR_HTG_SYSTEM: {}} assert ATTR_HTG_SYSTEM in params # TODO:",
"VAL, MIX, ELE) self._send_cmd(\"0005\", payload=f\"00{zone_type}\") for zone_type in (\"08\", \"09\", \"0A\", \"0B\", \"11\")",
"if testable_sensors: # the main matching algorithm... for zone_idx, temp in testable_zones.items(): #",
"_send_cmd(self, code, **kwargs) -> None: dest = kwargs.pop(\"dest_addr\", self._ctl.id) payload = kwargs.pop(\"payload\", \"00\")",
"== \"30C9\": # zone._temp = zone_dict # if msg.code in (\"000A\", \"2309\", \"30C9\"):",
"50.0 def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self._dhw = None def",
"sensor: 1. The 10A0 RQ/RP *from/to a 07:* (1x/4h) - reliable 2. Use",
"not in status[ATTR_HTG_SYSTEM] # TODO: removeme # status[ATTR_HTG_SYSTEM][ATTR_HTG_CONTROL] = ( # self.heating_control.status if",
"& not from another zone)\", [s.id for s in matching_sensors], ) if len(matching_sensors)",
"# 000C: find the HTG relay and DHW sensor, if any (DHW relays",
"ATTR_HTG_CONTROL not in status[ATTR_HTG_SYSTEM] # TODO: removeme # status[ATTR_HTG_SYSTEM][ATTR_HTG_CONTROL] = ( # self.heating_control.status",
"status[ATTR_HTG_SYSTEM][\"relay_failsafes\"] = self.relay_failsafes return status class Evohome(SysLanguage, SysMode, MultiZone, UfhSystem, System): # evohome",
"if len(htg_control) == 1 else None # HACK for 10: def _set_htg_control(self, device:",
"_LOGGER.setLevel(logging.DEBUG) class SysFaultLog: # 0418 def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs)",
"W\", payload=f\"00{dtm_to_hex(dtm)}\")) # return self.datetime @property def status(self) -> dict: status = super().status",
"ctl is sensor if not testable_zones: return # no testable zones zone_idx, temp",
"_set_htg_control(self, device: Device) -> None: # self._htg_control \"\"\"Set the heating control relay for",
"self.zone_by_idx[zone_idx] zone._set_sensor(self) zone.sensor._set_ctl(self) _LOGGER.debug(\"System state (finally): %s\", self) super()._handle_msg(msg) if msg.code in (\"000A\",)",
"# this will be true if ctl is sensor if not testable_zones: return",
"schema(self) -> dict: assert ATTR_DHW_SYSTEM not in super().schema # TODO: removeme return {**super().schema,",
"(if any). There is only 2 ways to to find a controller's DHW",
"prev_msg.dtm + td(seconds=secs): return # only compare against 30C9 (array) pkt from the",
"TODO: removeme status[\"fault_log\"] = self._fault_log.fault_log status[\"last_fault\"] = self._msgz[\" I\"].get(\"0418\") return status class SysDatetime:",
"OUT_find_dhw_sensor(this): \"\"\"Discover the stored HW this system (if any). There is only 2",
"d.type == \"02\" }, } @property def status(self) -> dict: assert ATTR_UFH_SYSTEM not",
"not in status[ATTR_HTG_SYSTEM] # TODO: removeme status[ATTR_HTG_SYSTEM][\"datetime\"] = self.datetime return status class SysLanguage:",
"{z.idx: z.status for z in self._zones}} class UfhSystem: @property def schema(self) -> dict:",
"-> dict: assert ATTR_ZONES not in super().status # TODO: removeme return {**super().status, ATTR_ZONES:",
"msg.payload: idx = msg.payload[\"domain_id\"] if msg.code == \"0008\": self._relay_demands[idx] = msg elif msg.code",
"# the main matching algorithm... for zone_idx, temp in testable_zones.items(): # TODO: when",
"not None and d._msgs[\"30C9\"].dtm > prev_msg.dtm # changed temp during last cycle ]",
"for k, v in self._heat_demands.items()} @property def relay_demands(self) -> Optional[dict]: # 0008 if",
"ATTR_DHW_SYSTEM not in super().schema # TODO: removeme return {**super().schema, ATTR_DHW_SYSTEM: self.dhw.schema if self.dhw",
"(%s)\", dev_addr.id, self.__class__) super().__init__(gwy, **kwargs) self.id = ctl.id gwy.systems.append(self) gwy.system_by_id[self.id] = self self._ctl",
"removeme schema[ATTR_ORPHANS] = sorted( [d.id for d in self._ctl.devices if not d._domain_id and",
"zone_idx) if not self._gwy.config[DISABLE_DISCOVERY]: # TODO: needs tidyup (ref #67) zone._discover() # discover_flag=DISCOVER_ALL)",
"in prev_msg.payload } # zones with changed temps _LOGGER.debug(\"Changed zones (from 30C9): %s\",",
"class SysFaultLog: # 0418 def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self._fault_log",
"for k, v in changed_zones.items() if k != z] + [None] } #",
"self.zone_by_idx: cmd = Command.get_zone_mode(self.id, zone_idx, priority=Priority.LOW) self._gwy.send_cmd(cmd) # for zone in self.zones: #",
"self._msg_payload(self._system_mode) def set_mode(self, system_mode=None, until=None) -> Task: \"\"\"Set a system mode for a",
"\"F9\", \"FA\", \"FB\", \"FC\", \"FF\"): # # self._send_cmd(code, payload=payload) # # TODO: opentherm:",
"OUT_is_exchange(this, prev): # TODO:use is? return this.src is prev.dst and this.dst is prev.src.addr",
"& a 13: (TPI cycle rate, usu. 6x/hr) Data from the CTL is",
"None if this.code == \"3220\" and this.verb == \"RQ\": if this.src is self",
"super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_PARAMS: self._send_cmd(\"0100\") # language def _handle_msg(self, msg, prev_msg=None): super()._handle_msg(msg)",
"for zone_idx, temp in testable_zones.items(): # TODO: when sensors announce temp, ?also includes",
"if not testable_zones: return # no testable zones zone_idx, temp = list(testable_zones.items())[0] _LOGGER.debug(\"Testing",
"self._system_mode = None def _discover(self, discover_flag=DISCOVER_ALL) -> None: super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_STATUS:",
"reliable 2. Use sensor temp matching - non-deterministic Data from the CTL is",
"-> None: super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_PARAMS: self._send_cmd(\"0100\") # language def _handle_msg(self, msg,",
"07:045960 --:------ 07:045960 1260 003 000911 # 1F41: I/01: get parent controller, but",
"{ z[\"zone_idx\"]: z[\"temperature\"] for z in msg.payload if z not in prev_msg.payload }",
"return json.dumps({self._ctl.id: self.schema}) def _discover(self, discover_flag=DISCOVER_ALL) -> None: # super()._discover(discover_flag=discover_flag) if discover_flag &",
"self._api_lock.release() # raise ExpiredCallbackError(\"failed to set schedule\") # self._api_lock.release() # async def get_datetime(self)",
"super()._handle_msg(msg) # [xxx(z) for z in msg.payload] # else: # xxx(msg.payload) if msg.code",
"None: dest = kwargs.pop(\"dest_addr\", self._ctl.id) payload = kwargs.pop(\"payload\", \"00\") super()._send_cmd(code, dest, payload, **kwargs)",
"self._relay_demands[msg.payload[\"domain_id\"]] = msg if msg.payload[\"domain_id\"] == \"F9\": device = self.dhw.heating_valve if self.dhw else",
"elif msg.code not in (\"0001\", \"000C\", \"0418\", \"1100\", \"3B00\"): assert False, msg.code @property",
"self.dhw: raise LookupError(f\"Duplicate stored HW: {zone_idx}\") dhw = self._dhw = DhwZone(self) if not",
"None and d._msgs[\"30C9\"].dtm > prev_msg.dtm # changed temp during last cycle ] if",
"z not in prev_msg.payload } # zones with changed temps _LOGGER.debug(\"Changed zones (from",
"# TODO: removeme return {**super().status, ATTR_DHW_SYSTEM: self.dhw.status if self.dhw else {}} class MultiZone:",
"is only 2 ways to to find a controller's DHW sensor: 1. The",
"get_fault_log(self, force_refresh=None) -> Optional[dict]: # 0418 try: return await self._fault_log.get_fault_log(force_refresh=force_refresh) except ExpiredCallbackError: return",
"z in self._zones}} class UfhSystem: @property def schema(self) -> dict: assert ATTR_UFH_SYSTEM not",
"only compare against 30C9 (array) pkt from the last cycle _LOGGER.debug(\"System state (before):",
"in (\"0000\", \"00\", \"F8\", \"F9\", \"FA\", \"FB\", \"FC\", \"FF\"): # # self._send_cmd(code, payload=payload)",
"StoredHw: MIN_SETPOINT = 30.0 # NOTE: these may be removed MAX_SETPOINT = 85.0",
"] _LOGGER.debug(\"Testing zone %s, temp: %s\", zone_idx, temp) _LOGGER.debug( \" - matching sensor(s):",
"d.id: d.schema for d in sorted(self._ctl.devices) if d.type == \"02\" }, } @property",
"is None and # find_htg_relay(msg, prev=prev_msg) def _send_cmd(self, code, **kwargs) -> None: dest",
"01:145038 --:------ 01:145038 3B00 002 FCC8 # note the order: most to least",
"== 1 else None # HACK for 10: def _set_htg_control(self, device: Device) ->",
"else None @property def hotwater_valve(self) -> Device: return self._dhw._dhw_valve if self._dhw else None",
"Device, Entity from .exceptions import CorruptStateError, ExpiredCallbackError from .schema import ( ATTR_CONTROLLER, ATTR_DHW_SYSTEM,",
"an RFG100 self._send_cmd(\"0005\", payload=f\"00{zone_type}\") for zone_type in (\"00\", \"04\", \"0C\", \"0F\", \"10\") ]",
"None: zone._set_dhw_sensor(sensor) return zone @property def dhw(self) -> DhwZone: return self._dhw def _set_dhw(self,",
"= this.dst elif this.code == \"3EF0\" and this.verb == \"RQ\": if this.src is",
"this.code == \"3B00\" and this.verb == \" I\" and prev is not None:",
"Priority.LOW, \"retries\": 2} for code in (\"0008\", \"3EF1\"): device._send_cmd(code, qos) if msg.code ==",
"or 13:).\"\"\" if not isinstance(device, Device) or device.type not in (\"10\", \"13\"): raise",
"# self._api_lock.release() # raise ExpiredCallbackError(\"failed to set schedule\") # self._api_lock.release() # async def",
"SysFaultLog \"\"\"The Controller class.\"\"\" def __init__(self, gwy, ctl, **kwargs) -> None: super().__init__(gwy, ctl,",
"assert ATTR_DHW_SYSTEM not in super().schema # TODO: removeme return {**super().schema, ATTR_DHW_SYSTEM: self.dhw.schema if",
"006 000002FFFFFF sensor = None if this.code == \"10A0\" and this.verb == \"RP\":",
"zone is not. In particular, the controller may be a sensor for a",
"None: # zone_added = bool(prev_msg.code == \"0004\") # else zone_deleted # elif msg.code",
"\"10\") ] if discover_flag & DISCOVER_STATUS: self._send_cmd(\"0006\") def _handle_msg(self, msg, prev_msg=None): def OUT_find_zone_sensors()",
"0000050000 # 18:14:14.446 065 RP --- 10:067219 01:078710 --:------ 3220 005 00C00500FF #",
"\"13\"): raise TypeError(f\"{ATTR_HTG_CONTROL} can't be: {device}\") if self._htg_control is not None: if self._htg_control",
"None: super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_STATUS: self._gwy._tasks.append(self._loop.create_task(self.get_fault_log())) async def get_fault_log(self, force_refresh=None) -> Optional[dict]:",
"{dhw}\") if self._dhw is not None: if self._dhw is dhw: return raise CorruptStateError(\"DHW",
"params = {ATTR_HTG_SYSTEM: {}} assert ATTR_HTG_SYSTEM in params # TODO: removeme # devices",
"msg.code == \"000A\": # zone._zone_config = zone_dict # elif msg.code == \"2309\": #",
"I\"].get(\"0418\") return status class SysDatetime: # 313F def __init__(self, *args, **kwargs) -> None:",
"if prev.code == this.code and prev.verb == this.verb: if this.src is self and",
"\"\"\"Return the system's current state.\"\"\" status = {ATTR_HTG_SYSTEM: {}} assert ATTR_HTG_SYSTEM in status",
"# CODE_000C_DEVICE_TYPE # for dev_type, description in CODE_000C_DEVICE_TYPE.items() fix payload # if description",
"htg_control = [d for d in self._ctl.devices if d._domain_id == \"FC\"] return htg_control[0]",
"return {**super().status, ATTR_ZONES: {z.idx: z.status for z in self._zones}} class UfhSystem: @property def",
"# zones with changed temps _LOGGER.debug(\"Changed zones (from 30C9): %s\", changed_zones) if not",
"# if device.evo is not None and device.evo is not self: # raise",
"status[ATTR_HTG_SYSTEM][ATTR_HTG_CONTROL] = ( # self.heating_control.status if self.heating_control else None # ) status[ATTR_HTG_SYSTEM][\"heat_demand\"] =",
"class SysMode: # 2E04 def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self._system_mode",
"== \"3EF0\" and this.verb == \"RQ\": if this.src is self and this.dst.type in",
"\"\"\"Evohome RF - The evohome-compatible system.\"\"\" import logging from asyncio import Task from",
"zone_idx, temp) _LOGGER.debug( \" - matching sensor(s): %s (same temp & not from",
"a DHW zone's sensor & valves?. \"\"\" def create_dhw(zone_idx) -> DhwZone: if self.dhw:",
"if _LOGGER.isEnabledFor(logging.DEBUG): _LOGGER.debug( \"Testable zones: %s (unique/non-null temps & sensorless)\", testable_zones, ) _LOGGER.debug(",
"# want to avoid complexity of z._temp # zone = self.zone_by_idx[zone_idx] # if",
"\"30C9\" and isinstance(msg.payload, list): # msg.is_array: # find_zone_sensors() def _get_zone(self, zone_idx, sensor=None, **kwargs)",
"self._gwy._get_device(xxx) # self.add_device(dhw.sensor) # self.add_device(dhw.relay) self._dhw = dhw @property def dhw_sensor(self) -> Device:",
"_LOGGER.debug(\"System state (before): %s\", self) changed_zones = { z[\"zone_idx\"]: z[\"temperature\"] for z in",
"temps & orphans or zoneless)\", {d.id: d.temperature for d in testable_sensors}, ) if",
"super()._handle_msg(msg) if msg.code in (\"10A0\", \"1260\"): # self.dhw.sensor is None and # if",
"zone is None: zone = create_dhw(zone_idx) if kwargs.get(\"dhw_valve\"): zone._set_dhw_valve(kwargs[\"dhw_valve\"]) if kwargs.get(\"htg_valve\"): zone._set_dhw_valve(kwargs[\"htg_valve\"]) if",
"zones + their type (RAD, UFH, VAL, MIX, ELE) self._send_cmd(\"0005\", payload=f\"00{zone_type}\") for zone_type",
"\"0F\", \"10\") ] if discover_flag & DISCOVER_STATUS: self._send_cmd(\"0006\") def _handle_msg(self, msg, prev_msg=None): def",
"if self._gwy.serial_port: # only if in monitor mode... secs = self._get_msg_value(\"1F09\", \"remaining_seconds\") if",
"!= \"HW\": return zone = self.dhw # TODO: self.zone_by_idx.get(\"HW\") too? if zone is",
"zone._temp is None: # return # TODO: should have a (not-None) temperature matching_sensors",
"\"3B00\"): assert False, msg.code @property def heat_demands(self) -> Optional[dict]: # 3150 if self._heat_demands:",
"\"000F\") # CODE_000C_DEVICE_TYPE # for dev_type, description in CODE_000C_DEVICE_TYPE.items() fix payload # if",
"in (\"000A\", \"2309\", \"30C9\"): # if isinstance(msg.payload, list): # super()._handle_msg(msg) # [xxx(z) for",
"self.wait_for(Command(\"313F\", verb=\"RQ\")) # return self.datetime # async def set_datetime(self, dtm: dt) -> str:",
"self._dhw is not None: if self._dhw is dhw: return raise CorruptStateError(\"DHW shouldn't change:",
"--:------ 01:145038 1F41 012 000004FFFFFF1E060E0507E4 # 045 I --- 01:145038 --:------ 01:145038 1F41",
"make a dt object # def wait_for(self, cmd, callback): # self._api_lock.acquire() # self._send_cmd(\"313F\",",
"None: # return # TODO: should have a (not-None) temperature matching_sensors = [",
"DISCOVER_PARAMS: self._send_cmd(\"1100\", payload=\"FC\") # TPI params # # for code in (\"3B00\",): #",
"return self.datetime # async def set_datetime(self, dtm: dt) -> str: # wait for",
"DEV_MODE = __dev_mode__ _LOGGER = logging.getLogger(__name__) if DEV_MODE: _LOGGER.setLevel(logging.DEBUG) class SysFaultLog: # 0418",
"TODO: removeme params[ATTR_HTG_SYSTEM][\"system_mode\"] = self.system_mode return params class StoredHw: MIN_SETPOINT = 30.0 #",
"removeme params[ATTR_HTG_SYSTEM][\"tpi_params\"] = ( self.heating_control._get_msg_value(\"1100\") if self.heating_control else None ) return params @property",
"= msg elif msg.code not in (\"0001\", \"000C\", \"0418\", \"1100\", \"3B00\"): assert False,",
"*from/to a 07:* (1x/4h) - reliable 2. Use sensor temp matching - non-deterministic",
"msg.code in (\"000A\", \"2309\", \"30C9\") and not isinstance(msg.payload, list): pass else: super()._handle_msg(msg) if",
"len(matching_sensors) == 1: _LOGGER.debug(\" - matched sensor: %s\", matching_sensors[0].id) zone = self.zone_by_idx[zone_idx] zone._set_sensor(matching_sensors[0])",
"(uses CTL?)\") else: _LOGGER.debug(\" - multiple sensors: %s\", matching_sensors) _LOGGER.debug(\"System state (after): %s\",",
"isinstance(msg.payload, list): pass else: super()._handle_msg(msg) if msg.code == \"0008\" and msg.verb in (\"",
"000002FFFFFF sensor = None if this.code == \"10A0\" and this.verb == \"RP\": if",
"if self.dhw else None elif msg.payload[\"domain_id\"] == \"FC\": device = self.heating_control else: device",
"class Chronotherm(Evohome): def __repr__(self) -> str: return f\"{self._ctl.id} (chronotherm)\" class Hometronics(System): RQ_SUPPORTED =",
"None) ] _LOGGER.debug( \" - matching sensor(s): %s (excl. controller)\", [s.id for s",
"None # ) status[ATTR_HTG_SYSTEM][\"heat_demand\"] = self.heat_demand status[ATTR_DEVICES] = {d.id: d.status for d in",
"%s\", self) # now see if we can allocate the controller as a",
"def status(self) -> dict: status = super().status assert \"fault_log\" not in status #",
"TODO: should have a (not-None) temperature matching_sensors = [ s for s in",
"discover_flag & DISCOVER_STATUS: # for domain_id in range(0xF8, 0x100): # self._send_cmd(\"0008\", payload=f\"{domain_id:02X}00\") pass",
"(e.g. ST9420C).\"\"\" # 0008|0009|1030|1100|2309|3B00 def __init__(self, gwy, ctl, **kwargs) -> None: # _LOGGER.debug(\"Creating",
"payload # if description is not None ] if discover_flag & DISCOVER_PARAMS: self._send_cmd(\"1100\",",
"Evohome(System): # evohome \"\"\"The Evohome system - some controllers are evohome-compatible.\"\"\" def __init__(self,",
"evohome \"\"\"The Evohome system - some controllers are evohome-compatible.\"\"\" def __init__(self, gwy, ctl,",
"list): # super()._handle_msg(msg) # [xxx(z) for z in msg.payload] # else: # xxx(msg.payload)",
"self._send_cmd(\"1F09\") class Programmer(Evohome): def __repr__(self) -> str: return f\"{self._ctl.id} (programmer)\" class Sundial(Evohome): def",
"stored HW: {zone_idx}\") dhw = self._dhw = DhwZone(self) if not self._gwy.config[DISABLE_DISCOVERY]: dhw._discover() #",
"\"07\": sensor = this.dst if sensor is not None: if self.dhw is None:",
"None) and d.addr.type in DEVICE_HAS_ZONE_SENSOR and d.temperature is not None and d._msgs[\"30C9\"].dtm >",
"prev_msg=None): def OUT_find_zone_sensors() -> None: \"\"\"Determine each zone's sensor by matching zone/sensor temperatures.",
"zone = create_zone(zone_idx) if kwargs.get(\"zone_type\"): zone._set_zone_type(kwargs[\"zone_type\"]) if kwargs.get(\"actuators\"): # TODO: check not an",
"_LOGGER.debug(\" - no matching sensor (uses CTL?)\") else: _LOGGER.debug(\" - multiple sensors: %s\",",
"device._set_parent(self, domain=\"FC\") @property def tpi_params(self) -> Optional[float]: # 1100 return self._get_msg_value(\"1100\") @property def",
"pass def _handle_msg(self, msg) -> bool: def OUT_is_exchange(this, prev): # TODO:use is? return",
"generic controller (e.g. ST9420C).\"\"\" # 0008|0009|1030|1100|2309|3B00 def __init__(self, gwy, ctl, **kwargs) -> None:",
"self.dhw else {}} @property def status(self) -> dict: assert ATTR_DHW_SYSTEM not in super().status",
"= device if sensor is not None: zone._set_sensor(sensor) return zone @property def _zones(self)",
"self.heating_control.params if self.heating_control else None # ) assert \"tpi_params\" not in params[ATTR_HTG_SYSTEM] #",
"and t not in [v for k, v in changed_zones.items() if k !=",
"not self._htg_control: return if self._htg_control.actuator_state: return True @property def schema(self) -> dict: \"\"\"Return",
"== \"0009\": self._relay_failsafes[idx] = msg elif msg.code == \"3150\": self._heat_demands[idx] = msg elif",
"dict: \"\"\"Return the system's configuration.\"\"\" params = {ATTR_HTG_SYSTEM: {}} assert ATTR_HTG_SYSTEM in params",
"if heater is not None: self._set_htg_control(heater) if msg.code in (\"000A\", \"2309\", \"30C9\") and",
"raise ExpiredCallbackError(\"failed to set schedule\") # self._api_lock.release() # async def get_datetime(self) -> str:",
"3220 # if discover_flag & DISCOVER_PARAMS: # for domain_id in range(0xF8, 0x100): #",
"pairs of packets, to maintain the system state.\"\"\" def OUT_find_dhw_sensor(this): \"\"\"Discover the stored",
"@property def schema(self) -> dict: \"\"\"Return the system's schema.\"\"\" schema = {ATTR_CONTROLLER: self._ctl.id,",
"f\"{self._ctl.id} (chronotherm)\" class Hometronics(System): RQ_SUPPORTED = (\"0004\", \"000C\", \"2E04\", \"313F\") # TODO: WIP",
"if kwargs.get(\"dhw_valve\"): zone._set_dhw_valve(kwargs[\"dhw_valve\"]) if kwargs.get(\"htg_valve\"): zone._set_dhw_valve(kwargs[\"htg_valve\"]) if sensor is not None: zone._set_dhw_sensor(sensor) return",
"= 30.0 # NOTE: these may be removed MAX_SETPOINT = 85.0 DEFAULT_SETPOINT =",
"self._msgz[\" I\"].get(\"0418\") return status class SysDatetime: # 313F def __init__(self, *args, **kwargs) ->",
"class Programmer(Evohome): def __repr__(self) -> str: return f\"{self._ctl.id} (programmer)\" class Sundial(Evohome): def __repr__(self)",
"in (\" I\", \"RP\"): # TODO: W self._datetime = msg @property def datetime(self)",
"datetime import timedelta as td from threading import Lock from typing import List,",
"TODO: removeme assert \"datetime\" not in status[ATTR_HTG_SYSTEM] # TODO: removeme status[ATTR_HTG_SYSTEM][\"datetime\"] = self.datetime",
"if prev_msg is None: return if len([z for z in self.zones if z.sensor",
"not in [v for k, v in changed_zones.items() if k != z] +",
"(from 30C9): %s\", changed_zones) if not changed_zones: return # ctl's 30C9 says no",
"None: # TODO: FIXME qos = {\"priority\": Priority.LOW, \"retries\": 2} for code in",
"without a sensor testable_zones = { z: t for z, t in changed_zones.items()",
"return f\"{self._ctl.id} (programmer)\" class Sundial(Evohome): def __repr__(self) -> str: return f\"{self._ctl.id} (sundial)\" SYSTEM_CLASSES",
"RQ/RP *to/from a 10:* (1x/5min) 2a. The 3EF0 RQ/RP *to/from a 10:* (1x/1min)",
"**kwargs) -> None: super().__init__(*args, **kwargs) self._system_mode = None def _discover(self, discover_flag=DISCOVER_ALL) -> None:",
"sort out @property def heating_control(self) -> Device: if self._htg_control: return self._htg_control htg_control =",
"@property def params(self) -> dict: assert ATTR_ZONES not in super().params # TODO: removeme",
"return f\"{self._ctl.id} (evohome)\" def _discover(self, discover_flag=DISCOVER_ALL) -> None: super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_STATUS:",
"schedule\") # self._api_lock.release() # async def get_datetime(self) -> str: # wait for the",
"d.status for d in sorted(self._ctl.devices) if d.type == \"02\" }, } class SystemBase(Entity):",
"# self.add_device(dhw.sensor) # self.add_device(dhw.relay) self._dhw = dhw @property def dhw_sensor(self) -> Device: return",
"def _discover(self, discover_flag=DISCOVER_ALL) -> None: super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_STATUS: self._gwy._tasks.append(self._loop.create_task(self.get_fault_log())) async def",
"DhwZone: \"\"\"Return a DHW zone (will create it if required). Can also set",
"# self.heating_control is None and # find_htg_relay(msg, prev=prev_msg) def _send_cmd(self, code, **kwargs) ->",
"self.dhw.sensor is None: # find_dhw_sensor(msg) pass elif msg.code in (\"1F41\",): # dhw_mode pass",
"in (\"0001\", \"000C\", \"0418\", \"1100\", \"3B00\"): assert False, msg.code @property def heat_demands(self) ->",
"and prev.verb == this.verb: if this.src is self and prev.src.type == \"13\": heater",
"dict: \"\"\"Return the system's current state.\"\"\" status = super().status assert ATTR_HTG_SYSTEM in status",
"removeme assert \"system_mode\" not in params[ATTR_HTG_SYSTEM] # TODO: removeme params[ATTR_HTG_SYSTEM][\"system_mode\"] = self.system_mode return",
"SysLanguage: # 0100 def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self._language =",
"3EF0 RQ/RP *to/from a 10:* (1x/1min) 2b. The 3EF0 RQ (no RP) *to",
"d in self._ctl.devices if d._domain_id == \"FC\"] return htg_control[0] if len(htg_control) == 1",
"str: return f\"{self._ctl.id} (sundial)\" SYSTEM_CLASSES = { SystemType.CHRONOTHERM: Chronotherm, SystemType.EVOHOME: Evohome, SystemType.HOMETRONICS: Hometronics,",
"too? if zone is None: zone = create_dhw(zone_idx) if kwargs.get(\"dhw_valve\"): zone._set_dhw_valve(kwargs[\"dhw_valve\"]) if kwargs.get(\"htg_valve\"):",
"_handle_msg(self, msg, prev_msg=None): super()._handle_msg(msg) if msg.code == \"313F\" and msg.verb in (\" I\",",
"return # (currently) no zone without a sensor # if self._gwy.serial_port: # only",
"def _set_htg_control(self, device: Device) -> None: # self._htg_control \"\"\"Set the heating control relay",
"return this.src is prev.dst and this.dst is prev.src.addr def OUT_find_htg_relay(this, prev=None): \"\"\"Discover the",
"[d for d in kwargs[\"actuators\"] if d not in zone.devices]: zone.devices.append(device) zone.device_by_id[device.id] =",
"_set_dhw(self, dhw: DhwZone) -> None: # self._dhw \"\"\"Set the DHW zone system.\"\"\" if",
"z.schema for z in self._zones}} @property def params(self) -> dict: assert ATTR_ZONES not",
"self._set_htg_control(heater) if msg.code in (\"000A\", \"2309\", \"30C9\") and not isinstance(msg.payload, list): pass else:",
"{}} @property def params(self) -> dict: assert ATTR_DHW_SYSTEM not in super().params # TODO:",
"str: return f\"{self._ctl.id} (hometronics)\" def _discover(self, discover_flag=DISCOVER_ALL) -> None: # super()._discover(discover_flag=discover_flag) # will",
"else {}} @property def params(self) -> dict: assert ATTR_DHW_SYSTEM not in super().params #",
"this.verb == \"RP\": if this.src is self and this.dst.type == \"07\": sensor =",
"= {ATTR_CONTROLLER: self._ctl.id, ATTR_HTG_SYSTEM: {}} assert ATTR_HTG_SYSTEM in schema # TODO: removeme assert",
"import timedelta as td from threading import Lock from typing import List, Optional",
"RQ --- 07:030741 01:102458 --:------ 10A0 006 00181F0003E4 # 062 RP --- 01:102458",
"system (if any). There is only 2 ways to to find a controller's",
"DhwZone): raise TypeError(f\"stored_hw can't be: {dhw}\") if self._dhw is not None: if self._dhw",
"= self.system_mode return params class StoredHw: MIN_SETPOINT = 30.0 # NOTE: these may",
"sensor, if any (DHW relays in DHW) self._send_cmd(\"000C\", payload=dev_type) for dev_type in (\"000D\",",
"async def set_datetime(self, dtm: dt) -> str: # wait for the I/313F #",
"TIMER_LONG_TIMEOUT: # self._api_lock.release() # raise ExpiredCallbackError(\"failed to set schedule\") # self._api_lock.release() # async",
"sensor = this.dst if sensor is not None: if self.dhw is None: self._get_zone(\"FA\")",
"dhw @property def dhw_sensor(self) -> Device: return self._dhw._dhw_sensor if self._dhw else None @property",
"self._ctl.id) zone = self.zone_by_idx[zone_idx] zone._set_sensor(self) zone.sensor._set_ctl(self) _LOGGER.debug(\"System state (finally): %s\", self) super()._handle_msg(msg) if",
"a controller's DHW sensor: 1. The 10A0 RQ/RP *from/to a 07:* (1x/4h) -",
"the controller as a sensor. \"\"\" prev_msg, self._prev_30c9 = self._prev_30c9, msg if prev_msg",
"self._send_cmd(code, payload=payload) # # TODO: opentherm: 1FD4, 22D9, 3220 # if discover_flag &",
"# raise ExpiredCallbackError(\"failed to set schedule\") # self._api_lock.release() # async def get_datetime(self) ->",
"def relay_failsafes(self) -> Optional[dict]: # 0009 if self._relay_failsafes: return {} # failsafe_enabled @property",
") from .zones import DhwZone, Zone DEV_MODE = __dev_mode__ _LOGGER = logging.getLogger(__name__) if",
"in sorted(self._ctl.devices) if d.type == \"02\" }, } @property def params(self) -> dict:",
"RP) *to a 13:* (3x/60min) 3. The 3B00 I/I exchange between a CTL",
"self._heat_demand[\"heat_demand\"] @property def is_calling_for_heat(self) -> Optional[bool]: \"\"\"Return True is the system is currently",
"import Lock from typing import List, Optional from .command import Command, FaultLog, Priority",
"01:145038 3B00 002 FCC8 # note the order: most to least reliable heater",
"Use sensor temp matching - non-deterministic Data from the CTL is considered more",
"msg @property def language(self) -> Optional[str]: # 0100 return self._msg_payload(self._language, \"language\") @property def",
"this.dst.type in (\"10\", \"13\"): heater = this.dst elif this.code == \"3B00\" and this.verb",
"-> None: super().__init__(*args, **kwargs) self.zones = [] self.zone_by_idx = {} # self.zone_by_name =",
"ValueError(f\"Invalid zone idx: {zone_idx} (exceeds max_zones)\") if zone_idx in self.zone_by_idx: raise LookupError(f\"Duplicated zone:",
"status(self) -> dict: status = super().status assert \"fault_log\" not in status # TODO:",
"# def wait_for(self, cmd, callback): # self._api_lock.acquire() # self._send_cmd(\"313F\", verb=\"RQ\", callback=callback) # time_start",
"msg.code == \"3150\" and msg.verb in (\" I\", \"RP\"): if \"domain_id\" in msg.payload",
"for s in matching_sensors], ) # can safely(?) assume this zone is using",
"is prev.src.addr def OUT_find_htg_relay(this, prev=None): \"\"\"Discover the heat relay (10: or 13:) for",
"reset_mode(self) -> Task: \"\"\"Revert system to Auto, force *all* zones to FollowSchedule.\"\"\" return",
"if msg.code == \"2E04\" and msg.verb in (\" I\", \"RP\"): # this is",
"in testable_sensors if s.temperature == temp and s._zone in (zone_idx, None) ] _LOGGER.debug(\"Testing",
"if this.code == \"3220\" and this.verb == \"RQ\": if this.src is self and",
"super()._handle_msg(msg) if msg.code == \"313F\" and msg.verb in (\" I\", \"RP\"): # TODO:",
"> time_start + TIMER_LONG_TIMEOUT: # self._api_lock.release() # raise ExpiredCallbackError(\"failed to set schedule\") #",
"07:030741 --:------ 10A0 006 0018380003E8 # 1260: I/07: can't get which parent controller",
"if msg.code in (\"3220\", \"3B00\", \"3EF0\"): # self.heating_control is None and # find_htg_relay(msg,",
"and # find_htg_relay(msg, prev=prev_msg) def _send_cmd(self, code, **kwargs) -> None: dest = kwargs.pop(\"dest_addr\",",
"self._heat_demands[idx] = msg elif msg.code not in (\"0001\", \"000C\", \"0418\", \"1100\", \"3B00\"): assert",
") status[ATTR_HTG_SYSTEM][\"heat_demand\"] = self.heat_demand status[ATTR_DEVICES] = {d.id: d.status for d in sorted(self._ctl.devices)} return",
"create_dhw(zone_idx) if kwargs.get(\"dhw_valve\"): zone._set_dhw_valve(kwargs[\"dhw_valve\"]) if kwargs.get(\"htg_valve\"): zone._set_dhw_valve(kwargs[\"htg_valve\"]) if sensor is not None: zone._set_dhw_sensor(sensor)",
"device = self.dhw.heating_valve if self.dhw else None elif msg.payload[\"domain_id\"] == \"FA\": device =",
"-> None: super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_STATUS: self._gwy._tasks.append(self._loop.create_task(self.get_fault_log())) async def get_fault_log(self, force_refresh=None) ->",
"if self._htg_control is not None: if self._htg_control is device: return raise CorruptStateError( f\"{ATTR_HTG_CONTROL}",
"\"Testable zones: %s (unique/non-null temps & sensorless)\", testable_zones, ) _LOGGER.debug( \"Testable sensors: %s",
"special case self._system_mode = msg @property def system_mode(self) -> Optional[dict]: # 2E04 return",
"d in sorted(self._ctl.devices) if d.type == \"02\" }, } class SystemBase(Entity): # 3B00",
"--- 07:030741 01:102458 --:------ 10A0 006 00181F0003E4 # 062 RP --- 01:102458 07:030741",
"--- 01:145038 13:237335 --:------ 3EF0 001 00 # 06:49:05.467 045 RQ --- 01:145038",
"# evohome \"\"\"The Evohome system - some controllers are evohome-compatible.\"\"\" def __init__(self, gwy,",
"SystemType, __dev_mode__, ) from .devices import Device, Entity from .exceptions import CorruptStateError, ExpiredCallbackError",
"don't have params # assert ATTR_HTG_CONTROL not in params[ATTR_HTG_SYSTEM] # TODO: removeme #",
"2 ways to to find a controller's DHW sensor: 1. The 10A0 RQ/RP",
"(\"000D\", \"000F\") # CODE_000C_DEVICE_TYPE # for dev_type, description in CODE_000C_DEVICE_TYPE.items() fix payload #",
"-> str: # wait for the RP/313F # await self.wait_for(Command(\"313F\", verb=\"RQ\")) # return",
"= super().status assert ATTR_HTG_SYSTEM in status # TODO: removeme status[ATTR_HTG_SYSTEM][\"heat_demands\"] = self.heat_demands status[ATTR_HTG_SYSTEM][\"relay_demands\"]",
") # can safely(?) assume this zone is using the CTL as a",
"self.zone_by_idx[zone_idx] # if zone._temp is None: # return # TODO: should have a",
"uses the controller as a sensor. \"\"\" prev_msg, self._prev_30c9 = self._prev_30c9, msg if",
"d not in zone.devices]: zone.devices.append(device) zone.device_by_id[device.id] = device if sensor is not None:",
"& DISCOVER_STATUS: # for domain_id in range(0xF8, 0x100): # self._send_cmd(\"0008\", payload=f\"{domain_id:02X}00\") pass def",
"params(self) -> dict: assert ATTR_ZONES not in super().params # TODO: removeme return {**super().params,",
"!= \"02\"] ) # devices without a parent zone, NB: CTL can be",
"# TODO: removeme params[ATTR_HTG_SYSTEM][\"language\"] = self.language return params class SysMode: # 2E04 def",
"with the same value. This leaves only a process of exclusion as a",
"ATTR_DHW_SYSTEM: self.dhw.params if self.dhw else {}} @property def status(self) -> dict: assert ATTR_DHW_SYSTEM",
"zone_dict # if msg.code in (\"000A\", \"2309\", \"30C9\"): # if isinstance(msg.payload, list): #",
"not None: return # the controller has already been allocated if len([z for",
"# only compare against 30C9 (array) pkt from the last cycle _LOGGER.debug(\"System state",
"self.zone_by_idx.get(\"HW\") too? if zone is None: zone = create_dhw(zone_idx) if kwargs.get(\"dhw_valve\"): zone._set_dhw_valve(kwargs[\"dhw_valve\"]) if",
"001 00 # 06:49:05.467 045 RQ --- 01:145038 13:237335 --:------ 3EF0 001 00",
"msg.payload[\"domain_id\"] if msg.code == \"0008\": self._relay_demands[idx] = msg elif msg.code == \"0009\": self._relay_failsafes[idx]",
"--:------ 3EF0 001 00 # 06:49:07.468 045 RQ --- 01:145038 13:237335 --:------ 3EF0",
"== \"02\" }, } @property def status(self) -> dict: assert ATTR_UFH_SYSTEM not in",
"-> Optional[float]: # 1100 return self._get_msg_value(\"1100\") @property def heat_demand(self) -> Optional[float]: # 3150/FC",
"zone._set_sensor(self) zone.sensor._set_ctl(self) _LOGGER.debug(\"System state (finally): %s\", self) super()._handle_msg(msg) if msg.code in (\"000A\",) and",
"_LOGGER.debug( \" - matching sensor(s): %s (excl. controller)\", [s.id for s in matching_sensors],",
"RQ --- 01:145038 13:237335 --:------ 3EF0 001 00 # 09:03:59.693 051 I ---",
"The 3B00 I/I exchange between a CTL & a 13: (TPI cycle rate,",
"discover_flag & DISCOVER_PARAMS: self._send_cmd(\"1100\", payload=\"FC\") # TPI params # # for code in",
"\"language\" not in params[ATTR_HTG_SYSTEM] # TODO: removeme params[ATTR_HTG_SYSTEM][\"language\"] = self.language return params class",
"zone: {zone_idx} for {self}\") zone = Zone(self, zone_idx) if not self._gwy.config[DISABLE_DISCOVERY]: # TODO:",
"not in super().params # TODO: removeme return {**super().params, ATTR_ZONES: {z.idx: z.params for z",
"most to least reliable heater = None if this.code == \"3220\" and this.verb",
"each zone is reliably known (30C9 array), but the sensor for each zone",
"if z.sensor is None]) != 1: return # no single zone without a",
"in self._heat_demands.items()} @property def relay_demands(self) -> Optional[dict]: # 0008 if self._relay_demands: return {",
"sensor: %s\", matching_sensors[0].id) zone = self.zone_by_idx[zone_idx] zone._set_sensor(matching_sensors[0]) zone.sensor._set_ctl(self) elif len(matching_sensors) == 0: _LOGGER.debug(\"",
"device = self.heating_control else: device = None if False and device is not",
"if self._zone is not None: return # the controller has already been allocated",
"self.heating_control.id if self.heating_control else None ) assert ATTR_ORPHANS not in schema[ATTR_HTG_SYSTEM] # TODO:",
"status(self) -> dict: assert ATTR_UFH_SYSTEM not in super().status # TODO: removeme return {",
"-> Optional[dict]: # 0009 if self._relay_failsafes: return {} # failsafe_enabled @property def status(self)",
"includes it's parent zone matching_sensors = [ s for s in testable_sensors if",
"a sensor for a zone, but unfortunately it does not announce its sensor",
"self.dhw else {}} @property def params(self) -> dict: assert ATTR_DHW_SYSTEM not in super().params",
"if d.type == \"02\" }, } @property def params(self) -> dict: assert ATTR_UFH_SYSTEM",
"= None self._htg_control = None def __repr__(self) -> str: return f\"{self._ctl.id} (sys_base)\" #",
"10:067219 01:078710 --:------ 3EF0 006 0000100000FF # noqa # 06:49:03.465 045 RQ ---",
"\"13\"): heater = this.dst elif this.code == \"3B00\" and this.verb == \" I\"",
"main matching algorithm... for zone_idx, temp in testable_zones.items(): # TODO: when sensors announce",
"without a parent zone, NB: CTL can be a sensor for a zones",
"TODO: WIP # return json.dumps({self._ctl.id: self.schema}) def _discover(self, discover_flag=DISCOVER_ALL) -> None: # super()._discover(discover_flag=discover_flag)",
"zone, NB: CTL can be a sensor for a zones # TODO: where",
"# no testable zones testable_sensors = [ d for d in self._gwy.devices #",
"(\"00\", \"04\", \"0C\", \"0F\", \"10\") ] if discover_flag & DISCOVER_STATUS: self._send_cmd(\"0006\") def _handle_msg(self,",
"TODO: removeme # params[ATTR_HTG_SYSTEM][ATTR_HTG_CONTROL] = ( # self.heating_control.params if self.heating_control else None #",
"considered 'authorative'. The 1FC9 RQ/RP exchange to/from a CTL is too rare to",
"TODO: to sort out @property def heating_control(self) -> Device: if self._htg_control: return self._htg_control",
"ATTR_DHW_SYSTEM, ATTR_HTG_CONTROL, ATTR_HTG_SYSTEM, ATTR_ORPHANS, ATTR_UFH_SYSTEM, ATTR_ZONES, DISABLE_DISCOVERY, MAX_ZONES, ) from .zones import DhwZone,",
"= dt.now() # while not self._schedule_done: # await asyncio.sleep(TIMER_SHORT_SLEEP) # if dt.now() >",
"not self._schedule_done: # await asyncio.sleep(TIMER_SHORT_SLEEP) # if dt.now() > time_start + TIMER_LONG_TIMEOUT: #",
"zones with changed temps _LOGGER.debug(\"Changed zones (from 30C9): %s\", changed_zones) if not changed_zones:",
"device: Device) -> None: # self._htg_control \"\"\"Set the heating control relay for this",
"zone_dict # elif msg.code == \"30C9\": # zone._temp = zone_dict # if msg.code",
"def status(self) -> dict: status = super().status assert ATTR_HTG_SYSTEM in status # TODO:",
"} @property def relay_failsafes(self) -> Optional[dict]: # 0009 if self._relay_failsafes: return {} #",
"# await asyncio.sleep(TIMER_SHORT_SLEEP) # if dt.now() > time_start + TIMER_LONG_TIMEOUT: # self._api_lock.release() #",
"# return self.datetime # async def set_datetime(self, dtm: dt) -> str: # wait",
"# HACK for 10: def _set_htg_control(self, device: Device) -> None: # self._htg_control \"\"\"Set",
"not authorative. The I/1260 is not to/from a controller, so is not useful.",
"if this.src is self and prev.src.type == \"13\": heater = prev.src if heater",
"assert ATTR_HTG_CONTROL not in schema[ATTR_HTG_SYSTEM] # TODO: removeme schema[ATTR_HTG_SYSTEM][ATTR_HTG_CONTROL] = ( self.heating_control.id if",
"safely(?) assume this zone is using the CTL as a sensor... if len(matching_sensors)",
"not None: if self.dhw is None: self._get_zone(\"FA\") self.dhw._set_sensor(sensor) super()._handle_msg(msg) if msg.code in (\"10A0\",",
"be removed MAX_SETPOINT = 85.0 DEFAULT_SETPOINT = 50.0 def __init__(self, *args, **kwargs) ->",
"#67) zone._discover() # discover_flag=DISCOVER_ALL) return zone if zone_idx == \"HW\": return super()._get_zone(zone_idx, sensor=sensor,",
"_discover(self, discover_flag=DISCOVER_ALL) -> None: # super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_SCHEMA: [ # 000C:",
"ctl, **kwargs) -> None: super().__init__(gwy, ctl, **kwargs) def __repr__(self) -> str: return f\"{self._ctl.id}",
"dhw_mode pass def _get_zone(self, zone_idx, sensor=None, **kwargs) -> DhwZone: \"\"\"Return a DHW zone",
"_discover(self, discover_flag=DISCOVER_ALL) -> None: super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_STATUS: pass def _handle_msg(self, msg,",
"msg.payload: self._relay_demands[msg.payload[\"domain_id\"]] = msg if msg.payload[\"domain_id\"] == \"F9\": device = self.dhw.heating_valve if self.dhw",
"discover_flag & DISCOVER_STATUS: self._gwy._tasks.append(self._loop.create_task(self.get_fault_log())) async def get_fault_log(self, force_refresh=None) -> Optional[dict]: # 0418 try:",
"SysFaultLog: # 0418 def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self._fault_log =",
"(currently) no zone without a sensor # if self._gwy.serial_port: # only if in",
"%s, temp: %s\", zone_idx, temp) _LOGGER.debug( \" - matching sensor(s): %s (same temp",
"d.type == \"02\" }, } class SystemBase(Entity): # 3B00 (multi-relay) \"\"\"The most basic",
"msg.code in (\"000A\", \"2309\", \"30C9\") and isinstance(msg.payload, list): pass class Chronotherm(Evohome): def __repr__(self)",
"a 10:* (1x/1min) 2b. The 3EF0 RQ (no RP) *to a 13:* (3x/60min)",
"TODO: removeme status[ATTR_HTG_SYSTEM][\"heat_demands\"] = self.heat_demands status[ATTR_HTG_SYSTEM][\"relay_demands\"] = self.relay_demands status[ATTR_HTG_SYSTEM][\"relay_failsafes\"] = self.relay_failsafes return status",
"(will create it if required). Can also set a DHW zone's sensor &",
"against 30C9 (array) pkt from the last cycle _LOGGER.debug(\"System state (before): %s\", self)",
"10A0 006 0018380003E8 # 1260: I/07: can't get which parent controller - need",
"not None and device.evo is not self: # raise LookupError if self._htg_control is",
"self.__class__) super().__init__(gwy, **kwargs) self.id = ctl.id gwy.systems.append(self) gwy.system_by_id[self.id] = self self._ctl = ctl",
"in (\"000A\",) and isinstance(msg.payload, list): for zone_idx in self.zone_by_idx: cmd = Command.get_zone_mode(self.id, zone_idx,",
"stored HW this system (if any). There is only 2 ways to to",
"tpi_params(self) -> Optional[float]: # 1100 return self._get_msg_value(\"1100\") @property def heat_demand(self) -> Optional[float]: #",
"2} for code in (\"0008\", \"3EF1\"): device._send_cmd(code, qos) if msg.code == \"3150\" and",
"# 1F41: I/01: get parent controller, but not DHW sensor # 045 I",
"device in [d for d in kwargs[\"actuators\"] if d not in zone.devices]: zone.devices.append(device)",
"system's schema.\"\"\" schema = {ATTR_CONTROLLER: self._ctl.id, ATTR_HTG_SYSTEM: {}} assert ATTR_HTG_SYSTEM in schema #",
"= None def _discover(self, discover_flag=DISCOVER_ALL) -> None: super()._discover(discover_flag=discover_flag) if discover_flag & DISCOVER_STATUS: #",
"0008|0009|1030|1100|2309|3B00 def __init__(self, gwy, ctl, **kwargs) -> None: # _LOGGER.debug(\"Creating a System: %s",
"elif msg.code in (\"1F41\",): # dhw_mode pass def _get_zone(self, zone_idx, sensor=None, **kwargs) ->",
"a controller's heat relay (in order of reliability): 1. The 3220 RQ/RP *to/from",
"ATTR_ZONES not in super().schema # TODO: removeme return {**super().schema, ATTR_ZONES: {z.idx: z.schema for",
"= 50.0 def __init__(self, *args, **kwargs) -> None: super().__init__(*args, **kwargs) self._dhw = None",
"RF - The evohome-compatible system.\"\"\" import logging from asyncio import Task from datetime",
"= self.zone_by_idx[zone_idx] zone._set_sensor(self) zone.sensor._set_ctl(self) _LOGGER.debug(\"System state (finally): %s\", self) super()._handle_msg(msg) if msg.code in",
"self._language = msg @property def language(self) -> Optional[str]: # 0100 return self._msg_payload(self._language, \"language\")",
"t in changed_zones.items() if self.zone_by_idx[z].sensor is None and t not in [v for",
"if this.src is self and this.dst.type == \"07\": sensor = this.dst if sensor",
"None) ] _LOGGER.debug(\"Testing zone %s, temp: %s\", zone_idx, temp) _LOGGER.debug( \" - matching",
"def __init__(self, gwy, ctl, **kwargs) -> None: # _LOGGER.debug(\"Creating a System: %s (%s)\",",
"I/1260 is not to/from a controller, so is not useful. \"\"\" # 10A0:",
"The 3EF0 RQ (no RP) *to a 13:* (3x/60min) 3. The 3B00 I/I",
"temperatures. In addition, there may be 'orphan' (e.g. from a neighbour) sensors announcing",
"-*- # \"\"\"Evohome RF - The evohome-compatible system.\"\"\" import logging from asyncio import",
"\"\"\"Discover the stored HW this system (if any). There is only 2 ways",
"this.verb: if this.src is self and prev.src.type == \"13\": heater = prev.src if"
] |
[
"== 'relu': if uniform: init_range = tf.sqrt(6.0 / (n_inputs + n_outputs)) * np.sqrt(2)",
"# 2D convolution def conv2d(x, W, strides=1): conv_2d = tf.nn.conv2d(x, W, strides=[1, strides,",
"crop and concat def crop_and_concat(x1, x2): x1_shape = tf.shape(x1) x2_shape = tf.shape(x2) #",
"x2): x1_shape = tf.shape(x1) x2_shape = tf.shape(x2) # offsets for the top left",
"initialization (Xavier's init) def weight_xavier_init(shape, n_inputs, n_outputs, activefuncation='sigmoid', uniform=True, variable_name=None): if activefuncation ==",
"mean=0.0, stddev=stddev) return tf.Variable(initial, name=variable_name) elif activefuncation == 'tan': if uniform: init_range =",
"n_outputs)) * 4 initial = tf.truncated_normal(shape, mean=0.0, stddev=stddev) return tf.Variable(initial, name=variable_name) # Bias",
"np.sqrt(2) initial = tf.random_uniform(shape, -init_range, init_range) return tf.Variable(initial, name=variable_name) else: stddev = tf.sqrt(2.0",
"[1, C, 1, 1]) beta = tf.reshape(beta, [1, C, 1, 1]) output =",
"weight_xavier_init(shape, n_inputs, n_outputs, activefuncation='sigmoid', uniform=True, variable_name=None): if activefuncation == 'sigmoid': if uniform: init_range",
"None: H,W=height,width x = tf.reshape(x, [-1, G, C // G, H, W]) mean,",
"tf.name_scope(scope + norm_type): if norm_type == 'None': output = x elif norm_type ==",
"- x2_shape[1]) // 2, (x1_shape[2] - x2_shape[2]) // 2, 0] size = [-1,",
"resnet_Add(x1, x2): \"\"\" x1 shape[-1] is small x2 shape[-1] \"\"\" if x1.get_shape().as_list()[3] !=",
"init_range = tf.sqrt(6.0 / (n_inputs + n_outputs)) * np.sqrt(2) initial = tf.random_uniform(shape, -init_range,",
"!= x2.get_shape().as_list()[3]: # Option A:zero-padding residual_connection = x2 + tf.pad(x1, [[0, 0], [0,",
"+ n_outputs)) * np.sqrt(2) initial = tf.random_uniform(shape, -init_range, init_range) return tf.Variable(initial, name=variable_name) else:",
"(x1_shape[2] - x2_shape[2]) // 2, 0] size = [-1, x2_shape[1], x2_shape[2], -1] x1_crop",
"= [-1, x2_shape[1], x2_shape[2], -1] x1_crop = tf.slice(x1, offsets, size) return tf.concat([x1_crop, x2],",
"[-1, G, C // G, H, W]) mean, var = tf.nn.moments(x, [2, 3,",
"tf.truncated_normal(shape, mean=0.0, stddev=stddev) return tf.Variable(initial, name=variable_name) elif activefuncation == 'relu': if uniform: init_range",
"return tf.Variable(initial, name=variable_name) else: stddev = tf.sqrt(2.0 / (n_inputs + n_outputs)) initial =",
"gama = tf.reshape(gama, [1, C, 1, 1]) beta = tf.reshape(beta, [1, C, 1,",
"== 'None': output = x elif norm_type == 'batch': output = tf.contrib.layers.batch_norm(x, center=True,",
"= tf.constant(0.1, shape=shape) return tf.Variable(initial, name=variable_name) # 2D convolution def conv2d(x, W, strides=1):",
"norm_type == 'group': # tranpose:[bs,h,w,c]to[bs,c,h,w]follwing the paper x = tf.transpose(x, [0, 3, 1,",
"conv2d(x, W, strides=1): conv_2d = tf.nn.conv2d(x, W, strides=[1, strides, strides, 1], padding='SAME') return",
"deconvolution def deconv2d(x, W, stride=2): x_shape = tf.shape(x) output_shape = tf.stack([x_shape[0], x_shape[1] *",
"uniform: init_range = tf.sqrt(6.0 / (n_inputs + n_outputs)) initial = tf.random_uniform(shape, -init_range, init_range)",
"tf.sqrt(6.0 / (n_inputs + n_outputs)) initial = tf.random_uniform(shape, -init_range, init_range) return tf.Variable(initial, name=variable_name)",
"== 'sigmoid': if uniform: init_range = tf.sqrt(6.0 / (n_inputs + n_outputs)) initial =",
"= tf.sqrt(2.0 / (n_inputs + n_outputs)) initial = tf.truncated_normal(shape, mean=0.0, stddev=stddev) return tf.Variable(initial,",
"W, strides=[1, strides, strides, 1], padding='SAME') return conv_2d def normalizationlayer(x, is_train, height=None, width=None,",
"tf.Variable(initial, name=variable_name) else: stddev = tf.sqrt(2.0 / (n_inputs + n_outputs)) * 4 initial",
"beta = tf.get_variable(scope + norm_type + 'group_beta', [C], initializer=tf.constant_initializer(0.0)) gama = tf.reshape(gama, [1,",
"= min(G, C) if H == None and W == None: H,W=height,width x",
"init_range = tf.sqrt(6.0 / (n_inputs + n_outputs)) * 4 initial = tf.random_uniform(shape, -init_range,",
"x1 shape[-1] is small x2 shape[-1] \"\"\" if x1.get_shape().as_list()[3] != x2.get_shape().as_list()[3]: # Option",
"n_outputs)) * np.sqrt(2) initial = tf.random_uniform(shape, -init_range, init_range) return tf.Variable(initial, name=variable_name) else: stddev",
"H,W=height,width x = tf.reshape(x, [-1, G, C // G, H, W]) mean, var",
"+ n_outputs)) * 4 initial = tf.truncated_normal(shape, mean=0.0, stddev=stddev) return tf.Variable(initial, name=variable_name) #",
"and W == None: H,W=height,width x = tf.reshape(x, [-1, G, C // G,",
"tf.Variable(initial, name=variable_name) elif activefuncation == 'relu': if uniform: init_range = tf.sqrt(6.0 / (n_inputs",
"C, H, W]) * gama + beta ## tranpose:[bs,c,h,w]to[bs,h,w,c]follwing the paper output =",
"* 4 initial = tf.truncated_normal(shape, mean=0.0, stddev=stddev) return tf.Variable(initial, name=variable_name) # Bias initialization",
"* gama + beta ## tranpose:[bs,c,h,w]to[bs,h,w,c]follwing the paper output = tf.transpose(output, [0, 2,",
"x.get_shape().as_list() G = min(G, C) if H == None and W == None:",
"/ tf.sqrt(var + esp) # per channel gama and beta gama = tf.get_variable(scope",
"elif norm_type == 'group': # tranpose:[bs,h,w,c]to[bs,c,h,w]follwing the paper x = tf.transpose(x, [0, 3,",
"return tf.Variable(initial, name=variable_name) # Bias initialization def bias_variable(shape, variable_name=None): initial = tf.constant(0.1, shape=shape)",
"center=True, scale=True, is_training=is_train) elif norm_type == 'group': # tranpose:[bs,h,w,c]to[bs,c,h,w]follwing the paper x =",
"tf.shape(x) output_shape = tf.stack([x_shape[0], x_shape[1] * stride, x_shape[2] * stride, x_shape[3] // stride])",
"= tf.sqrt(2.0 / (n_inputs + n_outputs)) * 4 initial = tf.truncated_normal(shape, mean=0.0, stddev=stddev)",
"if uniform: init_range = tf.sqrt(6.0 / (n_inputs + n_outputs)) * np.sqrt(2) initial =",
"if x1.get_shape().as_list()[3] != x2.get_shape().as_list()[3]: # Option A:zero-padding residual_connection = x2 + tf.pad(x1, [[0,",
"H == None and W == None: H,W=height,width x = tf.reshape(x, [-1, G,",
"[C], initializer=tf.constant_initializer(1.0)) beta = tf.get_variable(scope + norm_type + 'group_beta', [C], initializer=tf.constant_initializer(0.0)) gama =",
"initial = tf.constant(0.1, shape=shape) return tf.Variable(initial, name=variable_name) # 2D convolution def conv2d(x, W,",
"x2_shape[2], -1] x1_crop = tf.slice(x1, offsets, size) return tf.concat([x1_crop, x2], 3) # Resnet",
"tf.shape(x1) x2_shape = tf.shape(x2) # offsets for the top left corner of the",
"stddev=stddev) return tf.Variable(initial, name=variable_name) # Bias initialization def bias_variable(shape, variable_name=None): initial = tf.constant(0.1,",
"initial = tf.truncated_normal(shape, mean=0.0, stddev=stddev) return tf.Variable(initial, name=variable_name) elif activefuncation == 'relu': if",
"tf.reshape(x, [-1, C, H, W]) * gama + beta ## tranpose:[bs,c,h,w]to[bs,h,w,c]follwing the paper",
"elif activefuncation == 'relu': if uniform: init_range = tf.sqrt(6.0 / (n_inputs + n_outputs))",
"tf.shape(x2) # offsets for the top left corner of the crop offsets =",
"// G, H, W]) mean, var = tf.nn.moments(x, [2, 3, 4], keep_dims=True) x",
"== 'group': # tranpose:[bs,h,w,c]to[bs,c,h,w]follwing the paper x = tf.transpose(x, [0, 3, 1, 2])",
"gama + beta ## tranpose:[bs,c,h,w]to[bs,h,w,c]follwing the paper output = tf.transpose(output, [0, 2, 3,",
"x2_shape[2]) // 2, 0] size = [-1, x2_shape[1], x2_shape[2], -1] x1_crop = tf.slice(x1,",
"uniform: init_range = tf.sqrt(6.0 / (n_inputs + n_outputs)) * np.sqrt(2) initial = tf.random_uniform(shape,",
"tf.slice(x1, offsets, size) return tf.concat([x1_crop, x2], 3) # Resnet add def resnet_Add(x1, x2):",
"[C], initializer=tf.constant_initializer(0.0)) gama = tf.reshape(gama, [1, C, 1, 1]) beta = tf.reshape(beta, [1,",
"channel gama and beta gama = tf.get_variable(scope + norm_type + 'group_gama', [C], initializer=tf.constant_initializer(1.0))",
"tf import numpy as np # Weight initialization (Xavier's init) def weight_xavier_init(shape, n_inputs,",
"/ (n_inputs + n_outputs)) * 4 initial = tf.truncated_normal(shape, mean=0.0, stddev=stddev) return tf.Variable(initial,",
"H, W]) * gama + beta ## tranpose:[bs,c,h,w]to[bs,h,w,c]follwing the paper output = tf.transpose(output,",
"= (x - mean) / tf.sqrt(var + esp) # per channel gama and",
"= tf.shape(x) output_shape = tf.stack([x_shape[0], x_shape[1] * stride, x_shape[2] * stride, x_shape[3] //",
"x1_crop = tf.slice(x1, offsets, size) return tf.concat([x1_crop, x2], 3) # Resnet add def",
"2, 3, 1]) return output # 2D deconvolution def deconv2d(x, W, stride=2): x_shape",
"if activefuncation == 'sigmoid': if uniform: init_range = tf.sqrt(6.0 / (n_inputs + n_outputs))",
"paper output = tf.transpose(output, [0, 2, 3, 1]) return output # 2D deconvolution",
"beta = tf.reshape(beta, [1, C, 1, 1]) output = tf.reshape(x, [-1, C, H,",
"= tf.transpose(output, [0, 2, 3, 1]) return output # 2D deconvolution def deconv2d(x,",
"else: stddev = tf.sqrt(2.0 / (n_inputs + n_outputs)) initial = tf.truncated_normal(shape, mean=0.0, stddev=stddev)",
"conv_2d def normalizationlayer(x, is_train, height=None, width=None, norm_type='None', G=16, esp=1e-5, scope=None): with tf.name_scope(scope +",
"stddev = tf.sqrt(2.0 / (n_inputs + n_outputs)) * np.sqrt(2) initial = tf.truncated_normal(shape, mean=0.0,",
"tf.reshape(gama, [1, C, 1, 1]) beta = tf.reshape(beta, [1, C, 1, 1]) output",
"= tf.sqrt(6.0 / (n_inputs + n_outputs)) * np.sqrt(2) initial = tf.random_uniform(shape, -init_range, init_range)",
"= tf.truncated_normal(shape, mean=0.0, stddev=stddev) return tf.Variable(initial, name=variable_name) elif activefuncation == 'tan': if uniform:",
"1]) beta = tf.reshape(beta, [1, C, 1, 1]) output = tf.reshape(x, [-1, C,",
"crop_and_concat(x1, x2): x1_shape = tf.shape(x1) x2_shape = tf.shape(x2) # offsets for the top",
"tranpose:[bs,c,h,w]to[bs,h,w,c]follwing the paper output = tf.transpose(output, [0, 2, 3, 1]) return output #",
"1], padding='SAME') return conv_2d def normalizationlayer(x, is_train, height=None, width=None, norm_type='None', G=16, esp=1e-5, scope=None):",
"name=variable_name) # 2D convolution def conv2d(x, W, strides=1): conv_2d = tf.nn.conv2d(x, W, strides=[1,",
"1]) output = tf.reshape(x, [-1, C, H, W]) * gama + beta ##",
"tranpose:[bs,h,w,c]to[bs,c,h,w]follwing the paper x = tf.transpose(x, [0, 3, 1, 2]) N, C, H,",
"= tf.random_uniform(shape, -init_range, init_range) return tf.Variable(initial, name=variable_name) else: stddev = tf.sqrt(2.0 / (n_inputs",
"C, 1, 1]) output = tf.reshape(x, [-1, C, H, W]) * gama +",
"+ n_outputs)) * 4 initial = tf.random_uniform(shape, -init_range, init_range) return tf.Variable(initial, name=variable_name) else:",
"= tf.get_variable(scope + norm_type + 'group_gama', [C], initializer=tf.constant_initializer(1.0)) beta = tf.get_variable(scope + norm_type",
"1], padding='SAME') # Unet crop and concat def crop_and_concat(x1, x2): x1_shape = tf.shape(x1)",
"[0, 0], [0, x2.get_shape().as_list()[3] - x1.get_shape().as_list()[3]]]) else: residual_connection = x2 + x1 #",
"# Bias initialization def bias_variable(shape, variable_name=None): initial = tf.constant(0.1, shape=shape) return tf.Variable(initial, name=variable_name)",
"// stride]) return tf.nn.conv2d_transpose(x, W, output_shape, strides=[1, stride, stride, 1], padding='SAME') # Unet",
"# per channel gama and beta gama = tf.get_variable(scope + norm_type + 'group_gama',",
"initializer=tf.constant_initializer(1.0)) beta = tf.get_variable(scope + norm_type + 'group_beta', [C], initializer=tf.constant_initializer(0.0)) gama = tf.reshape(gama,",
"x_shape[2] * stride, x_shape[3] // stride]) return tf.nn.conv2d_transpose(x, W, output_shape, strides=[1, stride, stride,",
"elif norm_type == 'batch': output = tf.contrib.layers.batch_norm(x, center=True, scale=True, is_training=is_train) elif norm_type ==",
"3, 4], keep_dims=True) x = (x - mean) / tf.sqrt(var + esp) #",
"tf.Variable(initial, name=variable_name) else: stddev = tf.sqrt(2.0 / (n_inputs + n_outputs)) initial = tf.truncated_normal(shape,",
"initial = tf.truncated_normal(shape, mean=0.0, stddev=stddev) return tf.Variable(initial, name=variable_name) elif activefuncation == 'tan': if",
"paper x = tf.transpose(x, [0, 3, 1, 2]) N, C, H, W =",
"stddev = tf.sqrt(2.0 / (n_inputs + n_outputs)) initial = tf.truncated_normal(shape, mean=0.0, stddev=stddev) return",
"= tf.reshape(gama, [1, C, 1, 1]) beta = tf.reshape(beta, [1, C, 1, 1])",
"= x.get_shape().as_list() G = min(G, C) if H == None and W ==",
"'batch': output = tf.contrib.layers.batch_norm(x, center=True, scale=True, is_training=is_train) elif norm_type == 'group': # tranpose:[bs,h,w,c]to[bs,c,h,w]follwing",
"# 2D deconvolution def deconv2d(x, W, stride=2): x_shape = tf.shape(x) output_shape = tf.stack([x_shape[0],",
"the paper output = tf.transpose(output, [0, 2, 3, 1]) return output # 2D",
"x2_shape[1], x2_shape[2], -1] x1_crop = tf.slice(x1, offsets, size) return tf.concat([x1_crop, x2], 3) #",
"== None: H,W=height,width x = tf.reshape(x, [-1, G, C // G, H, W])",
"x = (x - mean) / tf.sqrt(var + esp) # per channel gama",
"layer,pool layer,initialization。。。。 ''' import tensorflow as tf import numpy as np # Weight",
"(Xavier's init) def weight_xavier_init(shape, n_inputs, n_outputs, activefuncation='sigmoid', uniform=True, variable_name=None): if activefuncation == 'sigmoid':",
"tf.Variable(initial, name=variable_name) # Bias initialization def bias_variable(shape, variable_name=None): initial = tf.constant(0.1, shape=shape) return",
"(n_inputs + n_outputs)) * np.sqrt(2) initial = tf.truncated_normal(shape, mean=0.0, stddev=stddev) return tf.Variable(initial, name=variable_name)",
"C) if H == None and W == None: H,W=height,width x = tf.reshape(x,",
"return tf.Variable(initial, name=variable_name) # 2D convolution def conv2d(x, W, strides=1): conv_2d = tf.nn.conv2d(x,",
"/ (n_inputs + n_outputs)) * 4 initial = tf.random_uniform(shape, -init_range, init_range) return tf.Variable(initial,",
"+ 'group_gama', [C], initializer=tf.constant_initializer(1.0)) beta = tf.get_variable(scope + norm_type + 'group_beta', [C], initializer=tf.constant_initializer(0.0))",
"tf.sqrt(2.0 / (n_inputs + n_outputs)) * 4 initial = tf.truncated_normal(shape, mean=0.0, stddev=stddev) return",
"# Option A:zero-padding residual_connection = x2 + tf.pad(x1, [[0, 0], [0, 0], [0,",
"tf.sqrt(6.0 / (n_inputs + n_outputs)) * 4 initial = tf.random_uniform(shape, -init_range, init_range) return",
"H, W]) mean, var = tf.nn.moments(x, [2, 3, 4], keep_dims=True) x = (x",
"/ (n_inputs + n_outputs)) * np.sqrt(2) initial = tf.random_uniform(shape, -init_range, init_range) return tf.Variable(initial,",
"x2 + tf.pad(x1, [[0, 0], [0, 0], [0, 0], [0, x2.get_shape().as_list()[3] - x1.get_shape().as_list()[3]]])",
"def bias_variable(shape, variable_name=None): initial = tf.constant(0.1, shape=shape) return tf.Variable(initial, name=variable_name) # 2D convolution",
"tf.reshape(beta, [1, C, 1, 1]) output = tf.reshape(x, [-1, C, H, W]) *",
"as np # Weight initialization (Xavier's init) def weight_xavier_init(shape, n_inputs, n_outputs, activefuncation='sigmoid', uniform=True,",
"import numpy as np # Weight initialization (Xavier's init) def weight_xavier_init(shape, n_inputs, n_outputs,",
"// 2, 0] size = [-1, x2_shape[1], x2_shape[2], -1] x1_crop = tf.slice(x1, offsets,",
"2, (x1_shape[2] - x2_shape[2]) // 2, 0] size = [-1, x2_shape[1], x2_shape[2], -1]",
"name=variable_name) else: stddev = tf.sqrt(2.0 / (n_inputs + n_outputs)) * np.sqrt(2) initial =",
"min(G, C) if H == None and W == None: H,W=height,width x =",
"(n_inputs + n_outputs)) * 4 initial = tf.truncated_normal(shape, mean=0.0, stddev=stddev) return tf.Variable(initial, name=variable_name)",
"var = tf.nn.moments(x, [2, 3, 4], keep_dims=True) x = (x - mean) /",
"esp=1e-5, scope=None): with tf.name_scope(scope + norm_type): if norm_type == 'None': output = x",
"return output # 2D deconvolution def deconv2d(x, W, stride=2): x_shape = tf.shape(x) output_shape",
"activefuncation == 'relu': if uniform: init_range = tf.sqrt(6.0 / (n_inputs + n_outputs)) *",
"C, 1, 1]) beta = tf.reshape(beta, [1, C, 1, 1]) output = tf.reshape(x,",
"residual_connection = x2 + tf.pad(x1, [[0, 0], [0, 0], [0, 0], [0, x2.get_shape().as_list()[3]",
"mean, var = tf.nn.moments(x, [2, 3, 4], keep_dims=True) x = (x - mean)",
"numpy as np # Weight initialization (Xavier's init) def weight_xavier_init(shape, n_inputs, n_outputs, activefuncation='sigmoid',",
"tf.stack([x_shape[0], x_shape[1] * stride, x_shape[2] * stride, x_shape[3] // stride]) return tf.nn.conv2d_transpose(x, W,",
"size = [-1, x2_shape[1], x2_shape[2], -1] x1_crop = tf.slice(x1, offsets, size) return tf.concat([x1_crop,",
"shape[-1] is small x2 shape[-1] \"\"\" if x1.get_shape().as_list()[3] != x2.get_shape().as_list()[3]: # Option A:zero-padding",
"tf.pad(x1, [[0, 0], [0, 0], [0, 0], [0, x2.get_shape().as_list()[3] - x1.get_shape().as_list()[3]]]) else: residual_connection",
"A:zero-padding residual_connection = x2 + tf.pad(x1, [[0, 0], [0, 0], [0, 0], [0,",
"= x elif norm_type == 'batch': output = tf.contrib.layers.batch_norm(x, center=True, scale=True, is_training=is_train) elif",
"- mean) / tf.sqrt(var + esp) # per channel gama and beta gama",
"keep_dims=True) x = (x - mean) / tf.sqrt(var + esp) # per channel",
"<gh_stars>10-100 ''' covlution layer,pool layer,initialization。。。。 ''' import tensorflow as tf import numpy as",
"left corner of the crop offsets = [0, (x1_shape[1] - x2_shape[1]) // 2,",
"concat def crop_and_concat(x1, x2): x1_shape = tf.shape(x1) x2_shape = tf.shape(x2) # offsets for",
"np.sqrt(2) initial = tf.truncated_normal(shape, mean=0.0, stddev=stddev) return tf.Variable(initial, name=variable_name) elif activefuncation == 'tan':",
"name=variable_name) else: stddev = tf.sqrt(2.0 / (n_inputs + n_outputs)) initial = tf.truncated_normal(shape, mean=0.0,",
"x2_shape = tf.shape(x2) # offsets for the top left corner of the crop",
"tf.concat([x1_crop, x2], 3) # Resnet add def resnet_Add(x1, x2): \"\"\" x1 shape[-1] is",
"[-1, x2_shape[1], x2_shape[2], -1] x1_crop = tf.slice(x1, offsets, size) return tf.concat([x1_crop, x2], 3)",
"x_shape = tf.shape(x) output_shape = tf.stack([x_shape[0], x_shape[1] * stride, x_shape[2] * stride, x_shape[3]",
"init_range) return tf.Variable(initial, name=variable_name) else: stddev = tf.sqrt(2.0 / (n_inputs + n_outputs)) *",
"1, 1]) beta = tf.reshape(beta, [1, C, 1, 1]) output = tf.reshape(x, [-1,",
"= x2 + tf.pad(x1, [[0, 0], [0, 0], [0, 0], [0, x2.get_shape().as_list()[3] -",
"= tf.nn.moments(x, [2, 3, 4], keep_dims=True) x = (x - mean) / tf.sqrt(var",
"x1.get_shape().as_list()[3] != x2.get_shape().as_list()[3]: # Option A:zero-padding residual_connection = x2 + tf.pad(x1, [[0, 0],",
"W]) mean, var = tf.nn.moments(x, [2, 3, 4], keep_dims=True) x = (x -",
"+ norm_type + 'group_gama', [C], initializer=tf.constant_initializer(1.0)) beta = tf.get_variable(scope + norm_type + 'group_beta',",
"output = tf.contrib.layers.batch_norm(x, center=True, scale=True, is_training=is_train) elif norm_type == 'group': # tranpose:[bs,h,w,c]to[bs,c,h,w]follwing the",
"+ norm_type): if norm_type == 'None': output = x elif norm_type == 'batch':",
"return tf.Variable(initial, name=variable_name) elif activefuncation == 'tan': if uniform: init_range = tf.sqrt(6.0 /",
"n_outputs)) * np.sqrt(2) initial = tf.truncated_normal(shape, mean=0.0, stddev=stddev) return tf.Variable(initial, name=variable_name) elif activefuncation",
"strides=[1, stride, stride, 1], padding='SAME') # Unet crop and concat def crop_and_concat(x1, x2):",
"* 4 initial = tf.random_uniform(shape, -init_range, init_range) return tf.Variable(initial, name=variable_name) else: stddev =",
"None and W == None: H,W=height,width x = tf.reshape(x, [-1, G, C //",
"tf.Variable(initial, name=variable_name) # 2D convolution def conv2d(x, W, strides=1): conv_2d = tf.nn.conv2d(x, W,",
"beta ## tranpose:[bs,c,h,w]to[bs,h,w,c]follwing the paper output = tf.transpose(output, [0, 2, 3, 1]) return",
"(n_inputs + n_outputs)) * np.sqrt(2) initial = tf.random_uniform(shape, -init_range, init_range) return tf.Variable(initial, name=variable_name)",
"0] size = [-1, x2_shape[1], x2_shape[2], -1] x1_crop = tf.slice(x1, offsets, size) return",
"tf.nn.conv2d_transpose(x, W, output_shape, strides=[1, stride, stride, 1], padding='SAME') # Unet crop and concat",
"crop offsets = [0, (x1_shape[1] - x2_shape[1]) // 2, (x1_shape[2] - x2_shape[2]) //",
"name=variable_name) # Bias initialization def bias_variable(shape, variable_name=None): initial = tf.constant(0.1, shape=shape) return tf.Variable(initial,",
"'sigmoid': if uniform: init_range = tf.sqrt(6.0 / (n_inputs + n_outputs)) initial = tf.random_uniform(shape,",
"tf.nn.moments(x, [2, 3, 4], keep_dims=True) x = (x - mean) / tf.sqrt(var +",
"strides, strides, 1], padding='SAME') return conv_2d def normalizationlayer(x, is_train, height=None, width=None, norm_type='None', G=16,",
"strides=1): conv_2d = tf.nn.conv2d(x, W, strides=[1, strides, strides, 1], padding='SAME') return conv_2d def",
"G, C // G, H, W]) mean, var = tf.nn.moments(x, [2, 3, 4],",
"== 'tan': if uniform: init_range = tf.sqrt(6.0 / (n_inputs + n_outputs)) * 4",
"x1_shape = tf.shape(x1) x2_shape = tf.shape(x2) # offsets for the top left corner",
"+ 'group_beta', [C], initializer=tf.constant_initializer(0.0)) gama = tf.reshape(gama, [1, C, 1, 1]) beta =",
"the crop offsets = [0, (x1_shape[1] - x2_shape[1]) // 2, (x1_shape[2] - x2_shape[2])",
"= tf.reshape(x, [-1, G, C // G, H, W]) mean, var = tf.nn.moments(x,",
"'None': output = x elif norm_type == 'batch': output = tf.contrib.layers.batch_norm(x, center=True, scale=True,",
"else: stddev = tf.sqrt(2.0 / (n_inputs + n_outputs)) * 4 initial = tf.truncated_normal(shape,",
"tf.truncated_normal(shape, mean=0.0, stddev=stddev) return tf.Variable(initial, name=variable_name) # Bias initialization def bias_variable(shape, variable_name=None): initial",
"(n_inputs + n_outputs)) * 4 initial = tf.random_uniform(shape, -init_range, init_range) return tf.Variable(initial, name=variable_name)",
"tf.contrib.layers.batch_norm(x, center=True, scale=True, is_training=is_train) elif norm_type == 'group': # tranpose:[bs,h,w,c]to[bs,c,h,w]follwing the paper x",
"2, 0] size = [-1, x2_shape[1], x2_shape[2], -1] x1_crop = tf.slice(x1, offsets, size)",
"tf.sqrt(2.0 / (n_inputs + n_outputs)) * np.sqrt(2) initial = tf.truncated_normal(shape, mean=0.0, stddev=stddev) return",
"x = tf.reshape(x, [-1, G, C // G, H, W]) mean, var =",
"as tf import numpy as np # Weight initialization (Xavier's init) def weight_xavier_init(shape,",
"/ (n_inputs + n_outputs)) * np.sqrt(2) initial = tf.truncated_normal(shape, mean=0.0, stddev=stddev) return tf.Variable(initial,",
"tf.Variable(initial, name=variable_name) elif activefuncation == 'tan': if uniform: init_range = tf.sqrt(6.0 / (n_inputs",
"x2.get_shape().as_list()[3]: # Option A:zero-padding residual_connection = x2 + tf.pad(x1, [[0, 0], [0, 0],",
"C // G, H, W]) mean, var = tf.nn.moments(x, [2, 3, 4], keep_dims=True)",
"activefuncation='sigmoid', uniform=True, variable_name=None): if activefuncation == 'sigmoid': if uniform: init_range = tf.sqrt(6.0 /",
"init_range = tf.sqrt(6.0 / (n_inputs + n_outputs)) initial = tf.random_uniform(shape, -init_range, init_range) return",
"output = x elif norm_type == 'batch': output = tf.contrib.layers.batch_norm(x, center=True, scale=True, is_training=is_train)",
"if norm_type == 'None': output = x elif norm_type == 'batch': output =",
"x = tf.transpose(x, [0, 3, 1, 2]) N, C, H, W = x.get_shape().as_list()",
"# tranpose:[bs,h,w,c]to[bs,c,h,w]follwing the paper x = tf.transpose(x, [0, 3, 1, 2]) N, C,",
"stride, x_shape[2] * stride, x_shape[3] // stride]) return tf.nn.conv2d_transpose(x, W, output_shape, strides=[1, stride,",
"2D convolution def conv2d(x, W, strides=1): conv_2d = tf.nn.conv2d(x, W, strides=[1, strides, strides,",
"-1] x1_crop = tf.slice(x1, offsets, size) return tf.concat([x1_crop, x2], 3) # Resnet add",
"n_outputs)) initial = tf.truncated_normal(shape, mean=0.0, stddev=stddev) return tf.Variable(initial, name=variable_name) elif activefuncation == 'relu':",
"stride=2): x_shape = tf.shape(x) output_shape = tf.stack([x_shape[0], x_shape[1] * stride, x_shape[2] * stride,",
"and concat def crop_and_concat(x1, x2): x1_shape = tf.shape(x1) x2_shape = tf.shape(x2) # offsets",
"offsets for the top left corner of the crop offsets = [0, (x1_shape[1]",
"strides, 1], padding='SAME') return conv_2d def normalizationlayer(x, is_train, height=None, width=None, norm_type='None', G=16, esp=1e-5,",
"variable_name=None): if activefuncation == 'sigmoid': if uniform: init_range = tf.sqrt(6.0 / (n_inputs +",
"stddev=stddev) return tf.Variable(initial, name=variable_name) elif activefuncation == 'relu': if uniform: init_range = tf.sqrt(6.0",
"1, 2]) N, C, H, W = x.get_shape().as_list() G = min(G, C) if",
"C, H, W = x.get_shape().as_list() G = min(G, C) if H == None",
"[0, 0], [0, 0], [0, x2.get_shape().as_list()[3] - x1.get_shape().as_list()[3]]]) else: residual_connection = x2 +",
"if H == None and W == None: H,W=height,width x = tf.reshape(x, [-1,",
"x2_shape[1]) // 2, (x1_shape[2] - x2_shape[2]) // 2, 0] size = [-1, x2_shape[1],",
"3, 1, 2]) N, C, H, W = x.get_shape().as_list() G = min(G, C)",
"elif activefuncation == 'tan': if uniform: init_range = tf.sqrt(6.0 / (n_inputs + n_outputs))",
"def normalizationlayer(x, is_train, height=None, width=None, norm_type='None', G=16, esp=1e-5, scope=None): with tf.name_scope(scope + norm_type):",
"with tf.name_scope(scope + norm_type): if norm_type == 'None': output = x elif norm_type",
"H, W = x.get_shape().as_list() G = min(G, C) if H == None and",
"tf.sqrt(var + esp) # per channel gama and beta gama = tf.get_variable(scope +",
"width=None, norm_type='None', G=16, esp=1e-5, scope=None): with tf.name_scope(scope + norm_type): if norm_type == 'None':",
"x elif norm_type == 'batch': output = tf.contrib.layers.batch_norm(x, center=True, scale=True, is_training=is_train) elif norm_type",
"## tranpose:[bs,c,h,w]to[bs,h,w,c]follwing the paper output = tf.transpose(output, [0, 2, 3, 1]) return output",
"W, strides=1): conv_2d = tf.nn.conv2d(x, W, strides=[1, strides, strides, 1], padding='SAME') return conv_2d",
"\"\"\" if x1.get_shape().as_list()[3] != x2.get_shape().as_list()[3]: # Option A:zero-padding residual_connection = x2 + tf.pad(x1,",
"- x2_shape[2]) // 2, 0] size = [-1, x2_shape[1], x2_shape[2], -1] x1_crop =",
"= tf.shape(x1) x2_shape = tf.shape(x2) # offsets for the top left corner of",
"tf.get_variable(scope + norm_type + 'group_gama', [C], initializer=tf.constant_initializer(1.0)) beta = tf.get_variable(scope + norm_type +",
"3) # Resnet add def resnet_Add(x1, x2): \"\"\" x1 shape[-1] is small x2",
"'group_beta', [C], initializer=tf.constant_initializer(0.0)) gama = tf.reshape(gama, [1, C, 1, 1]) beta = tf.reshape(beta,",
"tf.Variable(initial, name=variable_name) else: stddev = tf.sqrt(2.0 / (n_inputs + n_outputs)) * np.sqrt(2) initial",
"else: stddev = tf.sqrt(2.0 / (n_inputs + n_outputs)) * np.sqrt(2) initial = tf.truncated_normal(shape,",
"4], keep_dims=True) x = (x - mean) / tf.sqrt(var + esp) # per",
"# offsets for the top left corner of the crop offsets = [0,",
"stddev=stddev) return tf.Variable(initial, name=variable_name) elif activefuncation == 'tan': if uniform: init_range = tf.sqrt(6.0",
"0], [0, 0], [0, 0], [0, x2.get_shape().as_list()[3] - x1.get_shape().as_list()[3]]]) else: residual_connection = x2",
"Unet crop and concat def crop_and_concat(x1, x2): x1_shape = tf.shape(x1) x2_shape = tf.shape(x2)",
"[0, 3, 1, 2]) N, C, H, W = x.get_shape().as_list() G = min(G,",
"G = min(G, C) if H == None and W == None: H,W=height,width",
"+ n_outputs)) * np.sqrt(2) initial = tf.truncated_normal(shape, mean=0.0, stddev=stddev) return tf.Variable(initial, name=variable_name) elif",
"np # Weight initialization (Xavier's init) def weight_xavier_init(shape, n_inputs, n_outputs, activefuncation='sigmoid', uniform=True, variable_name=None):",
"(x - mean) / tf.sqrt(var + esp) # per channel gama and beta",
"name=variable_name) elif activefuncation == 'relu': if uniform: init_range = tf.sqrt(6.0 / (n_inputs +",
"N, C, H, W = x.get_shape().as_list() G = min(G, C) if H ==",
"covlution layer,pool layer,initialization。。。。 ''' import tensorflow as tf import numpy as np #",
"the paper x = tf.transpose(x, [0, 3, 1, 2]) N, C, H, W",
"1]) return output # 2D deconvolution def deconv2d(x, W, stride=2): x_shape = tf.shape(x)",
"activefuncation == 'sigmoid': if uniform: init_range = tf.sqrt(6.0 / (n_inputs + n_outputs)) initial",
"is_train, height=None, width=None, norm_type='None', G=16, esp=1e-5, scope=None): with tf.name_scope(scope + norm_type): if norm_type",
"norm_type == 'None': output = x elif norm_type == 'batch': output = tf.contrib.layers.batch_norm(x,",
"* stride, x_shape[3] // stride]) return tf.nn.conv2d_transpose(x, W, output_shape, strides=[1, stride, stride, 1],",
"padding='SAME') # Unet crop and concat def crop_and_concat(x1, x2): x1_shape = tf.shape(x1) x2_shape",
"deconv2d(x, W, stride=2): x_shape = tf.shape(x) output_shape = tf.stack([x_shape[0], x_shape[1] * stride, x_shape[2]",
"= tf.stack([x_shape[0], x_shape[1] * stride, x_shape[2] * stride, x_shape[3] // stride]) return tf.nn.conv2d_transpose(x,",
"'group_gama', [C], initializer=tf.constant_initializer(1.0)) beta = tf.get_variable(scope + norm_type + 'group_beta', [C], initializer=tf.constant_initializer(0.0)) gama",
"size) return tf.concat([x1_crop, x2], 3) # Resnet add def resnet_Add(x1, x2): \"\"\" x1",
"= [0, (x1_shape[1] - x2_shape[1]) // 2, (x1_shape[2] - x2_shape[2]) // 2, 0]",
"activefuncation == 'tan': if uniform: init_range = tf.sqrt(6.0 / (n_inputs + n_outputs)) *",
"layer,initialization。。。。 ''' import tensorflow as tf import numpy as np # Weight initialization",
"return tf.concat([x1_crop, x2], 3) # Resnet add def resnet_Add(x1, x2): \"\"\" x1 shape[-1]",
"top left corner of the crop offsets = [0, (x1_shape[1] - x2_shape[1]) //",
"tf.truncated_normal(shape, mean=0.0, stddev=stddev) return tf.Variable(initial, name=variable_name) elif activefuncation == 'tan': if uniform: init_range",
"bias_variable(shape, variable_name=None): initial = tf.constant(0.1, shape=shape) return tf.Variable(initial, name=variable_name) # 2D convolution def",
"gama and beta gama = tf.get_variable(scope + norm_type + 'group_gama', [C], initializer=tf.constant_initializer(1.0)) beta",
"# Weight initialization (Xavier's init) def weight_xavier_init(shape, n_inputs, n_outputs, activefuncation='sigmoid', uniform=True, variable_name=None): if",
"\"\"\" x1 shape[-1] is small x2 shape[-1] \"\"\" if x1.get_shape().as_list()[3] != x2.get_shape().as_list()[3]: #",
"import tensorflow as tf import numpy as np # Weight initialization (Xavier's init)",
"initializer=tf.constant_initializer(0.0)) gama = tf.reshape(gama, [1, C, 1, 1]) beta = tf.reshape(beta, [1, C,",
"conv_2d = tf.nn.conv2d(x, W, strides=[1, strides, strides, 1], padding='SAME') return conv_2d def normalizationlayer(x,",
"// 2, (x1_shape[2] - x2_shape[2]) // 2, 0] size = [-1, x2_shape[1], x2_shape[2],",
"[2, 3, 4], keep_dims=True) x = (x - mean) / tf.sqrt(var + esp)",
"2]) N, C, H, W = x.get_shape().as_list() G = min(G, C) if H",
"stride, x_shape[3] // stride]) return tf.nn.conv2d_transpose(x, W, output_shape, strides=[1, stride, stride, 1], padding='SAME')",
"tensorflow as tf import numpy as np # Weight initialization (Xavier's init) def",
"(n_inputs + n_outputs)) initial = tf.random_uniform(shape, -init_range, init_range) return tf.Variable(initial, name=variable_name) else: stddev",
"x2], 3) # Resnet add def resnet_Add(x1, x2): \"\"\" x1 shape[-1] is small",
"stride, stride, 1], padding='SAME') # Unet crop and concat def crop_and_concat(x1, x2): x1_shape",
"= tf.sqrt(6.0 / (n_inputs + n_outputs)) initial = tf.random_uniform(shape, -init_range, init_range) return tf.Variable(initial,",
"output = tf.transpose(output, [0, 2, 3, 1]) return output # 2D deconvolution def",
"return tf.Variable(initial, name=variable_name) else: stddev = tf.sqrt(2.0 / (n_inputs + n_outputs)) * np.sqrt(2)",
"2D deconvolution def deconv2d(x, W, stride=2): x_shape = tf.shape(x) output_shape = tf.stack([x_shape[0], x_shape[1]",
"stride]) return tf.nn.conv2d_transpose(x, W, output_shape, strides=[1, stride, stride, 1], padding='SAME') # Unet crop",
"shape=shape) return tf.Variable(initial, name=variable_name) # 2D convolution def conv2d(x, W, strides=1): conv_2d =",
"* stride, x_shape[2] * stride, x_shape[3] // stride]) return tf.nn.conv2d_transpose(x, W, output_shape, strides=[1,",
"== None and W == None: H,W=height,width x = tf.reshape(x, [-1, G, C",
"return conv_2d def normalizationlayer(x, is_train, height=None, width=None, norm_type='None', G=16, esp=1e-5, scope=None): with tf.name_scope(scope",
"return tf.nn.conv2d_transpose(x, W, output_shape, strides=[1, stride, stride, 1], padding='SAME') # Unet crop and",
"Weight initialization (Xavier's init) def weight_xavier_init(shape, n_inputs, n_outputs, activefuncation='sigmoid', uniform=True, variable_name=None): if activefuncation",
"if uniform: init_range = tf.sqrt(6.0 / (n_inputs + n_outputs)) initial = tf.random_uniform(shape, -init_range,",
"Bias initialization def bias_variable(shape, variable_name=None): initial = tf.constant(0.1, shape=shape) return tf.Variable(initial, name=variable_name) #",
"tf.constant(0.1, shape=shape) return tf.Variable(initial, name=variable_name) # 2D convolution def conv2d(x, W, strides=1): conv_2d",
"= tf.reshape(beta, [1, C, 1, 1]) output = tf.reshape(x, [-1, C, H, W])",
"[0, 2, 3, 1]) return output # 2D deconvolution def deconv2d(x, W, stride=2):",
"W == None: H,W=height,width x = tf.reshape(x, [-1, G, C // G, H,",
"def resnet_Add(x1, x2): \"\"\" x1 shape[-1] is small x2 shape[-1] \"\"\" if x1.get_shape().as_list()[3]",
"+ tf.pad(x1, [[0, 0], [0, 0], [0, 0], [0, x2.get_shape().as_list()[3] - x1.get_shape().as_list()[3]]]) else:",
"+ norm_type + 'group_beta', [C], initializer=tf.constant_initializer(0.0)) gama = tf.reshape(gama, [1, C, 1, 1])",
"W = x.get_shape().as_list() G = min(G, C) if H == None and W",
"-init_range, init_range) return tf.Variable(initial, name=variable_name) else: stddev = tf.sqrt(2.0 / (n_inputs + n_outputs))",
"W, output_shape, strides=[1, stride, stride, 1], padding='SAME') # Unet crop and concat def",
"def conv2d(x, W, strides=1): conv_2d = tf.nn.conv2d(x, W, strides=[1, strides, strides, 1], padding='SAME')",
"4 initial = tf.truncated_normal(shape, mean=0.0, stddev=stddev) return tf.Variable(initial, name=variable_name) # Bias initialization def",
"tf.random_uniform(shape, -init_range, init_range) return tf.Variable(initial, name=variable_name) else: stddev = tf.sqrt(2.0 / (n_inputs +",
"stride, 1], padding='SAME') # Unet crop and concat def crop_and_concat(x1, x2): x1_shape =",
"'group': # tranpose:[bs,h,w,c]to[bs,c,h,w]follwing the paper x = tf.transpose(x, [0, 3, 1, 2]) N,",
"Option A:zero-padding residual_connection = x2 + tf.pad(x1, [[0, 0], [0, 0], [0, 0],",
"4 initial = tf.random_uniform(shape, -init_range, init_range) return tf.Variable(initial, name=variable_name) else: stddev = tf.sqrt(2.0",
"stddev = tf.sqrt(2.0 / (n_inputs + n_outputs)) * 4 initial = tf.truncated_normal(shape, mean=0.0,",
"x_shape[3] // stride]) return tf.nn.conv2d_transpose(x, W, output_shape, strides=[1, stride, stride, 1], padding='SAME') #",
"def crop_and_concat(x1, x2): x1_shape = tf.shape(x1) x2_shape = tf.shape(x2) # offsets for the",
"offsets = [0, (x1_shape[1] - x2_shape[1]) // 2, (x1_shape[2] - x2_shape[2]) // 2,",
"shape[-1] \"\"\" if x1.get_shape().as_list()[3] != x2.get_shape().as_list()[3]: # Option A:zero-padding residual_connection = x2 +",
"= tf.contrib.layers.batch_norm(x, center=True, scale=True, is_training=is_train) elif norm_type == 'group': # tranpose:[bs,h,w,c]to[bs,c,h,w]follwing the paper",
"init_range) return tf.Variable(initial, name=variable_name) else: stddev = tf.sqrt(2.0 / (n_inputs + n_outputs)) initial",
"esp) # per channel gama and beta gama = tf.get_variable(scope + norm_type +",
"+ n_outputs)) initial = tf.truncated_normal(shape, mean=0.0, stddev=stddev) return tf.Variable(initial, name=variable_name) elif activefuncation ==",
"+ beta ## tranpose:[bs,c,h,w]to[bs,h,w,c]follwing the paper output = tf.transpose(output, [0, 2, 3, 1])",
"the top left corner of the crop offsets = [0, (x1_shape[1] - x2_shape[1])",
"n_outputs)) * 4 initial = tf.random_uniform(shape, -init_range, init_range) return tf.Variable(initial, name=variable_name) else: stddev",
"of the crop offsets = [0, (x1_shape[1] - x2_shape[1]) // 2, (x1_shape[2] -",
"= tf.get_variable(scope + norm_type + 'group_beta', [C], initializer=tf.constant_initializer(0.0)) gama = tf.reshape(gama, [1, C,",
"is_training=is_train) elif norm_type == 'group': # tranpose:[bs,h,w,c]to[bs,c,h,w]follwing the paper x = tf.transpose(x, [0,",
"normalizationlayer(x, is_train, height=None, width=None, norm_type='None', G=16, esp=1e-5, scope=None): with tf.name_scope(scope + norm_type): if",
"convolution def conv2d(x, W, strides=1): conv_2d = tf.nn.conv2d(x, W, strides=[1, strides, strides, 1],",
"output_shape, strides=[1, stride, stride, 1], padding='SAME') # Unet crop and concat def crop_and_concat(x1,",
"tf.nn.conv2d(x, W, strides=[1, strides, strides, 1], padding='SAME') return conv_2d def normalizationlayer(x, is_train, height=None,",
"offsets, size) return tf.concat([x1_crop, x2], 3) # Resnet add def resnet_Add(x1, x2): \"\"\"",
"norm_type): if norm_type == 'None': output = x elif norm_type == 'batch': output",
"'tan': if uniform: init_range = tf.sqrt(6.0 / (n_inputs + n_outputs)) * 4 initial",
"1, 1]) output = tf.reshape(x, [-1, C, H, W]) * gama + beta",
"height=None, width=None, norm_type='None', G=16, esp=1e-5, scope=None): with tf.name_scope(scope + norm_type): if norm_type ==",
"return tf.Variable(initial, name=variable_name) else: stddev = tf.sqrt(2.0 / (n_inputs + n_outputs)) * 4",
"0], [0, x2.get_shape().as_list()[3] - x1.get_shape().as_list()[3]]]) else: residual_connection = x2 + x1 # residual_connection=tf.add(x1,x2)",
"and beta gama = tf.get_variable(scope + norm_type + 'group_gama', [C], initializer=tf.constant_initializer(1.0)) beta =",
"* np.sqrt(2) initial = tf.truncated_normal(shape, mean=0.0, stddev=stddev) return tf.Variable(initial, name=variable_name) elif activefuncation ==",
"tf.reshape(x, [-1, G, C // G, H, W]) mean, var = tf.nn.moments(x, [2,",
"= tf.truncated_normal(shape, mean=0.0, stddev=stddev) return tf.Variable(initial, name=variable_name) # Bias initialization def bias_variable(shape, variable_name=None):",
"scale=True, is_training=is_train) elif norm_type == 'group': # tranpose:[bs,h,w,c]to[bs,c,h,w]follwing the paper x = tf.transpose(x,",
"= tf.truncated_normal(shape, mean=0.0, stddev=stddev) return tf.Variable(initial, name=variable_name) elif activefuncation == 'relu': if uniform:",
"uniform: init_range = tf.sqrt(6.0 / (n_inputs + n_outputs)) * 4 initial = tf.random_uniform(shape,",
"W, stride=2): x_shape = tf.shape(x) output_shape = tf.stack([x_shape[0], x_shape[1] * stride, x_shape[2] *",
"''' import tensorflow as tf import numpy as np # Weight initialization (Xavier's",
"scope=None): with tf.name_scope(scope + norm_type): if norm_type == 'None': output = x elif",
"Resnet add def resnet_Add(x1, x2): \"\"\" x1 shape[-1] is small x2 shape[-1] \"\"\"",
"initial = tf.truncated_normal(shape, mean=0.0, stddev=stddev) return tf.Variable(initial, name=variable_name) # Bias initialization def bias_variable(shape,",
"'relu': if uniform: init_range = tf.sqrt(6.0 / (n_inputs + n_outputs)) * np.sqrt(2) initial",
"x2): \"\"\" x1 shape[-1] is small x2 shape[-1] \"\"\" if x1.get_shape().as_list()[3] != x2.get_shape().as_list()[3]:",
"n_outputs, activefuncation='sigmoid', uniform=True, variable_name=None): if activefuncation == 'sigmoid': if uniform: init_range = tf.sqrt(6.0",
"[1, C, 1, 1]) output = tf.reshape(x, [-1, C, H, W]) * gama",
"= tf.reshape(x, [-1, C, H, W]) * gama + beta ## tranpose:[bs,c,h,w]to[bs,h,w,c]follwing the",
"norm_type == 'batch': output = tf.contrib.layers.batch_norm(x, center=True, scale=True, is_training=is_train) elif norm_type == 'group':",
"initialization def bias_variable(shape, variable_name=None): initial = tf.constant(0.1, shape=shape) return tf.Variable(initial, name=variable_name) # 2D",
"uniform=True, variable_name=None): if activefuncation == 'sigmoid': if uniform: init_range = tf.sqrt(6.0 / (n_inputs",
"* np.sqrt(2) initial = tf.random_uniform(shape, -init_range, init_range) return tf.Variable(initial, name=variable_name) else: stddev =",
"[[0, 0], [0, 0], [0, 0], [0, x2.get_shape().as_list()[3] - x1.get_shape().as_list()[3]]]) else: residual_connection =",
"tf.sqrt(6.0 / (n_inputs + n_outputs)) * np.sqrt(2) initial = tf.random_uniform(shape, -init_range, init_range) return",
"= tf.sqrt(6.0 / (n_inputs + n_outputs)) * 4 initial = tf.random_uniform(shape, -init_range, init_range)",
"= tf.shape(x2) # offsets for the top left corner of the crop offsets",
"name=variable_name) elif activefuncation == 'tan': if uniform: init_range = tf.sqrt(6.0 / (n_inputs +",
"# Resnet add def resnet_Add(x1, x2): \"\"\" x1 shape[-1] is small x2 shape[-1]",
"name=variable_name) else: stddev = tf.sqrt(2.0 / (n_inputs + n_outputs)) * 4 initial =",
"initial = tf.random_uniform(shape, -init_range, init_range) return tf.Variable(initial, name=variable_name) else: stddev = tf.sqrt(2.0 /",
"3, 1]) return output # 2D deconvolution def deconv2d(x, W, stride=2): x_shape =",
"G, H, W]) mean, var = tf.nn.moments(x, [2, 3, 4], keep_dims=True) x =",
"W]) * gama + beta ## tranpose:[bs,c,h,w]to[bs,h,w,c]follwing the paper output = tf.transpose(output, [0,",
"/ (n_inputs + n_outputs)) initial = tf.random_uniform(shape, -init_range, init_range) return tf.Variable(initial, name=variable_name) else:",
"gama = tf.get_variable(scope + norm_type + 'group_gama', [C], initializer=tf.constant_initializer(1.0)) beta = tf.get_variable(scope +",
"norm_type + 'group_beta', [C], initializer=tf.constant_initializer(0.0)) gama = tf.reshape(gama, [1, C, 1, 1]) beta",
"[0, x2.get_shape().as_list()[3] - x1.get_shape().as_list()[3]]]) else: residual_connection = x2 + x1 # residual_connection=tf.add(x1,x2) return",
"== 'batch': output = tf.contrib.layers.batch_norm(x, center=True, scale=True, is_training=is_train) elif norm_type == 'group': #",
"output_shape = tf.stack([x_shape[0], x_shape[1] * stride, x_shape[2] * stride, x_shape[3] // stride]) return",
"tf.transpose(x, [0, 3, 1, 2]) N, C, H, W = x.get_shape().as_list() G =",
"norm_type='None', G=16, esp=1e-5, scope=None): with tf.name_scope(scope + norm_type): if norm_type == 'None': output",
"strides=[1, strides, strides, 1], padding='SAME') return conv_2d def normalizationlayer(x, is_train, height=None, width=None, norm_type='None',",
"init) def weight_xavier_init(shape, n_inputs, n_outputs, activefuncation='sigmoid', uniform=True, variable_name=None): if activefuncation == 'sigmoid': if",
"x_shape[1] * stride, x_shape[2] * stride, x_shape[3] // stride]) return tf.nn.conv2d_transpose(x, W, output_shape,",
"output # 2D deconvolution def deconv2d(x, W, stride=2): x_shape = tf.shape(x) output_shape =",
"if uniform: init_range = tf.sqrt(6.0 / (n_inputs + n_outputs)) * 4 initial =",
"[-1, C, H, W]) * gama + beta ## tranpose:[bs,c,h,w]to[bs,h,w,c]follwing the paper output",
"= tf.sqrt(2.0 / (n_inputs + n_outputs)) * np.sqrt(2) initial = tf.truncated_normal(shape, mean=0.0, stddev=stddev)",
"+ n_outputs)) initial = tf.random_uniform(shape, -init_range, init_range) return tf.Variable(initial, name=variable_name) else: stddev =",
"n_outputs)) initial = tf.random_uniform(shape, -init_range, init_range) return tf.Variable(initial, name=variable_name) else: stddev = tf.sqrt(2.0",
"return tf.Variable(initial, name=variable_name) elif activefuncation == 'relu': if uniform: init_range = tf.sqrt(6.0 /",
"add def resnet_Add(x1, x2): \"\"\" x1 shape[-1] is small x2 shape[-1] \"\"\" if",
"beta gama = tf.get_variable(scope + norm_type + 'group_gama', [C], initializer=tf.constant_initializer(1.0)) beta = tf.get_variable(scope",
"(x1_shape[1] - x2_shape[1]) // 2, (x1_shape[2] - x2_shape[2]) // 2, 0] size =",
"tf.get_variable(scope + norm_type + 'group_beta', [C], initializer=tf.constant_initializer(0.0)) gama = tf.reshape(gama, [1, C, 1,",
"output = tf.reshape(x, [-1, C, H, W]) * gama + beta ## tranpose:[bs,c,h,w]to[bs,h,w,c]follwing",
"def deconv2d(x, W, stride=2): x_shape = tf.shape(x) output_shape = tf.stack([x_shape[0], x_shape[1] * stride,",
"+ esp) # per channel gama and beta gama = tf.get_variable(scope + norm_type",
"0], [0, 0], [0, x2.get_shape().as_list()[3] - x1.get_shape().as_list()[3]]]) else: residual_connection = x2 + x1",
"padding='SAME') return conv_2d def normalizationlayer(x, is_train, height=None, width=None, norm_type='None', G=16, esp=1e-5, scope=None): with",
"= tf.slice(x1, offsets, size) return tf.concat([x1_crop, x2], 3) # Resnet add def resnet_Add(x1,",
"= tf.transpose(x, [0, 3, 1, 2]) N, C, H, W = x.get_shape().as_list() G",
"# Unet crop and concat def crop_and_concat(x1, x2): x1_shape = tf.shape(x1) x2_shape =",
"mean) / tf.sqrt(var + esp) # per channel gama and beta gama =",
"mean=0.0, stddev=stddev) return tf.Variable(initial, name=variable_name) elif activefuncation == 'relu': if uniform: init_range =",
"tf.transpose(output, [0, 2, 3, 1]) return output # 2D deconvolution def deconv2d(x, W,",
"(n_inputs + n_outputs)) initial = tf.truncated_normal(shape, mean=0.0, stddev=stddev) return tf.Variable(initial, name=variable_name) elif activefuncation",
"G=16, esp=1e-5, scope=None): with tf.name_scope(scope + norm_type): if norm_type == 'None': output =",
"corner of the crop offsets = [0, (x1_shape[1] - x2_shape[1]) // 2, (x1_shape[2]",
"variable_name=None): initial = tf.constant(0.1, shape=shape) return tf.Variable(initial, name=variable_name) # 2D convolution def conv2d(x,",
"tf.sqrt(2.0 / (n_inputs + n_outputs)) initial = tf.truncated_normal(shape, mean=0.0, stddev=stddev) return tf.Variable(initial, name=variable_name)",
"x2.get_shape().as_list()[3] - x1.get_shape().as_list()[3]]]) else: residual_connection = x2 + x1 # residual_connection=tf.add(x1,x2) return residual_connection",
"mean=0.0, stddev=stddev) return tf.Variable(initial, name=variable_name) # Bias initialization def bias_variable(shape, variable_name=None): initial =",
"= tf.nn.conv2d(x, W, strides=[1, strides, strides, 1], padding='SAME') return conv_2d def normalizationlayer(x, is_train,",
"per channel gama and beta gama = tf.get_variable(scope + norm_type + 'group_gama', [C],",
"for the top left corner of the crop offsets = [0, (x1_shape[1] -",
"''' covlution layer,pool layer,initialization。。。。 ''' import tensorflow as tf import numpy as np",
"def weight_xavier_init(shape, n_inputs, n_outputs, activefuncation='sigmoid', uniform=True, variable_name=None): if activefuncation == 'sigmoid': if uniform:",
"is small x2 shape[-1] \"\"\" if x1.get_shape().as_list()[3] != x2.get_shape().as_list()[3]: # Option A:zero-padding residual_connection",
"/ (n_inputs + n_outputs)) initial = tf.truncated_normal(shape, mean=0.0, stddev=stddev) return tf.Variable(initial, name=variable_name) elif",
"small x2 shape[-1] \"\"\" if x1.get_shape().as_list()[3] != x2.get_shape().as_list()[3]: # Option A:zero-padding residual_connection =",
"n_inputs, n_outputs, activefuncation='sigmoid', uniform=True, variable_name=None): if activefuncation == 'sigmoid': if uniform: init_range =",
"norm_type + 'group_gama', [C], initializer=tf.constant_initializer(1.0)) beta = tf.get_variable(scope + norm_type + 'group_beta', [C],",
"[0, (x1_shape[1] - x2_shape[1]) // 2, (x1_shape[2] - x2_shape[2]) // 2, 0] size",
"x2 shape[-1] \"\"\" if x1.get_shape().as_list()[3] != x2.get_shape().as_list()[3]: # Option A:zero-padding residual_connection = x2"
] |
[
"= enc_units # Size of the hidden units present in GRU. self.embedding =",
"self.GRU(inputs, initial_state = hidden) return output, state if __name__ == '__main__': print('oot sssd",
"= tf.keras.layers.GRU(self.enc_units, return_sequences=True, return_state=True, recurrent_initializer='glorot_uniform', kernel_regularizer=tf.keras.regularizers.L2(0.001)) # here GRU (Gated recurrent unit) is",
"= tf.keras.layers.Embedding(vocab_size, embedding) self.GRU = tf.keras.layers.GRU(self.enc_units, return_sequences=True, return_state=True, recurrent_initializer='glorot_uniform', kernel_regularizer=tf.keras.regularizers.L2(0.001)) # here GRU",
"intermediate hidden states of GRU state: final hidden state of GRU \"\"\" def",
"tf class Encoder(tf.keras.Model): def __init__(self, vocab_size, embedding, enc_units, batch_size): super(Encoder, self).__init__() self.batch_size =",
"all intermediate hidden states of GRU state: final hidden state of GRU \"\"\"",
"# Size of the hidden units present in GRU. self.embedding = tf.keras.layers.Embedding(vocab_size, embedding)",
"training data hidden: initial hidden state for GRU output: all intermediate hidden states",
"# here GRU (Gated recurrent unit) is used \"\"\" inputs: initial input from",
"for GRU output: all intermediate hidden states of GRU state: final hidden state",
"the hidden units present in GRU. self.embedding = tf.keras.layers.Embedding(vocab_size, embedding) self.GRU = tf.keras.layers.GRU(self.enc_units,",
"self.batch_size = batch_size self.enc_units = enc_units # Size of the hidden units present",
"output, state = self.GRU(inputs, initial_state = hidden) return output, state if __name__ ==",
"Size of the hidden units present in GRU. self.embedding = tf.keras.layers.Embedding(vocab_size, embedding) self.GRU",
"= self.embedding(inputs) output, state = self.GRU(inputs, initial_state = hidden) return output, state if",
"from training data hidden: initial hidden state for GRU output: all intermediate hidden",
"embedding) self.GRU = tf.keras.layers.GRU(self.enc_units, return_sequences=True, return_state=True, recurrent_initializer='glorot_uniform', kernel_regularizer=tf.keras.regularizers.L2(0.001)) # here GRU (Gated recurrent",
"present in GRU. self.embedding = tf.keras.layers.Embedding(vocab_size, embedding) self.GRU = tf.keras.layers.GRU(self.enc_units, return_sequences=True, return_state=True, recurrent_initializer='glorot_uniform',",
"as tf class Encoder(tf.keras.Model): def __init__(self, vocab_size, embedding, enc_units, batch_size): super(Encoder, self).__init__() self.batch_size",
"inputs = self.embedding(inputs) output, state = self.GRU(inputs, initial_state = hidden) return output, state",
"initial_state = hidden) return output, state if __name__ == '__main__': print('oot sssd enc')",
"inputs: initial input from training data hidden: initial hidden state for GRU output:",
"\"\"\" def call(self, inputs, hidden): inputs = self.embedding(inputs) output, state = self.GRU(inputs, initial_state",
"GRU (Gated recurrent unit) is used \"\"\" inputs: initial input from training data",
"self).__init__() self.batch_size = batch_size self.enc_units = enc_units # Size of the hidden units",
"tf.keras.layers.GRU(self.enc_units, return_sequences=True, return_state=True, recurrent_initializer='glorot_uniform', kernel_regularizer=tf.keras.regularizers.L2(0.001)) # here GRU (Gated recurrent unit) is used",
"GRU. self.embedding = tf.keras.layers.Embedding(vocab_size, embedding) self.GRU = tf.keras.layers.GRU(self.enc_units, return_sequences=True, return_state=True, recurrent_initializer='glorot_uniform', kernel_regularizer=tf.keras.regularizers.L2(0.001)) #",
"initial hidden state for GRU output: all intermediate hidden states of GRU state:",
"of GRU state: final hidden state of GRU \"\"\" def call(self, inputs, hidden):",
"recurrent unit) is used \"\"\" inputs: initial input from training data hidden: initial",
"unit) is used \"\"\" inputs: initial input from training data hidden: initial hidden",
"of the hidden units present in GRU. self.embedding = tf.keras.layers.Embedding(vocab_size, embedding) self.GRU =",
"states of GRU state: final hidden state of GRU \"\"\" def call(self, inputs,",
"used \"\"\" inputs: initial input from training data hidden: initial hidden state for",
"input from training data hidden: initial hidden state for GRU output: all intermediate",
"tensorflow as tf class Encoder(tf.keras.Model): def __init__(self, vocab_size, embedding, enc_units, batch_size): super(Encoder, self).__init__()",
"in GRU. self.embedding = tf.keras.layers.Embedding(vocab_size, embedding) self.GRU = tf.keras.layers.GRU(self.enc_units, return_sequences=True, return_state=True, recurrent_initializer='glorot_uniform', kernel_regularizer=tf.keras.regularizers.L2(0.001))",
"final hidden state of GRU \"\"\" def call(self, inputs, hidden): inputs = self.embedding(inputs)",
"__init__(self, vocab_size, embedding, enc_units, batch_size): super(Encoder, self).__init__() self.batch_size = batch_size self.enc_units = enc_units",
"kernel_regularizer=tf.keras.regularizers.L2(0.001)) # here GRU (Gated recurrent unit) is used \"\"\" inputs: initial input",
"output: all intermediate hidden states of GRU state: final hidden state of GRU",
"self.enc_units = enc_units # Size of the hidden units present in GRU. self.embedding",
"state: final hidden state of GRU \"\"\" def call(self, inputs, hidden): inputs =",
"units present in GRU. self.embedding = tf.keras.layers.Embedding(vocab_size, embedding) self.GRU = tf.keras.layers.GRU(self.enc_units, return_sequences=True, return_state=True,",
"GRU \"\"\" def call(self, inputs, hidden): inputs = self.embedding(inputs) output, state = self.GRU(inputs,",
"return_sequences=True, return_state=True, recurrent_initializer='glorot_uniform', kernel_regularizer=tf.keras.regularizers.L2(0.001)) # here GRU (Gated recurrent unit) is used \"\"\"",
"GRU state: final hidden state of GRU \"\"\" def call(self, inputs, hidden): inputs",
"Encoder(tf.keras.Model): def __init__(self, vocab_size, embedding, enc_units, batch_size): super(Encoder, self).__init__() self.batch_size = batch_size self.enc_units",
"(Gated recurrent unit) is used \"\"\" inputs: initial input from training data hidden:",
"of GRU \"\"\" def call(self, inputs, hidden): inputs = self.embedding(inputs) output, state =",
"is used \"\"\" inputs: initial input from training data hidden: initial hidden state",
"<filename>encoder.py<gh_stars>0 import tensorflow as tf class Encoder(tf.keras.Model): def __init__(self, vocab_size, embedding, enc_units, batch_size):",
"state = self.GRU(inputs, initial_state = hidden) return output, state if __name__ == '__main__':",
"enc_units # Size of the hidden units present in GRU. self.embedding = tf.keras.layers.Embedding(vocab_size,",
"initial input from training data hidden: initial hidden state for GRU output: all",
"super(Encoder, self).__init__() self.batch_size = batch_size self.enc_units = enc_units # Size of the hidden",
"here GRU (Gated recurrent unit) is used \"\"\" inputs: initial input from training",
"= batch_size self.enc_units = enc_units # Size of the hidden units present in",
"self.embedding = tf.keras.layers.Embedding(vocab_size, embedding) self.GRU = tf.keras.layers.GRU(self.enc_units, return_sequences=True, return_state=True, recurrent_initializer='glorot_uniform', kernel_regularizer=tf.keras.regularizers.L2(0.001)) # here",
"recurrent_initializer='glorot_uniform', kernel_regularizer=tf.keras.regularizers.L2(0.001)) # here GRU (Gated recurrent unit) is used \"\"\" inputs: initial",
"enc_units, batch_size): super(Encoder, self).__init__() self.batch_size = batch_size self.enc_units = enc_units # Size of",
"hidden state for GRU output: all intermediate hidden states of GRU state: final",
"= self.GRU(inputs, initial_state = hidden) return output, state if __name__ == '__main__': print('oot",
"\"\"\" inputs: initial input from training data hidden: initial hidden state for GRU",
"self.embedding(inputs) output, state = self.GRU(inputs, initial_state = hidden) return output, state if __name__",
"tf.keras.layers.Embedding(vocab_size, embedding) self.GRU = tf.keras.layers.GRU(self.enc_units, return_sequences=True, return_state=True, recurrent_initializer='glorot_uniform', kernel_regularizer=tf.keras.regularizers.L2(0.001)) # here GRU (Gated",
"hidden): inputs = self.embedding(inputs) output, state = self.GRU(inputs, initial_state = hidden) return output,",
"state for GRU output: all intermediate hidden states of GRU state: final hidden",
"state of GRU \"\"\" def call(self, inputs, hidden): inputs = self.embedding(inputs) output, state",
"hidden state of GRU \"\"\" def call(self, inputs, hidden): inputs = self.embedding(inputs) output,",
"embedding, enc_units, batch_size): super(Encoder, self).__init__() self.batch_size = batch_size self.enc_units = enc_units # Size",
"call(self, inputs, hidden): inputs = self.embedding(inputs) output, state = self.GRU(inputs, initial_state = hidden)",
"def call(self, inputs, hidden): inputs = self.embedding(inputs) output, state = self.GRU(inputs, initial_state =",
"import tensorflow as tf class Encoder(tf.keras.Model): def __init__(self, vocab_size, embedding, enc_units, batch_size): super(Encoder,",
"hidden units present in GRU. self.embedding = tf.keras.layers.Embedding(vocab_size, embedding) self.GRU = tf.keras.layers.GRU(self.enc_units, return_sequences=True,",
"return_state=True, recurrent_initializer='glorot_uniform', kernel_regularizer=tf.keras.regularizers.L2(0.001)) # here GRU (Gated recurrent unit) is used \"\"\" inputs:",
"batch_size): super(Encoder, self).__init__() self.batch_size = batch_size self.enc_units = enc_units # Size of the",
"hidden states of GRU state: final hidden state of GRU \"\"\" def call(self,",
"inputs, hidden): inputs = self.embedding(inputs) output, state = self.GRU(inputs, initial_state = hidden) return",
"batch_size self.enc_units = enc_units # Size of the hidden units present in GRU.",
"data hidden: initial hidden state for GRU output: all intermediate hidden states of",
"self.GRU = tf.keras.layers.GRU(self.enc_units, return_sequences=True, return_state=True, recurrent_initializer='glorot_uniform', kernel_regularizer=tf.keras.regularizers.L2(0.001)) # here GRU (Gated recurrent unit)",
"class Encoder(tf.keras.Model): def __init__(self, vocab_size, embedding, enc_units, batch_size): super(Encoder, self).__init__() self.batch_size = batch_size",
"def __init__(self, vocab_size, embedding, enc_units, batch_size): super(Encoder, self).__init__() self.batch_size = batch_size self.enc_units =",
"GRU output: all intermediate hidden states of GRU state: final hidden state of",
"hidden: initial hidden state for GRU output: all intermediate hidden states of GRU",
"vocab_size, embedding, enc_units, batch_size): super(Encoder, self).__init__() self.batch_size = batch_size self.enc_units = enc_units #"
] |
[
"the other instances of formatting strings used variables that were not # strings.",
"= \"don't\" y = f\"Those who know {binary} and those who {do_not}.\" hilarious",
"used in a formatted string # recreate the variables from ex6 types_of_people =",
"= f\"Those who know {binary} and those who {do_not}.\" hilarious = False #",
"{do_not}.\" hilarious = False # print type of each variable print(\"types_of_people:\", type(types_of_people)) print(\"x:\",",
"use the function type to print out the # type of each variable",
"out the # type of each variable used in a formatted string #",
"recreate the variables from ex6 types_of_people = 10 x = f\"There are {types_of_people}",
"a formatted string # recreate the variables from ex6 types_of_people = 10 x",
"= \"binary\" do_not = \"don't\" y = f\"Those who know {binary} and those",
"{types_of_people} type of people.\" binary = \"binary\" do_not = \"don't\" y = f\"Those",
"do_not = \"don't\" y = f\"Those who know {binary} and those who {do_not}.\"",
"To prove it, I'll use the function type to print out the #",
"know {binary} and those who {do_not}.\" hilarious = False # print type of",
"instances of formatting strings used variables that were not # strings. To prove",
"of people.\" binary = \"binary\" do_not = \"don't\" y = f\"Those who know",
"y = f\"Those who know {binary} and those who {do_not}.\" hilarious = False",
"other instances of formatting strings used variables that were not # strings. To",
"type of each variable used in a formatted string # recreate the variables",
"\"don't\" y = f\"Those who know {binary} and those who {do_not}.\" hilarious =",
"function type to print out the # type of each variable used in",
"binary = \"binary\" do_not = \"don't\" y = f\"Those who know {binary} and",
"hilarious = False # print type of each variable print(\"types_of_people:\", type(types_of_people)) print(\"x:\", type(x))",
"I'll use the function type to print out the # type of each",
"the variables from ex6 types_of_people = 10 x = f\"There are {types_of_people} type",
"{binary} and those who {do_not}.\" hilarious = False # print type of each",
"each variable used in a formatted string # recreate the variables from ex6",
"print out the # type of each variable used in a formatted string",
"variables that were not # strings. To prove it, I'll use the function",
"of formatting strings used variables that were not # strings. To prove it,",
"who {do_not}.\" hilarious = False # print type of each variable print(\"types_of_people:\", type(types_of_people))",
"prove it, I'll use the function type to print out the # type",
"the function type to print out the # type of each variable used",
"each variable print(\"types_of_people:\", type(types_of_people)) print(\"x:\", type(x)) print(\"binary:\", type(binary)) print(\"do_not:\", type(do_not)) print(\"y:\", type(y)) print(\"hilarious:\",",
"f\"Those who know {binary} and those who {do_not}.\" hilarious = False # print",
"= 10 x = f\"There are {types_of_people} type of people.\" binary = \"binary\"",
"formatting strings used variables that were not # strings. To prove it, I'll",
"<reponame>jlaw8504/lp3thw # the other instances of formatting strings used variables that were not",
"= f\"There are {types_of_people} type of people.\" binary = \"binary\" do_not = \"don't\"",
"are {types_of_people} type of people.\" binary = \"binary\" do_not = \"don't\" y =",
"# recreate the variables from ex6 types_of_people = 10 x = f\"There are",
"not # strings. To prove it, I'll use the function type to print",
"\"binary\" do_not = \"don't\" y = f\"Those who know {binary} and those who",
"# print type of each variable print(\"types_of_people:\", type(types_of_people)) print(\"x:\", type(x)) print(\"binary:\", type(binary)) print(\"do_not:\",",
"in a formatted string # recreate the variables from ex6 types_of_people = 10",
"# the other instances of formatting strings used variables that were not #",
"it, I'll use the function type to print out the # type of",
"# strings. To prove it, I'll use the function type to print out",
"strings. To prove it, I'll use the function type to print out the",
"# type of each variable used in a formatted string # recreate the",
"= False # print type of each variable print(\"types_of_people:\", type(types_of_people)) print(\"x:\", type(x)) print(\"binary:\",",
"to print out the # type of each variable used in a formatted",
"the # type of each variable used in a formatted string # recreate",
"of each variable print(\"types_of_people:\", type(types_of_people)) print(\"x:\", type(x)) print(\"binary:\", type(binary)) print(\"do_not:\", type(do_not)) print(\"y:\", type(y))",
"that were not # strings. To prove it, I'll use the function type",
"from ex6 types_of_people = 10 x = f\"There are {types_of_people} type of people.\"",
"variable used in a formatted string # recreate the variables from ex6 types_of_people",
"those who {do_not}.\" hilarious = False # print type of each variable print(\"types_of_people:\",",
"and those who {do_not}.\" hilarious = False # print type of each variable",
"f\"There are {types_of_people} type of people.\" binary = \"binary\" do_not = \"don't\" y",
"string # recreate the variables from ex6 types_of_people = 10 x = f\"There",
"types_of_people = 10 x = f\"There are {types_of_people} type of people.\" binary =",
"x = f\"There are {types_of_people} type of people.\" binary = \"binary\" do_not =",
"type of each variable print(\"types_of_people:\", type(types_of_people)) print(\"x:\", type(x)) print(\"binary:\", type(binary)) print(\"do_not:\", type(do_not)) print(\"y:\",",
"of each variable used in a formatted string # recreate the variables from",
"10 x = f\"There are {types_of_people} type of people.\" binary = \"binary\" do_not",
"strings used variables that were not # strings. To prove it, I'll use",
"ex6 types_of_people = 10 x = f\"There are {types_of_people} type of people.\" binary",
"were not # strings. To prove it, I'll use the function type to",
"used variables that were not # strings. To prove it, I'll use the",
"who know {binary} and those who {do_not}.\" hilarious = False # print type",
"print type of each variable print(\"types_of_people:\", type(types_of_people)) print(\"x:\", type(x)) print(\"binary:\", type(binary)) print(\"do_not:\", type(do_not))",
"False # print type of each variable print(\"types_of_people:\", type(types_of_people)) print(\"x:\", type(x)) print(\"binary:\", type(binary))",
"variable print(\"types_of_people:\", type(types_of_people)) print(\"x:\", type(x)) print(\"binary:\", type(binary)) print(\"do_not:\", type(do_not)) print(\"y:\", type(y)) print(\"hilarious:\", type(hilarious))",
"type to print out the # type of each variable used in a",
"variables from ex6 types_of_people = 10 x = f\"There are {types_of_people} type of",
"people.\" binary = \"binary\" do_not = \"don't\" y = f\"Those who know {binary}",
"formatted string # recreate the variables from ex6 types_of_people = 10 x =",
"type of people.\" binary = \"binary\" do_not = \"don't\" y = f\"Those who"
] |
[
"this name? self.pointer = point # points to a linked list in adjacency",
"to a linked list in adjacency list self.rep = rep # string representation",
"= destination self.weight = weight self.capacity = capacity self.name = x self.flow =",
"return self.destination if vertex is self.origin else self.origin def to_string(self, ends_vertex_obs = False):",
"- should be speific for use \"\"\" class Vertex: def __init__(self, x=None, point=None,",
"self.index = x # made this because I didn't want to refactor to",
"to change .name to .index everywhere. class Edge: def __init__(self, origin, destination, x=None,",
"Edge: def __init__(self, origin, destination, x=None, weight=None, capacity=None, flow=None, residual_capacity=None, residual_flow=None): self.origin =",
"weight=None, capacity=None, flow=None, residual_capacity=None, residual_flow=None): self.origin = origin self.destination = destination self.weight =",
"flow=None, residual_capacity=None, residual_flow=None): self.origin = origin self.destination = destination self.weight = weight self.capacity",
"if vertex is self.origin else self.origin def to_string(self, ends_vertex_obs = False): if ends_vertex_obs:",
"\"og: \" + str(self.origin.name) + \" to: \" + str(self.destination.name) return \"og: \"",
"change .name to .index everywhere. class Edge: def __init__(self, origin, destination, x=None, weight=None,",
"def __init__(self, origin, destination, x=None, weight=None, capacity=None, flow=None, residual_capacity=None, residual_flow=None): self.origin = origin",
"point=None, rep=None): self.name = x # integer 'name' or index....why did I call",
"'name' or index....why did I call this name? self.pointer = point # points",
"def __init__(self, x=None, point=None, rep=None): self.name = x # integer 'name' or index....why",
"be honest - should be speific for use \"\"\" class Vertex: def __init__(self,",
"self.origin else self.origin def to_string(self, ends_vertex_obs = False): if ends_vertex_obs: return \"og: \"",
"= x # made this because I didn't want to refactor to change",
"x self.flow = flow self.residual_capacity = residual_capacity self.residual_flow = residual_flow def get_endpoints(self): return",
"self.destination if vertex is self.origin else self.origin def to_string(self, ends_vertex_obs = False): if",
"self.residual_capacity = residual_capacity self.residual_flow = residual_flow def get_endpoints(self): return self.origin, self.destination def get_opposite(self,",
"__init__(self, origin, destination, x=None, weight=None, capacity=None, flow=None, residual_capacity=None, residual_flow=None): self.origin = origin self.destination",
"\" + str(self.origin.name) + \" to: \" + str(self.destination.name) return \"og: \" +",
"that is opposite v on this edge\"\"\" return self.destination if vertex is self.origin",
"self.weight = weight self.capacity = capacity self.name = x self.flow = flow self.residual_capacity",
"+ str(self.origin.name) + \" to: \" + str(self.destination.name) return \"og: \" + str(self.origin)",
"did I call this name? self.pointer = point # points to a linked",
"= False): if ends_vertex_obs: return \"og: \" + str(self.origin.name) + \" to: \"",
"self.residual_flow = residual_flow def get_endpoints(self): return self.origin, self.destination def get_opposite(self, vertex): \"\"\"Return the",
"I call this name? self.pointer = point # points to a linked list",
"# points to a linked list in adjacency list self.rep = rep #",
"to refactor to change .name to .index everywhere. class Edge: def __init__(self, origin,",
"index....why did I call this name? self.pointer = point # points to a",
"flow self.residual_capacity = residual_capacity self.residual_flow = residual_flow def get_endpoints(self): return self.origin, self.destination def",
"in adjacency list self.rep = rep # string representation self.distance = None self.index",
"= rep # string representation self.distance = None self.index = x # made",
"# made this because I didn't want to refactor to change .name to",
"x=None, point=None, rep=None): self.name = x # integer 'name' or index....why did I",
"destination self.weight = weight self.capacity = capacity self.name = x self.flow = flow",
"get_opposite(self, vertex): \"\"\"Return the vertex that is opposite v on this edge\"\"\" return",
"didn't want to refactor to change .name to .index everywhere. class Edge: def",
"str(self.origin.name) + \" to: \" + str(self.destination.name) return \"og: \" + str(self.origin) +",
"integer 'name' or index....why did I call this name? self.pointer = point #",
"= origin self.destination = destination self.weight = weight self.capacity = capacity self.name =",
"is opposite v on this edge\"\"\" return self.destination if vertex is self.origin else",
"self.origin, self.destination def get_opposite(self, vertex): \"\"\"Return the vertex that is opposite v on",
"generic too be honest - should be speific for use \"\"\" class Vertex:",
"def get_endpoints(self): return self.origin, self.destination def get_opposite(self, vertex): \"\"\"Return the vertex that is",
"ends_vertex_obs: return \"og: \" + str(self.origin.name) + \" to: \" + str(self.destination.name) return",
"= None self.index = x # made this because I didn't want to",
"too generic too be honest - should be speific for use \"\"\" class",
"class Edge: def __init__(self, origin, destination, x=None, weight=None, capacity=None, flow=None, residual_capacity=None, residual_flow=None): self.origin",
"self.distance = None self.index = x # made this because I didn't want",
"edge\"\"\" return self.destination if vertex is self.origin else self.origin def to_string(self, ends_vertex_obs =",
"honest - should be speific for use \"\"\" class Vertex: def __init__(self, x=None,",
"list self.rep = rep # string representation self.distance = None self.index = x",
"or index....why did I call this name? self.pointer = point # points to",
"- a bit too generic too be honest - should be speific for",
"vertex that is opposite v on this edge\"\"\" return self.destination if vertex is",
"origin, destination, x=None, weight=None, capacity=None, flow=None, residual_capacity=None, residual_flow=None): self.origin = origin self.destination =",
"self.destination def get_opposite(self, vertex): \"\"\"Return the vertex that is opposite v on this",
"bit too generic too be honest - should be speific for use \"\"\"",
"\" + str(self.destination.name) return \"og: \" + str(self.origin) + \" to: \" +",
"= flow self.residual_capacity = residual_capacity self.residual_flow = residual_flow def get_endpoints(self): return self.origin, self.destination",
"is self.origin else self.origin def to_string(self, ends_vertex_obs = False): if ends_vertex_obs: return \"og:",
"residual_capacity self.residual_flow = residual_flow def get_endpoints(self): return self.origin, self.destination def get_opposite(self, vertex): \"\"\"Return",
"use \"\"\" class Vertex: def __init__(self, x=None, point=None, rep=None): self.name = x #",
"else self.origin def to_string(self, ends_vertex_obs = False): if ends_vertex_obs: return \"og: \" +",
"rep # string representation self.distance = None self.index = x # made this",
"too be honest - should be speific for use \"\"\" class Vertex: def",
"23/08/2016 @modified: Based Vertex and Edge clases - a bit too generic too",
"list in adjacency list self.rep = rep # string representation self.distance = None",
"on this edge\"\"\" return self.destination if vertex is self.origin else self.origin def to_string(self,",
"if ends_vertex_obs: return \"og: \" + str(self.origin.name) + \" to: \" + str(self.destination.name)",
"# string representation self.distance = None self.index = x # made this because",
"x=None, weight=None, capacity=None, flow=None, residual_capacity=None, residual_flow=None): self.origin = origin self.destination = destination self.weight",
"self.name = x # integer 'name' or index....why did I call this name?",
"\"\"\"Return the vertex that is opposite v on this edge\"\"\" return self.destination if",
"capacity self.name = x self.flow = flow self.residual_capacity = residual_capacity self.residual_flow = residual_flow",
"= residual_capacity self.residual_flow = residual_flow def get_endpoints(self): return self.origin, self.destination def get_opposite(self, vertex):",
"representation self.distance = None self.index = x # made this because I didn't",
".index everywhere. class Edge: def __init__(self, origin, destination, x=None, weight=None, capacity=None, flow=None, residual_capacity=None,",
".name to .index everywhere. class Edge: def __init__(self, origin, destination, x=None, weight=None, capacity=None,",
"x # made this because I didn't want to refactor to change .name",
"self.flow = flow self.residual_capacity = residual_capacity self.residual_flow = residual_flow def get_endpoints(self): return self.origin,",
"= residual_flow def get_endpoints(self): return self.origin, self.destination def get_opposite(self, vertex): \"\"\"Return the vertex",
"def get_opposite(self, vertex): \"\"\"Return the vertex that is opposite v on this edge\"\"\"",
"residual_flow=None): self.origin = origin self.destination = destination self.weight = weight self.capacity = capacity",
"opposite v on this edge\"\"\" return self.destination if vertex is self.origin else self.origin",
"+ \" to: \" + str(self.destination.name) return \"og: \" + str(self.origin) + \"",
"self.destination = destination self.weight = weight self.capacity = capacity self.name = x self.flow",
"string representation self.distance = None self.index = x # made this because I",
"I didn't want to refactor to change .name to .index everywhere. class Edge:",
"clases - a bit too generic too be honest - should be speific",
"@since: 23/08/2016 @modified: Based Vertex and Edge clases - a bit too generic",
"should be speific for use \"\"\" class Vertex: def __init__(self, x=None, point=None, rep=None):",
"points to a linked list in adjacency list self.rep = rep # string",
"Vertex and Edge clases - a bit too generic too be honest -",
"get_endpoints(self): return self.origin, self.destination def get_opposite(self, vertex): \"\"\"Return the vertex that is opposite",
"vertex is self.origin else self.origin def to_string(self, ends_vertex_obs = False): if ends_vertex_obs: return",
"None self.index = x # made this because I didn't want to refactor",
"to: \" + str(self.destination.name) return \"og: \" + str(self.origin) + \" to: \"",
"self.name = x self.flow = flow self.residual_capacity = residual_capacity self.residual_flow = residual_flow def",
"refactor to change .name to .index everywhere. class Edge: def __init__(self, origin, destination,",
"capacity=None, flow=None, residual_capacity=None, residual_flow=None): self.origin = origin self.destination = destination self.weight = weight",
"self.origin def to_string(self, ends_vertex_obs = False): if ends_vertex_obs: return \"og: \" + str(self.origin.name)",
"@author: <NAME> @since: 23/08/2016 @modified: Based Vertex and Edge clases - a bit",
"# integer 'name' or index....why did I call this name? self.pointer = point",
"Based Vertex and Edge clases - a bit too generic too be honest",
"residual_flow def get_endpoints(self): return self.origin, self.destination def get_opposite(self, vertex): \"\"\"Return the vertex that",
"origin self.destination = destination self.weight = weight self.capacity = capacity self.name = x",
"residual_capacity=None, residual_flow=None): self.origin = origin self.destination = destination self.weight = weight self.capacity =",
"@modified: Based Vertex and Edge clases - a bit too generic too be",
"because I didn't want to refactor to change .name to .index everywhere. class",
"linked list in adjacency list self.rep = rep # string representation self.distance =",
"def to_string(self, ends_vertex_obs = False): if ends_vertex_obs: return \"og: \" + str(self.origin.name) +",
"Vertex: def __init__(self, x=None, point=None, rep=None): self.name = x # integer 'name' or",
"\"\"\" class Vertex: def __init__(self, x=None, point=None, rep=None): self.name = x # integer",
"__init__(self, x=None, point=None, rep=None): self.name = x # integer 'name' or index....why did",
"weight self.capacity = capacity self.name = x self.flow = flow self.residual_capacity = residual_capacity",
"to_string(self, ends_vertex_obs = False): if ends_vertex_obs: return \"og: \" + str(self.origin.name) + \"",
"class Vertex: def __init__(self, x=None, point=None, rep=None): self.name = x # integer 'name'",
"\"\"\" @author: <NAME> @since: 23/08/2016 @modified: Based Vertex and Edge clases - a",
"destination, x=None, weight=None, capacity=None, flow=None, residual_capacity=None, residual_flow=None): self.origin = origin self.destination = destination",
"= capacity self.name = x self.flow = flow self.residual_capacity = residual_capacity self.residual_flow =",
"this edge\"\"\" return self.destination if vertex is self.origin else self.origin def to_string(self, ends_vertex_obs",
"for use \"\"\" class Vertex: def __init__(self, x=None, point=None, rep=None): self.name = x",
"return self.origin, self.destination def get_opposite(self, vertex): \"\"\"Return the vertex that is opposite v",
"x # integer 'name' or index....why did I call this name? self.pointer =",
"adjacency list self.rep = rep # string representation self.distance = None self.index =",
"and Edge clases - a bit too generic too be honest - should",
"= point # points to a linked list in adjacency list self.rep =",
"self.capacity = capacity self.name = x self.flow = flow self.residual_capacity = residual_capacity self.residual_flow",
"the vertex that is opposite v on this edge\"\"\" return self.destination if vertex",
"\" to: \" + str(self.destination.name) return \"og: \" + str(self.origin) + \" to:",
"call this name? self.pointer = point # points to a linked list in",
"this because I didn't want to refactor to change .name to .index everywhere.",
"speific for use \"\"\" class Vertex: def __init__(self, x=None, point=None, rep=None): self.name =",
"self.pointer = point # points to a linked list in adjacency list self.rep",
"want to refactor to change .name to .index everywhere. class Edge: def __init__(self,",
"self.rep = rep # string representation self.distance = None self.index = x #",
"everywhere. class Edge: def __init__(self, origin, destination, x=None, weight=None, capacity=None, flow=None, residual_capacity=None, residual_flow=None):",
"ends_vertex_obs = False): if ends_vertex_obs: return \"og: \" + str(self.origin.name) + \" to:",
"made this because I didn't want to refactor to change .name to .index",
"+ str(self.destination.name) return \"og: \" + str(self.origin) + \" to: \" + str(self.destination)",
"name? self.pointer = point # points to a linked list in adjacency list",
"= x # integer 'name' or index....why did I call this name? self.pointer",
"Edge clases - a bit too generic too be honest - should be",
"<reponame>vaishnavprachi98/technical-interviews<filename>algorithms_datastructures/graphs/implementations/structures.py \"\"\" @author: <NAME> @since: 23/08/2016 @modified: Based Vertex and Edge clases -",
"a linked list in adjacency list self.rep = rep # string representation self.distance",
"return \"og: \" + str(self.origin.name) + \" to: \" + str(self.destination.name) return \"og:",
"= weight self.capacity = capacity self.name = x self.flow = flow self.residual_capacity =",
"v on this edge\"\"\" return self.destination if vertex is self.origin else self.origin def",
"= x self.flow = flow self.residual_capacity = residual_capacity self.residual_flow = residual_flow def get_endpoints(self):",
"be speific for use \"\"\" class Vertex: def __init__(self, x=None, point=None, rep=None): self.name",
"a bit too generic too be honest - should be speific for use",
"point # points to a linked list in adjacency list self.rep = rep",
"vertex): \"\"\"Return the vertex that is opposite v on this edge\"\"\" return self.destination",
"self.origin = origin self.destination = destination self.weight = weight self.capacity = capacity self.name",
"rep=None): self.name = x # integer 'name' or index....why did I call this",
"<NAME> @since: 23/08/2016 @modified: Based Vertex and Edge clases - a bit too",
"False): if ends_vertex_obs: return \"og: \" + str(self.origin.name) + \" to: \" +",
"to .index everywhere. class Edge: def __init__(self, origin, destination, x=None, weight=None, capacity=None, flow=None,"
] |
[
"os.makedirs(args.output, exist_ok=True) output_filename = os.path.join(args.output, 'nyc-taxi-fare.pkl') pickle.dump(clf, open(output_filename, 'wb')) print('Model file nyc-taxi-fare.pkl saved!')",
"OneHotEncoder from sklearn_pandas import DataFrameMapper from sklearn.metrics import mean_squared_error print(\"In train.py\") print(\"As a",
"numerical = ['vendorID', 'passengerCount', 'tripDistance', 'day_of_month', 'month_num', 'snowDepth', 'precipTime', 'precipDepth', 'temperature'] numeric_transformations =",
"engineered features: # hour_sine, hour_cosine, day_of_week_sine, day_of_week_cosine categorical = ['normalizeHolidayName', 'isPaidTimeOff'] numerical =",
"f in numerical] categorical_transformations = [([f], OneHotEncoder(handle_unknown='ignore', sparse=False)) for f in categorical] transformations",
"SimpleImputer(strategy='median')), ('scaler', StandardScaler())])) for f in numerical] categorical_transformations = [([f], OneHotEncoder(handle_unknown='ignore', sparse=False)) for",
"# df_out will return a data frame, and default = None will pass",
"is None): os.makedirs(args.output, exist_ok=True) output_filename = os.path.join(args.output, 'nyc-taxi-fare.pkl') pickle.dump(clf, open(output_filename, 'wb')) print('Model file",
"this is where I write my training code.\") parser = argparse.ArgumentParser(\"train\") parser.add_argument(\"--input\", type=str,",
"1: %s\" % args.input) print(\"Argument 2: %s\" % args.output) # Load your processed",
"= ['vendorID', 'passengerCount', 'tripDistance', 'day_of_month', 'month_num', 'snowDepth', 'precipTime', 'precipDepth', 'temperature'] numeric_transformations = [([f],",
"clf = Pipeline(steps=[('preprocessor', mapper), ('regressor', GradientBoostingRegressor())]) clf.fit(X_train, y_train) y_predict = clf.predict(X_test) y_actual =",
"engineered features unchanged mapper = DataFrameMapper(transformations, input_df=True, df_out=True, default=None, sparse=False) clf = Pipeline(steps=[('preprocessor',",
"sklearn.metrics import mean_squared_error print(\"In train.py\") print(\"As a data scientist, this is where I",
"SimpleImputer from sklearn.preprocessing import StandardScaler, OneHotEncoder from sklearn_pandas import DataFrameMapper from sklearn.metrics import",
"clf.fit(X_train, y_train) y_predict = clf.predict(X_test) y_actual = y_test.values.flatten().tolist() rmse = math.sqrt(mean_squared_error(y_actual, y_predict)) print('The",
"the model if not (args.output is None): os.makedirs(args.output, exist_ok=True) output_filename = os.path.join(args.output, 'nyc-taxi-fare.pkl')",
"import DataFrameMapper from sklearn.metrics import mean_squared_error print(\"In train.py\") print(\"As a data scientist, this",
"pandas as pd import numpy as np import math import pickle from sklearn.model_selection",
"mapper), ('regressor', GradientBoostingRegressor())]) clf.fit(X_train, y_train) y_predict = clf.predict(X_test) y_actual = y_test.values.flatten().tolist() rmse =",
"pd import numpy as np import math import pickle from sklearn.model_selection import train_test_split",
"y_df = df['totalAmount'] X_train, X_test, y_train, y_test = train_test_split(x_df, y_df, test_size=0.2, random_state=0) #",
"for f in numerical] categorical_transformations = [([f], OneHotEncoder(handle_unknown='ignore', sparse=False)) for f in categorical]",
"'month_num', 'snowDepth', 'precipTime', 'precipDepth', 'temperature'] numeric_transformations = [([f], Pipeline(steps=[ ('imputer', SimpleImputer(strategy='median')), ('scaler', StandardScaler())]))",
"args = parser.parse_args() print(\"Argument 1: %s\" % args.input) print(\"Argument 2: %s\" % args.output)",
"is where I write my training code.\") parser = argparse.ArgumentParser(\"train\") parser.add_argument(\"--input\", type=str, help=\"input",
"score on test data for GradientBoostingRegressor: ', rmse) # Save the model if",
"Pipeline from sklearn.impute import SimpleImputer from sklearn.preprocessing import StandardScaler, OneHotEncoder from sklearn_pandas import",
"import GradientBoostingRegressor from sklearn.pipeline import Pipeline from sklearn.impute import SimpleImputer from sklearn.preprocessing import",
"we will not transform / scale the four engineered features: # hour_sine, hour_cosine,",
"import train_test_split from sklearn.ensemble import GradientBoostingRegressor from sklearn.pipeline import Pipeline from sklearn.impute import",
"rmse) # Save the model if not (args.output is None): os.makedirs(args.output, exist_ok=True) output_filename",
"input_df=True, df_out=True, default=None, sparse=False) clf = Pipeline(steps=[('preprocessor', mapper), ('regressor', GradientBoostingRegressor())]) clf.fit(X_train, y_train) y_predict",
"transformations = numeric_transformations + categorical_transformations # df_out will return a data frame, and",
"help=\"input directory\", dest=\"input\", required=True) parser.add_argument(\"--output\", type=str, help=\"output directory\", dest=\"output\", required=True) args = parser.parse_args()",
"import numpy as np import math import pickle from sklearn.model_selection import train_test_split from",
"X_train, X_test, y_train, y_test = train_test_split(x_df, y_df, test_size=0.2, random_state=0) # we will not",
"return a data frame, and default = None will pass the engineered features",
"print(\"Argument 2: %s\" % args.output) # Load your processed features and outputs df",
"None will pass the engineered features unchanged mapper = DataFrameMapper(transformations, input_df=True, df_out=True, default=None,",
"RMSE score on test data for GradientBoostingRegressor: ', rmse) # Save the model",
"print(\"Argument 1: %s\" % args.input) print(\"Argument 2: %s\" % args.output) # Load your",
"print('The RMSE score on test data for GradientBoostingRegressor: ', rmse) # Save the",
"rmse = math.sqrt(mean_squared_error(y_actual, y_predict)) print('The RMSE score on test data for GradientBoostingRegressor: ',",
"('imputer', SimpleImputer(strategy='median')), ('scaler', StandardScaler())])) for f in numerical] categorical_transformations = [([f], OneHotEncoder(handle_unknown='ignore', sparse=False))",
"= None will pass the engineered features unchanged mapper = DataFrameMapper(transformations, input_df=True, df_out=True,",
"help=\"output directory\", dest=\"output\", required=True) args = parser.parse_args() print(\"Argument 1: %s\" % args.input) print(\"Argument",
"# hour_sine, hour_cosine, day_of_week_sine, day_of_week_cosine categorical = ['normalizeHolidayName', 'isPaidTimeOff'] numerical = ['vendorID', 'passengerCount',",
"= clf.predict(X_test) y_actual = y_test.values.flatten().tolist() rmse = math.sqrt(mean_squared_error(y_actual, y_predict)) print('The RMSE score on",
"%s\" % args.input) print(\"Argument 2: %s\" % args.output) # Load your processed features",
"'isPaidTimeOff'] numerical = ['vendorID', 'passengerCount', 'tripDistance', 'day_of_month', 'month_num', 'snowDepth', 'precipTime', 'precipDepth', 'temperature'] numeric_transformations",
"'tripDistance', 'day_of_month', 'month_num', 'snowDepth', 'precipTime', 'precipDepth', 'temperature'] numeric_transformations = [([f], Pipeline(steps=[ ('imputer', SimpleImputer(strategy='median')),",
"numeric_transformations + categorical_transformations # df_out will return a data frame, and default =",
"and default = None will pass the engineered features unchanged mapper = DataFrameMapper(transformations,",
"sklearn.pipeline import Pipeline from sklearn.impute import SimpleImputer from sklearn.preprocessing import StandardScaler, OneHotEncoder from",
"np import math import pickle from sklearn.model_selection import train_test_split from sklearn.ensemble import GradientBoostingRegressor",
"df_out will return a data frame, and default = None will pass the",
"where I write my training code.\") parser = argparse.ArgumentParser(\"train\") parser.add_argument(\"--input\", type=str, help=\"input directory\",",
"argparse import os import pandas as pd import numpy as np import math",
"pass the engineered features unchanged mapper = DataFrameMapper(transformations, input_df=True, df_out=True, default=None, sparse=False) clf",
"import mean_squared_error print(\"In train.py\") print(\"As a data scientist, this is where I write",
"y_predict = clf.predict(X_test) y_actual = y_test.values.flatten().tolist() rmse = math.sqrt(mean_squared_error(y_actual, y_predict)) print('The RMSE score",
"# we will not transform / scale the four engineered features: # hour_sine,",
"dest=\"output\", required=True) args = parser.parse_args() print(\"Argument 1: %s\" % args.input) print(\"Argument 2: %s\"",
"from sklearn.ensemble import GradientBoostingRegressor from sklearn.pipeline import Pipeline from sklearn.impute import SimpleImputer from",
"axis=1) y_df = df['totalAmount'] X_train, X_test, y_train, y_test = train_test_split(x_df, y_df, test_size=0.2, random_state=0)",
"from sklearn.metrics import mean_squared_error print(\"In train.py\") print(\"As a data scientist, this is where",
"processed features and outputs df = pd.read_csv(os.path.join(args.input, 'nyc-taxi-processed-data.csv')) x_df = df.drop(['totalAmount'], axis=1) y_df",
"for f in categorical] transformations = numeric_transformations + categorical_transformations # df_out will return",
"in categorical] transformations = numeric_transformations + categorical_transformations # df_out will return a data",
"import pandas as pd import numpy as np import math import pickle from",
"sklearn.preprocessing import StandardScaler, OneHotEncoder from sklearn_pandas import DataFrameMapper from sklearn.metrics import mean_squared_error print(\"In",
"y_train) y_predict = clf.predict(X_test) y_actual = y_test.values.flatten().tolist() rmse = math.sqrt(mean_squared_error(y_actual, y_predict)) print('The RMSE",
"import math import pickle from sklearn.model_selection import train_test_split from sklearn.ensemble import GradientBoostingRegressor from",
"train.py\") print(\"As a data scientist, this is where I write my training code.\")",
"categorical = ['normalizeHolidayName', 'isPaidTimeOff'] numerical = ['vendorID', 'passengerCount', 'tripDistance', 'day_of_month', 'month_num', 'snowDepth', 'precipTime',",
"= numeric_transformations + categorical_transformations # df_out will return a data frame, and default",
"GradientBoostingRegressor: ', rmse) # Save the model if not (args.output is None): os.makedirs(args.output,",
"write my training code.\") parser = argparse.ArgumentParser(\"train\") parser.add_argument(\"--input\", type=str, help=\"input directory\", dest=\"input\", required=True)",
"# Load your processed features and outputs df = pd.read_csv(os.path.join(args.input, 'nyc-taxi-processed-data.csv')) x_df =",
"StandardScaler, OneHotEncoder from sklearn_pandas import DataFrameMapper from sklearn.metrics import mean_squared_error print(\"In train.py\") print(\"As",
"required=True) args = parser.parse_args() print(\"Argument 1: %s\" % args.input) print(\"Argument 2: %s\" %",
"'precipTime', 'precipDepth', 'temperature'] numeric_transformations = [([f], Pipeline(steps=[ ('imputer', SimpleImputer(strategy='median')), ('scaler', StandardScaler())])) for f",
"from sklearn.impute import SimpleImputer from sklearn.preprocessing import StandardScaler, OneHotEncoder from sklearn_pandas import DataFrameMapper",
"y_df, test_size=0.2, random_state=0) # we will not transform / scale the four engineered",
"/ scale the four engineered features: # hour_sine, hour_cosine, day_of_week_sine, day_of_week_cosine categorical =",
"% args.output) # Load your processed features and outputs df = pd.read_csv(os.path.join(args.input, 'nyc-taxi-processed-data.csv'))",
"features: # hour_sine, hour_cosine, day_of_week_sine, day_of_week_cosine categorical = ['normalizeHolidayName', 'isPaidTimeOff'] numerical = ['vendorID',",
"data for GradientBoostingRegressor: ', rmse) # Save the model if not (args.output is",
"default = None will pass the engineered features unchanged mapper = DataFrameMapper(transformations, input_df=True,",
"df.drop(['totalAmount'], axis=1) y_df = df['totalAmount'] X_train, X_test, y_train, y_test = train_test_split(x_df, y_df, test_size=0.2,",
"x_df = df.drop(['totalAmount'], axis=1) y_df = df['totalAmount'] X_train, X_test, y_train, y_test = train_test_split(x_df,",
"train_test_split(x_df, y_df, test_size=0.2, random_state=0) # we will not transform / scale the four",
"mapper = DataFrameMapper(transformations, input_df=True, df_out=True, default=None, sparse=False) clf = Pipeline(steps=[('preprocessor', mapper), ('regressor', GradientBoostingRegressor())])",
"df_out=True, default=None, sparse=False) clf = Pipeline(steps=[('preprocessor', mapper), ('regressor', GradientBoostingRegressor())]) clf.fit(X_train, y_train) y_predict =",
"import Pipeline from sklearn.impute import SimpleImputer from sklearn.preprocessing import StandardScaler, OneHotEncoder from sklearn_pandas",
"['normalizeHolidayName', 'isPaidTimeOff'] numerical = ['vendorID', 'passengerCount', 'tripDistance', 'day_of_month', 'month_num', 'snowDepth', 'precipTime', 'precipDepth', 'temperature']",
"= parser.parse_args() print(\"Argument 1: %s\" % args.input) print(\"Argument 2: %s\" % args.output) #",
"import pickle from sklearn.model_selection import train_test_split from sklearn.ensemble import GradientBoostingRegressor from sklearn.pipeline import",
"% args.input) print(\"Argument 2: %s\" % args.output) # Load your processed features and",
"= [([f], Pipeline(steps=[ ('imputer', SimpleImputer(strategy='median')), ('scaler', StandardScaler())])) for f in numerical] categorical_transformations =",
"import argparse import os import pandas as pd import numpy as np import",
"will pass the engineered features unchanged mapper = DataFrameMapper(transformations, input_df=True, df_out=True, default=None, sparse=False)",
"'passengerCount', 'tripDistance', 'day_of_month', 'month_num', 'snowDepth', 'precipTime', 'precipDepth', 'temperature'] numeric_transformations = [([f], Pipeline(steps=[ ('imputer',",
"sklearn.impute import SimpleImputer from sklearn.preprocessing import StandardScaler, OneHotEncoder from sklearn_pandas import DataFrameMapper from",
"+ categorical_transformations # df_out will return a data frame, and default = None",
"clf.predict(X_test) y_actual = y_test.values.flatten().tolist() rmse = math.sqrt(mean_squared_error(y_actual, y_predict)) print('The RMSE score on test",
"', rmse) # Save the model if not (args.output is None): os.makedirs(args.output, exist_ok=True)",
"for GradientBoostingRegressor: ', rmse) # Save the model if not (args.output is None):",
"print(\"In train.py\") print(\"As a data scientist, this is where I write my training",
"print(\"As a data scientist, this is where I write my training code.\") parser",
"type=str, help=\"input directory\", dest=\"input\", required=True) parser.add_argument(\"--output\", type=str, help=\"output directory\", dest=\"output\", required=True) args =",
"(args.output is None): os.makedirs(args.output, exist_ok=True) output_filename = os.path.join(args.output, 'nyc-taxi-fare.pkl') pickle.dump(clf, open(output_filename, 'wb')) print('Model",
"args.input) print(\"Argument 2: %s\" % args.output) # Load your processed features and outputs",
"= [([f], OneHotEncoder(handle_unknown='ignore', sparse=False)) for f in categorical] transformations = numeric_transformations + categorical_transformations",
"my training code.\") parser = argparse.ArgumentParser(\"train\") parser.add_argument(\"--input\", type=str, help=\"input directory\", dest=\"input\", required=True) parser.add_argument(\"--output\",",
"day_of_week_sine, day_of_week_cosine categorical = ['normalizeHolidayName', 'isPaidTimeOff'] numerical = ['vendorID', 'passengerCount', 'tripDistance', 'day_of_month', 'month_num',",
"scale the four engineered features: # hour_sine, hour_cosine, day_of_week_sine, day_of_week_cosine categorical = ['normalizeHolidayName',",
"directory\", dest=\"output\", required=True) args = parser.parse_args() print(\"Argument 1: %s\" % args.input) print(\"Argument 2:",
"the engineered features unchanged mapper = DataFrameMapper(transformations, input_df=True, df_out=True, default=None, sparse=False) clf =",
"not (args.output is None): os.makedirs(args.output, exist_ok=True) output_filename = os.path.join(args.output, 'nyc-taxi-fare.pkl') pickle.dump(clf, open(output_filename, 'wb'))",
"the four engineered features: # hour_sine, hour_cosine, day_of_week_sine, day_of_week_cosine categorical = ['normalizeHolidayName', 'isPaidTimeOff']",
"# Save the model if not (args.output is None): os.makedirs(args.output, exist_ok=True) output_filename =",
"= ['normalizeHolidayName', 'isPaidTimeOff'] numerical = ['vendorID', 'passengerCount', 'tripDistance', 'day_of_month', 'month_num', 'snowDepth', 'precipTime', 'precipDepth',",
"Pipeline(steps=[ ('imputer', SimpleImputer(strategy='median')), ('scaler', StandardScaler())])) for f in numerical] categorical_transformations = [([f], OneHotEncoder(handle_unknown='ignore',",
"parser.add_argument(\"--output\", type=str, help=\"output directory\", dest=\"output\", required=True) args = parser.parse_args() print(\"Argument 1: %s\" %",
"= df['totalAmount'] X_train, X_test, y_train, y_test = train_test_split(x_df, y_df, test_size=0.2, random_state=0) # we",
"pickle from sklearn.model_selection import train_test_split from sklearn.ensemble import GradientBoostingRegressor from sklearn.pipeline import Pipeline",
"= pd.read_csv(os.path.join(args.input, 'nyc-taxi-processed-data.csv')) x_df = df.drop(['totalAmount'], axis=1) y_df = df['totalAmount'] X_train, X_test, y_train,",
"['vendorID', 'passengerCount', 'tripDistance', 'day_of_month', 'month_num', 'snowDepth', 'precipTime', 'precipDepth', 'temperature'] numeric_transformations = [([f], Pipeline(steps=[",
"model if not (args.output is None): os.makedirs(args.output, exist_ok=True) output_filename = os.path.join(args.output, 'nyc-taxi-fare.pkl') pickle.dump(clf,",
"frame, and default = None will pass the engineered features unchanged mapper =",
"features unchanged mapper = DataFrameMapper(transformations, input_df=True, df_out=True, default=None, sparse=False) clf = Pipeline(steps=[('preprocessor', mapper),",
"a data frame, and default = None will pass the engineered features unchanged",
"categorical] transformations = numeric_transformations + categorical_transformations # df_out will return a data frame,",
"from sklearn.preprocessing import StandardScaler, OneHotEncoder from sklearn_pandas import DataFrameMapper from sklearn.metrics import mean_squared_error",
"in numerical] categorical_transformations = [([f], OneHotEncoder(handle_unknown='ignore', sparse=False)) for f in categorical] transformations =",
"unchanged mapper = DataFrameMapper(transformations, input_df=True, df_out=True, default=None, sparse=False) clf = Pipeline(steps=[('preprocessor', mapper), ('regressor',",
"your processed features and outputs df = pd.read_csv(os.path.join(args.input, 'nyc-taxi-processed-data.csv')) x_df = df.drop(['totalAmount'], axis=1)",
"a data scientist, this is where I write my training code.\") parser =",
"random_state=0) # we will not transform / scale the four engineered features: #",
"data frame, and default = None will pass the engineered features unchanged mapper",
"sklearn.ensemble import GradientBoostingRegressor from sklearn.pipeline import Pipeline from sklearn.impute import SimpleImputer from sklearn.preprocessing",
"os import pandas as pd import numpy as np import math import pickle",
"mean_squared_error print(\"In train.py\") print(\"As a data scientist, this is where I write my",
"categorical_transformations # df_out will return a data frame, and default = None will",
"= math.sqrt(mean_squared_error(y_actual, y_predict)) print('The RMSE score on test data for GradientBoostingRegressor: ', rmse)",
"import os import pandas as pd import numpy as np import math import",
"'snowDepth', 'precipTime', 'precipDepth', 'temperature'] numeric_transformations = [([f], Pipeline(steps=[ ('imputer', SimpleImputer(strategy='median')), ('scaler', StandardScaler())])) for",
"directory\", dest=\"input\", required=True) parser.add_argument(\"--output\", type=str, help=\"output directory\", dest=\"output\", required=True) args = parser.parse_args() print(\"Argument",
"hour_cosine, day_of_week_sine, day_of_week_cosine categorical = ['normalizeHolidayName', 'isPaidTimeOff'] numerical = ['vendorID', 'passengerCount', 'tripDistance', 'day_of_month',",
"'temperature'] numeric_transformations = [([f], Pipeline(steps=[ ('imputer', SimpleImputer(strategy='median')), ('scaler', StandardScaler())])) for f in numerical]",
"[([f], OneHotEncoder(handle_unknown='ignore', sparse=False)) for f in categorical] transformations = numeric_transformations + categorical_transformations #",
"if not (args.output is None): os.makedirs(args.output, exist_ok=True) output_filename = os.path.join(args.output, 'nyc-taxi-fare.pkl') pickle.dump(clf, open(output_filename,",
"scientist, this is where I write my training code.\") parser = argparse.ArgumentParser(\"train\") parser.add_argument(\"--input\",",
"[([f], Pipeline(steps=[ ('imputer', SimpleImputer(strategy='median')), ('scaler', StandardScaler())])) for f in numerical] categorical_transformations = [([f],",
"= y_test.values.flatten().tolist() rmse = math.sqrt(mean_squared_error(y_actual, y_predict)) print('The RMSE score on test data for",
"%s\" % args.output) # Load your processed features and outputs df = pd.read_csv(os.path.join(args.input,",
"not transform / scale the four engineered features: # hour_sine, hour_cosine, day_of_week_sine, day_of_week_cosine",
"= Pipeline(steps=[('preprocessor', mapper), ('regressor', GradientBoostingRegressor())]) clf.fit(X_train, y_train) y_predict = clf.predict(X_test) y_actual = y_test.values.flatten().tolist()",
"import StandardScaler, OneHotEncoder from sklearn_pandas import DataFrameMapper from sklearn.metrics import mean_squared_error print(\"In train.py\")",
"args.output) # Load your processed features and outputs df = pd.read_csv(os.path.join(args.input, 'nyc-taxi-processed-data.csv')) x_df",
"from sklearn.model_selection import train_test_split from sklearn.ensemble import GradientBoostingRegressor from sklearn.pipeline import Pipeline from",
"DataFrameMapper from sklearn.metrics import mean_squared_error print(\"In train.py\") print(\"As a data scientist, this is",
"dest=\"input\", required=True) parser.add_argument(\"--output\", type=str, help=\"output directory\", dest=\"output\", required=True) args = parser.parse_args() print(\"Argument 1:",
"= argparse.ArgumentParser(\"train\") parser.add_argument(\"--input\", type=str, help=\"input directory\", dest=\"input\", required=True) parser.add_argument(\"--output\", type=str, help=\"output directory\", dest=\"output\",",
"<gh_stars>0 import argparse import os import pandas as pd import numpy as np",
"from sklearn_pandas import DataFrameMapper from sklearn.metrics import mean_squared_error print(\"In train.py\") print(\"As a data",
"parser.add_argument(\"--input\", type=str, help=\"input directory\", dest=\"input\", required=True) parser.add_argument(\"--output\", type=str, help=\"output directory\", dest=\"output\", required=True) args",
"as pd import numpy as np import math import pickle from sklearn.model_selection import",
"pd.read_csv(os.path.join(args.input, 'nyc-taxi-processed-data.csv')) x_df = df.drop(['totalAmount'], axis=1) y_df = df['totalAmount'] X_train, X_test, y_train, y_test",
"'nyc-taxi-processed-data.csv')) x_df = df.drop(['totalAmount'], axis=1) y_df = df['totalAmount'] X_train, X_test, y_train, y_test =",
"numeric_transformations = [([f], Pipeline(steps=[ ('imputer', SimpleImputer(strategy='median')), ('scaler', StandardScaler())])) for f in numerical] categorical_transformations",
"train_test_split from sklearn.ensemble import GradientBoostingRegressor from sklearn.pipeline import Pipeline from sklearn.impute import SimpleImputer",
"GradientBoostingRegressor from sklearn.pipeline import Pipeline from sklearn.impute import SimpleImputer from sklearn.preprocessing import StandardScaler,",
"y_actual = y_test.values.flatten().tolist() rmse = math.sqrt(mean_squared_error(y_actual, y_predict)) print('The RMSE score on test data",
"math import pickle from sklearn.model_selection import train_test_split from sklearn.ensemble import GradientBoostingRegressor from sklearn.pipeline",
"argparse.ArgumentParser(\"train\") parser.add_argument(\"--input\", type=str, help=\"input directory\", dest=\"input\", required=True) parser.add_argument(\"--output\", type=str, help=\"output directory\", dest=\"output\", required=True)",
"f in categorical] transformations = numeric_transformations + categorical_transformations # df_out will return a",
"hour_sine, hour_cosine, day_of_week_sine, day_of_week_cosine categorical = ['normalizeHolidayName', 'isPaidTimeOff'] numerical = ['vendorID', 'passengerCount', 'tripDistance',",
"2: %s\" % args.output) # Load your processed features and outputs df =",
"('regressor', GradientBoostingRegressor())]) clf.fit(X_train, y_train) y_predict = clf.predict(X_test) y_actual = y_test.values.flatten().tolist() rmse = math.sqrt(mean_squared_error(y_actual,",
"parser.parse_args() print(\"Argument 1: %s\" % args.input) print(\"Argument 2: %s\" % args.output) # Load",
"y_predict)) print('The RMSE score on test data for GradientBoostingRegressor: ', rmse) # Save",
"test data for GradientBoostingRegressor: ', rmse) # Save the model if not (args.output",
"data scientist, this is where I write my training code.\") parser = argparse.ArgumentParser(\"train\")",
"parser = argparse.ArgumentParser(\"train\") parser.add_argument(\"--input\", type=str, help=\"input directory\", dest=\"input\", required=True) parser.add_argument(\"--output\", type=str, help=\"output directory\",",
"four engineered features: # hour_sine, hour_cosine, day_of_week_sine, day_of_week_cosine categorical = ['normalizeHolidayName', 'isPaidTimeOff'] numerical",
"day_of_week_cosine categorical = ['normalizeHolidayName', 'isPaidTimeOff'] numerical = ['vendorID', 'passengerCount', 'tripDistance', 'day_of_month', 'month_num', 'snowDepth',",
"transform / scale the four engineered features: # hour_sine, hour_cosine, day_of_week_sine, day_of_week_cosine categorical",
"DataFrameMapper(transformations, input_df=True, df_out=True, default=None, sparse=False) clf = Pipeline(steps=[('preprocessor', mapper), ('regressor', GradientBoostingRegressor())]) clf.fit(X_train, y_train)",
"GradientBoostingRegressor())]) clf.fit(X_train, y_train) y_predict = clf.predict(X_test) y_actual = y_test.values.flatten().tolist() rmse = math.sqrt(mean_squared_error(y_actual, y_predict))",
"type=str, help=\"output directory\", dest=\"output\", required=True) args = parser.parse_args() print(\"Argument 1: %s\" % args.input)",
"y_train, y_test = train_test_split(x_df, y_df, test_size=0.2, random_state=0) # we will not transform /",
"math.sqrt(mean_squared_error(y_actual, y_predict)) print('The RMSE score on test data for GradientBoostingRegressor: ', rmse) #",
"on test data for GradientBoostingRegressor: ', rmse) # Save the model if not",
"will not transform / scale the four engineered features: # hour_sine, hour_cosine, day_of_week_sine,",
"numpy as np import math import pickle from sklearn.model_selection import train_test_split from sklearn.ensemble",
"df = pd.read_csv(os.path.join(args.input, 'nyc-taxi-processed-data.csv')) x_df = df.drop(['totalAmount'], axis=1) y_df = df['totalAmount'] X_train, X_test,",
"sklearn_pandas import DataFrameMapper from sklearn.metrics import mean_squared_error print(\"In train.py\") print(\"As a data scientist,",
"categorical_transformations = [([f], OneHotEncoder(handle_unknown='ignore', sparse=False)) for f in categorical] transformations = numeric_transformations +",
"y_test.values.flatten().tolist() rmse = math.sqrt(mean_squared_error(y_actual, y_predict)) print('The RMSE score on test data for GradientBoostingRegressor:",
"I write my training code.\") parser = argparse.ArgumentParser(\"train\") parser.add_argument(\"--input\", type=str, help=\"input directory\", dest=\"input\",",
"test_size=0.2, random_state=0) # we will not transform / scale the four engineered features:",
"'precipDepth', 'temperature'] numeric_transformations = [([f], Pipeline(steps=[ ('imputer', SimpleImputer(strategy='median')), ('scaler', StandardScaler())])) for f in",
"required=True) parser.add_argument(\"--output\", type=str, help=\"output directory\", dest=\"output\", required=True) args = parser.parse_args() print(\"Argument 1: %s\"",
"training code.\") parser = argparse.ArgumentParser(\"train\") parser.add_argument(\"--input\", type=str, help=\"input directory\", dest=\"input\", required=True) parser.add_argument(\"--output\", type=str,",
"Pipeline(steps=[('preprocessor', mapper), ('regressor', GradientBoostingRegressor())]) clf.fit(X_train, y_train) y_predict = clf.predict(X_test) y_actual = y_test.values.flatten().tolist() rmse",
"outputs df = pd.read_csv(os.path.join(args.input, 'nyc-taxi-processed-data.csv')) x_df = df.drop(['totalAmount'], axis=1) y_df = df['totalAmount'] X_train,",
"will return a data frame, and default = None will pass the engineered",
"= df.drop(['totalAmount'], axis=1) y_df = df['totalAmount'] X_train, X_test, y_train, y_test = train_test_split(x_df, y_df,",
"X_test, y_train, y_test = train_test_split(x_df, y_df, test_size=0.2, random_state=0) # we will not transform",
"default=None, sparse=False) clf = Pipeline(steps=[('preprocessor', mapper), ('regressor', GradientBoostingRegressor())]) clf.fit(X_train, y_train) y_predict = clf.predict(X_test)",
"sparse=False) clf = Pipeline(steps=[('preprocessor', mapper), ('regressor', GradientBoostingRegressor())]) clf.fit(X_train, y_train) y_predict = clf.predict(X_test) y_actual",
"Load your processed features and outputs df = pd.read_csv(os.path.join(args.input, 'nyc-taxi-processed-data.csv')) x_df = df.drop(['totalAmount'],",
"'day_of_month', 'month_num', 'snowDepth', 'precipTime', 'precipDepth', 'temperature'] numeric_transformations = [([f], Pipeline(steps=[ ('imputer', SimpleImputer(strategy='median')), ('scaler',",
"as np import math import pickle from sklearn.model_selection import train_test_split from sklearn.ensemble import",
"features and outputs df = pd.read_csv(os.path.join(args.input, 'nyc-taxi-processed-data.csv')) x_df = df.drop(['totalAmount'], axis=1) y_df =",
"OneHotEncoder(handle_unknown='ignore', sparse=False)) for f in categorical] transformations = numeric_transformations + categorical_transformations # df_out",
"import SimpleImputer from sklearn.preprocessing import StandardScaler, OneHotEncoder from sklearn_pandas import DataFrameMapper from sklearn.metrics",
"df['totalAmount'] X_train, X_test, y_train, y_test = train_test_split(x_df, y_df, test_size=0.2, random_state=0) # we will",
"StandardScaler())])) for f in numerical] categorical_transformations = [([f], OneHotEncoder(handle_unknown='ignore', sparse=False)) for f in",
"from sklearn.pipeline import Pipeline from sklearn.impute import SimpleImputer from sklearn.preprocessing import StandardScaler, OneHotEncoder",
"and outputs df = pd.read_csv(os.path.join(args.input, 'nyc-taxi-processed-data.csv')) x_df = df.drop(['totalAmount'], axis=1) y_df = df['totalAmount']",
"sparse=False)) for f in categorical] transformations = numeric_transformations + categorical_transformations # df_out will",
"= train_test_split(x_df, y_df, test_size=0.2, random_state=0) # we will not transform / scale the",
"Save the model if not (args.output is None): os.makedirs(args.output, exist_ok=True) output_filename = os.path.join(args.output,",
"numerical] categorical_transformations = [([f], OneHotEncoder(handle_unknown='ignore', sparse=False)) for f in categorical] transformations = numeric_transformations",
"sklearn.model_selection import train_test_split from sklearn.ensemble import GradientBoostingRegressor from sklearn.pipeline import Pipeline from sklearn.impute",
"('scaler', StandardScaler())])) for f in numerical] categorical_transformations = [([f], OneHotEncoder(handle_unknown='ignore', sparse=False)) for f",
"y_test = train_test_split(x_df, y_df, test_size=0.2, random_state=0) # we will not transform / scale",
"code.\") parser = argparse.ArgumentParser(\"train\") parser.add_argument(\"--input\", type=str, help=\"input directory\", dest=\"input\", required=True) parser.add_argument(\"--output\", type=str, help=\"output",
"= DataFrameMapper(transformations, input_df=True, df_out=True, default=None, sparse=False) clf = Pipeline(steps=[('preprocessor', mapper), ('regressor', GradientBoostingRegressor())]) clf.fit(X_train,",
"None): os.makedirs(args.output, exist_ok=True) output_filename = os.path.join(args.output, 'nyc-taxi-fare.pkl') pickle.dump(clf, open(output_filename, 'wb')) print('Model file nyc-taxi-fare.pkl"
] |
[
"importlib.import_module(label) except (ImportError, TypeError): pass else: return hasattr(mod, '__path__') return os.path.isdir(os.path.abspath(label)) if __name__",
"module, or \"module.ClassName[.method_name]\", just run those if not os.path.exists(label_as_path): tests = test_loader.loadTestsFromName(label) elif",
"different settings file') args = parser.parse_args() if args.settings: handler.execute_from_command_line(['', args.settings], quiet=True) os.environ['DUMMY'] =",
"this # run, to support running tests from two different top-levels. test_loader._top_level_dir =",
"suite.addTests(tests) return suite def is_discoverable(label): \"\"\" Check if a test label points to",
"= {} for label in test_labels: kwargs = discover_kwargs.copy() tests = None label_as_path",
"= argparse.ArgumentParser() parser.add_argument( 'modules', nargs='*', help='Optional path(s) to test modules; e.g. \"test_settings\" or",
"import unittest import os import importlib import sys from gmc.conf import settings, ENVIRONMENT_VARIABLE",
"= top_level if not (tests and tests.countTestCases()) and is_discoverable(label): # Try discovery if",
"a module, or \"module.ClassName[.method_name]\", just run those if not os.path.exists(label_as_path): tests = test_loader.loadTestsFromName(label)",
"file directory. Relative labels like \".\" and \"..\" are seen as directories. \"\"\"",
"import sys from gmc.conf import settings, ENVIRONMENT_VARIABLE from gmc.core import handler def build_suite(test_labels=None):",
"def build_suite(test_labels=None): suite = unittest.TestSuite() test_loader = unittest.defaultTestLoader test_labels = test_labels or ['.']",
"label_as_path while True: init_py = os.path.join(top_level, '__init__.py') if os.path.exists(init_py): try_next = os.path.dirname(top_level) if",
"nargs='*', help='Optional path(s) to test modules; e.g. \"test_settings\" or ' '\"test_settings.tests.TestSettings.test_settings_loader\".', ) parser.add_argument('--settings',",
"from gmc.conf import settings, ENVIRONMENT_VARIABLE from gmc.core import handler def build_suite(test_labels=None): suite =",
"# if a module, or \"module.ClassName[.method_name]\", just run those if not os.path.exists(label_as_path): tests",
"like \".\" and \"..\" are seen as directories. \"\"\" try: mod = importlib.import_module(label)",
"return hasattr(mod, '__path__') return os.path.isdir(os.path.abspath(label)) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument(",
"else: os.environ[ENVIRONMENT_VARIABLE] = 'setting' os.environ['DUMMY'] = \"TRUE\" args.modules = [os.path.normpath(labels) for labels in",
"break kwargs['top_level_dir'] = top_level if not (tests and tests.countTestCases()) and is_discoverable(label): # Try",
"if try_next == top_level: # __init__.py all the way down? give up. break",
"os.path.isdir(label_as_path): top_level = label_as_path while True: init_py = os.path.join(top_level, '__init__.py') if os.path.exists(init_py): try_next",
"if not (tests and tests.countTestCases()) and is_discoverable(label): # Try discovery if path is",
"way down? give up. break top_level = try_next continue break kwargs['top_level_dir'] = top_level",
"the way down? give up. break top_level = try_next continue break kwargs['top_level_dir'] =",
"a package or directory tests = test_loader.discover(start_dir=label, **kwargs) # Make unittest forget the",
"test modules; e.g. \"test_settings\" or ' '\"test_settings.tests.TestSettings.test_settings_loader\".', ) parser.add_argument('--settings', help='Test gmc with different",
"test_loader.discover(start_dir=label, **kwargs) # Make unittest forget the top-level dir it calculated from this",
"suite def is_discoverable(label): \"\"\" Check if a test label points to a python",
"Relative labels like \".\" and \"..\" are seen as directories. \"\"\" try: mod",
"suite = unittest.TestSuite() test_loader = unittest.defaultTestLoader test_labels = test_labels or ['.'] discover_kwargs =",
"= os.path.abspath(label) # if a module, or \"module.ClassName[.method_name]\", just run those if not",
"in test_labels: kwargs = discover_kwargs.copy() tests = None label_as_path = os.path.abspath(label) # if",
"file') args = parser.parse_args() if args.settings: handler.execute_from_command_line(['', args.settings], quiet=True) os.environ['DUMMY'] = \"FALSE\" else:",
"tests.countTestCases()) and is_discoverable(label): # Try discovery if path is a package or directory",
"different top-levels. test_loader._top_level_dir = None suite.addTests(tests) return suite def is_discoverable(label): \"\"\" Check if",
"os.environ['DUMMY'] = \"TRUE\" args.modules = [os.path.normpath(labels) for labels in args.modules] suite = build_suite(args.modules)",
"from two different top-levels. test_loader._top_level_dir = None suite.addTests(tests) return suite def is_discoverable(label): \"\"\"",
"help='Optional path(s) to test modules; e.g. \"test_settings\" or ' '\"test_settings.tests.TestSettings.test_settings_loader\".', ) parser.add_argument('--settings', help='Test",
"and \"..\" are seen as directories. \"\"\" try: mod = importlib.import_module(label) except (ImportError,",
"tests = test_loader.discover(start_dir=label, **kwargs) # Make unittest forget the top-level dir it calculated",
"discover_kwargs.copy() tests = None label_as_path = os.path.abspath(label) # if a module, or \"module.ClassName[.method_name]\",",
"args.modules = [os.path.normpath(labels) for labels in args.modules] suite = build_suite(args.modules) runner = unittest.TextTestRunner()",
"top-level dir it calculated from this # run, to support running tests from",
"e.g. \"test_settings\" or ' '\"test_settings.tests.TestSettings.test_settings_loader\".', ) parser.add_argument('--settings', help='Test gmc with different settings file')",
"down? give up. break top_level = try_next continue break kwargs['top_level_dir'] = top_level if",
"unittest import os import importlib import sys from gmc.conf import settings, ENVIRONMENT_VARIABLE from",
"= test_labels or ['.'] discover_kwargs = {} for label in test_labels: kwargs =",
"importlib import sys from gmc.conf import settings, ENVIRONMENT_VARIABLE from gmc.core import handler def",
"None label_as_path = os.path.abspath(label) # if a module, or \"module.ClassName[.method_name]\", just run those",
"True: init_py = os.path.join(top_level, '__init__.py') if os.path.exists(init_py): try_next = os.path.dirname(top_level) if try_next ==",
"and is_discoverable(label): # Try discovery if path is a package or directory tests",
"seen as directories. \"\"\" try: mod = importlib.import_module(label) except (ImportError, TypeError): pass else:",
"\"test_settings\" or ' '\"test_settings.tests.TestSettings.test_settings_loader\".', ) parser.add_argument('--settings', help='Test gmc with different settings file') args",
"for label in test_labels: kwargs = discover_kwargs.copy() tests = None label_as_path = os.path.abspath(label)",
"\"..\" are seen as directories. \"\"\" try: mod = importlib.import_module(label) except (ImportError, TypeError):",
"those if not os.path.exists(label_as_path): tests = test_loader.loadTestsFromName(label) elif os.path.isdir(label_as_path): top_level = label_as_path while",
"= [os.path.normpath(labels) for labels in args.modules] suite = build_suite(args.modules) runner = unittest.TextTestRunner() runner.run(suite)",
"dir it calculated from this # run, to support running tests from two",
"from this # run, to support running tests from two different top-levels. test_loader._top_level_dir",
"not os.path.exists(label_as_path): tests = test_loader.loadTestsFromName(label) elif os.path.isdir(label_as_path): top_level = label_as_path while True: init_py",
"kwargs['top_level_dir'] = top_level if not (tests and tests.countTestCases()) and is_discoverable(label): # Try discovery",
"TypeError): pass else: return hasattr(mod, '__path__') return os.path.isdir(os.path.abspath(label)) if __name__ == '__main__': parser",
"unittest.TestSuite() test_loader = unittest.defaultTestLoader test_labels = test_labels or ['.'] discover_kwargs = {} for",
"if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument( 'modules', nargs='*', help='Optional path(s) to",
"from gmc.core import handler def build_suite(test_labels=None): suite = unittest.TestSuite() test_loader = unittest.defaultTestLoader test_labels",
"the top-level dir it calculated from this # run, to support running tests",
"if a test label points to a python package or file directory. Relative",
"it calculated from this # run, to support running tests from two different",
"= \"TRUE\" args.modules = [os.path.normpath(labels) for labels in args.modules] suite = build_suite(args.modules) runner",
"tests = test_loader.loadTestsFromName(label) elif os.path.isdir(label_as_path): top_level = label_as_path while True: init_py = os.path.join(top_level,",
"directory tests = test_loader.discover(start_dir=label, **kwargs) # Make unittest forget the top-level dir it",
"if a module, or \"module.ClassName[.method_name]\", just run those if not os.path.exists(label_as_path): tests =",
"os.path.dirname(top_level) if try_next == top_level: # __init__.py all the way down? give up.",
"two different top-levels. test_loader._top_level_dir = None suite.addTests(tests) return suite def is_discoverable(label): \"\"\" Check",
"a python package or file directory. Relative labels like \".\" and \"..\" are",
"else: return hasattr(mod, '__path__') return os.path.isdir(os.path.abspath(label)) if __name__ == '__main__': parser = argparse.ArgumentParser()",
"args.settings: handler.execute_from_command_line(['', args.settings], quiet=True) os.environ['DUMMY'] = \"FALSE\" else: os.environ[ENVIRONMENT_VARIABLE] = 'setting' os.environ['DUMMY'] =",
"'setting' os.environ['DUMMY'] = \"TRUE\" args.modules = [os.path.normpath(labels) for labels in args.modules] suite =",
"build_suite(test_labels=None): suite = unittest.TestSuite() test_loader = unittest.defaultTestLoader test_labels = test_labels or ['.'] discover_kwargs",
"top_level: # __init__.py all the way down? give up. break top_level = try_next",
"parser.add_argument('--settings', help='Test gmc with different settings file') args = parser.parse_args() if args.settings: handler.execute_from_command_line(['',",
"tests from two different top-levels. test_loader._top_level_dir = None suite.addTests(tests) return suite def is_discoverable(label):",
"import importlib import sys from gmc.conf import settings, ENVIRONMENT_VARIABLE from gmc.core import handler",
"kwargs = discover_kwargs.copy() tests = None label_as_path = os.path.abspath(label) # if a module,",
"Make unittest forget the top-level dir it calculated from this # run, to",
"points to a python package or file directory. Relative labels like \".\" and",
"'\"test_settings.tests.TestSettings.test_settings_loader\".', ) parser.add_argument('--settings', help='Test gmc with different settings file') args = parser.parse_args() if",
"= test_loader.discover(start_dir=label, **kwargs) # Make unittest forget the top-level dir it calculated from",
"\"FALSE\" else: os.environ[ENVIRONMENT_VARIABLE] = 'setting' os.environ['DUMMY'] = \"TRUE\" args.modules = [os.path.normpath(labels) for labels",
"try_next continue break kwargs['top_level_dir'] = top_level if not (tests and tests.countTestCases()) and is_discoverable(label):",
"or file directory. Relative labels like \".\" and \"..\" are seen as directories.",
"\"module.ClassName[.method_name]\", just run those if not os.path.exists(label_as_path): tests = test_loader.loadTestsFromName(label) elif os.path.isdir(label_as_path): top_level",
"give up. break top_level = try_next continue break kwargs['top_level_dir'] = top_level if not",
"label points to a python package or file directory. Relative labels like \".\"",
"is_discoverable(label): # Try discovery if path is a package or directory tests =",
"directory. Relative labels like \".\" and \"..\" are seen as directories. \"\"\" try:",
"os.environ[ENVIRONMENT_VARIABLE] = 'setting' os.environ['DUMMY'] = \"TRUE\" args.modules = [os.path.normpath(labels) for labels in args.modules]",
"forget the top-level dir it calculated from this # run, to support running",
"os import importlib import sys from gmc.conf import settings, ENVIRONMENT_VARIABLE from gmc.core import",
"= unittest.defaultTestLoader test_labels = test_labels or ['.'] discover_kwargs = {} for label in",
"= os.path.dirname(top_level) if try_next == top_level: # __init__.py all the way down? give",
"discovery if path is a package or directory tests = test_loader.discover(start_dir=label, **kwargs) #",
"or \"module.ClassName[.method_name]\", just run those if not os.path.exists(label_as_path): tests = test_loader.loadTestsFromName(label) elif os.path.isdir(label_as_path):",
"['.'] discover_kwargs = {} for label in test_labels: kwargs = discover_kwargs.copy() tests =",
"**kwargs) # Make unittest forget the top-level dir it calculated from this #",
"support running tests from two different top-levels. test_loader._top_level_dir = None suite.addTests(tests) return suite",
"os.path.join(top_level, '__init__.py') if os.path.exists(init_py): try_next = os.path.dirname(top_level) if try_next == top_level: # __init__.py",
"__init__.py all the way down? give up. break top_level = try_next continue break",
"not (tests and tests.countTestCases()) and is_discoverable(label): # Try discovery if path is a",
"None suite.addTests(tests) return suite def is_discoverable(label): \"\"\" Check if a test label points",
"continue break kwargs['top_level_dir'] = top_level if not (tests and tests.countTestCases()) and is_discoverable(label): #",
"'modules', nargs='*', help='Optional path(s) to test modules; e.g. \"test_settings\" or ' '\"test_settings.tests.TestSettings.test_settings_loader\".', )",
"to a python package or file directory. Relative labels like \".\" and \"..\"",
"__name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument( 'modules', nargs='*', help='Optional path(s) to test",
"os.path.exists(label_as_path): tests = test_loader.loadTestsFromName(label) elif os.path.isdir(label_as_path): top_level = label_as_path while True: init_py =",
"{} for label in test_labels: kwargs = discover_kwargs.copy() tests = None label_as_path =",
"test_labels or ['.'] discover_kwargs = {} for label in test_labels: kwargs = discover_kwargs.copy()",
"is a package or directory tests = test_loader.discover(start_dir=label, **kwargs) # Make unittest forget",
"top_level if not (tests and tests.countTestCases()) and is_discoverable(label): # Try discovery if path",
"if path is a package or directory tests = test_loader.discover(start_dir=label, **kwargs) # Make",
"break top_level = try_next continue break kwargs['top_level_dir'] = top_level if not (tests and",
"gmc.core import handler def build_suite(test_labels=None): suite = unittest.TestSuite() test_loader = unittest.defaultTestLoader test_labels =",
"Check if a test label points to a python package or file directory.",
"if not os.path.exists(label_as_path): tests = test_loader.loadTestsFromName(label) elif os.path.isdir(label_as_path): top_level = label_as_path while True:",
"path(s) to test modules; e.g. \"test_settings\" or ' '\"test_settings.tests.TestSettings.test_settings_loader\".', ) parser.add_argument('--settings', help='Test gmc",
"elif os.path.isdir(label_as_path): top_level = label_as_path while True: init_py = os.path.join(top_level, '__init__.py') if os.path.exists(init_py):",
"top_level = try_next continue break kwargs['top_level_dir'] = top_level if not (tests and tests.countTestCases())",
"or ' '\"test_settings.tests.TestSettings.test_settings_loader\".', ) parser.add_argument('--settings', help='Test gmc with different settings file') args =",
"as directories. \"\"\" try: mod = importlib.import_module(label) except (ImportError, TypeError): pass else: return",
"if args.settings: handler.execute_from_command_line(['', args.settings], quiet=True) os.environ['DUMMY'] = \"FALSE\" else: os.environ[ENVIRONMENT_VARIABLE] = 'setting' os.environ['DUMMY']",
"test_loader._top_level_dir = None suite.addTests(tests) return suite def is_discoverable(label): \"\"\" Check if a test",
"python package or file directory. Relative labels like \".\" and \"..\" are seen",
"# Try discovery if path is a package or directory tests = test_loader.discover(start_dir=label,",
"\"\"\" Check if a test label points to a python package or file",
"= parser.parse_args() if args.settings: handler.execute_from_command_line(['', args.settings], quiet=True) os.environ['DUMMY'] = \"FALSE\" else: os.environ[ENVIRONMENT_VARIABLE] =",
"with different settings file') args = parser.parse_args() if args.settings: handler.execute_from_command_line(['', args.settings], quiet=True) os.environ['DUMMY']",
"argparse.ArgumentParser() parser.add_argument( 'modules', nargs='*', help='Optional path(s) to test modules; e.g. \"test_settings\" or '",
"= try_next continue break kwargs['top_level_dir'] = top_level if not (tests and tests.countTestCases()) and",
"== top_level: # __init__.py all the way down? give up. break top_level =",
"= unittest.TestSuite() test_loader = unittest.defaultTestLoader test_labels = test_labels or ['.'] discover_kwargs = {}",
"= \"FALSE\" else: os.environ[ENVIRONMENT_VARIABLE] = 'setting' os.environ['DUMMY'] = \"TRUE\" args.modules = [os.path.normpath(labels) for",
"to test modules; e.g. \"test_settings\" or ' '\"test_settings.tests.TestSettings.test_settings_loader\".', ) parser.add_argument('--settings', help='Test gmc with",
"test_loader.loadTestsFromName(label) elif os.path.isdir(label_as_path): top_level = label_as_path while True: init_py = os.path.join(top_level, '__init__.py') if",
"calculated from this # run, to support running tests from two different top-levels.",
"= discover_kwargs.copy() tests = None label_as_path = os.path.abspath(label) # if a module, or",
"args.settings], quiet=True) os.environ['DUMMY'] = \"FALSE\" else: os.environ[ENVIRONMENT_VARIABLE] = 'setting' os.environ['DUMMY'] = \"TRUE\" args.modules",
"= None label_as_path = os.path.abspath(label) # if a module, or \"module.ClassName[.method_name]\", just run",
"Try discovery if path is a package or directory tests = test_loader.discover(start_dir=label, **kwargs)",
"label in test_labels: kwargs = discover_kwargs.copy() tests = None label_as_path = os.path.abspath(label) #",
"discover_kwargs = {} for label in test_labels: kwargs = discover_kwargs.copy() tests = None",
"settings file') args = parser.parse_args() if args.settings: handler.execute_from_command_line(['', args.settings], quiet=True) os.environ['DUMMY'] = \"FALSE\"",
"# run, to support running tests from two different top-levels. test_loader._top_level_dir = None",
"def is_discoverable(label): \"\"\" Check if a test label points to a python package",
"(tests and tests.countTestCases()) and is_discoverable(label): # Try discovery if path is a package",
"import os import importlib import sys from gmc.conf import settings, ENVIRONMENT_VARIABLE from gmc.core",
"# Make unittest forget the top-level dir it calculated from this # run,",
"handler.execute_from_command_line(['', args.settings], quiet=True) os.environ['DUMMY'] = \"FALSE\" else: os.environ[ENVIRONMENT_VARIABLE] = 'setting' os.environ['DUMMY'] = \"TRUE\"",
"test_labels: kwargs = discover_kwargs.copy() tests = None label_as_path = os.path.abspath(label) # if a",
"== '__main__': parser = argparse.ArgumentParser() parser.add_argument( 'modules', nargs='*', help='Optional path(s) to test modules;",
"run those if not os.path.exists(label_as_path): tests = test_loader.loadTestsFromName(label) elif os.path.isdir(label_as_path): top_level = label_as_path",
"parser = argparse.ArgumentParser() parser.add_argument( 'modules', nargs='*', help='Optional path(s) to test modules; e.g. \"test_settings\"",
"are seen as directories. \"\"\" try: mod = importlib.import_module(label) except (ImportError, TypeError): pass",
"os.path.abspath(label) # if a module, or \"module.ClassName[.method_name]\", just run those if not os.path.exists(label_as_path):",
"try_next = os.path.dirname(top_level) if try_next == top_level: # __init__.py all the way down?",
"and tests.countTestCases()) and is_discoverable(label): # Try discovery if path is a package or",
"except (ImportError, TypeError): pass else: return hasattr(mod, '__path__') return os.path.isdir(os.path.abspath(label)) if __name__ ==",
"up. break top_level = try_next continue break kwargs['top_level_dir'] = top_level if not (tests",
"= 'setting' os.environ['DUMMY'] = \"TRUE\" args.modules = [os.path.normpath(labels) for labels in args.modules] suite",
"'__main__': parser = argparse.ArgumentParser() parser.add_argument( 'modules', nargs='*', help='Optional path(s) to test modules; e.g.",
"\".\" and \"..\" are seen as directories. \"\"\" try: mod = importlib.import_module(label) except",
"'__path__') return os.path.isdir(os.path.abspath(label)) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument( 'modules', nargs='*',",
"handler def build_suite(test_labels=None): suite = unittest.TestSuite() test_loader = unittest.defaultTestLoader test_labels = test_labels or",
"= os.path.join(top_level, '__init__.py') if os.path.exists(init_py): try_next = os.path.dirname(top_level) if try_next == top_level: #",
"# __init__.py all the way down? give up. break top_level = try_next continue",
"mod = importlib.import_module(label) except (ImportError, TypeError): pass else: return hasattr(mod, '__path__') return os.path.isdir(os.path.abspath(label))",
"\"\"\" try: mod = importlib.import_module(label) except (ImportError, TypeError): pass else: return hasattr(mod, '__path__')",
"'__init__.py') if os.path.exists(init_py): try_next = os.path.dirname(top_level) if try_next == top_level: # __init__.py all",
"\"TRUE\" args.modules = [os.path.normpath(labels) for labels in args.modules] suite = build_suite(args.modules) runner =",
"top_level = label_as_path while True: init_py = os.path.join(top_level, '__init__.py') if os.path.exists(init_py): try_next =",
"os.path.exists(init_py): try_next = os.path.dirname(top_level) if try_next == top_level: # __init__.py all the way",
"top-levels. test_loader._top_level_dir = None suite.addTests(tests) return suite def is_discoverable(label): \"\"\" Check if a",
"is_discoverable(label): \"\"\" Check if a test label points to a python package or",
"= label_as_path while True: init_py = os.path.join(top_level, '__init__.py') if os.path.exists(init_py): try_next = os.path.dirname(top_level)",
"help='Test gmc with different settings file') args = parser.parse_args() if args.settings: handler.execute_from_command_line(['', args.settings],",
"= None suite.addTests(tests) return suite def is_discoverable(label): \"\"\" Check if a test label",
"return suite def is_discoverable(label): \"\"\" Check if a test label points to a",
"unittest forget the top-level dir it calculated from this # run, to support",
"while True: init_py = os.path.join(top_level, '__init__.py') if os.path.exists(init_py): try_next = os.path.dirname(top_level) if try_next",
"to support running tests from two different top-levels. test_loader._top_level_dir = None suite.addTests(tests) return",
"= importlib.import_module(label) except (ImportError, TypeError): pass else: return hasattr(mod, '__path__') return os.path.isdir(os.path.abspath(label)) if",
"test label points to a python package or file directory. Relative labels like",
"package or directory tests = test_loader.discover(start_dir=label, **kwargs) # Make unittest forget the top-level",
") parser.add_argument('--settings', help='Test gmc with different settings file') args = parser.parse_args() if args.settings:",
"tests = None label_as_path = os.path.abspath(label) # if a module, or \"module.ClassName[.method_name]\", just",
"just run those if not os.path.exists(label_as_path): tests = test_loader.loadTestsFromName(label) elif os.path.isdir(label_as_path): top_level =",
"running tests from two different top-levels. test_loader._top_level_dir = None suite.addTests(tests) return suite def",
"hasattr(mod, '__path__') return os.path.isdir(os.path.abspath(label)) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument( 'modules',",
"a test label points to a python package or file directory. Relative labels",
"os.environ['DUMMY'] = \"FALSE\" else: os.environ[ENVIRONMENT_VARIABLE] = 'setting' os.environ['DUMMY'] = \"TRUE\" args.modules = [os.path.normpath(labels)",
"gmc.conf import settings, ENVIRONMENT_VARIABLE from gmc.core import handler def build_suite(test_labels=None): suite = unittest.TestSuite()",
"init_py = os.path.join(top_level, '__init__.py') if os.path.exists(init_py): try_next = os.path.dirname(top_level) if try_next == top_level:",
"path is a package or directory tests = test_loader.discover(start_dir=label, **kwargs) # Make unittest",
"os.path.isdir(os.path.abspath(label)) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument( 'modules', nargs='*', help='Optional path(s)",
"pass else: return hasattr(mod, '__path__') return os.path.isdir(os.path.abspath(label)) if __name__ == '__main__': parser =",
"' '\"test_settings.tests.TestSettings.test_settings_loader\".', ) parser.add_argument('--settings', help='Test gmc with different settings file') args = parser.parse_args()",
"import handler def build_suite(test_labels=None): suite = unittest.TestSuite() test_loader = unittest.defaultTestLoader test_labels = test_labels",
"test_labels = test_labels or ['.'] discover_kwargs = {} for label in test_labels: kwargs",
"sys from gmc.conf import settings, ENVIRONMENT_VARIABLE from gmc.core import handler def build_suite(test_labels=None): suite",
"return os.path.isdir(os.path.abspath(label)) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument( 'modules', nargs='*', help='Optional",
"import settings, ENVIRONMENT_VARIABLE from gmc.core import handler def build_suite(test_labels=None): suite = unittest.TestSuite() test_loader",
"label_as_path = os.path.abspath(label) # if a module, or \"module.ClassName[.method_name]\", just run those if",
"quiet=True) os.environ['DUMMY'] = \"FALSE\" else: os.environ[ENVIRONMENT_VARIABLE] = 'setting' os.environ['DUMMY'] = \"TRUE\" args.modules =",
"or directory tests = test_loader.discover(start_dir=label, **kwargs) # Make unittest forget the top-level dir",
"test_loader = unittest.defaultTestLoader test_labels = test_labels or ['.'] discover_kwargs = {} for label",
"try_next == top_level: # __init__.py all the way down? give up. break top_level",
"all the way down? give up. break top_level = try_next continue break kwargs['top_level_dir']",
"settings, ENVIRONMENT_VARIABLE from gmc.core import handler def build_suite(test_labels=None): suite = unittest.TestSuite() test_loader =",
"argparse import unittest import os import importlib import sys from gmc.conf import settings,",
"ENVIRONMENT_VARIABLE from gmc.core import handler def build_suite(test_labels=None): suite = unittest.TestSuite() test_loader = unittest.defaultTestLoader",
"directories. \"\"\" try: mod = importlib.import_module(label) except (ImportError, TypeError): pass else: return hasattr(mod,",
"= test_loader.loadTestsFromName(label) elif os.path.isdir(label_as_path): top_level = label_as_path while True: init_py = os.path.join(top_level, '__init__.py')",
"if os.path.exists(init_py): try_next = os.path.dirname(top_level) if try_next == top_level: # __init__.py all the",
"try: mod = importlib.import_module(label) except (ImportError, TypeError): pass else: return hasattr(mod, '__path__') return",
"parser.add_argument( 'modules', nargs='*', help='Optional path(s) to test modules; e.g. \"test_settings\" or ' '\"test_settings.tests.TestSettings.test_settings_loader\".',",
"import argparse import unittest import os import importlib import sys from gmc.conf import",
"package or file directory. Relative labels like \".\" and \"..\" are seen as",
"unittest.defaultTestLoader test_labels = test_labels or ['.'] discover_kwargs = {} for label in test_labels:",
"parser.parse_args() if args.settings: handler.execute_from_command_line(['', args.settings], quiet=True) os.environ['DUMMY'] = \"FALSE\" else: os.environ[ENVIRONMENT_VARIABLE] = 'setting'",
"gmc with different settings file') args = parser.parse_args() if args.settings: handler.execute_from_command_line(['', args.settings], quiet=True)",
"run, to support running tests from two different top-levels. test_loader._top_level_dir = None suite.addTests(tests)",
"(ImportError, TypeError): pass else: return hasattr(mod, '__path__') return os.path.isdir(os.path.abspath(label)) if __name__ == '__main__':",
"modules; e.g. \"test_settings\" or ' '\"test_settings.tests.TestSettings.test_settings_loader\".', ) parser.add_argument('--settings', help='Test gmc with different settings",
"labels like \".\" and \"..\" are seen as directories. \"\"\" try: mod =",
"or ['.'] discover_kwargs = {} for label in test_labels: kwargs = discover_kwargs.copy() tests",
"args = parser.parse_args() if args.settings: handler.execute_from_command_line(['', args.settings], quiet=True) os.environ['DUMMY'] = \"FALSE\" else: os.environ[ENVIRONMENT_VARIABLE]"
] |
[
"coding: utf-8 -*- \"\"\" Singleton class to manage configuration Description: Todo: \"\"\" import",
"to manage configuration Description: Todo: \"\"\" import json import os import sys import",
"except Exception as error: logging.error(error, exc_info=True) return self.config def store(self): try: with open(self._url,",
"self._url = url Config.__instance = self def load(self, url): try: self.config = json.load(open(url))",
"import constant class Config(object): # Here will be the instance stored. __instance =",
"Singleton class to manage configuration Description: Todo: \"\"\" import json import os import",
"@classmethod def getInstance(cls): \"\"\" Static access method. \"\"\" if Config.__instance == None: raise",
"load(self, url): try: self.config = json.load(open(url)) self.config[\"version\"] = constant.APPVERSION logging.info(self.config) except Exception as",
"= json.load(open(url)) self.config[\"version\"] = constant.APPVERSION logging.info(self.config) except Exception as error: logging.error(error, exc_info=True) return",
"def __init__(self, url): \"\"\" Virtually private constructor. \"\"\" if Config.__instance != None: raise",
"instance stored. __instance = None @classmethod def getInstance(cls): \"\"\" Static access method. \"\"\"",
"access method. \"\"\" if Config.__instance == None: raise Exception(\"Any configuration is not initialized",
"try: with open(self._url, \"w\") as outfile: json.dump(self.config, outfile, indent=4) except Exception as error:",
"is a singleton!\") else: self.config = dict() self.load(url) self._url = url Config.__instance =",
"Config.__instance def __init__(self, url): \"\"\" Virtually private constructor. \"\"\" if Config.__instance != None:",
"# Here will be the instance stored. __instance = None @classmethod def getInstance(cls):",
"Config.__instance == None: raise Exception(\"Any configuration is not initialized yet!\") return Config.__instance def",
"-*- \"\"\" Singleton class to manage configuration Description: Todo: \"\"\" import json import",
"Exception as error: logging.error(error, exc_info=True) return self.config def store(self): try: with open(self._url, \"w\")",
"!= None: raise Exception(\"This class is a singleton!\") else: self.config = dict() self.load(url)",
"if Config.__instance != None: raise Exception(\"This class is a singleton!\") else: self.config =",
"Static access method. \"\"\" if Config.__instance == None: raise Exception(\"Any configuration is not",
"constant.APPVERSION logging.info(self.config) except Exception as error: logging.error(error, exc_info=True) return self.config def store(self): try:",
"else: self.config = dict() self.load(url) self._url = url Config.__instance = self def load(self,",
"dict() self.load(url) self._url = url Config.__instance = self def load(self, url): try: self.config",
"private constructor. \"\"\" if Config.__instance != None: raise Exception(\"This class is a singleton!\")",
"import os import sys import logging import constant class Config(object): # Here will",
"the instance stored. __instance = None @classmethod def getInstance(cls): \"\"\" Static access method.",
"exc_info=True) return self.config def store(self): try: with open(self._url, \"w\") as outfile: json.dump(self.config, outfile,",
"constructor. \"\"\" if Config.__instance != None: raise Exception(\"This class is a singleton!\") else:",
"import sys import logging import constant class Config(object): # Here will be the",
"url Config.__instance = self def load(self, url): try: self.config = json.load(open(url)) self.config[\"version\"] =",
"class Config(object): # Here will be the instance stored. __instance = None @classmethod",
"\"\"\" if Config.__instance != None: raise Exception(\"This class is a singleton!\") else: self.config",
"json.load(open(url)) self.config[\"version\"] = constant.APPVERSION logging.info(self.config) except Exception as error: logging.error(error, exc_info=True) return self.config",
"__instance = None @classmethod def getInstance(cls): \"\"\" Static access method. \"\"\" if Config.__instance",
"Virtually private constructor. \"\"\" if Config.__instance != None: raise Exception(\"This class is a",
"error: logging.error(error, exc_info=True) return self.config def store(self): try: with open(self._url, \"w\") as outfile:",
"Here will be the instance stored. __instance = None @classmethod def getInstance(cls): \"\"\"",
"return self.config def store(self): try: with open(self._url, \"w\") as outfile: json.dump(self.config, outfile, indent=4)",
"sys import logging import constant class Config(object): # Here will be the instance",
"store(self): try: with open(self._url, \"w\") as outfile: json.dump(self.config, outfile, indent=4) except Exception as",
"be the instance stored. __instance = None @classmethod def getInstance(cls): \"\"\" Static access",
"\"\"\" import json import os import sys import logging import constant class Config(object):",
"Config.__instance != None: raise Exception(\"This class is a singleton!\") else: self.config = dict()",
"Config.__instance = self def load(self, url): try: self.config = json.load(open(url)) self.config[\"version\"] = constant.APPVERSION",
"# -*- coding: utf-8 -*- \"\"\" Singleton class to manage configuration Description: Todo:",
"logging.info(self.config) except Exception as error: logging.error(error, exc_info=True) return self.config def store(self): try: with",
"\"\"\" Singleton class to manage configuration Description: Todo: \"\"\" import json import os",
"manage configuration Description: Todo: \"\"\" import json import os import sys import logging",
"class is a singleton!\") else: self.config = dict() self.load(url) self._url = url Config.__instance",
"with open(self._url, \"w\") as outfile: json.dump(self.config, outfile, indent=4) except Exception as error: logging.error(error,",
"\"\"\" if Config.__instance == None: raise Exception(\"Any configuration is not initialized yet!\") return",
"\"\"\" Virtually private constructor. \"\"\" if Config.__instance != None: raise Exception(\"This class is",
"getInstance(cls): \"\"\" Static access method. \"\"\" if Config.__instance == None: raise Exception(\"Any configuration",
"url): \"\"\" Virtually private constructor. \"\"\" if Config.__instance != None: raise Exception(\"This class",
"None: raise Exception(\"Any configuration is not initialized yet!\") return Config.__instance def __init__(self, url):",
"None @classmethod def getInstance(cls): \"\"\" Static access method. \"\"\" if Config.__instance == None:",
"configuration Description: Todo: \"\"\" import json import os import sys import logging import",
"json import os import sys import logging import constant class Config(object): # Here",
"import logging import constant class Config(object): # Here will be the instance stored.",
"import json import os import sys import logging import constant class Config(object): #",
"method. \"\"\" if Config.__instance == None: raise Exception(\"Any configuration is not initialized yet!\")",
"will be the instance stored. __instance = None @classmethod def getInstance(cls): \"\"\" Static",
"not initialized yet!\") return Config.__instance def __init__(self, url): \"\"\" Virtually private constructor. \"\"\"",
"url): try: self.config = json.load(open(url)) self.config[\"version\"] = constant.APPVERSION logging.info(self.config) except Exception as error:",
"= url Config.__instance = self def load(self, url): try: self.config = json.load(open(url)) self.config[\"version\"]",
"self.load(url) self._url = url Config.__instance = self def load(self, url): try: self.config =",
"Description: Todo: \"\"\" import json import os import sys import logging import constant",
"None: raise Exception(\"This class is a singleton!\") else: self.config = dict() self.load(url) self._url",
"self.config = dict() self.load(url) self._url = url Config.__instance = self def load(self, url):",
"try: self.config = json.load(open(url)) self.config[\"version\"] = constant.APPVERSION logging.info(self.config) except Exception as error: logging.error(error,",
"= constant.APPVERSION logging.info(self.config) except Exception as error: logging.error(error, exc_info=True) return self.config def store(self):",
"singleton!\") else: self.config = dict() self.load(url) self._url = url Config.__instance = self def",
"Todo: \"\"\" import json import os import sys import logging import constant class",
"class to manage configuration Description: Todo: \"\"\" import json import os import sys",
"= dict() self.load(url) self._url = url Config.__instance = self def load(self, url): try:",
"constant class Config(object): # Here will be the instance stored. __instance = None",
"Exception(\"This class is a singleton!\") else: self.config = dict() self.load(url) self._url = url",
"configuration is not initialized yet!\") return Config.__instance def __init__(self, url): \"\"\" Virtually private",
"initialized yet!\") return Config.__instance def __init__(self, url): \"\"\" Virtually private constructor. \"\"\" if",
"== None: raise Exception(\"Any configuration is not initialized yet!\") return Config.__instance def __init__(self,",
"self.config[\"version\"] = constant.APPVERSION logging.info(self.config) except Exception as error: logging.error(error, exc_info=True) return self.config def",
"self def load(self, url): try: self.config = json.load(open(url)) self.config[\"version\"] = constant.APPVERSION logging.info(self.config) except",
"if Config.__instance == None: raise Exception(\"Any configuration is not initialized yet!\") return Config.__instance",
"self.config = json.load(open(url)) self.config[\"version\"] = constant.APPVERSION logging.info(self.config) except Exception as error: logging.error(error, exc_info=True)",
"Config(object): # Here will be the instance stored. __instance = None @classmethod def",
"utf-8 -*- \"\"\" Singleton class to manage configuration Description: Todo: \"\"\" import json",
"as error: logging.error(error, exc_info=True) return self.config def store(self): try: with open(self._url, \"w\") as",
"logging.error(error, exc_info=True) return self.config def store(self): try: with open(self._url, \"w\") as outfile: json.dump(self.config,",
"self.config def store(self): try: with open(self._url, \"w\") as outfile: json.dump(self.config, outfile, indent=4) except",
"raise Exception(\"Any configuration is not initialized yet!\") return Config.__instance def __init__(self, url): \"\"\"",
"logging import constant class Config(object): # Here will be the instance stored. __instance",
"__init__(self, url): \"\"\" Virtually private constructor. \"\"\" if Config.__instance != None: raise Exception(\"This",
"is not initialized yet!\") return Config.__instance def __init__(self, url): \"\"\" Virtually private constructor.",
"a singleton!\") else: self.config = dict() self.load(url) self._url = url Config.__instance = self",
"return Config.__instance def __init__(self, url): \"\"\" Virtually private constructor. \"\"\" if Config.__instance !=",
"def load(self, url): try: self.config = json.load(open(url)) self.config[\"version\"] = constant.APPVERSION logging.info(self.config) except Exception",
"def store(self): try: with open(self._url, \"w\") as outfile: json.dump(self.config, outfile, indent=4) except Exception",
"os import sys import logging import constant class Config(object): # Here will be",
"raise Exception(\"This class is a singleton!\") else: self.config = dict() self.load(url) self._url =",
"= self def load(self, url): try: self.config = json.load(open(url)) self.config[\"version\"] = constant.APPVERSION logging.info(self.config)",
"-*- coding: utf-8 -*- \"\"\" Singleton class to manage configuration Description: Todo: \"\"\"",
"yet!\") return Config.__instance def __init__(self, url): \"\"\" Virtually private constructor. \"\"\" if Config.__instance",
"= None @classmethod def getInstance(cls): \"\"\" Static access method. \"\"\" if Config.__instance ==",
"Exception(\"Any configuration is not initialized yet!\") return Config.__instance def __init__(self, url): \"\"\" Virtually",
"def getInstance(cls): \"\"\" Static access method. \"\"\" if Config.__instance == None: raise Exception(\"Any",
"\"\"\" Static access method. \"\"\" if Config.__instance == None: raise Exception(\"Any configuration is",
"open(self._url, \"w\") as outfile: json.dump(self.config, outfile, indent=4) except Exception as error: logging.error(error, exc_info=True)",
"stored. __instance = None @classmethod def getInstance(cls): \"\"\" Static access method. \"\"\" if"
] |
[
"every w in W[l],\", \"this method serves almost no purpose as it causes",
"W[l],\", \"this method serves almost no purpose as it causes neurons to perform",
"almost no purpose as it causes neurons to perform the same calculation in",
"__name__ == \"__main__\": print( \"Zero Initialization:\", \"Since the derivatives will remain same for",
"as it causes neurons to perform the same calculation in each iterations and",
"for every w in W[l],\", \"this method serves almost no purpose as it",
"\"this method serves almost no purpose as it causes neurons to perform the",
"it causes neurons to perform the same calculation in each iterations and produces",
"same for every w in W[l],\", \"this method serves almost no purpose as",
"\"__main__\": print( \"Zero Initialization:\", \"Since the derivatives will remain same for every w",
"== \"__main__\": print( \"Zero Initialization:\", \"Since the derivatives will remain same for every",
"will remain same for every w in W[l],\", \"this method serves almost no",
"method serves almost no purpose as it causes neurons to perform the same",
"Initialization:\", \"Since the derivatives will remain same for every w in W[l],\", \"this",
"if __name__ == \"__main__\": print( \"Zero Initialization:\", \"Since the derivatives will remain same",
"print( \"Zero Initialization:\", \"Since the derivatives will remain same for every w in",
"w in W[l],\", \"this method serves almost no purpose as it causes neurons",
"no purpose as it causes neurons to perform the same calculation in each",
"purpose as it causes neurons to perform the same calculation in each iterations",
"causes neurons to perform the same calculation in each iterations and produces same",
"neurons to perform the same calculation in each iterations and produces same outputs.\",",
"the derivatives will remain same for every w in W[l],\", \"this method serves",
"<reponame>coookie89/Intern-Training if __name__ == \"__main__\": print( \"Zero Initialization:\", \"Since the derivatives will remain",
"derivatives will remain same for every w in W[l],\", \"this method serves almost",
"serves almost no purpose as it causes neurons to perform the same calculation",
"in W[l],\", \"this method serves almost no purpose as it causes neurons to",
"\"Since the derivatives will remain same for every w in W[l],\", \"this method",
"to perform the same calculation in each iterations and produces same outputs.\", )",
"remain same for every w in W[l],\", \"this method serves almost no purpose",
"\"Zero Initialization:\", \"Since the derivatives will remain same for every w in W[l],\","
] |
[
"Escriba su codigo a partir de este punto <<< ## import pandas as",
"este punto <<< ## import pandas as pd import numpy as np import",
"## Construya una gráfica similar a la presentada en el archivo `original.png` ##",
"## ## Construya una gráfica similar a la presentada en el archivo `original.png`",
"partir de este punto <<< ## import pandas as pd import numpy as",
"generada debe salvarse en el ## archivo `generada.png`. ## ## Salve la figura",
"en el archivo `original.png` ## usando el archivo `data.csv`. La gráfica generada debe",
"= pd.read_csv('data.csv', sep=',') data = df.groupby('Region').sum()[['Poblacion 0-14', 'Poblacion 15-64', 'Poblacion 65+']] fig, axs",
"matplotlib as mpl import matplotlib.pyplot as plt df = pd.read_csv('data.csv', sep=',') data =",
"plt.setp(axs[0], ylabel='Poblacion') for index, region in enumerate(data.index): axs[index].bar(range(3), data.iloc[index,:], color=['tab:orange', 'tab:blue', 'tab:green']) for",
"color=['tab:orange', 'tab:blue', 'tab:green']) for n, ax in enumerate(axs): ax.set_xticks(range(3)); ax.set_xticklabels(data.columns, rotation=90); ax.set_title(data.index[n]); plt.tight_layout()",
"plt.subplots_adjust(wspace = 0.1, hspace=0.1) plt.setp(axs[0], ylabel='Poblacion') for index, region in enumerate(data.index): axs[index].bar(range(3), data.iloc[index,:],",
"Graficacion usando Matplotlib ## =========================================================================== ## ## Construya una gráfica similar a la",
"data.iloc[index,:], color=['tab:orange', 'tab:blue', 'tab:green']) for n, ax in enumerate(axs): ax.set_xticks(range(3)); ax.set_xticklabels(data.columns, rotation=90); ax.set_title(data.index[n]);",
"index, region in enumerate(data.index): axs[index].bar(range(3), data.iloc[index,:], color=['tab:orange', 'tab:blue', 'tab:green']) for n, ax in",
"Construya una gráfica similar a la presentada en el archivo `original.png` ## usando",
"salvarse en el ## archivo `generada.png`. ## ## Salve la figura al disco",
"una gráfica similar a la presentada en el archivo `original.png` ## usando el",
"0.1, hspace=0.1) plt.setp(axs[0], ylabel='Poblacion') for index, region in enumerate(data.index): axs[index].bar(range(3), data.iloc[index,:], color=['tab:orange', 'tab:blue',",
"enumerate(data.index): axs[index].bar(range(3), data.iloc[index,:], color=['tab:orange', 'tab:blue', 'tab:green']) for n, ax in enumerate(axs): ax.set_xticks(range(3)); ax.set_xticklabels(data.columns,",
"pd.read_csv('data.csv', sep=',') data = df.groupby('Region').sum()[['Poblacion 0-14', 'Poblacion 15-64', 'Poblacion 65+']] fig, axs =",
"La gráfica generada debe salvarse en el ## archivo `generada.png`. ## ## Salve",
"pd import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt",
"debe salvarse en el ## archivo `generada.png`. ## ## Salve la figura al",
"## =========================================================================== ## ## Construya una gráfica similar a la presentada en el",
"=========================================================================== ## ## Construya una gráfica similar a la presentada en el archivo",
"pandas as pd import numpy as np import matplotlib as mpl import matplotlib.pyplot",
"## ## >>> Escriba su codigo a partir de este punto <<< ##",
"codigo a partir de este punto <<< ## import pandas as pd import",
"axs[index].bar(range(3), data.iloc[index,:], color=['tab:orange', 'tab:blue', 'tab:green']) for n, ax in enumerate(axs): ax.set_xticks(range(3)); ax.set_xticklabels(data.columns, rotation=90);",
"df.groupby('Region').sum()[['Poblacion 0-14', 'Poblacion 15-64', 'Poblacion 65+']] fig, axs = plt.subplots(1, 6, sharex='col', sharey='row',",
"15-64', 'Poblacion 65+']] fig, axs = plt.subplots(1, 6, sharex='col', sharey='row', figsize=(13,6), dpi=72); plt.subplots_adjust(wspace",
"plt.subplots(1, 6, sharex='col', sharey='row', figsize=(13,6), dpi=72); plt.subplots_adjust(wspace = 0.1, hspace=0.1) plt.setp(axs[0], ylabel='Poblacion') for",
"= 0.1, hspace=0.1) plt.setp(axs[0], ylabel='Poblacion') for index, region in enumerate(data.index): axs[index].bar(range(3), data.iloc[index,:], color=['tab:orange',",
"su codigo a partir de este punto <<< ## import pandas as pd",
"plt df = pd.read_csv('data.csv', sep=',') data = df.groupby('Region').sum()[['Poblacion 0-14', 'Poblacion 15-64', 'Poblacion 65+']]",
">>> Escriba su codigo a partir de este punto <<< ## import pandas",
"import matplotlib as mpl import matplotlib.pyplot as plt df = pd.read_csv('data.csv', sep=',') data",
"archivo `data.csv`. La gráfica generada debe salvarse en el ## archivo `generada.png`. ##",
"## ## plt.savefig('generada.png') ## ## >>> Escriba su codigo a partir de este",
"hspace=0.1) plt.setp(axs[0], ylabel='Poblacion') for index, region in enumerate(data.index): axs[index].bar(range(3), data.iloc[index,:], color=['tab:orange', 'tab:blue', 'tab:green'])",
"figura al disco con: ## ## plt.savefig('generada.png') ## ## >>> Escriba su codigo",
"similar a la presentada en el archivo `original.png` ## usando el archivo `data.csv`.",
"gráfica generada debe salvarse en el ## archivo `generada.png`. ## ## Salve la",
"6, sharex='col', sharey='row', figsize=(13,6), dpi=72); plt.subplots_adjust(wspace = 0.1, hspace=0.1) plt.setp(axs[0], ylabel='Poblacion') for index,",
"de este punto <<< ## import pandas as pd import numpy as np",
"65+']] fig, axs = plt.subplots(1, 6, sharex='col', sharey='row', figsize=(13,6), dpi=72); plt.subplots_adjust(wspace = 0.1,",
"sharey='row', figsize=(13,6), dpi=72); plt.subplots_adjust(wspace = 0.1, hspace=0.1) plt.setp(axs[0], ylabel='Poblacion') for index, region in",
"el archivo `data.csv`. La gráfica generada debe salvarse en el ## archivo `generada.png`.",
"## Graficacion usando Matplotlib ## =========================================================================== ## ## Construya una gráfica similar a",
"punto <<< ## import pandas as pd import numpy as np import matplotlib",
"## usando el archivo `data.csv`. La gráfica generada debe salvarse en el ##",
"## import pandas as pd import numpy as np import matplotlib as mpl",
"numpy as np import matplotlib as mpl import matplotlib.pyplot as plt df =",
"a la presentada en el archivo `original.png` ## usando el archivo `data.csv`. La",
"## Salve la figura al disco con: ## ## plt.savefig('generada.png') ## ## >>>",
"presentada en el archivo `original.png` ## usando el archivo `data.csv`. La gráfica generada",
"import pandas as pd import numpy as np import matplotlib as mpl import",
"`original.png` ## usando el archivo `data.csv`. La gráfica generada debe salvarse en el",
"Salve la figura al disco con: ## ## plt.savefig('generada.png') ## ## >>> Escriba",
"## plt.savefig('generada.png') ## ## >>> Escriba su codigo a partir de este punto",
"a partir de este punto <<< ## import pandas as pd import numpy",
"<<< ## import pandas as pd import numpy as np import matplotlib as",
"dpi=72); plt.subplots_adjust(wspace = 0.1, hspace=0.1) plt.setp(axs[0], ylabel='Poblacion') for index, region in enumerate(data.index): axs[index].bar(range(3),",
"usando Matplotlib ## =========================================================================== ## ## Construya una gráfica similar a la presentada",
"axs = plt.subplots(1, 6, sharex='col', sharey='row', figsize=(13,6), dpi=72); plt.subplots_adjust(wspace = 0.1, hspace=0.1) plt.setp(axs[0],",
"'tab:blue', 'tab:green']) for n, ax in enumerate(axs): ax.set_xticks(range(3)); ax.set_xticklabels(data.columns, rotation=90); ax.set_title(data.index[n]); plt.tight_layout() plt.savefig('generada.png');",
"el archivo `original.png` ## usando el archivo `data.csv`. La gráfica generada debe salvarse",
"import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt df",
"as mpl import matplotlib.pyplot as plt df = pd.read_csv('data.csv', sep=',') data = df.groupby('Region').sum()[['Poblacion",
"Matplotlib ## =========================================================================== ## ## Construya una gráfica similar a la presentada en",
"sep=',') data = df.groupby('Region').sum()[['Poblacion 0-14', 'Poblacion 15-64', 'Poblacion 65+']] fig, axs = plt.subplots(1,",
"sharex='col', sharey='row', figsize=(13,6), dpi=72); plt.subplots_adjust(wspace = 0.1, hspace=0.1) plt.setp(axs[0], ylabel='Poblacion') for index, region",
"## ## Graficacion usando Matplotlib ## =========================================================================== ## ## Construya una gráfica similar",
"as np import matplotlib as mpl import matplotlib.pyplot as plt df = pd.read_csv('data.csv',",
"df = pd.read_csv('data.csv', sep=',') data = df.groupby('Region').sum()[['Poblacion 0-14', 'Poblacion 15-64', 'Poblacion 65+']] fig,",
"np import matplotlib as mpl import matplotlib.pyplot as plt df = pd.read_csv('data.csv', sep=',')",
"disco con: ## ## plt.savefig('generada.png') ## ## >>> Escriba su codigo a partir",
"ylabel='Poblacion') for index, region in enumerate(data.index): axs[index].bar(range(3), data.iloc[index,:], color=['tab:orange', 'tab:blue', 'tab:green']) for n,",
"archivo `generada.png`. ## ## Salve la figura al disco con: ## ## plt.savefig('generada.png')",
"en el ## archivo `generada.png`. ## ## Salve la figura al disco con:",
"plt.savefig('generada.png') ## ## >>> Escriba su codigo a partir de este punto <<<",
"`data.csv`. La gráfica generada debe salvarse en el ## archivo `generada.png`. ## ##",
"con: ## ## plt.savefig('generada.png') ## ## >>> Escriba su codigo a partir de",
"fig, axs = plt.subplots(1, 6, sharex='col', sharey='row', figsize=(13,6), dpi=72); plt.subplots_adjust(wspace = 0.1, hspace=0.1)",
"for index, region in enumerate(data.index): axs[index].bar(range(3), data.iloc[index,:], color=['tab:orange', 'tab:blue', 'tab:green']) for n, ax",
"el ## archivo `generada.png`. ## ## Salve la figura al disco con: ##",
"'Poblacion 65+']] fig, axs = plt.subplots(1, 6, sharex='col', sharey='row', figsize=(13,6), dpi=72); plt.subplots_adjust(wspace =",
"archivo `original.png` ## usando el archivo `data.csv`. La gráfica generada debe salvarse en",
"figsize=(13,6), dpi=72); plt.subplots_adjust(wspace = 0.1, hspace=0.1) plt.setp(axs[0], ylabel='Poblacion') for index, region in enumerate(data.index):",
"la presentada en el archivo `original.png` ## usando el archivo `data.csv`. La gráfica",
"## archivo `generada.png`. ## ## Salve la figura al disco con: ## ##",
"import matplotlib.pyplot as plt df = pd.read_csv('data.csv', sep=',') data = df.groupby('Region').sum()[['Poblacion 0-14', 'Poblacion",
"## >>> Escriba su codigo a partir de este punto <<< ## import",
"mpl import matplotlib.pyplot as plt df = pd.read_csv('data.csv', sep=',') data = df.groupby('Region').sum()[['Poblacion 0-14',",
"usando el archivo `data.csv`. La gráfica generada debe salvarse en el ## archivo",
"al disco con: ## ## plt.savefig('generada.png') ## ## >>> Escriba su codigo a",
"'Poblacion 15-64', 'Poblacion 65+']] fig, axs = plt.subplots(1, 6, sharex='col', sharey='row', figsize=(13,6), dpi=72);",
"matplotlib.pyplot as plt df = pd.read_csv('data.csv', sep=',') data = df.groupby('Region').sum()[['Poblacion 0-14', 'Poblacion 15-64',",
"as plt df = pd.read_csv('data.csv', sep=',') data = df.groupby('Region').sum()[['Poblacion 0-14', 'Poblacion 15-64', 'Poblacion",
"0-14', 'Poblacion 15-64', 'Poblacion 65+']] fig, axs = plt.subplots(1, 6, sharex='col', sharey='row', figsize=(13,6),",
"## ## Salve la figura al disco con: ## ## plt.savefig('generada.png') ## ##",
"= df.groupby('Region').sum()[['Poblacion 0-14', 'Poblacion 15-64', 'Poblacion 65+']] fig, axs = plt.subplots(1, 6, sharex='col',",
"as pd import numpy as np import matplotlib as mpl import matplotlib.pyplot as",
"in enumerate(data.index): axs[index].bar(range(3), data.iloc[index,:], color=['tab:orange', 'tab:blue', 'tab:green']) for n, ax in enumerate(axs): ax.set_xticks(range(3));",
"`generada.png`. ## ## Salve la figura al disco con: ## ## plt.savefig('generada.png') ##",
"= plt.subplots(1, 6, sharex='col', sharey='row', figsize=(13,6), dpi=72); plt.subplots_adjust(wspace = 0.1, hspace=0.1) plt.setp(axs[0], ylabel='Poblacion')",
"la figura al disco con: ## ## plt.savefig('generada.png') ## ## >>> Escriba su",
"gráfica similar a la presentada en el archivo `original.png` ## usando el archivo",
"data = df.groupby('Region').sum()[['Poblacion 0-14', 'Poblacion 15-64', 'Poblacion 65+']] fig, axs = plt.subplots(1, 6,",
"region in enumerate(data.index): axs[index].bar(range(3), data.iloc[index,:], color=['tab:orange', 'tab:blue', 'tab:green']) for n, ax in enumerate(axs):"
] |
[
"user_text = dict(zip(keys, row[1:])) write_config_file( user_text, file_name + \".pickle\", directory=\"Resources/Languages/\" + language) #==============================================================================",
"file_name + \".pickle\", directory=\"Resources/Languages/\" + language) #============================================================================== def generate_keys(pattern): keys = list() for",
"with open(\"data/\" + file_name + \".csv\", \"rb\") as csvfile: table = csv.reader(csvfile) for",
"#============================================================================== def generate_tool_tips_keys(): return generate_keys(\"TOOL_TIP\") #============================================================================== def write_user_text(): write_user_strings(\"UserText\", generate_user_text_keys()) #============================================================================== def write_tool_tips():",
"generate_keys(\"USER_TEXT\") #============================================================================== def generate_tool_tips_keys(): return generate_keys(\"TOOL_TIP\") #============================================================================== def write_user_text(): write_user_strings(\"UserText\", generate_user_text_keys()) #============================================================================== def",
"it will not be included in the program it #D is just for",
"os import csv import pickle import sys import re # local imports OPTIONS",
"file_name + \".csv\", \"rb\") as csvfile: table = csv.reader(csvfile) for i, row in",
"for adding/changing options in the standard Options.pickle file. # # python imports from",
"adding/changing options in the standard Options.pickle file. # # python imports from __future__",
"\"en_GB\", \"available_languages\": [\"en_GB\", \"de_DE\", \"en_AU\", \"en_US\", \"fr_FR\"], } TEST_OPTIONS = { \"code_css\": \"\",",
"user_text, file_name + \".pickle\", directory=\"Resources/Languages/\" + language) #============================================================================== def generate_keys(pattern): keys = list()",
"def generate_tool_tips_keys(): return generate_keys(\"TOOL_TIP\") #============================================================================== def write_user_text(): write_user_strings(\"UserText\", generate_user_text_keys()) #============================================================================== def write_tool_tips(): write_user_strings(\"ToolTips\",",
"return keys #============================================================================== def generate_user_text_keys(): return generate_keys(\"USER_TEXT\") #============================================================================== def generate_tool_tips_keys(): return generate_keys(\"TOOL_TIP\") #==============================================================================",
"lines = py_file.readlines() for line in lines: if (pattern.lower() in line.lower()): match =",
"DGC # #D This is purely for developer use, it will not be",
"#============================================================================== def write_tool_tips(): write_user_strings(\"ToolTips\", generate_tool_tips_keys()) #============================================================================== if (__name__ == \"__main__\"): write_options_files() write_user_text() write_tool_tips()",
"by: DGC # #D This is purely for developer use, it will not",
"# \"language\": \"en_GB\", } #============================================================================== def write_config_file(object, file_name, directory=\"Resources\"): \"\"\" Pickles the object",
"} #============================================================================== def write_config_file(object, file_name, directory=\"Resources\"): \"\"\" Pickles the object to file_name where",
"imports OPTIONS = { \"code_css\": \"Standard\", \"code_css_class\": \"highlight\", \"show_html\": False, \"processor\": \"markdown_all\", \"markdown_css\":",
"Pickles the object to file_name where file_name is a relative path under Resources",
") file_path = os.path.join(options_path, file_name) with open(file_path, \"wb\") as options_file: pickle.dump(object, options_file) #==============================================================================",
"for k in keys if k not in verifier] if (difference): raise Exception(",
"file_name) with open(file_path, \"wb\") as options_file: pickle.dump(object, options_file) #============================================================================== def write_options_files(): write_config_file(OPTIONS, \"Options.pickle\")",
"False, \"processor\": \"markdown_all\", \"markdown_css\": \"\", \"display_line_numbers\": False, \"font\": \"Arial,12,-1,5,50,0,0,0,0,0\", # \"language\": \"en_GB\", }",
"to file_name where file_name is a relative path under Resources \"\"\" options_path =",
"} TEST_OPTIONS = { \"code_css\": \"\", \"code_css_class\": \"highlight\", \"show_html\": False, \"processor\": \"markdown_all\", \"markdown_css\":",
"\"\"\" options_path = os.path.join( os.path.dirname(sys.argv[0]), \"../\" + directory ) file_path = os.path.join(options_path, file_name)",
"\"en_AU\", \"en_US\", \"fr_FR\"], } TEST_OPTIONS = { \"code_css\": \"\", \"code_css_class\": \"highlight\", \"show_html\": False,",
"raise Exception( \"Bad key found in %s: %s\" %(file_name, str(difference)) ) #============================================================================== def",
"row in enumerate(table): if (i == 0): keys = row[1:] verify_keys(file_name, keys, verifier)",
"lines: if (pattern.lower() in line.lower()): match = re.search(\".*\" + pattern + \"\\[\\\"(.*)\\\"\\]\", line)",
"imports from __future__ import unicode_literals import os import csv import pickle import sys",
"+ \".csv\", \"rb\") as csvfile: table = csv.reader(csvfile) for i, row in enumerate(table):",
"path in os.listdir(\".\"): if (path[-3:] == \".py\"): with open(path, \"r\") as py_file: lines",
"= row[1:] verify_keys(file_name, keys, verifier) continue language = row[0] user_text = dict(zip(keys, row[1:]))",
"\"show_html\": False, \"processor\": \"markdown_all\", \"markdown_css\": \"\", \"display_line_numbers\": False, \"font\": \"Arial,12,-1,5,50,0,0,0,0,0\", # \"language\": \"en_GB\",",
"= dict(zip(keys, row[1:])) write_config_file( user_text, file_name + \".pickle\", directory=\"Resources/Languages/\" + language) #============================================================================== def",
"in the standard Options.pickle file. # # python imports from __future__ import unicode_literals",
"line.lower()): match = re.search(\".*\" + pattern + \"\\[\\\"(.*)\\\"\\]\", line) if match: keys.append(match.group(1)) return",
"pattern + \"\\[\\\"(.*)\\\"\\]\", line) if match: keys.append(match.group(1)) return keys #============================================================================== def generate_user_text_keys(): return",
"\"\", \"code_css_class\": \"highlight\", \"show_html\": False, \"processor\": \"markdown_all\", \"markdown_css\": \"\", \"display_line_numbers\": False, \"font\": \"Arial,12,-1,5,50,0,0,0,0,0\",",
"keys, verifier) continue language = row[0] user_text = dict(zip(keys, row[1:])) write_config_file( user_text, file_name",
"import re # local imports OPTIONS = { \"code_css\": \"Standard\", \"code_css_class\": \"highlight\", \"show_html\":",
"} LOCALISATION_OPTIONS = { \"language\": \"en_GB\", \"available_languages\": [\"en_GB\", \"de_DE\", \"en_AU\", \"en_US\", \"fr_FR\"], }",
"Exception( \"Bad key found in %s: %s\" %(file_name, str(difference)) ) #============================================================================== def write_user_strings(file_name,",
"\"code_css_class\": \"highlight\", \"show_html\": False, \"processor\": \"markdown_all\", \"markdown_css\": \"Markdown\", \"display_line_numbers\": False, \"font\": \"Arial,12,-1,5,50,0,0,0,0,0\", }",
"set(keys) verifier = set(verifier) difference = [k for k in keys if k",
"[k for k in keys if k not in verifier] if (difference): raise",
"%(file_name, str(difference)) ) #============================================================================== def write_user_strings(file_name, verifier): with open(\"data/\" + file_name + \".csv\",",
"in os.listdir(\".\"): if (path[-3:] == \".py\"): with open(path, \"r\") as py_file: lines =",
"key found in %s: %s\" %(file_name, str(difference)) ) #============================================================================== def write_user_strings(file_name, verifier): with",
"file_name, directory=\"Resources\"): \"\"\" Pickles the object to file_name where file_name is a relative",
"(path[-3:] == \".py\"): with open(path, \"r\") as py_file: lines = py_file.readlines() for line",
"\"rb\") as csvfile: table = csv.reader(csvfile) for i, row in enumerate(table): if (i",
"import os import csv import pickle import sys import re # local imports",
"for developer use, it will not be included in the program it #D",
"directory=\"Resources/Languages\" ) write_config_file(TEST_OPTIONS, \"Options.pickle\", directory=\"Integration\") #============================================================================== def verify_keys(file_name, keys, verifier): keys = set(keys)",
"in verifier] if (difference): raise Exception( \"Bad key found in %s: %s\" %(file_name,",
"pickle import sys import re # local imports OPTIONS = { \"code_css\": \"Standard\",",
"continue language = row[0] user_text = dict(zip(keys, row[1:])) write_config_file( user_text, file_name + \".pickle\",",
"write_config_file( user_text, file_name + \".pickle\", directory=\"Resources/Languages/\" + language) #============================================================================== def generate_keys(pattern): keys =",
"#============================================================================== def write_user_strings(file_name, verifier): with open(\"data/\" + file_name + \".csv\", \"rb\") as csvfile:",
"if (pattern.lower() in line.lower()): match = re.search(\".*\" + pattern + \"\\[\\\"(.*)\\\"\\]\", line) if",
"\"processor\": \"markdown_all\", \"markdown_css\": \"Markdown\", \"display_line_numbers\": False, \"font\": \"Arial,12,-1,5,50,0,0,0,0,0\", } LOCALISATION_OPTIONS = { \"language\":",
"\"code_css\": \"Standard\", \"code_css_class\": \"highlight\", \"show_html\": False, \"processor\": \"markdown_all\", \"markdown_css\": \"Markdown\", \"display_line_numbers\": False, \"font\":",
"{ \"code_css\": \"\", \"code_css_class\": \"highlight\", \"show_html\": False, \"processor\": \"markdown_all\", \"markdown_css\": \"\", \"display_line_numbers\": False,",
"\"wb\") as options_file: pickle.dump(object, options_file) #============================================================================== def write_options_files(): write_config_file(OPTIONS, \"Options.pickle\") write_config_file( LOCALISATION_OPTIONS, \"Languages.pickle\",",
"= row[0] user_text = dict(zip(keys, row[1:])) write_config_file( user_text, file_name + \".pickle\", directory=\"Resources/Languages/\" +",
"str(difference)) ) #============================================================================== def write_user_strings(file_name, verifier): with open(\"data/\" + file_name + \".csv\", \"rb\")",
"directory=\"Resources/Languages/\" + language) #============================================================================== def generate_keys(pattern): keys = list() for path in os.listdir(\".\"):",
"def write_config_file(object, file_name, directory=\"Resources\"): \"\"\" Pickles the object to file_name where file_name is",
"language) #============================================================================== def generate_keys(pattern): keys = list() for path in os.listdir(\".\"): if (path[-3:]",
"\".py\"): with open(path, \"r\") as py_file: lines = py_file.readlines() for line in lines:",
"line) if match: keys.append(match.group(1)) return keys #============================================================================== def generate_user_text_keys(): return generate_keys(\"USER_TEXT\") #============================================================================== def",
"def generate_user_text_keys(): return generate_keys(\"USER_TEXT\") #============================================================================== def generate_tool_tips_keys(): return generate_keys(\"TOOL_TIP\") #============================================================================== def write_user_text(): write_user_strings(\"UserText\",",
"the standard Options.pickle file. # # python imports from __future__ import unicode_literals import",
"not in verifier] if (difference): raise Exception( \"Bad key found in %s: %s\"",
"This is purely for developer use, it will not be included in the",
"directory ) file_path = os.path.join(options_path, file_name) with open(file_path, \"wb\") as options_file: pickle.dump(object, options_file)",
"= set(verifier) difference = [k for k in keys if k not in",
"#============================================================================== def generate_user_text_keys(): return generate_keys(\"USER_TEXT\") #============================================================================== def generate_tool_tips_keys(): return generate_keys(\"TOOL_TIP\") #============================================================================== def write_user_text():",
"as py_file: lines = py_file.readlines() for line in lines: if (pattern.lower() in line.lower()):",
"row[0] user_text = dict(zip(keys, row[1:])) write_config_file( user_text, file_name + \".pickle\", directory=\"Resources/Languages/\" + language)",
"options_file: pickle.dump(object, options_file) #============================================================================== def write_options_files(): write_config_file(OPTIONS, \"Options.pickle\") write_config_file( LOCALISATION_OPTIONS, \"Languages.pickle\", directory=\"Resources/Languages\" )",
"the program it #D is just for adding/changing options in the standard Options.pickle",
"os.path.join( os.path.dirname(sys.argv[0]), \"../\" + directory ) file_path = os.path.join(options_path, file_name) with open(file_path, \"wb\")",
"def generate_keys(pattern): keys = list() for path in os.listdir(\".\"): if (path[-3:] == \".py\"):",
"\"code_css\": \"\", \"code_css_class\": \"highlight\", \"show_html\": False, \"processor\": \"markdown_all\", \"markdown_css\": \"\", \"display_line_numbers\": False, \"font\":",
"match = re.search(\".*\" + pattern + \"\\[\\\"(.*)\\\"\\]\", line) if match: keys.append(match.group(1)) return keys",
"os.path.join(options_path, file_name) with open(file_path, \"wb\") as options_file: pickle.dump(object, options_file) #============================================================================== def write_options_files(): write_config_file(OPTIONS,",
"write_config_file(object, file_name, directory=\"Resources\"): \"\"\" Pickles the object to file_name where file_name is a",
"\"fr_FR\"], } TEST_OPTIONS = { \"code_css\": \"\", \"code_css_class\": \"highlight\", \"show_html\": False, \"processor\": \"markdown_all\",",
"# # python imports from __future__ import unicode_literals import os import csv import",
"\"\"\" Pickles the object to file_name where file_name is a relative path under",
"open(file_path, \"wb\") as options_file: pickle.dump(object, options_file) #============================================================================== def write_options_files(): write_config_file(OPTIONS, \"Options.pickle\") write_config_file( LOCALISATION_OPTIONS,",
"is just for adding/changing options in the standard Options.pickle file. # # python",
"#============================================================================== def verify_keys(file_name, keys, verifier): keys = set(keys) verifier = set(verifier) difference =",
"= py_file.readlines() for line in lines: if (pattern.lower() in line.lower()): match = re.search(\".*\"",
"\"en_US\", \"fr_FR\"], } TEST_OPTIONS = { \"code_css\": \"\", \"code_css_class\": \"highlight\", \"show_html\": False, \"processor\":",
"is purely for developer use, it will not be included in the program",
"options in the standard Options.pickle file. # # python imports from __future__ import",
"\"Arial,12,-1,5,50,0,0,0,0,0\", } LOCALISATION_OPTIONS = { \"language\": \"en_GB\", \"available_languages\": [\"en_GB\", \"de_DE\", \"en_AU\", \"en_US\", \"fr_FR\"],",
"\"en_GB\", } #============================================================================== def write_config_file(object, file_name, directory=\"Resources\"): \"\"\" Pickles the object to file_name",
"\"../\" + directory ) file_path = os.path.join(options_path, file_name) with open(file_path, \"wb\") as options_file:",
"= set(keys) verifier = set(verifier) difference = [k for k in keys if",
"csv.reader(csvfile) for i, row in enumerate(table): if (i == 0): keys = row[1:]",
"\"language\": \"en_GB\", \"available_languages\": [\"en_GB\", \"de_DE\", \"en_AU\", \"en_US\", \"fr_FR\"], } TEST_OPTIONS = { \"code_css\":",
"Options.pickle file. # # python imports from __future__ import unicode_literals import os import",
"keys if k not in verifier] if (difference): raise Exception( \"Bad key found",
"\"Standard\", \"code_css_class\": \"highlight\", \"show_html\": False, \"processor\": \"markdown_all\", \"markdown_css\": \"Markdown\", \"display_line_numbers\": False, \"font\": \"Arial,12,-1,5,50,0,0,0,0,0\",",
") #============================================================================== def write_user_strings(file_name, verifier): with open(\"data/\" + file_name + \".csv\", \"rb\") as",
"= [k for k in keys if k not in verifier] if (difference):",
"csvfile: table = csv.reader(csvfile) for i, row in enumerate(table): if (i == 0):",
"re # local imports OPTIONS = { \"code_css\": \"Standard\", \"code_css_class\": \"highlight\", \"show_html\": False,",
"def verify_keys(file_name, keys, verifier): keys = set(keys) verifier = set(verifier) difference = [k",
"for path in os.listdir(\".\"): if (path[-3:] == \".py\"): with open(path, \"r\") as py_file:",
"\"display_line_numbers\": False, \"font\": \"Arial,12,-1,5,50,0,0,0,0,0\", # \"language\": \"en_GB\", } #============================================================================== def write_config_file(object, file_name, directory=\"Resources\"):",
"\"\", \"display_line_numbers\": False, \"font\": \"Arial,12,-1,5,50,0,0,0,0,0\", # \"language\": \"en_GB\", } #============================================================================== def write_config_file(object, file_name,",
"under Resources \"\"\" options_path = os.path.join( os.path.dirname(sys.argv[0]), \"../\" + directory ) file_path =",
"def write_options_files(): write_config_file(OPTIONS, \"Options.pickle\") write_config_file( LOCALISATION_OPTIONS, \"Languages.pickle\", directory=\"Resources/Languages\" ) write_config_file(TEST_OPTIONS, \"Options.pickle\", directory=\"Integration\") #==============================================================================",
"def write_user_strings(file_name, verifier): with open(\"data/\" + file_name + \".csv\", \"rb\") as csvfile: table",
"re.search(\".*\" + pattern + \"\\[\\\"(.*)\\\"\\]\", line) if match: keys.append(match.group(1)) return keys #============================================================================== def",
"generate_user_text_keys()) #============================================================================== def write_tool_tips(): write_user_strings(\"ToolTips\", generate_tool_tips_keys()) #============================================================================== if (__name__ == \"__main__\"): write_options_files() write_user_text()",
"LOCALISATION_OPTIONS, \"Languages.pickle\", directory=\"Resources/Languages\" ) write_config_file(TEST_OPTIONS, \"Options.pickle\", directory=\"Integration\") #============================================================================== def verify_keys(file_name, keys, verifier): keys",
"in %s: %s\" %(file_name, str(difference)) ) #============================================================================== def write_user_strings(file_name, verifier): with open(\"data/\" +",
"[\"en_GB\", \"de_DE\", \"en_AU\", \"en_US\", \"fr_FR\"], } TEST_OPTIONS = { \"code_css\": \"\", \"code_css_class\": \"highlight\",",
"in keys if k not in verifier] if (difference): raise Exception( \"Bad key",
"\"markdown_css\": \"Markdown\", \"display_line_numbers\": False, \"font\": \"Arial,12,-1,5,50,0,0,0,0,0\", } LOCALISATION_OPTIONS = { \"language\": \"en_GB\", \"available_languages\":",
"\"display_line_numbers\": False, \"font\": \"Arial,12,-1,5,50,0,0,0,0,0\", } LOCALISATION_OPTIONS = { \"language\": \"en_GB\", \"available_languages\": [\"en_GB\", \"de_DE\",",
"LOCALISATION_OPTIONS = { \"language\": \"en_GB\", \"available_languages\": [\"en_GB\", \"de_DE\", \"en_AU\", \"en_US\", \"fr_FR\"], } TEST_OPTIONS",
"#============================================================================== def write_config_file(object, file_name, directory=\"Resources\"): \"\"\" Pickles the object to file_name where file_name",
"if (i == 0): keys = row[1:] verify_keys(file_name, keys, verifier) continue language =",
"generate_keys(pattern): keys = list() for path in os.listdir(\".\"): if (path[-3:] == \".py\"): with",
"\"processor\": \"markdown_all\", \"markdown_css\": \"\", \"display_line_numbers\": False, \"font\": \"Arial,12,-1,5,50,0,0,0,0,0\", # \"language\": \"en_GB\", } #==============================================================================",
"verifier) continue language = row[0] user_text = dict(zip(keys, row[1:])) write_config_file( user_text, file_name +",
"for i, row in enumerate(table): if (i == 0): keys = row[1:] verify_keys(file_name,",
"dict(zip(keys, row[1:])) write_config_file( user_text, file_name + \".pickle\", directory=\"Resources/Languages/\" + language) #============================================================================== def generate_keys(pattern):",
"\"font\": \"Arial,12,-1,5,50,0,0,0,0,0\", } LOCALISATION_OPTIONS = { \"language\": \"en_GB\", \"available_languages\": [\"en_GB\", \"de_DE\", \"en_AU\", \"en_US\",",
"+ \"\\[\\\"(.*)\\\"\\]\", line) if match: keys.append(match.group(1)) return keys #============================================================================== def generate_user_text_keys(): return generate_keys(\"USER_TEXT\")",
"#============================================================================== def write_user_text(): write_user_strings(\"UserText\", generate_user_text_keys()) #============================================================================== def write_tool_tips(): write_user_strings(\"ToolTips\", generate_tool_tips_keys()) #============================================================================== if (__name__",
"not be included in the program it #D is just for adding/changing options",
"keys = row[1:] verify_keys(file_name, keys, verifier) continue language = row[0] user_text = dict(zip(keys,",
"enumerate(table): if (i == 0): keys = row[1:] verify_keys(file_name, keys, verifier) continue language",
"OPTIONS = { \"code_css\": \"Standard\", \"code_css_class\": \"highlight\", \"show_html\": False, \"processor\": \"markdown_all\", \"markdown_css\": \"Markdown\",",
"keys = set(keys) verifier = set(verifier) difference = [k for k in keys",
"== 0): keys = row[1:] verify_keys(file_name, keys, verifier) continue language = row[0] user_text",
"with open(file_path, \"wb\") as options_file: pickle.dump(object, options_file) #============================================================================== def write_options_files(): write_config_file(OPTIONS, \"Options.pickle\") write_config_file(",
"write_config_file( LOCALISATION_OPTIONS, \"Languages.pickle\", directory=\"Resources/Languages\" ) write_config_file(TEST_OPTIONS, \"Options.pickle\", directory=\"Integration\") #============================================================================== def verify_keys(file_name, keys, verifier):",
"\"highlight\", \"show_html\": False, \"processor\": \"markdown_all\", \"markdown_css\": \"\", \"display_line_numbers\": False, \"font\": \"Arial,12,-1,5,50,0,0,0,0,0\", # \"language\":",
"verifier): keys = set(keys) verifier = set(verifier) difference = [k for k in",
"python # Written by: DGC # #D This is purely for developer use,",
"\"Arial,12,-1,5,50,0,0,0,0,0\", # \"language\": \"en_GB\", } #============================================================================== def write_config_file(object, file_name, directory=\"Resources\"): \"\"\" Pickles the",
"\"font\": \"Arial,12,-1,5,50,0,0,0,0,0\", # \"language\": \"en_GB\", } #============================================================================== def write_config_file(object, file_name, directory=\"Resources\"): \"\"\" Pickles",
"k in keys if k not in verifier] if (difference): raise Exception( \"Bad",
"write_config_file(TEST_OPTIONS, \"Options.pickle\", directory=\"Integration\") #============================================================================== def verify_keys(file_name, keys, verifier): keys = set(keys) verifier =",
"table = csv.reader(csvfile) for i, row in enumerate(table): if (i == 0): keys",
"sys import re # local imports OPTIONS = { \"code_css\": \"Standard\", \"code_css_class\": \"highlight\",",
"use, it will not be included in the program it #D is just",
"\"code_css_class\": \"highlight\", \"show_html\": False, \"processor\": \"markdown_all\", \"markdown_css\": \"\", \"display_line_numbers\": False, \"font\": \"Arial,12,-1,5,50,0,0,0,0,0\", #",
"from __future__ import unicode_literals import os import csv import pickle import sys import",
"\"markdown_all\", \"markdown_css\": \"\", \"display_line_numbers\": False, \"font\": \"Arial,12,-1,5,50,0,0,0,0,0\", # \"language\": \"en_GB\", } #============================================================================== def",
"keys = list() for path in os.listdir(\".\"): if (path[-3:] == \".py\"): with open(path,",
"= os.path.join( os.path.dirname(sys.argv[0]), \"../\" + directory ) file_path = os.path.join(options_path, file_name) with open(file_path,",
"directory=\"Integration\") #============================================================================== def verify_keys(file_name, keys, verifier): keys = set(keys) verifier = set(verifier) difference",
"program it #D is just for adding/changing options in the standard Options.pickle file.",
"False, \"font\": \"Arial,12,-1,5,50,0,0,0,0,0\", } LOCALISATION_OPTIONS = { \"language\": \"en_GB\", \"available_languages\": [\"en_GB\", \"de_DE\", \"en_AU\",",
"write_config_file(OPTIONS, \"Options.pickle\") write_config_file( LOCALISATION_OPTIONS, \"Languages.pickle\", directory=\"Resources/Languages\" ) write_config_file(TEST_OPTIONS, \"Options.pickle\", directory=\"Integration\") #============================================================================== def verify_keys(file_name,",
"be included in the program it #D is just for adding/changing options in",
"\"Options.pickle\") write_config_file( LOCALISATION_OPTIONS, \"Languages.pickle\", directory=\"Resources/Languages\" ) write_config_file(TEST_OPTIONS, \"Options.pickle\", directory=\"Integration\") #============================================================================== def verify_keys(file_name, keys,",
"language = row[0] user_text = dict(zip(keys, row[1:])) write_config_file( user_text, file_name + \".pickle\", directory=\"Resources/Languages/\"",
"\"markdown_all\", \"markdown_css\": \"Markdown\", \"display_line_numbers\": False, \"font\": \"Arial,12,-1,5,50,0,0,0,0,0\", } LOCALISATION_OPTIONS = { \"language\": \"en_GB\",",
"TEST_OPTIONS = { \"code_css\": \"\", \"code_css_class\": \"highlight\", \"show_html\": False, \"processor\": \"markdown_all\", \"markdown_css\": \"\",",
"difference = [k for k in keys if k not in verifier] if",
"verify_keys(file_name, keys, verifier): keys = set(keys) verifier = set(verifier) difference = [k for",
"\"language\": \"en_GB\", } #============================================================================== def write_config_file(object, file_name, directory=\"Resources\"): \"\"\" Pickles the object to",
"import sys import re # local imports OPTIONS = { \"code_css\": \"Standard\", \"code_css_class\":",
"pickle.dump(object, options_file) #============================================================================== def write_options_files(): write_config_file(OPTIONS, \"Options.pickle\") write_config_file( LOCALISATION_OPTIONS, \"Languages.pickle\", directory=\"Resources/Languages\" ) write_config_file(TEST_OPTIONS,",
"write_user_strings(file_name, verifier): with open(\"data/\" + file_name + \".csv\", \"rb\") as csvfile: table =",
"== \".py\"): with open(path, \"r\") as py_file: lines = py_file.readlines() for line in",
"(pattern.lower() in line.lower()): match = re.search(\".*\" + pattern + \"\\[\\\"(.*)\\\"\\]\", line) if match:",
"Written by: DGC # #D This is purely for developer use, it will",
"open(\"data/\" + file_name + \".csv\", \"rb\") as csvfile: table = csv.reader(csvfile) for i,",
"will not be included in the program it #D is just for adding/changing",
"= { \"code_css\": \"Standard\", \"code_css_class\": \"highlight\", \"show_html\": False, \"processor\": \"markdown_all\", \"markdown_css\": \"Markdown\", \"display_line_numbers\":",
"%s: %s\" %(file_name, str(difference)) ) #============================================================================== def write_user_strings(file_name, verifier): with open(\"data/\" + file_name",
"+ directory ) file_path = os.path.join(options_path, file_name) with open(file_path, \"wb\") as options_file: pickle.dump(object,",
"file_name is a relative path under Resources \"\"\" options_path = os.path.join( os.path.dirname(sys.argv[0]), \"../\"",
"#D is just for adding/changing options in the standard Options.pickle file. # #",
"\"de_DE\", \"en_AU\", \"en_US\", \"fr_FR\"], } TEST_OPTIONS = { \"code_css\": \"\", \"code_css_class\": \"highlight\", \"show_html\":",
"row[1:])) write_config_file( user_text, file_name + \".pickle\", directory=\"Resources/Languages/\" + language) #============================================================================== def generate_keys(pattern): keys",
"= list() for path in os.listdir(\".\"): if (path[-3:] == \".py\"): with open(path, \"r\")",
"Resources \"\"\" options_path = os.path.join( os.path.dirname(sys.argv[0]), \"../\" + directory ) file_path = os.path.join(options_path,",
") write_config_file(TEST_OPTIONS, \"Options.pickle\", directory=\"Integration\") #============================================================================== def verify_keys(file_name, keys, verifier): keys = set(keys) verifier",
"in the program it #D is just for adding/changing options in the standard",
"relative path under Resources \"\"\" options_path = os.path.join( os.path.dirname(sys.argv[0]), \"../\" + directory )",
"__future__ import unicode_literals import os import csv import pickle import sys import re",
"\"Markdown\", \"display_line_numbers\": False, \"font\": \"Arial,12,-1,5,50,0,0,0,0,0\", } LOCALISATION_OPTIONS = { \"language\": \"en_GB\", \"available_languages\": [\"en_GB\",",
"file_name where file_name is a relative path under Resources \"\"\" options_path = os.path.join(",
"options_file) #============================================================================== def write_options_files(): write_config_file(OPTIONS, \"Options.pickle\") write_config_file( LOCALISATION_OPTIONS, \"Languages.pickle\", directory=\"Resources/Languages\" ) write_config_file(TEST_OPTIONS, \"Options.pickle\",",
"\".csv\", \"rb\") as csvfile: table = csv.reader(csvfile) for i, row in enumerate(table): if",
"= csv.reader(csvfile) for i, row in enumerate(table): if (i == 0): keys =",
"keys.append(match.group(1)) return keys #============================================================================== def generate_user_text_keys(): return generate_keys(\"USER_TEXT\") #============================================================================== def generate_tool_tips_keys(): return generate_keys(\"TOOL_TIP\")",
"keys #============================================================================== def generate_user_text_keys(): return generate_keys(\"USER_TEXT\") #============================================================================== def generate_tool_tips_keys(): return generate_keys(\"TOOL_TIP\") #============================================================================== def",
"csv import pickle import sys import re # local imports OPTIONS = {",
"options_path = os.path.join( os.path.dirname(sys.argv[0]), \"../\" + directory ) file_path = os.path.join(options_path, file_name) with",
"#D This is purely for developer use, it will not be included in",
"return generate_keys(\"TOOL_TIP\") #============================================================================== def write_user_text(): write_user_strings(\"UserText\", generate_user_text_keys()) #============================================================================== def write_tool_tips(): write_user_strings(\"ToolTips\", generate_tool_tips_keys()) #==============================================================================",
"#!/usr/bin/env python # Written by: DGC # #D This is purely for developer",
"purely for developer use, it will not be included in the program it",
"# local imports OPTIONS = { \"code_css\": \"Standard\", \"code_css_class\": \"highlight\", \"show_html\": False, \"processor\":",
"= os.path.join(options_path, file_name) with open(file_path, \"wb\") as options_file: pickle.dump(object, options_file) #============================================================================== def write_options_files():",
"%s\" %(file_name, str(difference)) ) #============================================================================== def write_user_strings(file_name, verifier): with open(\"data/\" + file_name +",
"os.listdir(\".\"): if (path[-3:] == \".py\"): with open(path, \"r\") as py_file: lines = py_file.readlines()",
"file_path = os.path.join(options_path, file_name) with open(file_path, \"wb\") as options_file: pickle.dump(object, options_file) #============================================================================== def",
"= { \"language\": \"en_GB\", \"available_languages\": [\"en_GB\", \"de_DE\", \"en_AU\", \"en_US\", \"fr_FR\"], } TEST_OPTIONS =",
"import unicode_literals import os import csv import pickle import sys import re #",
"+ file_name + \".csv\", \"rb\") as csvfile: table = csv.reader(csvfile) for i, row",
"False, \"font\": \"Arial,12,-1,5,50,0,0,0,0,0\", # \"language\": \"en_GB\", } #============================================================================== def write_config_file(object, file_name, directory=\"Resources\"): \"\"\"",
"as options_file: pickle.dump(object, options_file) #============================================================================== def write_options_files(): write_config_file(OPTIONS, \"Options.pickle\") write_config_file( LOCALISATION_OPTIONS, \"Languages.pickle\", directory=\"Resources/Languages\"",
"(i == 0): keys = row[1:] verify_keys(file_name, keys, verifier) continue language = row[0]",
"file. # # python imports from __future__ import unicode_literals import os import csv",
"path under Resources \"\"\" options_path = os.path.join( os.path.dirname(sys.argv[0]), \"../\" + directory ) file_path",
"py_file: lines = py_file.readlines() for line in lines: if (pattern.lower() in line.lower()): match",
"in lines: if (pattern.lower() in line.lower()): match = re.search(\".*\" + pattern + \"\\[\\\"(.*)\\\"\\]\",",
"= { \"code_css\": \"\", \"code_css_class\": \"highlight\", \"show_html\": False, \"processor\": \"markdown_all\", \"markdown_css\": \"\", \"display_line_numbers\":",
"(difference): raise Exception( \"Bad key found in %s: %s\" %(file_name, str(difference)) ) #==============================================================================",
"standard Options.pickle file. # # python imports from __future__ import unicode_literals import os",
"py_file.readlines() for line in lines: if (pattern.lower() in line.lower()): match = re.search(\".*\" +",
"if (path[-3:] == \".py\"): with open(path, \"r\") as py_file: lines = py_file.readlines() for",
"\"\\[\\\"(.*)\\\"\\]\", line) if match: keys.append(match.group(1)) return keys #============================================================================== def generate_user_text_keys(): return generate_keys(\"USER_TEXT\") #==============================================================================",
"verify_keys(file_name, keys, verifier) continue language = row[0] user_text = dict(zip(keys, row[1:])) write_config_file( user_text,",
"generate_user_text_keys(): return generate_keys(\"USER_TEXT\") #============================================================================== def generate_tool_tips_keys(): return generate_keys(\"TOOL_TIP\") #============================================================================== def write_user_text(): write_user_strings(\"UserText\", generate_user_text_keys())",
"import pickle import sys import re # local imports OPTIONS = { \"code_css\":",
"generate_tool_tips_keys(): return generate_keys(\"TOOL_TIP\") #============================================================================== def write_user_text(): write_user_strings(\"UserText\", generate_user_text_keys()) #============================================================================== def write_tool_tips(): write_user_strings(\"ToolTips\", generate_tool_tips_keys())",
"a relative path under Resources \"\"\" options_path = os.path.join( os.path.dirname(sys.argv[0]), \"../\" + directory",
"write_user_strings(\"UserText\", generate_user_text_keys()) #============================================================================== def write_tool_tips(): write_user_strings(\"ToolTips\", generate_tool_tips_keys()) #============================================================================== if (__name__ == \"__main__\"): write_options_files()",
"it #D is just for adding/changing options in the standard Options.pickle file. #",
"the object to file_name where file_name is a relative path under Resources \"\"\"",
"import csv import pickle import sys import re # local imports OPTIONS =",
"\"available_languages\": [\"en_GB\", \"de_DE\", \"en_AU\", \"en_US\", \"fr_FR\"], } TEST_OPTIONS = { \"code_css\": \"\", \"code_css_class\":",
"os.path.dirname(sys.argv[0]), \"../\" + directory ) file_path = os.path.join(options_path, file_name) with open(file_path, \"wb\") as",
"i, row in enumerate(table): if (i == 0): keys = row[1:] verify_keys(file_name, keys,",
"write_user_text(): write_user_strings(\"UserText\", generate_user_text_keys()) #============================================================================== def write_tool_tips(): write_user_strings(\"ToolTips\", generate_tool_tips_keys()) #============================================================================== if (__name__ == \"__main__\"):",
"#============================================================================== def generate_keys(pattern): keys = list() for path in os.listdir(\".\"): if (path[-3:] ==",
"generate_keys(\"TOOL_TIP\") #============================================================================== def write_user_text(): write_user_strings(\"UserText\", generate_user_text_keys()) #============================================================================== def write_tool_tips(): write_user_strings(\"ToolTips\", generate_tool_tips_keys()) #============================================================================== if",
"# Written by: DGC # #D This is purely for developer use, it",
"# #D This is purely for developer use, it will not be included",
"write_options_files(): write_config_file(OPTIONS, \"Options.pickle\") write_config_file( LOCALISATION_OPTIONS, \"Languages.pickle\", directory=\"Resources/Languages\" ) write_config_file(TEST_OPTIONS, \"Options.pickle\", directory=\"Integration\") #============================================================================== def",
"{ \"code_css\": \"Standard\", \"code_css_class\": \"highlight\", \"show_html\": False, \"processor\": \"markdown_all\", \"markdown_css\": \"Markdown\", \"display_line_numbers\": False,",
"object to file_name where file_name is a relative path under Resources \"\"\" options_path",
"where file_name is a relative path under Resources \"\"\" options_path = os.path.join( os.path.dirname(sys.argv[0]),",
"line in lines: if (pattern.lower() in line.lower()): match = re.search(\".*\" + pattern +",
"verifier] if (difference): raise Exception( \"Bad key found in %s: %s\" %(file_name, str(difference))",
"open(path, \"r\") as py_file: lines = py_file.readlines() for line in lines: if (pattern.lower()",
"{ \"language\": \"en_GB\", \"available_languages\": [\"en_GB\", \"de_DE\", \"en_AU\", \"en_US\", \"fr_FR\"], } TEST_OPTIONS = {",
"\"Bad key found in %s: %s\" %(file_name, str(difference)) ) #============================================================================== def write_user_strings(file_name, verifier):",
"# python imports from __future__ import unicode_literals import os import csv import pickle",
"included in the program it #D is just for adding/changing options in the",
"set(verifier) difference = [k for k in keys if k not in verifier]",
"found in %s: %s\" %(file_name, str(difference)) ) #============================================================================== def write_user_strings(file_name, verifier): with open(\"data/\"",
"python imports from __future__ import unicode_literals import os import csv import pickle import",
"list() for path in os.listdir(\".\"): if (path[-3:] == \".py\"): with open(path, \"r\") as",
"in enumerate(table): if (i == 0): keys = row[1:] verify_keys(file_name, keys, verifier) continue",
"+ \".pickle\", directory=\"Resources/Languages/\" + language) #============================================================================== def generate_keys(pattern): keys = list() for path",
"0): keys = row[1:] verify_keys(file_name, keys, verifier) continue language = row[0] user_text =",
"+ pattern + \"\\[\\\"(.*)\\\"\\]\", line) if match: keys.append(match.group(1)) return keys #============================================================================== def generate_user_text_keys():",
"k not in verifier] if (difference): raise Exception( \"Bad key found in %s:",
"local imports OPTIONS = { \"code_css\": \"Standard\", \"code_css_class\": \"highlight\", \"show_html\": False, \"processor\": \"markdown_all\",",
"\"Languages.pickle\", directory=\"Resources/Languages\" ) write_config_file(TEST_OPTIONS, \"Options.pickle\", directory=\"Integration\") #============================================================================== def verify_keys(file_name, keys, verifier): keys =",
"directory=\"Resources\"): \"\"\" Pickles the object to file_name where file_name is a relative path",
"\"highlight\", \"show_html\": False, \"processor\": \"markdown_all\", \"markdown_css\": \"Markdown\", \"display_line_numbers\": False, \"font\": \"Arial,12,-1,5,50,0,0,0,0,0\", } LOCALISATION_OPTIONS",
"if (difference): raise Exception( \"Bad key found in %s: %s\" %(file_name, str(difference)) )",
"= re.search(\".*\" + pattern + \"\\[\\\"(.*)\\\"\\]\", line) if match: keys.append(match.group(1)) return keys #==============================================================================",
"return generate_keys(\"USER_TEXT\") #============================================================================== def generate_tool_tips_keys(): return generate_keys(\"TOOL_TIP\") #============================================================================== def write_user_text(): write_user_strings(\"UserText\", generate_user_text_keys()) #==============================================================================",
"is a relative path under Resources \"\"\" options_path = os.path.join( os.path.dirname(sys.argv[0]), \"../\" +",
"False, \"processor\": \"markdown_all\", \"markdown_css\": \"Markdown\", \"display_line_numbers\": False, \"font\": \"Arial,12,-1,5,50,0,0,0,0,0\", } LOCALISATION_OPTIONS = {",
"#============================================================================== def write_options_files(): write_config_file(OPTIONS, \"Options.pickle\") write_config_file( LOCALISATION_OPTIONS, \"Languages.pickle\", directory=\"Resources/Languages\" ) write_config_file(TEST_OPTIONS, \"Options.pickle\", directory=\"Integration\")",
"\"show_html\": False, \"processor\": \"markdown_all\", \"markdown_css\": \"Markdown\", \"display_line_numbers\": False, \"font\": \"Arial,12,-1,5,50,0,0,0,0,0\", } LOCALISATION_OPTIONS =",
"unicode_literals import os import csv import pickle import sys import re # local",
"verifier): with open(\"data/\" + file_name + \".csv\", \"rb\") as csvfile: table = csv.reader(csvfile)",
"with open(path, \"r\") as py_file: lines = py_file.readlines() for line in lines: if",
"\"r\") as py_file: lines = py_file.readlines() for line in lines: if (pattern.lower() in",
"as csvfile: table = csv.reader(csvfile) for i, row in enumerate(table): if (i ==",
"\".pickle\", directory=\"Resources/Languages/\" + language) #============================================================================== def generate_keys(pattern): keys = list() for path in",
"for line in lines: if (pattern.lower() in line.lower()): match = re.search(\".*\" + pattern",
"keys, verifier): keys = set(keys) verifier = set(verifier) difference = [k for k",
"if k not in verifier] if (difference): raise Exception( \"Bad key found in",
"+ language) #============================================================================== def generate_keys(pattern): keys = list() for path in os.listdir(\".\"): if",
"match: keys.append(match.group(1)) return keys #============================================================================== def generate_user_text_keys(): return generate_keys(\"USER_TEXT\") #============================================================================== def generate_tool_tips_keys(): return",
"just for adding/changing options in the standard Options.pickle file. # # python imports",
"row[1:] verify_keys(file_name, keys, verifier) continue language = row[0] user_text = dict(zip(keys, row[1:])) write_config_file(",
"in line.lower()): match = re.search(\".*\" + pattern + \"\\[\\\"(.*)\\\"\\]\", line) if match: keys.append(match.group(1))",
"developer use, it will not be included in the program it #D is",
"\"markdown_css\": \"\", \"display_line_numbers\": False, \"font\": \"Arial,12,-1,5,50,0,0,0,0,0\", # \"language\": \"en_GB\", } #============================================================================== def write_config_file(object,",
"verifier = set(verifier) difference = [k for k in keys if k not",
"\"Options.pickle\", directory=\"Integration\") #============================================================================== def verify_keys(file_name, keys, verifier): keys = set(keys) verifier = set(verifier)",
"if match: keys.append(match.group(1)) return keys #============================================================================== def generate_user_text_keys(): return generate_keys(\"USER_TEXT\") #============================================================================== def generate_tool_tips_keys():",
"def write_user_text(): write_user_strings(\"UserText\", generate_user_text_keys()) #============================================================================== def write_tool_tips(): write_user_strings(\"ToolTips\", generate_tool_tips_keys()) #============================================================================== if (__name__ =="
] |
[
"= [ ('registration', '0002_auto_20200717_1825'), ] operations = [ migrations.CreateModel( name='Student_Registration', fields=[ ('id', models.AutoField(auto_created=True,",
"[ ('registration', '0002_auto_20200717_1825'), ] operations = [ migrations.CreateModel( name='Student_Registration', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True,",
"('first_name', models.CharField(max_length=50)), ('last_name', models.CharField(max_length=50)), ('Date_of_Birth', models.DateField()), ('Blood_Group', models.CharField(max_length=2)), ('Nationality', models.CharField(max_length=15)), ('Email', models.EmailField(max_length=254)), ('Religion',",
"2020-07-18 06:14 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('registration',",
"Generated by Django 3.0.8 on 2020-07-18 06:14 from django.db import migrations, models class",
"migrations, models class Migration(migrations.Migration): dependencies = [ ('registration', '0002_auto_20200717_1825'), ] operations = [",
"<reponame>NUKSI911/School-Mng<gh_stars>0 # Generated by Django 3.0.8 on 2020-07-18 06:14 from django.db import migrations,",
"'0002_auto_20200717_1825'), ] operations = [ migrations.CreateModel( name='Student_Registration', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),",
"verbose_name='ID')), ('first_name', models.CharField(max_length=50)), ('last_name', models.CharField(max_length=50)), ('Date_of_Birth', models.DateField()), ('Blood_Group', models.CharField(max_length=2)), ('Nationality', models.CharField(max_length=15)), ('Email', models.EmailField(max_length=254)),",
"django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('registration', '0002_auto_20200717_1825'), ] operations",
"('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('first_name', models.CharField(max_length=50)), ('last_name', models.CharField(max_length=50)), ('Date_of_Birth', models.DateField()), ('Blood_Group', models.CharField(max_length=2)),",
"Migration(migrations.Migration): dependencies = [ ('registration', '0002_auto_20200717_1825'), ] operations = [ migrations.CreateModel( name='Student_Registration', fields=[",
"dependencies = [ ('registration', '0002_auto_20200717_1825'), ] operations = [ migrations.CreateModel( name='Student_Registration', fields=[ ('id',",
"operations = [ migrations.CreateModel( name='Student_Registration', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('first_name', models.CharField(max_length=50)),",
"[ migrations.CreateModel( name='Student_Registration', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('first_name', models.CharField(max_length=50)), ('last_name', models.CharField(max_length=50)),",
"models.CharField(max_length=50)), ('Date_of_Birth', models.DateField()), ('Blood_Group', models.CharField(max_length=2)), ('Nationality', models.CharField(max_length=15)), ('Email', models.EmailField(max_length=254)), ('Religion', models.CharField(max_length=25)), ('Phone_No', models.CharField(max_length=12)),",
"models class Migration(migrations.Migration): dependencies = [ ('registration', '0002_auto_20200717_1825'), ] operations = [ migrations.CreateModel(",
"name='Student_Registration', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('first_name', models.CharField(max_length=50)), ('last_name', models.CharField(max_length=50)), ('Date_of_Birth', models.DateField()),",
"('Blood_Group', models.CharField(max_length=2)), ('Nationality', models.CharField(max_length=15)), ('Email', models.EmailField(max_length=254)), ('Religion', models.CharField(max_length=25)), ('Phone_No', models.CharField(max_length=12)), ], ), ]",
"on 2020-07-18 06:14 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [",
"# Generated by Django 3.0.8 on 2020-07-18 06:14 from django.db import migrations, models",
"models.DateField()), ('Blood_Group', models.CharField(max_length=2)), ('Nationality', models.CharField(max_length=15)), ('Email', models.EmailField(max_length=254)), ('Religion', models.CharField(max_length=25)), ('Phone_No', models.CharField(max_length=12)), ], ),",
"class Migration(migrations.Migration): dependencies = [ ('registration', '0002_auto_20200717_1825'), ] operations = [ migrations.CreateModel( name='Student_Registration',",
"models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('first_name', models.CharField(max_length=50)), ('last_name', models.CharField(max_length=50)), ('Date_of_Birth', models.DateField()), ('Blood_Group', models.CharField(max_length=2)), ('Nationality',",
"Django 3.0.8 on 2020-07-18 06:14 from django.db import migrations, models class Migration(migrations.Migration): dependencies",
"= [ migrations.CreateModel( name='Student_Registration', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('first_name', models.CharField(max_length=50)), ('last_name',",
"import migrations, models class Migration(migrations.Migration): dependencies = [ ('registration', '0002_auto_20200717_1825'), ] operations =",
"06:14 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('registration', '0002_auto_20200717_1825'),",
"('registration', '0002_auto_20200717_1825'), ] operations = [ migrations.CreateModel( name='Student_Registration', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False,",
"by Django 3.0.8 on 2020-07-18 06:14 from django.db import migrations, models class Migration(migrations.Migration):",
"migrations.CreateModel( name='Student_Registration', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('first_name', models.CharField(max_length=50)), ('last_name', models.CharField(max_length=50)), ('Date_of_Birth',",
"primary_key=True, serialize=False, verbose_name='ID')), ('first_name', models.CharField(max_length=50)), ('last_name', models.CharField(max_length=50)), ('Date_of_Birth', models.DateField()), ('Blood_Group', models.CharField(max_length=2)), ('Nationality', models.CharField(max_length=15)),",
"('last_name', models.CharField(max_length=50)), ('Date_of_Birth', models.DateField()), ('Blood_Group', models.CharField(max_length=2)), ('Nationality', models.CharField(max_length=15)), ('Email', models.EmailField(max_length=254)), ('Religion', models.CharField(max_length=25)), ('Phone_No',",
"] operations = [ migrations.CreateModel( name='Student_Registration', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('first_name',",
"serialize=False, verbose_name='ID')), ('first_name', models.CharField(max_length=50)), ('last_name', models.CharField(max_length=50)), ('Date_of_Birth', models.DateField()), ('Blood_Group', models.CharField(max_length=2)), ('Nationality', models.CharField(max_length=15)), ('Email',",
"3.0.8 on 2020-07-18 06:14 from django.db import migrations, models class Migration(migrations.Migration): dependencies =",
"('Date_of_Birth', models.DateField()), ('Blood_Group', models.CharField(max_length=2)), ('Nationality', models.CharField(max_length=15)), ('Email', models.EmailField(max_length=254)), ('Religion', models.CharField(max_length=25)), ('Phone_No', models.CharField(max_length=12)), ],",
"models.CharField(max_length=50)), ('last_name', models.CharField(max_length=50)), ('Date_of_Birth', models.DateField()), ('Blood_Group', models.CharField(max_length=2)), ('Nationality', models.CharField(max_length=15)), ('Email', models.EmailField(max_length=254)), ('Religion', models.CharField(max_length=25)),",
"from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('registration', '0002_auto_20200717_1825'), ]",
"fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('first_name', models.CharField(max_length=50)), ('last_name', models.CharField(max_length=50)), ('Date_of_Birth', models.DateField()), ('Blood_Group',"
] |
[
"L1) diagonal = retangulo.Diagonal(A1, L1) print(\"Area: {}\".format(area)) print(\"Perímetro: {}\".format(perimetro)) print(\"Diagonal: {}\".format(diagonal)) print(\"\") elif(opcao",
"input(\"Nome: \") s2 = float(input(\"Salário: \")) media =(s1 + s2 ) / 2",
"retângulo: \") L1 = float(input(\"Largura: \")) A1 = float(input(\"Altura: \")) retangulo = Retangulo(A1,L1)",
"Segundo funcionairo: \") p2 = input(\"Nome: \") s2 = float(input(\"Salário: \")) media =(s1",
"input(\"Nome: \") i2 = int(input(\"Idade: \")) if(i1 > i2): print(\"pessoa mais velha: {}\".format(p1))",
"\") L1 = float(input(\"Largura: \")) A1 = float(input(\"Altura: \")) retangulo = Retangulo(A1,L1) area",
"retangulo = Retangulo(A1,L1) area = retangulo.Area(A1,L1) perimetro = retangulo.Perimetro(A1, L1) diagonal = retangulo.Diagonal(A1,",
"print(\"Atividade de PARADIGMAS\") print(\" 1 - QUESTÃO 01\") print(\" 2 - QUESTÃO 02\")",
"o nome do primeiro funcionairo: \") p1 = input(\"Nome: \") s1 = float(input(\"Salário:",
"=(s1 + s2 ) / 2 print(\"Salário médio = {}\".format(media)) print(\"\") elif(opcao ==",
"p1 = input(\"Nome: \") s1 = float(input(\"Salário: \")) print(\"Digite o nome do Segundo",
"print(\" 5 - QUESTÃO 05\") print(\" 0 - PARA SAIR\") print(\"\") opcao =",
"print(\"Area: {}\".format(area)) print(\"Perímetro: {}\".format(perimetro)) print(\"Diagonal: {}\".format(diagonal)) print(\"\") elif(opcao == 4): from funcionario import",
"QUESTÃO 02\") print(\" 3 - QUESTÃO 03\") print(\" 4 - QUESTÃO 04\") print(\"",
"print(\"Entre com a largura e altura do retângulo: \") L1 = float(input(\"Largura: \"))",
"from funcionario import Funcionario print(\"ATUALIZAÇÃO DE DADOS\") print(\"Digite um funcionario\") nome = input(\"Nome:",
"4 - QUESTÃO 04\") print(\" 5 - QUESTÃO 05\") print(\" 0 - PARA",
"opcao = int(input(\"Digite o desejado: \")) clear() if(opcao == 1): print(\"PESSOA MAIS VELHA\")",
"SAIR\") print(\"\") opcao = int(input(\"Digite o desejado: \")) clear() if(opcao == 1): print(\"PESSOA",
"nota2 = float(input(\"Segunda nota : \")) nota3 = float(input(\"Terceira nota : \")) notas",
"print(\" 0 - PARA SAIR\") print(\"\") opcao = int(input(\"Digite o desejado: \")) clear()",
"= Funcionario(nome, salario, imposto) liquido = funcionario1.SalarioLiquido(salario, imposto) print(\" \") print(\"Funcionairo : {}",
"o nome da Segunda pessoa: \") p2 = input(\"Nome: \") i2 = int(input(\"Idade:",
"5): print(\"APROVADO OU REPROVADO\") nome = input(\"Nome do Aluno: \") nota1 = float(input(\"Primeira",
"= retangulo.Diagonal(A1, L1) print(\"Area: {}\".format(area)) print(\"Perímetro: {}\".format(perimetro)) print(\"Diagonal: {}\".format(diagonal)) print(\"\") elif(opcao == 4):",
"2 - QUESTÃO 02\") print(\" 3 - QUESTÃO 03\") print(\" 4 - QUESTÃO",
"diagonal = retangulo.Diagonal(A1, L1) print(\"Area: {}\".format(area)) print(\"Perímetro: {}\".format(perimetro)) print(\"Diagonal: {}\".format(diagonal)) print(\"\") elif(opcao ==",
"salario = float(input(\"Salario: \")) imposto = float(input(\"Imposto: \")) funcionario1 = Funcionario(nome, salario, imposto)",
"= float(input(\"Imposto: \")) funcionario1 = Funcionario(nome, salario, imposto) liquido = funcionario1.SalarioLiquido(salario, imposto) print(\"",
": \")) nota3 = float(input(\"Terceira nota : \")) notas = (nota1 + nota2",
"\") salario = float(input(\"Salario: \")) imposto = float(input(\"Imposto: \")) funcionario1 = Funcionario(nome, salario,",
"médio = {}\".format(media)) print(\"\") elif(opcao == 3): from retangulo import Retangulo print(\"LARGURA E",
"i2 = int(input(\"Idade: \")) if(i1 > i2): print(\"pessoa mais velha: {}\".format(p1)) else: print(\"pessoa",
"print(\"LARGURA E ALTURA DE UM RETÂNGULO\") print(\"Entre com a largura e altura do",
"= float(input(\"Altura: \")) retangulo = Retangulo(A1,L1) area = retangulo.Area(A1,L1) perimetro = retangulo.Perimetro(A1, L1)",
"2): print(\"MEDIA DE SALÁRIO\") print(\"Digite o nome do primeiro funcionairo: \") p1 =",
"o nome do Segundo funcionairo: \") p2 = input(\"Nome: \") s2 = float(input(\"Salário:",
"DE UM RETÂNGULO\") print(\"Entre com a largura e altura do retângulo: \") L1",
"os.system('clear') clear() opcao = 1 while(opcao != 0): print(\"Atividade de PARADIGMAS\") print(\" 1",
"notas if(notas >= vb): print(\"Nota final = {:.2f}\".format(notas)) print(\"Aprovado\") else: print(\"Nota final =",
"com a largura e altura do retângulo: \") L1 = float(input(\"Largura: \")) A1",
"{:.2f}\".format(notas)) print(\"Reprovado\") print(\"Faltaram {:.2f} pontos\".format(vr)) print(\"\") elif(opcao == 0): break else: print(\"Valor informado",
"REPROVADO\") nome = input(\"Nome do Aluno: \") nota1 = float(input(\"Primeira nota : \"))",
"nota2 + nota3) print(\"\") vb = 60.0 vr = vb - notas if(notas",
"= float(input(\"Salário: \")) print(\"Digite o nome do Segundo funcionairo: \") p2 = input(\"Nome:",
"\")) nota3 = float(input(\"Terceira nota : \")) notas = (nota1 + nota2 +",
"{:.2f}\".format(notas)) print(\"Aprovado\") else: print(\"Nota final = {:.2f}\".format(notas)) print(\"Reprovado\") print(\"Faltaram {:.2f} pontos\".format(vr)) print(\"\") elif(opcao",
"{} , R$ {}\".format(nome, liquido)) comis = float(input(\"Digite a porcentagem para aumentar o",
"desejado: \")) clear() if(opcao == 1): print(\"PESSOA MAIS VELHA\") print(\"Digite o nome da",
"Segunda pessoa: \") p2 = input(\"Nome: \") i2 = int(input(\"Idade: \")) if(i1 >",
"= input(\"Nome: \") salario = float(input(\"Salario: \")) imposto = float(input(\"Imposto: \")) funcionario1 =",
": \")) notas = (nota1 + nota2 + nota3) print(\"\") vb = 60.0",
"nota3 = float(input(\"Terceira nota : \")) notas = (nota1 + nota2 + nota3)",
"= 60.0 vr = vb - notas if(notas >= vb): print(\"Nota final =",
"o salário: \")) aument = funcionario1.AumentoSalario(salario, liquido, comis) print(\"Dados Atualizados : {} R$",
"= retangulo.Area(A1,L1) perimetro = retangulo.Perimetro(A1, L1) diagonal = retangulo.Diagonal(A1, L1) print(\"Area: {}\".format(area)) print(\"Perímetro:",
"final = {:.2f}\".format(notas)) print(\"Aprovado\") else: print(\"Nota final = {:.2f}\".format(notas)) print(\"Reprovado\") print(\"Faltaram {:.2f} pontos\".format(vr))",
"= input(\"Nome: \") s1 = float(input(\"Salário: \")) print(\"Digite o nome do Segundo funcionairo:",
"nome = input(\"Nome: \") salario = float(input(\"Salario: \")) imposto = float(input(\"Imposto: \")) funcionario1",
"Retangulo(A1,L1) area = retangulo.Area(A1,L1) perimetro = retangulo.Perimetro(A1, L1) diagonal = retangulo.Diagonal(A1, L1) print(\"Area:",
"velha: {}\".format(p1)) else: print(\"pessoa mais velha: {}\".format(p2)) print(\"\") elif(opcao == 2): print(\"MEDIA DE",
"- PARA SAIR\") print(\"\") opcao = int(input(\"Digite o desejado: \")) clear() if(opcao ==",
"elif(opcao == 4): from funcionario import Funcionario print(\"ATUALIZAÇÃO DE DADOS\") print(\"Digite um funcionario\")",
"\")) retangulo = Retangulo(A1,L1) area = retangulo.Area(A1,L1) perimetro = retangulo.Perimetro(A1, L1) diagonal =",
"do primeiro funcionairo: \") p1 = input(\"Nome: \") s1 = float(input(\"Salário: \")) print(\"Digite",
"float(input(\"Primeira nota : \")) nota2 = float(input(\"Segunda nota : \")) nota3 = float(input(\"Terceira",
"\") p2 = input(\"Nome: \") s2 = float(input(\"Salário: \")) media =(s1 + s2",
"= int(input(\"Idade: \")) if(i1 > i2): print(\"pessoa mais velha: {}\".format(p1)) else: print(\"pessoa mais",
"R$ {}\".format(nome, aument)) print(\"\") elif(opcao == 5): print(\"APROVADO OU REPROVADO\") nome = input(\"Nome",
"print(\"\") elif(opcao == 4): from funcionario import Funcionario print(\"ATUALIZAÇÃO DE DADOS\") print(\"Digite um",
"liquido = funcionario1.SalarioLiquido(salario, imposto) print(\" \") print(\"Funcionairo : {} , R$ {}\".format(nome, liquido))",
"do retângulo: \") L1 = float(input(\"Largura: \")) A1 = float(input(\"Altura: \")) retangulo =",
"do Aluno: \") nota1 = float(input(\"Primeira nota : \")) nota2 = float(input(\"Segunda nota",
"\")) funcionario1 = Funcionario(nome, salario, imposto) liquido = funcionario1.SalarioLiquido(salario, imposto) print(\" \") print(\"Funcionairo",
"{}\".format(p2)) print(\"\") elif(opcao == 2): print(\"MEDIA DE SALÁRIO\") print(\"Digite o nome do primeiro",
"E ALTURA DE UM RETÂNGULO\") print(\"Entre com a largura e altura do retângulo:",
"int(input(\"Idade: \")) print(\"Digite o nome da Segunda pessoa: \") p2 = input(\"Nome: \")",
"\")) clear() if(opcao == 1): print(\"PESSOA MAIS VELHA\") print(\"Digite o nome da primeira",
"{}\".format(media)) print(\"\") elif(opcao == 3): from retangulo import Retangulo print(\"LARGURA E ALTURA DE",
"float(input(\"Salario: \")) imposto = float(input(\"Imposto: \")) funcionario1 = Funcionario(nome, salario, imposto) liquido =",
"{}\".format(nome, liquido)) comis = float(input(\"Digite a porcentagem para aumentar o salário: \")) aument",
"\") p2 = input(\"Nome: \") i2 = int(input(\"Idade: \")) if(i1 > i2): print(\"pessoa",
"largura e altura do retângulo: \") L1 = float(input(\"Largura: \")) A1 = float(input(\"Altura:",
"funcionairo: \") p1 = input(\"Nome: \") s1 = float(input(\"Salário: \")) print(\"Digite o nome",
"vb): print(\"Nota final = {:.2f}\".format(notas)) print(\"Aprovado\") else: print(\"Nota final = {:.2f}\".format(notas)) print(\"Reprovado\") print(\"Faltaram",
"== 4): from funcionario import Funcionario print(\"ATUALIZAÇÃO DE DADOS\") print(\"Digite um funcionario\") nome",
"float(input(\"Altura: \")) retangulo = Retangulo(A1,L1) area = retangulo.Area(A1,L1) perimetro = retangulo.Perimetro(A1, L1) diagonal",
"aumentar o salário: \")) aument = funcionario1.AumentoSalario(salario, liquido, comis) print(\"Dados Atualizados : {}",
"input(\"Nome do Aluno: \") nota1 = float(input(\"Primeira nota : \")) nota2 = float(input(\"Segunda",
"import os clear = lambda: os.system('clear') clear() opcao = 1 while(opcao != 0):",
"= input(\"Nome: \") s2 = float(input(\"Salário: \")) media =(s1 + s2 ) /",
"um funcionario\") nome = input(\"Nome: \") salario = float(input(\"Salario: \")) imposto = float(input(\"Imposto:",
"3 - QUESTÃO 03\") print(\" 4 - QUESTÃO 04\") print(\" 5 - QUESTÃO",
"> i2): print(\"pessoa mais velha: {}\".format(p1)) else: print(\"pessoa mais velha: {}\".format(p2)) print(\"\") elif(opcao",
"clear() if(opcao == 1): print(\"PESSOA MAIS VELHA\") print(\"Digite o nome da primeira pessoa:",
"primeiro funcionairo: \") p1 = input(\"Nome: \") s1 = float(input(\"Salário: \")) print(\"Digite o",
"do Segundo funcionairo: \") p2 = input(\"Nome: \") s2 = float(input(\"Salário: \")) media",
"= int(input(\"Idade: \")) print(\"Digite o nome da Segunda pessoa: \") p2 = input(\"Nome:",
"= float(input(\"Salario: \")) imposto = float(input(\"Imposto: \")) funcionario1 = Funcionario(nome, salario, imposto) liquido",
"else: print(\"Nota final = {:.2f}\".format(notas)) print(\"Reprovado\") print(\"Faltaram {:.2f} pontos\".format(vr)) print(\"\") elif(opcao == 0):",
"+ nota2 + nota3) print(\"\") vb = 60.0 vr = vb - notas",
"if(opcao == 1): print(\"PESSOA MAIS VELHA\") print(\"Digite o nome da primeira pessoa: \")",
"print(\" 1 - QUESTÃO 01\") print(\" 2 - QUESTÃO 02\") print(\" 3 -",
"print(\"\") vb = 60.0 vr = vb - notas if(notas >= vb): print(\"Nota",
"PARADIGMAS\") print(\" 1 - QUESTÃO 01\") print(\" 2 - QUESTÃO 02\") print(\" 3",
"salario, imposto) liquido = funcionario1.SalarioLiquido(salario, imposto) print(\" \") print(\"Funcionairo : {} , R$",
"\")) print(\"Digite o nome da Segunda pessoa: \") p2 = input(\"Nome: \") i2",
"funcionario1 = Funcionario(nome, salario, imposto) liquido = funcionario1.SalarioLiquido(salario, imposto) print(\" \") print(\"Funcionairo :",
"print(\"\") elif(opcao == 5): print(\"APROVADO OU REPROVADO\") nome = input(\"Nome do Aluno: \")",
"area = retangulo.Area(A1,L1) perimetro = retangulo.Perimetro(A1, L1) diagonal = retangulo.Diagonal(A1, L1) print(\"Area: {}\".format(area))",
"nome do primeiro funcionairo: \") p1 = input(\"Nome: \") s1 = float(input(\"Salário: \"))",
"print(\"Salário médio = {}\".format(media)) print(\"\") elif(opcao == 3): from retangulo import Retangulo print(\"LARGURA",
": {} , R$ {}\".format(nome, liquido)) comis = float(input(\"Digite a porcentagem para aumentar",
"print(\" 2 - QUESTÃO 02\") print(\" 3 - QUESTÃO 03\") print(\" 4 -",
"print(\"Aprovado\") else: print(\"Nota final = {:.2f}\".format(notas)) print(\"Reprovado\") print(\"Faltaram {:.2f} pontos\".format(vr)) print(\"\") elif(opcao ==",
"float(input(\"Terceira nota : \")) notas = (nota1 + nota2 + nota3) print(\"\") vb",
"DE DADOS\") print(\"Digite um funcionario\") nome = input(\"Nome: \") salario = float(input(\"Salario: \"))",
"\") nota1 = float(input(\"Primeira nota : \")) nota2 = float(input(\"Segunda nota : \"))",
"= input(\"Nome do Aluno: \") nota1 = float(input(\"Primeira nota : \")) nota2 =",
"QUESTÃO 01\") print(\" 2 - QUESTÃO 02\") print(\" 3 - QUESTÃO 03\") print(\"",
"nota : \")) notas = (nota1 + nota2 + nota3) print(\"\") vb =",
"= retangulo.Perimetro(A1, L1) diagonal = retangulo.Diagonal(A1, L1) print(\"Area: {}\".format(area)) print(\"Perímetro: {}\".format(perimetro)) print(\"Diagonal: {}\".format(diagonal))",
"import Funcionario print(\"ATUALIZAÇÃO DE DADOS\") print(\"Digite um funcionario\") nome = input(\"Nome: \") salario",
"{}\".format(nome, aument)) print(\"\") elif(opcao == 5): print(\"APROVADO OU REPROVADO\") nome = input(\"Nome do",
"\") s1 = float(input(\"Salário: \")) print(\"Digite o nome do Segundo funcionairo: \") p2",
"salário: \")) aument = funcionario1.AumentoSalario(salario, liquido, comis) print(\"Dados Atualizados : {} R$ {}\".format(nome,",
"while(opcao != 0): print(\"Atividade de PARADIGMAS\") print(\" 1 - QUESTÃO 01\") print(\" 2",
"input(\"Nome: \") i1 = int(input(\"Idade: \")) print(\"Digite o nome da Segunda pessoa: \")",
"4): from funcionario import Funcionario print(\"ATUALIZAÇÃO DE DADOS\") print(\"Digite um funcionario\") nome =",
"== 1): print(\"PESSOA MAIS VELHA\") print(\"Digite o nome da primeira pessoa: \") p1",
"{}\".format(area)) print(\"Perímetro: {}\".format(perimetro)) print(\"Diagonal: {}\".format(diagonal)) print(\"\") elif(opcao == 4): from funcionario import Funcionario",
"{} R$ {}\".format(nome, aument)) print(\"\") elif(opcao == 5): print(\"APROVADO OU REPROVADO\") nome =",
"media =(s1 + s2 ) / 2 print(\"Salário médio = {}\".format(media)) print(\"\") elif(opcao",
"R$ {}\".format(nome, liquido)) comis = float(input(\"Digite a porcentagem para aumentar o salário: \"))",
"a largura e altura do retângulo: \") L1 = float(input(\"Largura: \")) A1 =",
"MAIS VELHA\") print(\"Digite o nome da primeira pessoa: \") p1 = input(\"Nome: \")",
"if(i1 > i2): print(\"pessoa mais velha: {}\".format(p1)) else: print(\"pessoa mais velha: {}\".format(p2)) print(\"\")",
"e altura do retângulo: \") L1 = float(input(\"Largura: \")) A1 = float(input(\"Altura: \"))",
"from retangulo import Retangulo print(\"LARGURA E ALTURA DE UM RETÂNGULO\") print(\"Entre com a",
"print(\"ATUALIZAÇÃO DE DADOS\") print(\"Digite um funcionario\") nome = input(\"Nome: \") salario = float(input(\"Salario:",
"{}\".format(p1)) else: print(\"pessoa mais velha: {}\".format(p2)) print(\"\") elif(opcao == 2): print(\"MEDIA DE SALÁRIO\")",
"= input(\"Nome: \") i2 = int(input(\"Idade: \")) if(i1 > i2): print(\"pessoa mais velha:",
"print(\"Digite o nome da Segunda pessoa: \") p2 = input(\"Nome: \") i2 =",
"nome da primeira pessoa: \") p1 = input(\"Nome: \") i1 = int(input(\"Idade: \"))",
"imposto = float(input(\"Imposto: \")) funcionario1 = Funcionario(nome, salario, imposto) liquido = funcionario1.SalarioLiquido(salario, imposto)",
"Funcionario(nome, salario, imposto) liquido = funcionario1.SalarioLiquido(salario, imposto) print(\" \") print(\"Funcionairo : {} ,",
"o desejado: \")) clear() if(opcao == 1): print(\"PESSOA MAIS VELHA\") print(\"Digite o nome",
"UM RETÂNGULO\") print(\"Entre com a largura e altura do retângulo: \") L1 =",
"p2 = input(\"Nome: \") s2 = float(input(\"Salário: \")) media =(s1 + s2 )",
"= float(input(\"Primeira nota : \")) nota2 = float(input(\"Segunda nota : \")) nota3 =",
"2 print(\"Salário médio = {}\".format(media)) print(\"\") elif(opcao == 3): from retangulo import Retangulo",
"notas = (nota1 + nota2 + nota3) print(\"\") vb = 60.0 vr =",
"input(\"Nome: \") s1 = float(input(\"Salário: \")) print(\"Digite o nome do Segundo funcionairo: \")",
"pessoa: \") p2 = input(\"Nome: \") i2 = int(input(\"Idade: \")) if(i1 > i2):",
"04\") print(\" 5 - QUESTÃO 05\") print(\" 0 - PARA SAIR\") print(\"\") opcao",
"print(\"PESSOA MAIS VELHA\") print(\"Digite o nome da primeira pessoa: \") p1 = input(\"Nome:",
"funcionario import Funcionario print(\"ATUALIZAÇÃO DE DADOS\") print(\"Digite um funcionario\") nome = input(\"Nome: \")",
"print(\"\") elif(opcao == 3): from retangulo import Retangulo print(\"LARGURA E ALTURA DE UM",
"print(\"Reprovado\") print(\"Faltaram {:.2f} pontos\".format(vr)) print(\"\") elif(opcao == 0): break else: print(\"Valor informado inválido!",
"01\") print(\" 2 - QUESTÃO 02\") print(\" 3 - QUESTÃO 03\") print(\" 4",
"nota3) print(\"\") vb = 60.0 vr = vb - notas if(notas >= vb):",
"DE SALÁRIO\") print(\"Digite o nome do primeiro funcionairo: \") p1 = input(\"Nome: \")",
"s1 = float(input(\"Salário: \")) print(\"Digite o nome do Segundo funcionairo: \") p2 =",
"== 3): from retangulo import Retangulo print(\"LARGURA E ALTURA DE UM RETÂNGULO\") print(\"Entre",
"print(\"Nota final = {:.2f}\".format(notas)) print(\"Reprovado\") print(\"Faltaram {:.2f} pontos\".format(vr)) print(\"\") elif(opcao == 0): break",
"nota : \")) nota2 = float(input(\"Segunda nota : \")) nota3 = float(input(\"Terceira nota",
"comis) print(\"Dados Atualizados : {} R$ {}\".format(nome, aument)) print(\"\") elif(opcao == 5): print(\"APROVADO",
"print(\"\") opcao = int(input(\"Digite o desejado: \")) clear() if(opcao == 1): print(\"PESSOA MAIS",
"opcao = 1 while(opcao != 0): print(\"Atividade de PARADIGMAS\") print(\" 1 - QUESTÃO",
"primeira pessoa: \") p1 = input(\"Nome: \") i1 = int(input(\"Idade: \")) print(\"Digite o",
"L1 = float(input(\"Largura: \")) A1 = float(input(\"Altura: \")) retangulo = Retangulo(A1,L1) area =",
"\")) notas = (nota1 + nota2 + nota3) print(\"\") vb = 60.0 vr",
"+ nota3) print(\"\") vb = 60.0 vr = vb - notas if(notas >=",
"input(\"Nome: \") salario = float(input(\"Salario: \")) imposto = float(input(\"Imposto: \")) funcionario1 = Funcionario(nome,",
"SALÁRIO\") print(\"Digite o nome do primeiro funcionairo: \") p1 = input(\"Nome: \") s1",
"i2): print(\"pessoa mais velha: {}\".format(p1)) else: print(\"pessoa mais velha: {}\".format(p2)) print(\"\") elif(opcao ==",
"QUESTÃO 03\") print(\" 4 - QUESTÃO 04\") print(\" 5 - QUESTÃO 05\") print(\"",
"os clear = lambda: os.system('clear') clear() opcao = 1 while(opcao != 0): print(\"Atividade",
"\")) nota2 = float(input(\"Segunda nota : \")) nota3 = float(input(\"Terceira nota : \"))",
"\")) aument = funcionario1.AumentoSalario(salario, liquido, comis) print(\"Dados Atualizados : {} R$ {}\".format(nome, aument))",
"= {:.2f}\".format(notas)) print(\"Aprovado\") else: print(\"Nota final = {:.2f}\".format(notas)) print(\"Reprovado\") print(\"Faltaram {:.2f} pontos\".format(vr)) print(\"\")",
"DADOS\") print(\"Digite um funcionario\") nome = input(\"Nome: \") salario = float(input(\"Salario: \")) imposto",
"pessoa: \") p1 = input(\"Nome: \") i1 = int(input(\"Idade: \")) print(\"Digite o nome",
"3): from retangulo import Retangulo print(\"LARGURA E ALTURA DE UM RETÂNGULO\") print(\"Entre com",
"= float(input(\"Digite a porcentagem para aumentar o salário: \")) aument = funcionario1.AumentoSalario(salario, liquido,",
"p1 = input(\"Nome: \") i1 = int(input(\"Idade: \")) print(\"Digite o nome da Segunda",
"\") i1 = int(input(\"Idade: \")) print(\"Digite o nome da Segunda pessoa: \") p2",
"(nota1 + nota2 + nota3) print(\"\") vb = 60.0 vr = vb -",
"= vb - notas if(notas >= vb): print(\"Nota final = {:.2f}\".format(notas)) print(\"Aprovado\") else:",
"5 - QUESTÃO 05\") print(\" 0 - PARA SAIR\") print(\"\") opcao = int(input(\"Digite",
"print(\"Diagonal: {}\".format(diagonal)) print(\"\") elif(opcao == 4): from funcionario import Funcionario print(\"ATUALIZAÇÃO DE DADOS\")",
"print(\"pessoa mais velha: {}\".format(p2)) print(\"\") elif(opcao == 2): print(\"MEDIA DE SALÁRIO\") print(\"Digite o",
"retangulo.Perimetro(A1, L1) diagonal = retangulo.Diagonal(A1, L1) print(\"Area: {}\".format(area)) print(\"Perímetro: {}\".format(perimetro)) print(\"Diagonal: {}\".format(diagonal)) print(\"\")",
"= float(input(\"Segunda nota : \")) nota3 = float(input(\"Terceira nota : \")) notas =",
"/ 2 print(\"Salário médio = {}\".format(media)) print(\"\") elif(opcao == 3): from retangulo import",
"para aumentar o salário: \")) aument = funcionario1.AumentoSalario(salario, liquido, comis) print(\"Dados Atualizados :",
"print(\"pessoa mais velha: {}\".format(p1)) else: print(\"pessoa mais velha: {}\".format(p2)) print(\"\") elif(opcao == 2):",
"imposto) print(\" \") print(\"Funcionairo : {} , R$ {}\".format(nome, liquido)) comis = float(input(\"Digite",
"QUESTÃO 04\") print(\" 5 - QUESTÃO 05\") print(\" 0 - PARA SAIR\") print(\"\")",
") / 2 print(\"Salário médio = {}\".format(media)) print(\"\") elif(opcao == 3): from retangulo",
"print(\"APROVADO OU REPROVADO\") nome = input(\"Nome do Aluno: \") nota1 = float(input(\"Primeira nota",
"float(input(\"Imposto: \")) funcionario1 = Funcionario(nome, salario, imposto) liquido = funcionario1.SalarioLiquido(salario, imposto) print(\" \")",
"PARA SAIR\") print(\"\") opcao = int(input(\"Digite o desejado: \")) clear() if(opcao == 1):",
"print(\"Perímetro: {}\".format(perimetro)) print(\"Diagonal: {}\".format(diagonal)) print(\"\") elif(opcao == 4): from funcionario import Funcionario print(\"ATUALIZAÇÃO",
"s2 ) / 2 print(\"Salário médio = {}\".format(media)) print(\"\") elif(opcao == 3): from",
"comis = float(input(\"Digite a porcentagem para aumentar o salário: \")) aument = funcionario1.AumentoSalario(salario,",
"print(\"Faltaram {:.2f} pontos\".format(vr)) print(\"\") elif(opcao == 0): break else: print(\"Valor informado inválido! \")",
"= 1 while(opcao != 0): print(\"Atividade de PARADIGMAS\") print(\" 1 - QUESTÃO 01\")",
"= {}\".format(media)) print(\"\") elif(opcao == 3): from retangulo import Retangulo print(\"LARGURA E ALTURA",
"clear = lambda: os.system('clear') clear() opcao = 1 while(opcao != 0): print(\"Atividade de",
"porcentagem para aumentar o salário: \")) aument = funcionario1.AumentoSalario(salario, liquido, comis) print(\"Dados Atualizados",
"\")) print(\"Digite o nome do Segundo funcionairo: \") p2 = input(\"Nome: \") s2",
"= int(input(\"Digite o desejado: \")) clear() if(opcao == 1): print(\"PESSOA MAIS VELHA\") print(\"Digite",
"print(\"Digite o nome do primeiro funcionairo: \") p1 = input(\"Nome: \") s1 =",
"print(\" \") print(\"Funcionairo : {} , R$ {}\".format(nome, liquido)) comis = float(input(\"Digite a",
"retangulo.Area(A1,L1) perimetro = retangulo.Perimetro(A1, L1) diagonal = retangulo.Diagonal(A1, L1) print(\"Area: {}\".format(area)) print(\"Perímetro: {}\".format(perimetro))",
"perimetro = retangulo.Perimetro(A1, L1) diagonal = retangulo.Diagonal(A1, L1) print(\"Area: {}\".format(area)) print(\"Perímetro: {}\".format(perimetro)) print(\"Diagonal:",
"float(input(\"Salário: \")) print(\"Digite o nome do Segundo funcionairo: \") p2 = input(\"Nome: \")",
"float(input(\"Salário: \")) media =(s1 + s2 ) / 2 print(\"Salário médio = {}\".format(media))",
"= {:.2f}\".format(notas)) print(\"Reprovado\") print(\"Faltaram {:.2f} pontos\".format(vr)) print(\"\") elif(opcao == 0): break else: print(\"Valor",
"lambda: os.system('clear') clear() opcao = 1 while(opcao != 0): print(\"Atividade de PARADIGMAS\") print(\"",
"a porcentagem para aumentar o salário: \")) aument = funcionario1.AumentoSalario(salario, liquido, comis) print(\"Dados",
"!= 0): print(\"Atividade de PARADIGMAS\") print(\" 1 - QUESTÃO 01\") print(\" 2 -",
"nota1 = float(input(\"Primeira nota : \")) nota2 = float(input(\"Segunda nota : \")) nota3",
"\")) if(i1 > i2): print(\"pessoa mais velha: {}\".format(p1)) else: print(\"pessoa mais velha: {}\".format(p2))",
"mais velha: {}\".format(p2)) print(\"\") elif(opcao == 2): print(\"MEDIA DE SALÁRIO\") print(\"Digite o nome",
"print(\" 3 - QUESTÃO 03\") print(\" 4 - QUESTÃO 04\") print(\" 5 -",
"\") print(\"Funcionairo : {} , R$ {}\".format(nome, liquido)) comis = float(input(\"Digite a porcentagem",
"print(\"Dados Atualizados : {} R$ {}\".format(nome, aument)) print(\"\") elif(opcao == 5): print(\"APROVADO OU",
": {} R$ {}\".format(nome, aument)) print(\"\") elif(opcao == 5): print(\"APROVADO OU REPROVADO\") nome",
"da Segunda pessoa: \") p2 = input(\"Nome: \") i2 = int(input(\"Idade: \")) if(i1",
"da primeira pessoa: \") p1 = input(\"Nome: \") i1 = int(input(\"Idade: \")) print(\"Digite",
"VELHA\") print(\"Digite o nome da primeira pessoa: \") p1 = input(\"Nome: \") i1",
"int(input(\"Digite o desejado: \")) clear() if(opcao == 1): print(\"PESSOA MAIS VELHA\") print(\"Digite o",
"== 2): print(\"MEDIA DE SALÁRIO\") print(\"Digite o nome do primeiro funcionairo: \") p1",
"Retangulo print(\"LARGURA E ALTURA DE UM RETÂNGULO\") print(\"Entre com a largura e altura",
"0): print(\"Atividade de PARADIGMAS\") print(\" 1 - QUESTÃO 01\") print(\" 2 - QUESTÃO",
"de PARADIGMAS\") print(\" 1 - QUESTÃO 01\") print(\" 2 - QUESTÃO 02\") print(\"",
"import Retangulo print(\"LARGURA E ALTURA DE UM RETÂNGULO\") print(\"Entre com a largura e",
"mais velha: {}\".format(p1)) else: print(\"pessoa mais velha: {}\".format(p2)) print(\"\") elif(opcao == 2): print(\"MEDIA",
"== 5): print(\"APROVADO OU REPROVADO\") nome = input(\"Nome do Aluno: \") nota1 =",
"1): print(\"PESSOA MAIS VELHA\") print(\"Digite o nome da primeira pessoa: \") p1 =",
"print(\"Nota final = {:.2f}\".format(notas)) print(\"Aprovado\") else: print(\"Nota final = {:.2f}\".format(notas)) print(\"Reprovado\") print(\"Faltaram {:.2f}",
"- QUESTÃO 02\") print(\" 3 - QUESTÃO 03\") print(\" 4 - QUESTÃO 04\")",
"float(input(\"Segunda nota : \")) nota3 = float(input(\"Terceira nota : \")) notas = (nota1",
"= (nota1 + nota2 + nota3) print(\"\") vb = 60.0 vr = vb",
"print(\"Digite um funcionario\") nome = input(\"Nome: \") salario = float(input(\"Salario: \")) imposto =",
"nome = input(\"Nome do Aluno: \") nota1 = float(input(\"Primeira nota : \")) nota2",
"= lambda: os.system('clear') clear() opcao = 1 while(opcao != 0): print(\"Atividade de PARADIGMAS\")",
"\")) A1 = float(input(\"Altura: \")) retangulo = Retangulo(A1,L1) area = retangulo.Area(A1,L1) perimetro =",
"Funcionario print(\"ATUALIZAÇÃO DE DADOS\") print(\"Digite um funcionario\") nome = input(\"Nome: \") salario =",
"print(\"Digite o nome da primeira pessoa: \") p1 = input(\"Nome: \") i1 =",
"03\") print(\" 4 - QUESTÃO 04\") print(\" 5 - QUESTÃO 05\") print(\" 0",
"\")) imposto = float(input(\"Imposto: \")) funcionario1 = Funcionario(nome, salario, imposto) liquido = funcionario1.SalarioLiquido(salario,",
">= vb): print(\"Nota final = {:.2f}\".format(notas)) print(\"Aprovado\") else: print(\"Nota final = {:.2f}\".format(notas)) print(\"Reprovado\")",
"elif(opcao == 2): print(\"MEDIA DE SALÁRIO\") print(\"Digite o nome do primeiro funcionairo: \")",
"aument)) print(\"\") elif(opcao == 5): print(\"APROVADO OU REPROVADO\") nome = input(\"Nome do Aluno:",
"s2 = float(input(\"Salário: \")) media =(s1 + s2 ) / 2 print(\"Salário médio",
"nome do Segundo funcionairo: \") p2 = input(\"Nome: \") s2 = float(input(\"Salário: \"))",
"RETÂNGULO\") print(\"Entre com a largura e altura do retângulo: \") L1 = float(input(\"Largura:",
"i1 = int(input(\"Idade: \")) print(\"Digite o nome da Segunda pessoa: \") p2 =",
"o nome da primeira pessoa: \") p1 = input(\"Nome: \") i1 = int(input(\"Idade:",
"= input(\"Nome: \") i1 = int(input(\"Idade: \")) print(\"Digite o nome da Segunda pessoa:",
"\")) media =(s1 + s2 ) / 2 print(\"Salário médio = {}\".format(media)) print(\"\")",
"p2 = input(\"Nome: \") i2 = int(input(\"Idade: \")) if(i1 > i2): print(\"pessoa mais",
"= float(input(\"Salário: \")) media =(s1 + s2 ) / 2 print(\"Salário médio =",
"nome da Segunda pessoa: \") p2 = input(\"Nome: \") i2 = int(input(\"Idade: \"))",
"= float(input(\"Largura: \")) A1 = float(input(\"Altura: \")) retangulo = Retangulo(A1,L1) area = retangulo.Area(A1,L1)",
"retangulo.Diagonal(A1, L1) print(\"Area: {}\".format(area)) print(\"Perímetro: {}\".format(perimetro)) print(\"Diagonal: {}\".format(diagonal)) print(\"\") elif(opcao == 4): from",
", R$ {}\".format(nome, liquido)) comis = float(input(\"Digite a porcentagem para aumentar o salário:",
"if(notas >= vb): print(\"Nota final = {:.2f}\".format(notas)) print(\"Aprovado\") else: print(\"Nota final = {:.2f}\".format(notas))",
"OU REPROVADO\") nome = input(\"Nome do Aluno: \") nota1 = float(input(\"Primeira nota :",
"nota : \")) nota3 = float(input(\"Terceira nota : \")) notas = (nota1 +",
"05\") print(\" 0 - PARA SAIR\") print(\"\") opcao = int(input(\"Digite o desejado: \"))",
"\") p1 = input(\"Nome: \") i1 = int(input(\"Idade: \")) print(\"Digite o nome da",
"elif(opcao == 5): print(\"APROVADO OU REPROVADO\") nome = input(\"Nome do Aluno: \") nota1",
": \")) nota2 = float(input(\"Segunda nota : \")) nota3 = float(input(\"Terceira nota :",
"print(\" 4 - QUESTÃO 04\") print(\" 5 - QUESTÃO 05\") print(\" 0 -",
"L1) print(\"Area: {}\".format(area)) print(\"Perímetro: {}\".format(perimetro)) print(\"Diagonal: {}\".format(diagonal)) print(\"\") elif(opcao == 4): from funcionario",
"print(\"Digite o nome do Segundo funcionairo: \") p2 = input(\"Nome: \") s2 =",
"- QUESTÃO 01\") print(\" 2 - QUESTÃO 02\") print(\" 3 - QUESTÃO 03\")",
"vb - notas if(notas >= vb): print(\"Nota final = {:.2f}\".format(notas)) print(\"Aprovado\") else: print(\"Nota",
"QUESTÃO 05\") print(\" 0 - PARA SAIR\") print(\"\") opcao = int(input(\"Digite o desejado:",
"+ s2 ) / 2 print(\"Salário médio = {}\".format(media)) print(\"\") elif(opcao == 3):",
"ALTURA DE UM RETÂNGULO\") print(\"Entre com a largura e altura do retângulo: \")",
"print(\"MEDIA DE SALÁRIO\") print(\"Digite o nome do primeiro funcionairo: \") p1 = input(\"Nome:",
"int(input(\"Idade: \")) if(i1 > i2): print(\"pessoa mais velha: {}\".format(p1)) else: print(\"pessoa mais velha:",
"final = {:.2f}\".format(notas)) print(\"Reprovado\") print(\"Faltaram {:.2f} pontos\".format(vr)) print(\"\") elif(opcao == 0): break else:",
"A1 = float(input(\"Altura: \")) retangulo = Retangulo(A1,L1) area = retangulo.Area(A1,L1) perimetro = retangulo.Perimetro(A1,",
"Atualizados : {} R$ {}\".format(nome, aument)) print(\"\") elif(opcao == 5): print(\"APROVADO OU REPROVADO\")",
"= Retangulo(A1,L1) area = retangulo.Area(A1,L1) perimetro = retangulo.Perimetro(A1, L1) diagonal = retangulo.Diagonal(A1, L1)",
"= funcionario1.SalarioLiquido(salario, imposto) print(\" \") print(\"Funcionairo : {} , R$ {}\".format(nome, liquido)) comis",
"float(input(\"Digite a porcentagem para aumentar o salário: \")) aument = funcionario1.AumentoSalario(salario, liquido, comis)",
"velha: {}\".format(p2)) print(\"\") elif(opcao == 2): print(\"MEDIA DE SALÁRIO\") print(\"Digite o nome do",
"else: print(\"pessoa mais velha: {}\".format(p2)) print(\"\") elif(opcao == 2): print(\"MEDIA DE SALÁRIO\") print(\"Digite",
"1 while(opcao != 0): print(\"Atividade de PARADIGMAS\") print(\" 1 - QUESTÃO 01\") print(\"",
"- QUESTÃO 03\") print(\" 4 - QUESTÃO 04\") print(\" 5 - QUESTÃO 05\")",
"- QUESTÃO 04\") print(\" 5 - QUESTÃO 05\") print(\" 0 - PARA SAIR\")",
"imposto) liquido = funcionario1.SalarioLiquido(salario, imposto) print(\" \") print(\"Funcionairo : {} , R$ {}\".format(nome,",
"= float(input(\"Terceira nota : \")) notas = (nota1 + nota2 + nota3) print(\"\")",
"- notas if(notas >= vb): print(\"Nota final = {:.2f}\".format(notas)) print(\"Aprovado\") else: print(\"Nota final",
"\") p1 = input(\"Nome: \") s1 = float(input(\"Salário: \")) print(\"Digite o nome do",
"print(\"Funcionairo : {} , R$ {}\".format(nome, liquido)) comis = float(input(\"Digite a porcentagem para",
"funcionario1.AumentoSalario(salario, liquido, comis) print(\"Dados Atualizados : {} R$ {}\".format(nome, aument)) print(\"\") elif(opcao ==",
"vr = vb - notas if(notas >= vb): print(\"Nota final = {:.2f}\".format(notas)) print(\"Aprovado\")",
"print(\"\") elif(opcao == 2): print(\"MEDIA DE SALÁRIO\") print(\"Digite o nome do primeiro funcionairo:",
"60.0 vr = vb - notas if(notas >= vb): print(\"Nota final = {:.2f}\".format(notas))",
"{}\".format(perimetro)) print(\"Diagonal: {}\".format(diagonal)) print(\"\") elif(opcao == 4): from funcionario import Funcionario print(\"ATUALIZAÇÃO DE",
"liquido)) comis = float(input(\"Digite a porcentagem para aumentar o salário: \")) aument =",
"funcionario\") nome = input(\"Nome: \") salario = float(input(\"Salario: \")) imposto = float(input(\"Imposto: \"))",
"= funcionario1.AumentoSalario(salario, liquido, comis) print(\"Dados Atualizados : {} R$ {}\".format(nome, aument)) print(\"\") elif(opcao",
"liquido, comis) print(\"Dados Atualizados : {} R$ {}\".format(nome, aument)) print(\"\") elif(opcao == 5):",
"\") i2 = int(input(\"Idade: \")) if(i1 > i2): print(\"pessoa mais velha: {}\".format(p1)) else:",
"1 - QUESTÃO 01\") print(\" 2 - QUESTÃO 02\") print(\" 3 - QUESTÃO",
"clear() opcao = 1 while(opcao != 0): print(\"Atividade de PARADIGMAS\") print(\" 1 -",
"vb = 60.0 vr = vb - notas if(notas >= vb): print(\"Nota final",
"float(input(\"Largura: \")) A1 = float(input(\"Altura: \")) retangulo = Retangulo(A1,L1) area = retangulo.Area(A1,L1) perimetro",
"\") s2 = float(input(\"Salário: \")) media =(s1 + s2 ) / 2 print(\"Salário",
"funcionairo: \") p2 = input(\"Nome: \") s2 = float(input(\"Salário: \")) media =(s1 +",
"{}\".format(diagonal)) print(\"\") elif(opcao == 4): from funcionario import Funcionario print(\"ATUALIZAÇÃO DE DADOS\") print(\"Digite",
"retangulo import Retangulo print(\"LARGURA E ALTURA DE UM RETÂNGULO\") print(\"Entre com a largura",
"aument = funcionario1.AumentoSalario(salario, liquido, comis) print(\"Dados Atualizados : {} R$ {}\".format(nome, aument)) print(\"\")",
"Aluno: \") nota1 = float(input(\"Primeira nota : \")) nota2 = float(input(\"Segunda nota :",
"funcionario1.SalarioLiquido(salario, imposto) print(\" \") print(\"Funcionairo : {} , R$ {}\".format(nome, liquido)) comis =",
"02\") print(\" 3 - QUESTÃO 03\") print(\" 4 - QUESTÃO 04\") print(\" 5",
"- QUESTÃO 05\") print(\" 0 - PARA SAIR\") print(\"\") opcao = int(input(\"Digite o",
"elif(opcao == 3): from retangulo import Retangulo print(\"LARGURA E ALTURA DE UM RETÂNGULO\")",
"altura do retângulo: \") L1 = float(input(\"Largura: \")) A1 = float(input(\"Altura: \")) retangulo",
"0 - PARA SAIR\") print(\"\") opcao = int(input(\"Digite o desejado: \")) clear() if(opcao"
] |
[
"from amara.xpath.locationpaths import nodetests from amara.xpath.functions import nodesets from amara.xpath.expressions import booleans import",
"for attr_op in attr_ops: print attr_op print \" PI OPS\" for pi_op in",
"This would yield nodes, attribute, PIs, and comments #class AnyTest(object): # pass class",
"= id self.xpath = xpath self._nfa = nfa def nfas_to_machine_states(nfas): union_nfa = nfas[0].copy()",
"path) # \"@a\", \"a/@b\", and even \"@a/@b\", which gives nothing nfa = NFA()",
"tree.if_false) tree.if_false = new_branch else: self._add(tree.if_false, new_false_test, to_node_id, intersect) def _add_to_leaves(self, tree, to_node_id):",
"labels for (name, tree) in ( (\"NODE\", self.node_tree), (\"ATTR\", self.attr_tree), (\"PROCESSING-INSTRUCTION\", self.pi_tree), (\"COMMENT\",",
"like # \"a\" \"a/b\", \"a/b/c[0]/d[@x]\" (relative location path) # \"@a\", \"a/@b\", and even",
"#manager.add(\".//*\") machine_states = manager._build_machine_states() dump_machine_states(machine_states) hand = RuleMachineHandler(machine_states) import os doc = amara.parse(testxml,rule_handler=hand)",
"amara.xpath.expressions.nodesets.union_expr: # \"a|b\" nfa = to_nfa(expr._paths[0], namespaces) for path in expr._paths[1:]: nfa.union(to_nfa(path, namespaces))",
"v in inspect.getmembers(expr): if k.startswith(\"__\") and k.endswith(\"__\"): continue print repr(k), repr(v) raise AssertionError(expr)",
"is a set of path specifiers like # \"a\" \"a/b\", \"a/b/c[0]/d[@x]\" (relative location",
"x in enumerate(machine_states): print \"== INFO FOR\", i, \"==\" handlers, node_ops, attr_ops, pi_ops,",
"class ProcessingInstructionTest(object): match_type = \"processing-instruction\" def __init__(self, target): self.target = target def __str__(self):",
"# otherwise, loop #print \"GoTo\", next_state self.stack.append(next_state) handlers = self.machine_states[next_state][0] for handler in",
"xpath_handler): nfa = to_nfa(xpath_parser.parse(xpath), self.namespaces) i = len(self.expressions) nfa.add_handler((i, xpath_handler)) exp = Expression(i,",
"loop def to_nfa(expr, namespaces): #print \"Eval\", expr.__class__ if (expr.__class__ is locationpaths.relative_location_path): # This",
"if parent_test is not None: assert isinstance(parent_test, ProcessingInstructionTest), parent_test assert isinstance(child_test, ProcessingInstructionTest), child_test",
"expr.__class__ if (expr.__class__ is locationpaths.relative_location_path): # This is a set of path specifiers",
"class AttributeFunctionCallPred(object): def __init__(self, func): self.func = func ##### # This would yield",
"= end_node_handler, attr_handler = attr_handler) def dump_machine_states(machine_states): for i, x in enumerate(machine_states): print",
"handlers.append(handler) # node tree tree = table.node_tree.if_true if isinstance(tree, set): # Special case",
"False return False, child_test def attr_intersect(parent_test, child_test): if parent_test is not None: assert",
"node_ops = [(None, None, None, -numbering[frozenset(tree)])] else: node_ops = [tree] todo = [0]",
"ns, ln, test_function, if_true, if_false = element_ops[i] assert test_function is None if ((ns",
"localname=%r predicates=%r\" % (self.name[0], self.name[1], self.predicates) # predicates make no sense here because",
"fails. # TODO: something more sophisticated? For example, if there are a #",
"everything? for nfa in nfas[1:]: union_nfa.union(nfa) dfa, numbering = nfa_to_dfa(union_nfa) return build_states(union_nfa, dfa,",
"are in (id, class) pairs) table = dfa[node_ids] if dfa_id == 0: handlers",
"[(dfa_start, None)] while todo: current_dfa, match_type = todo.pop() #print \"All transitions from\", current_dfa",
"# Match any attribute attr_ops.append( (None, None, numbering[frozenset(tree)]) ) attr_ops = tuple(attr_ops) #",
"child_test def comment_intersect(parent_test, child_test): if parent_test is not None: assert isinstance(parent_test, CommentTest), parent_test",
"\"tree:\" # The first branch is always true self._dump(tree.if_true, 0, numbering) def _dump(self,",
"=\", comment_state class PushtreeHandler(object): def startSubtree(self, element): pass def endSubtree(self, element): pass def",
"AttributeFunctionCallPred(object): def __init__(self, func): self.func = func ##### # This would yield nodes,",
"XXX check for predicates! if parent_test.name == child_test.name: return True, False return False,",
"node): pass def commentMatch(self, node): pass def processingInstructionMatch(self, node): pass class VerbosePushtreeHandler(PushtreeHandler): def",
"= NFA() for step in expr._steps: axis = step.axis axis_name = axis.name assert",
"pi_ops, comment_state = x print \" HANDLERS\", handlers print \" NODE OPS\" for",
"# pass class BaseNodeTest(object): match_type = \"node\" # What about *[@spam] ? class",
"test</li> <li x='2'><a href='spam'>that</a> was nothing</li> </ul> </body> \"\"\" manager = PushtreeManager(\"body/ul/li\", VerbosePushtreeHandler(\"main\"))",
"def __init__(self): self.start_edges = [] self.edges = {} # from_node_id -> [(to_node_id, test),",
"nothing leading off from it #print \"GOTO -1\" self.stack.append(-1) return namespace, localname =",
"nfa.connect(any_node, to_node_id, test) nfa.connect(any_node, any_node, AnyNodeTest()) # loop def to_nfa(expr, namespaces): #print \"Eval\",",
"is None: print \" No\", name, \"tree\" else: print name, \"tree:\" # The",
"return nfa if (expr.__class__ is locationpaths.abbreviated_absolute_location_path): # This is an abbreviated_absolute_location_path # \"//a\",",
"current_dfa transitions = all_transitions(nfa, current_dfa) if not transitions: # Make sure there's always",
"for node_id, edges in [(None, self.start_edges)] + sorted(self.edges.items()): if node_id is None: node_name",
"set([dfa_start]) todo = [(dfa_start, None)] while todo: current_dfa, match_type = todo.pop() #print \"All",
"result, numbering def die(expr): import inspect print \" == FAILURE ==\" print type(expr)",
"return self.start_edges return self.edges[node_id] def add_handler(self, labeled_handler): for node_id in self.terminal_nodes: self.labeled_handlers[node_id].append(labeled_handler) def",
"nfa.connect(any_node, any_node, AnyNodeTest()) # loop def to_nfa(expr, namespaces): #print \"Eval\", expr.__class__ if (expr.__class__",
"numbering = nfa_to_dfa(union_nfa) return build_states(union_nfa, dfa, numbering) class PushtreeManager(object): def __init__(self, subtree_xpath, subtree_handler",
"parent_test assert isinstance(child_test, AttributeTest), child_test if parent_test is None: return child_test, False if",
"NFA() node_test = expr.node_test if node_test.__class__ is nodetests.local_name_test: # Something without a namespace,",
"pattern, end_node_handler, attr_handler, namespaces=None): self.xpm = xpm = ExpressionManager(namespaces=namespaces); xpm.add(pattern) nfa, dfa, numbering",
"= None, namespaces = None): if namespaces is None: namespaces = {} self.namespaces",
"(handlers, node_ops, attr_ops, pi_ops, comment_state) ) return tuple(states) class Expression(object): def __init__(self, id,",
"attribute, comment, etc. transitions state_table = StateTable(match_type, nfa, current_dfa) for to_node_id, test in",
"in sorted( (dfa_id, node_ids) for (node_ids, dfa_id) in numbering.items() ): assert dfa_id ==",
"elif new_false_test: if isinstance(tree.if_false, set): new_branch = Branch(new_false_test, tree.if_false | set([to_node_id]), tree.if_false) tree.if_false",
"self.xpm = xpm = ExpressionManager(namespaces=namespaces); xpm.add(pattern) nfa, dfa, numbering = xpm.build_dfa_tables() machine_states =",
"all_transitions(nfa, current_dfa): transitions = [] for node_id in current_dfa: if node_id is None:",
"= [tree] todo = [0] while todo: i = todo.pop() #print \"Access\", i,",
"if_false) #print \"Added\", node_ops[i] if if_false > 0: todo.append(if_false) if if_true > 0:",
"to_node_id) def get_final_nodes(self): result = {} for match_type, tree in ( (BaseNodeTest.match_type, self.node_tree),",
"unique node numbers states = [] for dfa_id, node_ids in sorted( (dfa_id, node_ids)",
"node): print self.prefix+\"attributeMatch\", node def commentMatch(self, node): print self.prefix+\"commentMatch\", node def processingInstructionMatch(self, node):",
"[0] #dump_machine_states(self.machine_states) def startElementNS(self, node, name, qname, attrs): state = self.stack[-1] #print \"startElementNS\",",
"xpath, nfa) self.expressions.append(exp) return exp def add(self, xpath, xpath_handler=None): return self._add(xpath, xpath_handler) def",
"not isinstance(tree, set): target = tree.test.target pi_ops.append( (target, numbering[frozenset(tree.if_true)]) ) tree = tree.if_false",
"else: node_ops = [tree] todo = [0] while todo: i = todo.pop() #print",
"valid target, but there's nothing leading off from it #print \"GOTO -1\" self.stack.append(-1)",
"(to_node_id, test) in edge in nfa_state.edges: if edge[0] == event: yield edge[1] #",
"node_op in node_ops: print node_op print \" ATTR OPS\" for attr_op in attr_ops:",
"self.start_edges)] + sorted(self.edges.items()): if node_id is None: node_name = \"(start)\" labels = \"\"",
"= Branch(new_false_test, tree.if_false | set([to_node_id]), tree.if_false) tree.if_false = new_branch else: self._add(tree.if_false, new_false_test, to_node_id,",
"next_state self.stack.append(next_state) handlers = self.machine_states[next_state][0] for handler in handlers: handler.startElementMatch(node) # Also handle",
"(name, tree) in ( (\"NODE\", self.node_tree), (\"ATTR\", self.attr_tree), (\"PROCESSING-INSTRUCTION\", self.pi_tree), (\"COMMENT\", self.comment_tree) ):",
"step along the child axis, with two predicates # \"@a\" - step along",
"isinstance(tree.if_true, set): new_branch = Branch(new_true_test, tree.if_true | set([to_node_id]), tree.if_true) tree.if_true = new_branch else:",
"node_ids == set([None]) # handlers (which are in (id, class) pairs) table =",
"NodeTest): return child_test, False elif isinstance(parent_test, NodeTest): if isinstance(child_test, AnyNodeTest): return True, True",
"isinstance(child_test, NodeTest): return child_test, False elif isinstance(parent_test, NodeTest): if isinstance(child_test, AnyNodeTest): return True,",
"for nfa_node in self.nfa_node_ids: labels = [x[0] for x in self.nfa.labeled_handlers[nfa_node]] if labels:",
"return result, numbering def die(expr): import inspect print \" == FAILURE ==\" print",
"like \"a\" node_id = nfa.new_node(None, klass(node_test.name_key, expr.predicates)) elif node_test.__class__ is nodetests.namespace_test: # Namespace",
"localname)): i = if_true else: i = if_false if i == 0: #",
"node): pass class VerbosePushtreeHandler(PushtreeHandler): def __init__(self, prefix=None): if prefix is None: prefix =",
"node_id is None: return self.start_edges return self.edges[node_id] def add_handler(self, labeled_handler): for node_id in",
"_build_machine_states(self): return nfas_to_machine_states([x._nfa for x in self.expressions]) def build_pushtree_handler(self): return RuleMachineHandler(self._build_machine_states()) # Special",
"start_edges = nfa.start_edges[:] any_node = nfa.new_node(None, AnyNodeTest()) for (to_node_id, test) in start_edges: nfa.connect(any_node,",
"or ln == localname)): i = if_true else: i = if_false if i",
"parser as xpath_parser from amara.xpath import locationpaths from amara.xpath.locationpaths import axisspecifiers from amara.xpath.locationpaths",
"labels self._dump_edges(edges) print \"======\" def _dump_edges(self, edges): for (to_node_id, test) in edges: print",
"klass(node_test.name_key, expr.predicates)) elif node_test.__class__ is nodetests.namespace_test: # Namespace but no name, like \"a:*\"",
"tag tests then sort the tags and start # in the middle. Should",
"while todo: current_dfa, match_type = todo.pop() #print \"All transitions from\", current_dfa transitions =",
"test:\", (ns, ln), (namespace, localname) if ((ns is None or namespace == ns)",
"class PushtreeManager(object): def __init__(self, subtree_xpath, subtree_handler = None, namespaces = None): if namespaces",
"print s, \"<> (empty)\" else: print s, tree.test, \"?\" self._dump(tree.if_true, depth+1, numbering) self._dump(tree.if_false,",
"= {} # from_node_id -> [(to_node_id, test), ...] self.terminal_nodes = set() # The",
"qname last_state = self.stack.pop() if last_state == -1: return handlers = self.machine_states[last_state][0] for",
"print self.prefix+\"endSubtree\", element def startElementMatch(self, node): print self.prefix+\"startElementMatch\", node def endElementMatch(self, node): print",
"assert not predicates self.predicates = predicates def __str__(self): return \"Attr name=%r\" % (self.name,)",
"is always true self._dump(tree.if_true, 0, numbering) def _dump(self, tree, depth, numbering): s =",
"return False, child_test def attr_intersect(parent_test, child_test): if parent_test is not None: assert isinstance(parent_test,",
"new_true_test == True: self._add_to_leaves(tree.if_true, to_node_id) elif new_true_test: if isinstance(tree.if_true, set): new_branch = Branch(new_true_test,",
"labels = [x[0] for x in self.nfa.labeled_handlers[nfa_node]] if labels: print \"Report\", self.nfa.match_types[nfa_node], labels",
"= len(numbering) # for k, table in sorted(result.items(), key=lambda x:sorted(x[0])): # print \"State\",",
"while visit: node = visit.pop() if isinstance(node, set): if node: result[frozenset(node)] = match_type",
"sense here because we only support downward axes # and these have no",
"the attribute axis axis = expr.axis axis_name = axis.name assert axis_name in (\"child\",",
"a step along some axis, such as: # \"a\" - step along the",
"node_id = nfa.new_node(None, klass((namespace, None), expr.predicates)) elif node_test.__class__ is nodetests.qualified_name_test: prefix, localname =",
"print self.prefix+\"commentMatch\", node def processingInstructionMatch(self, node): print self.prefix+\"processingInstructionMatch\", node if __name__ == '__main__':",
"except the startElement and # endElement use different method. handlers = [] for",
"of path specifiers like # \"a\" \"a/b\", \"a/b/c[0]/d[@x]\" (relative location path) # \"@a\",",
"[] self._add(subtree_xpath, subtree_handler) def _add(self, xpath, xpath_handler): nfa = to_nfa(xpath_parser.parse(xpath), self.namespaces) i =",
"(node, (namespace, localname) ) ) def endElementNS(self, node, name, qname): #print \"endElementNS\", node,",
"[(None, None, None, -numbering[frozenset(tree)])] else: node_ops = [tree] todo = [0] while todo:",
"decisions to make if not tree: node_ops = [] # ... because there",
"if pi_target == target: handlers = self.machine_states[pi_state][0] for handler in handlers: handler.processingInstruction(node) #",
"actual instances I need except the startElement and # endElement use different method.",
"xpm.build_dfa_tables() machine_states = build_instructions(nfa,dfa,numbering) RuleMachineHandler.__init__(self, machine_states, end_node_handler = end_node_handler, attr_handler = attr_handler) def",
"defined to have no attributes self.stack.append(-1) return if i < 0: next_state =",
"transition from something # which wasn't a node or a record match_type =",
"match_type = todo.pop() #print \"All transitions from\", current_dfa transitions = all_transitions(nfa, current_dfa) if",
"intersect) def _add_to_leaves(self, tree, to_node_id): if isinstance(tree, set): tree.add(to_node_id) else: self._add_to_leaves(tree.if_true, to_node_id) self._add_to_leaves(tree.if_false,",
"= self.stack.pop() if last_state == -1: return handlers = self.machine_states[last_state][0] for handler in",
"intersect): new_true_test, new_false_test = intersect(tree.test, test) if new_true_test == True: self._add_to_leaves(tree.if_true, to_node_id) elif",
"self.op = op self.value = value class AttributeFunctionCallPred(object): def __init__(self, func): self.func =",
"self.pi_tree), (\"COMMENT\", self.comment_tree) ): if tree is None: print \" No\", name, \"tree\"",
"to_node_id) elif new_true_test: if isinstance(tree.if_true, set): new_branch = Branch(new_true_test, tree.if_true | set([to_node_id]), tree.if_true)",
"def _dump_edges(self, edges): for (to_node_id, test) in edges: print \"\", test, \"->\", to_node_id",
"in self.labeled_handlers[node_id]]) is_terminal = \"(terminal)\" if (node_id in self.terminal_nodes) else \"\" print node_name,",
"self.start_edges return self.edges[node_id] def add_handler(self, labeled_handler): for node_id in self.terminal_nodes: self.labeled_handlers[node_id].append(labeled_handler) def new_node(self,",
"if_false class StateTable(object): def __init__(self, match_type, nfa, nfa_node_ids): self.match_type = match_type # 'None'",
"in handlers: handler.startElementMatch(node) # Also handle any attributes attr_ops = self.machine_states[next_state][2] if not",
"= frozenset(nfa_nodes) if some_dfa not in seen: seen.add(some_dfa) todo.append( (some_dfa, match_type) ) result[current_dfa]",
"attribute attr_ops.append( (None, None, numbering[frozenset(tree)]) ) attr_ops = tuple(attr_ops) # processing instruction tree",
"nodesets! from amara.xpath.expressions import basics counter = itertools.count(1) # [@x] class AttributeExistsPred(object): def",
"is None or ln == localname)): i = if_true else: i = if_false",
"namespaces = {} self.namespaces = namespaces self.expressions = [] self._add(subtree_xpath, subtree_handler) def _add(self,",
"if node: result[frozenset(node)] = match_type elif node is not None: visit.append(node.if_true) visit.append(node.if_false) return",
"\" \" + str([x[0] for x in self.labeled_handlers[node_id]]) is_terminal = \"(terminal)\" if (node_id",
"if node_id is None: return self.start_edges return self.edges[node_id] def add_handler(self, labeled_handler): for node_id",
"None): if namespaces is None: namespaces = {} self.namespaces = namespaces self.expressions =",
"_add_initial_loop(nfa) return nfa if (expr.__class__ is locationpaths.absolute_location_path): # This is an absolute path",
"test): self.get_edges(from_node_id).append( (to_node_id, test) ) def extend(self, other): assert not set(self.edges) & set(other.edges),",
"element_ops = self.machine_states[state][1] if not element_ops: # This was a valid target, but",
"def copy(self): nfa = NFA() nfa.start_edges[:] = self.start_edges nfa.edges.update(self.edges) nfa.terminal_nodes.update(self.terminal_nodes) nfa.match_types.update(self.match_types) nfa.labeled_handlers.update(self.labeled_handlers) return",
"amara.xpath.locationpaths import axisspecifiers from amara.xpath.locationpaths import nodetests from amara.xpath.functions import nodesets from amara.xpath.expressions",
"anything for having reached here? if list(self.nfa_node_ids) != [None]: for nfa_node in self.nfa_node_ids:",
"match_type, tree in ( (BaseNodeTest.match_type, self.node_tree), (AttributeTest.match_type, self.attr_tree), (ProcessingInstructionTest.match_type, self.pi_tree), (CommentTest.match_type, self.comment_tree) ):",
"isinstance(test, CommentTest): self._add(self.comment_tree, test, to_node_id, comment_intersect) else: raise AssertionError(test) def _add(self, tree, test,",
"== -1: return pi_ops = self.machine_states[state][3] for (pi_target, pi_state) in pi_ops: if pi_target",
"nfa.edges[node_id] transitions.extend(new_transitions) return transitions def transition(nfa_state, event): for (to_node_id, test) in edge in",
"numbering[current_dfa] = len(numbering) continue # This adds element, attribute, comment, etc. transitions state_table",
"None, -numbering[frozenset(tree)])] else: node_ops = [tree] todo = [0] while todo: i =",
"node self.nfa = nfa self.nfa_node_ids = nfa_node_ids self.node_tree = Branch(None, set(), set()) self.attr_tree",
"(\"COMMENT\", self.comment_tree) ): if tree is None: print \" No\", name, \"tree\" else:",
"name, qname): #print \"endElementNS\", node, name, qname last_state = self.stack.pop() if last_state ==",
"a string if parent_test.target == child_test.target: return True, False return False, child_test def",
"two predicates # \"@a\" - step along the attribute axis axis = expr.axis",
"method. handlers = [] for (label, handler) in sorted(handler_map.items()): handlers.append(handler) # node tree",
"attribute node handler.attributeMatch( (node, (namespace, localname) ) ) def endElementNS(self, node, name, qname):",
"return transitions def transition(nfa_state, event): for (to_node_id, test) in edge in nfa_state.edges: if",
"\" HANDLERS\", handlers print \" NODE OPS\" for node_op in node_ops: print node_op",
"None: assert isinstance(parent_test, AttributeTest), parent_test assert isinstance(child_test, AttributeTest), child_test if parent_test is None:",
"self.stack.append(-1) return namespace, localname = name i = 0 while 1: ns, ln,",
"isinstance(child_test, ProcessingInstructionTest), child_test if parent_test is None: return child_test, False # Is there",
"step in expr._steps: axis = step.axis axis_name = axis.name assert axis_name in (\"child\",",
"= namespaces[prefix] node_id = nfa.new_node(None, klass((namespace, localname), expr.predicates)) elif node_test.__class__ is nodetests.processing_instruction_test: node_id",
"match *any* PI? # Looks like Amara support XPath 1.0, where this is",
"= \"\" else: node_name = str(node_id) action = str(self.match_types[node_id]) labels += \" \"",
"or ns == namespace) and (ln is None or ln == localname)): i",
"| set([to_node_id]), tree.if_false) tree.if_false = new_branch else: self._add(tree.if_false, new_false_test, to_node_id, intersect) def _add_to_leaves(self,",
"sorted(handler_map.items()): handlers.append(handler) # node tree tree = table.node_tree.if_true if isinstance(tree, set): # Special",
"= to_nfa(xpath_parser.parse(xpath), self.namespaces) i = len(self.expressions) nfa.add_handler((i, xpath_handler)) exp = Expression(i, xpath, nfa)",
"expr.predicates)) elif node_test.__class__ is nodetests.qualified_name_test: prefix, localname = node_test.name_key namespace = namespaces[prefix] node_id",
"else: handler_map = {} for node_id in node_ids: for (label, handler) in nfa.labeled_handlers[node_id]:",
"return nfa die(expr) def node_intersect(parent_test, child_test): if parent_test is not None: assert isinstance(parent_test,",
"handler object to bridge with pushbind support in the builder # Implemented by",
"node numbers states = [] for dfa_id, node_ids in sorted( (dfa_id, node_ids) for",
"- step along the child axis, with two predicates # \"@a\" - step",
"getattr(parent_test, \"predicates\", None) is None assert isinstance(child_test, BaseNodeTest), child_test assert getattr(child_test, \"predicates\", None)",
"pi_ops, comment_state) ) return tuple(states) class Expression(object): def __init__(self, id, xpath, nfa): self.id",
"return nfa def get_edges(self, node_id): if node_id is None: return self.start_edges return self.edges[node_id]",
"n is no more than 10 or so. class Branch(object): def __init__(self, test,",
"return exp def add(self, xpath, xpath_handler=None): return self._add(xpath, xpath_handler) def _build_machine_states(self): return nfas_to_machine_states([x._nfa",
"None: node_name = \"(start)\" labels = \"\" else: node_name = str(node_id) action =",
"= nfa.new_node(None, AnyNodeTest()) for (to_node_id, test) in start_edges: nfa.connect(any_node, to_node_id, test) nfa.connect(any_node, any_node,",
"self.namespaces) i = len(self.expressions) nfa.add_handler((i, xpath_handler)) exp = Expression(i, xpath, nfa) self.expressions.append(exp) return",
"is not a proper SAX handler class RuleMachineHandler(object): def __init__(self, machine_states): self.machine_states =",
"state_table.get_final_nodes(): some_dfa = frozenset(nfa_nodes) if some_dfa not in seen: seen.add(some_dfa) todo.append( (some_dfa, match_type)",
"value): self.name = name self.op = op self.value = value class AttributeFunctionCallPred(object): def",
"AnyNodeTest()) for (to_node_id, test) in start_edges: nfa.connect(any_node, to_node_id, test) nfa.connect(any_node, any_node, AnyNodeTest()) #",
"(self.name,) class ProcessingInstructionTest(object): match_type = \"processing-instruction\" def __init__(self, target): self.target = target def",
"in transitions: state_table.add(test, to_node_id) for nfa_nodes, match_type in state_table.get_final_nodes(): some_dfa = frozenset(nfa_nodes) if",
"len(node_ops) tree = node_ops[i] if isinstance(tree.if_true, set): if tree.if_true: if_true = -numbering[frozenset(tree.if_true)] else:",
"if k.startswith(\"__\") and k.endswith(\"__\"): continue print repr(k), repr(v) raise AssertionError(expr) def build_states(nfa, dfa,",
"parent_test assert isinstance(child_test, ProcessingInstructionTest), child_test if parent_test is None: return child_test, False #",
"true self._dump(tree.if_true, 0, numbering) def _dump(self, tree, depth, numbering): s = \"-\"*depth if",
"nodetests.processing_instruction_test: node_id = nfa.new_node(None, ProcessingInstructionTest(node_test._target)) elif node_test.__class__ is locationpaths.nodetests.principal_type_test: node_id = nfa.new_node(None, klass((None,",
"attr tree attr_ops = [] tree = table.attr_tree.if_true while not isinstance(tree, set): namespace,",
"None: assert isinstance(parent_test, ProcessingInstructionTest), parent_test assert isinstance(child_test, ProcessingInstructionTest), child_test if parent_test is None:",
"locationpaths.abbreviated_absolute_location_path): # This is an abbreviated_absolute_location_path # \"//a\", \"a//b\" nfa = NFA() for",
"or localname == ln)): # Match! handlers = self.machine_states[attr_state_id][0] for handler in handlers:",
"= \"(terminal)\" if (node_id in self.terminal_nodes) else \"\" print node_name, is_terminal, labels self._dump_edges(edges)",
"prefix = \"\" else: prefix = \"(%s) \" % (prefix,) self.prefix = prefix",
"(ln is None or ln == localname)): i = if_true else: i =",
"tree.test.target pi_ops.append( (target, numbering[frozenset(tree.if_true)]) ) tree = tree.if_false if tree: pi_ops.append( (None, numbering[frozenset(tree)])",
"-numbering[frozenset(tree)])] else: node_ops = [tree] todo = [0] while todo: i = todo.pop()",
"in self.nfa.labeled_handlers[nfa_node]] if labels: print \"Report\", self.nfa.match_types[nfa_node], labels for (name, tree) in (",
"= nfa_to_dfa(union_nfa) return build_states(union_nfa, dfa, numbering) class PushtreeManager(object): def __init__(self, subtree_xpath, subtree_handler =",
"= new_branch else: self._add(tree.if_true, new_true_test, to_node_id, intersect) if new_false_test == True: self._add_to_leaves(tree.if_false, to_node_id)",
"= tuple(pi_ops) # comment tree tree = table.comment_tree.if_true assert isinstance(tree, set) if tree:",
"current_dfa) for to_node_id, test in transitions: state_table.add(test, to_node_id) for nfa_nodes, match_type in state_table.get_final_nodes():",
"{} # from frozenset -> 0, 1, 2, ... dfa_start = frozenset([None]) #",
"there are no decisions to make if not tree: node_ops = [] #",
"handlers = self.machine_states[next_state][0] for handler in handlers: handler.startElementMatch(node) # Also handle any attributes",
"-> 0, 1, 2, ... dfa_start = frozenset([None]) # nfa start node result",
"node_id = nfa.new_node(None, klass((None, None), None)) else: die(node_test) nfa.terminal_nodes.add(node_id) #if axis_name == \"descendant\":",
"= tuple(node_ops) # attr tree attr_ops = [] tree = table.attr_tree.if_true while not",
"[] self.match_types[to_node_id] = test.match_type self.labeled_handlers[to_node_id] = [] edges.append( (to_node_id, test) ) return to_node_id",
"def add(self, test, to_node_id): if isinstance(test, BaseNodeTest): self._add(self.node_tree, test, to_node_id, node_intersect) elif isinstance(test,",
"start_edges: nfa.connect(any_node, to_node_id, test) nfa.connect(any_node, any_node, AnyNodeTest()) # loop def to_nfa(expr, namespaces): #print",
"\"descendant\"), axis_name subnfa = to_nfa(step, namespaces) if axis_name == \"descendant\": _add_initial_loop(subnfa) nfa.extend(subnfa) return",
"self.value = value class AttributeFunctionCallPred(object): def __init__(self, func): self.func = func ##### #",
"give O(log(number of tags)) performance # instead of O(n). However, for now, n",
"is_terminal = \"(terminal)\" if (node_id in self.terminal_nodes) else \"\" print node_name, is_terminal, labels",
"startSubtree(self, element): pass def endSubtree(self, element): pass def startElementMatch(self, node): pass def endElementMatch(self,",
"self._add_to_leaves(tree.if_false, to_node_id) def get_final_nodes(self): result = {} for match_type, tree in ( (BaseNodeTest.match_type,",
"PIs, and comments #class AnyTest(object): # pass class BaseNodeTest(object): match_type = \"node\" #",
"self._dump_edges(edges) print \"======\" def _dump_edges(self, edges): for (to_node_id, test) in edges: print \"\",",
"VerbosePushtreeHandler(\"@x\")) manager.expressions[3]._nfa.dump() manager.add(\"a\", VerbosePushtreeHandler(\"a\")) manager.expressions[4]._nfa.dump() #manager.add(\".//*\") machine_states = manager._build_machine_states() dump_machine_states(machine_states) hand = RuleMachineHandler(machine_states)",
"O(n). However, for now, n is no more than 10 or so. class",
"print \"\", test, \"->\", to_node_id def _add_initial_loop(nfa): start_edges = nfa.start_edges[:] any_node = nfa.new_node(None,",
"Branch(None, set(), set()) self.comment_tree = Branch(None, set(), set()) def add(self, test, to_node_id): if",
"s, \"<> (empty)\" else: print s, tree.test, \"?\" self._dump(tree.if_true, depth+1, numbering) self._dump(tree.if_false, depth+1,",
"# 0 node is defined to have no attributes self.stack.append(-1) return if i",
"for to_node_id, test in transitions: state_table.add(test, to_node_id) for nfa_nodes, match_type in state_table.get_final_nodes(): some_dfa",
"= next(counter) self.edges[to_node_id] = [] self.match_types[to_node_id] = test.match_type self.labeled_handlers[to_node_id] = [] edges.append( (to_node_id,",
"node_id is None: new_transitions = nfa.start_edges else: # XXX I can't transition from",
"print self.prefix+\"attributeMatch\", node def commentMatch(self, node): print self.prefix+\"commentMatch\", node def processingInstructionMatch(self, node): print",
"if (expr.__class__ is locationpaths.absolute_location_path): # This is an absolute path like # \"/a\",",
"print \" == FAILURE ==\" print type(expr) print dir(expr) for k, v in",
"test) if new_true_test == True: self._add_to_leaves(tree.if_true, to_node_id) elif new_true_test: if isinstance(tree.if_true, set): new_branch",
"target, data): state = self.stack[-1] if state == -1: return pi_ops = self.machine_states[state][3]",
"i = todo.pop() #print \"Access\", i, len(node_ops) tree = node_ops[i] if isinstance(tree.if_true, set):",
"how to get # the attribute node handler.attributeMatch( (node, (namespace, localname) ) )",
"{} # node_id -> match_type self.labeled_handlers = {} # node_id -> (label, PushtreeHandler)",
"but no name, like \"a:*\" namespace = namespaces[node_test._prefix] node_id = nfa.new_node(None, klass((namespace, None),",
"is locationpaths.absolute_location_path): # This is an absolute path like # \"/a\", \"/a[0]/b[@x]\" nfa",
"def comment_intersect(parent_test, child_test): if parent_test is not None: assert isinstance(parent_test, CommentTest), parent_test assert",
"== localname)): i = if_true else: i = if_false if i == 0:",
"#print \"goto -1\" self.stack.append(-1) return element_ops = self.machine_states[state][1] if not element_ops: # This",
"in attrs.keys(): for (ns, ln, attr_state_id) in attr_ops: #print \"attr test:\", (ns, ln),",
"element def endSubtree(self, element): print self.prefix+\"endSubtree\", element def startElementMatch(self, node): print self.prefix+\"startElementMatch\", node",
"it #print \"GOTO -1\" self.stack.append(-1) return namespace, localname = name i = 0",
"PI? # Looks like Amara support XPath 1.0, where this is a string",
"union everything? for nfa in nfas[1:]: union_nfa.union(nfa) dfa, numbering = nfa_to_dfa(union_nfa) return build_states(union_nfa,",
"states = [] for dfa_id, node_ids in sorted( (dfa_id, node_ids) for (node_ids, dfa_id)",
"if edge[0] == event: yield edge[1] # Raymond's code def nfa_to_dfa(nfa): numbering =",
"if the namespace fields are different. # XXX check for predicates! if parent_test.name",
"state = self.stack[-1] #print \"startElementNS\", name, qname, attrs, \"state\", state if state ==",
"# This are PushtreeHandler instances. I could find the # actual instances I",
"print node_name, is_terminal, labels self._dump_edges(edges) print \"======\" def _dump_edges(self, edges): for (to_node_id, test)",
"handler class RuleMachineHandler(object): def __init__(self, machine_states): self.machine_states = machine_states def startDocument(self,node): self.stack =",
"# Also handle any attributes attr_ops = self.machine_states[next_state][2] if not attr_ops: return for",
"child_test.name: return True, False return False, child_test def pi_intersect(parent_test, child_test): if parent_test is",
"is a step along some axis, such as: # \"a\" - step along",
"ln, test_function, if_true, if_false = element_ops[i] assert test_function is None if ((ns is",
"namespaces): #print \"Eval\", expr.__class__ if (expr.__class__ is locationpaths.relative_location_path): # This is a set",
"dfa_id) in numbering.items() ): assert dfa_id == len(states) if dfa_id == 0: assert",
"node is not None: visit.append(node.if_true) visit.append(node.if_false) return result.items() def dump(self, numbering): # Do",
"= state_table numbering[current_dfa] = len(numbering) # for k, table in sorted(result.items(), key=lambda x:sorted(x[0])):",
"import locationpaths from amara.xpath.locationpaths import axisspecifiers from amara.xpath.locationpaths import nodetests from amara.xpath.functions import",
"pi_intersect) elif isinstance(test, CommentTest): self._add(self.comment_tree, test, to_node_id, comment_intersect) else: raise AssertionError(test) def _add(self,",
"localname = tree.test.name node_ops[i] = (namespace, localname, None, if_true, if_false) #print \"Added\", node_ops[i]",
"attr_intersect(parent_test, child_test): if parent_test is not None: assert isinstance(parent_test, AttributeTest), parent_test assert isinstance(child_test,",
"[] # ... because there are no states else: node_ops = [(None, None,",
"frozenset([None]) # nfa start node result = {} # [] seen = set([dfa_start])",
"isinstance(parent_test, CommentTest), parent_test assert isinstance(child_test, CommentTest), child_test return True, False # Used to",
"self.attr_tree), (ProcessingInstructionTest.match_type, self.pi_tree), (CommentTest.match_type, self.comment_tree) ): visit = [tree] while visit: node =",
"otherwise, loop #print \"GoTo\", next_state self.stack.append(next_state) handlers = self.machine_states[next_state][0] for handler in handlers:",
"node_name, is_terminal, labels self._dump_edges(edges) print \"======\" def _dump_edges(self, edges): for (to_node_id, test) in",
"name): self.name = name # [@x=\"a\"] class AttributeBinOpPred(object): def __init__(self, name, op, value):",
"me<b/></li> <ul> <li x='1'>This <i>is</i> test</li> <li x='2'><a href='spam'>that</a> was nothing</li> </ul> </body>",
"# The start node has no type self.match_types = {} # node_id ->",
"{} # node_id -> (label, PushtreeHandler) def copy(self): nfa = NFA() nfa.start_edges[:] =",
"isinstance(tree, set): if tree: k = sorted(tree) print s, \"<>\", numbering[frozenset(tree)], k else:",
"comment tree tree = table.comment_tree.if_true assert isinstance(tree, set) if tree: comment_state = numbering[frozenset(tree)]",
"if match_type not in (\"node\", \"record\"): continue new_transitions = nfa.edges[node_id] transitions.extend(new_transitions) return transitions",
"for k, table in sorted(result.items(), key=lambda x:sorted(x[0])): # print \"State\", sorted(k) # table.dump()",
"a # large number of element tag tests then sort the tags and",
"namespace, localname = tree.test.name attr_ops.append( (namespace, localname, numbering[frozenset(tree.if_true)]) ) tree = tree.if_false if",
"assert getattr(parent_test, \"predicates\", None) is None assert isinstance(child_test, BaseNodeTest), child_test assert getattr(child_test, \"predicates\",",
"nfas_to_machine_states(nfas): union_nfa = nfas[0].copy() # XXX start with empty and union everything? for",
"... dfa_start = frozenset([None]) # nfa start node result = {} # []",
"isinstance(tree.if_true, set): if tree.if_true: if_true = -numbering[frozenset(tree.if_true)] else: if_true = 0 else: if_true",
"set): if tree: k = sorted(tree) print s, \"<>\", numbering[frozenset(tree)], k else: print",
"match_type = \"attr\" def __init__(self, name, predicates): self.name = name assert not predicates",
"predicates self.predicates = predicates def __str__(self): return \"Attr name=%r\" % (self.name,) class ProcessingInstructionTest(object):",
"(dfa_id, node_ids) for (node_ids, dfa_id) in numbering.items() ): assert dfa_id == len(states) if",
"return nfas_to_machine_states([x._nfa for x in self.expressions]) def build_pushtree_handler(self): return RuleMachineHandler(self._build_machine_states()) # Special handler",
"Amara support XPath 1.0, where this is a string if parent_test.target == child_test.target:",
"can't transition from something # which wasn't a node or a record match_type",
"= if_true self.if_false = if_false class StateTable(object): def __init__(self, match_type, nfa, nfa_node_ids): self.match_type",
"[] tree = table.attr_tree.if_true while not isinstance(tree, set): namespace, localname = tree.test.name attr_ops.append(",
"result[frozenset(node)] = match_type elif node is not None: visit.append(node.if_true) visit.append(node.if_false) return result.items() def",
"return nfa if expr.__class__ is locationpaths.location_step: # This is a step along some",
"is an abbreviated_absolute_location_path # \"//a\", \"a//b\" nfa = NFA() for step in expr._steps:",
"elif node_test.__class__ is nodetests.namespace_test: # Namespace but no name, like \"a:*\" namespace =",
"is None: prefix = \"\" else: prefix = \"(%s) \" % (prefix,) self.prefix",
"parent_test is None: return child_test, False # Is there any way to match",
"= [tree] while visit: node = visit.pop() if isinstance(node, set): if node: result[frozenset(node)]",
"amara.xpath import locationpaths from amara.xpath.locationpaths import axisspecifiers from amara.xpath.locationpaths import nodetests from amara.xpath.functions",
"in nfas[1:]: union_nfa.union(nfa) dfa, numbering = nfa_to_dfa(union_nfa) return build_states(union_nfa, dfa, numbering) class PushtreeManager(object):",
"child_test, False elif isinstance(parent_test, NodeTest): if isinstance(child_test, AnyNodeTest): return True, True if isinstance(child_test,",
"match_type # 'None' for the start node self.nfa = nfa self.nfa_node_ids = nfa_node_ids",
"endElementMatch(self, node): pass def attributeMatch(self, node): pass def commentMatch(self, node): pass def processingInstructionMatch(self,",
"for x in self.labeled_handlers[node_id]]) is_terminal = \"(terminal)\" if (node_id in self.terminal_nodes) else \"\"",
"any_node, AnyNodeTest()) # loop def to_nfa(expr, namespaces): #print \"Eval\", expr.__class__ if (expr.__class__ is",
"union_nfa.union(nfa) dfa, numbering = nfa_to_dfa(union_nfa) return build_states(union_nfa, dfa, numbering) class PushtreeManager(object): def __init__(self,",
"new_true_test, new_false_test = intersect(tree.test, test) if new_true_test == True: self._add_to_leaves(tree.if_true, to_node_id) elif new_true_test:",
"other.start_edges self.edges.update(other.edges) self.match_types.update(other.match_types) for node_id in self.terminal_nodes: self.edges[node_id].extend(other.start_edges) self.terminal_nodes.clear() self.terminal_nodes.update(other.terminal_nodes) self.labeled_handlers.update(other.labeled_handlers) def union(self,",
"sorted(self.edges.items()): if node_id is None: node_name = \"(start)\" labels = \"\" else: node_name",
"performance # instead of O(n). However, for now, n is no more than",
"result[current_dfa] = StateTable(match_type, nfa, current_dfa) numbering[current_dfa] = len(numbering) continue # This adds element,",
"is None: new_transitions = nfa.start_edges else: # XXX I can't transition from something",
"else: if_true = len(node_ops) node_ops.append(tree.if_true) if isinstance(tree.if_false, set): if tree.if_false: if_false = -numbering[frozenset(tree.if_false)]",
"== \"descendant\": _add_initial_loop(subnfa) nfa.extend(subnfa) return nfa if (expr.__class__ is locationpaths.abbreviated_absolute_location_path): # This is",
"return element_ops = self.machine_states[state][1] if not element_ops: # This was a valid target,",
"\"non-empty intersection\" if not self.start_edges: self.start_edges[:] = other.start_edges self.edges.update(other.edges) self.match_types.update(other.match_types) for node_id in",
"\"a\" - step along the child axis # \"a[@x][@y='1']\" - step along the",
"comment_intersect(parent_test, child_test): if parent_test is not None: assert isinstance(parent_test, CommentTest), parent_test assert isinstance(child_test,",
"def __init__(self, target): self.target = target def __str__(self): return \"processing-instruction(%r)\" % (self.target,) class",
"0 states.append( (handlers, node_ops, attr_ops, pi_ops, comment_state) ) return tuple(states) class Expression(object): def",
"handler) in sorted(handler_map.items()): handlers.append(handler) # node tree tree = table.node_tree.if_true if isinstance(tree, set):",
"self._add(tree.if_false, new_false_test, to_node_id, intersect) def _add_to_leaves(self, tree, to_node_id): if isinstance(tree, set): tree.add(to_node_id) else:",
"endElement use different method. handlers = [] for (label, handler) in sorted(handler_map.items()): handlers.append(handler)",
"class NFA(object): def __init__(self): self.start_edges = [] self.edges = {} # from_node_id ->",
"= self.start_edges nfa.edges.update(self.edges) nfa.terminal_nodes.update(self.terminal_nodes) nfa.match_types.update(self.match_types) nfa.labeled_handlers.update(self.labeled_handlers) return nfa def get_edges(self, node_id): if node_id",
"\"a:*\" namespace = namespaces[node_test._prefix] node_id = nfa.new_node(None, klass((namespace, None), expr.predicates)) elif node_test.__class__ is",
"def attributeMatch(self, node): print self.prefix+\"attributeMatch\", node def commentMatch(self, node): print self.prefix+\"commentMatch\", node def",
"namespace, like \"a\" node_id = nfa.new_node(None, klass(node_test.name_key, expr.predicates)) elif node_test.__class__ is nodetests.namespace_test: #",
"in node_ops: print node_op print \" ATTR OPS\" for attr_op in attr_ops: print",
"are no decisions to make if not tree: node_ops = [] # ...",
"[] edges.append( (to_node_id, test) ) return to_node_id def connect(self, from_node_id, to_node_id, test): self.get_edges(from_node_id).append(",
"= nfa.new_node(None, klass((namespace, None), expr.predicates)) elif node_test.__class__ is nodetests.qualified_name_test: prefix, localname = node_test.name_key",
"seen = set([dfa_start]) todo = [(dfa_start, None)] while todo: current_dfa, match_type = todo.pop()",
"any_node = nfa.new_node(None, AnyNodeTest()) for (to_node_id, test) in start_edges: nfa.connect(any_node, to_node_id, test) nfa.connect(any_node,",
"OPS\" for pi_op in pi_ops: print pi_op print \" COMMENT STATE =\", comment_state",
"tree = table.pi_tree.if_true while not isinstance(tree, set): target = tree.test.target pi_ops.append( (target, numbering[frozenset(tree.if_true)])",
"isinstance(parent_test, NodeTest): if isinstance(child_test, AnyNodeTest): return True, True if isinstance(child_test, NodeTest): # XXX",
"This is a step along some axis, such as: # \"a\" - step",
"in attr_ops: print attr_op print \" PI OPS\" for pi_op in pi_ops: print",
"False if isinstance(parent_test, AnyNodeTest): if isinstance(child_test, AnyNodeTest): return True, False if isinstance(child_test, NodeTest):",
"child_test): if parent_test is not None: assert isinstance(parent_test, AttributeTest), parent_test assert isinstance(child_test, AttributeTest),",
"self._add_to_leaves(tree.if_false, to_node_id) elif new_false_test: if isinstance(tree.if_false, set): new_branch = Branch(new_false_test, tree.if_false | set([to_node_id]),",
"self.match_types.update(other.match_types) for node_id in self.terminal_nodes: self.edges[node_id].extend(other.start_edges) self.terminal_nodes.clear() self.terminal_nodes.update(other.terminal_nodes) self.labeled_handlers.update(other.labeled_handlers) def union(self, other): assert",
"nfa_node_ids self.node_tree = Branch(None, set(), set()) self.attr_tree = Branch(None, set(), set()) self.pi_tree =",
"not isinstance(tree, set): namespace, localname = tree.test.name attr_ops.append( (namespace, localname, numbering[frozenset(tree.if_true)]) ) tree",
"<li x='2'><a href='spam'>that</a> was nothing</li> </ul> </body> \"\"\" manager = PushtreeManager(\"body/ul/li\", VerbosePushtreeHandler(\"main\")) manager.expressions[0]._nfa.dump()",
"def __init__(self, machine_states): self.machine_states = machine_states def startDocument(self,node): self.stack = [0] #dump_machine_states(self.machine_states) def",
"(to_node_id, test) in start_edges: nfa.connect(any_node, to_node_id, test) nfa.connect(any_node, any_node, AnyNodeTest()) # loop def",
"self.edges.update(other.edges) self.match_types.update(other.match_types) for node_id in self.terminal_nodes: self.edges[node_id].extend(other.start_edges) self.terminal_nodes.clear() self.terminal_nodes.update(other.terminal_nodes) self.labeled_handlers.update(other.labeled_handlers) def union(self, other):",
"machine_states): self.machine_states = machine_states def startDocument(self,node): self.stack = [0] #dump_machine_states(self.machine_states) def startElementNS(self, node,",
"= NodeTest nfa = NFA() node_test = expr.node_test if node_test.__class__ is nodetests.local_name_test: #",
"i < 0: next_state = -i break # otherwise, loop #print \"GoTo\", next_state",
"set(other.edges), \"non-empty intersection\" self.start_edges.extend(other.start_edges) self.edges.update(other.edges) self.match_types.update(other.match_types) self.terminal_nodes.update(other.terminal_nodes) self.labeled_handlers.update(other.labeled_handlers) def dump(self): for node_id, edges",
"than 10 or so. class Branch(object): def __init__(self, test, if_true, if_false): self.test =",
"nfa = NFA() node_test = expr.node_test if node_test.__class__ is nodetests.local_name_test: # Something without",
"assert isinstance(child_test, BaseNodeTest), child_test assert getattr(child_test, \"predicates\", None) is None if parent_test is",
"node_intersect(parent_test, child_test): if parent_test is not None: assert isinstance(parent_test, BaseNodeTest), parent_test assert getattr(parent_test,",
"parent_test.name == child_test.name: return True, False return False, child_test def pi_intersect(parent_test, child_test): if",
"child_test def pi_intersect(parent_test, child_test): if parent_test is not None: assert isinstance(parent_test, ProcessingInstructionTest), parent_test",
"sorted(k) # table.dump() return result, numbering def die(expr): import inspect print \" ==",
"nfa.start_edges else: # XXX I can't transition from something # which wasn't a",
"for handler in handlers: handler.startElementMatch(node) # Also handle any attributes attr_ops = self.machine_states[next_state][2]",
"even # if the namespace fields are different. # XXX check for predicates!",
"= PushtreeManager(\"body/ul/li\", VerbosePushtreeHandler(\"main\")) manager.expressions[0]._nfa.dump() manager.add(\"pre/post\", VerbosePushtreeHandler(\"pre/post\")) manager.expressions[1]._nfa.dump() manager.add(\"//a\", VerbosePushtreeHandler(\"//a\")) manager.expressions[2]._nfa.dump() manager.add(\"@x\", VerbosePushtreeHandler(\"@x\")) manager.expressions[3]._nfa.dump()",
"union(self, other): assert not set(self.edges) & set(other.edges), \"non-empty intersection\" self.start_edges.extend(other.start_edges) self.edges.update(other.edges) self.match_types.update(other.match_types) self.terminal_nodes.update(other.terminal_nodes)",
"in reversed(handlers): handler.endElementMatch(node) def processingInstruction(self, node, target, data): state = self.stack[-1] if state",
"def union(self, other): assert not set(self.edges) & set(other.edges), \"non-empty intersection\" self.start_edges.extend(other.start_edges) self.edges.update(other.edges) self.match_types.update(other.match_types)",
"assert node_ids == set([None]) # handlers (which are in (id, class) pairs) table",
"state == -1: return pi_ops = self.machine_states[state][3] for (pi_target, pi_state) in pi_ops: if",
"assert isinstance(child_test, AttributeTest), child_test if parent_test is None: return child_test, False if parent_test.name",
"if_true else: i = if_false if i == 0: # dead-end; no longer",
"import inspect print \" == FAILURE ==\" print type(expr) print dir(expr) for k,",
"namespaces)) return nfa die(expr) def node_intersect(parent_test, child_test): if parent_test is not None: assert",
"step along the child axis # \"a[@x][@y='1']\" - step along the child axis,",
"Special handler object to bridge with pushbind support in the builder # Implemented",
"= self.machine_states[next_state][0] for handler in handlers: handler.startElementMatch(node) # Also handle any attributes attr_ops",
"= value class AttributeFunctionCallPred(object): def __init__(self, func): self.func = func ##### # This",
"assert isinstance(child_test, CommentTest), child_test return True, False # Used to make a decision",
"if labels: print \"Report\", self.nfa.match_types[nfa_node], labels for (name, tree) in ( (\"NODE\", self.node_tree),",
"numbering = {} # from frozenset -> 0, 1, 2, ... dfa_start =",
"dfa, numbering) class PushtreeManager(object): def __init__(self, subtree_xpath, subtree_handler = None, namespaces = None):",
"\"GOTO -1\" self.stack.append(-1) return namespace, localname = name i = 0 while 1:",
"for step in expr._steps: axis = step.axis axis_name = axis.name assert axis_name in",
"table in sorted(result.items(), key=lambda x:sorted(x[0])): # print \"State\", sorted(k) # table.dump() return result,",
"self.attr_tree), (\"PROCESSING-INSTRUCTION\", self.pi_tree), (\"COMMENT\", self.comment_tree) ): if tree is None: print \" No\",",
"Looks like Amara support XPath 1.0, where this is a string if parent_test.target",
"not None: assert isinstance(parent_test, CommentTest), parent_test assert isinstance(child_test, CommentTest), child_test return True, False",
"_add_initial_loop(subnfa) nfa.extend(subnfa) return nfa if (expr.__class__ is locationpaths.abbreviated_absolute_location_path): # This is an abbreviated_absolute_location_path",
"dfa_id == 0: handlers = () else: handler_map = {} for node_id in",
"This is not a proper SAX handler class RuleMachineHandler(object): def __init__(self, machine_states): self.machine_states",
"is not None: visit.append(node.if_true) visit.append(node.if_false) return result.items() def dump(self, numbering): # Do I",
"(None, None, numbering[frozenset(tree)]) ) attr_ops = tuple(attr_ops) # processing instruction tree pi_ops =",
"tuple(pi_ops) # comment tree tree = table.comment_tree.if_true assert isinstance(tree, set) if tree: comment_state",
"\"\", test, \"->\", to_node_id def _add_initial_loop(nfa): start_edges = nfa.start_edges[:] any_node = nfa.new_node(None, AnyNodeTest())",
"elif isinstance(test, CommentTest): self._add(self.comment_tree, test, to_node_id, comment_intersect) else: raise AssertionError(test) def _add(self, tree,",
"pi_ops = tuple(pi_ops) # comment tree tree = table.comment_tree.if_true assert isinstance(tree, set) if",
"always a target. # This also stores any handler events result[current_dfa] = StateTable(match_type,",
"with empty and union everything? for nfa in nfas[1:]: union_nfa.union(nfa) dfa, numbering =",
"visit.append(node.if_true) visit.append(node.if_false) return result.items() def dump(self, numbering): # Do I report anything for",
"only support downward axes # and these have no downward axes. (XXX I",
"return True, False return False, child_test def pi_intersect(parent_test, child_test): if parent_test is not",
"startDocument(self,node): self.stack = [0] #dump_machine_states(self.machine_states) def startElementNS(self, node, name, qname, attrs): state =",
"def __init__(self, id, xpath, nfa): self.id = id self.xpath = xpath self._nfa =",
"if_false = -numbering[frozenset(tree.if_false)] else: if_false = 0 else: if_false = len(node_ops) node_ops.append(tree.if_false) namespace,",
"= namespaces self.expressions = [] self._add(subtree_xpath, subtree_handler) def _add(self, xpath, xpath_handler): nfa =",
"of element tag tests then sort the tags and start # in the",
"expr.node_test if node_test.__class__ is nodetests.local_name_test: # Something without a namespace, like \"a\" node_id",
"# Special handler object to bridge with pushbind support in the builder #",
"is an absolute path like # \"/a\", \"/a[0]/b[@x]\" nfa = NFA() for step",
"if_false = element_ops[i] assert test_function is None if ((ns is None or ns",
"if prefix is None: prefix = \"\" else: prefix = \"(%s) \" %",
"node def endElementMatch(self, node): print self.prefix+\"endElementMatch\", node def attributeMatch(self, node): print self.prefix+\"attributeMatch\", node",
"I could find the # actual instances I need except the startElement and",
"axis_name == \"descendant\": _add_initial_loop(subnfa) nfa.extend(subnfa) return nfa if (expr.__class__ is locationpaths.abbreviated_absolute_location_path): # This",
"name assert not predicates self.predicates = predicates def __str__(self): return \"Attr name=%r\" %",
"seen.add(some_dfa) todo.append( (some_dfa, match_type) ) result[current_dfa] = state_table numbering[current_dfa] = len(numbering) # for",
"[None]: for nfa_node in self.nfa_node_ids: labels = [x[0] for x in self.nfa.labeled_handlers[nfa_node]] if",
"name, predicates): # (ns, name) self.name = name self.predicates = predicates def __str__(self):",
"self._add_to_leaves(tree.if_true, to_node_id) self._add_to_leaves(tree.if_false, to_node_id) def get_final_nodes(self): result = {} for match_type, tree in",
"# \"a[@x][@y='1']\" - step along the child axis, with two predicates # \"@a\"",
"class AttributeBinOpPred(object): def __init__(self, name, op, value): self.name = name self.op = op",
"def __str__(self): return \"Node ns=%r localname=%r predicates=%r\" % (self.name[0], self.name[1], self.predicates) # predicates",
"node_id): if node_id is None: return self.start_edges return self.edges[node_id] def add_handler(self, labeled_handler): for",
"attribute axis axis = expr.axis axis_name = axis.name assert axis_name in (\"child\", \"descendant\",",
"new_transitions = nfa.start_edges else: # XXX I can't transition from something # which",
"x in self.labeled_handlers[node_id]]) is_terminal = \"(terminal)\" if (node_id in self.terminal_nodes) else \"\" print",
"transitions state_table = StateTable(match_type, nfa, current_dfa) for to_node_id, test in transitions: state_table.add(test, to_node_id)",
"element def startElementMatch(self, node): print self.prefix+\"startElementMatch\", node def endElementMatch(self, node): print self.prefix+\"endElementMatch\", node",
"xpath_handler) def _build_machine_states(self): return nfas_to_machine_states([x._nfa for x in self.expressions]) def build_pushtree_handler(self): return RuleMachineHandler(self._build_machine_states())",
"self.prefix+\"attributeMatch\", node def commentMatch(self, node): print self.prefix+\"commentMatch\", node def processingInstructionMatch(self, node): print self.prefix+\"processingInstructionMatch\",",
"# This adds element, attribute, comment, etc. transitions state_table = StateTable(match_type, nfa, current_dfa)",
"= [] tree = table.pi_tree.if_true while not isinstance(tree, set): target = tree.test.target pi_ops.append(",
"sort the tags and start # in the middle. Should give O(log(number of",
"node, name, qname, attrs): state = self.stack[-1] #print \"startElementNS\", name, qname, attrs, \"state\",",
"attr_ops.append( (namespace, localname, numbering[frozenset(tree.if_true)]) ) tree = tree.if_false if tree: # Match any",
"= predicates def __str__(self): return \"Node ns=%r localname=%r predicates=%r\" % (self.name[0], self.name[1], self.predicates)",
"\"a[@x][@y='1']\" - step along the child axis, with two predicates # \"@a\" -",
"NodeTest): return child_test, False if isinstance(parent_test, AnyNodeTest): if isinstance(child_test, AnyNodeTest): return True, False",
"def _add_initial_loop(nfa): start_edges = nfa.start_edges[:] any_node = nfa.new_node(None, AnyNodeTest()) for (to_node_id, test) in",
"self.test = test self.if_true = if_true self.if_false = if_false class StateTable(object): def __init__(self,",
"handler.attributeMatch( (node, (namespace, localname) ) ) def endElementNS(self, node, name, qname): #print \"endElementNS\",",
"for x in self.nfa.labeled_handlers[nfa_node]] if labels: print \"Report\", self.nfa.match_types[nfa_node], labels for (name, tree)",
"Expression(i, xpath, nfa) self.expressions.append(exp) return exp def add(self, xpath, xpath_handler=None): return self._add(xpath, xpath_handler)",
"INFO FOR\", i, \"==\" handlers, node_ops, attr_ops, pi_ops, comment_state = x print \"",
"str([x[0] for x in self.labeled_handlers[node_id]]) is_terminal = \"(terminal)\" if (node_id in self.terminal_nodes) else",
"if isinstance(child_test, AnyNodeTest): return True, False if isinstance(child_test, NodeTest): return child_test, False if",
"was a valid target, but there's nothing leading off from it #print \"GOTO",
"else: if_false = 0 else: if_false = len(node_ops) node_ops.append(tree.if_false) namespace, localname = tree.test.name",
") attr_ops = tuple(attr_ops) # processing instruction tree pi_ops = [] tree =",
"_add(self, tree, test, to_node_id, intersect): new_true_test, new_false_test = intersect(tree.test, test) if new_true_test ==",
"xpath_handler=None): return self._add(xpath, xpath_handler) def _build_machine_states(self): return nfas_to_machine_states([x._nfa for x in self.expressions]) def",
"handler in handlers: #print \"Notify attribute match:\", event_ids, (namespace, localname) # This is",
"not self.start_edges: self.start_edges[:] = other.start_edges self.edges.update(other.edges) self.match_types.update(other.match_types) for node_id in self.terminal_nodes: self.edges[node_id].extend(other.start_edges) self.terminal_nodes.clear()",
"assert isinstance(parent_test, CommentTest), parent_test assert isinstance(child_test, CommentTest), child_test return True, False # Used",
"nfa.start_edges[:] any_node = nfa.new_node(None, AnyNodeTest()) for (to_node_id, test) in start_edges: nfa.connect(any_node, to_node_id, test)",
"handler in reversed(handlers): handler.endElementMatch(node) def processingInstruction(self, node, target, data): state = self.stack[-1] if",
"self.name = name # [@x=\"a\"] class AttributeBinOpPred(object): def __init__(self, name, op, value): self.name",
"in self.terminal_nodes: self.edges[node_id].extend(other.start_edges) self.terminal_nodes.clear() self.terminal_nodes.update(other.terminal_nodes) self.labeled_handlers.update(other.labeled_handlers) def union(self, other): assert not set(self.edges) &",
"nfa def nfas_to_machine_states(nfas): union_nfa = nfas[0].copy() # XXX start with empty and union",
"\"Node ns=%r localname=%r predicates=%r\" % (self.name[0], self.name[1], self.predicates) # predicates make no sense",
"todo.append(if_true) node_ops = tuple(node_ops) # attr tree attr_ops = [] tree = table.attr_tree.if_true",
"if tree: pi_ops.append( (None, numbering[frozenset(tree)]) ) pi_ops = tuple(pi_ops) # comment tree tree",
"#print \"Added\", node_ops[i] if if_false > 0: todo.append(if_false) if if_true > 0: todo.append(if_true)",
"= len(numbering) continue # This adds element, attribute, comment, etc. transitions state_table =",
"CommentTest(object): match_type = \"comment\" class NFA(object): def __init__(self): self.start_edges = [] self.edges =",
"edges: print \"\", test, \"->\", to_node_id def _add_initial_loop(nfa): start_edges = nfa.start_edges[:] any_node =",
"in sorted(result.items(), key=lambda x:sorted(x[0])): # print \"State\", sorted(k) # table.dump() return result, numbering",
"nothing</li> </ul> </body> \"\"\" manager = PushtreeManager(\"body/ul/li\", VerbosePushtreeHandler(\"main\")) manager.expressions[0]._nfa.dump() manager.add(\"pre/post\", VerbosePushtreeHandler(\"pre/post\")) manager.expressions[1]._nfa.dump() manager.add(\"//a\",",
"[] for (label, handler) in sorted(handler_map.items()): handlers.append(handler) # node tree tree = table.node_tree.if_true",
"if parent_test is None: return child_test, False # Is there any way to",
"transitions def transition(nfa_state, event): for (to_node_id, test) in edge in nfa_state.edges: if edge[0]",
"= if_false class StateTable(object): def __init__(self, match_type, nfa, nfa_node_ids): self.match_type = match_type #",
"expr.predicates)) elif node_test.__class__ is nodetests.namespace_test: # Namespace but no name, like \"a:*\" namespace",
"if_true, if_false): self.test = test self.if_true = if_true self.if_false = if_false class StateTable(object):",
"\"-\"*depth if isinstance(tree, set): if tree: k = sorted(tree) print s, \"<>\", numbering[frozenset(tree)],",
"tree.add(to_node_id) else: self._add_to_leaves(tree.if_true, to_node_id) self._add_to_leaves(tree.if_false, to_node_id) def get_final_nodes(self): result = {} for match_type,",
"to_node_id, test in transitions: state_table.add(test, to_node_id) for nfa_nodes, match_type in state_table.get_final_nodes(): some_dfa =",
"'None' for the start node self.nfa = nfa self.nfa_node_ids = nfa_node_ids self.node_tree =",
"node): print self.prefix+\"processingInstructionMatch\", node if __name__ == '__main__': testxml = \"\"\"\\ <body> <li>Ignore",
"result.items() def dump(self, numbering): # Do I report anything for having reached here?",
"expr.__class__ is amara.xpath.expressions.nodesets.union_expr: # \"a|b\" nfa = to_nfa(expr._paths[0], namespaces) for path in expr._paths[1:]:",
"node_ops, attr_ops, pi_ops, comment_state = x print \" HANDLERS\", handlers print \" NODE",
"- step along the child axis # \"a[@x][@y='1']\" - step along the child",
"node_ops[i] if if_false > 0: todo.append(if_false) if if_true > 0: todo.append(if_true) node_ops =",
"# table.dump() return result, numbering def die(expr): import inspect print \" == FAILURE",
"NFA() nfa.start_edges[:] = self.start_edges nfa.edges.update(self.edges) nfa.terminal_nodes.update(self.terminal_nodes) nfa.match_types.update(self.match_types) nfa.labeled_handlers.update(self.labeled_handlers) return nfa def get_edges(self, node_id):",
"*any* PI? # Looks like Amara support XPath 1.0, where this is a",
"handler_map = {} for node_id in node_ids: for (label, handler) in nfa.labeled_handlers[node_id]: handler_map[label]",
"This is a set of path specifiers like # \"a\" \"a/b\", \"a/b/c[0]/d[@x]\" (relative",
"print \"Report\", self.nfa.match_types[nfa_node], labels for (name, tree) in ( (\"NODE\", self.node_tree), (\"ATTR\", self.attr_tree),",
"if ((ns is None or ns == namespace) and (ln is None or",
"0: todo.append(if_false) if if_true > 0: todo.append(if_true) node_ops = tuple(node_ops) # attr tree",
"add(self, test, to_node_id): if isinstance(test, BaseNodeTest): self._add(self.node_tree, test, to_node_id, node_intersect) elif isinstance(test, AttributeTest):",
"visit.append(node.if_false) return result.items() def dump(self, numbering): # Do I report anything for having",
"# from_node_id -> [(to_node_id, test), ...] self.terminal_nodes = set() # The start node",
"prefix = \"(%s) \" % (prefix,) self.prefix = prefix def startSubtree(self, element): print",
"node_test.__class__ is nodetests.qualified_name_test: prefix, localname = node_test.name_key namespace = namespaces[prefix] node_id = nfa.new_node(None,",
"elif isinstance(test, ProcessingInstructionTest): self._add(self.pi_tree, test, to_node_id, pi_intersect) elif isinstance(test, CommentTest): self._add(self.comment_tree, test, to_node_id,",
"match_type = nfa.match_types[node_id] if match_type not in (\"node\", \"record\"): continue new_transitions = nfa.edges[node_id]",
"localname, None, if_true, if_false) #print \"Added\", node_ops[i] if if_false > 0: todo.append(if_false) if",
"False return False, child_test def comment_intersect(parent_test, child_test): if parent_test is not None: assert",
"add(self, xpath, xpath_handler=None): return self._add(xpath, xpath_handler) def _build_machine_states(self): return nfas_to_machine_states([x._nfa for x in",
"manager.expressions[1]._nfa.dump() manager.add(\"//a\", VerbosePushtreeHandler(\"//a\")) manager.expressions[2]._nfa.dump() manager.add(\"@x\", VerbosePushtreeHandler(\"@x\")) manager.expressions[3]._nfa.dump() manager.add(\"a\", VerbosePushtreeHandler(\"a\")) manager.expressions[4]._nfa.dump() #manager.add(\".//*\") machine_states =",
"build_states(nfa, dfa, numbering): # unique node numbers states = [] for dfa_id, node_ids",
"1.0, where this is a string if parent_test.target == child_test.target: return True, False",
"__init__(self, test, if_true, if_false): self.test = test self.if_true = if_true self.if_false = if_false",
"tuple(node_ops) # attr tree attr_ops = [] tree = table.attr_tree.if_true while not isinstance(tree,",
"self.comment_tree) ): visit = [tree] while visit: node = visit.pop() if isinstance(node, set):",
"child axis # \"a[@x][@y='1']\" - step along the child axis, with two predicates",
"= match_type # 'None' for the start node self.nfa = nfa self.nfa_node_ids =",
"def add_handler(self, labeled_handler): for node_id in self.terminal_nodes: self.labeled_handlers[node_id].append(labeled_handler) def new_node(self, from_node_id, test): edges",
"def endSubtree(self, element): pass def startElementMatch(self, node): pass def endElementMatch(self, node): pass def",
"# Is there any way to match *any* PI? # Looks like Amara",
"if expr.__class__ is amara.xpath.expressions.nodesets.union_expr: # \"a|b\" nfa = to_nfa(expr._paths[0], namespaces) for path in",
"return self._add(xpath, xpath_handler) def _build_machine_states(self): return nfas_to_machine_states([x._nfa for x in self.expressions]) def build_pushtree_handler(self):",
"self.id = id self.xpath = xpath self._nfa = nfa def nfas_to_machine_states(nfas): union_nfa =",
"there's nothing leading off from it #print \"GOTO -1\" self.stack.append(-1) return namespace, localname",
"= table.pi_tree.if_true while not isinstance(tree, set): target = tree.test.target pi_ops.append( (target, numbering[frozenset(tree.if_true)]) )",
"BaseNodeTest), child_test assert getattr(child_test, \"predicates\", None) is None if parent_test is None: if",
"if_true = -numbering[frozenset(tree.if_true)] else: if_true = 0 else: if_true = len(node_ops) node_ops.append(tree.if_true) if",
"transitions: state_table.add(test, to_node_id) for nfa_nodes, match_type in state_table.get_final_nodes(): some_dfa = frozenset(nfa_nodes) if some_dfa",
"if parent_test is not None: assert isinstance(parent_test, BaseNodeTest), parent_test assert getattr(parent_test, \"predicates\", None)",
"0, 1, 2, ... dfa_start = frozenset([None]) # nfa start node result =",
"set()) self.attr_tree = Branch(None, set(), set()) self.pi_tree = Branch(None, set(), set()) self.comment_tree =",
"instead of O(n). However, for now, n is no more than 10 or",
"are a # large number of element tag tests then sort the tags",
"set): target = tree.test.target pi_ops.append( (target, numbering[frozenset(tree.if_true)]) ) tree = tree.if_false if tree:",
"(namespace, localname) if ((ns is None or namespace == ns) and (ln is",
"endElementNS(self, node, name, qname): #print \"endElementNS\", node, name, qname last_state = self.stack.pop() if",
"\"goto -1\" self.stack.append(-1) return element_ops = self.machine_states[state][1] if not element_ops: # This was",
"self.machine_states[attr_state_id][0] for handler in handlers: #print \"Notify attribute match:\", event_ids, (namespace, localname) #",
"pi_ops: if pi_target == target: handlers = self.machine_states[pi_state][0] for handler in handlers: handler.processingInstruction(node)",
"def startSubtree(self, element): pass def endSubtree(self, element): pass def startElementMatch(self, node): pass def",
"self._nfa = nfa def nfas_to_machine_states(nfas): union_nfa = nfas[0].copy() # XXX start with empty",
"node_test.name_key namespace = namespaces[prefix] node_id = nfa.new_node(None, klass((namespace, localname), expr.predicates)) elif node_test.__class__ is",
"None: new_transitions = nfa.start_edges else: # XXX I can't transition from something #",
"self.labeled_handlers.update(other.labeled_handlers) def dump(self): for node_id, edges in [(None, self.start_edges)] + sorted(self.edges.items()): if node_id",
"set(), set()) self.comment_tree = Branch(None, set(), set()) def add(self, test, to_node_id): if isinstance(test,",
"\"(%s) \" % (prefix,) self.prefix = prefix def startSubtree(self, element): print self.prefix+\"startSubtree\", element",
"is locationpaths.relative_location_path): # This is a set of path specifiers like # \"a\"",
"= self.machine_states[attr_state_id][0] for handler in handlers: #print \"Notify attribute match:\", event_ids, (namespace, localname)",
"manager.add(\"@x\", VerbosePushtreeHandler(\"@x\")) manager.expressions[3]._nfa.dump() manager.add(\"a\", VerbosePushtreeHandler(\"a\")) manager.expressions[4]._nfa.dump() #manager.add(\".//*\") machine_states = manager._build_machine_states() dump_machine_states(machine_states) hand =",
"namespaces) if axis_name == \"descendant\": _add_initial_loop(subnfa) nfa.extend(subnfa) return nfa if (expr.__class__ is locationpaths.abbreviated_absolute_location_path):",
"namespaces)) _add_initial_loop(nfa) return nfa if (expr.__class__ is locationpaths.absolute_location_path): # This is an absolute",
"return \"Node ns=%r localname=%r predicates=%r\" % (self.name[0], self.name[1], self.predicates) # predicates make no",
"tree = table.node_tree.if_true if isinstance(tree, set): # Special case when there are no",
"here because we only support downward axes # and these have no downward",
"# attr tree attr_ops = [] tree = table.attr_tree.if_true while not isinstance(tree, set):",
"= [] # ... because there are no states else: node_ops = [(None,",
"\"AnyNode (*)\" class NodeTest(BaseNodeTest): def __init__(self, name, predicates): # (ns, name) self.name =",
"? class AnyNodeTest(BaseNodeTest): def __str__(self): return \"AnyNode (*)\" class NodeTest(BaseNodeTest): def __init__(self, name,",
"self.prefix+\"processingInstructionMatch\", node if __name__ == '__main__': testxml = \"\"\"\\ <body> <li>Ignore me<b/></li> <ul>",
"(pi_target, pi_state) in pi_ops: if pi_target == target: handlers = self.machine_states[pi_state][0] for handler",
"<li>Ignore me<b/></li> <ul> <li x='1'>This <i>is</i> test</li> <li x='2'><a href='spam'>that</a> was nothing</li> </ul>",
"# handlers (which are in (id, class) pairs) table = dfa[node_ids] if dfa_id",
"the test passes or it fails. # TODO: something more sophisticated? For example,",
"None, numbering[frozenset(tree)]) ) attr_ops = tuple(attr_ops) # processing instruction tree pi_ops = []",
"state if state == -1: #print \"goto -1\" self.stack.append(-1) return element_ops = self.machine_states[state][1]",
"die(node_test) nfa.terminal_nodes.add(node_id) #if axis_name == \"descendant\": # _add_initial_loop(nfa) #print \"QWERQWER\" #nfa.dump() return nfa",
"# _add_initial_loop(nfa) #print \"QWERQWER\" #nfa.dump() return nfa if expr.__class__ is amara.xpath.expressions.nodesets.union_expr: # \"a|b\"",
"= name self.op = op self.value = value class AttributeFunctionCallPred(object): def __init__(self, func):",
"None assert isinstance(child_test, BaseNodeTest), child_test assert getattr(child_test, \"predicates\", None) is None if parent_test",
"child_test): if parent_test is not None: assert isinstance(parent_test, ProcessingInstructionTest), parent_test assert isinstance(child_test, ProcessingInstructionTest),",
"k, table in sorted(result.items(), key=lambda x:sorted(x[0])): # print \"State\", sorted(k) # table.dump() return",
"def __str__(self): return \"Attr name=%r\" % (self.name,) class ProcessingInstructionTest(object): match_type = \"processing-instruction\" def",
"self.get_edges(from_node_id).append( (to_node_id, test) ) def extend(self, other): assert not set(self.edges) & set(other.edges), \"non-empty",
"nfa.labeled_handlers[node_id]: handler_map[label] = handler # This are PushtreeHandler instances. I could find the",
"__init__(self, id, xpath, nfa): self.id = id self.xpath = xpath self._nfa = nfa",
"= new_branch else: self._add(tree.if_false, new_false_test, to_node_id, intersect) def _add_to_leaves(self, tree, to_node_id): if isinstance(tree,",
"= expr.node_test if node_test.__class__ is nodetests.local_name_test: # Something without a namespace, like \"a\"",
"== len(states) if dfa_id == 0: assert node_ids == set([None]) # handlers (which",
"part of the DFA and the # 0 node is defined to have",
"# XXX check for predicates! if parent_test.name == child_test.name: return True, False return",
"attr_ops = self.machine_states[next_state][2] if not attr_ops: return for namespace, localname in attrs.keys(): for",
"isinstance(tree.if_false, set): if tree.if_false: if_false = -numbering[frozenset(tree.if_false)] else: if_false = 0 else: if_false",
"new_node(self, from_node_id, test): edges = self.get_edges(from_node_id) to_node_id = next(counter) self.edges[to_node_id] = [] self.match_types[to_node_id]",
"node_ops[i] if isinstance(tree.if_true, set): if tree.if_true: if_true = -numbering[frozenset(tree.if_true)] else: if_true = 0",
"test, to_node_id, attr_intersect) elif isinstance(test, ProcessingInstructionTest): self._add(self.pi_tree, test, to_node_id, pi_intersect) elif isinstance(test, CommentTest):",
"nodetests.qualified_name_test: prefix, localname = node_test.name_key namespace = namespaces[prefix] node_id = nfa.new_node(None, klass((namespace, localname),",
"isinstance(test, BaseNodeTest): self._add(self.node_tree, test, to_node_id, node_intersect) elif isinstance(test, AttributeTest): self._add(self.attr_tree, test, to_node_id, attr_intersect)",
"[@x] class AttributeExistsPred(object): def __init__(self, name): self.name = name # [@x=\"a\"] class AttributeBinOpPred(object):",
"Implemented by beazley. Note: This is not a proper SAX handler class RuleMachineHandler(object):",
"OPS\" for attr_op in attr_ops: print attr_op print \" PI OPS\" for pi_op",
"event: yield edge[1] # Raymond's code def nfa_to_dfa(nfa): numbering = {} # from",
"string if parent_test.target == child_test.target: return True, False return False, child_test def comment_intersect(parent_test,",
"node tree tree = table.node_tree.if_true if isinstance(tree, set): # Special case when there",
"from frozenset -> 0, 1, 2, ... dfa_start = frozenset([None]) # nfa start",
"but there's nothing leading off from it #print \"GOTO -1\" self.stack.append(-1) return namespace,",
"): visit = [tree] while visit: node = visit.pop() if isinstance(node, set): if",
"if not attr_ops: return for namespace, localname in attrs.keys(): for (ns, ln, attr_state_id)",
"if there are a # large number of element tag tests then sort",
"NodeTest): if isinstance(child_test, AnyNodeTest): return True, True if isinstance(child_test, NodeTest): # XXX This",
"STATE =\", comment_state class PushtreeHandler(object): def startSubtree(self, element): pass def endSubtree(self, element): pass",
"len(numbering) continue # This adds element, attribute, comment, etc. transitions state_table = StateTable(match_type,",
"s, \"<>\", numbering[frozenset(tree)], k else: print s, \"<> (empty)\" else: print s, tree.test,",
"# This is a step along some axis, such as: # \"a\" -",
"attributes self.stack.append(-1) return if i < 0: next_state = -i break # otherwise,",
"if_false if i == 0: # dead-end; no longer part of the DFA",
"__init__(self, subtree_xpath, subtree_handler = None, namespaces = None): if namespaces is None: namespaces",
"predicates): self.name = name assert not predicates self.predicates = predicates def __str__(self): return",
"parent_test is None: return child_test, False if parent_test.name == child_test.name: return True, False",
"figure out how to get # the attribute node handler.attributeMatch( (node, (namespace, localname)",
"node_ops.append(tree.if_true) if isinstance(tree.if_false, set): if tree.if_false: if_false = -numbering[frozenset(tree.if_false)] else: if_false = 0",
"return True, False return False, child_test def attr_intersect(parent_test, child_test): if parent_test is not",
"node_ops = tuple(node_ops) # attr tree attr_ops = [] tree = table.attr_tree.if_true while",
"def startDocument(self,node): self.stack = [0] #dump_machine_states(self.machine_states) def startElementNS(self, node, name, qname, attrs): state",
"wrong. Resolved namespaces can be the same even # if the namespace fields",
"return \"processing-instruction(%r)\" % (self.target,) class CommentTest(object): match_type = \"comment\" class NFA(object): def __init__(self):",
"prefix def startSubtree(self, element): print self.prefix+\"startSubtree\", element def endSubtree(self, element): print self.prefix+\"endSubtree\", element",
"manager.add(\"//a\", VerbosePushtreeHandler(\"//a\")) manager.expressions[2]._nfa.dump() manager.add(\"@x\", VerbosePushtreeHandler(\"@x\")) manager.expressions[3]._nfa.dump() manager.add(\"a\", VerbosePushtreeHandler(\"a\")) manager.expressions[4]._nfa.dump() #manager.add(\".//*\") machine_states = manager._build_machine_states()",
"= {} # [] seen = set([dfa_start]) todo = [(dfa_start, None)] while todo:",
"= to_nfa(step, namespaces) if axis_name == \"descendant\": _add_initial_loop(subnfa) nfa.extend(subnfa) return nfa if (expr.__class__",
"# print \"State\", sorted(k) # table.dump() return result, numbering def die(expr): import inspect",
"amara.xpath.expressions import basics counter = itertools.count(1) # [@x] class AttributeExistsPred(object): def __init__(self, name):",
"self.edges[node_id] def add_handler(self, labeled_handler): for node_id in self.terminal_nodes: self.labeled_handlers[node_id].append(labeled_handler) def new_node(self, from_node_id, test):",
"commentMatch(self, node): pass def processingInstructionMatch(self, node): pass class VerbosePushtreeHandler(PushtreeHandler): def __init__(self, prefix=None): if",
"self.start_edges.extend(other.start_edges) self.edges.update(other.edges) self.match_types.update(other.match_types) self.terminal_nodes.update(other.terminal_nodes) self.labeled_handlers.update(other.labeled_handlers) def dump(self): for node_id, edges in [(None, self.start_edges)]",
"node): print self.prefix+\"startElementMatch\", node def endElementMatch(self, node): print self.prefix+\"endElementMatch\", node def attributeMatch(self, node):",
"attr_ops: print attr_op print \" PI OPS\" for pi_op in pi_ops: print pi_op",
"# instead of O(n). However, for now, n is no more than 10",
"current_dfa) if not transitions: # Make sure there's always a target. # This",
"assert isinstance(tree, set) if tree: comment_state = numbering[frozenset(tree)] else: comment_state = 0 states.append(",
"empty and union everything? for nfa in nfas[1:]: union_nfa.union(nfa) dfa, numbering = nfa_to_dfa(union_nfa)",
"step in expr._steps: nfa.extend(to_nfa(step, namespaces)) _add_initial_loop(nfa) return nfa if (expr.__class__ is locationpaths.absolute_location_path): #",
"def startElementMatch(self, node): pass def endElementMatch(self, node): pass def attributeMatch(self, node): pass def",
"subnfa = to_nfa(step, namespaces) if axis_name == \"descendant\": _add_initial_loop(subnfa) nfa.extend(subnfa) return nfa if",
"different method. handlers = [] for (label, handler) in sorted(handler_map.items()): handlers.append(handler) # node",
"new_true_test: if isinstance(tree.if_true, set): new_branch = Branch(new_true_test, tree.if_true | set([to_node_id]), tree.if_true) tree.if_true =",
"build_instructions(nfa,dfa,numbering) RuleMachineHandler.__init__(self, machine_states, end_node_handler = end_node_handler, attr_handler = attr_handler) def dump_machine_states(machine_states): for i,",
"parent_test assert getattr(parent_test, \"predicates\", None) is None assert isinstance(child_test, BaseNodeTest), child_test assert getattr(child_test,",
"xpath, xpath_handler=None): return self._add(xpath, xpath_handler) def _build_machine_states(self): return nfas_to_machine_states([x._nfa for x in self.expressions])",
"TODO: something more sophisticated? For example, if there are a # large number",
"def __init__(self, prefix=None): if prefix is None: prefix = \"\" else: prefix =",
"nodes, attribute, PIs, and comments #class AnyTest(object): # pass class BaseNodeTest(object): match_type =",
"dump_machine_states(machine_states): for i, x in enumerate(machine_states): print \"== INFO FOR\", i, \"==\" handlers,",
"# if the namespace fields are different. # XXX check for predicates! if",
"if dfa_id == 0: assert node_ids == set([None]) # handlers (which are in",
"isinstance(tree, set): namespace, localname = tree.test.name attr_ops.append( (namespace, localname, numbering[frozenset(tree.if_true)]) ) tree =",
"if not tree: node_ops = [] # ... because there are no states",
"tree tree = table.node_tree.if_true if isinstance(tree, set): # Special case when there are",
"if isinstance(test, BaseNodeTest): self._add(self.node_tree, test, to_node_id, node_intersect) elif isinstance(test, AttributeTest): self._add(self.attr_tree, test, to_node_id,",
"(expr.__class__ is locationpaths.relative_location_path): # This is a set of path specifiers like #",
"= self.machine_states[state][3] for (pi_target, pi_state) in pi_ops: if pi_target == target: handlers =",
"self.func = func ##### # This would yield nodes, attribute, PIs, and comments",
"# actual instances I need except the startElement and # endElement use different",
"make a decision tree. Either the test passes or it fails. # TODO:",
"parent_test is not None: assert isinstance(parent_test, ProcessingInstructionTest), parent_test assert isinstance(child_test, ProcessingInstructionTest), child_test if",
"loop #print \"GoTo\", next_state self.stack.append(next_state) handlers = self.machine_states[next_state][0] for handler in handlers: handler.startElementMatch(node)",
"op, value): self.name = name self.op = op self.value = value class AttributeFunctionCallPred(object):",
"parent_test assert isinstance(child_test, CommentTest), child_test return True, False # Used to make a",
"startElement and # endElement use different method. handlers = [] for (label, handler)",
"((ns is None or ns == namespace) and (ln is None or ln",
"= attr_handler) def dump_machine_states(machine_states): for i, x in enumerate(machine_states): print \"== INFO FOR\",",
"False, child_test def pi_intersect(parent_test, child_test): if parent_test is not None: assert isinstance(parent_test, ProcessingInstructionTest),",
"match_type in state_table.get_final_nodes(): some_dfa = frozenset(nfa_nodes) if some_dfa not in seen: seen.add(some_dfa) todo.append(",
"node_op print \" ATTR OPS\" for attr_op in attr_ops: print attr_op print \"",
"to make if not tree: node_ops = [] # ... because there are",
"pass def startElementMatch(self, node): pass def endElementMatch(self, node): pass def attributeMatch(self, node): pass",
"if if_true > 0: todo.append(if_true) node_ops = tuple(node_ops) # attr tree attr_ops =",
"new_false_test == True: self._add_to_leaves(tree.if_false, to_node_id) elif new_false_test: if isinstance(tree.if_false, set): new_branch = Branch(new_false_test,",
"self.labeled_handlers[node_id].append(labeled_handler) def new_node(self, from_node_id, test): edges = self.get_edges(from_node_id) to_node_id = next(counter) self.edges[to_node_id] =",
"{} for node_id in node_ids: for (label, handler) in nfa.labeled_handlers[node_id]: handler_map[label] = handler",
"path in expr._paths[1:]: nfa.union(to_nfa(path, namespaces)) return nfa die(expr) def node_intersect(parent_test, child_test): if parent_test",
"This also stores any handler events result[current_dfa] = StateTable(match_type, nfa, current_dfa) numbering[current_dfa] =",
"the attribute node handler.attributeMatch( (node, (namespace, localname) ) ) def endElementNS(self, node, name,",
") tree = tree.if_false if tree: # Match any attribute attr_ops.append( (None, None,",
"PI OPS\" for pi_op in pi_ops: print pi_op print \" COMMENT STATE =\",",
"axis = step.axis axis_name = axis.name assert axis_name in (\"child\", \"descendant\"), axis_name subnfa",
"nfa self.nfa_node_ids = nfa_node_ids self.node_tree = Branch(None, set(), set()) self.attr_tree = Branch(None, set(),",
"assert not set(self.edges) & set(other.edges), \"non-empty intersection\" if not self.start_edges: self.start_edges[:] = other.start_edges",
"FOR\", i, \"==\" handlers, node_ops, attr_ops, pi_ops, comment_state = x print \" HANDLERS\",",
"def __init__(self, name): self.name = name # [@x=\"a\"] class AttributeBinOpPred(object): def __init__(self, name,",
"= len(node_ops) node_ops.append(tree.if_false) namespace, localname = tree.test.name node_ops[i] = (namespace, localname, None, if_true,",
"True: self._add_to_leaves(tree.if_true, to_node_id) elif new_true_test: if isinstance(tree.if_true, set): new_branch = Branch(new_true_test, tree.if_true |",
"-i break # otherwise, loop #print \"GoTo\", next_state self.stack.append(next_state) handlers = self.machine_states[next_state][0] for",
"value class AttributeFunctionCallPred(object): def __init__(self, func): self.func = func ##### # This would",
"not predicates self.predicates = predicates def __str__(self): return \"Attr name=%r\" % (self.name,) class",
"tags and start # in the middle. Should give O(log(number of tags)) performance",
"print self.prefix+\"startElementMatch\", node def endElementMatch(self, node): print self.prefix+\"endElementMatch\", node def attributeMatch(self, node): print",
"downward axes. (XXX I think.) class AttributeTest(object): match_type = \"attr\" def __init__(self, name,",
"union_nfa = nfas[0].copy() # XXX start with empty and union everything? for nfa",
"def dump(self, numbering): # Do I report anything for having reached here? if",
"match_type, nfa, nfa_node_ids): self.match_type = match_type # 'None' for the start node self.nfa",
"manager.expressions[4]._nfa.dump() #manager.add(\".//*\") machine_states = manager._build_machine_states() dump_machine_states(machine_states) hand = RuleMachineHandler(machine_states) import os doc =",
"expr._paths[1:]: nfa.union(to_nfa(path, namespaces)) return nfa die(expr) def node_intersect(parent_test, child_test): if parent_test is not",
"if isinstance(child_test, AnyNodeTest): return True, True if isinstance(child_test, NodeTest): # XXX This is",
"also stores any handler events result[current_dfa] = StateTable(match_type, nfa, current_dfa) numbering[current_dfa] = len(numbering)",
"element): print self.prefix+\"startSubtree\", element def endSubtree(self, element): print self.prefix+\"endSubtree\", element def startElementMatch(self, node):",
"attr_ops: #print \"attr test:\", (ns, ln), (namespace, localname) if ((ns is None or",
"expr._steps: nfa.extend(to_nfa(step, namespaces)) _add_initial_loop(nfa) return nfa if expr.__class__ is locationpaths.location_step: # This is",
"step in expr._steps: nfa.extend(to_nfa(step, namespaces)) _add_initial_loop(nfa) return nfa if expr.__class__ is locationpaths.location_step: #",
"for x in self.expressions]) def build_pushtree_handler(self): return RuleMachineHandler(self._build_machine_states()) # Special handler object to",
"AttributeTest), child_test if parent_test is None: return child_test, False if parent_test.name == child_test.name:",
"manager = PushtreeManager(\"body/ul/li\", VerbosePushtreeHandler(\"main\")) manager.expressions[0]._nfa.dump() manager.add(\"pre/post\", VerbosePushtreeHandler(\"pre/post\")) manager.expressions[1]._nfa.dump() manager.add(\"//a\", VerbosePushtreeHandler(\"//a\")) manager.expressions[2]._nfa.dump() manager.add(\"@x\", VerbosePushtreeHandler(\"@x\"))",
"self.if_true = if_true self.if_false = if_false class StateTable(object): def __init__(self, match_type, nfa, nfa_node_ids):",
"is a string if parent_test.target == child_test.target: return True, False return False, child_test",
"False, child_test def comment_intersect(parent_test, child_test): if parent_test is not None: assert isinstance(parent_test, CommentTest),",
"return \"Attr name=%r\" % (self.name,) class ProcessingInstructionTest(object): match_type = \"processing-instruction\" def __init__(self, target):",
"class StateTable(object): def __init__(self, match_type, nfa, nfa_node_ids): self.match_type = match_type # 'None' for",
"self.node_tree), (\"ATTR\", self.attr_tree), (\"PROCESSING-INSTRUCTION\", self.pi_tree), (\"COMMENT\", self.comment_tree) ): if tree is None: print",
"predicates! if parent_test.name == child_test.name: return True, False return False, child_test def attr_intersect(parent_test,",
"pushbind support in the builder # Implemented by beazley. Note: This is not",
"However, for now, n is no more than 10 or so. class Branch(object):",
"# For Dave class RulePatternHandler(RuleMachineHandler): def __init__(self, pattern, end_node_handler, attr_handler, namespaces=None): self.xpm =",
"when there are no decisions to make if not tree: node_ops = []",
"ln == localname)): i = if_true else: i = if_false if i ==",
"id self.xpath = xpath self._nfa = nfa def nfas_to_machine_states(nfas): union_nfa = nfas[0].copy() #",
"if (expr.__class__ is locationpaths.relative_location_path): # This is a set of path specifiers like",
"== ns) and (ln is None or localname == ln)): # Match! handlers",
"assert isinstance(parent_test, BaseNodeTest), parent_test assert getattr(parent_test, \"predicates\", None) is None assert isinstance(child_test, BaseNodeTest),",
"numbering[frozenset(tree.if_true)]) ) tree = tree.if_false if tree: # Match any attribute attr_ops.append( (None,",
"for (label, handler) in sorted(handler_map.items()): handlers.append(handler) # node tree tree = table.node_tree.if_true if",
"depth+1, numbering) def all_transitions(nfa, current_dfa): transitions = [] for node_id in current_dfa: if",
"if list(self.nfa_node_ids) != [None]: for nfa_node in self.nfa_node_ids: labels = [x[0] for x",
"nfa.match_types[node_id] if match_type not in (\"node\", \"record\"): continue new_transitions = nfa.edges[node_id] transitions.extend(new_transitions) return",
"self.predicates = predicates def __str__(self): return \"Node ns=%r localname=%r predicates=%r\" % (self.name[0], self.name[1],",
"break # otherwise, loop #print \"GoTo\", next_state self.stack.append(next_state) handlers = self.machine_states[next_state][0] for handler",
"tree attr_ops = [] tree = table.attr_tree.if_true while not isinstance(tree, set): namespace, localname",
"comment_state = x print \" HANDLERS\", handlers print \" NODE OPS\" for node_op",
"else: if_false = len(node_ops) node_ops.append(tree.if_false) namespace, localname = tree.test.name node_ops[i] = (namespace, localname,",
"if parent_test is not None: assert isinstance(parent_test, CommentTest), parent_test assert isinstance(child_test, CommentTest), child_test",
"Used to make a decision tree. Either the test passes or it fails.",
"die(expr): import inspect print \" == FAILURE ==\" print type(expr) print dir(expr) for",
"tree is None: print \" No\", name, \"tree\" else: print name, \"tree:\" #",
"None or namespace == ns) and (ln is None or localname == ln)):",
"amara.xpath.functions import nodesets from amara.xpath.expressions import booleans import amara.xpath.expressions.nodesets # another nodesets! from",
"visit = [tree] while visit: node = visit.pop() if isinstance(node, set): if node:",
"I need except the startElement and # endElement use different method. handlers =",
"in state_table.get_final_nodes(): some_dfa = frozenset(nfa_nodes) if some_dfa not in seen: seen.add(some_dfa) todo.append( (some_dfa,",
"self.edges[node_id].extend(other.start_edges) self.terminal_nodes.clear() self.terminal_nodes.update(other.terminal_nodes) self.labeled_handlers.update(other.labeled_handlers) def union(self, other): assert not set(self.edges) & set(other.edges), \"non-empty",
"repr(k), repr(v) raise AssertionError(expr) def build_states(nfa, dfa, numbering): # unique node numbers states",
"until I can figure out how to get # the attribute node handler.attributeMatch(",
"beazley. Note: This is not a proper SAX handler class RuleMachineHandler(object): def __init__(self,",
"without a namespace, like \"a\" node_id = nfa.new_node(None, klass(node_test.name_key, expr.predicates)) elif node_test.__class__ is",
"== child_test.name: return True, False return False, child_test def pi_intersect(parent_test, child_test): if parent_test",
"not in seen: seen.add(some_dfa) todo.append( (some_dfa, match_type) ) result[current_dfa] = state_table numbering[current_dfa] =",
"qname, attrs, \"state\", state if state == -1: #print \"goto -1\" self.stack.append(-1) return",
"tree.if_true | set([to_node_id]), tree.if_true) tree.if_true = new_branch else: self._add(tree.if_true, new_true_test, to_node_id, intersect) if",
"return child_test, False # Is there any way to match *any* PI? #",
"= table.attr_tree.if_true while not isinstance(tree, set): namespace, localname = tree.test.name attr_ops.append( (namespace, localname,",
"class RuleMachineHandler(object): def __init__(self, machine_states): self.machine_states = machine_states def startDocument(self,node): self.stack = [0]",
"not element_ops: # This was a valid target, but there's nothing leading off",
"XXX I can't transition from something # which wasn't a node or a",
"print \" COMMENT STATE =\", comment_state class PushtreeHandler(object): def startSubtree(self, element): pass def",
"# Implemented by beazley. Note: This is not a proper SAX handler class",
"__str__(self): return \"processing-instruction(%r)\" % (self.target,) class CommentTest(object): match_type = \"comment\" class NFA(object): def",
"= handler # This are PushtreeHandler instances. I could find the # actual",
"[] for node_id in current_dfa: if node_id is None: new_transitions = nfa.start_edges else:",
"import nodesets from amara.xpath.expressions import booleans import amara.xpath.expressions.nodesets # another nodesets! from amara.xpath.expressions",
"CommentTest), parent_test assert isinstance(child_test, CommentTest), child_test return True, False # Used to make",
"test, if_true, if_false): self.test = test self.if_true = if_true self.if_false = if_false class",
"\"\" else: node_name = str(node_id) action = str(self.match_types[node_id]) labels += \" \" +",
"= None): if namespaces is None: namespaces = {} self.namespaces = namespaces self.expressions",
"func): self.func = func ##### # This would yield nodes, attribute, PIs, and",
"# This is an abbreviated_absolute_location_path # \"//a\", \"a//b\" nfa = NFA() for step",
"Raymond's code def nfa_to_dfa(nfa): numbering = {} # from frozenset -> 0, 1,",
"attr_state_id) in attr_ops: #print \"attr test:\", (ns, ln), (namespace, localname) if ((ns is",
"node_ids) for (node_ids, dfa_id) in numbering.items() ): assert dfa_id == len(states) if dfa_id",
"return self.edges[node_id] def add_handler(self, labeled_handler): for node_id in self.terminal_nodes: self.labeled_handlers[node_id].append(labeled_handler) def new_node(self, from_node_id,",
"i = if_false if i == 0: # dead-end; no longer part of",
"None: prefix = \"\" else: prefix = \"(%s) \" % (prefix,) self.prefix =",
"VerbosePushtreeHandler(\"pre/post\")) manager.expressions[1]._nfa.dump() manager.add(\"//a\", VerbosePushtreeHandler(\"//a\")) manager.expressions[2]._nfa.dump() manager.add(\"@x\", VerbosePushtreeHandler(\"@x\")) manager.expressions[3]._nfa.dump() manager.add(\"a\", VerbosePushtreeHandler(\"a\")) manager.expressions[4]._nfa.dump() #manager.add(\".//*\") machine_states",
"\"== INFO FOR\", i, \"==\" handlers, node_ops, attr_ops, pi_ops, comment_state = x print",
"#print \"GoTo\", next_state self.stack.append(next_state) handlers = self.machine_states[next_state][0] for handler in handlers: handler.startElementMatch(node) #",
"False if parent_test.name == child_test.name: return True, False return False, child_test def pi_intersect(parent_test,",
"def _dump(self, tree, depth, numbering): s = \"-\"*depth if isinstance(tree, set): if tree:",
"match_type self.labeled_handlers = {} # node_id -> (label, PushtreeHandler) def copy(self): nfa =",
"klass((namespace, None), expr.predicates)) elif node_test.__class__ is nodetests.qualified_name_test: prefix, localname = node_test.name_key namespace =",
"VerbosePushtreeHandler(\"main\")) manager.expressions[0]._nfa.dump() manager.add(\"pre/post\", VerbosePushtreeHandler(\"pre/post\")) manager.expressions[1]._nfa.dump() manager.add(\"//a\", VerbosePushtreeHandler(\"//a\")) manager.expressions[2]._nfa.dump() manager.add(\"@x\", VerbosePushtreeHandler(\"@x\")) manager.expressions[3]._nfa.dump() manager.add(\"a\", VerbosePushtreeHandler(\"a\"))",
"handler in handlers: handler.processingInstruction(node) # For Dave class RulePatternHandler(RuleMachineHandler): def __init__(self, pattern, end_node_handler,",
"test) ) return to_node_id def connect(self, from_node_id, to_node_id, test): self.get_edges(from_node_id).append( (to_node_id, test) )",
"self._add(subtree_xpath, subtree_handler) def _add(self, xpath, xpath_handler): nfa = to_nfa(xpath_parser.parse(xpath), self.namespaces) i = len(self.expressions)",
"set): if tree.if_false: if_false = -numbering[frozenset(tree.if_false)] else: if_false = 0 else: if_false =",
"isinstance(tree, set): # Special case when there are no decisions to make if",
"# (ns, name) self.name = name self.predicates = predicates def __str__(self): return \"Node",
"> 0: todo.append(if_false) if if_true > 0: todo.append(if_true) node_ops = tuple(node_ops) # attr",
"tree.test.name attr_ops.append( (namespace, localname, numbering[frozenset(tree.if_true)]) ) tree = tree.if_false if tree: # Match",
"transitions.extend(new_transitions) return transitions def transition(nfa_state, event): for (to_node_id, test) in edge in nfa_state.edges:",
"Is there any way to match *any* PI? # Looks like Amara support",
"get_final_nodes(self): result = {} for match_type, tree in ( (BaseNodeTest.match_type, self.node_tree), (AttributeTest.match_type, self.attr_tree),",
"else: i = if_false if i == 0: # dead-end; no longer part",
"def __init__(self, test, if_true, if_false): self.test = test self.if_true = if_true self.if_false =",
"if axis_name == \"attribute\": klass = AttributeTest else: klass = NodeTest nfa =",
"self.pi_tree = Branch(None, set(), set()) self.comment_tree = Branch(None, set(), set()) def add(self, test,",
"handlers (which are in (id, class) pairs) table = dfa[node_ids] if dfa_id ==",
"i = 0 while 1: ns, ln, test_function, if_true, if_false = element_ops[i] assert",
"Branch(new_true_test, tree.if_true | set([to_node_id]), tree.if_true) tree.if_true = new_branch else: self._add(tree.if_true, new_true_test, to_node_id, intersect)",
"0 while 1: ns, ln, test_function, if_true, if_false = element_ops[i] assert test_function is",
"[0] while todo: i = todo.pop() #print \"Access\", i, len(node_ops) tree = node_ops[i]",
"= len(self.expressions) nfa.add_handler((i, xpath_handler)) exp = Expression(i, xpath, nfa) self.expressions.append(exp) return exp def",
"\"descendant\": # _add_initial_loop(nfa) #print \"QWERQWER\" #nfa.dump() return nfa if expr.__class__ is amara.xpath.expressions.nodesets.union_expr: #",
"start node result = {} # [] seen = set([dfa_start]) todo = [(dfa_start,",
"\"a//b\" nfa = NFA() for step in expr._steps: nfa.extend(to_nfa(step, namespaces)) _add_initial_loop(nfa) return nfa",
"or namespace == ns) and (ln is None or localname == ln)): #",
"which gives nothing nfa = NFA() for step in expr._steps: nfa.extend(to_nfa(step, namespaces)) _add_initial_loop(nfa)",
"def __init__(self, name, op, value): self.name = name self.op = op self.value =",
"= \"(start)\" labels = \"\" else: node_name = str(node_id) action = str(self.match_types[node_id]) labels",
"_dump_edges(self, edges): for (to_node_id, test) in edges: print \"\", test, \"->\", to_node_id def",
"element): pass def endSubtree(self, element): pass def startElementMatch(self, node): pass def endElementMatch(self, node):",
"self.terminal_nodes) else \"\" print node_name, is_terminal, labels self._dump_edges(edges) print \"======\" def _dump_edges(self, edges):",
"name, \"tree:\" # The first branch is always true self._dump(tree.if_true, 0, numbering) def",
"__str__(self): return \"Node ns=%r localname=%r predicates=%r\" % (self.name[0], self.name[1], self.predicates) # predicates make",
"action = str(self.match_types[node_id]) labels += \" \" + str([x[0] for x in self.labeled_handlers[node_id]])",
"about *[@spam] ? class AnyNodeTest(BaseNodeTest): def __str__(self): return \"AnyNode (*)\" class NodeTest(BaseNodeTest): def",
"= {} # from frozenset -> 0, 1, 2, ... dfa_start = frozenset([None])",
"def attributeMatch(self, node): pass def commentMatch(self, node): pass def processingInstructionMatch(self, node): pass class",
"StateTable(object): def __init__(self, match_type, nfa, nfa_node_ids): self.match_type = match_type # 'None' for the",
"if dfa_id == 0: handlers = () else: handler_map = {} for node_id",
"nfa.extend(subnfa) return nfa if (expr.__class__ is locationpaths.abbreviated_absolute_location_path): # This is an abbreviated_absolute_location_path #",
"== child_test.name: return True, False return False, child_test def attr_intersect(parent_test, child_test): if parent_test",
"if isinstance(tree.if_false, set): if tree.if_false: if_false = -numbering[frozenset(tree.if_false)] else: if_false = 0 else:",
"print s, tree.test, \"?\" self._dump(tree.if_true, depth+1, numbering) self._dump(tree.if_false, depth+1, numbering) def all_transitions(nfa, current_dfa):",
"visit: node = visit.pop() if isinstance(node, set): if node: result[frozenset(node)] = match_type elif",
"edge[0] == event: yield edge[1] # Raymond's code def nfa_to_dfa(nfa): numbering = {}",
"def processingInstructionMatch(self, node): pass class VerbosePushtreeHandler(PushtreeHandler): def __init__(self, prefix=None): if prefix is None:",
"def extend(self, other): assert not set(self.edges) & set(other.edges), \"non-empty intersection\" if not self.start_edges:",
"handler_map[label] = handler # This are PushtreeHandler instances. I could find the #",
"XXX This is wrong. Resolved namespaces can be the same even # if",
"node_id in self.terminal_nodes: self.labeled_handlers[node_id].append(labeled_handler) def new_node(self, from_node_id, test): edges = self.get_edges(from_node_id) to_node_id =",
"node_test.__class__ is nodetests.local_name_test: # Something without a namespace, like \"a\" node_id = nfa.new_node(None,",
"comment, etc. transitions state_table = StateTable(match_type, nfa, current_dfa) for to_node_id, test in transitions:",
"to_node_id) for nfa_nodes, match_type in state_table.get_final_nodes(): some_dfa = frozenset(nfa_nodes) if some_dfa not in",
"assert test_function is None if ((ns is None or ns == namespace) and",
"= self.stack[-1] if state == -1: return pi_ops = self.machine_states[state][3] for (pi_target, pi_state)",
"handler.processingInstruction(node) # For Dave class RulePatternHandler(RuleMachineHandler): def __init__(self, pattern, end_node_handler, attr_handler, namespaces=None): self.xpm",
"are no states else: node_ops = [(None, None, None, -numbering[frozenset(tree)])] else: node_ops =",
"machine_states = build_instructions(nfa,dfa,numbering) RuleMachineHandler.__init__(self, machine_states, end_node_handler = end_node_handler, attr_handler = attr_handler) def dump_machine_states(machine_states):",
"test, to_node_id): if isinstance(test, BaseNodeTest): self._add(self.node_tree, test, to_node_id, node_intersect) elif isinstance(test, AttributeTest): self._add(self.attr_tree,",
"adds element, attribute, comment, etc. transitions state_table = StateTable(match_type, nfa, current_dfa) for to_node_id,",
"def get_edges(self, node_id): if node_id is None: return self.start_edges return self.edges[node_id] def add_handler(self,",
"= intersect(tree.test, test) if new_true_test == True: self._add_to_leaves(tree.if_true, to_node_id) elif new_true_test: if isinstance(tree.if_true,",
"set(), set()) def add(self, test, to_node_id): if isinstance(test, BaseNodeTest): self._add(self.node_tree, test, to_node_id, node_intersect)",
"table.pi_tree.if_true while not isinstance(tree, set): target = tree.test.target pi_ops.append( (target, numbering[frozenset(tree.if_true)]) ) tree",
"VerbosePushtreeHandler(PushtreeHandler): def __init__(self, prefix=None): if prefix is None: prefix = \"\" else: prefix",
"AssertionError(expr) def build_states(nfa, dfa, numbering): # unique node numbers states = [] for",
"return True, False if isinstance(child_test, NodeTest): return child_test, False if isinstance(parent_test, AnyNodeTest): if",
"child_test if parent_test is None: return child_test, False # Is there any way",
"axis_name in (\"child\", \"descendant\"), axis_name subnfa = to_nfa(step, namespaces) if axis_name == \"descendant\":",
"Either the test passes or it fails. # TODO: something more sophisticated? For",
"while not isinstance(tree, set): target = tree.test.target pi_ops.append( (target, numbering[frozenset(tree.if_true)]) ) tree =",
"self.edges = {} # from_node_id -> [(to_node_id, test), ...] self.terminal_nodes = set() #",
"<reponame>zepheira/amara<gh_stars>1-10 import itertools from amara.xpath import parser as xpath_parser from amara.xpath import locationpaths",
"True, False if isinstance(child_test, NodeTest): return child_test, False if isinstance(parent_test, AnyNodeTest): if isinstance(child_test,",
"from amara.xpath.functions import nodesets from amara.xpath.expressions import booleans import amara.xpath.expressions.nodesets # another nodesets!",
"axis = expr.axis axis_name = axis.name assert axis_name in (\"child\", \"descendant\", \"attribute\"), axis_name",
") def extend(self, other): assert not set(self.edges) & set(other.edges), \"non-empty intersection\" if not",
"along some axis, such as: # \"a\" - step along the child axis",
"= () else: handler_map = {} for node_id in node_ids: for (label, handler)",
"parent_test is not None: assert isinstance(parent_test, BaseNodeTest), parent_test assert getattr(parent_test, \"predicates\", None) is",
"self.name[1], self.predicates) # predicates make no sense here because we only support downward",
"True, False return False, child_test def pi_intersect(parent_test, child_test): if parent_test is not None:",
"# This is a hack until I can figure out how to get",
"if new_false_test == True: self._add_to_leaves(tree.if_false, to_node_id) elif new_false_test: if isinstance(tree.if_false, set): new_branch =",
"tree.if_true: if_true = -numbering[frozenset(tree.if_true)] else: if_true = 0 else: if_true = len(node_ops) node_ops.append(tree.if_true)",
"None)] while todo: current_dfa, match_type = todo.pop() #print \"All transitions from\", current_dfa transitions",
"= NFA() for step in expr._steps: nfa.extend(to_nfa(step, namespaces)) _add_initial_loop(nfa) return nfa if expr.__class__",
"= nfas[0].copy() # XXX start with empty and union everything? for nfa in",
"self.name = name assert not predicates self.predicates = predicates def __str__(self): return \"Attr",
"attr_handler = attr_handler) def dump_machine_states(machine_states): for i, x in enumerate(machine_states): print \"== INFO",
"= itertools.count(1) # [@x] class AttributeExistsPred(object): def __init__(self, name): self.name = name #",
"__init__(self, pattern, end_node_handler, attr_handler, namespaces=None): self.xpm = xpm = ExpressionManager(namespaces=namespaces); xpm.add(pattern) nfa, dfa,",
"# predicates make no sense here because we only support downward axes #",
"think.) class AttributeTest(object): match_type = \"attr\" def __init__(self, name, predicates): self.name = name",
"something # which wasn't a node or a record match_type = nfa.match_types[node_id] if",
"__init__(self, target): self.target = target def __str__(self): return \"processing-instruction(%r)\" % (self.target,) class CommentTest(object):",
"XXX start with empty and union everything? for nfa in nfas[1:]: union_nfa.union(nfa) dfa,",
"ln), (namespace, localname) if ((ns is None or namespace == ns) and (ln",
"= Branch(None, set(), set()) self.pi_tree = Branch(None, set(), set()) self.comment_tree = Branch(None, set(),",
"to_node_id def connect(self, from_node_id, to_node_id, test): self.get_edges(from_node_id).append( (to_node_id, test) ) def extend(self, other):",
"last_state == -1: return handlers = self.machine_states[last_state][0] for handler in reversed(handlers): handler.endElementMatch(node) def",
"Expression(object): def __init__(self, id, xpath, nfa): self.id = id self.xpath = xpath self._nfa",
"handler in handlers: handler.startElementMatch(node) # Also handle any attributes attr_ops = self.machine_states[next_state][2] if",
"pass class VerbosePushtreeHandler(PushtreeHandler): def __init__(self, prefix=None): if prefix is None: prefix = \"\"",
"\"record\"): continue new_transitions = nfa.edges[node_id] transitions.extend(new_transitions) return transitions def transition(nfa_state, event): for (to_node_id,",
"some_dfa not in seen: seen.add(some_dfa) todo.append( (some_dfa, match_type) ) result[current_dfa] = state_table numbering[current_dfa]",
"localname) # This is a hack until I can figure out how to",
"if_true, if_false = element_ops[i] assert test_function is None if ((ns is None or",
"# node_id -> match_type self.labeled_handlers = {} # node_id -> (label, PushtreeHandler) def",
"This is an abbreviated_absolute_location_path # \"//a\", \"a//b\" nfa = NFA() for step in",
"to_node_id, comment_intersect) else: raise AssertionError(test) def _add(self, tree, test, to_node_id, intersect): new_true_test, new_false_test",
"def __init__(self, match_type, nfa, nfa_node_ids): self.match_type = match_type # 'None' for the start",
"the startElement and # endElement use different method. handlers = [] for (label,",
"set): namespace, localname = tree.test.name attr_ops.append( (namespace, localname, numbering[frozenset(tree.if_true)]) ) tree = tree.if_false",
"transitions = all_transitions(nfa, current_dfa) if not transitions: # Make sure there's always a",
"numbering[current_dfa] = len(numbering) # for k, table in sorted(result.items(), key=lambda x:sorted(x[0])): # print",
"(namespace, localname, numbering[frozenset(tree.if_true)]) ) tree = tree.if_false if tree: # Match any attribute",
"# the attribute node handler.attributeMatch( (node, (namespace, localname) ) ) def endElementNS(self, node,",
"nodesets from amara.xpath.expressions import booleans import amara.xpath.expressions.nodesets # another nodesets! from amara.xpath.expressions import",
"subtree_handler = None, namespaces = None): if namespaces is None: namespaces = {}",
"no name, like \"a:*\" namespace = namespaces[node_test._prefix] node_id = nfa.new_node(None, klass((namespace, None), expr.predicates))",
"attr_handler, namespaces=None): self.xpm = xpm = ExpressionManager(namespaces=namespaces); xpm.add(pattern) nfa, dfa, numbering = xpm.build_dfa_tables()",
"or a record match_type = nfa.match_types[node_id] if match_type not in (\"node\", \"record\"): continue",
"seen: seen.add(some_dfa) todo.append( (some_dfa, match_type) ) result[current_dfa] = state_table numbering[current_dfa] = len(numbering) #",
"Also handle any attributes attr_ops = self.machine_states[next_state][2] if not attr_ops: return for namespace,",
"==\" print type(expr) print dir(expr) for k, v in inspect.getmembers(expr): if k.startswith(\"__\") and",
"\"Eval\", expr.__class__ if (expr.__class__ is locationpaths.relative_location_path): # This is a set of path",
"isinstance(child_test, AttributeTest), child_test if parent_test is None: return child_test, False if parent_test.name ==",
"None: return child_test, False if parent_test.name == child_test.name: return True, False return False,",
"return to_node_id def connect(self, from_node_id, to_node_id, test): self.get_edges(from_node_id).append( (to_node_id, test) ) def extend(self,",
"attr_ops, pi_ops, comment_state) ) return tuple(states) class Expression(object): def __init__(self, id, xpath, nfa):",
"elif isinstance(parent_test, NodeTest): if isinstance(child_test, AnyNodeTest): return True, True if isinstance(child_test, NodeTest): #",
"localname = tree.test.name attr_ops.append( (namespace, localname, numbering[frozenset(tree.if_true)]) ) tree = tree.if_false if tree:",
"for handler in handlers: #print \"Notify attribute match:\", event_ids, (namespace, localname) # This",
"= [] for node_id in current_dfa: if node_id is None: new_transitions = nfa.start_edges",
"class VerbosePushtreeHandler(PushtreeHandler): def __init__(self, prefix=None): if prefix is None: prefix = \"\" else:",
"if_false > 0: todo.append(if_false) if if_true > 0: todo.append(if_true) node_ops = tuple(node_ops) #",
"For Dave class RulePatternHandler(RuleMachineHandler): def __init__(self, pattern, end_node_handler, attr_handler, namespaces=None): self.xpm = xpm",
"None) is None if parent_test is None: if isinstance(child_test, AnyNodeTest): return True, False",
"handlers = self.machine_states[attr_state_id][0] for handler in handlers: #print \"Notify attribute match:\", event_ids, (namespace,",
"= set() # The start node has no type self.match_types = {} #",
"element): pass def startElementMatch(self, node): pass def endElementMatch(self, node): pass def attributeMatch(self, node):",
"node_id in current_dfa: if node_id is None: new_transitions = nfa.start_edges else: # XXX",
"need except the startElement and # endElement use different method. handlers = []",
"if_true self.if_false = if_false class StateTable(object): def __init__(self, match_type, nfa, nfa_node_ids): self.match_type =",
"child_test, False if parent_test.name == child_test.name: return True, False return False, child_test def",
"# Special case when there are no decisions to make if not tree:",
"klass((namespace, localname), expr.predicates)) elif node_test.__class__ is nodetests.processing_instruction_test: node_id = nfa.new_node(None, ProcessingInstructionTest(node_test._target)) elif node_test.__class__",
"# endElement use different method. handlers = [] for (label, handler) in sorted(handler_map.items()):",
"axis_name = axis.name assert axis_name in (\"child\", \"descendant\", \"attribute\"), axis_name if axis_name ==",
"= [] self.match_types[to_node_id] = test.match_type self.labeled_handlers[to_node_id] = [] edges.append( (to_node_id, test) ) return",
"= \"(%s) \" % (prefix,) self.prefix = prefix def startSubtree(self, element): print self.prefix+\"startSubtree\",",
"None, if_true, if_false) #print \"Added\", node_ops[i] if if_false > 0: todo.append(if_false) if if_true",
"None: namespaces = {} self.namespaces = namespaces self.expressions = [] self._add(subtree_xpath, subtree_handler) def",
"= tree.if_false if tree: # Match any attribute attr_ops.append( (None, None, numbering[frozenset(tree)]) )",
"for having reached here? if list(self.nfa_node_ids) != [None]: for nfa_node in self.nfa_node_ids: labels",
"0: # dead-end; no longer part of the DFA and the # 0",
"new_branch = Branch(new_false_test, tree.if_false | set([to_node_id]), tree.if_false) tree.if_false = new_branch else: self._add(tree.if_false, new_false_test,",
"# Namespace but no name, like \"a:*\" namespace = namespaces[node_test._prefix] node_id = nfa.new_node(None,",
"where this is a string if parent_test.target == child_test.target: return True, False return",
"def __init__(self, pattern, end_node_handler, attr_handler, namespaces=None): self.xpm = xpm = ExpressionManager(namespaces=namespaces); xpm.add(pattern) nfa,",
"intersect) if new_false_test == True: self._add_to_leaves(tree.if_false, to_node_id) elif new_false_test: if isinstance(tree.if_false, set): new_branch",
"test self.if_true = if_true self.if_false = if_false class StateTable(object): def __init__(self, match_type, nfa,",
"== FAILURE ==\" print type(expr) print dir(expr) for k, v in inspect.getmembers(expr): if",
"# This also stores any handler events result[current_dfa] = StateTable(match_type, nfa, current_dfa) numbering[current_dfa]",
"set): new_branch = Branch(new_true_test, tree.if_true | set([to_node_id]), tree.if_true) tree.if_true = new_branch else: self._add(tree.if_true,",
"along the child axis # \"a[@x][@y='1']\" - step along the child axis, with",
"self.nfa.match_types[nfa_node], labels for (name, tree) in ( (\"NODE\", self.node_tree), (\"ATTR\", self.attr_tree), (\"PROCESSING-INSTRUCTION\", self.pi_tree),",
"axis_name = axis.name assert axis_name in (\"child\", \"descendant\"), axis_name subnfa = to_nfa(step, namespaces)",
"comment_intersect) else: raise AssertionError(test) def _add(self, tree, test, to_node_id, intersect): new_true_test, new_false_test =",
"# \"@a\" - step along the attribute axis axis = expr.axis axis_name =",
"nfa.new_node(None, klass((None, None), None)) else: die(node_test) nfa.terminal_nodes.add(node_id) #if axis_name == \"descendant\": # _add_initial_loop(nfa)",
"(id, class) pairs) table = dfa[node_ids] if dfa_id == 0: handlers = ()",
"tree.if_true = new_branch else: self._add(tree.if_true, new_true_test, to_node_id, intersect) if new_false_test == True: self._add_to_leaves(tree.if_false,",
"# for k, table in sorted(result.items(), key=lambda x:sorted(x[0])): # print \"State\", sorted(k) #",
"if parent_test.name == child_test.name: return True, False return False, child_test def attr_intersect(parent_test, child_test):",
"match_type) ) result[current_dfa] = state_table numbering[current_dfa] = len(numbering) # for k, table in",
"parent_test is not None: assert isinstance(parent_test, CommentTest), parent_test assert isinstance(child_test, CommentTest), child_test return",
"len(self.expressions) nfa.add_handler((i, xpath_handler)) exp = Expression(i, xpath, nfa) self.expressions.append(exp) return exp def add(self,",
"id, xpath, nfa): self.id = id self.xpath = xpath self._nfa = nfa def",
"along the attribute axis axis = expr.axis axis_name = axis.name assert axis_name in",
"tree: node_ops = [] # ... because there are no states else: node_ops",
"assert axis_name in (\"child\", \"descendant\", \"attribute\"), axis_name if axis_name == \"attribute\": klass =",
"assert getattr(child_test, \"predicates\", None) is None if parent_test is None: if isinstance(child_test, AnyNodeTest):",
"func ##### # This would yield nodes, attribute, PIs, and comments #class AnyTest(object):",
"Branch(new_false_test, tree.if_false | set([to_node_id]), tree.if_false) tree.if_false = new_branch else: self._add(tree.if_false, new_false_test, to_node_id, intersect)",
"[tree] todo = [0] while todo: i = todo.pop() #print \"Access\", i, len(node_ops)",
"table.attr_tree.if_true while not isinstance(tree, set): namespace, localname = tree.test.name attr_ops.append( (namespace, localname, numbering[frozenset(tree.if_true)])",
"namespace) and (ln is None or ln == localname)): i = if_true else:",
"axes. (XXX I think.) class AttributeTest(object): match_type = \"attr\" def __init__(self, name, predicates):",
"\"attribute\": klass = AttributeTest else: klass = NodeTest nfa = NFA() node_test =",
"axis # \"a[@x][@y='1']\" - step along the child axis, with two predicates #",
"[] tree = table.pi_tree.if_true while not isinstance(tree, set): target = tree.test.target pi_ops.append( (target,",
"None: assert isinstance(parent_test, CommentTest), parent_test assert isinstance(child_test, CommentTest), child_test return True, False #",
"wasn't a node or a record match_type = nfa.match_types[node_id] if match_type not in",
"nfas[1:]: union_nfa.union(nfa) dfa, numbering = nfa_to_dfa(union_nfa) return build_states(union_nfa, dfa, numbering) class PushtreeManager(object): def",
"def _build_machine_states(self): return nfas_to_machine_states([x._nfa for x in self.expressions]) def build_pushtree_handler(self): return RuleMachineHandler(self._build_machine_states()) #",
"self.prefix = prefix def startSubtree(self, element): print self.prefix+\"startSubtree\", element def endSubtree(self, element): print",
"nodetests.local_name_test: # Something without a namespace, like \"a\" node_id = nfa.new_node(None, klass(node_test.name_key, expr.predicates))",
"and # endElement use different method. handlers = [] for (label, handler) in",
"along the child axis, with two predicates # \"@a\" - step along the",
"if not element_ops: # This was a valid target, but there's nothing leading",
"= -i break # otherwise, loop #print \"GoTo\", next_state self.stack.append(next_state) handlers = self.machine_states[next_state][0]",
"edges = self.get_edges(from_node_id) to_node_id = next(counter) self.edges[to_node_id] = [] self.match_types[to_node_id] = test.match_type self.labeled_handlers[to_node_id]",
"print pi_op print \" COMMENT STATE =\", comment_state class PushtreeHandler(object): def startSubtree(self, element):",
"\"@a/@b\", which gives nothing nfa = NFA() for step in expr._steps: nfa.extend(to_nfa(step, namespaces))",
"isinstance(tree, set) if tree: comment_state = numbering[frozenset(tree)] else: comment_state = 0 states.append( (handlers,",
"<body> <li>Ignore me<b/></li> <ul> <li x='1'>This <i>is</i> test</li> <li x='2'><a href='spam'>that</a> was nothing</li>",
"tree.test.name node_ops[i] = (namespace, localname, None, if_true, if_false) #print \"Added\", node_ops[i] if if_false",
"nfa, dfa, numbering = xpm.build_dfa_tables() machine_states = build_instructions(nfa,dfa,numbering) RuleMachineHandler.__init__(self, machine_states, end_node_handler = end_node_handler,",
"connect(self, from_node_id, to_node_id, test): self.get_edges(from_node_id).append( (to_node_id, test) ) def extend(self, other): assert not",
"\"predicates\", None) is None assert isinstance(child_test, BaseNodeTest), child_test assert getattr(child_test, \"predicates\", None) is",
"= 0 else: if_false = len(node_ops) node_ops.append(tree.if_false) namespace, localname = tree.test.name node_ops[i] =",
"No\", name, \"tree\" else: print name, \"tree:\" # The first branch is always",
"= [x[0] for x in self.nfa.labeled_handlers[nfa_node]] if labels: print \"Report\", self.nfa.match_types[nfa_node], labels for",
"next_state = -i break # otherwise, loop #print \"GoTo\", next_state self.stack.append(next_state) handlers =",
"# Do I report anything for having reached here? if list(self.nfa_node_ids) != [None]:",
"nfa.match_types.update(self.match_types) nfa.labeled_handlers.update(self.labeled_handlers) return nfa def get_edges(self, node_id): if node_id is None: return self.start_edges",
"def build_pushtree_handler(self): return RuleMachineHandler(self._build_machine_states()) # Special handler object to bridge with pushbind support",
"decision tree. Either the test passes or it fails. # TODO: something more",
"some axis, such as: # \"a\" - step along the child axis #",
"\"Notify attribute match:\", event_ids, (namespace, localname) # This is a hack until I",
"labels: print \"Report\", self.nfa.match_types[nfa_node], labels for (name, tree) in ( (\"NODE\", self.node_tree), (\"ATTR\",",
"tree = node_ops[i] if isinstance(tree.if_true, set): if tree.if_true: if_true = -numbering[frozenset(tree.if_true)] else: if_true",
"# and these have no downward axes. (XXX I think.) class AttributeTest(object): match_type",
"localname) if ((ns is None or namespace == ns) and (ln is None",
"namespace == ns) and (ln is None or localname == ln)): # Match!",
"Resolved namespaces can be the same even # if the namespace fields are",
"current_dfa) numbering[current_dfa] = len(numbering) continue # This adds element, attribute, comment, etc. transitions",
"namespaces)) _add_initial_loop(nfa) return nfa if expr.__class__ is locationpaths.location_step: # This is a step",
"case when there are no decisions to make if not tree: node_ops =",
"is a hack until I can figure out how to get # the",
"-1: #print \"goto -1\" self.stack.append(-1) return element_ops = self.machine_states[state][1] if not element_ops: #",
"dfa_id == len(states) if dfa_id == 0: assert node_ids == set([None]) # handlers",
"for (ns, ln, attr_state_id) in attr_ops: #print \"attr test:\", (ns, ln), (namespace, localname)",
"for k, v in inspect.getmembers(expr): if k.startswith(\"__\") and k.endswith(\"__\"): continue print repr(k), repr(v)",
"if isinstance(tree, set): if tree: k = sorted(tree) print s, \"<>\", numbering[frozenset(tree)], k",
"\"(terminal)\" if (node_id in self.terminal_nodes) else \"\" print node_name, is_terminal, labels self._dump_edges(edges) print",
"= namespaces[node_test._prefix] node_id = nfa.new_node(None, klass((namespace, None), expr.predicates)) elif node_test.__class__ is nodetests.qualified_name_test: prefix,",
"\"==\" handlers, node_ops, attr_ops, pi_ops, comment_state = x print \" HANDLERS\", handlers print",
"is locationpaths.location_step: # This is a step along some axis, such as: #",
"depth+1, numbering) self._dump(tree.if_false, depth+1, numbering) def all_transitions(nfa, current_dfa): transitions = [] for node_id",
"is_terminal, labels self._dump_edges(edges) print \"======\" def _dump_edges(self, edges): for (to_node_id, test) in edges:",
"= str(self.match_types[node_id]) labels += \" \" + str([x[0] for x in self.labeled_handlers[node_id]]) is_terminal",
"numbering def die(expr): import inspect print \" == FAILURE ==\" print type(expr) print",
"(\"PROCESSING-INSTRUCTION\", self.pi_tree), (\"COMMENT\", self.comment_tree) ): if tree is None: print \" No\", name,",
"node_ids: for (label, handler) in nfa.labeled_handlers[node_id]: handler_map[label] = handler # This are PushtreeHandler",
"else: if_true = 0 else: if_true = len(node_ops) node_ops.append(tree.if_true) if isinstance(tree.if_false, set): if",
"node_ops = [tree] todo = [0] while todo: i = todo.pop() #print \"Access\",",
"# [@x=\"a\"] class AttributeBinOpPred(object): def __init__(self, name, op, value): self.name = name self.op",
"there's always a target. # This also stores any handler events result[current_dfa] =",
"enumerate(machine_states): print \"== INFO FOR\", i, \"==\" handlers, node_ops, attr_ops, pi_ops, comment_state =",
"absolute path like # \"/a\", \"/a[0]/b[@x]\" nfa = NFA() for step in expr._steps:",
"raise AssertionError(test) def _add(self, tree, test, to_node_id, intersect): new_true_test, new_false_test = intersect(tree.test, test)",
"is None if ((ns is None or ns == namespace) and (ln is",
"if isinstance(parent_test, AnyNodeTest): if isinstance(child_test, AnyNodeTest): return True, False if isinstance(child_test, NodeTest): return",
"nfa.new_node(None, klass(node_test.name_key, expr.predicates)) elif node_test.__class__ is nodetests.namespace_test: # Namespace but no name, like",
"__init__(self): self.start_edges = [] self.edges = {} # from_node_id -> [(to_node_id, test), ...]",
"numbers states = [] for dfa_id, node_ids in sorted( (dfa_id, node_ids) for (node_ids,",
"# node_id -> (label, PushtreeHandler) def copy(self): nfa = NFA() nfa.start_edges[:] = self.start_edges",
"Something without a namespace, like \"a\" node_id = nfa.new_node(None, klass(node_test.name_key, expr.predicates)) elif node_test.__class__",
"#print \"startElementNS\", name, qname, attrs, \"state\", state if state == -1: #print \"goto",
"RuleMachineHandler(self._build_machine_states()) # Special handler object to bridge with pushbind support in the builder",
"namespaces[node_test._prefix] node_id = nfa.new_node(None, klass((namespace, None), expr.predicates)) elif node_test.__class__ is nodetests.qualified_name_test: prefix, localname",
"new_false_test = intersect(tree.test, test) if new_true_test == True: self._add_to_leaves(tree.if_true, to_node_id) elif new_true_test: if",
"\"a/@b\", and even \"@a/@b\", which gives nothing nfa = NFA() for step in",
"AnyNodeTest): return True, False if isinstance(child_test, NodeTest): return child_test, False elif isinstance(parent_test, NodeTest):",
"in numbering.items() ): assert dfa_id == len(states) if dfa_id == 0: assert node_ids",
"NodeTest): # XXX This is wrong. Resolved namespaces can be the same even",
"True, False if isinstance(child_test, NodeTest): return child_test, False elif isinstance(parent_test, NodeTest): if isinstance(child_test,",
"None: if isinstance(child_test, AnyNodeTest): return True, False if isinstance(child_test, NodeTest): return child_test, False",
"predicates): # (ns, name) self.name = name self.predicates = predicates def __str__(self): return",
"= ExpressionManager(namespaces=namespaces); xpm.add(pattern) nfa, dfa, numbering = xpm.build_dfa_tables() machine_states = build_instructions(nfa,dfa,numbering) RuleMachineHandler.__init__(self, machine_states,",
"to_node_id, pi_intersect) elif isinstance(test, CommentTest): self._add(self.comment_tree, test, to_node_id, comment_intersect) else: raise AssertionError(test) def",
"numbering[frozenset(tree.if_true)]) ) tree = tree.if_false if tree: pi_ops.append( (None, numbering[frozenset(tree)]) ) pi_ops =",
"axis_name == \"attribute\": klass = AttributeTest else: klass = NodeTest nfa = NFA()",
"pi_op print \" COMMENT STATE =\", comment_state class PushtreeHandler(object): def startSubtree(self, element): pass",
"axis_name if axis_name == \"attribute\": klass = AttributeTest else: klass = NodeTest nfa",
"like Amara support XPath 1.0, where this is a string if parent_test.target ==",
"is None or ns == namespace) and (ln is None or ln ==",
"= Branch(None, set(), set()) self.comment_tree = Branch(None, set(), set()) def add(self, test, to_node_id):",
"dfa, numbering): # unique node numbers states = [] for dfa_id, node_ids in",
"numbering) class PushtreeManager(object): def __init__(self, subtree_xpath, subtree_handler = None, namespaces = None): if",
"= name i = 0 while 1: ns, ln, test_function, if_true, if_false =",
"longer part of the DFA and the # 0 node is defined to",
"nfa if (expr.__class__ is locationpaths.absolute_location_path): # This is an absolute path like #",
"== child_test.target: return True, False return False, child_test def comment_intersect(parent_test, child_test): if parent_test",
"a node or a record match_type = nfa.match_types[node_id] if match_type not in (\"node\",",
"= visit.pop() if isinstance(node, set): if node: result[frozenset(node)] = match_type elif node is",
"from something # which wasn't a node or a record match_type = nfa.match_types[node_id]",
"transition(nfa_state, event): for (to_node_id, test) in edge in nfa_state.edges: if edge[0] == event:",
"current_dfa): transitions = [] for node_id in current_dfa: if node_id is None: new_transitions",
"return namespace, localname = name i = 0 while 1: ns, ln, test_function,",
"self.terminal_nodes.clear() self.terminal_nodes.update(other.terminal_nodes) self.labeled_handlers.update(other.labeled_handlers) def union(self, other): assert not set(self.edges) & set(other.edges), \"non-empty intersection\"",
"AttributeExistsPred(object): def __init__(self, name): self.name = name # [@x=\"a\"] class AttributeBinOpPred(object): def __init__(self,",
"# [@x] class AttributeExistsPred(object): def __init__(self, name): self.name = name # [@x=\"a\"] class",
"10 or so. class Branch(object): def __init__(self, test, if_true, if_false): self.test = test",
"(XXX I think.) class AttributeTest(object): match_type = \"attr\" def __init__(self, name, predicates): self.name",
"for (to_node_id, test) in start_edges: nfa.connect(any_node, to_node_id, test) nfa.connect(any_node, any_node, AnyNodeTest()) # loop",
"last_state = self.stack.pop() if last_state == -1: return handlers = self.machine_states[last_state][0] for handler",
"namespaces=None): self.xpm = xpm = ExpressionManager(namespaces=namespaces); xpm.add(pattern) nfa, dfa, numbering = xpm.build_dfa_tables() machine_states",
"in edges: print \"\", test, \"->\", to_node_id def _add_initial_loop(nfa): start_edges = nfa.start_edges[:] any_node",
"end_node_handler, attr_handler = attr_handler) def dump_machine_states(machine_states): for i, x in enumerate(machine_states): print \"==",
"AnyNodeTest(BaseNodeTest): def __str__(self): return \"AnyNode (*)\" class NodeTest(BaseNodeTest): def __init__(self, name, predicates): #",
"__str__(self): return \"AnyNode (*)\" class NodeTest(BaseNodeTest): def __init__(self, name, predicates): # (ns, name)",
"element tag tests then sort the tags and start # in the middle.",
"#print \"QWERQWER\" #nfa.dump() return nfa if expr.__class__ is amara.xpath.expressions.nodesets.union_expr: # \"a|b\" nfa =",
"tree.if_false | set([to_node_id]), tree.if_false) tree.if_false = new_branch else: self._add(tree.if_false, new_false_test, to_node_id, intersect) def",
"transitions: # Make sure there's always a target. # This also stores any",
"visit.pop() if isinstance(node, set): if node: result[frozenset(node)] = match_type elif node is not",
"return child_test, False elif isinstance(parent_test, NodeTest): if isinstance(child_test, AnyNodeTest): return True, True if",
"print attr_op print \" PI OPS\" for pi_op in pi_ops: print pi_op print",
"a record match_type = nfa.match_types[node_id] if match_type not in (\"node\", \"record\"): continue new_transitions",
"print repr(k), repr(v) raise AssertionError(expr) def build_states(nfa, dfa, numbering): # unique node numbers",
"self.terminal_nodes.update(other.terminal_nodes) self.labeled_handlers.update(other.labeled_handlers) def union(self, other): assert not set(self.edges) & set(other.edges), \"non-empty intersection\" self.start_edges.extend(other.start_edges)",
"self.machine_states[next_state][0] for handler in handlers: handler.startElementMatch(node) # Also handle any attributes attr_ops =",
"for path in expr._paths[1:]: nfa.union(to_nfa(path, namespaces)) return nfa die(expr) def node_intersect(parent_test, child_test): if",
"AttributeTest else: klass = NodeTest nfa = NFA() node_test = expr.node_test if node_test.__class__",
"ns) and (ln is None or localname == ln)): # Match! handlers =",
"to_node_id) elif new_false_test: if isinstance(tree.if_false, set): new_branch = Branch(new_false_test, tree.if_false | set([to_node_id]), tree.if_false)",
"locationpaths.location_step: # This is a step along some axis, such as: # \"a\"",
"test_function is None if ((ns is None or ns == namespace) and (ln",
"VerbosePushtreeHandler(\"a\")) manager.expressions[4]._nfa.dump() #manager.add(\".//*\") machine_states = manager._build_machine_states() dump_machine_states(machine_states) hand = RuleMachineHandler(machine_states) import os doc",
"BaseNodeTest(object): match_type = \"node\" # What about *[@spam] ? class AnyNodeTest(BaseNodeTest): def __str__(self):",
"more sophisticated? For example, if there are a # large number of element",
"self.start_edges[:] = other.start_edges self.edges.update(other.edges) self.match_types.update(other.match_types) for node_id in self.terminal_nodes: self.edges[node_id].extend(other.start_edges) self.terminal_nodes.clear() self.terminal_nodes.update(other.terminal_nodes) self.labeled_handlers.update(other.labeled_handlers)",
"HANDLERS\", handlers print \" NODE OPS\" for node_op in node_ops: print node_op print",
"sorted(result.items(), key=lambda x:sorted(x[0])): # print \"State\", sorted(k) # table.dump() return result, numbering def",
"labels = \"\" else: node_name = str(node_id) action = str(self.match_types[node_id]) labels += \"",
"for step in expr._steps: nfa.extend(to_nfa(step, namespaces)) _add_initial_loop(nfa) return nfa if (expr.__class__ is locationpaths.absolute_location_path):",
"\"<>\", numbering[frozenset(tree)], k else: print s, \"<> (empty)\" else: print s, tree.test, \"?\"",
"is nodetests.qualified_name_test: prefix, localname = node_test.name_key namespace = namespaces[prefix] node_id = nfa.new_node(None, klass((namespace,",
"self.labeled_handlers[node_id]]) is_terminal = \"(terminal)\" if (node_id in self.terminal_nodes) else \"\" print node_name, is_terminal,",
"child axis, with two predicates # \"@a\" - step along the attribute axis",
"tree. Either the test passes or it fails. # TODO: something more sophisticated?",
"have no attributes self.stack.append(-1) return if i < 0: next_state = -i break",
"__init__(self, name, op, value): self.name = name self.op = op self.value = value",
"isinstance(tree.if_false, set): new_branch = Branch(new_false_test, tree.if_false | set([to_node_id]), tree.if_false) tree.if_false = new_branch else:",
"k, v in inspect.getmembers(expr): if k.startswith(\"__\") and k.endswith(\"__\"): continue print repr(k), repr(v) raise",
"return result.items() def dump(self, numbering): # Do I report anything for having reached",
"tree: k = sorted(tree) print s, \"<>\", numbering[frozenset(tree)], k else: print s, \"<>",
"not None: assert isinstance(parent_test, BaseNodeTest), parent_test assert getattr(parent_test, \"predicates\", None) is None assert",
"\"endElementNS\", node, name, qname last_state = self.stack.pop() if last_state == -1: return handlers",
"numbering) self._dump(tree.if_false, depth+1, numbering) def all_transitions(nfa, current_dfa): transitions = [] for node_id in",
"node def commentMatch(self, node): print self.prefix+\"commentMatch\", node def processingInstructionMatch(self, node): print self.prefix+\"processingInstructionMatch\", node",
"todo = [0] while todo: i = todo.pop() #print \"Access\", i, len(node_ops) tree",
"x in self.nfa.labeled_handlers[nfa_node]] if labels: print \"Report\", self.nfa.match_types[nfa_node], labels for (name, tree) in",
"= Expression(i, xpath, nfa) self.expressions.append(exp) return exp def add(self, xpath, xpath_handler=None): return self._add(xpath,",
"is None: return child_test, False # Is there any way to match *any*",
"if_false = 0 else: if_false = len(node_ops) node_ops.append(tree.if_false) namespace, localname = tree.test.name node_ops[i]",
"= [0] while todo: i = todo.pop() #print \"Access\", i, len(node_ops) tree =",
"Branch(None, set(), set()) def add(self, test, to_node_id): if isinstance(test, BaseNodeTest): self._add(self.node_tree, test, to_node_id,",
"(BaseNodeTest.match_type, self.node_tree), (AttributeTest.match_type, self.attr_tree), (ProcessingInstructionTest.match_type, self.pi_tree), (CommentTest.match_type, self.comment_tree) ): visit = [tree] while",
"else: print s, tree.test, \"?\" self._dump(tree.if_true, depth+1, numbering) self._dump(tree.if_false, depth+1, numbering) def all_transitions(nfa,",
"= nfa def nfas_to_machine_states(nfas): union_nfa = nfas[0].copy() # XXX start with empty and",
"pi_state) in pi_ops: if pi_target == target: handlers = self.machine_states[pi_state][0] for handler in",
"isinstance(parent_test, AttributeTest), parent_test assert isinstance(child_test, AttributeTest), child_test if parent_test is None: return child_test,",
"PushtreeHandler instances. I could find the # actual instances I need except the",
"numbering = xpm.build_dfa_tables() machine_states = build_instructions(nfa,dfa,numbering) RuleMachineHandler.__init__(self, machine_states, end_node_handler = end_node_handler, attr_handler =",
"handlers = self.machine_states[last_state][0] for handler in reversed(handlers): handler.endElementMatch(node) def processingInstruction(self, node, target, data):",
"self.node_tree), (AttributeTest.match_type, self.attr_tree), (ProcessingInstructionTest.match_type, self.pi_tree), (CommentTest.match_type, self.comment_tree) ): visit = [tree] while visit:",
"comment_state class PushtreeHandler(object): def startSubtree(self, element): pass def endSubtree(self, element): pass def startElementMatch(self,",
"True: self._add_to_leaves(tree.if_false, to_node_id) elif new_false_test: if isinstance(tree.if_false, set): new_branch = Branch(new_false_test, tree.if_false |",
"a set of path specifiers like # \"a\" \"a/b\", \"a/b/c[0]/d[@x]\" (relative location path)",
"ns == namespace) and (ln is None or ln == localname)): i =",
"key=lambda x:sorted(x[0])): # print \"State\", sorted(k) # table.dump() return result, numbering def die(expr):",
"False return False, child_test def pi_intersect(parent_test, child_test): if parent_test is not None: assert",
"# ... because there are no states else: node_ops = [(None, None, None,",
"the DFA and the # 0 node is defined to have no attributes",
"else: print name, \"tree:\" # The first branch is always true self._dump(tree.if_true, 0,",
"print self.prefix+\"processingInstructionMatch\", node if __name__ == '__main__': testxml = \"\"\"\\ <body> <li>Ignore me<b/></li>",
"{} # from_node_id -> [(to_node_id, test), ...] self.terminal_nodes = set() # The start",
"_add_to_leaves(self, tree, to_node_id): if isinstance(tree, set): tree.add(to_node_id) else: self._add_to_leaves(tree.if_true, to_node_id) self._add_to_leaves(tree.if_false, to_node_id) def",
"self._add(xpath, xpath_handler) def _build_machine_states(self): return nfas_to_machine_states([x._nfa for x in self.expressions]) def build_pushtree_handler(self): return",
"<li x='1'>This <i>is</i> test</li> <li x='2'><a href='spam'>that</a> was nothing</li> </ul> </body> \"\"\" manager",
"\"/a[0]/b[@x]\" nfa = NFA() for step in expr._steps: axis = step.axis axis_name =",
"child_test assert getattr(child_test, \"predicates\", None) is None if parent_test is None: if isinstance(child_test,",
"I think.) class AttributeTest(object): match_type = \"attr\" def __init__(self, name, predicates): self.name =",
"= self.stack[-1] #print \"startElementNS\", name, qname, attrs, \"state\", state if state == -1:",
"= self.machine_states[last_state][0] for handler in reversed(handlers): handler.endElementMatch(node) def processingInstruction(self, node, target, data): state",
"AnyTest(object): # pass class BaseNodeTest(object): match_type = \"node\" # What about *[@spam] ?",
"in nfa.labeled_handlers[node_id]: handler_map[label] = handler # This are PushtreeHandler instances. I could find",
"{} for match_type, tree in ( (BaseNodeTest.match_type, self.node_tree), (AttributeTest.match_type, self.attr_tree), (ProcessingInstructionTest.match_type, self.pi_tree), (CommentTest.match_type,",
"subtree_xpath, subtree_handler = None, namespaces = None): if namespaces is None: namespaces =",
"nfa.labeled_handlers.update(self.labeled_handlers) return nfa def get_edges(self, node_id): if node_id is None: return self.start_edges return",
"\"->\", to_node_id def _add_initial_loop(nfa): start_edges = nfa.start_edges[:] any_node = nfa.new_node(None, AnyNodeTest()) for (to_node_id,",
"print \" NODE OPS\" for node_op in node_ops: print node_op print \" ATTR",
"self.match_type = match_type # 'None' for the start node self.nfa = nfa self.nfa_node_ids",
"0 else: if_true = len(node_ops) node_ops.append(tree.if_true) if isinstance(tree.if_false, set): if tree.if_false: if_false =",
"def endElementMatch(self, node): pass def attributeMatch(self, node): pass def commentMatch(self, node): pass def",
"def processingInstructionMatch(self, node): print self.prefix+\"processingInstructionMatch\", node if __name__ == '__main__': testxml = \"\"\"\\",
"= test self.if_true = if_true self.if_false = if_false class StateTable(object): def __init__(self, match_type,",
"commentMatch(self, node): print self.prefix+\"commentMatch\", node def processingInstructionMatch(self, node): print self.prefix+\"processingInstructionMatch\", node if __name__",
"= table.node_tree.if_true if isinstance(tree, set): # Special case when there are no decisions",
"be the same even # if the namespace fields are different. # XXX",
"(target, numbering[frozenset(tree.if_true)]) ) tree = tree.if_false if tree: pi_ops.append( (None, numbering[frozenset(tree)]) ) pi_ops",
"##### # This would yield nodes, attribute, PIs, and comments #class AnyTest(object): #",
"print name, \"tree:\" # The first branch is always true self._dump(tree.if_true, 0, numbering)",
"(relative location path) # \"@a\", \"a/@b\", and even \"@a/@b\", which gives nothing nfa",
"attrs, \"state\", state if state == -1: #print \"goto -1\" self.stack.append(-1) return element_ops",
"next(counter) self.edges[to_node_id] = [] self.match_types[to_node_id] = test.match_type self.labeled_handlers[to_node_id] = [] edges.append( (to_node_id, test)",
"exp def add(self, xpath, xpath_handler=None): return self._add(xpath, xpath_handler) def _build_machine_states(self): return nfas_to_machine_states([x._nfa for",
"Do I report anything for having reached here? if list(self.nfa_node_ids) != [None]: for",
"\"\" print node_name, is_terminal, labels self._dump_edges(edges) print \"======\" def _dump_edges(self, edges): for (to_node_id,",
"target = tree.test.target pi_ops.append( (target, numbering[frozenset(tree.if_true)]) ) tree = tree.if_false if tree: pi_ops.append(",
"builder # Implemented by beazley. Note: This is not a proper SAX handler",
"self.machine_states[pi_state][0] for handler in handlers: handler.processingInstruction(node) # For Dave class RulePatternHandler(RuleMachineHandler): def __init__(self,",
"[(None, self.start_edges)] + sorted(self.edges.items()): if node_id is None: node_name = \"(start)\" labels =",
"elif node_test.__class__ is nodetests.qualified_name_test: prefix, localname = node_test.name_key namespace = namespaces[prefix] node_id =",
"expr.__class__ is locationpaths.location_step: # This is a step along some axis, such as:",
"nfa.terminal_nodes.add(node_id) #if axis_name == \"descendant\": # _add_initial_loop(nfa) #print \"QWERQWER\" #nfa.dump() return nfa if",
"self._add_to_leaves(tree.if_true, to_node_id) elif new_true_test: if isinstance(tree.if_true, set): new_branch = Branch(new_true_test, tree.if_true | set([to_node_id]),",
"way to match *any* PI? # Looks like Amara support XPath 1.0, where",
"= [] tree = table.attr_tree.if_true while not isinstance(tree, set): namespace, localname = tree.test.name",
"getattr(child_test, \"predicates\", None) is None if parent_test is None: if isinstance(child_test, AnyNodeTest): return",
"child_test return True, False # Used to make a decision tree. Either the",
"path specifiers like # \"a\" \"a/b\", \"a/b/c[0]/d[@x]\" (relative location path) # \"@a\", \"a/@b\",",
"print type(expr) print dir(expr) for k, v in inspect.getmembers(expr): if k.startswith(\"__\") and k.endswith(\"__\"):",
"attr_ops = tuple(attr_ops) # processing instruction tree pi_ops = [] tree = table.pi_tree.if_true",
"(ProcessingInstructionTest.match_type, self.pi_tree), (CommentTest.match_type, self.comment_tree) ): visit = [tree] while visit: node = visit.pop()",
"= {} # node_id -> match_type self.labeled_handlers = {} # node_id -> (label,",
"# Something without a namespace, like \"a\" node_id = nfa.new_node(None, klass(node_test.name_key, expr.predicates)) elif",
"node result = {} # [] seen = set([dfa_start]) todo = [(dfa_start, None)]",
"in (id, class) pairs) table = dfa[node_ids] if dfa_id == 0: handlers =",
"name self.predicates = predicates def __str__(self): return \"Node ns=%r localname=%r predicates=%r\" % (self.name[0],",
"# Raymond's code def nfa_to_dfa(nfa): numbering = {} # from frozenset -> 0,",
"name i = 0 while 1: ns, ln, test_function, if_true, if_false = element_ops[i]",
"states else: node_ops = [(None, None, None, -numbering[frozenset(tree)])] else: node_ops = [tree] todo",
"self.predicates) # predicates make no sense here because we only support downward axes",
"= NFA() nfa.start_edges[:] = self.start_edges nfa.edges.update(self.edges) nfa.terminal_nodes.update(self.terminal_nodes) nfa.match_types.update(self.match_types) nfa.labeled_handlers.update(self.labeled_handlers) return nfa def get_edges(self,",
"op self.value = value class AttributeFunctionCallPred(object): def __init__(self, func): self.func = func #####",
"handler events result[current_dfa] = StateTable(match_type, nfa, current_dfa) numbering[current_dfa] = len(numbering) continue # This",
"if isinstance(child_test, NodeTest): # XXX This is wrong. Resolved namespaces can be the",
"else: self._add_to_leaves(tree.if_true, to_node_id) self._add_to_leaves(tree.if_false, to_node_id) def get_final_nodes(self): result = {} for match_type, tree",
"= [(None, None, None, -numbering[frozenset(tree)])] else: node_ops = [tree] todo = [0] while",
"node): pass def endElementMatch(self, node): pass def attributeMatch(self, node): pass def commentMatch(self, node):",
"print \" ATTR OPS\" for attr_op in attr_ops: print attr_op print \" PI",
"\" % (prefix,) self.prefix = prefix def startSubtree(self, element): print self.prefix+\"startSubtree\", element def",
"def get_final_nodes(self): result = {} for match_type, tree in ( (BaseNodeTest.match_type, self.node_tree), (AttributeTest.match_type,",
"True, False # Used to make a decision tree. Either the test passes",
"such as: # \"a\" - step along the child axis # \"a[@x][@y='1']\" -",
"= self.machine_states[pi_state][0] for handler in handlers: handler.processingInstruction(node) # For Dave class RulePatternHandler(RuleMachineHandler): def",
"of tags)) performance # instead of O(n). However, for now, n is no",
"the namespace fields are different. # XXX check for predicates! if parent_test.name ==",
"i, x in enumerate(machine_states): print \"== INFO FOR\", i, \"==\" handlers, node_ops, attr_ops,",
"to_node_id, intersect) if new_false_test == True: self._add_to_leaves(tree.if_false, to_node_id) elif new_false_test: if isinstance(tree.if_false, set):",
"def processingInstruction(self, node, target, data): state = self.stack[-1] if state == -1: return",
"self.expressions]) def build_pushtree_handler(self): return RuleMachineHandler(self._build_machine_states()) # Special handler object to bridge with pushbind",
"def die(expr): import inspect print \" == FAILURE ==\" print type(expr) print dir(expr)",
"if if_false > 0: todo.append(if_false) if if_true > 0: todo.append(if_true) node_ops = tuple(node_ops)",
"no more than 10 or so. class Branch(object): def __init__(self, test, if_true, if_false):",
"endElementMatch(self, node): print self.prefix+\"endElementMatch\", node def attributeMatch(self, node): print self.prefix+\"attributeMatch\", node def commentMatch(self,",
"= step.axis axis_name = axis.name assert axis_name in (\"child\", \"descendant\"), axis_name subnfa =",
"x:sorted(x[0])): # print \"State\", sorted(k) # table.dump() return result, numbering def die(expr): import",
"attr_ops, pi_ops, comment_state = x print \" HANDLERS\", handlers print \" NODE OPS\"",
"tree.if_false: if_false = -numbering[frozenset(tree.if_false)] else: if_false = 0 else: if_false = len(node_ops) node_ops.append(tree.if_false)",
"predicates make no sense here because we only support downward axes # and",
"'__main__': testxml = \"\"\"\\ <body> <li>Ignore me<b/></li> <ul> <li x='1'>This <i>is</i> test</li> <li",
"(to_node_id, test) in edges: print \"\", test, \"->\", to_node_id def _add_initial_loop(nfa): start_edges =",
"#if axis_name == \"descendant\": # _add_initial_loop(nfa) #print \"QWERQWER\" #nfa.dump() return nfa if expr.__class__",
"self.machine_states[last_state][0] for handler in reversed(handlers): handler.endElementMatch(node) def processingInstruction(self, node, target, data): state =",
"another nodesets! from amara.xpath.expressions import basics counter = itertools.count(1) # [@x] class AttributeExistsPred(object):",
"support XPath 1.0, where this is a string if parent_test.target == child_test.target: return",
"here? if list(self.nfa_node_ids) != [None]: for nfa_node in self.nfa_node_ids: labels = [x[0] for",
"None: visit.append(node.if_true) visit.append(node.if_false) return result.items() def dump(self, numbering): # Do I report anything",
"__name__ == '__main__': testxml = \"\"\"\\ <body> <li>Ignore me<b/></li> <ul> <li x='1'>This <i>is</i>",
"the # actual instances I need except the startElement and # endElement use",
"name, qname last_state = self.stack.pop() if last_state == -1: return handlers = self.machine_states[last_state][0]",
"Namespace but no name, like \"a:*\" namespace = namespaces[node_test._prefix] node_id = nfa.new_node(None, klass((namespace,",
"as xpath_parser from amara.xpath import locationpaths from amara.xpath.locationpaths import axisspecifiers from amara.xpath.locationpaths import",
"__init__(self, name, predicates): # (ns, name) self.name = name self.predicates = predicates def",
"node_test.__class__ is nodetests.namespace_test: # Namespace but no name, like \"a:*\" namespace = namespaces[node_test._prefix]",
"= machine_states def startDocument(self,node): self.stack = [0] #dump_machine_states(self.machine_states) def startElementNS(self, node, name, qname,",
"self.target = target def __str__(self): return \"processing-instruction(%r)\" % (self.target,) class CommentTest(object): match_type =",
"__init__(self, machine_states): self.machine_states = machine_states def startDocument(self,node): self.stack = [0] #dump_machine_states(self.machine_states) def startElementNS(self,",
"is None or localname == ln)): # Match! handlers = self.machine_states[attr_state_id][0] for handler",
"def startSubtree(self, element): print self.prefix+\"startSubtree\", element def endSubtree(self, element): print self.prefix+\"endSubtree\", element def",
"if tree.if_false: if_false = -numbering[frozenset(tree.if_false)] else: if_false = 0 else: if_false = len(node_ops)",
"self.stack.append(-1) return if i < 0: next_state = -i break # otherwise, loop",
"#print \"Access\", i, len(node_ops) tree = node_ops[i] if isinstance(tree.if_true, set): if tree.if_true: if_true",
"(ns, ln, attr_state_id) in attr_ops: #print \"attr test:\", (ns, ln), (namespace, localname) if",
"reached here? if list(self.nfa_node_ids) != [None]: for nfa_node in self.nfa_node_ids: labels = [x[0]",
"the child axis # \"a[@x][@y='1']\" - step along the child axis, with two",
"# from frozenset -> 0, 1, 2, ... dfa_start = frozenset([None]) # nfa",
"!= [None]: for nfa_node in self.nfa_node_ids: labels = [x[0] for x in self.nfa.labeled_handlers[nfa_node]]",
"= 0 while 1: ns, ln, test_function, if_true, if_false = element_ops[i] assert test_function",
"PushtreeHandler(object): def startSubtree(self, element): pass def endSubtree(self, element): pass def startElementMatch(self, node): pass",
"test.match_type self.labeled_handlers[to_node_id] = [] edges.append( (to_node_id, test) ) return to_node_id def connect(self, from_node_id,",
"AttributeTest(object): match_type = \"attr\" def __init__(self, name, predicates): self.name = name assert not",
"# \"/a\", \"/a[0]/b[@x]\" nfa = NFA() for step in expr._steps: axis = step.axis",
"parent_test is not None: assert isinstance(parent_test, AttributeTest), parent_test assert isinstance(child_test, AttributeTest), child_test if",
"self.start_edges: self.start_edges[:] = other.start_edges self.edges.update(other.edges) self.match_types.update(other.match_types) for node_id in self.terminal_nodes: self.edges[node_id].extend(other.start_edges) self.terminal_nodes.clear() self.terminal_nodes.update(other.terminal_nodes)",
"- step along the attribute axis axis = expr.axis axis_name = axis.name assert",
"of O(n). However, for now, n is no more than 10 or so.",
"is no more than 10 or so. class Branch(object): def __init__(self, test, if_true,",
"= \"\" else: prefix = \"(%s) \" % (prefix,) self.prefix = prefix def",
"& set(other.edges), \"non-empty intersection\" self.start_edges.extend(other.start_edges) self.edges.update(other.edges) self.match_types.update(other.match_types) self.terminal_nodes.update(other.terminal_nodes) self.labeled_handlers.update(other.labeled_handlers) def dump(self): for node_id,",
"= nfa.new_node(None, klass((None, None), None)) else: die(node_test) nfa.terminal_nodes.add(node_id) #if axis_name == \"descendant\": #",
"return True, False if isinstance(child_test, NodeTest): return child_test, False elif isinstance(parent_test, NodeTest): if",
"def connect(self, from_node_id, to_node_id, test): self.get_edges(from_node_id).append( (to_node_id, test) ) def extend(self, other): assert",
"# 'None' for the start node self.nfa = nfa self.nfa_node_ids = nfa_node_ids self.node_tree",
"\"processing-instruction(%r)\" % (self.target,) class CommentTest(object): match_type = \"comment\" class NFA(object): def __init__(self): self.start_edges",
"self.get_edges(from_node_id) to_node_id = next(counter) self.edges[to_node_id] = [] self.match_types[to_node_id] = test.match_type self.labeled_handlers[to_node_id] = []",
"node): pass def attributeMatch(self, node): pass def commentMatch(self, node): pass def processingInstructionMatch(self, node):",
"None, None, -numbering[frozenset(tree)])] else: node_ops = [tree] todo = [0] while todo: i",
"None or ln == localname)): i = if_true else: i = if_false if",
"middle. Should give O(log(number of tags)) performance # instead of O(n). However, for",
"attr_ops.append( (None, None, numbering[frozenset(tree)]) ) attr_ops = tuple(attr_ops) # processing instruction tree pi_ops",
"namespace = namespaces[prefix] node_id = nfa.new_node(None, klass((namespace, localname), expr.predicates)) elif node_test.__class__ is nodetests.processing_instruction_test:",
"1, 2, ... dfa_start = frozenset([None]) # nfa start node result = {}",
"any attributes attr_ops = self.machine_states[next_state][2] if not attr_ops: return for namespace, localname in",
"ln, attr_state_id) in attr_ops: #print \"attr test:\", (ns, ln), (namespace, localname) if ((ns",
"itertools.count(1) # [@x] class AttributeExistsPred(object): def __init__(self, name): self.name = name # [@x=\"a\"]",
"no downward axes. (XXX I think.) class AttributeTest(object): match_type = \"attr\" def __init__(self,",
"nfa = NFA() for step in expr._steps: axis = step.axis axis_name = axis.name",
") result[current_dfa] = state_table numbering[current_dfa] = len(numbering) # for k, table in sorted(result.items(),",
"new_false_test: if isinstance(tree.if_false, set): new_branch = Branch(new_false_test, tree.if_false | set([to_node_id]), tree.if_false) tree.if_false =",
"def __init__(self, func): self.func = func ##### # This would yield nodes, attribute,",
"== \"attribute\": klass = AttributeTest else: klass = NodeTest nfa = NFA() node_test",
"manager.add(\"pre/post\", VerbosePushtreeHandler(\"pre/post\")) manager.expressions[1]._nfa.dump() manager.add(\"//a\", VerbosePushtreeHandler(\"//a\")) manager.expressions[2]._nfa.dump() manager.add(\"@x\", VerbosePushtreeHandler(\"@x\")) manager.expressions[3]._nfa.dump() manager.add(\"a\", VerbosePushtreeHandler(\"a\")) manager.expressions[4]._nfa.dump() #manager.add(\".//*\")",
"self.pi_tree), (CommentTest.match_type, self.comment_tree) ): visit = [tree] while visit: node = visit.pop() if",
"continue # This adds element, attribute, comment, etc. transitions state_table = StateTable(match_type, nfa,",
"StateTable(match_type, nfa, current_dfa) for to_node_id, test in transitions: state_table.add(test, to_node_id) for nfa_nodes, match_type",
"0 else: if_false = len(node_ops) node_ops.append(tree.if_false) namespace, localname = tree.test.name node_ops[i] = (namespace,",
"in expr._steps: nfa.extend(to_nfa(step, namespaces)) _add_initial_loop(nfa) return nfa if expr.__class__ is locationpaths.location_step: # This",
"node_ops, attr_ops, pi_ops, comment_state) ) return tuple(states) class Expression(object): def __init__(self, id, xpath,",
"handlers: handler.startElementMatch(node) # Also handle any attributes attr_ops = self.machine_states[next_state][2] if not attr_ops:",
"if tree.if_true: if_true = -numbering[frozenset(tree.if_true)] else: if_true = 0 else: if_true = len(node_ops)",
"nfa.new_node(None, ProcessingInstructionTest(node_test._target)) elif node_test.__class__ is locationpaths.nodetests.principal_type_test: node_id = nfa.new_node(None, klass((None, None), None)) else:",
"if namespaces is None: namespaces = {} self.namespaces = namespaces self.expressions = []",
"else: self._add(tree.if_true, new_true_test, to_node_id, intersect) if new_false_test == True: self._add_to_leaves(tree.if_false, to_node_id) elif new_false_test:",
"was nothing</li> </ul> </body> \"\"\" manager = PushtreeManager(\"body/ul/li\", VerbosePushtreeHandler(\"main\")) manager.expressions[0]._nfa.dump() manager.add(\"pre/post\", VerbosePushtreeHandler(\"pre/post\")) manager.expressions[1]._nfa.dump()",
"class Branch(object): def __init__(self, test, if_true, if_false): self.test = test self.if_true = if_true",
"state_table numbering[current_dfa] = len(numbering) # for k, table in sorted(result.items(), key=lambda x:sorted(x[0])): #",
"\" NODE OPS\" for node_op in node_ops: print node_op print \" ATTR OPS\"",
"nfa = NFA() for step in expr._steps: nfa.extend(to_nfa(step, namespaces)) _add_initial_loop(nfa) return nfa if",
"= \"node\" # What about *[@spam] ? class AnyNodeTest(BaseNodeTest): def __str__(self): return \"AnyNode",
"if parent_test is not None: assert isinstance(parent_test, AttributeTest), parent_test assert isinstance(child_test, AttributeTest), child_test",
"self._dump(tree.if_true, depth+1, numbering) self._dump(tree.if_false, depth+1, numbering) def all_transitions(nfa, current_dfa): transitions = [] for",
"if isinstance(tree, set): tree.add(to_node_id) else: self._add_to_leaves(tree.if_true, to_node_id) self._add_to_leaves(tree.if_false, to_node_id) def get_final_nodes(self): result =",
"nodetests.namespace_test: # Namespace but no name, like \"a:*\" namespace = namespaces[node_test._prefix] node_id =",
"to have no attributes self.stack.append(-1) return if i < 0: next_state = -i",
"for handler in reversed(handlers): handler.endElementMatch(node) def processingInstruction(self, node, target, data): state = self.stack[-1]",
"Branch(object): def __init__(self, test, if_true, if_false): self.test = test self.if_true = if_true self.if_false",
"this is a string if parent_test.target == child_test.target: return True, False return False,",
"attribute, PIs, and comments #class AnyTest(object): # pass class BaseNodeTest(object): match_type = \"node\"",
"nfa if expr.__class__ is locationpaths.location_step: # This is a step along some axis,",
"exp = Expression(i, xpath, nfa) self.expressions.append(exp) return exp def add(self, xpath, xpath_handler=None): return",
"= node_ops[i] if isinstance(tree.if_true, set): if tree.if_true: if_true = -numbering[frozenset(tree.if_true)] else: if_true =",
"(\"NODE\", self.node_tree), (\"ATTR\", self.attr_tree), (\"PROCESSING-INSTRUCTION\", self.pi_tree), (\"COMMENT\", self.comment_tree) ): if tree is None:",
"= element_ops[i] assert test_function is None if ((ns is None or ns ==",
"# dead-end; no longer part of the DFA and the # 0 node",
"test, \"->\", to_node_id def _add_initial_loop(nfa): start_edges = nfa.start_edges[:] any_node = nfa.new_node(None, AnyNodeTest()) for",
"AnyNodeTest): return True, True if isinstance(child_test, NodeTest): # XXX This is wrong. Resolved",
"to_node_id) self._add_to_leaves(tree.if_false, to_node_id) def get_final_nodes(self): result = {} for match_type, tree in (",
"AnyNodeTest): return True, False if isinstance(child_test, NodeTest): return child_test, False if isinstance(parent_test, AnyNodeTest):",
"in self.nfa_node_ids: labels = [x[0] for x in self.nfa.labeled_handlers[nfa_node]] if labels: print \"Report\",",
"in ( (BaseNodeTest.match_type, self.node_tree), (AttributeTest.match_type, self.attr_tree), (ProcessingInstructionTest.match_type, self.pi_tree), (CommentTest.match_type, self.comment_tree) ): visit =",
"self._dump(tree.if_true, 0, numbering) def _dump(self, tree, depth, numbering): s = \"-\"*depth if isinstance(tree,",
"set()) def add(self, test, to_node_id): if isinstance(test, BaseNodeTest): self._add(self.node_tree, test, to_node_id, node_intersect) elif",
"handlers, node_ops, attr_ops, pi_ops, comment_state = x print \" HANDLERS\", handlers print \"",
"an abbreviated_absolute_location_path # \"//a\", \"a//b\" nfa = NFA() for step in expr._steps: nfa.extend(to_nfa(step,",
"\"a/b/c[0]/d[@x]\" (relative location path) # \"@a\", \"a/@b\", and even \"@a/@b\", which gives nothing",
"to_nfa(expr, namespaces): #print \"Eval\", expr.__class__ if (expr.__class__ is locationpaths.relative_location_path): # This is a",
"something more sophisticated? For example, if there are a # large number of",
"and union everything? for nfa in nfas[1:]: union_nfa.union(nfa) dfa, numbering = nfa_to_dfa(union_nfa) return",
"\"startElementNS\", name, qname, attrs, \"state\", state if state == -1: #print \"goto -1\"",
"# This is an absolute path like # \"/a\", \"/a[0]/b[@x]\" nfa = NFA()",
"self.prefix+\"endSubtree\", element def startElementMatch(self, node): print self.prefix+\"startElementMatch\", node def endElementMatch(self, node): print self.prefix+\"endElementMatch\",",
"it fails. # TODO: something more sophisticated? For example, if there are a",
"= -numbering[frozenset(tree.if_false)] else: if_false = 0 else: if_false = len(node_ops) node_ops.append(tree.if_false) namespace, localname",
"else: raise AssertionError(test) def _add(self, tree, test, to_node_id, intersect): new_true_test, new_false_test = intersect(tree.test,",
"todo.pop() #print \"All transitions from\", current_dfa transitions = all_transitions(nfa, current_dfa) if not transitions:",
"would yield nodes, attribute, PIs, and comments #class AnyTest(object): # pass class BaseNodeTest(object):",
"# This was a valid target, but there's nothing leading off from it",
"self.terminal_nodes.update(other.terminal_nodes) self.labeled_handlers.update(other.labeled_handlers) def dump(self): for node_id, edges in [(None, self.start_edges)] + sorted(self.edges.items()): if",
"tree: # Match any attribute attr_ops.append( (None, None, numbering[frozenset(tree)]) ) attr_ops = tuple(attr_ops)",
") ) def endElementNS(self, node, name, qname): #print \"endElementNS\", node, name, qname last_state",
"match_type = \"comment\" class NFA(object): def __init__(self): self.start_edges = [] self.edges = {}",
"in self.terminal_nodes: self.labeled_handlers[node_id].append(labeled_handler) def new_node(self, from_node_id, test): edges = self.get_edges(from_node_id) to_node_id = next(counter)",
"node): print self.prefix+\"endElementMatch\", node def attributeMatch(self, node): print self.prefix+\"attributeMatch\", node def commentMatch(self, node):",
"node def attributeMatch(self, node): print self.prefix+\"attributeMatch\", node def commentMatch(self, node): print self.prefix+\"commentMatch\", node",
"to_nfa(expr._paths[0], namespaces) for path in expr._paths[1:]: nfa.union(to_nfa(path, namespaces)) return nfa die(expr) def node_intersect(parent_test,",
"test, to_node_id, intersect): new_true_test, new_false_test = intersect(tree.test, test) if new_true_test == True: self._add_to_leaves(tree.if_true,",
"attr_op print \" PI OPS\" for pi_op in pi_ops: print pi_op print \"",
"ProcessingInstructionTest), parent_test assert isinstance(child_test, ProcessingInstructionTest), child_test if parent_test is None: return child_test, False",
"because there are no states else: node_ops = [(None, None, None, -numbering[frozenset(tree)])] else:",
"def dump_machine_states(machine_states): for i, x in enumerate(machine_states): print \"== INFO FOR\", i, \"==\"",
"attr_intersect) elif isinstance(test, ProcessingInstructionTest): self._add(self.pi_tree, test, to_node_id, pi_intersect) elif isinstance(test, CommentTest): self._add(self.comment_tree, test,",
"dfa[node_ids] if dfa_id == 0: handlers = () else: handler_map = {} for",
"# another nodesets! from amara.xpath.expressions import basics counter = itertools.count(1) # [@x] class",
"-> [(to_node_id, test), ...] self.terminal_nodes = set() # The start node has no",
"specifiers like # \"a\" \"a/b\", \"a/b/c[0]/d[@x]\" (relative location path) # \"@a\", \"a/@b\", and",
"match_type elif node is not None: visit.append(node.if_true) visit.append(node.if_false) return result.items() def dump(self, numbering):",
"qname, attrs): state = self.stack[-1] #print \"startElementNS\", name, qname, attrs, \"state\", state if",
"attrs): state = self.stack[-1] #print \"startElementNS\", name, qname, attrs, \"state\", state if state",
"False # Is there any way to match *any* PI? # Looks like",
"handlers = self.machine_states[pi_state][0] for handler in handlers: handler.processingInstruction(node) # For Dave class RulePatternHandler(RuleMachineHandler):",
"extend(self, other): assert not set(self.edges) & set(other.edges), \"non-empty intersection\" if not self.start_edges: self.start_edges[:]",
"in the builder # Implemented by beazley. Note: This is not a proper",
"def commentMatch(self, node): print self.prefix+\"commentMatch\", node def processingInstructionMatch(self, node): print self.prefix+\"processingInstructionMatch\", node if",
"and k.endswith(\"__\"): continue print repr(k), repr(v) raise AssertionError(expr) def build_states(nfa, dfa, numbering): #",
"(namespace, localname, None, if_true, if_false) #print \"Added\", node_ops[i] if if_false > 0: todo.append(if_false)",
"nfas[0].copy() # XXX start with empty and union everything? for nfa in nfas[1:]:",
"\"Access\", i, len(node_ops) tree = node_ops[i] if isinstance(tree.if_true, set): if tree.if_true: if_true =",
"dir(expr) for k, v in inspect.getmembers(expr): if k.startswith(\"__\") and k.endswith(\"__\"): continue print repr(k),",
"= [] for (label, handler) in sorted(handler_map.items()): handlers.append(handler) # node tree tree =",
"and even \"@a/@b\", which gives nothing nfa = NFA() for step in expr._steps:",
"type(expr) print dir(expr) for k, v in inspect.getmembers(expr): if k.startswith(\"__\") and k.endswith(\"__\"): continue",
"in [(None, self.start_edges)] + sorted(self.edges.items()): if node_id is None: node_name = \"(start)\" labels",
"== target: handlers = self.machine_states[pi_state][0] for handler in handlers: handler.processingInstruction(node) # For Dave",
"set()) self.pi_tree = Branch(None, set(), set()) self.comment_tree = Branch(None, set(), set()) def add(self,",
"= {} for match_type, tree in ( (BaseNodeTest.match_type, self.node_tree), (AttributeTest.match_type, self.attr_tree), (ProcessingInstructionTest.match_type, self.pi_tree),",
"namespace = namespaces[node_test._prefix] node_id = nfa.new_node(None, klass((namespace, None), expr.predicates)) elif node_test.__class__ is nodetests.qualified_name_test:",
"and these have no downward axes. (XXX I think.) class AttributeTest(object): match_type =",
"# Looks like Amara support XPath 1.0, where this is a string if",
"PushtreeManager(object): def __init__(self, subtree_xpath, subtree_handler = None, namespaces = None): if namespaces is",
"step along the attribute axis axis = expr.axis axis_name = axis.name assert axis_name",
"pass def endElementMatch(self, node): pass def attributeMatch(self, node): pass def commentMatch(self, node): pass",
"namespaces = None): if namespaces is None: namespaces = {} self.namespaces = namespaces",
"nfa die(expr) def node_intersect(parent_test, child_test): if parent_test is not None: assert isinstance(parent_test, BaseNodeTest),",
"else: comment_state = 0 states.append( (handlers, node_ops, attr_ops, pi_ops, comment_state) ) return tuple(states)",
"class NodeTest(BaseNodeTest): def __init__(self, name, predicates): # (ns, name) self.name = name self.predicates",
"< 0: next_state = -i break # otherwise, loop #print \"GoTo\", next_state self.stack.append(next_state)",
"other): assert not set(self.edges) & set(other.edges), \"non-empty intersection\" self.start_edges.extend(other.start_edges) self.edges.update(other.edges) self.match_types.update(other.match_types) self.terminal_nodes.update(other.terminal_nodes) self.labeled_handlers.update(other.labeled_handlers)",
"= dfa[node_ids] if dfa_id == 0: handlers = () else: handler_map = {}",
"child_test if parent_test is None: return child_test, False if parent_test.name == child_test.name: return",
"+= \" \" + str([x[0] for x in self.labeled_handlers[node_id]]) is_terminal = \"(terminal)\" if",
"== 0: # dead-end; no longer part of the DFA and the #",
"node_name = str(node_id) action = str(self.match_types[node_id]) labels += \" \" + str([x[0] for",
"isinstance(child_test, AnyNodeTest): return True, False if isinstance(child_test, NodeTest): return child_test, False if isinstance(parent_test,",
"set(), set()) self.attr_tree = Branch(None, set(), set()) self.pi_tree = Branch(None, set(), set()) self.comment_tree",
"test) in edge in nfa_state.edges: if edge[0] == event: yield edge[1] # Raymond's",
"OPS\" for node_op in node_ops: print node_op print \" ATTR OPS\" for attr_op",
"__init__(self, name, predicates): self.name = name assert not predicates self.predicates = predicates def",
"(namespace, localname) ) ) def endElementNS(self, node, name, qname): #print \"endElementNS\", node, name,",
"self.stack[-1] #print \"startElementNS\", name, qname, attrs, \"state\", state if state == -1: #print",
"(to_node_id, test) ) return to_node_id def connect(self, from_node_id, to_node_id, test): self.get_edges(from_node_id).append( (to_node_id, test)",
"node_ops: print node_op print \" ATTR OPS\" for attr_op in attr_ops: print attr_op",
"NFA() for step in expr._steps: nfa.extend(to_nfa(step, namespaces)) _add_initial_loop(nfa) return nfa if expr.__class__ is",
"if node_id is None: node_name = \"(start)\" labels = \"\" else: node_name =",
"(CommentTest.match_type, self.comment_tree) ): visit = [tree] while visit: node = visit.pop() if isinstance(node,",
"{} # [] seen = set([dfa_start]) todo = [(dfa_start, None)] while todo: current_dfa,",
"to_nfa(xpath_parser.parse(xpath), self.namespaces) i = len(self.expressions) nfa.add_handler((i, xpath_handler)) exp = Expression(i, xpath, nfa) self.expressions.append(exp)",
"False # Used to make a decision tree. Either the test passes or",
"xpath_parser from amara.xpath import locationpaths from amara.xpath.locationpaths import axisspecifiers from amara.xpath.locationpaths import nodetests",
"= \"-\"*depth if isinstance(tree, set): if tree: k = sorted(tree) print s, \"<>\",",
"# nfa start node result = {} # [] seen = set([dfa_start]) todo",
"startElementMatch(self, node): pass def endElementMatch(self, node): pass def attributeMatch(self, node): pass def commentMatch(self,",
"Dave class RulePatternHandler(RuleMachineHandler): def __init__(self, pattern, end_node_handler, attr_handler, namespaces=None): self.xpm = xpm =",
"\"@a\" - step along the attribute axis axis = expr.axis axis_name = axis.name",
"= self.machine_states[next_state][2] if not attr_ops: return for namespace, localname in attrs.keys(): for (ns,",
"= tree.if_false if tree: pi_ops.append( (None, numbering[frozenset(tree)]) ) pi_ops = tuple(pi_ops) # comment",
"ExpressionManager(namespaces=namespaces); xpm.add(pattern) nfa, dfa, numbering = xpm.build_dfa_tables() machine_states = build_instructions(nfa,dfa,numbering) RuleMachineHandler.__init__(self, machine_states, end_node_handler",
"other): assert not set(self.edges) & set(other.edges), \"non-empty intersection\" if not self.start_edges: self.start_edges[:] =",
"die(expr) def node_intersect(parent_test, child_test): if parent_test is not None: assert isinstance(parent_test, BaseNodeTest), parent_test",
"edge in nfa_state.edges: if edge[0] == event: yield edge[1] # Raymond's code def",
"ln)): # Match! handlers = self.machine_states[attr_state_id][0] for handler in handlers: #print \"Notify attribute",
"0: assert node_ids == set([None]) # handlers (which are in (id, class) pairs)",
"#class AnyTest(object): # pass class BaseNodeTest(object): match_type = \"node\" # What about *[@spam]",
"#print \"Eval\", expr.__class__ if (expr.__class__ is locationpaths.relative_location_path): # This is a set of",
"and start # in the middle. Should give O(log(number of tags)) performance #",
"assert isinstance(parent_test, AttributeTest), parent_test assert isinstance(child_test, AttributeTest), child_test if parent_test is None: return",
"= Branch(None, set(), set()) def add(self, test, to_node_id): if isinstance(test, BaseNodeTest): self._add(self.node_tree, test,",
"isinstance(test, AttributeTest): self._add(self.attr_tree, test, to_node_id, attr_intersect) elif isinstance(test, ProcessingInstructionTest): self._add(self.pi_tree, test, to_node_id, pi_intersect)",
"for (to_node_id, test) in edge in nfa_state.edges: if edge[0] == event: yield edge[1]",
"leading off from it #print \"GOTO -1\" self.stack.append(-1) return namespace, localname = name",
"while 1: ns, ln, test_function, if_true, if_false = element_ops[i] assert test_function is None",
"None: assert isinstance(parent_test, BaseNodeTest), parent_test assert getattr(parent_test, \"predicates\", None) is None assert isinstance(child_test,",
"# unique node numbers states = [] for dfa_id, node_ids in sorted( (dfa_id,",
"= NFA() node_test = expr.node_test if node_test.__class__ is nodetests.local_name_test: # Something without a",
"-> (label, PushtreeHandler) def copy(self): nfa = NFA() nfa.start_edges[:] = self.start_edges nfa.edges.update(self.edges) nfa.terminal_nodes.update(self.terminal_nodes)",
"(AttributeTest.match_type, self.attr_tree), (ProcessingInstructionTest.match_type, self.pi_tree), (CommentTest.match_type, self.comment_tree) ): visit = [tree] while visit: node",
"= xpm.build_dfa_tables() machine_states = build_instructions(nfa,dfa,numbering) RuleMachineHandler.__init__(self, machine_states, end_node_handler = end_node_handler, attr_handler = attr_handler)",
"\"attr\" def __init__(self, name, predicates): self.name = name assert not predicates self.predicates =",
"there any way to match *any* PI? # Looks like Amara support XPath",
"todo.append( (some_dfa, match_type) ) result[current_dfa] = state_table numbering[current_dfa] = len(numbering) # for k,",
"machine_states = manager._build_machine_states() dump_machine_states(machine_states) hand = RuleMachineHandler(machine_states) import os doc = amara.parse(testxml,rule_handler=hand) os._exit(0)",
"\"comment\" class NFA(object): def __init__(self): self.start_edges = [] self.edges = {} # from_node_id",
"node_name = \"(start)\" labels = \"\" else: node_name = str(node_id) action = str(self.match_types[node_id])",
"_add_initial_loop(nfa) #print \"QWERQWER\" #nfa.dump() return nfa if expr.__class__ is amara.xpath.expressions.nodesets.union_expr: # \"a|b\" nfa",
"# \"a|b\" nfa = to_nfa(expr._paths[0], namespaces) for path in expr._paths[1:]: nfa.union(to_nfa(path, namespaces)) return",
"== -1: return handlers = self.machine_states[last_state][0] for handler in reversed(handlers): handler.endElementMatch(node) def processingInstruction(self,",
"numbering[frozenset(tree)]) ) attr_ops = tuple(attr_ops) # processing instruction tree pi_ops = [] tree",
"instances I need except the startElement and # endElement use different method. handlers",
"if expr.__class__ is locationpaths.location_step: # This is a step along some axis, such",
"amara.xpath.expressions.nodesets # another nodesets! from amara.xpath.expressions import basics counter = itertools.count(1) # [@x]",
"name, predicates): self.name = name assert not predicates self.predicates = predicates def __str__(self):",
"with pushbind support in the builder # Implemented by beazley. Note: This is",
"NodeTest nfa = NFA() node_test = expr.node_test if node_test.__class__ is nodetests.local_name_test: # Something",
"nfa_node in self.nfa_node_ids: labels = [x[0] for x in self.nfa.labeled_handlers[nfa_node]] if labels: print",
"from amara.xpath.expressions import basics counter = itertools.count(1) # [@x] class AttributeExistsPred(object): def __init__(self,",
"#print \"attr test:\", (ns, ln), (namespace, localname) if ((ns is None or namespace",
"= NFA() for step in expr._steps: nfa.extend(to_nfa(step, namespaces)) _add_initial_loop(nfa) return nfa if (expr.__class__",
"nfa.start_edges[:] = self.start_edges nfa.edges.update(self.edges) nfa.terminal_nodes.update(self.terminal_nodes) nfa.match_types.update(self.match_types) nfa.labeled_handlers.update(self.labeled_handlers) return nfa def get_edges(self, node_id): if",
"name, qname, attrs, \"state\", state if state == -1: #print \"goto -1\" self.stack.append(-1)",
"self.start_edges = [] self.edges = {} # from_node_id -> [(to_node_id, test), ...] self.terminal_nodes",
"len(node_ops) node_ops.append(tree.if_false) namespace, localname = tree.test.name node_ops[i] = (namespace, localname, None, if_true, if_false)",
"if isinstance(tree, set): # Special case when there are no decisions to make",
"class AttributeExistsPred(object): def __init__(self, name): self.name = name # [@x=\"a\"] class AttributeBinOpPred(object): def",
"== True: self._add_to_leaves(tree.if_false, to_node_id) elif new_false_test: if isinstance(tree.if_false, set): new_branch = Branch(new_false_test, tree.if_false",
"axis, such as: # \"a\" - step along the child axis # \"a[@x][@y='1']\"",
"import basics counter = itertools.count(1) # [@x] class AttributeExistsPred(object): def __init__(self, name): self.name",
"nfa_state.edges: if edge[0] == event: yield edge[1] # Raymond's code def nfa_to_dfa(nfa): numbering",
"is not None: assert isinstance(parent_test, BaseNodeTest), parent_test assert getattr(parent_test, \"predicates\", None) is None",
"dump(self): for node_id, edges in [(None, self.start_edges)] + sorted(self.edges.items()): if node_id is None:",
"if node_id is None: new_transitions = nfa.start_edges else: # XXX I can't transition",
"= test.match_type self.labeled_handlers[to_node_id] = [] edges.append( (to_node_id, test) ) return to_node_id def connect(self,",
"\"a|b\" nfa = to_nfa(expr._paths[0], namespaces) for path in expr._paths[1:]: nfa.union(to_nfa(path, namespaces)) return nfa",
"elif node is not None: visit.append(node.if_true) visit.append(node.if_false) return result.items() def dump(self, numbering): #",
"False elif isinstance(parent_test, NodeTest): if isinstance(child_test, AnyNodeTest): return True, True if isinstance(child_test, NodeTest):",
"check for predicates! if parent_test.name == child_test.name: return True, False return False, child_test",
"handlers = [] for (label, handler) in sorted(handler_map.items()): handlers.append(handler) # node tree tree",
"isinstance(parent_test, BaseNodeTest), parent_test assert getattr(parent_test, \"predicates\", None) is None assert isinstance(child_test, BaseNodeTest), child_test",
"expr.axis axis_name = axis.name assert axis_name in (\"child\", \"descendant\", \"attribute\"), axis_name if axis_name",
"set): if node: result[frozenset(node)] = match_type elif node is not None: visit.append(node.if_true) visit.append(node.if_false)",
"result[current_dfa] = state_table numbering[current_dfa] = len(numbering) # for k, table in sorted(result.items(), key=lambda",
"tree, test, to_node_id, intersect): new_true_test, new_false_test = intersect(tree.test, test) if new_true_test == True:",
"None) is None assert isinstance(child_test, BaseNodeTest), child_test assert getattr(child_test, \"predicates\", None) is None",
"0: handlers = () else: handler_map = {} for node_id in node_ids: for",
"== event: yield edge[1] # Raymond's code def nfa_to_dfa(nfa): numbering = {} #",
"= -numbering[frozenset(tree.if_true)] else: if_true = 0 else: if_true = len(node_ops) node_ops.append(tree.if_true) if isinstance(tree.if_false,",
"if state == -1: return pi_ops = self.machine_states[state][3] for (pi_target, pi_state) in pi_ops:",
"is not None: assert isinstance(parent_test, CommentTest), parent_test assert isinstance(child_test, CommentTest), child_test return True,",
"numbering): # Do I report anything for having reached here? if list(self.nfa_node_ids) !=",
"print node_op print \" ATTR OPS\" for attr_op in attr_ops: print attr_op print",
"\"predicates\", None) is None if parent_test is None: if isinstance(child_test, AnyNodeTest): return True,",
"SAX handler class RuleMachineHandler(object): def __init__(self, machine_states): self.machine_states = machine_states def startDocument(self,node): self.stack",
"AnyNodeTest()) # loop def to_nfa(expr, namespaces): #print \"Eval\", expr.__class__ if (expr.__class__ is locationpaths.relative_location_path):",
"todo = [(dfa_start, None)] while todo: current_dfa, match_type = todo.pop() #print \"All transitions",
"match_type not in (\"node\", \"record\"): continue new_transitions = nfa.edges[node_id] transitions.extend(new_transitions) return transitions def",
"in (\"node\", \"record\"): continue new_transitions = nfa.edges[node_id] transitions.extend(new_transitions) return transitions def transition(nfa_state, event):",
"( (BaseNodeTest.match_type, self.node_tree), (AttributeTest.match_type, self.attr_tree), (ProcessingInstructionTest.match_type, self.pi_tree), (CommentTest.match_type, self.comment_tree) ): visit = [tree]",
"= table.comment_tree.if_true assert isinstance(tree, set) if tree: comment_state = numbering[frozenset(tree)] else: comment_state =",
"None)) else: die(node_test) nfa.terminal_nodes.add(node_id) #if axis_name == \"descendant\": # _add_initial_loop(nfa) #print \"QWERQWER\" #nfa.dump()",
"if parent_test.target == child_test.target: return True, False return False, child_test def comment_intersect(parent_test, child_test):",
"return True, True if isinstance(child_test, NodeTest): # XXX This is wrong. Resolved namespaces",
"nfa.union(to_nfa(path, namespaces)) return nfa die(expr) def node_intersect(parent_test, child_test): if parent_test is not None:",
"intersection\" if not self.start_edges: self.start_edges[:] = other.start_edges self.edges.update(other.edges) self.match_types.update(other.match_types) for node_id in self.terminal_nodes:",
"set of path specifiers like # \"a\" \"a/b\", \"a/b/c[0]/d[@x]\" (relative location path) #",
"self.machine_states[state][1] if not element_ops: # This was a valid target, but there's nothing",
"O(log(number of tags)) performance # instead of O(n). However, for now, n is",
"ATTR OPS\" for attr_op in attr_ops: print attr_op print \" PI OPS\" for",
"axes # and these have no downward axes. (XXX I think.) class AttributeTest(object):",
"nfa if (expr.__class__ is locationpaths.abbreviated_absolute_location_path): # This is an abbreviated_absolute_location_path # \"//a\", \"a//b\"",
"PushtreeHandler) def copy(self): nfa = NFA() nfa.start_edges[:] = self.start_edges nfa.edges.update(self.edges) nfa.terminal_nodes.update(self.terminal_nodes) nfa.match_types.update(self.match_types) nfa.labeled_handlers.update(self.labeled_handlers)",
"in expr._paths[1:]: nfa.union(to_nfa(path, namespaces)) return nfa die(expr) def node_intersect(parent_test, child_test): if parent_test is",
"copy(self): nfa = NFA() nfa.start_edges[:] = self.start_edges nfa.edges.update(self.edges) nfa.terminal_nodes.update(self.terminal_nodes) nfa.match_types.update(self.match_types) nfa.labeled_handlers.update(self.labeled_handlers) return nfa",
"to_node_id): if isinstance(test, BaseNodeTest): self._add(self.node_tree, test, to_node_id, node_intersect) elif isinstance(test, AttributeTest): self._add(self.attr_tree, test,",
"in self.expressions]) def build_pushtree_handler(self): return RuleMachineHandler(self._build_machine_states()) # Special handler object to bridge with",
"self.prefix+\"endElementMatch\", node def attributeMatch(self, node): print self.prefix+\"attributeMatch\", node def commentMatch(self, node): print self.prefix+\"commentMatch\",",
"localname), expr.predicates)) elif node_test.__class__ is nodetests.processing_instruction_test: node_id = nfa.new_node(None, ProcessingInstructionTest(node_test._target)) elif node_test.__class__ is",
"axis_name in (\"child\", \"descendant\", \"attribute\"), axis_name if axis_name == \"attribute\": klass = AttributeTest",
"instances. I could find the # actual instances I need except the startElement",
"prefix is None: prefix = \"\" else: prefix = \"(%s) \" % (prefix,)",
"return \"AnyNode (*)\" class NodeTest(BaseNodeTest): def __init__(self, name, predicates): # (ns, name) self.name",
"in current_dfa: if node_id is None: new_transitions = nfa.start_edges else: # XXX I",
"parent_test is None: if isinstance(child_test, AnyNodeTest): return True, False if isinstance(child_test, NodeTest): return",
"and comments #class AnyTest(object): # pass class BaseNodeTest(object): match_type = \"node\" # What",
"= todo.pop() #print \"All transitions from\", current_dfa transitions = all_transitions(nfa, current_dfa) if not",
"# XXX This is wrong. Resolved namespaces can be the same even #",
"for pi_op in pi_ops: print pi_op print \" COMMENT STATE =\", comment_state class",
"if_false = len(node_ops) node_ops.append(tree.if_false) namespace, localname = tree.test.name node_ops[i] = (namespace, localname, None,",
"(expr.__class__ is locationpaths.abbreviated_absolute_location_path): # This is an abbreviated_absolute_location_path # \"//a\", \"a//b\" nfa =",
"class) pairs) table = dfa[node_ids] if dfa_id == 0: handlers = () else:",
"if parent_test is None: return child_test, False if parent_test.name == child_test.name: return True,",
"= op self.value = value class AttributeFunctionCallPred(object): def __init__(self, func): self.func = func",
"[] seen = set([dfa_start]) todo = [(dfa_start, None)] while todo: current_dfa, match_type =",
"child_test.name: return True, False return False, child_test def attr_intersect(parent_test, child_test): if parent_test is",
"# comment tree tree = table.comment_tree.if_true assert isinstance(tree, set) if tree: comment_state =",
"COMMENT STATE =\", comment_state class PushtreeHandler(object): def startSubtree(self, element): pass def endSubtree(self, element):",
"for match_type, tree in ( (BaseNodeTest.match_type, self.node_tree), (AttributeTest.match_type, self.attr_tree), (ProcessingInstructionTest.match_type, self.pi_tree), (CommentTest.match_type, self.comment_tree)",
"instruction tree pi_ops = [] tree = table.pi_tree.if_true while not isinstance(tree, set): target",
"namespace, localname = name i = 0 while 1: ns, ln, test_function, if_true,",
"yield edge[1] # Raymond's code def nfa_to_dfa(nfa): numbering = {} # from frozenset",
"edge[1] # Raymond's code def nfa_to_dfa(nfa): numbering = {} # from frozenset ->",
"tree, to_node_id): if isinstance(tree, set): tree.add(to_node_id) else: self._add_to_leaves(tree.if_true, to_node_id) self._add_to_leaves(tree.if_false, to_node_id) def get_final_nodes(self):",
"any attribute attr_ops.append( (None, None, numbering[frozenset(tree)]) ) attr_ops = tuple(attr_ops) # processing instruction",
"(\"child\", \"descendant\"), axis_name subnfa = to_nfa(step, namespaces) if axis_name == \"descendant\": _add_initial_loop(subnfa) nfa.extend(subnfa)",
"nfa.new_node(None, klass((namespace, None), expr.predicates)) elif node_test.__class__ is nodetests.qualified_name_test: prefix, localname = node_test.name_key namespace",
"name # [@x=\"a\"] class AttributeBinOpPred(object): def __init__(self, name, op, value): self.name = name",
"state_table.add(test, to_node_id) for nfa_nodes, match_type in state_table.get_final_nodes(): some_dfa = frozenset(nfa_nodes) if some_dfa not",
"ProcessingInstructionTest(node_test._target)) elif node_test.__class__ is locationpaths.nodetests.principal_type_test: node_id = nfa.new_node(None, klass((None, None), None)) else: die(node_test)",
"test) nfa.connect(any_node, any_node, AnyNodeTest()) # loop def to_nfa(expr, namespaces): #print \"Eval\", expr.__class__ if",
"def endElementNS(self, node, name, qname): #print \"endElementNS\", node, name, qname last_state = self.stack.pop()",
"False if isinstance(child_test, NodeTest): return child_test, False elif isinstance(parent_test, NodeTest): if isinstance(child_test, AnyNodeTest):",
"report anything for having reached here? if list(self.nfa_node_ids) != [None]: for nfa_node in",
"# [] seen = set([dfa_start]) todo = [(dfa_start, None)] while todo: current_dfa, match_type",
"\"a\" node_id = nfa.new_node(None, klass(node_test.name_key, expr.predicates)) elif node_test.__class__ is nodetests.namespace_test: # Namespace but",
"can figure out how to get # the attribute node handler.attributeMatch( (node, (namespace,",
"attr_ops = [] tree = table.attr_tree.if_true while not isinstance(tree, set): namespace, localname =",
"\"attr test:\", (ns, ln), (namespace, localname) if ((ns is None or namespace ==",
"child_test, False if isinstance(parent_test, AnyNodeTest): if isinstance(child_test, AnyNodeTest): return True, False if isinstance(child_test,",
"tree.if_false = new_branch else: self._add(tree.if_false, new_false_test, to_node_id, intersect) def _add_to_leaves(self, tree, to_node_id): if",
"[x[0] for x in self.nfa.labeled_handlers[nfa_node]] if labels: print \"Report\", self.nfa.match_types[nfa_node], labels for (name,",
"prefix=None): if prefix is None: prefix = \"\" else: prefix = \"(%s) \"",
"For example, if there are a # large number of element tag tests",
"could find the # actual instances I need except the startElement and #",
"-1: return handlers = self.machine_states[last_state][0] for handler in reversed(handlers): handler.endElementMatch(node) def processingInstruction(self, node,",
"% (self.name[0], self.name[1], self.predicates) # predicates make no sense here because we only",
"a hack until I can figure out how to get # the attribute",
"= func ##### # This would yield nodes, attribute, PIs, and comments #class",
"edges): for (to_node_id, test) in edges: print \"\", test, \"->\", to_node_id def _add_initial_loop(nfa):",
"-numbering[frozenset(tree.if_true)] else: if_true = 0 else: if_true = len(node_ops) node_ops.append(tree.if_true) if isinstance(tree.if_false, set):",
"isinstance(child_test, BaseNodeTest), child_test assert getattr(child_test, \"predicates\", None) is None if parent_test is None:",
"\"a\" \"a/b\", \"a/b/c[0]/d[@x]\" (relative location path) # \"@a\", \"a/@b\", and even \"@a/@b\", which",
"i, len(node_ops) tree = node_ops[i] if isinstance(tree.if_true, set): if tree.if_true: if_true = -numbering[frozenset(tree.if_true)]",
"False if isinstance(child_test, NodeTest): return child_test, False if isinstance(parent_test, AnyNodeTest): if isinstance(child_test, AnyNodeTest):",
"has no type self.match_types = {} # node_id -> match_type self.labeled_handlers = {}",
"match_type = \"processing-instruction\" def __init__(self, target): self.target = target def __str__(self): return \"processing-instruction(%r)\"",
"dump(self, numbering): # Do I report anything for having reached here? if list(self.nfa_node_ids)",
"new_branch else: self._add(tree.if_false, new_false_test, to_node_id, intersect) def _add_to_leaves(self, tree, to_node_id): if isinstance(tree, set):",
"for namespace, localname in attrs.keys(): for (ns, ln, attr_state_id) in attr_ops: #print \"attr",
"set([None]) # handlers (which are in (id, class) pairs) table = dfa[node_ids] if",
"= if_true else: i = if_false if i == 0: # dead-end; no",
"() else: handler_map = {} for node_id in node_ids: for (label, handler) in",
"in (\"child\", \"descendant\", \"attribute\"), axis_name if axis_name == \"attribute\": klass = AttributeTest else:",
"def all_transitions(nfa, current_dfa): transitions = [] for node_id in current_dfa: if node_id is",
"self._add(self.attr_tree, test, to_node_id, attr_intersect) elif isinstance(test, ProcessingInstructionTest): self._add(self.pi_tree, test, to_node_id, pi_intersect) elif isinstance(test,",
"return if i < 0: next_state = -i break # otherwise, loop #print",
"== True: self._add_to_leaves(tree.if_true, to_node_id) elif new_true_test: if isinstance(tree.if_true, set): new_branch = Branch(new_true_test, tree.if_true",
"child_test.target: return True, False return False, child_test def comment_intersect(parent_test, child_test): if parent_test is",
"make if not tree: node_ops = [] # ... because there are no",
"if __name__ == '__main__': testxml = \"\"\"\\ <body> <li>Ignore me<b/></li> <ul> <li x='1'>This",
"name, like \"a:*\" namespace = namespaces[node_test._prefix] node_id = nfa.new_node(None, klass((namespace, None), expr.predicates)) elif",
"localname in attrs.keys(): for (ns, ln, attr_state_id) in attr_ops: #print \"attr test:\", (ns,",
"subtree_handler) def _add(self, xpath, xpath_handler): nfa = to_nfa(xpath_parser.parse(xpath), self.namespaces) i = len(self.expressions) nfa.add_handler((i,",
"handler.startElementMatch(node) # Also handle any attributes attr_ops = self.machine_states[next_state][2] if not attr_ops: return",
"self.node_tree = Branch(None, set(), set()) self.attr_tree = Branch(None, set(), set()) self.pi_tree = Branch(None,",
"name=%r\" % (self.name,) class ProcessingInstructionTest(object): match_type = \"processing-instruction\" def __init__(self, target): self.target =",
"pi_ops = [] tree = table.pi_tree.if_true while not isinstance(tree, set): target = tree.test.target",
"else: node_name = str(node_id) action = str(self.match_types[node_id]) labels += \" \" + str([x[0]",
"self.stack = [0] #dump_machine_states(self.machine_states) def startElementNS(self, node, name, qname, attrs): state = self.stack[-1]",
"axis.name assert axis_name in (\"child\", \"descendant\"), axis_name subnfa = to_nfa(step, namespaces) if axis_name",
"return child_test, False if isinstance(parent_test, AnyNodeTest): if isinstance(child_test, AnyNodeTest): return True, False if",
"= if_false if i == 0: # dead-end; no longer part of the",
"amara.xpath.locationpaths import nodetests from amara.xpath.functions import nodesets from amara.xpath.expressions import booleans import amara.xpath.expressions.nodesets",
"% (self.name,) class ProcessingInstructionTest(object): match_type = \"processing-instruction\" def __init__(self, target): self.target = target",
"nothing nfa = NFA() for step in expr._steps: nfa.extend(to_nfa(step, namespaces)) _add_initial_loop(nfa) return nfa",
"xpath, nfa): self.id = id self.xpath = xpath self._nfa = nfa def nfas_to_machine_states(nfas):",
"import amara.xpath.expressions.nodesets # another nodesets! from amara.xpath.expressions import basics counter = itertools.count(1) #",
"for node_id in node_ids: for (label, handler) in nfa.labeled_handlers[node_id]: handler_map[label] = handler #",
"def _add(self, tree, test, to_node_id, intersect): new_true_test, new_false_test = intersect(tree.test, test) if new_true_test",
"set): tree.add(to_node_id) else: self._add_to_leaves(tree.if_true, to_node_id) self._add_to_leaves(tree.if_false, to_node_id) def get_final_nodes(self): result = {} for",
"= name # [@x=\"a\"] class AttributeBinOpPred(object): def __init__(self, name, op, value): self.name =",
"def _add(self, xpath, xpath_handler): nfa = to_nfa(xpath_parser.parse(xpath), self.namespaces) i = len(self.expressions) nfa.add_handler((i, xpath_handler))",
"print \"== INFO FOR\", i, \"==\" handlers, node_ops, attr_ops, pi_ops, comment_state = x",
"inspect.getmembers(expr): if k.startswith(\"__\") and k.endswith(\"__\"): continue print repr(k), repr(v) raise AssertionError(expr) def build_states(nfa,",
"I report anything for having reached here? if list(self.nfa_node_ids) != [None]: for nfa_node",
"xpath self._nfa = nfa def nfas_to_machine_states(nfas): union_nfa = nfas[0].copy() # XXX start with",
"to_nfa(step, namespaces) if axis_name == \"descendant\": _add_initial_loop(subnfa) nfa.extend(subnfa) return nfa if (expr.__class__ is",
"= str(node_id) action = str(self.match_types[node_id]) labels += \" \" + str([x[0] for x",
"a proper SAX handler class RuleMachineHandler(object): def __init__(self, machine_states): self.machine_states = machine_states def",
"\" ATTR OPS\" for attr_op in attr_ops: print attr_op print \" PI OPS\"",
"def new_node(self, from_node_id, test): edges = self.get_edges(from_node_id) to_node_id = next(counter) self.edges[to_node_id] = []",
"self.nfa_node_ids: labels = [x[0] for x in self.nfa.labeled_handlers[nfa_node]] if labels: print \"Report\", self.nfa.match_types[nfa_node],",
"i = len(self.expressions) nfa.add_handler((i, xpath_handler)) exp = Expression(i, xpath, nfa) self.expressions.append(exp) return exp",
"= set([dfa_start]) todo = [(dfa_start, None)] while todo: current_dfa, match_type = todo.pop() #print",
"= [] edges.append( (to_node_id, test) ) return to_node_id def connect(self, from_node_id, to_node_id, test):",
"\"\" else: prefix = \"(%s) \" % (prefix,) self.prefix = prefix def startSubtree(self,",
"ProcessingInstructionTest(object): match_type = \"processing-instruction\" def __init__(self, target): self.target = target def __str__(self): return",
"== namespace) and (ln is None or ln == localname)): i = if_true",
"for (to_node_id, test) in edges: print \"\", test, \"->\", to_node_id def _add_initial_loop(nfa): start_edges",
"if_true = len(node_ops) node_ops.append(tree.if_true) if isinstance(tree.if_false, set): if tree.if_false: if_false = -numbering[frozenset(tree.if_false)] else:",
"to_node_id): if isinstance(tree, set): tree.add(to_node_id) else: self._add_to_leaves(tree.if_true, to_node_id) self._add_to_leaves(tree.if_false, to_node_id) def get_final_nodes(self): result",
"print \"======\" def _dump_edges(self, edges): for (to_node_id, test) in edges: print \"\", test,",
"x print \" HANDLERS\", handlers print \" NODE OPS\" for node_op in node_ops:",
"dfa_start = frozenset([None]) # nfa start node result = {} # [] seen",
"not transitions: # Make sure there's always a target. # This also stores",
"predicates def __str__(self): return \"Attr name=%r\" % (self.name,) class ProcessingInstructionTest(object): match_type = \"processing-instruction\"",
"expr._steps: axis = step.axis axis_name = axis.name assert axis_name in (\"child\", \"descendant\"), axis_name",
"if isinstance(tree.if_true, set): new_branch = Branch(new_true_test, tree.if_true | set([to_node_id]), tree.if_true) tree.if_true = new_branch",
"endSubtree(self, element): print self.prefix+\"endSubtree\", element def startElementMatch(self, node): print self.prefix+\"startElementMatch\", node def endElementMatch(self,",
"== set([None]) # handlers (which are in (id, class) pairs) table = dfa[node_ids]",
"# Make sure there's always a target. # This also stores any handler",
"len(states) if dfa_id == 0: assert node_ids == set([None]) # handlers (which are",
"x='1'>This <i>is</i> test</li> <li x='2'><a href='spam'>that</a> was nothing</li> </ul> </body> \"\"\" manager =",
"= self.machine_states[state][1] if not element_ops: # This was a valid target, but there's",
"stores any handler events result[current_dfa] = StateTable(match_type, nfa, current_dfa) numbering[current_dfa] = len(numbering) continue",
"more than 10 or so. class Branch(object): def __init__(self, test, if_true, if_false): self.test",
"machine_states, end_node_handler = end_node_handler, attr_handler = attr_handler) def dump_machine_states(machine_states): for i, x in",
"Branch(None, set(), set()) self.attr_tree = Branch(None, set(), set()) self.pi_tree = Branch(None, set(), set())",
"node def processingInstructionMatch(self, node): print self.prefix+\"processingInstructionMatch\", node if __name__ == '__main__': testxml =",
"sorted(tree) print s, \"<>\", numbering[frozenset(tree)], k else: print s, \"<> (empty)\" else: print",
"dfa_id == 0: assert node_ids == set([None]) # handlers (which are in (id,",
"test) in edges: print \"\", test, \"->\", to_node_id def _add_initial_loop(nfa): start_edges = nfa.start_edges[:]",
"self._add(self.node_tree, test, to_node_id, node_intersect) elif isinstance(test, AttributeTest): self._add(self.attr_tree, test, to_node_id, attr_intersect) elif isinstance(test,",
"x in self.expressions]) def build_pushtree_handler(self): return RuleMachineHandler(self._build_machine_states()) # Special handler object to bridge",
"= [] self.edges = {} # from_node_id -> [(to_node_id, test), ...] self.terminal_nodes =",
"build_pushtree_handler(self): return RuleMachineHandler(self._build_machine_states()) # Special handler object to bridge with pushbind support in",
"(*)\" class NodeTest(BaseNodeTest): def __init__(self, name, predicates): # (ns, name) self.name = name",
"print \" PI OPS\" for pi_op in pi_ops: print pi_op print \" COMMENT",
"-1: return pi_ops = self.machine_states[state][3] for (pi_target, pi_state) in pi_ops: if pi_target ==",
"#print \"GOTO -1\" self.stack.append(-1) return namespace, localname = name i = 0 while",
"if tree: k = sorted(tree) print s, \"<>\", numbering[frozenset(tree)], k else: print s,",
"isinstance(parent_test, ProcessingInstructionTest), parent_test assert isinstance(child_test, ProcessingInstructionTest), child_test if parent_test is None: return child_test,",
"amara.xpath import parser as xpath_parser from amara.xpath import locationpaths from amara.xpath.locationpaths import axisspecifiers",
"= node_test.name_key namespace = namespaces[prefix] node_id = nfa.new_node(None, klass((namespace, localname), expr.predicates)) elif node_test.__class__",
"downward axes # and these have no downward axes. (XXX I think.) class",
"\"GoTo\", next_state self.stack.append(next_state) handlers = self.machine_states[next_state][0] for handler in handlers: handler.startElementMatch(node) # Also",
"import axisspecifiers from amara.xpath.locationpaths import nodetests from amara.xpath.functions import nodesets from amara.xpath.expressions import",
"FAILURE ==\" print type(expr) print dir(expr) for k, v in inspect.getmembers(expr): if k.startswith(\"__\")",
"i, \"==\" handlers, node_ops, attr_ops, pi_ops, comment_state = x print \" HANDLERS\", handlers",
"isinstance(parent_test, AnyNodeTest): if isinstance(child_test, AnyNodeTest): return True, False if isinstance(child_test, NodeTest): return child_test,",
"...] self.terminal_nodes = set() # The start node has no type self.match_types =",
"= tuple(attr_ops) # processing instruction tree pi_ops = [] tree = table.pi_tree.if_true while",
"no attributes self.stack.append(-1) return if i < 0: next_state = -i break #",
"... because there are no states else: node_ops = [(None, None, None, -numbering[frozenset(tree)])]",
"return False, child_test def pi_intersect(parent_test, child_test): if parent_test is not None: assert isinstance(parent_test,",
"self.attr_tree = Branch(None, set(), set()) self.pi_tree = Branch(None, set(), set()) self.comment_tree = Branch(None,",
"there are no states else: node_ops = [(None, None, None, -numbering[frozenset(tree)])] else: node_ops",
"self.machine_states[state][3] for (pi_target, pi_state) in pi_ops: if pi_target == target: handlers = self.machine_states[pi_state][0]",
"# \"//a\", \"a//b\" nfa = NFA() for step in expr._steps: nfa.extend(to_nfa(step, namespaces)) _add_initial_loop(nfa)",
"href='spam'>that</a> was nothing</li> </ul> </body> \"\"\" manager = PushtreeManager(\"body/ul/li\", VerbosePushtreeHandler(\"main\")) manager.expressions[0]._nfa.dump() manager.add(\"pre/post\", VerbosePushtreeHandler(\"pre/post\"))",
"any way to match *any* PI? # Looks like Amara support XPath 1.0,",
"nfa.new_node(None, AnyNodeTest()) for (to_node_id, test) in start_edges: nfa.connect(any_node, to_node_id, test) nfa.connect(any_node, any_node, AnyNodeTest())",
"or it fails. # TODO: something more sophisticated? For example, if there are",
"code def nfa_to_dfa(nfa): numbering = {} # from frozenset -> 0, 1, 2,",
"no type self.match_types = {} # node_id -> match_type self.labeled_handlers = {} #",
"dead-end; no longer part of the DFA and the # 0 node is",
"in nfa_state.edges: if edge[0] == event: yield edge[1] # Raymond's code def nfa_to_dfa(nfa):",
"target, but there's nothing leading off from it #print \"GOTO -1\" self.stack.append(-1) return",
"in expr._steps: nfa.extend(to_nfa(step, namespaces)) _add_initial_loop(nfa) return nfa if (expr.__class__ is locationpaths.absolute_location_path): # This",
"self.nfa.labeled_handlers[nfa_node]] if labels: print \"Report\", self.nfa.match_types[nfa_node], labels for (name, tree) in ( (\"NODE\",",
"\"descendant\": _add_initial_loop(subnfa) nfa.extend(subnfa) return nfa if (expr.__class__ is locationpaths.abbreviated_absolute_location_path): # This is an",
"for (label, handler) in nfa.labeled_handlers[node_id]: handler_map[label] = handler # This are PushtreeHandler instances.",
"== ln)): # Match! handlers = self.machine_states[attr_state_id][0] for handler in handlers: #print \"Notify",
"object to bridge with pushbind support in the builder # Implemented by beazley.",
"node_id -> match_type self.labeled_handlers = {} # node_id -> (label, PushtreeHandler) def copy(self):",
"\" PI OPS\" for pi_op in pi_ops: print pi_op print \" COMMENT STATE",
"= StateTable(match_type, nfa, current_dfa) for to_node_id, test in transitions: state_table.add(test, to_node_id) for nfa_nodes,",
"is None: namespaces = {} self.namespaces = namespaces self.expressions = [] self._add(subtree_xpath, subtree_handler)",
"and (ln is None or localname == ln)): # Match! handlers = self.machine_states[attr_state_id][0]",
"namespace, localname in attrs.keys(): for (ns, ln, attr_state_id) in attr_ops: #print \"attr test:\",",
"NFA(object): def __init__(self): self.start_edges = [] self.edges = {} # from_node_id -> [(to_node_id,",
"klass = NodeTest nfa = NFA() node_test = expr.node_test if node_test.__class__ is nodetests.local_name_test:",
"numbering[frozenset(tree)]) ) pi_ops = tuple(pi_ops) # comment tree tree = table.comment_tree.if_true assert isinstance(tree,",
"node = visit.pop() if isinstance(node, set): if node: result[frozenset(node)] = match_type elif node",
"use different method. handlers = [] for (label, handler) in sorted(handler_map.items()): handlers.append(handler) #",
"return False, child_test def comment_intersect(parent_test, child_test): if parent_test is not None: assert isinstance(parent_test,",
"tree: comment_state = numbering[frozenset(tree)] else: comment_state = 0 states.append( (handlers, node_ops, attr_ops, pi_ops,",
"nfa = NFA() nfa.start_edges[:] = self.start_edges nfa.edges.update(self.edges) nfa.terminal_nodes.update(self.terminal_nodes) nfa.match_types.update(self.match_types) nfa.labeled_handlers.update(self.labeled_handlers) return nfa def",
"True, True if isinstance(child_test, NodeTest): # XXX This is wrong. Resolved namespaces can",
"= AttributeTest else: klass = NodeTest nfa = NFA() node_test = expr.node_test if",
") tree = tree.if_false if tree: pi_ops.append( (None, numbering[frozenset(tree)]) ) pi_ops = tuple(pi_ops)",
"= [(dfa_start, None)] while todo: current_dfa, match_type = todo.pop() #print \"All transitions from\",",
"# Match! handlers = self.machine_states[attr_state_id][0] for handler in handlers: #print \"Notify attribute match:\",",
"target: handlers = self.machine_states[pi_state][0] for handler in handlers: handler.processingInstruction(node) # For Dave class",
"Note: This is not a proper SAX handler class RuleMachineHandler(object): def __init__(self, machine_states):",
"in enumerate(machine_states): print \"== INFO FOR\", i, \"==\" handlers, node_ops, attr_ops, pi_ops, comment_state",
"[] self.edges = {} # from_node_id -> [(to_node_id, test), ...] self.terminal_nodes = set()",
"support in the builder # Implemented by beazley. Note: This is not a",
"self.name = name self.op = op self.value = value class AttributeFunctionCallPred(object): def __init__(self,",
"pi_ops: print pi_op print \" COMMENT STATE =\", comment_state class PushtreeHandler(object): def startSubtree(self,",
"attributeMatch(self, node): pass def commentMatch(self, node): pass def processingInstructionMatch(self, node): pass class VerbosePushtreeHandler(PushtreeHandler):",
"first branch is always true self._dump(tree.if_true, 0, numbering) def _dump(self, tree, depth, numbering):",
"def nfas_to_machine_states(nfas): union_nfa = nfas[0].copy() # XXX start with empty and union everything?",
"if isinstance(child_test, NodeTest): return child_test, False elif isinstance(parent_test, NodeTest): if isinstance(child_test, AnyNodeTest): return",
"k.endswith(\"__\"): continue print repr(k), repr(v) raise AssertionError(expr) def build_states(nfa, dfa, numbering): # unique",
"child_test): if parent_test is not None: assert isinstance(parent_test, BaseNodeTest), parent_test assert getattr(parent_test, \"predicates\",",
"#dump_machine_states(self.machine_states) def startElementNS(self, node, name, qname, attrs): state = self.stack[-1] #print \"startElementNS\", name,",
"localname, numbering[frozenset(tree.if_true)]) ) tree = tree.if_false if tree: # Match any attribute attr_ops.append(",
"= \"comment\" class NFA(object): def __init__(self): self.start_edges = [] self.edges = {} #",
"list(self.nfa_node_ids) != [None]: for nfa_node in self.nfa_node_ids: labels = [x[0] for x in",
"# This is a set of path specifiers like # \"a\" \"a/b\", \"a/b/c[0]/d[@x]\"",
"\"tree\" else: print name, \"tree:\" # The first branch is always true self._dump(tree.if_true,",
"node is defined to have no attributes self.stack.append(-1) return if i < 0:",
"axis.name assert axis_name in (\"child\", \"descendant\", \"attribute\"), axis_name if axis_name == \"attribute\": klass",
"match_type = \"node\" # What about *[@spam] ? class AnyNodeTest(BaseNodeTest): def __str__(self): return",
"handler) in nfa.labeled_handlers[node_id]: handler_map[label] = handler # This are PushtreeHandler instances. I could",
"set(other.edges), \"non-empty intersection\" if not self.start_edges: self.start_edges[:] = other.start_edges self.edges.update(other.edges) self.match_types.update(other.match_types) for node_id",
"return RuleMachineHandler(self._build_machine_states()) # Special handler object to bridge with pushbind support in the",
"isinstance(child_test, AnyNodeTest): return True, True if isinstance(child_test, NodeTest): # XXX This is wrong.",
"= \"\"\"\\ <body> <li>Ignore me<b/></li> <ul> <li x='1'>This <i>is</i> test</li> <li x='2'><a href='spam'>that</a>",
"node_ops.append(tree.if_false) namespace, localname = tree.test.name node_ops[i] = (namespace, localname, None, if_true, if_false) #print",
"nfa.new_node(None, klass((namespace, localname), expr.predicates)) elif node_test.__class__ is nodetests.processing_instruction_test: node_id = nfa.new_node(None, ProcessingInstructionTest(node_test._target)) elif",
"is None if parent_test is None: if isinstance(child_test, AnyNodeTest): return True, False if",
"(None, numbering[frozenset(tree)]) ) pi_ops = tuple(pi_ops) # comment tree tree = table.comment_tree.if_true assert",
"new_true_test, to_node_id, intersect) if new_false_test == True: self._add_to_leaves(tree.if_false, to_node_id) elif new_false_test: if isinstance(tree.if_false,",
"pi_op in pi_ops: print pi_op print \" COMMENT STATE =\", comment_state class PushtreeHandler(object):",
"= name assert not predicates self.predicates = predicates def __str__(self): return \"Attr name=%r\"",
"This is a hack until I can figure out how to get #",
"= Branch(new_true_test, tree.if_true | set([to_node_id]), tree.if_true) tree.if_true = new_branch else: self._add(tree.if_true, new_true_test, to_node_id,",
"import nodetests from amara.xpath.functions import nodesets from amara.xpath.expressions import booleans import amara.xpath.expressions.nodesets #",
"= [] for dfa_id, node_ids in sorted( (dfa_id, node_ids) for (node_ids, dfa_id) in",
"= other.start_edges self.edges.update(other.edges) self.match_types.update(other.match_types) for node_id in self.terminal_nodes: self.edges[node_id].extend(other.start_edges) self.terminal_nodes.clear() self.terminal_nodes.update(other.terminal_nodes) self.labeled_handlers.update(other.labeled_handlers) def",
"= to_nfa(expr._paths[0], namespaces) for path in expr._paths[1:]: nfa.union(to_nfa(path, namespaces)) return nfa die(expr) def",
"= nfa.match_types[node_id] if match_type not in (\"node\", \"record\"): continue new_transitions = nfa.edges[node_id] transitions.extend(new_transitions)",
"return True, False return False, child_test def comment_intersect(parent_test, child_test): if parent_test is not",
"test_function, if_true, if_false = element_ops[i] assert test_function is None if ((ns is None",
"self.labeled_handlers.update(other.labeled_handlers) def union(self, other): assert not set(self.edges) & set(other.edges), \"non-empty intersection\" self.start_edges.extend(other.start_edges) self.edges.update(other.edges)",
"tests then sort the tags and start # in the middle. Should give",
"node_test = expr.node_test if node_test.__class__ is nodetests.local_name_test: # Something without a namespace, like",
"dfa, numbering = nfa_to_dfa(union_nfa) return build_states(union_nfa, dfa, numbering) class PushtreeManager(object): def __init__(self, subtree_xpath,",
"[tree] while visit: node = visit.pop() if isinstance(node, set): if node: result[frozenset(node)] =",
"which wasn't a node or a record match_type = nfa.match_types[node_id] if match_type not",
"manager.expressions[3]._nfa.dump() manager.add(\"a\", VerbosePushtreeHandler(\"a\")) manager.expressions[4]._nfa.dump() #manager.add(\".//*\") machine_states = manager._build_machine_states() dump_machine_states(machine_states) hand = RuleMachineHandler(machine_states) import",
"self._add(self.pi_tree, test, to_node_id, pi_intersect) elif isinstance(test, CommentTest): self._add(self.comment_tree, test, to_node_id, comment_intersect) else: raise",
"same even # if the namespace fields are different. # XXX check for",
"test passes or it fails. # TODO: something more sophisticated? For example, if",
"no sense here because we only support downward axes # and these have",
"from_node_id -> [(to_node_id, test), ...] self.terminal_nodes = set() # The start node has",
"if parent_test is None: if isinstance(child_test, AnyNodeTest): return True, False if isinstance(child_test, NodeTest):",
"pi_intersect(parent_test, child_test): if parent_test is not None: assert isinstance(parent_test, ProcessingInstructionTest), parent_test assert isinstance(child_test,",
"if some_dfa not in seen: seen.add(some_dfa) todo.append( (some_dfa, match_type) ) result[current_dfa] = state_table",
"make no sense here because we only support downward axes # and these",
"self.stack.append(next_state) handlers = self.machine_states[next_state][0] for handler in handlers: handler.startElementMatch(node) # Also handle any",
"etc. transitions state_table = StateTable(match_type, nfa, current_dfa) for to_node_id, test in transitions: state_table.add(test,",
"= {} # node_id -> (label, PushtreeHandler) def copy(self): nfa = NFA() nfa.start_edges[:]",
"_add_initial_loop(nfa): start_edges = nfa.start_edges[:] any_node = nfa.new_node(None, AnyNodeTest()) for (to_node_id, test) in start_edges:",
"The first branch is always true self._dump(tree.if_true, 0, numbering) def _dump(self, tree, depth,",
"\"?\" self._dump(tree.if_true, depth+1, numbering) self._dump(tree.if_false, depth+1, numbering) def all_transitions(nfa, current_dfa): transitions = []",
"like # \"/a\", \"/a[0]/b[@x]\" nfa = NFA() for step in expr._steps: axis =",
"for nfa_nodes, match_type in state_table.get_final_nodes(): some_dfa = frozenset(nfa_nodes) if some_dfa not in seen:",
"processingInstructionMatch(self, node): pass class VerbosePushtreeHandler(PushtreeHandler): def __init__(self, prefix=None): if prefix is None: prefix",
"\"QWERQWER\" #nfa.dump() return nfa if expr.__class__ is amara.xpath.expressions.nodesets.union_expr: # \"a|b\" nfa = to_nfa(expr._paths[0],",
"= sorted(tree) print s, \"<>\", numbering[frozenset(tree)], k else: print s, \"<> (empty)\" else:",
"Match any attribute attr_ops.append( (None, None, numbering[frozenset(tree)]) ) attr_ops = tuple(attr_ops) # processing",
"StateTable(match_type, nfa, current_dfa) numbering[current_dfa] = len(numbering) continue # This adds element, attribute, comment,",
"no decisions to make if not tree: node_ops = [] # ... because",
"not a proper SAX handler class RuleMachineHandler(object): def __init__(self, machine_states): self.machine_states = machine_states",
"test, to_node_id, node_intersect) elif isinstance(test, AttributeTest): self._add(self.attr_tree, test, to_node_id, attr_intersect) elif isinstance(test, ProcessingInstructionTest):",
"node: result[frozenset(node)] = match_type elif node is not None: visit.append(node.if_true) visit.append(node.if_false) return result.items()",
"AssertionError(test) def _add(self, tree, test, to_node_id, intersect): new_true_test, new_false_test = intersect(tree.test, test) if",
"comment_state = numbering[frozenset(tree)] else: comment_state = 0 states.append( (handlers, node_ops, attr_ops, pi_ops, comment_state)",
"target): self.target = target def __str__(self): return \"processing-instruction(%r)\" % (self.target,) class CommentTest(object): match_type",
"\"Attr name=%r\" % (self.name,) class ProcessingInstructionTest(object): match_type = \"processing-instruction\" def __init__(self, target): self.target",
"__init__(self, name): self.name = name # [@x=\"a\"] class AttributeBinOpPred(object): def __init__(self, name, op,",
"self.name = name self.predicates = predicates def __str__(self): return \"Node ns=%r localname=%r predicates=%r\"",
"numbering) def all_transitions(nfa, current_dfa): transitions = [] for node_id in current_dfa: if node_id",
"_dump(self, tree, depth, numbering): s = \"-\"*depth if isinstance(tree, set): if tree: k",
"table.comment_tree.if_true assert isinstance(tree, set) if tree: comment_state = numbering[frozenset(tree)] else: comment_state = 0",
"node or a record match_type = nfa.match_types[node_id] if match_type not in (\"node\", \"record\"):",
"end_node_handler = end_node_handler, attr_handler = attr_handler) def dump_machine_states(machine_states): for i, x in enumerate(machine_states):",
"start node self.nfa = nfa self.nfa_node_ids = nfa_node_ids self.node_tree = Branch(None, set(), set())",
"in pi_ops: print pi_op print \" COMMENT STATE =\", comment_state class PushtreeHandler(object): def",
"= build_instructions(nfa,dfa,numbering) RuleMachineHandler.__init__(self, machine_states, end_node_handler = end_node_handler, attr_handler = attr_handler) def dump_machine_states(machine_states): for",
"if i == 0: # dead-end; no longer part of the DFA and",
"= StateTable(match_type, nfa, current_dfa) numbering[current_dfa] = len(numbering) continue # This adds element, attribute,",
"= xpath self._nfa = nfa def nfas_to_machine_states(nfas): union_nfa = nfas[0].copy() # XXX start",
"test) in start_edges: nfa.connect(any_node, to_node_id, test) nfa.connect(any_node, any_node, AnyNodeTest()) # loop def to_nfa(expr,",
"dfa_id, node_ids in sorted( (dfa_id, node_ids) for (node_ids, dfa_id) in numbering.items() ): assert",
"assert not set(self.edges) & set(other.edges), \"non-empty intersection\" self.start_edges.extend(other.start_edges) self.edges.update(other.edges) self.match_types.update(other.match_types) self.terminal_nodes.update(other.terminal_nodes) self.labeled_handlers.update(other.labeled_handlers) def",
"\" == FAILURE ==\" print type(expr) print dir(expr) for k, v in inspect.getmembers(expr):",
"xpath_handler)) exp = Expression(i, xpath, nfa) self.expressions.append(exp) return exp def add(self, xpath, xpath_handler=None):",
"isinstance(child_test, NodeTest): return child_test, False if isinstance(parent_test, AnyNodeTest): if isinstance(child_test, AnyNodeTest): return True,",
"class BaseNodeTest(object): match_type = \"node\" # What about *[@spam] ? class AnyNodeTest(BaseNodeTest): def",
"path like # \"/a\", \"/a[0]/b[@x]\" nfa = NFA() for step in expr._steps: axis",
"child_test, False # Is there any way to match *any* PI? # Looks",
"xpm = ExpressionManager(namespaces=namespaces); xpm.add(pattern) nfa, dfa, numbering = xpm.build_dfa_tables() machine_states = build_instructions(nfa,dfa,numbering) RuleMachineHandler.__init__(self,",
"not None: assert isinstance(parent_test, ProcessingInstructionTest), parent_test assert isinstance(child_test, ProcessingInstructionTest), child_test if parent_test is",
"of the DFA and the # 0 node is defined to have no",
"Should give O(log(number of tags)) performance # instead of O(n). However, for now,",
"#print \"All transitions from\", current_dfa transitions = all_transitions(nfa, current_dfa) if not transitions: #",
"handlers print \" NODE OPS\" for node_op in node_ops: print node_op print \"",
"Make sure there's always a target. # This also stores any handler events",
"is defined to have no attributes self.stack.append(-1) return if i < 0: next_state",
"def pi_intersect(parent_test, child_test): if parent_test is not None: assert isinstance(parent_test, ProcessingInstructionTest), parent_test assert",
"the child axis, with two predicates # \"@a\" - step along the attribute",
"% (prefix,) self.prefix = prefix def startSubtree(self, element): print self.prefix+\"startSubtree\", element def endSubtree(self,",
"= nfa_node_ids self.node_tree = Branch(None, set(), set()) self.attr_tree = Branch(None, set(), set()) self.pi_tree",
"# in the middle. Should give O(log(number of tags)) performance # instead of",
"isinstance(tree, set): target = tree.test.target pi_ops.append( (target, numbering[frozenset(tree.if_true)]) ) tree = tree.if_false if",
"self.match_types.update(other.match_types) self.terminal_nodes.update(other.terminal_nodes) self.labeled_handlers.update(other.labeled_handlers) def dump(self): for node_id, edges in [(None, self.start_edges)] + sorted(self.edges.items()):",
"the # 0 node is defined to have no attributes self.stack.append(-1) return if",
"self.match_types = {} # node_id -> match_type self.labeled_handlers = {} # node_id ->",
"is nodetests.local_name_test: # Something without a namespace, like \"a\" node_id = nfa.new_node(None, klass(node_test.name_key,",
"like \"a:*\" namespace = namespaces[node_test._prefix] node_id = nfa.new_node(None, klass((namespace, None), expr.predicates)) elif node_test.__class__",
"for i, x in enumerate(machine_states): print \"== INFO FOR\", i, \"==\" handlers, node_ops,",
"node has no type self.match_types = {} # node_id -> match_type self.labeled_handlers =",
"have no downward axes. (XXX I think.) class AttributeTest(object): match_type = \"attr\" def",
"str(node_id) action = str(self.match_types[node_id]) labels += \" \" + str([x[0] for x in",
"from amara.xpath.locationpaths import axisspecifiers from amara.xpath.locationpaths import nodetests from amara.xpath.functions import nodesets from",
"return nfa if (expr.__class__ is locationpaths.absolute_location_path): # This is an absolute path like",
"todo.append(if_false) if if_true > 0: todo.append(if_true) node_ops = tuple(node_ops) # attr tree attr_ops",
"if ((ns is None or namespace == ns) and (ln is None or",
"start # in the middle. Should give O(log(number of tags)) performance # instead",
"> 0: todo.append(if_true) node_ops = tuple(node_ops) # attr tree attr_ops = [] tree",
"can be the same even # if the namespace fields are different. #",
"node, target, data): state = self.stack[-1] if state == -1: return pi_ops =",
"(some_dfa, match_type) ) result[current_dfa] = state_table numbering[current_dfa] = len(numbering) # for k, table",
"return for namespace, localname in attrs.keys(): for (ns, ln, attr_state_id) in attr_ops: #print",
"# node tree tree = table.node_tree.if_true if isinstance(tree, set): # Special case when",
"labels += \" \" + str([x[0] for x in self.labeled_handlers[node_id]]) is_terminal = \"(terminal)\"",
"axis_name subnfa = to_nfa(step, namespaces) if axis_name == \"descendant\": _add_initial_loop(subnfa) nfa.extend(subnfa) return nfa",
"predicates def __str__(self): return \"Node ns=%r localname=%r predicates=%r\" % (self.name[0], self.name[1], self.predicates) #",
"to_node_id = next(counter) self.edges[to_node_id] = [] self.match_types[to_node_id] = test.match_type self.labeled_handlers[to_node_id] = [] edges.append(",
"None or ns == namespace) and (ln is None or ln == localname)):",
"transitions = [] for node_id in current_dfa: if node_id is None: new_transitions =",
"target. # This also stores any handler events result[current_dfa] = StateTable(match_type, nfa, current_dfa)",
"locationpaths.absolute_location_path): # This is an absolute path like # \"/a\", \"/a[0]/b[@x]\" nfa =",
"True, False return False, child_test def attr_intersect(parent_test, child_test): if parent_test is not None:",
"state = self.stack[-1] if state == -1: return pi_ops = self.machine_states[state][3] for (pi_target,",
") pi_ops = tuple(pi_ops) # comment tree tree = table.comment_tree.if_true assert isinstance(tree, set)",
"self.machine_states[next_state][2] if not attr_ops: return for namespace, localname in attrs.keys(): for (ns, ln,",
"if node_test.__class__ is nodetests.local_name_test: # Something without a namespace, like \"a\" node_id =",
"import parser as xpath_parser from amara.xpath import locationpaths from amara.xpath.locationpaths import axisspecifiers from",
"self.prefix+\"startElementMatch\", node def endElementMatch(self, node): print self.prefix+\"endElementMatch\", node def attributeMatch(self, node): print self.prefix+\"attributeMatch\",",
"in self.terminal_nodes) else \"\" print node_name, is_terminal, labels self._dump_edges(edges) print \"======\" def _dump_edges(self,",
"new_branch = Branch(new_true_test, tree.if_true | set([to_node_id]), tree.if_true) tree.if_true = new_branch else: self._add(tree.if_true, new_true_test,",
"= tree.test.name attr_ops.append( (namespace, localname, numbering[frozenset(tree.if_true)]) ) tree = tree.if_false if tree: #",
"states.append( (handlers, node_ops, attr_ops, pi_ops, comment_state) ) return tuple(states) class Expression(object): def __init__(self,",
"if tree: comment_state = numbering[frozenset(tree)] else: comment_state = 0 states.append( (handlers, node_ops, attr_ops,",
"because we only support downward axes # and these have no downward axes.",
"a valid target, but there's nothing leading off from it #print \"GOTO -1\"",
"(label, handler) in nfa.labeled_handlers[node_id]: handler_map[label] = handler # This are PushtreeHandler instances. I",
"(ln is None or localname == ln)): # Match! handlers = self.machine_states[attr_state_id][0] for",
"self._add(self.comment_tree, test, to_node_id, comment_intersect) else: raise AssertionError(test) def _add(self, tree, test, to_node_id, intersect):",
"for (name, tree) in ( (\"NODE\", self.node_tree), (\"ATTR\", self.attr_tree), (\"PROCESSING-INSTRUCTION\", self.pi_tree), (\"COMMENT\", self.comment_tree)",
"isinstance(child_test, AnyNodeTest): return True, False if isinstance(child_test, NodeTest): return child_test, False elif isinstance(parent_test,",
"end_node_handler, attr_handler, namespaces=None): self.xpm = xpm = ExpressionManager(namespaces=namespaces); xpm.add(pattern) nfa, dfa, numbering =",
"def endSubtree(self, element): print self.prefix+\"endSubtree\", element def startElementMatch(self, node): print self.prefix+\"startElementMatch\", node def",
"elif node_test.__class__ is locationpaths.nodetests.principal_type_test: node_id = nfa.new_node(None, klass((None, None), None)) else: die(node_test) nfa.terminal_nodes.add(node_id)",
"for nfa in nfas[1:]: union_nfa.union(nfa) dfa, numbering = nfa_to_dfa(union_nfa) return build_states(union_nfa, dfa, numbering)",
"some_dfa = frozenset(nfa_nodes) if some_dfa not in seen: seen.add(some_dfa) todo.append( (some_dfa, match_type) )",
"if isinstance(tree.if_false, set): new_branch = Branch(new_false_test, tree.if_false | set([to_node_id]), tree.if_false) tree.if_false = new_branch",
"a target. # This also stores any handler events result[current_dfa] = StateTable(match_type, nfa,",
"& set(other.edges), \"non-empty intersection\" if not self.start_edges: self.start_edges[:] = other.start_edges self.edges.update(other.edges) self.match_types.update(other.match_types) for",
"numbering) def _dump(self, tree, depth, numbering): s = \"-\"*depth if isinstance(tree, set): if",
"\"descendant\", \"attribute\"), axis_name if axis_name == \"attribute\": klass = AttributeTest else: klass =",
"localname == ln)): # Match! handlers = self.machine_states[attr_state_id][0] for handler in handlers: #print",
"set) if tree: comment_state = numbering[frozenset(tree)] else: comment_state = 0 states.append( (handlers, node_ops,",
"nfa): self.id = id self.xpath = xpath self._nfa = nfa def nfas_to_machine_states(nfas): union_nfa",
"NFA() for step in expr._steps: axis = step.axis axis_name = axis.name assert axis_name",
"is None: if isinstance(child_test, AnyNodeTest): return True, False if isinstance(child_test, NodeTest): return child_test,",
"( (\"NODE\", self.node_tree), (\"ATTR\", self.attr_tree), (\"PROCESSING-INSTRUCTION\", self.pi_tree), (\"COMMENT\", self.comment_tree) ): if tree is",
"not set(self.edges) & set(other.edges), \"non-empty intersection\" self.start_edges.extend(other.start_edges) self.edges.update(other.edges) self.match_types.update(other.match_types) self.terminal_nodes.update(other.terminal_nodes) self.labeled_handlers.update(other.labeled_handlers) def dump(self):",
"def to_nfa(expr, namespaces): #print \"Eval\", expr.__class__ if (expr.__class__ is locationpaths.relative_location_path): # This is",
"((ns is None or namespace == ns) and (ln is None or localname",
"intersect(tree.test, test) if new_true_test == True: self._add_to_leaves(tree.if_true, to_node_id) elif new_true_test: if isinstance(tree.if_true, set):",
"RulePatternHandler(RuleMachineHandler): def __init__(self, pattern, end_node_handler, attr_handler, namespaces=None): self.xpm = xpm = ExpressionManager(namespaces=namespaces); xpm.add(pattern)",
"namespaces) for path in expr._paths[1:]: nfa.union(to_nfa(path, namespaces)) return nfa die(expr) def node_intersect(parent_test, child_test):",
"(self.target,) class CommentTest(object): match_type = \"comment\" class NFA(object): def __init__(self): self.start_edges = []",
"isinstance(child_test, NodeTest): # XXX This is wrong. Resolved namespaces can be the same",
"class AttributeTest(object): match_type = \"attr\" def __init__(self, name, predicates): self.name = name assert",
"in attr_ops: #print \"attr test:\", (ns, ln), (namespace, localname) if ((ns is None",
"= predicates def __str__(self): return \"Attr name=%r\" % (self.name,) class ProcessingInstructionTest(object): match_type =",
"handlers: handler.processingInstruction(node) # For Dave class RulePatternHandler(RuleMachineHandler): def __init__(self, pattern, end_node_handler, attr_handler, namespaces=None):",
"not set(self.edges) & set(other.edges), \"non-empty intersection\" if not self.start_edges: self.start_edges[:] = other.start_edges self.edges.update(other.edges)",
"nfa start node result = {} # [] seen = set([dfa_start]) todo =",
"\"a/b\", \"a/b/c[0]/d[@x]\" (relative location path) # \"@a\", \"a/@b\", and even \"@a/@b\", which gives",
"element, attribute, comment, etc. transitions state_table = StateTable(match_type, nfa, current_dfa) for to_node_id, test",
"to_node_id, test): self.get_edges(from_node_id).append( (to_node_id, test) ) def extend(self, other): assert not set(self.edges) &",
"add_handler(self, labeled_handler): for node_id in self.terminal_nodes: self.labeled_handlers[node_id].append(labeled_handler) def new_node(self, from_node_id, test): edges =",
"self.prefix+\"startSubtree\", element def endSubtree(self, element): print self.prefix+\"endSubtree\", element def startElementMatch(self, node): print self.prefix+\"startElementMatch\",",
"for the start node self.nfa = nfa self.nfa_node_ids = nfa_node_ids self.node_tree = Branch(None,",
"tree = table.attr_tree.if_true while not isinstance(tree, set): namespace, localname = tree.test.name attr_ops.append( (namespace,",
"is locationpaths.abbreviated_absolute_location_path): # This is an abbreviated_absolute_location_path # \"//a\", \"a//b\" nfa = NFA()",
"node_id = nfa.new_node(None, ProcessingInstructionTest(node_test._target)) elif node_test.__class__ is locationpaths.nodetests.principal_type_test: node_id = nfa.new_node(None, klass((None, None),",
"to_node_id, attr_intersect) elif isinstance(test, ProcessingInstructionTest): self._add(self.pi_tree, test, to_node_id, pi_intersect) elif isinstance(test, CommentTest): self._add(self.comment_tree,",
"test) ) def extend(self, other): assert not set(self.edges) & set(other.edges), \"non-empty intersection\" if",
"for (node_ids, dfa_id) in numbering.items() ): assert dfa_id == len(states) if dfa_id ==",
"to_node_id, intersect) def _add_to_leaves(self, tree, to_node_id): if isinstance(tree, set): tree.add(to_node_id) else: self._add_to_leaves(tree.if_true, to_node_id)",
"node): print self.prefix+\"commentMatch\", node def processingInstructionMatch(self, node): print self.prefix+\"processingInstructionMatch\", node if __name__ ==",
"self.stack[-1] if state == -1: return pi_ops = self.machine_states[state][3] for (pi_target, pi_state) in",
"from_node_id, to_node_id, test): self.get_edges(from_node_id).append( (to_node_id, test) ) def extend(self, other): assert not set(self.edges)",
"self.nfa_node_ids = nfa_node_ids self.node_tree = Branch(None, set(), set()) self.attr_tree = Branch(None, set(), set())",
"I can figure out how to get # the attribute node handler.attributeMatch( (node,",
"assert dfa_id == len(states) if dfa_id == 0: assert node_ids == set([None]) #",
"nfa if expr.__class__ is amara.xpath.expressions.nodesets.union_expr: # \"a|b\" nfa = to_nfa(expr._paths[0], namespaces) for path",
"CommentTest), child_test return True, False # Used to make a decision tree. Either",
"nfa_to_dfa(nfa): numbering = {} # from frozenset -> 0, 1, 2, ... dfa_start",
"number of element tag tests then sort the tags and start # in",
"self.edges.update(other.edges) self.match_types.update(other.match_types) self.terminal_nodes.update(other.terminal_nodes) self.labeled_handlers.update(other.labeled_handlers) def dump(self): for node_id, edges in [(None, self.start_edges)] +",
"from amara.xpath.expressions import booleans import amara.xpath.expressions.nodesets # another nodesets! from amara.xpath.expressions import basics",
"s = \"-\"*depth if isinstance(tree, set): if tree: k = sorted(tree) print s,",
"# which wasn't a node or a record match_type = nfa.match_types[node_id] if match_type",
"event_ids, (namespace, localname) # This is a hack until I can figure out",
"self.comment_tree = Branch(None, set(), set()) def add(self, test, to_node_id): if isinstance(test, BaseNodeTest): self._add(self.node_tree,",
"# XXX start with empty and union everything? for nfa in nfas[1:]: union_nfa.union(nfa)",
"self.labeled_handlers = {} # node_id -> (label, PushtreeHandler) def copy(self): nfa = NFA()",
"events result[current_dfa] = StateTable(match_type, nfa, current_dfa) numbering[current_dfa] = len(numbering) continue # This adds",
"</body> \"\"\" manager = PushtreeManager(\"body/ul/li\", VerbosePushtreeHandler(\"main\")) manager.expressions[0]._nfa.dump() manager.add(\"pre/post\", VerbosePushtreeHandler(\"pre/post\")) manager.expressions[1]._nfa.dump() manager.add(\"//a\", VerbosePushtreeHandler(\"//a\")) manager.expressions[2]._nfa.dump()",
"location path) # \"@a\", \"a/@b\", and even \"@a/@b\", which gives nothing nfa =",
"node if __name__ == '__main__': testxml = \"\"\"\\ <body> <li>Ignore me<b/></li> <ul> <li",
"child_test def attr_intersect(parent_test, child_test): if parent_test is not None: assert isinstance(parent_test, AttributeTest), parent_test",
"(\"node\", \"record\"): continue new_transitions = nfa.edges[node_id] transitions.extend(new_transitions) return transitions def transition(nfa_state, event): for",
"if not transitions: # Make sure there's always a target. # This also",
"<ul> <li x='1'>This <i>is</i> test</li> <li x='2'><a href='spam'>that</a> was nothing</li> </ul> </body> \"\"\"",
"edges in [(None, self.start_edges)] + sorted(self.edges.items()): if node_id is None: node_name = \"(start)\"",
"nfa, current_dfa) numbering[current_dfa] = len(numbering) continue # This adds element, attribute, comment, etc.",
"namespace, localname = tree.test.name node_ops[i] = (namespace, localname, None, if_true, if_false) #print \"Added\",",
"comment_state) ) return tuple(states) class Expression(object): def __init__(self, id, xpath, nfa): self.id =",
"def dump(self): for node_id, edges in [(None, self.start_edges)] + sorted(self.edges.items()): if node_id is",
"return build_states(union_nfa, dfa, numbering) class PushtreeManager(object): def __init__(self, subtree_xpath, subtree_handler = None, namespaces",
"itertools from amara.xpath import parser as xpath_parser from amara.xpath import locationpaths from amara.xpath.locationpaths",
"self.namespaces = namespaces self.expressions = [] self._add(subtree_xpath, subtree_handler) def _add(self, xpath, xpath_handler): nfa",
"reversed(handlers): handler.endElementMatch(node) def processingInstruction(self, node, target, data): state = self.stack[-1] if state ==",
"= nfa.edges[node_id] transitions.extend(new_transitions) return transitions def transition(nfa_state, event): for (to_node_id, test) in edge",
"pass class BaseNodeTest(object): match_type = \"node\" # What about *[@spam] ? class AnyNodeTest(BaseNodeTest):",
"from_node_id, test): edges = self.get_edges(from_node_id) to_node_id = next(counter) self.edges[to_node_id] = [] self.match_types[to_node_id] =",
"bridge with pushbind support in the builder # Implemented by beazley. Note: This",
"= expr.axis axis_name = axis.name assert axis_name in (\"child\", \"descendant\", \"attribute\"), axis_name if",
"class PushtreeHandler(object): def startSubtree(self, element): pass def endSubtree(self, element): pass def startElementMatch(self, node):",
"= \"processing-instruction\" def __init__(self, target): self.target = target def __str__(self): return \"processing-instruction(%r)\" %",
"self.terminal_nodes: self.edges[node_id].extend(other.start_edges) self.terminal_nodes.clear() self.terminal_nodes.update(other.terminal_nodes) self.labeled_handlers.update(other.labeled_handlers) def union(self, other): assert not set(self.edges) & set(other.edges),",
"(ns, name) self.name = name self.predicates = predicates def __str__(self): return \"Node ns=%r",
"None or localname == ln)): # Match! handlers = self.machine_states[attr_state_id][0] for handler in",
"def __init__(self, name, predicates): # (ns, name) self.name = name self.predicates = predicates",
") return to_node_id def connect(self, from_node_id, to_node_id, test): self.get_edges(from_node_id).append( (to_node_id, test) ) def",
"localname = node_test.name_key namespace = namespaces[prefix] node_id = nfa.new_node(None, klass((namespace, localname), expr.predicates)) elif",
"assert isinstance(child_test, ProcessingInstructionTest), child_test if parent_test is None: return child_test, False # Is",
"None, namespaces = None): if namespaces is None: namespaces = {} self.namespaces =",
"are PushtreeHandler instances. I could find the # actual instances I need except",
"support downward axes # and these have no downward axes. (XXX I think.)",
"for step in expr._steps: nfa.extend(to_nfa(step, namespaces)) _add_initial_loop(nfa) return nfa if expr.__class__ is locationpaths.location_step:",
"-1\" self.stack.append(-1) return element_ops = self.machine_states[state][1] if not element_ops: # This was a",
"locationpaths.relative_location_path): # This is a set of path specifiers like # \"a\" \"a/b\",",
"gives nothing nfa = NFA() for step in expr._steps: nfa.extend(to_nfa(step, namespaces)) _add_initial_loop(nfa) return",
"in edge in nfa_state.edges: if edge[0] == event: yield edge[1] # Raymond's code",
"new_branch else: self._add(tree.if_true, new_true_test, to_node_id, intersect) if new_false_test == True: self._add_to_leaves(tree.if_false, to_node_id) elif",
"now, n is no more than 10 or so. class Branch(object): def __init__(self,",
"type self.match_types = {} # node_id -> match_type self.labeled_handlers = {} # node_id",
"tree = table.comment_tree.if_true assert isinstance(tree, set) if tree: comment_state = numbering[frozenset(tree)] else: comment_state",
"[@x=\"a\"] class AttributeBinOpPred(object): def __init__(self, name, op, value): self.name = name self.op =",
"is nodetests.namespace_test: # Namespace but no name, like \"a:*\" namespace = namespaces[node_test._prefix] node_id",
"state_table = StateTable(match_type, nfa, current_dfa) for to_node_id, test in transitions: state_table.add(test, to_node_id) for",
"This was a valid target, but there's nothing leading off from it #print",
"fields are different. # XXX check for predicates! if parent_test.name == child_test.name: return",
"attribute match:\", event_ids, (namespace, localname) # This is a hack until I can",
"s, tree.test, \"?\" self._dump(tree.if_true, depth+1, numbering) self._dump(tree.if_false, depth+1, numbering) def all_transitions(nfa, current_dfa): transitions",
"name) self.name = name self.predicates = predicates def __str__(self): return \"Node ns=%r localname=%r",
"continue new_transitions = nfa.edges[node_id] transitions.extend(new_transitions) return transitions def transition(nfa_state, event): for (to_node_id, test)",
"node): pass def processingInstructionMatch(self, node): pass class VerbosePushtreeHandler(PushtreeHandler): def __init__(self, prefix=None): if prefix",
"I can't transition from something # which wasn't a node or a record",
"name, qname, attrs): state = self.stack[-1] #print \"startElementNS\", name, qname, attrs, \"state\", state",
"0 node is defined to have no attributes self.stack.append(-1) return if i <",
"the middle. Should give O(log(number of tags)) performance # instead of O(n). However,",
"by beazley. Note: This is not a proper SAX handler class RuleMachineHandler(object): def",
"self.xpath = xpath self._nfa = nfa def nfas_to_machine_states(nfas): union_nfa = nfas[0].copy() # XXX",
"abbreviated_absolute_location_path # \"//a\", \"a//b\" nfa = NFA() for step in expr._steps: nfa.extend(to_nfa(step, namespaces))",
"\" No\", name, \"tree\" else: print name, \"tree:\" # The first branch is",
"if tree is None: print \" No\", name, \"tree\" else: print name, \"tree:\"",
"node_id, edges in [(None, self.start_edges)] + sorted(self.edges.items()): if node_id is None: node_name =",
"for node_id in self.terminal_nodes: self.labeled_handlers[node_id].append(labeled_handler) def new_node(self, from_node_id, test): edges = self.get_edges(from_node_id) to_node_id",
"startSubtree(self, element): print self.prefix+\"startSubtree\", element def endSubtree(self, element): print self.prefix+\"endSubtree\", element def startElementMatch(self,",
"basics counter = itertools.count(1) # [@x] class AttributeExistsPred(object): def __init__(self, name): self.name =",
"booleans import amara.xpath.expressions.nodesets # another nodesets! from amara.xpath.expressions import basics counter = itertools.count(1)",
"1: ns, ln, test_function, if_true, if_false = element_ops[i] assert test_function is None if",
"nfa = to_nfa(expr._paths[0], namespaces) for path in expr._paths[1:]: nfa.union(to_nfa(path, namespaces)) return nfa die(expr)",
"\"@a\", \"a/@b\", and even \"@a/@b\", which gives nothing nfa = NFA() for step",
"for now, n is no more than 10 or so. class Branch(object): def",
"element_ops[i] assert test_function is None if ((ns is None or ns == namespace)",
"_add_initial_loop(nfa) return nfa if expr.__class__ is locationpaths.location_step: # This is a step along",
"(to_node_id, test) ) def extend(self, other): assert not set(self.edges) & set(other.edges), \"non-empty intersection\"",
"else: self._add(tree.if_false, new_false_test, to_node_id, intersect) def _add_to_leaves(self, tree, to_node_id): if isinstance(tree, set): tree.add(to_node_id)",
"def startElementNS(self, node, name, qname, attrs): state = self.stack[-1] #print \"startElementNS\", name, qname,",
"the builder # Implemented by beazley. Note: This is not a proper SAX",
"as: # \"a\" - step along the child axis # \"a[@x][@y='1']\" - step",
"step along some axis, such as: # \"a\" - step along the child",
"class RulePatternHandler(RuleMachineHandler): def __init__(self, pattern, end_node_handler, attr_handler, namespaces=None): self.xpm = xpm = ExpressionManager(namespaces=namespaces);",
"tree: pi_ops.append( (None, numbering[frozenset(tree)]) ) pi_ops = tuple(pi_ops) # comment tree tree =",
"xpath, xpath_handler): nfa = to_nfa(xpath_parser.parse(xpath), self.namespaces) i = len(self.expressions) nfa.add_handler((i, xpath_handler)) exp =",
"__init__(self, prefix=None): if prefix is None: prefix = \"\" else: prefix = \"(%s)",
"assert isinstance(parent_test, ProcessingInstructionTest), parent_test assert isinstance(child_test, ProcessingInstructionTest), child_test if parent_test is None: return",
"What about *[@spam] ? class AnyNodeTest(BaseNodeTest): def __str__(self): return \"AnyNode (*)\" class NodeTest(BaseNodeTest):",
"i = if_true else: i = if_false if i == 0: # dead-end;",
"def attr_intersect(parent_test, child_test): if parent_test is not None: assert isinstance(parent_test, AttributeTest), parent_test assert",
"processingInstructionMatch(self, node): print self.prefix+\"processingInstructionMatch\", node if __name__ == '__main__': testxml = \"\"\"\\ <body>",
"#nfa.dump() return nfa if expr.__class__ is amara.xpath.expressions.nodesets.union_expr: # \"a|b\" nfa = to_nfa(expr._paths[0], namespaces)",
"nfa.terminal_nodes.update(self.terminal_nodes) nfa.match_types.update(self.match_types) nfa.labeled_handlers.update(self.labeled_handlers) return nfa def get_edges(self, node_id): if node_id is None: return",
"self._dump(tree.if_false, depth+1, numbering) def all_transitions(nfa, current_dfa): transitions = [] for node_id in current_dfa:",
"isinstance(tree, set): tree.add(to_node_id) else: self._add_to_leaves(tree.if_true, to_node_id) self._add_to_leaves(tree.if_false, to_node_id) def get_final_nodes(self): result = {}",
"in handlers: handler.processingInstruction(node) # For Dave class RulePatternHandler(RuleMachineHandler): def __init__(self, pattern, end_node_handler, attr_handler,",
"repr(v) raise AssertionError(expr) def build_states(nfa, dfa, numbering): # unique node numbers states =",
"if_true, if_false) #print \"Added\", node_ops[i] if if_false > 0: todo.append(if_false) if if_true >",
"predicates # \"@a\" - step along the attribute axis axis = expr.axis axis_name",
"and (ln is None or ln == localname)): i = if_true else: i",
"in (\"child\", \"descendant\"), axis_name subnfa = to_nfa(step, namespaces) if axis_name == \"descendant\": _add_initial_loop(subnfa)",
"having reached here? if list(self.nfa_node_ids) != [None]: for nfa_node in self.nfa_node_ids: labels =",
"while todo: i = todo.pop() #print \"Access\", i, len(node_ops) tree = node_ops[i] if",
"handler # This are PushtreeHandler instances. I could find the # actual instances",
"self.expressions.append(exp) return exp def add(self, xpath, xpath_handler=None): return self._add(xpath, xpath_handler) def _build_machine_states(self): return",
"in expr._steps: axis = step.axis axis_name = axis.name assert axis_name in (\"child\", \"descendant\"),",
"if_true = 0 else: if_true = len(node_ops) node_ops.append(tree.if_true) if isinstance(tree.if_false, set): if tree.if_false:",
"to bridge with pushbind support in the builder # Implemented by beazley. Note:",
"# What about *[@spam] ? class AnyNodeTest(BaseNodeTest): def __str__(self): return \"AnyNode (*)\" class",
"\"<> (empty)\" else: print s, tree.test, \"?\" self._dump(tree.if_true, depth+1, numbering) self._dump(tree.if_false, depth+1, numbering)",
"print \"State\", sorted(k) # table.dump() return result, numbering def die(expr): import inspect print",
"comment_state = 0 states.append( (handlers, node_ops, attr_ops, pi_ops, comment_state) ) return tuple(states) class",
"self.comment_tree) ): if tree is None: print \" No\", name, \"tree\" else: print",
"[] for dfa_id, node_ids in sorted( (dfa_id, node_ids) for (node_ids, dfa_id) in numbering.items()",
"handle any attributes attr_ops = self.machine_states[next_state][2] if not attr_ops: return for namespace, localname",
"): assert dfa_id == len(states) if dfa_id == 0: assert node_ids == set([None])",
"handlers = () else: handler_map = {} for node_id in node_ids: for (label,",
"attr_op in attr_ops: print attr_op print \" PI OPS\" for pi_op in pi_ops:",
"None if parent_test is None: if isinstance(child_test, AnyNodeTest): return True, False if isinstance(child_test,",
"is wrong. Resolved namespaces can be the same even # if the namespace",
"\"(start)\" labels = \"\" else: node_name = str(node_id) action = str(self.match_types[node_id]) labels +=",
"pass def endSubtree(self, element): pass def startElementMatch(self, node): pass def endElementMatch(self, node): pass",
"tree pi_ops = [] tree = table.pi_tree.if_true while not isinstance(tree, set): target =",
"example, if there are a # large number of element tag tests then",
"# \"@a\", \"a/@b\", and even \"@a/@b\", which gives nothing nfa = NFA() for",
"numbering[frozenset(tree)], k else: print s, \"<> (empty)\" else: print s, tree.test, \"?\" self._dump(tree.if_true,",
"= all_transitions(nfa, current_dfa) if not transitions: # Make sure there's always a target.",
"from\", current_dfa transitions = all_transitions(nfa, current_dfa) if not transitions: # Make sure there's",
"to_node_id, intersect): new_true_test, new_false_test = intersect(tree.test, test) if new_true_test == True: self._add_to_leaves(tree.if_true, to_node_id)",
"= len(node_ops) node_ops.append(tree.if_true) if isinstance(tree.if_false, set): if tree.if_false: if_false = -numbering[frozenset(tree.if_false)] else: if_false",
"nfa_nodes, match_type in state_table.get_final_nodes(): some_dfa = frozenset(nfa_nodes) if some_dfa not in seen: seen.add(some_dfa)",
"self.if_false = if_false class StateTable(object): def __init__(self, match_type, nfa, nfa_node_ids): self.match_type = match_type",
"(node_ids, dfa_id) in numbering.items() ): assert dfa_id == len(states) if dfa_id == 0:",
"k.startswith(\"__\") and k.endswith(\"__\"): continue print repr(k), repr(v) raise AssertionError(expr) def build_states(nfa, dfa, numbering):",
"not in (\"node\", \"record\"): continue new_transitions = nfa.edges[node_id] transitions.extend(new_transitions) return transitions def transition(nfa_state,",
"node, name, qname): #print \"endElementNS\", node, name, qname last_state = self.stack.pop() if last_state",
"tree.if_false if tree: pi_ops.append( (None, numbering[frozenset(tree)]) ) pi_ops = tuple(pi_ops) # comment tree",
"(label, PushtreeHandler) def copy(self): nfa = NFA() nfa.start_edges[:] = self.start_edges nfa.edges.update(self.edges) nfa.terminal_nodes.update(self.terminal_nodes) nfa.match_types.update(self.match_types)",
"not tree: node_ops = [] # ... because there are no states else:",
"False, child_test def attr_intersect(parent_test, child_test): if parent_test is not None: assert isinstance(parent_test, AttributeTest),",
"</ul> </body> \"\"\" manager = PushtreeManager(\"body/ul/li\", VerbosePushtreeHandler(\"main\")) manager.expressions[0]._nfa.dump() manager.add(\"pre/post\", VerbosePushtreeHandler(\"pre/post\")) manager.expressions[1]._nfa.dump() manager.add(\"//a\", VerbosePushtreeHandler(\"//a\"))",
"xpm.add(pattern) nfa, dfa, numbering = xpm.build_dfa_tables() machine_states = build_instructions(nfa,dfa,numbering) RuleMachineHandler.__init__(self, machine_states, end_node_handler =",
"= 0 states.append( (handlers, node_ops, attr_ops, pi_ops, comment_state) ) return tuple(states) class Expression(object):",
"in ( (\"NODE\", self.node_tree), (\"ATTR\", self.attr_tree), (\"PROCESSING-INSTRUCTION\", self.pi_tree), (\"COMMENT\", self.comment_tree) ): if tree",
"set(self.edges) & set(other.edges), \"non-empty intersection\" self.start_edges.extend(other.start_edges) self.edges.update(other.edges) self.match_types.update(other.match_types) self.terminal_nodes.update(other.terminal_nodes) self.labeled_handlers.update(other.labeled_handlers) def dump(self): for",
"This adds element, attribute, comment, etc. transitions state_table = StateTable(match_type, nfa, current_dfa) for",
"ns=%r localname=%r predicates=%r\" % (self.name[0], self.name[1], self.predicates) # predicates make no sense here",
"def node_intersect(parent_test, child_test): if parent_test is not None: assert isinstance(parent_test, BaseNodeTest), parent_test assert",
"node_id in node_ids: for (label, handler) in nfa.labeled_handlers[node_id]: handler_map[label] = handler # This",
"self.start_edges nfa.edges.update(self.edges) nfa.terminal_nodes.update(self.terminal_nodes) nfa.match_types.update(self.match_types) nfa.labeled_handlers.update(self.labeled_handlers) return nfa def get_edges(self, node_id): if node_id is",
"+ str([x[0] for x in self.labeled_handlers[node_id]]) is_terminal = \"(terminal)\" if (node_id in self.terminal_nodes)",
"\"processing-instruction\" def __init__(self, target): self.target = target def __str__(self): return \"processing-instruction(%r)\" % (self.target,)",
"# This would yield nodes, attribute, PIs, and comments #class AnyTest(object): # pass",
"node_intersect) elif isinstance(test, AttributeTest): self._add(self.attr_tree, test, to_node_id, attr_intersect) elif isinstance(test, ProcessingInstructionTest): self._add(self.pi_tree, test,",
"= tree.test.target pi_ops.append( (target, numbering[frozenset(tree.if_true)]) ) tree = tree.if_false if tree: pi_ops.append( (None,",
"node_id is None: node_name = \"(start)\" labels = \"\" else: node_name = str(node_id)",
"PushtreeManager(\"body/ul/li\", VerbosePushtreeHandler(\"main\")) manager.expressions[0]._nfa.dump() manager.add(\"pre/post\", VerbosePushtreeHandler(\"pre/post\")) manager.expressions[1]._nfa.dump() manager.add(\"//a\", VerbosePushtreeHandler(\"//a\")) manager.expressions[2]._nfa.dump() manager.add(\"@x\", VerbosePushtreeHandler(\"@x\")) manager.expressions[3]._nfa.dump() manager.add(\"a\",",
"def __init__(self, subtree_xpath, subtree_handler = None, namespaces = None): if namespaces is None:",
"= todo.pop() #print \"Access\", i, len(node_ops) tree = node_ops[i] if isinstance(tree.if_true, set): if",
"# \"a\" \"a/b\", \"a/b/c[0]/d[@x]\" (relative location path) # \"@a\", \"a/@b\", and even \"@a/@b\",",
"This are PushtreeHandler instances. I could find the # actual instances I need",
"pi_target == target: handlers = self.machine_states[pi_state][0] for handler in handlers: handler.processingInstruction(node) # For",
"\"\"\" manager = PushtreeManager(\"body/ul/li\", VerbosePushtreeHandler(\"main\")) manager.expressions[0]._nfa.dump() manager.add(\"pre/post\", VerbosePushtreeHandler(\"pre/post\")) manager.expressions[1]._nfa.dump() manager.add(\"//a\", VerbosePushtreeHandler(\"//a\")) manager.expressions[2]._nfa.dump() manager.add(\"@x\",",
"these have no downward axes. (XXX I think.) class AttributeTest(object): match_type = \"attr\"",
"sorted( (dfa_id, node_ids) for (node_ids, dfa_id) in numbering.items() ): assert dfa_id == len(states)",
"k else: print s, \"<> (empty)\" else: print s, tree.test, \"?\" self._dump(tree.if_true, depth+1,",
"def transition(nfa_state, event): for (to_node_id, test) in edge in nfa_state.edges: if edge[0] ==",
"numbering.items() ): assert dfa_id == len(states) if dfa_id == 0: assert node_ids ==",
"# TODO: something more sophisticated? For example, if there are a # large",
"2, ... dfa_start = frozenset([None]) # nfa start node result = {} #",
"the start node self.nfa = nfa self.nfa_node_ids = nfa_node_ids self.node_tree = Branch(None, set(),",
"\"Added\", node_ops[i] if if_false > 0: todo.append(if_false) if if_true > 0: todo.append(if_true) node_ops",
"manager.add(\"a\", VerbosePushtreeHandler(\"a\")) manager.expressions[4]._nfa.dump() #manager.add(\".//*\") machine_states = manager._build_machine_states() dump_machine_states(machine_states) hand = RuleMachineHandler(machine_states) import os",
"element_ops: # This was a valid target, but there's nothing leading off from",
"pi_ops.append( (target, numbering[frozenset(tree.if_true)]) ) tree = tree.if_false if tree: pi_ops.append( (None, numbering[frozenset(tree)]) )",
"table.node_tree.if_true if isinstance(tree, set): # Special case when there are no decisions to",
"for predicates! if parent_test.name == child_test.name: return True, False return False, child_test def",
"set(), set()) self.pi_tree = Branch(None, set(), set()) self.comment_tree = Branch(None, set(), set()) def",
"pass def processingInstructionMatch(self, node): pass class VerbosePushtreeHandler(PushtreeHandler): def __init__(self, prefix=None): if prefix is",
"raise AssertionError(expr) def build_states(nfa, dfa, numbering): # unique node numbers states = []",
"if i < 0: next_state = -i break # otherwise, loop #print \"GoTo\",",
"not None: assert isinstance(parent_test, AttributeTest), parent_test assert isinstance(child_test, AttributeTest), child_test if parent_test is",
"from amara.xpath import locationpaths from amara.xpath.locationpaths import axisspecifiers from amara.xpath.locationpaths import nodetests from",
"for node_id in current_dfa: if node_id is None: new_transitions = nfa.start_edges else: #",
"nodetests from amara.xpath.functions import nodesets from amara.xpath.expressions import booleans import amara.xpath.expressions.nodesets # another",
"return True, False # Used to make a decision tree. Either the test",
"todo: i = todo.pop() #print \"Access\", i, len(node_ops) tree = node_ops[i] if isinstance(tree.if_true,",
"NFA() for step in expr._steps: nfa.extend(to_nfa(step, namespaces)) _add_initial_loop(nfa) return nfa if (expr.__class__ is",
"axis_name == \"descendant\": # _add_initial_loop(nfa) #print \"QWERQWER\" #nfa.dump() return nfa if expr.__class__ is",
"to match *any* PI? # Looks like Amara support XPath 1.0, where this",
"\" + str([x[0] for x in self.labeled_handlers[node_id]]) is_terminal = \"(terminal)\" if (node_id in",
"node_ops = [] # ... because there are no states else: node_ops =",
"in the middle. Should give O(log(number of tags)) performance # instead of O(n).",
"set([to_node_id]), tree.if_true) tree.if_true = new_branch else: self._add(tree.if_true, new_true_test, to_node_id, intersect) if new_false_test ==",
"expr._steps: nfa.extend(to_nfa(step, namespaces)) _add_initial_loop(nfa) return nfa if (expr.__class__ is locationpaths.absolute_location_path): # This is",
"todo.pop() #print \"Access\", i, len(node_ops) tree = node_ops[i] if isinstance(tree.if_true, set): if tree.if_true:",
"tree in ( (BaseNodeTest.match_type, self.node_tree), (AttributeTest.match_type, self.attr_tree), (ProcessingInstructionTest.match_type, self.pi_tree), (CommentTest.match_type, self.comment_tree) ): visit",
"elif new_true_test: if isinstance(tree.if_true, set): new_branch = Branch(new_true_test, tree.if_true | set([to_node_id]), tree.if_true) tree.if_true",
"== 0: assert node_ids == set([None]) # handlers (which are in (id, class)",
"= [] self._add(subtree_xpath, subtree_handler) def _add(self, xpath, xpath_handler): nfa = to_nfa(xpath_parser.parse(xpath), self.namespaces) i",
"state == -1: #print \"goto -1\" self.stack.append(-1) return element_ops = self.machine_states[state][1] if not",
"AnyNodeTest): if isinstance(child_test, AnyNodeTest): return True, False if isinstance(child_test, NodeTest): return child_test, False",
"tree.test, \"?\" self._dump(tree.if_true, depth+1, numbering) self._dump(tree.if_false, depth+1, numbering) def all_transitions(nfa, current_dfa): transitions =",
"return nfa if expr.__class__ is amara.xpath.expressions.nodesets.union_expr: # \"a|b\" nfa = to_nfa(expr._paths[0], namespaces) for",
"numbering[frozenset(tree)] else: comment_state = 0 states.append( (handlers, node_ops, attr_ops, pi_ops, comment_state) ) return",
"class AnyNodeTest(BaseNodeTest): def __str__(self): return \"AnyNode (*)\" class NodeTest(BaseNodeTest): def __init__(self, name, predicates):",
"Match! handlers = self.machine_states[attr_state_id][0] for handler in handlers: #print \"Notify attribute match:\", event_ids,",
"= self.get_edges(from_node_id) to_node_id = next(counter) self.edges[to_node_id] = [] self.match_types[to_node_id] = test.match_type self.labeled_handlers[to_node_id] =",
"tree, depth, numbering): s = \"-\"*depth if isinstance(tree, set): if tree: k =",
"build_states(union_nfa, dfa, numbering) class PushtreeManager(object): def __init__(self, subtree_xpath, subtree_handler = None, namespaces =",
"manager.expressions[2]._nfa.dump() manager.add(\"@x\", VerbosePushtreeHandler(\"@x\")) manager.expressions[3]._nfa.dump() manager.add(\"a\", VerbosePushtreeHandler(\"a\")) manager.expressions[4]._nfa.dump() #manager.add(\".//*\") machine_states = manager._build_machine_states() dump_machine_states(machine_states) hand",
"in inspect.getmembers(expr): if k.startswith(\"__\") and k.endswith(\"__\"): continue print repr(k), repr(v) raise AssertionError(expr) def",
"i == 0: # dead-end; no longer part of the DFA and the",
"proper SAX handler class RuleMachineHandler(object): def __init__(self, machine_states): self.machine_states = machine_states def startDocument(self,node):",
"NODE OPS\" for node_op in node_ops: print node_op print \" ATTR OPS\" for",
"def __str__(self): return \"AnyNode (*)\" class NodeTest(BaseNodeTest): def __init__(self, name, predicates): # (ns,",
"handlers: #print \"Notify attribute match:\", event_ids, (namespace, localname) # This is a hack",
"an absolute path like # \"/a\", \"/a[0]/b[@x]\" nfa = NFA() for step in",
"current_dfa, match_type = todo.pop() #print \"All transitions from\", current_dfa transitions = all_transitions(nfa, current_dfa)",
"tree tree = table.comment_tree.if_true assert isinstance(tree, set) if tree: comment_state = numbering[frozenset(tree)] else:",
") def endElementNS(self, node, name, qname): #print \"endElementNS\", node, name, qname last_state =",
"counter = itertools.count(1) # [@x] class AttributeExistsPred(object): def __init__(self, name): self.name = name",
"__init__(self, match_type, nfa, nfa_node_ids): self.match_type = match_type # 'None' for the start node",
"= axis.name assert axis_name in (\"child\", \"descendant\", \"attribute\"), axis_name if axis_name == \"attribute\":",
"endSubtree(self, element): pass def startElementMatch(self, node): pass def endElementMatch(self, node): pass def attributeMatch(self,",
"while not isinstance(tree, set): namespace, localname = tree.test.name attr_ops.append( (namespace, localname, numbering[frozenset(tree.if_true)]) )",
"with two predicates # \"@a\" - step along the attribute axis axis =",
"This is wrong. Resolved namespaces can be the same even # if the",
"\"attribute\"), axis_name if axis_name == \"attribute\": klass = AttributeTest else: klass = NodeTest",
"\"non-empty intersection\" self.start_edges.extend(other.start_edges) self.edges.update(other.edges) self.match_types.update(other.match_types) self.terminal_nodes.update(other.terminal_nodes) self.labeled_handlers.update(other.labeled_handlers) def dump(self): for node_id, edges in",
"is None or namespace == ns) and (ln is None or localname ==",
"elif node_test.__class__ is nodetests.processing_instruction_test: node_id = nfa.new_node(None, ProcessingInstructionTest(node_test._target)) elif node_test.__class__ is locationpaths.nodetests.principal_type_test: node_id",
"nfa) self.expressions.append(exp) return exp def add(self, xpath, xpath_handler=None): return self._add(xpath, xpath_handler) def _build_machine_states(self):",
"else: # XXX I can't transition from something # which wasn't a node",
"parent_test.name == child_test.name: return True, False return False, child_test def attr_intersect(parent_test, child_test): if",
"len(node_ops) node_ops.append(tree.if_true) if isinstance(tree.if_false, set): if tree.if_false: if_false = -numbering[frozenset(tree.if_false)] else: if_false =",
"Branch(None, set(), set()) self.pi_tree = Branch(None, set(), set()) self.comment_tree = Branch(None, set(), set())",
"parent_test.target == child_test.target: return True, False return False, child_test def comment_intersect(parent_test, child_test): if",
"target def __str__(self): return \"processing-instruction(%r)\" % (self.target,) class CommentTest(object): match_type = \"comment\" class",
"no states else: node_ops = [(None, None, None, -numbering[frozenset(tree)])] else: node_ops = [tree]",
"\"State\", sorted(k) # table.dump() return result, numbering def die(expr): import inspect print \"",
"self.stack.pop() if last_state == -1: return handlers = self.machine_states[last_state][0] for handler in reversed(handlers):",
"localname = name i = 0 while 1: ns, ln, test_function, if_true, if_false",
"nfa.extend(to_nfa(step, namespaces)) _add_initial_loop(nfa) return nfa if (expr.__class__ is locationpaths.absolute_location_path): # This is an",
"pass def attributeMatch(self, node): pass def commentMatch(self, node): pass def processingInstructionMatch(self, node): pass",
"self.machine_states = machine_states def startDocument(self,node): self.stack = [0] #dump_machine_states(self.machine_states) def startElementNS(self, node, name,",
"= (namespace, localname, None, if_true, if_false) #print \"Added\", node_ops[i] if if_false > 0:",
"if last_state == -1: return handlers = self.machine_states[last_state][0] for handler in reversed(handlers): handler.endElementMatch(node)",
"is locationpaths.nodetests.principal_type_test: node_id = nfa.new_node(None, klass((None, None), None)) else: die(node_test) nfa.terminal_nodes.add(node_id) #if axis_name",
"is None assert isinstance(child_test, BaseNodeTest), child_test assert getattr(child_test, \"predicates\", None) is None if",
"for (pi_target, pi_state) in pi_ops: if pi_target == target: handlers = self.machine_states[pi_state][0] for",
"not attr_ops: return for namespace, localname in attrs.keys(): for (ns, ln, attr_state_id) in",
"str(self.match_types[node_id]) labels += \" \" + str([x[0] for x in self.labeled_handlers[node_id]]) is_terminal =",
"BaseNodeTest), parent_test assert getattr(parent_test, \"predicates\", None) is None assert isinstance(child_test, BaseNodeTest), child_test assert",
"result = {} for match_type, tree in ( (BaseNodeTest.match_type, self.node_tree), (AttributeTest.match_type, self.attr_tree), (ProcessingInstructionTest.match_type,",
"return handlers = self.machine_states[last_state][0] for handler in reversed(handlers): handler.endElementMatch(node) def processingInstruction(self, node, target,",
"# large number of element tag tests then sort the tags and start",
"is None: return child_test, False if parent_test.name == child_test.name: return True, False return",
"namespaces self.expressions = [] self._add(subtree_xpath, subtree_handler) def _add(self, xpath, xpath_handler): nfa = to_nfa(xpath_parser.parse(xpath),",
"qname): #print \"endElementNS\", node, name, qname last_state = self.stack.pop() if last_state == -1:",
"tuple(states) class Expression(object): def __init__(self, id, xpath, nfa): self.id = id self.xpath =",
"if parent_test.name == child_test.name: return True, False return False, child_test def pi_intersect(parent_test, child_test):",
"*[@spam] ? class AnyNodeTest(BaseNodeTest): def __str__(self): return \"AnyNode (*)\" class NodeTest(BaseNodeTest): def __init__(self,",
"expr.predicates)) elif node_test.__class__ is nodetests.processing_instruction_test: node_id = nfa.new_node(None, ProcessingInstructionTest(node_test._target)) elif node_test.__class__ is locationpaths.nodetests.principal_type_test:",
"== -1: #print \"goto -1\" self.stack.append(-1) return element_ops = self.machine_states[state][1] if not element_ops:",
"if not self.start_edges: self.start_edges[:] = other.start_edges self.edges.update(other.edges) self.match_types.update(other.match_types) for node_id in self.terminal_nodes: self.edges[node_id].extend(other.start_edges)",
"BaseNodeTest): self._add(self.node_tree, test, to_node_id, node_intersect) elif isinstance(test, AttributeTest): self._add(self.attr_tree, test, to_node_id, attr_intersect) elif",
"nfa, current_dfa) for to_node_id, test in transitions: state_table.add(test, to_node_id) for nfa_nodes, match_type in",
"if_true > 0: todo.append(if_true) node_ops = tuple(node_ops) # attr tree attr_ops = []",
"self.match_types[to_node_id] = test.match_type self.labeled_handlers[to_node_id] = [] edges.append( (to_node_id, test) ) return to_node_id def",
"\"======\" def _dump_edges(self, edges): for (to_node_id, test) in edges: print \"\", test, \"->\",",
"pi_ops = self.machine_states[state][3] for (pi_target, pi_state) in pi_ops: if pi_target == target: handlers",
"attrs.keys(): for (ns, ln, attr_state_id) in attr_ops: #print \"attr test:\", (ns, ln), (namespace,",
"localname) ) ) def endElementNS(self, node, name, qname): #print \"endElementNS\", node, name, qname",
"= prefix def startSubtree(self, element): print self.prefix+\"startSubtree\", element def endSubtree(self, element): print self.prefix+\"endSubtree\",",
"set()) self.comment_tree = Branch(None, set(), set()) def add(self, test, to_node_id): if isinstance(test, BaseNodeTest):",
"if_false): self.test = test self.if_true = if_true self.if_false = if_false class StateTable(object): def",
"no longer part of the DFA and the # 0 node is defined",
"out how to get # the attribute node handler.attributeMatch( (node, (namespace, localname) )",
"NodeTest(BaseNodeTest): def __init__(self, name, predicates): # (ns, name) self.name = name self.predicates =",
"import itertools from amara.xpath import parser as xpath_parser from amara.xpath import locationpaths from",
"sophisticated? For example, if there are a # large number of element tag",
"= {} self.namespaces = namespaces self.expressions = [] self._add(subtree_xpath, subtree_handler) def _add(self, xpath,",
"0: todo.append(if_true) node_ops = tuple(node_ops) # attr tree attr_ops = [] tree =",
"then sort the tags and start # in the middle. Should give O(log(number",
"is not None: assert isinstance(parent_test, AttributeTest), parent_test assert isinstance(child_test, AttributeTest), child_test if parent_test",
"test, to_node_id, comment_intersect) else: raise AssertionError(test) def _add(self, tree, test, to_node_id, intersect): new_true_test,",
"if isinstance(node, set): if node: result[frozenset(node)] = match_type elif node is not None:",
"node_test.__class__ is locationpaths.nodetests.principal_type_test: node_id = nfa.new_node(None, klass((None, None), None)) else: die(node_test) nfa.terminal_nodes.add(node_id) #if",
"to_node_id, test) nfa.connect(any_node, any_node, AnyNodeTest()) # loop def to_nfa(expr, namespaces): #print \"Eval\", expr.__class__",
"elif isinstance(test, AttributeTest): self._add(self.attr_tree, test, to_node_id, attr_intersect) elif isinstance(test, ProcessingInstructionTest): self._add(self.pi_tree, test, to_node_id,",
"set([to_node_id]), tree.if_false) tree.if_false = new_branch else: self._add(tree.if_false, new_false_test, to_node_id, intersect) def _add_to_leaves(self, tree,",
"\"Report\", self.nfa.match_types[nfa_node], labels for (name, tree) in ( (\"NODE\", self.node_tree), (\"ATTR\", self.attr_tree), (\"PROCESSING-INSTRUCTION\",",
"frozenset -> 0, 1, 2, ... dfa_start = frozenset([None]) # nfa start node",
"self.terminal_nodes = set() # The start node has no type self.match_types = {}",
"DFA and the # 0 node is defined to have no attributes self.stack.append(-1)",
"test): edges = self.get_edges(from_node_id) to_node_id = next(counter) self.edges[to_node_id] = [] self.match_types[to_node_id] = test.match_type",
"locationpaths from amara.xpath.locationpaths import axisspecifiers from amara.xpath.locationpaths import nodetests from amara.xpath.functions import nodesets",
"node_id = nfa.new_node(None, klass((namespace, localname), expr.predicates)) elif node_test.__class__ is nodetests.processing_instruction_test: node_id = nfa.new_node(None,",
"nfa in nfas[1:]: union_nfa.union(nfa) dfa, numbering = nfa_to_dfa(union_nfa) return build_states(union_nfa, dfa, numbering) class",
"__init__(self, func): self.func = func ##### # This would yield nodes, attribute, PIs,",
"RuleMachineHandler(object): def __init__(self, machine_states): self.machine_states = machine_states def startDocument(self,node): self.stack = [0] #dump_machine_states(self.machine_states)",
"import booleans import amara.xpath.expressions.nodesets # another nodesets! from amara.xpath.expressions import basics counter =",
"set() # The start node has no type self.match_types = {} # node_id",
"= Branch(None, set(), set()) self.attr_tree = Branch(None, set(), set()) self.pi_tree = Branch(None, set(),",
"if state == -1: #print \"goto -1\" self.stack.append(-1) return element_ops = self.machine_states[state][1] if",
"(ns, ln), (namespace, localname) if ((ns is None or namespace == ns) and",
"continue print repr(k), repr(v) raise AssertionError(expr) def build_states(nfa, dfa, numbering): # unique node",
"(label, handler) in sorted(handler_map.items()): handlers.append(handler) # node tree tree = table.node_tree.if_true if isinstance(tree,",
"% (self.target,) class CommentTest(object): match_type = \"comment\" class NFA(object): def __init__(self): self.start_edges =",
"is None: node_name = \"(start)\" labels = \"\" else: node_name = str(node_id) action",
"table = dfa[node_ids] if dfa_id == 0: handlers = () else: handler_map =",
"print \" No\", name, \"tree\" else: print name, \"tree:\" # The first branch",
"in pi_ops: if pi_target == target: handlers = self.machine_states[pi_state][0] for handler in handlers:",
"= match_type elif node is not None: visit.append(node.if_true) visit.append(node.if_false) return result.items() def dump(self,",
"child_test): if parent_test is not None: assert isinstance(parent_test, CommentTest), parent_test assert isinstance(child_test, CommentTest),",
"= \"attr\" def __init__(self, name, predicates): self.name = name assert not predicates self.predicates",
"tree = tree.if_false if tree: # Match any attribute attr_ops.append( (None, None, numbering[frozenset(tree)])",
"# The first branch is always true self._dump(tree.if_true, 0, numbering) def _dump(self, tree,",
"def build_states(nfa, dfa, numbering): # unique node numbers states = [] for dfa_id,",
"print \" HANDLERS\", handlers print \" NODE OPS\" for node_op in node_ops: print",
"even \"@a/@b\", which gives nothing nfa = NFA() for step in expr._steps: nfa.extend(to_nfa(step,",
"if (expr.__class__ is locationpaths.abbreviated_absolute_location_path): # This is an abbreviated_absolute_location_path # \"//a\", \"a//b\" nfa",
"from amara.xpath import parser as xpath_parser from amara.xpath import locationpaths from amara.xpath.locationpaths import",
"else: node_ops = [(None, None, None, -numbering[frozenset(tree)])] else: node_ops = [tree] todo =",
"\"//a\", \"a//b\" nfa = NFA() for step in expr._steps: nfa.extend(to_nfa(step, namespaces)) _add_initial_loop(nfa) return",
"0: next_state = -i break # otherwise, loop #print \"GoTo\", next_state self.stack.append(next_state) handlers",
"RuleMachineHandler.__init__(self, machine_states, end_node_handler = end_node_handler, attr_handler = attr_handler) def dump_machine_states(machine_states): for i, x",
"match:\", event_ids, (namespace, localname) # This is a hack until I can figure",
"if axis_name == \"descendant\": _add_initial_loop(subnfa) nfa.extend(subnfa) return nfa if (expr.__class__ is locationpaths.abbreviated_absolute_location_path): #",
"isinstance(child_test, CommentTest), child_test return True, False # Used to make a decision tree.",
"<i>is</i> test</li> <li x='2'><a href='spam'>that</a> was nothing</li> </ul> </body> \"\"\" manager = PushtreeManager(\"body/ul/li\",",
"node_id -> (label, PushtreeHandler) def copy(self): nfa = NFA() nfa.start_edges[:] = self.start_edges nfa.edges.update(self.edges)",
"None: return child_test, False # Is there any way to match *any* PI?",
"\"node\" # What about *[@spam] ? class AnyNodeTest(BaseNodeTest): def __str__(self): return \"AnyNode (*)\"",
"| set([to_node_id]), tree.if_true) tree.if_true = new_branch else: self._add(tree.if_true, new_true_test, to_node_id, intersect) if new_false_test",
"= {} for node_id in node_ids: for (label, handler) in nfa.labeled_handlers[node_id]: handler_map[label] =",
"a decision tree. Either the test passes or it fails. # TODO: something",
"tuple(attr_ops) # processing instruction tree pi_ops = [] tree = table.pi_tree.if_true while not",
"there are a # large number of element tag tests then sort the",
"if isinstance(tree.if_true, set): if tree.if_true: if_true = -numbering[frozenset(tree.if_true)] else: if_true = 0 else:",
"the tags and start # in the middle. Should give O(log(number of tags))",
"# Used to make a decision tree. Either the test passes or it",
"in handlers: #print \"Notify attribute match:\", event_ids, (namespace, localname) # This is a",
"== '__main__': testxml = \"\"\"\\ <body> <li>Ignore me<b/></li> <ul> <li x='1'>This <i>is</i> test</li>",
"self.edges[to_node_id] = [] self.match_types[to_node_id] = test.match_type self.labeled_handlers[to_node_id] = [] edges.append( (to_node_id, test) )",
"klass = AttributeTest else: klass = NodeTest nfa = NFA() node_test = expr.node_test",
"tree) in ( (\"NODE\", self.node_tree), (\"ATTR\", self.attr_tree), (\"PROCESSING-INSTRUCTION\", self.pi_tree), (\"COMMENT\", self.comment_tree) ): if",
"\"/a\", \"/a[0]/b[@x]\" nfa = NFA() for step in expr._steps: axis = step.axis axis_name",
"-1\" self.stack.append(-1) return namespace, localname = name i = 0 while 1: ns,",
"nfa.extend(to_nfa(step, namespaces)) _add_initial_loop(nfa) return nfa if expr.__class__ is locationpaths.location_step: # This is a",
"isinstance(test, ProcessingInstructionTest): self._add(self.pi_tree, test, to_node_id, pi_intersect) elif isinstance(test, CommentTest): self._add(self.comment_tree, test, to_node_id, comment_intersect)",
"def __str__(self): return \"processing-instruction(%r)\" % (self.target,) class CommentTest(object): match_type = \"comment\" class NFA(object):",
"manager.expressions[0]._nfa.dump() manager.add(\"pre/post\", VerbosePushtreeHandler(\"pre/post\")) manager.expressions[1]._nfa.dump() manager.add(\"//a\", VerbosePushtreeHandler(\"//a\")) manager.expressions[2]._nfa.dump() manager.add(\"@x\", VerbosePushtreeHandler(\"@x\")) manager.expressions[3]._nfa.dump() manager.add(\"a\", VerbosePushtreeHandler(\"a\")) manager.expressions[4]._nfa.dump()",
"else: klass = NodeTest nfa = NFA() node_test = expr.node_test if node_test.__class__ is",
"return child_test, False if parent_test.name == child_test.name: return True, False return False, child_test",
"ProcessingInstructionTest), child_test if parent_test is None: return child_test, False # Is there any",
"different. # XXX check for predicates! if parent_test.name == child_test.name: return True, False",
"k = sorted(tree) print s, \"<>\", numbering[frozenset(tree)], k else: print s, \"<> (empty)\"",
"namespace fields are different. # XXX check for predicates! if parent_test.name == child_test.name:",
"depth, numbering): s = \"-\"*depth if isinstance(tree, set): if tree: k = sorted(tree)",
"= numbering[frozenset(tree)] else: comment_state = 0 states.append( (handlers, node_ops, attr_ops, pi_ops, comment_state) )",
"in sorted(handler_map.items()): handlers.append(handler) # node tree tree = table.node_tree.if_true if isinstance(tree, set): #",
"= frozenset([None]) # nfa start node result = {} # [] seen =",
"{} self.namespaces = namespaces self.expressions = [] self._add(subtree_xpath, subtree_handler) def _add(self, xpath, xpath_handler):",
"node_id = nfa.new_node(None, klass(node_test.name_key, expr.predicates)) elif node_test.__class__ is nodetests.namespace_test: # Namespace but no",
"name, op, value): self.name = name self.op = op self.value = value class",
"if isinstance(child_test, NodeTest): return child_test, False if isinstance(parent_test, AnyNodeTest): if isinstance(child_test, AnyNodeTest): return",
"(prefix,) self.prefix = prefix def startSubtree(self, element): print self.prefix+\"startSubtree\", element def endSubtree(self, element):",
"): if tree is None: print \" No\", name, \"tree\" else: print name,",
"AttributeBinOpPred(object): def __init__(self, name, op, value): self.name = name self.op = op self.value",
"(\"ATTR\", self.attr_tree), (\"PROCESSING-INSTRUCTION\", self.pi_tree), (\"COMMENT\", self.comment_tree) ): if tree is None: print \"",
"intersection\" self.start_edges.extend(other.start_edges) self.edges.update(other.edges) self.match_types.update(other.match_types) self.terminal_nodes.update(other.terminal_nodes) self.labeled_handlers.update(other.labeled_handlers) def dump(self): for node_id, edges in [(None,",
"todo: current_dfa, match_type = todo.pop() #print \"All transitions from\", current_dfa transitions = all_transitions(nfa,",
"= [0] #dump_machine_states(self.machine_states) def startElementNS(self, node, name, qname, attrs): state = self.stack[-1] #print",
"= target def __str__(self): return \"processing-instruction(%r)\" % (self.target,) class CommentTest(object): match_type = \"comment\"",
"None: print \" No\", name, \"tree\" else: print name, \"tree:\" # The first",
"test, to_node_id, pi_intersect) elif isinstance(test, CommentTest): self._add(self.comment_tree, test, to_node_id, comment_intersect) else: raise AssertionError(test)",
"numbering): s = \"-\"*depth if isinstance(tree, set): if tree: k = sorted(tree) print",
"result = {} # [] seen = set([dfa_start]) todo = [(dfa_start, None)] while",
"class CommentTest(object): match_type = \"comment\" class NFA(object): def __init__(self): self.start_edges = [] self.edges",
"set(self.edges) & set(other.edges), \"non-empty intersection\" if not self.start_edges: self.start_edges[:] = other.start_edges self.edges.update(other.edges) self.match_types.update(other.match_types)",
"self.nfa = nfa self.nfa_node_ids = nfa_node_ids self.node_tree = Branch(None, set(), set()) self.attr_tree =",
"to_node_id, node_intersect) elif isinstance(test, AttributeTest): self._add(self.attr_tree, test, to_node_id, attr_intersect) elif isinstance(test, ProcessingInstructionTest): self._add(self.pi_tree,",
"set): new_branch = Branch(new_false_test, tree.if_false | set([to_node_id]), tree.if_false) tree.if_false = new_branch else: self._add(tree.if_false,",
"= nfa.start_edges else: # XXX I can't transition from something # which wasn't",
") return tuple(states) class Expression(object): def __init__(self, id, xpath, nfa): self.id = id",
"ProcessingInstructionTest): self._add(self.pi_tree, test, to_node_id, pi_intersect) elif isinstance(test, CommentTest): self._add(self.comment_tree, test, to_node_id, comment_intersect) else:",
"start with empty and union everything? for nfa in nfas[1:]: union_nfa.union(nfa) dfa, numbering",
"#print \"Notify attribute match:\", event_ids, (namespace, localname) # This is a hack until",
"return tuple(states) class Expression(object): def __init__(self, id, xpath, nfa): self.id = id self.xpath",
"if tree: # Match any attribute attr_ops.append( (None, None, numbering[frozenset(tree)]) ) attr_ops =",
"namespaces is None: namespaces = {} self.namespaces = namespaces self.expressions = [] self._add(subtree_xpath,",
"# \"a\" - step along the child axis # \"a[@x][@y='1']\" - step along",
"len(numbering) # for k, table in sorted(result.items(), key=lambda x:sorted(x[0])): # print \"State\", sorted(k)",
"= nfa.start_edges[:] any_node = nfa.new_node(None, AnyNodeTest()) for (to_node_id, test) in start_edges: nfa.connect(any_node, to_node_id,",
"-numbering[frozenset(tree.if_false)] else: if_false = 0 else: if_false = len(node_ops) node_ops.append(tree.if_false) namespace, localname =",
"True if isinstance(child_test, NodeTest): # XXX This is wrong. Resolved namespaces can be",
"processingInstruction(self, node, target, data): state = self.stack[-1] if state == -1: return pi_ops",
"is nodetests.processing_instruction_test: node_id = nfa.new_node(None, ProcessingInstructionTest(node_test._target)) elif node_test.__class__ is locationpaths.nodetests.principal_type_test: node_id = nfa.new_node(None,",
"pass def commentMatch(self, node): pass def processingInstructionMatch(self, node): pass class VerbosePushtreeHandler(PushtreeHandler): def __init__(self,",
"for node_op in node_ops: print node_op print \" ATTR OPS\" for attr_op in",
"axis, with two predicates # \"@a\" - step along the attribute axis axis",
"if isinstance(child_test, AnyNodeTest): return True, False if isinstance(child_test, NodeTest): return child_test, False elif",
"_add(self, xpath, xpath_handler): nfa = to_nfa(xpath_parser.parse(xpath), self.namespaces) i = len(self.expressions) nfa.add_handler((i, xpath_handler)) exp",
"(empty)\" else: print s, tree.test, \"?\" self._dump(tree.if_true, depth+1, numbering) self._dump(tree.if_false, depth+1, numbering) def",
"node_id in self.terminal_nodes: self.edges[node_id].extend(other.start_edges) self.terminal_nodes.clear() self.terminal_nodes.update(other.terminal_nodes) self.labeled_handlers.update(other.labeled_handlers) def union(self, other): assert not set(self.edges)",
"handler.endElementMatch(node) def processingInstruction(self, node, target, data): state = self.stack[-1] if state == -1:",
"== \"descendant\": # _add_initial_loop(nfa) #print \"QWERQWER\" #nfa.dump() return nfa if expr.__class__ is amara.xpath.expressions.nodesets.union_expr:",
"def startElementMatch(self, node): print self.prefix+\"startElementMatch\", node def endElementMatch(self, node): print self.prefix+\"endElementMatch\", node def",
"namespaces[prefix] node_id = nfa.new_node(None, klass((namespace, localname), expr.predicates)) elif node_test.__class__ is nodetests.processing_instruction_test: node_id =",
"None), None)) else: die(node_test) nfa.terminal_nodes.add(node_id) #if axis_name == \"descendant\": # _add_initial_loop(nfa) #print \"QWERQWER\"",
"attributes attr_ops = self.machine_states[next_state][2] if not attr_ops: return for namespace, localname in attrs.keys():",
"axisspecifiers from amara.xpath.locationpaths import nodetests from amara.xpath.functions import nodesets from amara.xpath.expressions import booleans",
"print s, \"<>\", numbering[frozenset(tree)], k else: print s, \"<> (empty)\" else: print s,",
"\"All transitions from\", current_dfa transitions = all_transitions(nfa, current_dfa) if not transitions: # Make",
"nfa = to_nfa(xpath_parser.parse(xpath), self.namespaces) i = len(self.expressions) nfa.add_handler((i, xpath_handler)) exp = Expression(i, xpath,",
"#print \"endElementNS\", node, name, qname last_state = self.stack.pop() if last_state == -1: return",
"dfa, numbering = xpm.build_dfa_tables() machine_states = build_instructions(nfa,dfa,numbering) RuleMachineHandler.__init__(self, machine_states, end_node_handler = end_node_handler, attr_handler",
"axis axis = expr.axis axis_name = axis.name assert axis_name in (\"child\", \"descendant\", \"attribute\"),",
"nfa_to_dfa(union_nfa) return build_states(union_nfa, dfa, numbering) class PushtreeManager(object): def __init__(self, subtree_xpath, subtree_handler = None,",
"print dir(expr) for k, v in inspect.getmembers(expr): if k.startswith(\"__\") and k.endswith(\"__\"): continue print",
"nfas_to_machine_states([x._nfa for x in self.expressions]) def build_pushtree_handler(self): return RuleMachineHandler(self._build_machine_states()) # Special handler object",
"name self.op = op self.value = value class AttributeFunctionCallPred(object): def __init__(self, func): self.func",
"testxml = \"\"\"\\ <body> <li>Ignore me<b/></li> <ul> <li x='1'>This <i>is</i> test</li> <li x='2'><a",
"transitions from\", current_dfa transitions = all_transitions(nfa, current_dfa) if not transitions: # Make sure",
"tree.if_false if tree: # Match any attribute attr_ops.append( (None, None, numbering[frozenset(tree)]) ) attr_ops",
"= x print \" HANDLERS\", handlers print \" NODE OPS\" for node_op in",
"any handler events result[current_dfa] = StateTable(match_type, nfa, current_dfa) numbering[current_dfa] = len(numbering) continue #",
"= tree.test.name node_ops[i] = (namespace, localname, None, if_true, if_false) #print \"Added\", node_ops[i] if",
"is not None: assert isinstance(parent_test, ProcessingInstructionTest), parent_test assert isinstance(child_test, ProcessingInstructionTest), child_test if parent_test",
"attributeMatch(self, node): print self.prefix+\"attributeMatch\", node def commentMatch(self, node): print self.prefix+\"commentMatch\", node def processingInstructionMatch(self,",
"always true self._dump(tree.if_true, 0, numbering) def _dump(self, tree, depth, numbering): s = \"-\"*depth",
"= nfa self.nfa_node_ids = nfa_node_ids self.node_tree = Branch(None, set(), set()) self.attr_tree = Branch(None,",
"to_node_id def _add_initial_loop(nfa): start_edges = nfa.start_edges[:] any_node = nfa.new_node(None, AnyNodeTest()) for (to_node_id, test)",
"are different. # XXX check for predicates! if parent_test.name == child_test.name: return True,",
"record match_type = nfa.match_types[node_id] if match_type not in (\"node\", \"record\"): continue new_transitions =",
"sure there's always a target. # This also stores any handler events result[current_dfa]",
"a namespace, like \"a\" node_id = nfa.new_node(None, klass(node_test.name_key, expr.predicates)) elif node_test.__class__ is nodetests.namespace_test:",
"passes or it fails. # TODO: something more sophisticated? For example, if there",
"event): for (to_node_id, test) in edge in nfa_state.edges: if edge[0] == event: yield",
"True, False return False, child_test def comment_intersect(parent_test, child_test): if parent_test is not None:",
"get_edges(self, node_id): if node_id is None: return self.start_edges return self.edges[node_id] def add_handler(self, labeled_handler):",
"startElementNS(self, node, name, qname, attrs): state = self.stack[-1] #print \"startElementNS\", name, qname, attrs,",
"we only support downward axes # and these have no downward axes. (XXX",
"for node_id in self.terminal_nodes: self.edges[node_id].extend(other.start_edges) self.terminal_nodes.clear() self.terminal_nodes.update(other.terminal_nodes) self.labeled_handlers.update(other.labeled_handlers) def union(self, other): assert not",
"klass((None, None), None)) else: die(node_test) nfa.terminal_nodes.add(node_id) #if axis_name == \"descendant\": # _add_initial_loop(nfa) #print",
"to get # the attribute node handler.attributeMatch( (node, (namespace, localname) ) ) def",
"find the # actual instances I need except the startElement and # endElement",
"VerbosePushtreeHandler(\"//a\")) manager.expressions[2]._nfa.dump() manager.add(\"@x\", VerbosePushtreeHandler(\"@x\")) manager.expressions[3]._nfa.dump() manager.add(\"a\", VerbosePushtreeHandler(\"a\")) manager.expressions[4]._nfa.dump() #manager.add(\".//*\") machine_states = manager._build_machine_states() dump_machine_states(machine_states)",
"(node_id in self.terminal_nodes) else \"\" print node_name, is_terminal, labels self._dump_edges(edges) print \"======\" def",
"pi_ops.append( (None, numbering[frozenset(tree)]) ) pi_ops = tuple(pi_ops) # comment tree tree = table.comment_tree.if_true",
"or so. class Branch(object): def __init__(self, test, if_true, if_false): self.test = test self.if_true",
"test), ...] self.terminal_nodes = set() # The start node has no type self.match_types",
"(\"child\", \"descendant\", \"attribute\"), axis_name if axis_name == \"attribute\": klass = AttributeTest else: klass",
"nfa_node_ids): self.match_type = match_type # 'None' for the start node self.nfa = nfa",
"AttributeTest): self._add(self.attr_tree, test, to_node_id, attr_intersect) elif isinstance(test, ProcessingInstructionTest): self._add(self.pi_tree, test, to_node_id, pi_intersect) elif",
"the same even # if the namespace fields are different. # XXX check",
"isinstance(node, set): if node: result[frozenset(node)] = match_type elif node is not None: visit.append(node.if_true)",
"not None: visit.append(node.if_true) visit.append(node.if_false) return result.items() def dump(self, numbering): # Do I report",
"= axis.name assert axis_name in (\"child\", \"descendant\"), axis_name subnfa = to_nfa(step, namespaces) if",
"print self.prefix+\"endElementMatch\", node def attributeMatch(self, node): print self.prefix+\"attributeMatch\", node def commentMatch(self, node): print",
"attr_handler) def dump_machine_states(machine_states): for i, x in enumerate(machine_states): print \"== INFO FOR\", i,",
"self.stack.append(-1) return element_ops = self.machine_states[state][1] if not element_ops: # This was a valid",
"else: prefix = \"(%s) \" % (prefix,) self.prefix = prefix def startSubtree(self, element):",
"hack until I can figure out how to get # the attribute node",
"[(to_node_id, test), ...] self.terminal_nodes = set() # The start node has no type",
"(expr.__class__ is locationpaths.absolute_location_path): # This is an absolute path like # \"/a\", \"/a[0]/b[@x]\"",
"prefix, localname = node_test.name_key namespace = namespaces[prefix] node_id = nfa.new_node(None, klass((namespace, localname), expr.predicates))",
"current_dfa: if node_id is None: new_transitions = nfa.start_edges else: # XXX I can't",
"frozenset(nfa_nodes) if some_dfa not in seen: seen.add(some_dfa) todo.append( (some_dfa, match_type) ) result[current_dfa] =",
"node_test.__class__ is nodetests.processing_instruction_test: node_id = nfa.new_node(None, ProcessingInstructionTest(node_test._target)) elif node_test.__class__ is locationpaths.nodetests.principal_type_test: node_id =",
"in start_edges: nfa.connect(any_node, to_node_id, test) nfa.connect(any_node, any_node, AnyNodeTest()) # loop def to_nfa(expr, namespaces):",
"self.terminal_nodes: self.labeled_handlers[node_id].append(labeled_handler) def new_node(self, from_node_id, test): edges = self.get_edges(from_node_id) to_node_id = next(counter) self.edges[to_node_id]",
"is None: return self.start_edges return self.edges[node_id] def add_handler(self, labeled_handler): for node_id in self.terminal_nodes:",
"def add(self, xpath, xpath_handler=None): return self._add(xpath, xpath_handler) def _build_machine_states(self): return nfas_to_machine_states([x._nfa for x",
"numbering): # unique node numbers states = [] for dfa_id, node_ids in sorted(",
"name, \"tree\" else: print name, \"tree:\" # The first branch is always true",
"nfa, nfa_node_ids): self.match_type = match_type # 'None' for the start node self.nfa =",
"in node_ids: for (label, handler) in nfa.labeled_handlers[node_id]: handler_map[label] = handler # This are",
"self.expressions = [] self._add(subtree_xpath, subtree_handler) def _add(self, xpath, xpath_handler): nfa = to_nfa(xpath_parser.parse(xpath), self.namespaces)",
"nfa def get_edges(self, node_id): if node_id is None: return self.start_edges return self.edges[node_id] def",
"machine_states def startDocument(self,node): self.stack = [0] #dump_machine_states(self.machine_states) def startElementNS(self, node, name, qname, attrs):",
"= xpm = ExpressionManager(namespaces=namespaces); xpm.add(pattern) nfa, dfa, numbering = xpm.build_dfa_tables() machine_states = build_instructions(nfa,dfa,numbering)",
"self._add(tree.if_true, new_true_test, to_node_id, intersect) if new_false_test == True: self._add_to_leaves(tree.if_false, to_node_id) elif new_false_test: if",
"in seen: seen.add(some_dfa) todo.append( (some_dfa, match_type) ) result[current_dfa] = state_table numbering[current_dfa] = len(numbering)",
"table.dump() return result, numbering def die(expr): import inspect print \" == FAILURE ==\"",
"labeled_handler): for node_id in self.terminal_nodes: self.labeled_handlers[node_id].append(labeled_handler) def new_node(self, from_node_id, test): edges = self.get_edges(from_node_id)",
"XPath 1.0, where this is a string if parent_test.target == child_test.target: return True,",
"self.predicates = predicates def __str__(self): return \"Attr name=%r\" % (self.name,) class ProcessingInstructionTest(object): match_type",
"so. class Branch(object): def __init__(self, test, if_true, if_false): self.test = test self.if_true =",
"attr_ops: return for namespace, localname in attrs.keys(): for (ns, ln, attr_state_id) in attr_ops:",
"def __init__(self, name, predicates): self.name = name assert not predicates self.predicates = predicates",
"else: die(node_test) nfa.terminal_nodes.add(node_id) #if axis_name == \"descendant\": # _add_initial_loop(nfa) #print \"QWERQWER\" #nfa.dump() return",
"new_transitions = nfa.edges[node_id] transitions.extend(new_transitions) return transitions def transition(nfa_state, event): for (to_node_id, test) in",
"The start node has no type self.match_types = {} # node_id -> match_type",
"else \"\" print node_name, is_terminal, labels self._dump_edges(edges) print \"======\" def _dump_edges(self, edges): for",
"node handler.attributeMatch( (node, (namespace, localname) ) ) def endElementNS(self, node, name, qname): #print",
"if (node_id in self.terminal_nodes) else \"\" print node_name, is_terminal, labels self._dump_edges(edges) print \"======\"",
"nfa.add_handler((i, xpath_handler)) exp = Expression(i, xpath, nfa) self.expressions.append(exp) return exp def add(self, xpath,",
"get # the attribute node handler.attributeMatch( (node, (namespace, localname) ) ) def endElementNS(self,",
"None if ((ns is None or ns == namespace) and (ln is None",
"self.prefix+\"commentMatch\", node def processingInstructionMatch(self, node): print self.prefix+\"processingInstructionMatch\", node if __name__ == '__main__': testxml",
"node, name, qname last_state = self.stack.pop() if last_state == -1: return handlers =",
"= nfa.new_node(None, ProcessingInstructionTest(node_test._target)) elif node_test.__class__ is locationpaths.nodetests.principal_type_test: node_id = nfa.new_node(None, klass((None, None), None))",
"for dfa_id, node_ids in sorted( (dfa_id, node_ids) for (node_ids, dfa_id) in numbering.items() ):",
"self.labeled_handlers[to_node_id] = [] edges.append( (to_node_id, test) ) return to_node_id def connect(self, from_node_id, to_node_id,",
"(self.name[0], self.name[1], self.predicates) # predicates make no sense here because we only support",
"element): print self.prefix+\"endSubtree\", element def startElementMatch(self, node): print self.prefix+\"startElementMatch\", node def endElementMatch(self, node):",
"node_ids in sorted( (dfa_id, node_ids) for (node_ids, dfa_id) in numbering.items() ): assert dfa_id",
"x='2'><a href='spam'>that</a> was nothing</li> </ul> </body> \"\"\" manager = PushtreeManager(\"body/ul/li\", VerbosePushtreeHandler(\"main\")) manager.expressions[0]._nfa.dump() manager.add(\"pre/post\",",
"pairs) table = dfa[node_ids] if dfa_id == 0: handlers = () else: handler_map",
"This is an absolute path like # \"/a\", \"/a[0]/b[@x]\" nfa = NFA() for",
"namespaces can be the same even # if the namespace fields are different.",
"tree = tree.if_false if tree: pi_ops.append( (None, numbering[frozenset(tree)]) ) pi_ops = tuple(pi_ops) #",
"comments #class AnyTest(object): # pass class BaseNodeTest(object): match_type = \"node\" # What about",
"inspect print \" == FAILURE ==\" print type(expr) print dir(expr) for k, v",
"def commentMatch(self, node): pass def processingInstructionMatch(self, node): pass class VerbosePushtreeHandler(PushtreeHandler): def __init__(self, prefix=None):",
"test in transitions: state_table.add(test, to_node_id) for nfa_nodes, match_type in state_table.get_final_nodes(): some_dfa = frozenset(nfa_nodes)",
"is amara.xpath.expressions.nodesets.union_expr: # \"a|b\" nfa = to_nfa(expr._paths[0], namespaces) for path in expr._paths[1:]: nfa.union(to_nfa(path,",
"class Expression(object): def __init__(self, id, xpath, nfa): self.id = id self.xpath = xpath",
"# loop def to_nfa(expr, namespaces): #print \"Eval\", expr.__class__ if (expr.__class__ is locationpaths.relative_location_path): #",
"0, numbering) def _dump(self, tree, depth, numbering): s = \"-\"*depth if isinstance(tree, set):",
"to make a decision tree. Either the test passes or it fails. #",
"AttributeTest), parent_test assert isinstance(child_test, AttributeTest), child_test if parent_test is None: return child_test, False",
"tree.if_true) tree.if_true = new_branch else: self._add(tree.if_true, new_true_test, to_node_id, intersect) if new_false_test == True:",
"all_transitions(nfa, current_dfa) if not transitions: # Make sure there's always a target. #",
"(namespace, localname) # This is a hack until I can figure out how",
"node_ops[i] = (namespace, localname, None, if_true, if_false) #print \"Added\", node_ops[i] if if_false >",
"# processing instruction tree pi_ops = [] tree = table.pi_tree.if_true while not isinstance(tree,",
"yield nodes, attribute, PIs, and comments #class AnyTest(object): # pass class BaseNodeTest(object): match_type",
"\"state\", state if state == -1: #print \"goto -1\" self.stack.append(-1) return element_ops =",
"= nfa.new_node(None, klass((namespace, localname), expr.predicates)) elif node_test.__class__ is nodetests.processing_instruction_test: node_id = nfa.new_node(None, ProcessingInstructionTest(node_test._target))",
"\" COMMENT STATE =\", comment_state class PushtreeHandler(object): def startSubtree(self, element): pass def endSubtree(self,",
"startElementMatch(self, node): print self.prefix+\"startElementMatch\", node def endElementMatch(self, node): print self.prefix+\"endElementMatch\", node def attributeMatch(self,",
"def nfa_to_dfa(nfa): numbering = {} # from frozenset -> 0, 1, 2, ...",
"print self.prefix+\"startSubtree\", element def endSubtree(self, element): print self.prefix+\"endSubtree\", element def startElementMatch(self, node): print",
"= name self.predicates = predicates def __str__(self): return \"Node ns=%r localname=%r predicates=%r\" %",
"assert axis_name in (\"child\", \"descendant\"), axis_name subnfa = to_nfa(step, namespaces) if axis_name ==",
"def endElementMatch(self, node): print self.prefix+\"endElementMatch\", node def attributeMatch(self, node): print self.prefix+\"attributeMatch\", node def",
"def _add_to_leaves(self, tree, to_node_id): if isinstance(tree, set): tree.add(to_node_id) else: self._add_to_leaves(tree.if_true, to_node_id) self._add_to_leaves(tree.if_false, to_node_id)",
"else: print s, \"<> (empty)\" else: print s, tree.test, \"?\" self._dump(tree.if_true, depth+1, numbering)",
"tags)) performance # instead of O(n). However, for now, n is no more",
"None), expr.predicates)) elif node_test.__class__ is nodetests.qualified_name_test: prefix, localname = node_test.name_key namespace = namespaces[prefix]",
"large number of element tag tests then sort the tags and start #",
"from it #print \"GOTO -1\" self.stack.append(-1) return namespace, localname = name i =",
"None: return self.start_edges return self.edges[node_id] def add_handler(self, labeled_handler): for node_id in self.terminal_nodes: self.labeled_handlers[node_id].append(labeled_handler)",
"for handler in handlers: handler.processingInstruction(node) # For Dave class RulePatternHandler(RuleMachineHandler): def __init__(self, pattern,",
"predicates=%r\" % (self.name[0], self.name[1], self.predicates) # predicates make no sense here because we",
"__str__(self): return \"Attr name=%r\" % (self.name,) class ProcessingInstructionTest(object): match_type = \"processing-instruction\" def __init__(self,",
"# XXX I can't transition from something # which wasn't a node or",
"set): if tree.if_true: if_true = -numbering[frozenset(tree.if_true)] else: if_true = 0 else: if_true =",
"step.axis axis_name = axis.name assert axis_name in (\"child\", \"descendant\"), axis_name subnfa = to_nfa(step,",
"and the # 0 node is defined to have no attributes self.stack.append(-1) return",
"+ sorted(self.edges.items()): if node_id is None: node_name = \"(start)\" labels = \"\" else:",
"CommentTest): self._add(self.comment_tree, test, to_node_id, comment_intersect) else: raise AssertionError(test) def _add(self, tree, test, to_node_id,",
"if new_true_test == True: self._add_to_leaves(tree.if_true, to_node_id) elif new_true_test: if isinstance(tree.if_true, set): new_branch =",
"processing instruction tree pi_ops = [] tree = table.pi_tree.if_true while not isinstance(tree, set):",
"= 0 else: if_true = len(node_ops) node_ops.append(tree.if_true) if isinstance(tree.if_false, set): if tree.if_false: if_false",
"start node has no type self.match_types = {} # node_id -> match_type self.labeled_handlers",
"set): # Special case when there are no decisions to make if not",
"off from it #print \"GOTO -1\" self.stack.append(-1) return namespace, localname = name i",
"edges.append( (to_node_id, test) ) return to_node_id def connect(self, from_node_id, to_node_id, test): self.get_edges(from_node_id).append( (to_node_id,",
"return pi_ops = self.machine_states[state][3] for (pi_target, pi_state) in pi_ops: if pi_target == target:",
"data): state = self.stack[-1] if state == -1: return pi_ops = self.machine_states[state][3] for",
"nfa.edges.update(self.edges) nfa.terminal_nodes.update(self.terminal_nodes) nfa.match_types.update(self.match_types) nfa.labeled_handlers.update(self.labeled_handlers) return nfa def get_edges(self, node_id): if node_id is None:",
"amara.xpath.expressions import booleans import amara.xpath.expressions.nodesets # another nodesets! from amara.xpath.expressions import basics counter",
"= nfa.new_node(None, klass(node_test.name_key, expr.predicates)) elif node_test.__class__ is nodetests.namespace_test: # Namespace but no name,",
"branch is always true self._dump(tree.if_true, 0, numbering) def _dump(self, tree, depth, numbering): s",
"(which are in (id, class) pairs) table = dfa[node_ids] if dfa_id == 0:",
"== 0: handlers = () else: handler_map = {} for node_id in node_ids:",
"-> match_type self.labeled_handlers = {} # node_id -> (label, PushtreeHandler) def copy(self): nfa",
"Special case when there are no decisions to make if not tree: node_ops",
"locationpaths.nodetests.principal_type_test: node_id = nfa.new_node(None, klass((None, None), None)) else: die(node_test) nfa.terminal_nodes.add(node_id) #if axis_name ==",
"new_false_test, to_node_id, intersect) def _add_to_leaves(self, tree, to_node_id): if isinstance(tree, set): tree.add(to_node_id) else: self._add_to_leaves(tree.if_true,",
"\"\"\"\\ <body> <li>Ignore me<b/></li> <ul> <li x='1'>This <i>is</i> test</li> <li x='2'><a href='spam'>that</a> was"
] |
[
"via iteration count = 1 for line in self.tail: assert_that(line, equal_to(u'This is message",
"def teardown_method(self, method): # Revert logger stuff self.handler.close() self.handler = None self.logger =",
"# Check the cache directly to make sure messages were decoded. for i",
"# Revert logger stuff self.handler.close() self.handler = None self.logger = None # Kill",
"self.tail: assert_that(line, equal_to(u'This is message #%s\\x00' % count)) count += 1 # Check",
"time.sleep(0.1) # Release GIL so async listener can \"hear\" the DGRAMs count =",
"assert_that(self.tail.cache, has_length(0)) # TODO: test_overall doesn't work if there are other tests run",
"will cause test_overall to fail if run...so skipped for now. @disabled_test def test_addresses(self):",
"if run...so skipped for now. @disabled_test def test_addresses(self): assert_that(('localhost', 514), is_in(SYSLOG_ADDRESSES)) @disabled_test def",
"was cleared after iteration assert_that(self.tail.cache, has_length(0)) # TODO: test_overall doesn't work if there",
"message #%s\\x00' % count)) count += 1 # Check that cache was cleared",
"self.logger = None # Kill the SyslogTail self.tail.stop() self.tail = None def test_overall(self):",
"logger self.logger = logging.getLogger(self.__class__.__name__) self.logger.setLevel(logging.DEBUG) self.handler = SysLogHandler(address=('localhost', 514)) self.handler.setFormatter(logging.Formatter(' amplify: %(message)s')) self.logger.addHandler(self.handler)",
"logging.handlers import SysLogHandler from hamcrest import * from amplify.agent.pipelines.syslog import SyslogTail, SYSLOG_ADDRESSES, AmplifyAddresssAlreadyInUse",
"import time import logging from logging.handlers import SysLogHandler from hamcrest import * from",
"1 time.sleep(0.1) # Release GIL so async listener can handle DGRAMs # Check",
"count = 1 while count <= 5: self.logger.debug('This is message #%s' % count)",
"iteration count = 1 for line in self.tail: assert_that(line, equal_to(u'This is message #%s\\x00'",
"so async listener can \"hear\" the DGRAMs count = 1 while count <=",
"line in self.tail: assert_that(line, equal_to(u'This is message #%s\\x00' % count)) count += 1",
"def setup_method(self, method): super(SyslogTailTestCase, self).setup_method(method) self.tail = SyslogTail(address=('localhost', 514), interval=0.1) # Set up",
"\"Copyright (C) Nginx, Inc. All rights reserved.\" __license__ = \"\" __maintainer__ = \"<NAME>\"",
"#%s' % count) count += 1 time.sleep(0.1) # Release GIL so async listener",
"sure messages were decoded. for i in range(5): assert_that(self.tail.cache[i], equal_to(u'This is message #%s\\x00'",
"# Check that cache was cleared after iteration assert_that(self.tail.cache, has_length(0)) # TODO: test_overall",
"up python logger self.logger = logging.getLogger(self.__class__.__name__) self.logger.setLevel(logging.DEBUG) self.handler = SysLogHandler(address=('localhost', 514)) self.handler.setFormatter(logging.Formatter(' amplify:",
"# Kill the SyslogTail self.tail.stop() self.tail = None def test_overall(self): time.sleep(0.1) # Release",
"1 # Check that cache was cleared after iteration assert_that(self.tail.cache, has_length(0)) # TODO:",
"AmplifyAddresssAlreadyInUse from test.base import BaseTestCase, disabled_test __author__ = \"<NAME>\" __copyright__ = \"Copyright (C)",
"time.sleep(0.1) # Release GIL so async listener can handle DGRAMs # Check to",
"Check to see that SyslogListener read 5 messages assert_that(self.tail.cache, has_length(count-1)) # Check the",
"super(SyslogTailTestCase, self).setup_method(method) self.tail = SyslogTail(address=('localhost', 514), interval=0.1) # Set up python logger self.logger",
"Release GIL so async listener can handle DGRAMs # Check to see that",
"has_length(count-1)) # Check the cache directly to make sure messages were decoded. for",
"import SyslogTail, SYSLOG_ADDRESSES, AmplifyAddresssAlreadyInUse from test.base import BaseTestCase, disabled_test __author__ = \"<NAME>\" __copyright__",
"test.base import BaseTestCase, disabled_test __author__ = \"<NAME>\" __copyright__ = \"Copyright (C) Nginx, Inc.",
"#%s\\x00' % count)) count += 1 # Check that cache was cleared after",
"with it...why? # The tests below pass, but will cause test_overall to fail",
"SyslogTail self.tail.stop() self.tail = None def test_overall(self): time.sleep(0.1) # Release GIL so async",
"test_overall(self): time.sleep(0.1) # Release GIL so async listener can \"hear\" the DGRAMs count",
"so async listener can handle DGRAMs # Check to see that SyslogListener read",
"@disabled_test def test_addresses(self): assert_that(('localhost', 514), is_in(SYSLOG_ADDRESSES)) @disabled_test def test_socket_conflict(self): assert_that( calling(SyslogTail).with_args(address=('localhost', 514)), raises(AmplifyAddresssAlreadyInUse)",
"\"hear\" the DGRAMs count = 1 while count <= 5: self.logger.debug('This is message",
"time import logging from logging.handlers import SysLogHandler from hamcrest import * from amplify.agent.pipelines.syslog",
"self.logger.addHandler(self.handler) def teardown_method(self, method): # Revert logger stuff self.handler.close() self.handler = None self.logger",
"count <= 5: self.logger.debug('This is message #%s' % count) count += 1 time.sleep(0.1)",
"count)) count += 1 # Check that cache was cleared after iteration assert_that(self.tail.cache,",
"tests run with it...why? # The tests below pass, but will cause test_overall",
"import logging from logging.handlers import SysLogHandler from hamcrest import * from amplify.agent.pipelines.syslog import",
"interval=0.1) # Set up python logger self.logger = logging.getLogger(self.__class__.__name__) self.logger.setLevel(logging.DEBUG) self.handler = SysLogHandler(address=('localhost',",
"cause test_overall to fail if run...so skipped for now. @disabled_test def test_addresses(self): assert_that(('localhost',",
"% count)) count += 1 # Check that cache was cleared after iteration",
"# Release GIL so async listener can \"hear\" the DGRAMs count = 1",
"count += 1 time.sleep(0.1) # Release GIL so async listener can handle DGRAMs",
"# Release GIL so async listener can handle DGRAMs # Check to see",
"cache directly to make sure messages were decoded. for i in range(5): assert_that(self.tail.cache[i],",
"make sure messages were decoded. for i in range(5): assert_that(self.tail.cache[i], equal_to(u'This is message",
"__maintainer__ = \"<NAME>\" __email__ = \"<EMAIL>\" class SyslogTailTestCase(BaseTestCase): def setup_method(self, method): super(SyslogTailTestCase, self).setup_method(method)",
"now. @disabled_test def test_addresses(self): assert_that(('localhost', 514), is_in(SYSLOG_ADDRESSES)) @disabled_test def test_socket_conflict(self): assert_that( calling(SyslogTail).with_args(address=('localhost', 514)),",
"GIL so async listener can handle DGRAMs # Check to see that SyslogListener",
"\"\" __maintainer__ = \"<NAME>\" __email__ = \"<EMAIL>\" class SyslogTailTestCase(BaseTestCase): def setup_method(self, method): super(SyslogTailTestCase,",
"Check that cache was cleared after iteration assert_that(self.tail.cache, has_length(0)) # TODO: test_overall doesn't",
"there are other tests run with it...why? # The tests below pass, but",
"<= 5: self.logger.debug('This is message #%s' % count) count += 1 time.sleep(0.1) #",
"# Go through and check the messages via iteration count = 1 for",
"1 while count <= 5: self.logger.debug('This is message #%s' % count) count +=",
"equal_to(u'This is message #%s\\x00' % (i+1))) # Go through and check the messages",
"% (i+1))) # Go through and check the messages via iteration count =",
"self.handler.close() self.handler = None self.logger = None # Kill the SyslogTail self.tail.stop() self.tail",
"method): # Revert logger stuff self.handler.close() self.handler = None self.logger = None #",
"-*- import time import logging from logging.handlers import SysLogHandler from hamcrest import *",
"setup_method(self, method): super(SyslogTailTestCase, self).setup_method(method) self.tail = SyslogTail(address=('localhost', 514), interval=0.1) # Set up python",
"were decoded. for i in range(5): assert_that(self.tail.cache[i], equal_to(u'This is message #%s\\x00' % (i+1)))",
"async listener can \"hear\" the DGRAMs count = 1 while count <= 5:",
"run...so skipped for now. @disabled_test def test_addresses(self): assert_that(('localhost', 514), is_in(SYSLOG_ADDRESSES)) @disabled_test def test_socket_conflict(self):",
"= \"\" __maintainer__ = \"<NAME>\" __email__ = \"<EMAIL>\" class SyslogTailTestCase(BaseTestCase): def setup_method(self, method):",
"listener can \"hear\" the DGRAMs count = 1 while count <= 5: self.logger.debug('This",
"GIL so async listener can \"hear\" the DGRAMs count = 1 while count",
"Set up python logger self.logger = logging.getLogger(self.__class__.__name__) self.logger.setLevel(logging.DEBUG) self.handler = SysLogHandler(address=('localhost', 514)) self.handler.setFormatter(logging.Formatter('",
"def test_overall(self): time.sleep(0.1) # Release GIL so async listener can \"hear\" the DGRAMs",
"if there are other tests run with it...why? # The tests below pass,",
"test_overall to fail if run...so skipped for now. @disabled_test def test_addresses(self): assert_that(('localhost', 514),",
"#%s\\x00' % (i+1))) # Go through and check the messages via iteration count",
"doesn't work if there are other tests run with it...why? # The tests",
"logging from logging.handlers import SysLogHandler from hamcrest import * from amplify.agent.pipelines.syslog import SyslogTail,",
"read 5 messages assert_that(self.tail.cache, has_length(count-1)) # Check the cache directly to make sure",
"514)) self.handler.setFormatter(logging.Formatter(' amplify: %(message)s')) self.logger.addHandler(self.handler) def teardown_method(self, method): # Revert logger stuff self.handler.close()",
"self.handler = SysLogHandler(address=('localhost', 514)) self.handler.setFormatter(logging.Formatter(' amplify: %(message)s')) self.logger.addHandler(self.handler) def teardown_method(self, method): # Revert",
"after iteration assert_that(self.tail.cache, has_length(0)) # TODO: test_overall doesn't work if there are other",
"5 messages assert_that(self.tail.cache, has_length(count-1)) # Check the cache directly to make sure messages",
"= \"Copyright (C) Nginx, Inc. All rights reserved.\" __license__ = \"\" __maintainer__ =",
"other tests run with it...why? # The tests below pass, but will cause",
"# -*- coding: utf-8 -*- import time import logging from logging.handlers import SysLogHandler",
"run with it...why? # The tests below pass, but will cause test_overall to",
"+= 1 # Check that cache was cleared after iteration assert_that(self.tail.cache, has_length(0)) #",
"work if there are other tests run with it...why? # The tests below",
"see that SyslogListener read 5 messages assert_that(self.tail.cache, has_length(count-1)) # Check the cache directly",
"SyslogListener read 5 messages assert_that(self.tail.cache, has_length(count-1)) # Check the cache directly to make",
"handle DGRAMs # Check to see that SyslogListener read 5 messages assert_that(self.tail.cache, has_length(count-1))",
"utf-8 -*- import time import logging from logging.handlers import SysLogHandler from hamcrest import",
"self).setup_method(method) self.tail = SyslogTail(address=('localhost', 514), interval=0.1) # Set up python logger self.logger =",
"has_length(0)) # TODO: test_overall doesn't work if there are other tests run with",
"to fail if run...so skipped for now. @disabled_test def test_addresses(self): assert_that(('localhost', 514), is_in(SYSLOG_ADDRESSES))",
"python logger self.logger = logging.getLogger(self.__class__.__name__) self.logger.setLevel(logging.DEBUG) self.handler = SysLogHandler(address=('localhost', 514)) self.handler.setFormatter(logging.Formatter(' amplify: %(message)s'))",
"listener can handle DGRAMs # Check to see that SyslogListener read 5 messages",
"from amplify.agent.pipelines.syslog import SyslogTail, SYSLOG_ADDRESSES, AmplifyAddresssAlreadyInUse from test.base import BaseTestCase, disabled_test __author__ =",
"514), interval=0.1) # Set up python logger self.logger = logging.getLogger(self.__class__.__name__) self.logger.setLevel(logging.DEBUG) self.handler =",
"cache was cleared after iteration assert_that(self.tail.cache, has_length(0)) # TODO: test_overall doesn't work if",
"(C) Nginx, Inc. All rights reserved.\" __license__ = \"\" __maintainer__ = \"<NAME>\" __email__",
"self.handler.setFormatter(logging.Formatter(' amplify: %(message)s')) self.logger.addHandler(self.handler) def teardown_method(self, method): # Revert logger stuff self.handler.close() self.handler",
"amplify: %(message)s')) self.logger.addHandler(self.handler) def teardown_method(self, method): # Revert logger stuff self.handler.close() self.handler =",
"= \"<NAME>\" __copyright__ = \"Copyright (C) Nginx, Inc. All rights reserved.\" __license__ =",
"SyslogTail(address=('localhost', 514), interval=0.1) # Set up python logger self.logger = logging.getLogger(self.__class__.__name__) self.logger.setLevel(logging.DEBUG) self.handler",
"the SyslogTail self.tail.stop() self.tail = None def test_overall(self): time.sleep(0.1) # Release GIL so",
"Go through and check the messages via iteration count = 1 for line",
"class SyslogTailTestCase(BaseTestCase): def setup_method(self, method): super(SyslogTailTestCase, self).setup_method(method) self.tail = SyslogTail(address=('localhost', 514), interval=0.1) #",
"reserved.\" __license__ = \"\" __maintainer__ = \"<NAME>\" __email__ = \"<EMAIL>\" class SyslogTailTestCase(BaseTestCase): def",
"hamcrest import * from amplify.agent.pipelines.syslog import SyslogTail, SYSLOG_ADDRESSES, AmplifyAddresssAlreadyInUse from test.base import BaseTestCase,",
"\"<EMAIL>\" class SyslogTailTestCase(BaseTestCase): def setup_method(self, method): super(SyslogTailTestCase, self).setup_method(method) self.tail = SyslogTail(address=('localhost', 514), interval=0.1)",
"for line in self.tail: assert_that(line, equal_to(u'This is message #%s\\x00' % count)) count +=",
"import * from amplify.agent.pipelines.syslog import SyslogTail, SYSLOG_ADDRESSES, AmplifyAddresssAlreadyInUse from test.base import BaseTestCase, disabled_test",
"= 1 for line in self.tail: assert_that(line, equal_to(u'This is message #%s\\x00' % count))",
"self.logger.setLevel(logging.DEBUG) self.handler = SysLogHandler(address=('localhost', 514)) self.handler.setFormatter(logging.Formatter(' amplify: %(message)s')) self.logger.addHandler(self.handler) def teardown_method(self, method): #",
"self.logger = logging.getLogger(self.__class__.__name__) self.logger.setLevel(logging.DEBUG) self.handler = SysLogHandler(address=('localhost', 514)) self.handler.setFormatter(logging.Formatter(' amplify: %(message)s')) self.logger.addHandler(self.handler) def",
"__email__ = \"<EMAIL>\" class SyslogTailTestCase(BaseTestCase): def setup_method(self, method): super(SyslogTailTestCase, self).setup_method(method) self.tail = SyslogTail(address=('localhost',",
"__author__ = \"<NAME>\" __copyright__ = \"Copyright (C) Nginx, Inc. All rights reserved.\" __license__",
"BaseTestCase, disabled_test __author__ = \"<NAME>\" __copyright__ = \"Copyright (C) Nginx, Inc. All rights",
"= \"<EMAIL>\" class SyslogTailTestCase(BaseTestCase): def setup_method(self, method): super(SyslogTailTestCase, self).setup_method(method) self.tail = SyslogTail(address=('localhost', 514),",
"-*- coding: utf-8 -*- import time import logging from logging.handlers import SysLogHandler from",
"+= 1 time.sleep(0.1) # Release GIL so async listener can handle DGRAMs #",
"Check the cache directly to make sure messages were decoded. for i in",
"it...why? # The tests below pass, but will cause test_overall to fail if",
"DGRAMs # Check to see that SyslogListener read 5 messages assert_that(self.tail.cache, has_length(count-1)) #",
"def test_addresses(self): assert_that(('localhost', 514), is_in(SYSLOG_ADDRESSES)) @disabled_test def test_socket_conflict(self): assert_that( calling(SyslogTail).with_args(address=('localhost', 514)), raises(AmplifyAddresssAlreadyInUse) )",
"disabled_test __author__ = \"<NAME>\" __copyright__ = \"Copyright (C) Nginx, Inc. All rights reserved.\"",
"assert_that(line, equal_to(u'This is message #%s\\x00' % count)) count += 1 # Check that",
"that cache was cleared after iteration assert_that(self.tail.cache, has_length(0)) # TODO: test_overall doesn't work",
"while count <= 5: self.logger.debug('This is message #%s' % count) count += 1",
"decoded. for i in range(5): assert_that(self.tail.cache[i], equal_to(u'This is message #%s\\x00' % (i+1))) #",
"the cache directly to make sure messages were decoded. for i in range(5):",
"* from amplify.agent.pipelines.syslog import SyslogTail, SYSLOG_ADDRESSES, AmplifyAddresssAlreadyInUse from test.base import BaseTestCase, disabled_test __author__",
"SyslogTail, SYSLOG_ADDRESSES, AmplifyAddresssAlreadyInUse from test.base import BaseTestCase, disabled_test __author__ = \"<NAME>\" __copyright__ =",
"below pass, but will cause test_overall to fail if run...so skipped for now.",
"coding: utf-8 -*- import time import logging from logging.handlers import SysLogHandler from hamcrest",
"is message #%s\\x00' % (i+1))) # Go through and check the messages via",
"1 for line in self.tail: assert_that(line, equal_to(u'This is message #%s\\x00' % count)) count",
"count += 1 # Check that cache was cleared after iteration assert_that(self.tail.cache, has_length(0))",
"__copyright__ = \"Copyright (C) Nginx, Inc. All rights reserved.\" __license__ = \"\" __maintainer__",
"Kill the SyslogTail self.tail.stop() self.tail = None def test_overall(self): time.sleep(0.1) # Release GIL",
"from test.base import BaseTestCase, disabled_test __author__ = \"<NAME>\" __copyright__ = \"Copyright (C) Nginx,",
"teardown_method(self, method): # Revert logger stuff self.handler.close() self.handler = None self.logger = None",
"and check the messages via iteration count = 1 for line in self.tail:",
"cleared after iteration assert_that(self.tail.cache, has_length(0)) # TODO: test_overall doesn't work if there are",
"Inc. All rights reserved.\" __license__ = \"\" __maintainer__ = \"<NAME>\" __email__ = \"<EMAIL>\"",
"in self.tail: assert_that(line, equal_to(u'This is message #%s\\x00' % count)) count += 1 #",
"check the messages via iteration count = 1 for line in self.tail: assert_that(line,",
"None # Kill the SyslogTail self.tail.stop() self.tail = None def test_overall(self): time.sleep(0.1) #",
"= None self.logger = None # Kill the SyslogTail self.tail.stop() self.tail = None",
"count) count += 1 time.sleep(0.1) # Release GIL so async listener can handle",
"= SysLogHandler(address=('localhost', 514)) self.handler.setFormatter(logging.Formatter(' amplify: %(message)s')) self.logger.addHandler(self.handler) def teardown_method(self, method): # Revert logger",
"messages via iteration count = 1 for line in self.tail: assert_that(line, equal_to(u'This is",
"# Check to see that SyslogListener read 5 messages assert_that(self.tail.cache, has_length(count-1)) # Check",
"# Set up python logger self.logger = logging.getLogger(self.__class__.__name__) self.logger.setLevel(logging.DEBUG) self.handler = SysLogHandler(address=('localhost', 514))",
"= None def test_overall(self): time.sleep(0.1) # Release GIL so async listener can \"hear\"",
"# The tests below pass, but will cause test_overall to fail if run...so",
"self.handler = None self.logger = None # Kill the SyslogTail self.tail.stop() self.tail =",
"= None # Kill the SyslogTail self.tail.stop() self.tail = None def test_overall(self): time.sleep(0.1)",
"The tests below pass, but will cause test_overall to fail if run...so skipped",
"import SysLogHandler from hamcrest import * from amplify.agent.pipelines.syslog import SyslogTail, SYSLOG_ADDRESSES, AmplifyAddresssAlreadyInUse from",
"logger stuff self.handler.close() self.handler = None self.logger = None # Kill the SyslogTail",
"equal_to(u'This is message #%s\\x00' % count)) count += 1 # Check that cache",
"# TODO: test_overall doesn't work if there are other tests run with it...why?",
"but will cause test_overall to fail if run...so skipped for now. @disabled_test def",
"= SyslogTail(address=('localhost', 514), interval=0.1) # Set up python logger self.logger = logging.getLogger(self.__class__.__name__) self.logger.setLevel(logging.DEBUG)",
"iteration assert_that(self.tail.cache, has_length(0)) # TODO: test_overall doesn't work if there are other tests",
"pass, but will cause test_overall to fail if run...so skipped for now. @disabled_test",
"assert_that(self.tail.cache[i], equal_to(u'This is message #%s\\x00' % (i+1))) # Go through and check the",
"to make sure messages were decoded. for i in range(5): assert_that(self.tail.cache[i], equal_to(u'This is",
"can handle DGRAMs # Check to see that SyslogListener read 5 messages assert_that(self.tail.cache,",
"i in range(5): assert_that(self.tail.cache[i], equal_to(u'This is message #%s\\x00' % (i+1))) # Go through",
"stuff self.handler.close() self.handler = None self.logger = None # Kill the SyslogTail self.tail.stop()",
"message #%s' % count) count += 1 time.sleep(0.1) # Release GIL so async",
"can \"hear\" the DGRAMs count = 1 while count <= 5: self.logger.debug('This is",
"through and check the messages via iteration count = 1 for line in",
"SyslogTailTestCase(BaseTestCase): def setup_method(self, method): super(SyslogTailTestCase, self).setup_method(method) self.tail = SyslogTail(address=('localhost', 514), interval=0.1) # Set",
"directly to make sure messages were decoded. for i in range(5): assert_that(self.tail.cache[i], equal_to(u'This",
"for i in range(5): assert_that(self.tail.cache[i], equal_to(u'This is message #%s\\x00' % (i+1))) # Go",
"None def test_overall(self): time.sleep(0.1) # Release GIL so async listener can \"hear\" the",
"count = 1 for line in self.tail: assert_that(line, equal_to(u'This is message #%s\\x00' %",
"= 1 while count <= 5: self.logger.debug('This is message #%s' % count) count",
"DGRAMs count = 1 while count <= 5: self.logger.debug('This is message #%s' %",
"None self.logger = None # Kill the SyslogTail self.tail.stop() self.tail = None def",
"All rights reserved.\" __license__ = \"\" __maintainer__ = \"<NAME>\" __email__ = \"<EMAIL>\" class",
"from logging.handlers import SysLogHandler from hamcrest import * from amplify.agent.pipelines.syslog import SyslogTail, SYSLOG_ADDRESSES,",
"amplify.agent.pipelines.syslog import SyslogTail, SYSLOG_ADDRESSES, AmplifyAddresssAlreadyInUse from test.base import BaseTestCase, disabled_test __author__ = \"<NAME>\"",
"SYSLOG_ADDRESSES, AmplifyAddresssAlreadyInUse from test.base import BaseTestCase, disabled_test __author__ = \"<NAME>\" __copyright__ = \"Copyright",
"__license__ = \"\" __maintainer__ = \"<NAME>\" __email__ = \"<EMAIL>\" class SyslogTailTestCase(BaseTestCase): def setup_method(self,",
"fail if run...so skipped for now. @disabled_test def test_addresses(self): assert_that(('localhost', 514), is_in(SYSLOG_ADDRESSES)) @disabled_test",
"range(5): assert_that(self.tail.cache[i], equal_to(u'This is message #%s\\x00' % (i+1))) # Go through and check",
"tests below pass, but will cause test_overall to fail if run...so skipped for",
"SysLogHandler(address=('localhost', 514)) self.handler.setFormatter(logging.Formatter(' amplify: %(message)s')) self.logger.addHandler(self.handler) def teardown_method(self, method): # Revert logger stuff",
"are other tests run with it...why? # The tests below pass, but will",
"is message #%s\\x00' % count)) count += 1 # Check that cache was",
"messages were decoded. for i in range(5): assert_that(self.tail.cache[i], equal_to(u'This is message #%s\\x00' %",
"self.tail = SyslogTail(address=('localhost', 514), interval=0.1) # Set up python logger self.logger = logging.getLogger(self.__class__.__name__)",
"5: self.logger.debug('This is message #%s' % count) count += 1 time.sleep(0.1) # Release",
"self.tail = None def test_overall(self): time.sleep(0.1) # Release GIL so async listener can",
"self.tail.stop() self.tail = None def test_overall(self): time.sleep(0.1) # Release GIL so async listener",
"that SyslogListener read 5 messages assert_that(self.tail.cache, has_length(count-1)) # Check the cache directly to",
"TODO: test_overall doesn't work if there are other tests run with it...why? #",
"= \"<NAME>\" __email__ = \"<EMAIL>\" class SyslogTailTestCase(BaseTestCase): def setup_method(self, method): super(SyslogTailTestCase, self).setup_method(method) self.tail",
"the messages via iteration count = 1 for line in self.tail: assert_that(line, equal_to(u'This",
"in range(5): assert_that(self.tail.cache[i], equal_to(u'This is message #%s\\x00' % (i+1))) # Go through and",
"SysLogHandler from hamcrest import * from amplify.agent.pipelines.syslog import SyslogTail, SYSLOG_ADDRESSES, AmplifyAddresssAlreadyInUse from test.base",
"= logging.getLogger(self.__class__.__name__) self.logger.setLevel(logging.DEBUG) self.handler = SysLogHandler(address=('localhost', 514)) self.handler.setFormatter(logging.Formatter(' amplify: %(message)s')) self.logger.addHandler(self.handler) def teardown_method(self,",
"method): super(SyslogTailTestCase, self).setup_method(method) self.tail = SyslogTail(address=('localhost', 514), interval=0.1) # Set up python logger",
"(i+1))) # Go through and check the messages via iteration count = 1",
"rights reserved.\" __license__ = \"\" __maintainer__ = \"<NAME>\" __email__ = \"<EMAIL>\" class SyslogTailTestCase(BaseTestCase):",
"message #%s\\x00' % (i+1))) # Go through and check the messages via iteration",
"test_overall doesn't work if there are other tests run with it...why? # The",
"assert_that(self.tail.cache, has_length(count-1)) # Check the cache directly to make sure messages were decoded.",
"skipped for now. @disabled_test def test_addresses(self): assert_that(('localhost', 514), is_in(SYSLOG_ADDRESSES)) @disabled_test def test_socket_conflict(self): assert_that(",
"messages assert_that(self.tail.cache, has_length(count-1)) # Check the cache directly to make sure messages were",
"the DGRAMs count = 1 while count <= 5: self.logger.debug('This is message #%s'",
"logging.getLogger(self.__class__.__name__) self.logger.setLevel(logging.DEBUG) self.handler = SysLogHandler(address=('localhost', 514)) self.handler.setFormatter(logging.Formatter(' amplify: %(message)s')) self.logger.addHandler(self.handler) def teardown_method(self, method):",
"Nginx, Inc. All rights reserved.\" __license__ = \"\" __maintainer__ = \"<NAME>\" __email__ =",
"Revert logger stuff self.handler.close() self.handler = None self.logger = None # Kill the",
"for now. @disabled_test def test_addresses(self): assert_that(('localhost', 514), is_in(SYSLOG_ADDRESSES)) @disabled_test def test_socket_conflict(self): assert_that( calling(SyslogTail).with_args(address=('localhost',",
"%(message)s')) self.logger.addHandler(self.handler) def teardown_method(self, method): # Revert logger stuff self.handler.close() self.handler = None",
"Release GIL so async listener can \"hear\" the DGRAMs count = 1 while",
"\"<NAME>\" __email__ = \"<EMAIL>\" class SyslogTailTestCase(BaseTestCase): def setup_method(self, method): super(SyslogTailTestCase, self).setup_method(method) self.tail =",
"import BaseTestCase, disabled_test __author__ = \"<NAME>\" __copyright__ = \"Copyright (C) Nginx, Inc. All",
"self.logger.debug('This is message #%s' % count) count += 1 time.sleep(0.1) # Release GIL",
"\"<NAME>\" __copyright__ = \"Copyright (C) Nginx, Inc. All rights reserved.\" __license__ = \"\"",
"from hamcrest import * from amplify.agent.pipelines.syslog import SyslogTail, SYSLOG_ADDRESSES, AmplifyAddresssAlreadyInUse from test.base import",
"is message #%s' % count) count += 1 time.sleep(0.1) # Release GIL so",
"to see that SyslogListener read 5 messages assert_that(self.tail.cache, has_length(count-1)) # Check the cache",
"async listener can handle DGRAMs # Check to see that SyslogListener read 5",
"% count) count += 1 time.sleep(0.1) # Release GIL so async listener can"
] |
[
"0, -1], [1, 0, -1], [1, 0, -1]]) twist_vector = np.array([[0.], [0.], [.5]])",
"offset = np.array([-1, -1, 1]) voxel_size = 2 gradient_field = calculate_gradient_wrt_twist(live_field, twist_vector, array_offset=offset,",
"1] = 0 else: sdf_gradient_wrt_to_voxel[0, 1] = (post_sdf - pre_sdf) / 2 if",
"in range(live_field.shape[0]): for x_field in range(live_field.shape[1]): expected_gradient_field[y_field, x_field] = sdf_gradient_wrt_to_twist(live_field, y_field, x_field, twist_vector,",
"= (y_field + offset[2])*voxel_size point = np.array([[x_voxel, z_voxel, 1.]], dtype=np.float32).T twist_matrix_homo_inv = twist_vector_to_matrix2d(-twist_vector)",
"np.array([-1, -1, 1]) voxel_size = 2 gradient_field = calculate_gradient_wrt_twist(live_field, twist_vector, array_offset=offset, voxel_size=voxel_size) expected_gradient_field",
"sdf_gradient_wrt_to_voxel[0, 0] = 0 else: sdf_gradient_wrt_to_voxel[0, 0] = live_field[y_field, x_field] - pre_sdf else:",
"1] = (post_sdf - pre_sdf) / 2 if x_field - 1 < 0:",
"live_field = np.array([[1, 0, -1], [1, 0, -1], [1, 0, -1]]) twist_vector =",
"sdf_gradient_wrt_to_voxel[0, 1] = 0 else: sdf_gradient_wrt_to_voxel[0, 1] = (post_sdf - pre_sdf) / 2",
"x_field in range(live_field.shape[1]): expected_gradient_field[y_field, x_field] = sdf_gradient_wrt_to_twist(live_field, y_field, x_field, twist_vector, offset, voxel_size) self.assertTrue(np.allclose(expected_gradient_field,",
"- pre_sdf) / 2 if x_field - 1 < 0: post_sdf = live_field[y_field,",
"1], [0, 0, 0], [-1, -1, -1]]) twist_vector = np.array([[0.], [0.], [0.]]) offset",
"import numpy as np from rigid_opt.sdf_gradient_field import calculate_gradient_wrt_twist from math_utils.transformation import twist_vector_to_matrix2d def",
"= np.zeros((1, 2)) if y_field - 1 < 0: post_sdf = live_field[y_field +",
"live_field = np.array([[1, 1, 1], [0, 0, 0], [-1, -1, -1]]) twist_vector =",
"[0, 0, 0], [-1, -1, -1]]) twist_vector = np.array([[0.], [0.], [0.]]) offset =",
"offset[0])*voxel_size z_voxel = (y_field + offset[2])*voxel_size point = np.array([[x_voxel, z_voxel, 1.]], dtype=np.float32).T twist_matrix_homo_inv",
"(pre_sdf < -1): sdf_gradient_wrt_to_voxel[0, 1] = 0 else: sdf_gradient_wrt_to_voxel[0, 1] = (post_sdf -",
"expected_gradient_field[y_field, x_field] = sdf_gradient_wrt_to_twist(live_field, y_field, x_field, twist_vector, offset, voxel_size) self.assertTrue(np.allclose(expected_gradient_field, gradient_field)) def test_sdf_gradient_wrt_twist03(self):",
"post_sdf - live_field[y_field, x_field] elif y_field + 1 > live_field.shape[0] - 1: pre_sdf",
"3), dtype=np.float32) for y_field in range(live_field.shape[0]): for x_field in range(live_field.shape[1]): expected_gradient_field[y_field, x_field] =",
"if pre_sdf < -1: sdf_gradient_wrt_to_voxel[0, 1] = 0 else: sdf_gradient_wrt_to_voxel[0, 1] = live_field[y_field,",
"gradient_field)) def test_sdf_gradient_wrt_twist02(self): live_field = np.array([[1, 1, 1], [0, 0, 0], [-1, -1,",
"live_field[y_field, x_field] - pre_sdf else: pre_sdf = live_field[y_field, x_field - 1] post_sdf =",
"- 1] post_sdf = live_field[y_field, x_field + 1] if (post_sdf < -1) or",
"1, -trans[0]]]) return np.dot(sdf_gradient_wrt_to_voxel/voxel_size, voxel_gradient_wrt_to_twist).reshape((1, -1)) class MyTestCase(TestCase): def test_sdf_gradient_wrt_twist01(self): live_field = np.array([[1,",
"x_field] - pre_sdf else: pre_sdf = live_field[y_field - 1, x_field] post_sdf = live_field[y_field",
"y_field, x_field, twist_vector, offset, voxel_size) self.assertTrue(np.allclose(expected_gradient_field, gradient_field)) def test_sdf_gradient_wrt_twist04(self): live_field = np.array([[1, 0,",
"+ 1 > live_field.shape[1] - 1: pre_sdf = live_field[y_field, x_field - 1] if",
"y_field in range(live_field.shape[0]): for x_field in range(live_field.shape[1]): expected_gradient_field[y_field, x_field] = sdf_gradient_wrt_to_twist(live_field, y_field, x_field,",
"gradient_field)) def test_sdf_gradient_wrt_twist05(self): live_field = np.array([[1, 0, -1], [1, 0, -1], [1, 0,",
"from math_utils.transformation import twist_vector_to_matrix2d def sdf_gradient_wrt_to_twist(live_field, y_field, x_field, twist_vector, offset, voxel_size): sdf_gradient_wrt_to_voxel =",
"live_field[y_field, x_field - 1] if pre_sdf < -1: sdf_gradient_wrt_to_voxel[0, 0] = 0 else:",
"live_field[y_field, x_field - 1] post_sdf = live_field[y_field, x_field + 1] if (post_sdf <",
"else: pre_sdf = live_field[y_field - 1, x_field] post_sdf = live_field[y_field + 1, x_field]",
"pre_sdf < -1: sdf_gradient_wrt_to_voxel[0, 1] = 0 else: sdf_gradient_wrt_to_voxel[0, 1] = live_field[y_field, x_field]",
"calculate_gradient_wrt_twist from math_utils.transformation import twist_vector_to_matrix2d def sdf_gradient_wrt_to_twist(live_field, y_field, x_field, twist_vector, offset, voxel_size): sdf_gradient_wrt_to_voxel",
"range(live_field.shape[0]): for x_field in range(live_field.shape[1]): expected_gradient_field[y_field, x_field] = sdf_gradient_wrt_to_twist(live_field, y_field, x_field, twist_vector, offset,",
"1: pre_sdf = live_field[y_field - 1, x_field] if pre_sdf < -1: sdf_gradient_wrt_to_voxel[0, 1]",
"twist_vector = np.array([[0.], [-1.], [0.]]) offset = np.array([-1, -1, 1]) voxel_size = 1",
"1] post_sdf = live_field[y_field, x_field + 1] if (post_sdf < -1) or (pre_sdf",
"= np.array([[0.], [-1.], [0.]]) offset = np.array([-1, -1, 1]) voxel_size = 1 gradient_field",
"voxel_size) self.assertTrue(np.allclose(expected_gradient_field, gradient_field)) def test_sdf_gradient_wrt_twist04(self): live_field = np.array([[1, 0, -1], [1, 0, -1],",
"< -1): sdf_gradient_wrt_to_voxel[0, 0] = 0 else: sdf_gradient_wrt_to_voxel[0, 0] = (post_sdf - pre_sdf)",
"[0.], [0.]]) offset = np.array([-1, -1, 1]) voxel_size = 2 gradient_field = calculate_gradient_wrt_twist(live_field,",
"(post_sdf < -1) or (pre_sdf < -1): sdf_gradient_wrt_to_voxel[0, 1] = 0 else: sdf_gradient_wrt_to_voxel[0,",
"pre_sdf) / 2 x_voxel = (x_field + offset[0])*voxel_size z_voxel = (y_field + offset[2])*voxel_size",
"post_sdf < -1: sdf_gradient_wrt_to_voxel[0, 0] = 0 else: sdf_gradient_wrt_to_voxel[0, 0] = post_sdf -",
"-1]]) twist_vector = np.array([[0.], [1.], [0.]]) offset = np.array([-1, -1, 1]) voxel_size =",
"- 1] if pre_sdf < -1: sdf_gradient_wrt_to_voxel[0, 0] = 0 else: sdf_gradient_wrt_to_voxel[0, 0]",
"sdf_gradient_wrt_to_twist(live_field, y_field, x_field, twist_vector, offset, voxel_size) self.assertTrue(np.allclose(expected_gradient_field, gradient_field)) def test_sdf_gradient_wrt_twist03(self): live_field = np.array([[1,",
"live_field[y_field, x_field] - pre_sdf else: pre_sdf = live_field[y_field - 1, x_field] post_sdf =",
"1] = 0 else: sdf_gradient_wrt_to_voxel[0, 1] = post_sdf - live_field[y_field, x_field] elif y_field",
"0] = 0 else: sdf_gradient_wrt_to_voxel[0, 0] = live_field[y_field, x_field] - pre_sdf else: pre_sdf",
"voxel_size=voxel_size) expected_gradient_field = np.zeros((live_field.shape[0], live_field.shape[1], 3), dtype=np.float32) for y_field in range(live_field.shape[0]): for x_field",
"= 1 gradient_field = calculate_gradient_wrt_twist(live_field, twist_vector, array_offset=offset, voxel_size=voxel_size) expected_gradient_field = np.zeros((live_field.shape[0], live_field.shape[1], 3),",
"= 0 else: sdf_gradient_wrt_to_voxel[0, 1] = (post_sdf - pre_sdf) / 2 if x_field",
"0, -1], [1, 0, -1]]) twist_vector = np.array([[0.], [0.], [0.]]) offset = np.array([-1,",
"> live_field.shape[0] - 1: pre_sdf = live_field[y_field - 1, x_field] if pre_sdf <",
"+ 1, x_field] if (post_sdf < -1) or (pre_sdf < -1): sdf_gradient_wrt_to_voxel[0, 1]",
"= np.array([-1, -1, 1]) voxel_size = 1 gradient_field = calculate_gradient_wrt_twist(live_field, twist_vector, array_offset=offset, voxel_size=voxel_size)",
"sdf_gradient_wrt_to_voxel[0, 1] = 0 else: sdf_gradient_wrt_to_voxel[0, 1] = live_field[y_field, x_field] - pre_sdf else:",
"-1, -1]]) twist_vector = np.array([[0.], [0.], [0.]]) offset = np.array([-1, -1, 1]) voxel_size",
"= np.array([-1, -1, 1]) voxel_size = 2 gradient_field = calculate_gradient_wrt_twist(live_field, twist_vector, array_offset=offset, voxel_size=voxel_size)",
"self.assertTrue(np.allclose(expected_gradient_field, gradient_field)) def test_sdf_gradient_wrt_twist04(self): live_field = np.array([[1, 0, -1], [1, 0, -1], [1,",
"0, -1]]) twist_vector = np.array([[0.], [0.], [0.]]) offset = np.array([-1, -1, 1]) voxel_size",
"+ 1] if (post_sdf < -1) or (pre_sdf < -1): sdf_gradient_wrt_to_voxel[0, 0] =",
"np.dot(sdf_gradient_wrt_to_voxel/voxel_size, voxel_gradient_wrt_to_twist).reshape((1, -1)) class MyTestCase(TestCase): def test_sdf_gradient_wrt_twist01(self): live_field = np.array([[1, 0, -1], [1,",
"[1, 0, -1]]) twist_vector = np.array([[0.], [0.], [.5]]) offset = np.array([-1, -1, 1])",
"0] = 0 else: sdf_gradient_wrt_to_voxel[0, 0] = post_sdf - live_field[y_field, x_field] elif x_field",
"[1, 0, -1], [1, 0, -1]]) twist_vector = np.array([[0.], [0.], [.5]]) offset =",
"live_field[y_field, x_field] elif y_field + 1 > live_field.shape[0] - 1: pre_sdf = live_field[y_field",
"x_field] = sdf_gradient_wrt_to_twist(live_field, y_field, x_field, twist_vector, offset, voxel_size) self.assertTrue(np.allclose(expected_gradient_field, gradient_field)) def test_sdf_gradient_wrt_twist02(self): live_field",
"1.]], dtype=np.float32).T twist_matrix_homo_inv = twist_vector_to_matrix2d(-twist_vector) trans = np.dot(twist_matrix_homo_inv, point) voxel_gradient_wrt_to_twist = np.array([[1, 0,",
"test_sdf_gradient_wrt_twist06(self): live_field = np.array([[1, 0, -1], [1, 0, -1], [1, 0, -1]]) twist_vector",
"twist_vector, offset, voxel_size) self.assertTrue(np.allclose(expected_gradient_field, gradient_field)) def test_sdf_gradient_wrt_twist02(self): live_field = np.array([[1, 1, 1], [0,",
"live_field[y_field - 1, x_field] if pre_sdf < -1: sdf_gradient_wrt_to_voxel[0, 1] = 0 else:",
"- 1: pre_sdf = live_field[y_field, x_field - 1] if pre_sdf < -1: sdf_gradient_wrt_to_voxel[0,",
"voxel_size) self.assertTrue(np.allclose(expected_gradient_field, gradient_field)) def test_sdf_gradient_wrt_twist05(self): live_field = np.array([[1, 0, -1], [1, 0, -1],",
"0, 0], [-1, -1, -1]]) twist_vector = np.array([[0.], [0.], [0.]]) offset = np.array([-1,",
"sdf_gradient_wrt_to_voxel[0, 0] = live_field[y_field, x_field] - pre_sdf else: pre_sdf = live_field[y_field, x_field -",
"offset, voxel_size): sdf_gradient_wrt_to_voxel = np.zeros((1, 2)) if y_field - 1 < 0: post_sdf",
"live_field.shape[1], 3), dtype=np.float32) for y_field in range(live_field.shape[0]): for x_field in range(live_field.shape[1]): expected_gradient_field[y_field, x_field]",
"live_field.shape[0] - 1: pre_sdf = live_field[y_field - 1, x_field] if pre_sdf < -1:",
"- 1, x_field] post_sdf = live_field[y_field + 1, x_field] if (post_sdf < -1)",
"< -1: sdf_gradient_wrt_to_voxel[0, 1] = 0 else: sdf_gradient_wrt_to_voxel[0, 1] = post_sdf - live_field[y_field,",
"1 < 0: post_sdf = live_field[y_field + 1, x_field] if post_sdf < -1:",
"1] = post_sdf - live_field[y_field, x_field] elif y_field + 1 > live_field.shape[0] -",
"= calculate_gradient_wrt_twist(live_field, twist_vector, array_offset=offset, voxel_size=voxel_size) expected_gradient_field = np.zeros((live_field.shape[0], live_field.shape[1], 3), dtype=np.float32) for y_field",
"+ 1 > live_field.shape[0] - 1: pre_sdf = live_field[y_field - 1, x_field] if",
"voxel_gradient_wrt_to_twist).reshape((1, -1)) class MyTestCase(TestCase): def test_sdf_gradient_wrt_twist01(self): live_field = np.array([[1, 0, -1], [1, 0,",
"= live_field[y_field, x_field + 1] if post_sdf < -1: sdf_gradient_wrt_to_voxel[0, 0] = 0",
"= twist_vector_to_matrix2d(-twist_vector) trans = np.dot(twist_matrix_homo_inv, point) voxel_gradient_wrt_to_twist = np.array([[1, 0, trans[1]], [0, 1,",
"= live_field[y_field, x_field] - pre_sdf else: pre_sdf = live_field[y_field - 1, x_field] post_sdf",
"np from rigid_opt.sdf_gradient_field import calculate_gradient_wrt_twist from math_utils.transformation import twist_vector_to_matrix2d def sdf_gradient_wrt_to_twist(live_field, y_field, x_field,",
"[0, 1, -trans[0]]]) return np.dot(sdf_gradient_wrt_to_voxel/voxel_size, voxel_gradient_wrt_to_twist).reshape((1, -1)) class MyTestCase(TestCase): def test_sdf_gradient_wrt_twist01(self): live_field =",
"gradient_field)) def test_sdf_gradient_wrt_twist03(self): live_field = np.array([[1, 1, 1], [0, 0, 0], [-1, -1,",
"sdf_gradient_wrt_to_voxel[0, 0] = 0 else: sdf_gradient_wrt_to_voxel[0, 0] = post_sdf - live_field[y_field, x_field] elif",
"x_field] post_sdf = live_field[y_field + 1, x_field] if (post_sdf < -1) or (pre_sdf",
"np.array([[1, 0, -1], [1, 0, -1], [1, 0, -1]]) twist_vector = np.array([[0.], [0.],",
"+ 1] if post_sdf < -1: sdf_gradient_wrt_to_voxel[0, 0] = 0 else: sdf_gradient_wrt_to_voxel[0, 0]",
"else: sdf_gradient_wrt_to_voxel[0, 1] = live_field[y_field, x_field] - pre_sdf else: pre_sdf = live_field[y_field -",
"twist_vector = np.array([[0.], [0.], [.5]]) offset = np.array([-1, -1, 1]) voxel_size = 0.5",
"offset, voxel_size) self.assertTrue(np.allclose(expected_gradient_field, gradient_field)) def test_sdf_gradient_wrt_twist05(self): live_field = np.array([[1, 0, -1], [1, 0,",
"post_sdf - live_field[y_field, x_field] elif x_field + 1 > live_field.shape[1] - 1: pre_sdf",
"= sdf_gradient_wrt_to_twist(live_field, y_field, x_field, twist_vector, offset, voxel_size) self.assertTrue(np.allclose(expected_gradient_field, gradient_field)) def test_sdf_gradient_wrt_twist03(self): live_field =",
"x_field] if (post_sdf < -1) or (pre_sdf < -1): sdf_gradient_wrt_to_voxel[0, 1] = 0",
"sdf_gradient_wrt_to_voxel[0, 0] = (post_sdf - pre_sdf) / 2 x_voxel = (x_field + offset[0])*voxel_size",
"1, x_field] if post_sdf < -1: sdf_gradient_wrt_to_voxel[0, 1] = 0 else: sdf_gradient_wrt_to_voxel[0, 1]",
"x_field, twist_vector, offset, voxel_size) self.assertTrue(np.allclose(expected_gradient_field, gradient_field)) def test_sdf_gradient_wrt_twist04(self): live_field = np.array([[1, 0, -1],",
"gradient_field = calculate_gradient_wrt_twist(live_field, twist_vector, array_offset=offset, voxel_size=voxel_size) expected_gradient_field = np.zeros((live_field.shape[0], live_field.shape[1], 3), dtype=np.float32) for",
"= np.array([[0.], [0.], [0.]]) offset = np.array([-1, -1, 1]) voxel_size = 1 gradient_field",
"else: sdf_gradient_wrt_to_voxel[0, 0] = post_sdf - live_field[y_field, x_field] elif x_field + 1 >",
"sdf_gradient_wrt_to_voxel[0, 1] = post_sdf - live_field[y_field, x_field] elif y_field + 1 > live_field.shape[0]",
"= np.zeros((live_field.shape[0], live_field.shape[1], 3), dtype=np.float32) for y_field in range(live_field.shape[0]): for x_field in range(live_field.shape[1]):",
"> live_field.shape[1] - 1: pre_sdf = live_field[y_field, x_field - 1] if pre_sdf <",
"def sdf_gradient_wrt_to_twist(live_field, y_field, x_field, twist_vector, offset, voxel_size): sdf_gradient_wrt_to_voxel = np.zeros((1, 2)) if y_field",
"sdf_gradient_wrt_to_twist(live_field, y_field, x_field, twist_vector, offset, voxel_size): sdf_gradient_wrt_to_voxel = np.zeros((1, 2)) if y_field -",
"(post_sdf < -1) or (pre_sdf < -1): sdf_gradient_wrt_to_voxel[0, 0] = 0 else: sdf_gradient_wrt_to_voxel[0,",
"x_field - 1] if pre_sdf < -1: sdf_gradient_wrt_to_voxel[0, 0] = 0 else: sdf_gradient_wrt_to_voxel[0,",
"x_field] elif x_field + 1 > live_field.shape[1] - 1: pre_sdf = live_field[y_field, x_field",
"0, -1], [1, 0, -1]]) twist_vector = np.array([[0.], [1.], [0.]]) offset = np.array([-1,",
"else: sdf_gradient_wrt_to_voxel[0, 1] = (post_sdf - pre_sdf) / 2 if x_field - 1",
"[1, 0, -1], [1, 0, -1]]) twist_vector = np.array([[0.], [0.], [0.]]) offset =",
"offset, voxel_size) self.assertTrue(np.allclose(expected_gradient_field, gradient_field)) def test_sdf_gradient_wrt_twist03(self): live_field = np.array([[1, 1, 1], [0, 0,",
"def test_sdf_gradient_wrt_twist02(self): live_field = np.array([[1, 1, 1], [0, 0, 0], [-1, -1, -1]])",
"1: pre_sdf = live_field[y_field, x_field - 1] if pre_sdf < -1: sdf_gradient_wrt_to_voxel[0, 0]",
"= post_sdf - live_field[y_field, x_field] elif x_field + 1 > live_field.shape[1] - 1:",
"twist_vector, offset, voxel_size) self.assertTrue(np.allclose(expected_gradient_field, gradient_field)) def test_sdf_gradient_wrt_twist05(self): live_field = np.array([[1, 0, -1], [1,",
"gradient_field)) def test_sdf_gradient_wrt_twist06(self): live_field = np.array([[1, 0, -1], [1, 0, -1], [1, 0,",
"test_sdf_gradient_wrt_twist03(self): live_field = np.array([[1, 1, 1], [0, 0, 0], [-1, -1, -1]]) twist_vector",
"= 0 else: sdf_gradient_wrt_to_voxel[0, 0] = live_field[y_field, x_field] - pre_sdf else: pre_sdf =",
"np.array([[0.], [0.], [0.]]) offset = np.array([-1, -1, 1]) voxel_size = 2 gradient_field =",
"pre_sdf = live_field[y_field - 1, x_field] if pre_sdf < -1: sdf_gradient_wrt_to_voxel[0, 1] =",
"test_sdf_gradient_wrt_twist05(self): live_field = np.array([[1, 0, -1], [1, 0, -1], [1, 0, -1]]) twist_vector",
"-1], [1, 0, -1]]) twist_vector = np.array([[0.], [0.], [.5]]) offset = np.array([-1, -1,",
"twist_vector = np.array([[0.], [1.], [0.]]) offset = np.array([-1, -1, 1]) voxel_size = 1",
"live_field[y_field - 1, x_field] post_sdf = live_field[y_field + 1, x_field] if (post_sdf <",
"from rigid_opt.sdf_gradient_field import calculate_gradient_wrt_twist from math_utils.transformation import twist_vector_to_matrix2d def sdf_gradient_wrt_to_twist(live_field, y_field, x_field, twist_vector,",
"voxel_size): sdf_gradient_wrt_to_voxel = np.zeros((1, 2)) if y_field - 1 < 0: post_sdf =",
"0, -1], [1, 0, -1]]) twist_vector = np.array([[0.], [0.], [.5]]) offset = np.array([-1,",
"x_field] if pre_sdf < -1: sdf_gradient_wrt_to_voxel[0, 1] = 0 else: sdf_gradient_wrt_to_voxel[0, 1] =",
"0, -1]]) twist_vector = np.array([[0.], [-1.], [0.]]) offset = np.array([-1, -1, 1]) voxel_size",
"2 x_voxel = (x_field + offset[0])*voxel_size z_voxel = (y_field + offset[2])*voxel_size point =",
"< 0: post_sdf = live_field[y_field + 1, x_field] if post_sdf < -1: sdf_gradient_wrt_to_voxel[0,",
"z_voxel = (y_field + offset[2])*voxel_size point = np.array([[x_voxel, z_voxel, 1.]], dtype=np.float32).T twist_matrix_homo_inv =",
"= live_field[y_field - 1, x_field] if pre_sdf < -1: sdf_gradient_wrt_to_voxel[0, 1] = 0",
"= np.array([[1, 0, trans[1]], [0, 1, -trans[0]]]) return np.dot(sdf_gradient_wrt_to_voxel/voxel_size, voxel_gradient_wrt_to_twist).reshape((1, -1)) class MyTestCase(TestCase):",
"-1], [1, 0, -1], [1, 0, -1]]) twist_vector = np.array([[0.], [0.], [0.]]) offset",
"y_field, x_field, twist_vector, offset, voxel_size): sdf_gradient_wrt_to_voxel = np.zeros((1, 2)) if y_field - 1",
"test_sdf_gradient_wrt_twist04(self): live_field = np.array([[1, 0, -1], [1, 0, -1], [1, 0, -1]]) twist_vector",
"voxel_size = 1 gradient_field = calculate_gradient_wrt_twist(live_field, twist_vector, array_offset=offset, voxel_size=voxel_size) expected_gradient_field = np.zeros((live_field.shape[0], live_field.shape[1],",
"-1, 1]) voxel_size = 1 gradient_field = calculate_gradient_wrt_twist(live_field, twist_vector, array_offset=offset, voxel_size=voxel_size) expected_gradient_field =",
"- 1 < 0: post_sdf = live_field[y_field + 1, x_field] if post_sdf <",
"x_field] = sdf_gradient_wrt_to_twist(live_field, y_field, x_field, twist_vector, offset, voxel_size) self.assertTrue(np.allclose(expected_gradient_field, gradient_field)) def test_sdf_gradient_wrt_twist06(self): live_field",
"-1, 1]) voxel_size = 2 gradient_field = calculate_gradient_wrt_twist(live_field, twist_vector, array_offset=offset, voxel_size=voxel_size) expected_gradient_field =",
"x_field] - pre_sdf else: pre_sdf = live_field[y_field, x_field - 1] post_sdf = live_field[y_field,",
"or (pre_sdf < -1): sdf_gradient_wrt_to_voxel[0, 0] = 0 else: sdf_gradient_wrt_to_voxel[0, 0] = (post_sdf",
"0 else: sdf_gradient_wrt_to_voxel[0, 1] = (post_sdf - pre_sdf) / 2 if x_field -",
"2)) if y_field - 1 < 0: post_sdf = live_field[y_field + 1, x_field]",
"twist_vector, offset, voxel_size) self.assertTrue(np.allclose(expected_gradient_field, gradient_field)) def test_sdf_gradient_wrt_twist03(self): live_field = np.array([[1, 1, 1], [0,",
"-1: sdf_gradient_wrt_to_voxel[0, 0] = 0 else: sdf_gradient_wrt_to_voxel[0, 0] = live_field[y_field, x_field] - pre_sdf",
"< -1: sdf_gradient_wrt_to_voxel[0, 1] = 0 else: sdf_gradient_wrt_to_voxel[0, 1] = live_field[y_field, x_field] -",
"-1], [1, 0, -1]]) twist_vector = np.array([[0.], [0.], [0.]]) offset = np.array([-1, -1,",
"MyTestCase(TestCase): def test_sdf_gradient_wrt_twist01(self): live_field = np.array([[1, 0, -1], [1, 0, -1], [1, 0,",
"twist_vector, array_offset=offset, voxel_size=voxel_size) expected_gradient_field = np.zeros((live_field.shape[0], live_field.shape[1], 3), dtype=np.float32) for y_field in range(live_field.shape[0]):",
"pre_sdf) / 2 if x_field - 1 < 0: post_sdf = live_field[y_field, x_field",
"numpy as np from rigid_opt.sdf_gradient_field import calculate_gradient_wrt_twist from math_utils.transformation import twist_vector_to_matrix2d def sdf_gradient_wrt_to_twist(live_field,",
"self.assertTrue(np.allclose(expected_gradient_field, gradient_field)) def test_sdf_gradient_wrt_twist03(self): live_field = np.array([[1, 1, 1], [0, 0, 0], [-1,",
"expected_gradient_field = np.zeros((live_field.shape[0], live_field.shape[1], 3), dtype=np.float32) for y_field in range(live_field.shape[0]): for x_field in",
"rigid_opt.sdf_gradient_field import calculate_gradient_wrt_twist from math_utils.transformation import twist_vector_to_matrix2d def sdf_gradient_wrt_to_twist(live_field, y_field, x_field, twist_vector, offset,",
"-1: sdf_gradient_wrt_to_voxel[0, 1] = 0 else: sdf_gradient_wrt_to_voxel[0, 1] = live_field[y_field, x_field] - pre_sdf",
"x_field - 1] post_sdf = live_field[y_field, x_field + 1] if (post_sdf < -1)",
"test_sdf_gradient_wrt_twist01(self): live_field = np.array([[1, 0, -1], [1, 0, -1], [1, 0, -1]]) twist_vector",
"else: sdf_gradient_wrt_to_voxel[0, 0] = live_field[y_field, x_field] - pre_sdf else: pre_sdf = live_field[y_field, x_field",
"- 1: pre_sdf = live_field[y_field - 1, x_field] if pre_sdf < -1: sdf_gradient_wrt_to_voxel[0,",
"-1, 1]) voxel_size = 0.5 gradient_field = calculate_gradient_wrt_twist(live_field, twist_vector, array_offset=offset, voxel_size=voxel_size) expected_gradient_field =",
"= live_field[y_field, x_field - 1] post_sdf = live_field[y_field, x_field + 1] if (post_sdf",
"0] = 0 else: sdf_gradient_wrt_to_voxel[0, 0] = (post_sdf - pre_sdf) / 2 x_voxel",
"post_sdf = live_field[y_field + 1, x_field] if post_sdf < -1: sdf_gradient_wrt_to_voxel[0, 1] =",
"+ offset[2])*voxel_size point = np.array([[x_voxel, z_voxel, 1.]], dtype=np.float32).T twist_matrix_homo_inv = twist_vector_to_matrix2d(-twist_vector) trans =",
"np.zeros((1, 2)) if y_field - 1 < 0: post_sdf = live_field[y_field + 1,",
"voxel_size) self.assertTrue(np.allclose(expected_gradient_field, gradient_field)) def test_sdf_gradient_wrt_twist03(self): live_field = np.array([[1, 1, 1], [0, 0, 0],",
"= np.array([-1, -1, 1]) voxel_size = 0.5 gradient_field = calculate_gradient_wrt_twist(live_field, twist_vector, array_offset=offset, voxel_size=voxel_size)",
"np.array([-1, -1, 1]) voxel_size = 0.5 gradient_field = calculate_gradient_wrt_twist(live_field, twist_vector, array_offset=offset, voxel_size=voxel_size) expected_gradient_field",
"(post_sdf - pre_sdf) / 2 if x_field - 1 < 0: post_sdf =",
"y_field, x_field, twist_vector, offset, voxel_size) self.assertTrue(np.allclose(expected_gradient_field, gradient_field)) def test_sdf_gradient_wrt_twist05(self): live_field = np.array([[1, 0,",
"unittest import TestCase import numpy as np from rigid_opt.sdf_gradient_field import calculate_gradient_wrt_twist from math_utils.transformation",
"= sdf_gradient_wrt_to_twist(live_field, y_field, x_field, twist_vector, offset, voxel_size) self.assertTrue(np.allclose(expected_gradient_field, gradient_field)) def test_sdf_gradient_wrt_twist04(self): live_field =",
"= 2 gradient_field = calculate_gradient_wrt_twist(live_field, twist_vector, array_offset=offset, voxel_size=voxel_size) expected_gradient_field = np.zeros((live_field.shape[0], live_field.shape[1], 3),",
"dtype=np.float32).T twist_matrix_homo_inv = twist_vector_to_matrix2d(-twist_vector) trans = np.dot(twist_matrix_homo_inv, point) voxel_gradient_wrt_to_twist = np.array([[1, 0, trans[1]],",
"(y_field + offset[2])*voxel_size point = np.array([[x_voxel, z_voxel, 1.]], dtype=np.float32).T twist_matrix_homo_inv = twist_vector_to_matrix2d(-twist_vector) trans",
"pre_sdf = live_field[y_field - 1, x_field] post_sdf = live_field[y_field + 1, x_field] if",
"import unittest from unittest import TestCase import numpy as np from rigid_opt.sdf_gradient_field import",
"(x_field + offset[0])*voxel_size z_voxel = (y_field + offset[2])*voxel_size point = np.array([[x_voxel, z_voxel, 1.]],",
"offset, voxel_size) self.assertTrue(np.allclose(expected_gradient_field, gradient_field)) def test_sdf_gradient_wrt_twist06(self): live_field = np.array([[1, 0, -1], [1, 0,",
"def test_sdf_gradient_wrt_twist06(self): live_field = np.array([[1, 0, -1], [1, 0, -1], [1, 0, -1]])",
"-1): sdf_gradient_wrt_to_voxel[0, 1] = 0 else: sdf_gradient_wrt_to_voxel[0, 1] = (post_sdf - pre_sdf) /",
"= live_field[y_field, x_field + 1] if (post_sdf < -1) or (pre_sdf < -1):",
"x_field, twist_vector, offset, voxel_size) self.assertTrue(np.allclose(expected_gradient_field, gradient_field)) def test_sdf_gradient_wrt_twist02(self): live_field = np.array([[1, 1, 1],",
"-trans[0]]]) return np.dot(sdf_gradient_wrt_to_voxel/voxel_size, voxel_gradient_wrt_to_twist).reshape((1, -1)) class MyTestCase(TestCase): def test_sdf_gradient_wrt_twist01(self): live_field = np.array([[1, 0,",
"-1]]) twist_vector = np.array([[0.], [-1.], [0.]]) offset = np.array([-1, -1, 1]) voxel_size =",
"[0.]]) offset = np.array([-1, -1, 1]) voxel_size = 1 gradient_field = calculate_gradient_wrt_twist(live_field, twist_vector,",
"+ offset[0])*voxel_size z_voxel = (y_field + offset[2])*voxel_size point = np.array([[x_voxel, z_voxel, 1.]], dtype=np.float32).T",
"0 else: sdf_gradient_wrt_to_voxel[0, 0] = post_sdf - live_field[y_field, x_field] elif x_field + 1",
"< -1) or (pre_sdf < -1): sdf_gradient_wrt_to_voxel[0, 0] = 0 else: sdf_gradient_wrt_to_voxel[0, 0]",
"np.array([[0.], [1.], [0.]]) offset = np.array([-1, -1, 1]) voxel_size = 1 gradient_field =",
"= live_field[y_field + 1, x_field] if (post_sdf < -1) or (pre_sdf < -1):",
"1, 1], [0, 0, 0], [-1, -1, -1]]) twist_vector = np.array([[0.], [0.], [0.]])",
"offset[2])*voxel_size point = np.array([[x_voxel, z_voxel, 1.]], dtype=np.float32).T twist_matrix_homo_inv = twist_vector_to_matrix2d(-twist_vector) trans = np.dot(twist_matrix_homo_inv,",
"0, -1], [1, 0, -1], [1, 0, -1]]) twist_vector = np.array([[0.], [1.], [0.]])",
"2 gradient_field = calculate_gradient_wrt_twist(live_field, twist_vector, array_offset=offset, voxel_size=voxel_size) expected_gradient_field = np.zeros((live_field.shape[0], live_field.shape[1], 3), dtype=np.float32)",
"x_field - 1 < 0: post_sdf = live_field[y_field, x_field + 1] if post_sdf",
"1] = 0 else: sdf_gradient_wrt_to_voxel[0, 1] = live_field[y_field, x_field] - pre_sdf else: pre_sdf",
"expected_gradient_field[y_field, x_field] = sdf_gradient_wrt_to_twist(live_field, y_field, x_field, twist_vector, offset, voxel_size) self.assertTrue(np.allclose(expected_gradient_field, gradient_field)) def test_sdf_gradient_wrt_twist05(self):",
"pre_sdf = live_field[y_field, x_field - 1] post_sdf = live_field[y_field, x_field + 1] if",
"-1], [1, 0, -1], [1, 0, -1]]) twist_vector = np.array([[0.], [1.], [0.]]) offset",
"def test_sdf_gradient_wrt_twist05(self): live_field = np.array([[1, 0, -1], [1, 0, -1], [1, 0, -1]])",
"for x_field in range(live_field.shape[1]): expected_gradient_field[y_field, x_field] = sdf_gradient_wrt_to_twist(live_field, y_field, x_field, twist_vector, offset, voxel_size)",
"voxel_size) self.assertTrue(np.allclose(expected_gradient_field, gradient_field)) def test_sdf_gradient_wrt_twist02(self): live_field = np.array([[1, 1, 1], [0, 0, 0],",
"= (post_sdf - pre_sdf) / 2 x_voxel = (x_field + offset[0])*voxel_size z_voxel =",
"= np.dot(twist_matrix_homo_inv, point) voxel_gradient_wrt_to_twist = np.array([[1, 0, trans[1]], [0, 1, -trans[0]]]) return np.dot(sdf_gradient_wrt_to_voxel/voxel_size,",
"post_sdf = live_field[y_field, x_field + 1] if post_sdf < -1: sdf_gradient_wrt_to_voxel[0, 0] =",
"- pre_sdf else: pre_sdf = live_field[y_field, x_field - 1] post_sdf = live_field[y_field, x_field",
"x_field] elif y_field + 1 > live_field.shape[0] - 1: pre_sdf = live_field[y_field -",
"import calculate_gradient_wrt_twist from math_utils.transformation import twist_vector_to_matrix2d def sdf_gradient_wrt_to_twist(live_field, y_field, x_field, twist_vector, offset, voxel_size):",
"- pre_sdf else: pre_sdf = live_field[y_field - 1, x_field] post_sdf = live_field[y_field +",
"x_field] if post_sdf < -1: sdf_gradient_wrt_to_voxel[0, 1] = 0 else: sdf_gradient_wrt_to_voxel[0, 1] =",
"if y_field - 1 < 0: post_sdf = live_field[y_field + 1, x_field] if",
"class MyTestCase(TestCase): def test_sdf_gradient_wrt_twist01(self): live_field = np.array([[1, 0, -1], [1, 0, -1], [1,",
"self.assertTrue(np.allclose(expected_gradient_field, gradient_field)) def test_sdf_gradient_wrt_twist02(self): live_field = np.array([[1, 1, 1], [0, 0, 0], [-1,",
"= np.array([[0.], [0.], [0.]]) offset = np.array([-1, -1, 1]) voxel_size = 2 gradient_field",
"0] = post_sdf - live_field[y_field, x_field] elif x_field + 1 > live_field.shape[1] -",
"np.zeros((live_field.shape[0], live_field.shape[1], 3), dtype=np.float32) for y_field in range(live_field.shape[0]): for x_field in range(live_field.shape[1]): expected_gradient_field[y_field,",
"range(live_field.shape[1]): expected_gradient_field[y_field, x_field] = sdf_gradient_wrt_to_twist(live_field, y_field, x_field, twist_vector, offset, voxel_size) self.assertTrue(np.allclose(expected_gradient_field, gradient_field)) def",
"0, -1], [1, 0, -1]]) twist_vector = np.array([[0.], [-1.], [0.]]) offset = np.array([-1,",
"offset = np.array([-1, -1, 1]) voxel_size = 0.5 gradient_field = calculate_gradient_wrt_twist(live_field, twist_vector, array_offset=offset,",
"(pre_sdf < -1): sdf_gradient_wrt_to_voxel[0, 0] = 0 else: sdf_gradient_wrt_to_voxel[0, 0] = (post_sdf -",
"if x_field - 1 < 0: post_sdf = live_field[y_field, x_field + 1] if",
"<gh_stars>1-10 # import unittest from unittest import TestCase import numpy as np from",
"import twist_vector_to_matrix2d def sdf_gradient_wrt_to_twist(live_field, y_field, x_field, twist_vector, offset, voxel_size): sdf_gradient_wrt_to_voxel = np.zeros((1, 2))",
"< -1): sdf_gradient_wrt_to_voxel[0, 1] = 0 else: sdf_gradient_wrt_to_voxel[0, 1] = (post_sdf - pre_sdf)",
"= np.array([[1, 0, -1], [1, 0, -1], [1, 0, -1]]) twist_vector = np.array([[0.],",
"x_field] = sdf_gradient_wrt_to_twist(live_field, y_field, x_field, twist_vector, offset, voxel_size) self.assertTrue(np.allclose(expected_gradient_field, gradient_field)) def test_sdf_gradient_wrt_twist04(self): live_field",
"0, -1]]) twist_vector = np.array([[0.], [1.], [0.]]) offset = np.array([-1, -1, 1]) voxel_size",
"sdf_gradient_wrt_to_voxel[0, 0] = 0 else: sdf_gradient_wrt_to_voxel[0, 0] = (post_sdf - pre_sdf) / 2",
"np.array([[1, 1, 1], [0, 0, 0], [-1, -1, -1]]) twist_vector = np.array([[0.], [0.],",
"x_field] = sdf_gradient_wrt_to_twist(live_field, y_field, x_field, twist_vector, offset, voxel_size) self.assertTrue(np.allclose(expected_gradient_field, gradient_field)) def test_sdf_gradient_wrt_twist03(self): live_field",
"np.array([[0.], [-1.], [0.]]) offset = np.array([-1, -1, 1]) voxel_size = 1 gradient_field =",
"[.5]]) offset = np.array([-1, -1, 1]) voxel_size = 0.5 gradient_field = calculate_gradient_wrt_twist(live_field, twist_vector,",
"if (post_sdf < -1) or (pre_sdf < -1): sdf_gradient_wrt_to_voxel[0, 0] = 0 else:",
"def test_sdf_gradient_wrt_twist01(self): live_field = np.array([[1, 0, -1], [1, 0, -1], [1, 0, -1]])",
"voxel_gradient_wrt_to_twist = np.array([[1, 0, trans[1]], [0, 1, -trans[0]]]) return np.dot(sdf_gradient_wrt_to_voxel/voxel_size, voxel_gradient_wrt_to_twist).reshape((1, -1)) class",
"unittest from unittest import TestCase import numpy as np from rigid_opt.sdf_gradient_field import calculate_gradient_wrt_twist",
"# import unittest from unittest import TestCase import numpy as np from rigid_opt.sdf_gradient_field",
"point = np.array([[x_voxel, z_voxel, 1.]], dtype=np.float32).T twist_matrix_homo_inv = twist_vector_to_matrix2d(-twist_vector) trans = np.dot(twist_matrix_homo_inv, point)",
"1]) voxel_size = 2 gradient_field = calculate_gradient_wrt_twist(live_field, twist_vector, array_offset=offset, voxel_size=voxel_size) expected_gradient_field = np.zeros((live_field.shape[0],",
"twist_vector_to_matrix2d def sdf_gradient_wrt_to_twist(live_field, y_field, x_field, twist_vector, offset, voxel_size): sdf_gradient_wrt_to_voxel = np.zeros((1, 2)) if",
"= np.array([[1, 1, 1], [0, 0, 0], [-1, -1, -1]]) twist_vector = np.array([[0.],",
"np.array([-1, -1, 1]) voxel_size = 1 gradient_field = calculate_gradient_wrt_twist(live_field, twist_vector, array_offset=offset, voxel_size=voxel_size) expected_gradient_field",
"< -1) or (pre_sdf < -1): sdf_gradient_wrt_to_voxel[0, 1] = 0 else: sdf_gradient_wrt_to_voxel[0, 1]",
"TestCase import numpy as np from rigid_opt.sdf_gradient_field import calculate_gradient_wrt_twist from math_utils.transformation import twist_vector_to_matrix2d",
"= 0 else: sdf_gradient_wrt_to_voxel[0, 0] = post_sdf - live_field[y_field, x_field] elif x_field +",
"1, x_field] if (post_sdf < -1) or (pre_sdf < -1): sdf_gradient_wrt_to_voxel[0, 1] =",
"-1]]) twist_vector = np.array([[0.], [0.], [.5]]) offset = np.array([-1, -1, 1]) voxel_size =",
"x_field + 1] if (post_sdf < -1) or (pre_sdf < -1): sdf_gradient_wrt_to_voxel[0, 0]",
"else: sdf_gradient_wrt_to_voxel[0, 0] = (post_sdf - pre_sdf) / 2 x_voxel = (x_field +",
"x_field, twist_vector, offset, voxel_size) self.assertTrue(np.allclose(expected_gradient_field, gradient_field)) def test_sdf_gradient_wrt_twist05(self): live_field = np.array([[1, 0, -1],",
"sdf_gradient_wrt_to_twist(live_field, y_field, x_field, twist_vector, offset, voxel_size) self.assertTrue(np.allclose(expected_gradient_field, gradient_field)) def test_sdf_gradient_wrt_twist06(self): live_field = np.array([[1,",
"if (post_sdf < -1) or (pre_sdf < -1): sdf_gradient_wrt_to_voxel[0, 1] = 0 else:",
"- pre_sdf) / 2 x_voxel = (x_field + offset[0])*voxel_size z_voxel = (y_field +",
"live_field[y_field, x_field] elif x_field + 1 > live_field.shape[1] - 1: pre_sdf = live_field[y_field,",
"voxel_size) self.assertTrue(np.allclose(expected_gradient_field, gradient_field)) def test_sdf_gradient_wrt_twist06(self): live_field = np.array([[1, 0, -1], [1, 0, -1],",
"sdf_gradient_wrt_to_twist(live_field, y_field, x_field, twist_vector, offset, voxel_size) self.assertTrue(np.allclose(expected_gradient_field, gradient_field)) def test_sdf_gradient_wrt_twist05(self): live_field = np.array([[1,",
"twist_vector = np.array([[0.], [0.], [0.]]) offset = np.array([-1, -1, 1]) voxel_size = 1",
"post_sdf = live_field[y_field + 1, x_field] if (post_sdf < -1) or (pre_sdf <",
"elif x_field + 1 > live_field.shape[1] - 1: pre_sdf = live_field[y_field, x_field -",
"y_field, x_field, twist_vector, offset, voxel_size) self.assertTrue(np.allclose(expected_gradient_field, gradient_field)) def test_sdf_gradient_wrt_twist03(self): live_field = np.array([[1, 1,",
"pre_sdf else: pre_sdf = live_field[y_field, x_field - 1] post_sdf = live_field[y_field, x_field +",
"else: pre_sdf = live_field[y_field, x_field - 1] post_sdf = live_field[y_field, x_field + 1]",
"sdf_gradient_wrt_to_voxel = np.zeros((1, 2)) if y_field - 1 < 0: post_sdf = live_field[y_field",
"1]) voxel_size = 1 gradient_field = calculate_gradient_wrt_twist(live_field, twist_vector, array_offset=offset, voxel_size=voxel_size) expected_gradient_field = np.zeros((live_field.shape[0],",
"offset, voxel_size) self.assertTrue(np.allclose(expected_gradient_field, gradient_field)) def test_sdf_gradient_wrt_twist02(self): live_field = np.array([[1, 1, 1], [0, 0,",
"in range(live_field.shape[1]): expected_gradient_field[y_field, x_field] = sdf_gradient_wrt_to_twist(live_field, y_field, x_field, twist_vector, offset, voxel_size) self.assertTrue(np.allclose(expected_gradient_field, gradient_field))",
"-1: sdf_gradient_wrt_to_voxel[0, 1] = 0 else: sdf_gradient_wrt_to_voxel[0, 1] = post_sdf - live_field[y_field, x_field]",
"twist_vector, offset, voxel_size) self.assertTrue(np.allclose(expected_gradient_field, gradient_field)) def test_sdf_gradient_wrt_twist06(self): live_field = np.array([[1, 0, -1], [1,",
"expected_gradient_field[y_field, x_field] = sdf_gradient_wrt_to_twist(live_field, y_field, x_field, twist_vector, offset, voxel_size) self.assertTrue(np.allclose(expected_gradient_field, gradient_field)) def test_sdf_gradient_wrt_twist06(self):",
"y_field, x_field, twist_vector, offset, voxel_size) self.assertTrue(np.allclose(expected_gradient_field, gradient_field)) def test_sdf_gradient_wrt_twist06(self): live_field = np.array([[1, 0,",
"sdf_gradient_wrt_to_voxel[0, 1] = (post_sdf - pre_sdf) / 2 if x_field - 1 <",
"[1.], [0.]]) offset = np.array([-1, -1, 1]) voxel_size = 1 gradient_field = calculate_gradient_wrt_twist(live_field,",
"voxel_size = 0.5 gradient_field = calculate_gradient_wrt_twist(live_field, twist_vector, array_offset=offset, voxel_size=voxel_size) expected_gradient_field = np.zeros((live_field.shape[0], live_field.shape[1],",
"np.dot(twist_matrix_homo_inv, point) voxel_gradient_wrt_to_twist = np.array([[1, 0, trans[1]], [0, 1, -trans[0]]]) return np.dot(sdf_gradient_wrt_to_voxel/voxel_size, voxel_gradient_wrt_to_twist).reshape((1,",
"test_sdf_gradient_wrt_twist02(self): live_field = np.array([[1, 1, 1], [0, 0, 0], [-1, -1, -1]]) twist_vector",
"post_sdf < -1: sdf_gradient_wrt_to_voxel[0, 1] = 0 else: sdf_gradient_wrt_to_voxel[0, 1] = post_sdf -",
"twist_vector_to_matrix2d(-twist_vector) trans = np.dot(twist_matrix_homo_inv, point) voxel_gradient_wrt_to_twist = np.array([[1, 0, trans[1]], [0, 1, -trans[0]]])",
"live_field[y_field, x_field + 1] if (post_sdf < -1) or (pre_sdf < -1): sdf_gradient_wrt_to_voxel[0,",
"twist_vector, offset, voxel_size) self.assertTrue(np.allclose(expected_gradient_field, gradient_field)) def test_sdf_gradient_wrt_twist04(self): live_field = np.array([[1, 0, -1], [1,",
"return np.dot(sdf_gradient_wrt_to_voxel/voxel_size, voxel_gradient_wrt_to_twist).reshape((1, -1)) class MyTestCase(TestCase): def test_sdf_gradient_wrt_twist01(self): live_field = np.array([[1, 0, -1],",
"live_field.shape[1] - 1: pre_sdf = live_field[y_field, x_field - 1] if pre_sdf < -1:",
"= sdf_gradient_wrt_to_twist(live_field, y_field, x_field, twist_vector, offset, voxel_size) self.assertTrue(np.allclose(expected_gradient_field, gradient_field)) def test_sdf_gradient_wrt_twist05(self): live_field =",
"[1, 0, -1], [1, 0, -1]]) twist_vector = np.array([[0.], [1.], [0.]]) offset =",
"0], [-1, -1, -1]]) twist_vector = np.array([[0.], [0.], [0.]]) offset = np.array([-1, -1,",
"import TestCase import numpy as np from rigid_opt.sdf_gradient_field import calculate_gradient_wrt_twist from math_utils.transformation import",
"- 1 < 0: post_sdf = live_field[y_field, x_field + 1] if post_sdf <",
"-1)) class MyTestCase(TestCase): def test_sdf_gradient_wrt_twist01(self): live_field = np.array([[1, 0, -1], [1, 0, -1],",
"x_field + 1 > live_field.shape[1] - 1: pre_sdf = live_field[y_field, x_field - 1]",
"dtype=np.float32) for y_field in range(live_field.shape[0]): for x_field in range(live_field.shape[1]): expected_gradient_field[y_field, x_field] = sdf_gradient_wrt_to_twist(live_field,",
"-1], [1, 0, -1], [1, 0, -1]]) twist_vector = np.array([[0.], [0.], [.5]]) offset",
"= 0.5 gradient_field = calculate_gradient_wrt_twist(live_field, twist_vector, array_offset=offset, voxel_size=voxel_size) expected_gradient_field = np.zeros((live_field.shape[0], live_field.shape[1], 3),",
"np.array([[0.], [0.], [0.]]) offset = np.array([-1, -1, 1]) voxel_size = 1 gradient_field =",
"0, trans[1]], [0, 1, -trans[0]]]) return np.dot(sdf_gradient_wrt_to_voxel/voxel_size, voxel_gradient_wrt_to_twist).reshape((1, -1)) class MyTestCase(TestCase): def test_sdf_gradient_wrt_twist01(self):",
"sdf_gradient_wrt_to_twist(live_field, y_field, x_field, twist_vector, offset, voxel_size) self.assertTrue(np.allclose(expected_gradient_field, gradient_field)) def test_sdf_gradient_wrt_twist02(self): live_field = np.array([[1,",
"from unittest import TestCase import numpy as np from rigid_opt.sdf_gradient_field import calculate_gradient_wrt_twist from",
"[1, 0, -1]]) twist_vector = np.array([[0.], [0.], [0.]]) offset = np.array([-1, -1, 1])",
"sdf_gradient_wrt_to_voxel[0, 1] = 0 else: sdf_gradient_wrt_to_voxel[0, 1] = post_sdf - live_field[y_field, x_field] elif",
"1 gradient_field = calculate_gradient_wrt_twist(live_field, twist_vector, array_offset=offset, voxel_size=voxel_size) expected_gradient_field = np.zeros((live_field.shape[0], live_field.shape[1], 3), dtype=np.float32)",
"1] if post_sdf < -1: sdf_gradient_wrt_to_voxel[0, 0] = 0 else: sdf_gradient_wrt_to_voxel[0, 0] =",
"x_field + 1] if post_sdf < -1: sdf_gradient_wrt_to_voxel[0, 0] = 0 else: sdf_gradient_wrt_to_voxel[0,",
"if post_sdf < -1: sdf_gradient_wrt_to_voxel[0, 0] = 0 else: sdf_gradient_wrt_to_voxel[0, 0] = post_sdf",
"calculate_gradient_wrt_twist(live_field, twist_vector, array_offset=offset, voxel_size=voxel_size) expected_gradient_field = np.zeros((live_field.shape[0], live_field.shape[1], 3), dtype=np.float32) for y_field in",
"2 if x_field - 1 < 0: post_sdf = live_field[y_field, x_field + 1]",
"pre_sdf else: pre_sdf = live_field[y_field - 1, x_field] post_sdf = live_field[y_field + 1,",
"sdf_gradient_wrt_to_twist(live_field, y_field, x_field, twist_vector, offset, voxel_size) self.assertTrue(np.allclose(expected_gradient_field, gradient_field)) def test_sdf_gradient_wrt_twist04(self): live_field = np.array([[1,",
"-1: sdf_gradient_wrt_to_voxel[0, 0] = 0 else: sdf_gradient_wrt_to_voxel[0, 0] = post_sdf - live_field[y_field, x_field]",
"< -1: sdf_gradient_wrt_to_voxel[0, 0] = 0 else: sdf_gradient_wrt_to_voxel[0, 0] = post_sdf - live_field[y_field,",
"0] = (post_sdf - pre_sdf) / 2 x_voxel = (x_field + offset[0])*voxel_size z_voxel",
"gradient_field)) def test_sdf_gradient_wrt_twist04(self): live_field = np.array([[1, 0, -1], [1, 0, -1], [1, 0,",
"-1], [1, 0, -1]]) twist_vector = np.array([[0.], [-1.], [0.]]) offset = np.array([-1, -1,",
"y_field - 1 < 0: post_sdf = live_field[y_field + 1, x_field] if post_sdf",
"= np.array([[0.], [1.], [0.]]) offset = np.array([-1, -1, 1]) voxel_size = 1 gradient_field",
"0 else: sdf_gradient_wrt_to_voxel[0, 0] = live_field[y_field, x_field] - pre_sdf else: pre_sdf = live_field[y_field,",
"0] = live_field[y_field, x_field] - pre_sdf else: pre_sdf = live_field[y_field, x_field - 1]",
"offset = np.array([-1, -1, 1]) voxel_size = 1 gradient_field = calculate_gradient_wrt_twist(live_field, twist_vector, array_offset=offset,",
"-1], [1, 0, -1]]) twist_vector = np.array([[0.], [1.], [0.]]) offset = np.array([-1, -1,",
"self.assertTrue(np.allclose(expected_gradient_field, gradient_field)) def test_sdf_gradient_wrt_twist06(self): live_field = np.array([[1, 0, -1], [1, 0, -1], [1,",
"self.assertTrue(np.allclose(expected_gradient_field, gradient_field)) def test_sdf_gradient_wrt_twist05(self): live_field = np.array([[1, 0, -1], [1, 0, -1], [1,",
"sdf_gradient_wrt_to_voxel[0, 0] = post_sdf - live_field[y_field, x_field] elif x_field + 1 > live_field.shape[1]",
"else: sdf_gradient_wrt_to_voxel[0, 1] = post_sdf - live_field[y_field, x_field] elif y_field + 1 >",
"as np from rigid_opt.sdf_gradient_field import calculate_gradient_wrt_twist from math_utils.transformation import twist_vector_to_matrix2d def sdf_gradient_wrt_to_twist(live_field, y_field,",
"array_offset=offset, voxel_size=voxel_size) expected_gradient_field = np.zeros((live_field.shape[0], live_field.shape[1], 3), dtype=np.float32) for y_field in range(live_field.shape[0]): for",
"expected_gradient_field[y_field, x_field] = sdf_gradient_wrt_to_twist(live_field, y_field, x_field, twist_vector, offset, voxel_size) self.assertTrue(np.allclose(expected_gradient_field, gradient_field)) def test_sdf_gradient_wrt_twist04(self):",
"np.array([[1, 0, -1], [1, 0, -1], [1, 0, -1]]) twist_vector = np.array([[0.], [1.],",
"- 1, x_field] if pre_sdf < -1: sdf_gradient_wrt_to_voxel[0, 1] = 0 else: sdf_gradient_wrt_to_voxel[0,",
"- live_field[y_field, x_field] elif x_field + 1 > live_field.shape[1] - 1: pre_sdf =",
"= 0 else: sdf_gradient_wrt_to_voxel[0, 1] = post_sdf - live_field[y_field, x_field] elif y_field +",
"expected_gradient_field[y_field, x_field] = sdf_gradient_wrt_to_twist(live_field, y_field, x_field, twist_vector, offset, voxel_size) self.assertTrue(np.allclose(expected_gradient_field, gradient_field)) def test_sdf_gradient_wrt_twist02(self):",
"live_field[y_field + 1, x_field] if post_sdf < -1: sdf_gradient_wrt_to_voxel[0, 1] = 0 else:",
"= sdf_gradient_wrt_to_twist(live_field, y_field, x_field, twist_vector, offset, voxel_size) self.assertTrue(np.allclose(expected_gradient_field, gradient_field)) def test_sdf_gradient_wrt_twist02(self): live_field =",
"np.array([[1, 0, -1], [1, 0, -1], [1, 0, -1]]) twist_vector = np.array([[0.], [-1.],",
"0 else: sdf_gradient_wrt_to_voxel[0, 0] = (post_sdf - pre_sdf) / 2 x_voxel = (x_field",
"= live_field[y_field - 1, x_field] post_sdf = live_field[y_field + 1, x_field] if (post_sdf",
"[0.], [.5]]) offset = np.array([-1, -1, 1]) voxel_size = 0.5 gradient_field = calculate_gradient_wrt_twist(live_field,",
"= np.array([[x_voxel, z_voxel, 1.]], dtype=np.float32).T twist_matrix_homo_inv = twist_vector_to_matrix2d(-twist_vector) trans = np.dot(twist_matrix_homo_inv, point) voxel_gradient_wrt_to_twist",
"or (pre_sdf < -1): sdf_gradient_wrt_to_voxel[0, 1] = 0 else: sdf_gradient_wrt_to_voxel[0, 1] = (post_sdf",
"0, -1]]) twist_vector = np.array([[0.], [0.], [.5]]) offset = np.array([-1, -1, 1]) voxel_size",
"point) voxel_gradient_wrt_to_twist = np.array([[1, 0, trans[1]], [0, 1, -trans[0]]]) return np.dot(sdf_gradient_wrt_to_voxel/voxel_size, voxel_gradient_wrt_to_twist).reshape((1, -1))",
"= np.array([[0.], [0.], [.5]]) offset = np.array([-1, -1, 1]) voxel_size = 0.5 gradient_field",
"[0.]]) offset = np.array([-1, -1, 1]) voxel_size = 2 gradient_field = calculate_gradient_wrt_twist(live_field, twist_vector,",
"/ 2 x_voxel = (x_field + offset[0])*voxel_size z_voxel = (y_field + offset[2])*voxel_size point",
"offset, voxel_size) self.assertTrue(np.allclose(expected_gradient_field, gradient_field)) def test_sdf_gradient_wrt_twist04(self): live_field = np.array([[1, 0, -1], [1, 0,",
"z_voxel, 1.]], dtype=np.float32).T twist_matrix_homo_inv = twist_vector_to_matrix2d(-twist_vector) trans = np.dot(twist_matrix_homo_inv, point) voxel_gradient_wrt_to_twist = np.array([[1,",
"= (post_sdf - pre_sdf) / 2 if x_field - 1 < 0: post_sdf",
"[1, 0, -1]]) twist_vector = np.array([[0.], [-1.], [0.]]) offset = np.array([-1, -1, 1])",
"np.array([[0.], [0.], [.5]]) offset = np.array([-1, -1, 1]) voxel_size = 0.5 gradient_field =",
"1, x_field] post_sdf = live_field[y_field + 1, x_field] if (post_sdf < -1) or",
"(post_sdf - pre_sdf) / 2 x_voxel = (x_field + offset[0])*voxel_size z_voxel = (y_field",
"0: post_sdf = live_field[y_field, x_field + 1] if post_sdf < -1: sdf_gradient_wrt_to_voxel[0, 0]",
"- live_field[y_field, x_field] elif y_field + 1 > live_field.shape[0] - 1: pre_sdf =",
"-1) or (pre_sdf < -1): sdf_gradient_wrt_to_voxel[0, 0] = 0 else: sdf_gradient_wrt_to_voxel[0, 0] =",
"y_field, x_field, twist_vector, offset, voxel_size) self.assertTrue(np.allclose(expected_gradient_field, gradient_field)) def test_sdf_gradient_wrt_twist02(self): live_field = np.array([[1, 1,",
"x_field, twist_vector, offset, voxel_size) self.assertTrue(np.allclose(expected_gradient_field, gradient_field)) def test_sdf_gradient_wrt_twist03(self): live_field = np.array([[1, 1, 1],",
"1 > live_field.shape[1] - 1: pre_sdf = live_field[y_field, x_field - 1] if pre_sdf",
"1] = live_field[y_field, x_field] - pre_sdf else: pre_sdf = live_field[y_field - 1, x_field]",
"1 > live_field.shape[0] - 1: pre_sdf = live_field[y_field - 1, x_field] if pre_sdf",
"[1, 0, -1], [1, 0, -1]]) twist_vector = np.array([[0.], [-1.], [0.]]) offset =",
"< -1: sdf_gradient_wrt_to_voxel[0, 0] = 0 else: sdf_gradient_wrt_to_voxel[0, 0] = live_field[y_field, x_field] -",
"x_voxel = (x_field + offset[0])*voxel_size z_voxel = (y_field + offset[2])*voxel_size point = np.array([[x_voxel,",
"1 < 0: post_sdf = live_field[y_field, x_field + 1] if post_sdf < -1:",
"[-1.], [0.]]) offset = np.array([-1, -1, 1]) voxel_size = 1 gradient_field = calculate_gradient_wrt_twist(live_field,",
"trans[1]], [0, 1, -trans[0]]]) return np.dot(sdf_gradient_wrt_to_voxel/voxel_size, voxel_gradient_wrt_to_twist).reshape((1, -1)) class MyTestCase(TestCase): def test_sdf_gradient_wrt_twist01(self): live_field",
"def test_sdf_gradient_wrt_twist03(self): live_field = np.array([[1, 1, 1], [0, 0, 0], [-1, -1, -1]])",
"twist_matrix_homo_inv = twist_vector_to_matrix2d(-twist_vector) trans = np.dot(twist_matrix_homo_inv, point) voxel_gradient_wrt_to_twist = np.array([[1, 0, trans[1]], [0,",
"x_field] = sdf_gradient_wrt_to_twist(live_field, y_field, x_field, twist_vector, offset, voxel_size) self.assertTrue(np.allclose(expected_gradient_field, gradient_field)) def test_sdf_gradient_wrt_twist05(self): live_field",
"< 0: post_sdf = live_field[y_field, x_field + 1] if post_sdf < -1: sdf_gradient_wrt_to_voxel[0,",
"elif y_field + 1 > live_field.shape[0] - 1: pre_sdf = live_field[y_field - 1,",
"= 0 else: sdf_gradient_wrt_to_voxel[0, 0] = (post_sdf - pre_sdf) / 2 x_voxel =",
"= post_sdf - live_field[y_field, x_field] elif y_field + 1 > live_field.shape[0] - 1:",
"x_field, twist_vector, offset, voxel_size): sdf_gradient_wrt_to_voxel = np.zeros((1, 2)) if y_field - 1 <",
"= sdf_gradient_wrt_to_twist(live_field, y_field, x_field, twist_vector, offset, voxel_size) self.assertTrue(np.allclose(expected_gradient_field, gradient_field)) def test_sdf_gradient_wrt_twist06(self): live_field =",
"0: post_sdf = live_field[y_field + 1, x_field] if post_sdf < -1: sdf_gradient_wrt_to_voxel[0, 1]",
"0, -1], [1, 0, -1], [1, 0, -1]]) twist_vector = np.array([[0.], [-1.], [0.]])",
"= live_field[y_field + 1, x_field] if post_sdf < -1: sdf_gradient_wrt_to_voxel[0, 1] = 0",
"[1, 0, -1]]) twist_vector = np.array([[0.], [1.], [0.]]) offset = np.array([-1, -1, 1])",
"1] if pre_sdf < -1: sdf_gradient_wrt_to_voxel[0, 0] = 0 else: sdf_gradient_wrt_to_voxel[0, 0] =",
"x_field, twist_vector, offset, voxel_size) self.assertTrue(np.allclose(expected_gradient_field, gradient_field)) def test_sdf_gradient_wrt_twist06(self): live_field = np.array([[1, 0, -1],",
"-1): sdf_gradient_wrt_to_voxel[0, 0] = 0 else: sdf_gradient_wrt_to_voxel[0, 0] = (post_sdf - pre_sdf) /",
"np.array([[x_voxel, z_voxel, 1.]], dtype=np.float32).T twist_matrix_homo_inv = twist_vector_to_matrix2d(-twist_vector) trans = np.dot(twist_matrix_homo_inv, point) voxel_gradient_wrt_to_twist =",
"y_field + 1 > live_field.shape[0] - 1: pre_sdf = live_field[y_field - 1, x_field]",
"for y_field in range(live_field.shape[0]): for x_field in range(live_field.shape[1]): expected_gradient_field[y_field, x_field] = sdf_gradient_wrt_to_twist(live_field, y_field,",
"-1) or (pre_sdf < -1): sdf_gradient_wrt_to_voxel[0, 1] = 0 else: sdf_gradient_wrt_to_voxel[0, 1] =",
"0 else: sdf_gradient_wrt_to_voxel[0, 1] = live_field[y_field, x_field] - pre_sdf else: pre_sdf = live_field[y_field",
"0, -1], [1, 0, -1], [1, 0, -1]]) twist_vector = np.array([[0.], [0.], [0.]])",
"-1], [1, 0, -1], [1, 0, -1]]) twist_vector = np.array([[0.], [-1.], [0.]]) offset",
"trans = np.dot(twist_matrix_homo_inv, point) voxel_gradient_wrt_to_twist = np.array([[1, 0, trans[1]], [0, 1, -trans[0]]]) return",
"live_field[y_field, x_field + 1] if post_sdf < -1: sdf_gradient_wrt_to_voxel[0, 0] = 0 else:",
"+ 1, x_field] if post_sdf < -1: sdf_gradient_wrt_to_voxel[0, 1] = 0 else: sdf_gradient_wrt_to_voxel[0,",
"= (x_field + offset[0])*voxel_size z_voxel = (y_field + offset[2])*voxel_size point = np.array([[x_voxel, z_voxel,",
"= live_field[y_field, x_field - 1] if pre_sdf < -1: sdf_gradient_wrt_to_voxel[0, 0] = 0",
"1]) voxel_size = 0.5 gradient_field = calculate_gradient_wrt_twist(live_field, twist_vector, array_offset=offset, voxel_size=voxel_size) expected_gradient_field = np.zeros((live_field.shape[0],",
"post_sdf = live_field[y_field, x_field + 1] if (post_sdf < -1) or (pre_sdf <",
"voxel_size = 2 gradient_field = calculate_gradient_wrt_twist(live_field, twist_vector, array_offset=offset, voxel_size=voxel_size) expected_gradient_field = np.zeros((live_field.shape[0], live_field.shape[1],",
"[-1, -1, -1]]) twist_vector = np.array([[0.], [0.], [0.]]) offset = np.array([-1, -1, 1])",
"pre_sdf = live_field[y_field, x_field - 1] if pre_sdf < -1: sdf_gradient_wrt_to_voxel[0, 0] =",
"-1]]) twist_vector = np.array([[0.], [0.], [0.]]) offset = np.array([-1, -1, 1]) voxel_size =",
"pre_sdf < -1: sdf_gradient_wrt_to_voxel[0, 0] = 0 else: sdf_gradient_wrt_to_voxel[0, 0] = live_field[y_field, x_field]",
"1, x_field] if pre_sdf < -1: sdf_gradient_wrt_to_voxel[0, 1] = 0 else: sdf_gradient_wrt_to_voxel[0, 1]",
"sdf_gradient_wrt_to_voxel[0, 1] = live_field[y_field, x_field] - pre_sdf else: pre_sdf = live_field[y_field - 1,",
"0 else: sdf_gradient_wrt_to_voxel[0, 1] = post_sdf - live_field[y_field, x_field] elif y_field + 1",
"def test_sdf_gradient_wrt_twist04(self): live_field = np.array([[1, 0, -1], [1, 0, -1], [1, 0, -1]])",
"[0.], [0.]]) offset = np.array([-1, -1, 1]) voxel_size = 1 gradient_field = calculate_gradient_wrt_twist(live_field,",
"if pre_sdf < -1: sdf_gradient_wrt_to_voxel[0, 0] = 0 else: sdf_gradient_wrt_to_voxel[0, 0] = live_field[y_field,",
"math_utils.transformation import twist_vector_to_matrix2d def sdf_gradient_wrt_to_twist(live_field, y_field, x_field, twist_vector, offset, voxel_size): sdf_gradient_wrt_to_voxel = np.zeros((1,",
"live_field[y_field + 1, x_field] if (post_sdf < -1) or (pre_sdf < -1): sdf_gradient_wrt_to_voxel[0,",
"1] if (post_sdf < -1) or (pre_sdf < -1): sdf_gradient_wrt_to_voxel[0, 0] = 0",
"if post_sdf < -1: sdf_gradient_wrt_to_voxel[0, 1] = 0 else: sdf_gradient_wrt_to_voxel[0, 1] = post_sdf",
"= 0 else: sdf_gradient_wrt_to_voxel[0, 1] = live_field[y_field, x_field] - pre_sdf else: pre_sdf =",
"np.array([[1, 0, trans[1]], [0, 1, -trans[0]]]) return np.dot(sdf_gradient_wrt_to_voxel/voxel_size, voxel_gradient_wrt_to_twist).reshape((1, -1)) class MyTestCase(TestCase): def",
"/ 2 if x_field - 1 < 0: post_sdf = live_field[y_field, x_field +",
"twist_vector = np.array([[0.], [0.], [0.]]) offset = np.array([-1, -1, 1]) voxel_size = 2",
"twist_vector, offset, voxel_size): sdf_gradient_wrt_to_voxel = np.zeros((1, 2)) if y_field - 1 < 0:",
"0.5 gradient_field = calculate_gradient_wrt_twist(live_field, twist_vector, array_offset=offset, voxel_size=voxel_size) expected_gradient_field = np.zeros((live_field.shape[0], live_field.shape[1], 3), dtype=np.float32)",
"= live_field[y_field, x_field] - pre_sdf else: pre_sdf = live_field[y_field, x_field - 1] post_sdf"
] |
[
"point): point_name = point.get_point_name() self.point_store[point_name] = point return True def get_point_store(self): return self.point_store",
"__init__(self): self.point_store = {} self.number_points = 0 def set_new_point(self, point): point_name = point.get_point_name()",
"storage options. def __init__(self): self.point_store = {} self.number_points = 0 def set_new_point(self, point):",
"class NewPointStore: # TODO implement local database storage options. def __init__(self): self.point_store =",
"set_new_point(self, point): point_name = point.get_point_name() self.point_store[point_name] = point return True def get_point_store(self): return",
"<gh_stars>0 class NewPointStore: # TODO implement local database storage options. def __init__(self): self.point_store",
"# TODO implement local database storage options. def __init__(self): self.point_store = {} self.number_points",
"TODO implement local database storage options. def __init__(self): self.point_store = {} self.number_points =",
"NewPointStore: # TODO implement local database storage options. def __init__(self): self.point_store = {}",
"{} self.number_points = 0 def set_new_point(self, point): point_name = point.get_point_name() self.point_store[point_name] = point",
"def __init__(self): self.point_store = {} self.number_points = 0 def set_new_point(self, point): point_name =",
"database storage options. def __init__(self): self.point_store = {} self.number_points = 0 def set_new_point(self,",
"0 def set_new_point(self, point): point_name = point.get_point_name() self.point_store[point_name] = point return True def",
"local database storage options. def __init__(self): self.point_store = {} self.number_points = 0 def",
"def set_new_point(self, point): point_name = point.get_point_name() self.point_store[point_name] = point return True def get_point_store(self):",
"self.point_store = {} self.number_points = 0 def set_new_point(self, point): point_name = point.get_point_name() self.point_store[point_name]",
"= {} self.number_points = 0 def set_new_point(self, point): point_name = point.get_point_name() self.point_store[point_name] =",
"self.number_points = 0 def set_new_point(self, point): point_name = point.get_point_name() self.point_store[point_name] = point return",
"= 0 def set_new_point(self, point): point_name = point.get_point_name() self.point_store[point_name] = point return True",
"implement local database storage options. def __init__(self): self.point_store = {} self.number_points = 0",
"options. def __init__(self): self.point_store = {} self.number_points = 0 def set_new_point(self, point): point_name"
] |
[
"Número {} foi divisível {} vezes'.format(num,tot)) if tot == 2: print('E por isso",
"não um número primo. num = int(input('Digite um número: ')) tot = 0",
"diga se ele é ou não um número primo. num = int(input('Digite um",
"um número primo. num = int(input('Digite um número: ')) tot = 0 for",
"in range(1,num+1): if num % i == 0: print('\\033[33m', end='') tot += 1",
"end='') tot += 1 else: print('\\033[31m', end='') print('{} '.format(i), end='') print('\\n\\033[mO Número {}",
"ele é ou não um número primo. num = int(input('Digite um número: '))",
"int(input('Digite um número: ')) tot = 0 for i in range(1,num+1): if num",
"end='') print('{} '.format(i), end='') print('\\n\\033[mO Número {} foi divisível {} vezes'.format(num,tot)) if tot",
"+= 1 else: print('\\033[31m', end='') print('{} '.format(i), end='') print('\\n\\033[mO Número {} foi divisível",
"que leia um número inteiro e diga se ele é ou não um",
"i == 0: print('\\033[33m', end='') tot += 1 else: print('\\033[31m', end='') print('{} '.format(i),",
"por isso ele é PRIMO!') else: print('E por isso ele NÃO e PRIMO!')",
"número primo. num = int(input('Digite um número: ')) tot = 0 for i",
"print('E por isso ele é PRIMO!') else: print('E por isso ele NÃO e",
"num % i == 0: print('\\033[33m', end='') tot += 1 else: print('\\033[31m', end='')",
"== 0: print('\\033[33m', end='') tot += 1 else: print('\\033[31m', end='') print('{} '.format(i), end='')",
"== 2: print('E por isso ele é PRIMO!') else: print('E por isso ele",
"= 0 for i in range(1,num+1): if num % i == 0: print('\\033[33m',",
"vezes'.format(num,tot)) if tot == 2: print('E por isso ele é PRIMO!') else: print('E",
"if tot == 2: print('E por isso ele é PRIMO!') else: print('E por",
"print('{} '.format(i), end='') print('\\n\\033[mO Número {} foi divisível {} vezes'.format(num,tot)) if tot ==",
"else: print('\\033[31m', end='') print('{} '.format(i), end='') print('\\n\\033[mO Número {} foi divisível {} vezes'.format(num,tot))",
"tot = 0 for i in range(1,num+1): if num % i == 0:",
"tot += 1 else: print('\\033[31m', end='') print('{} '.format(i), end='') print('\\n\\033[mO Número {} foi",
"programa que leia um número inteiro e diga se ele é ou não",
"if num % i == 0: print('\\033[33m', end='') tot += 1 else: print('\\033[31m',",
"primo. num = int(input('Digite um número: ')) tot = 0 for i in",
"número: ')) tot = 0 for i in range(1,num+1): if num % i",
"for i in range(1,num+1): if num % i == 0: print('\\033[33m', end='') tot",
"end='') print('\\n\\033[mO Número {} foi divisível {} vezes'.format(num,tot)) if tot == 2: print('E",
"print('\\n\\033[mO Número {} foi divisível {} vezes'.format(num,tot)) if tot == 2: print('E por",
"1 else: print('\\033[31m', end='') print('{} '.format(i), end='') print('\\n\\033[mO Número {} foi divisível {}",
"2: print('E por isso ele é PRIMO!') else: print('E por isso ele NÃO",
"se ele é ou não um número primo. num = int(input('Digite um número:",
"tot == 2: print('E por isso ele é PRIMO!') else: print('E por isso",
"range(1,num+1): if num % i == 0: print('\\033[33m', end='') tot += 1 else:",
"% i == 0: print('\\033[33m', end='') tot += 1 else: print('\\033[31m', end='') print('{}",
"um programa que leia um número inteiro e diga se ele é ou",
"')) tot = 0 for i in range(1,num+1): if num % i ==",
"um número inteiro e diga se ele é ou não um número primo.",
"ou não um número primo. num = int(input('Digite um número: ')) tot =",
"= int(input('Digite um número: ')) tot = 0 for i in range(1,num+1): if",
"0 for i in range(1,num+1): if num % i == 0: print('\\033[33m', end='')",
"número inteiro e diga se ele é ou não um número primo. num",
"0: print('\\033[33m', end='') tot += 1 else: print('\\033[31m', end='') print('{} '.format(i), end='') print('\\n\\033[mO",
"foi divisível {} vezes'.format(num,tot)) if tot == 2: print('E por isso ele é",
"{} vezes'.format(num,tot)) if tot == 2: print('E por isso ele é PRIMO!') else:",
"leia um número inteiro e diga se ele é ou não um número",
"'.format(i), end='') print('\\n\\033[mO Número {} foi divisível {} vezes'.format(num,tot)) if tot == 2:",
"{} foi divisível {} vezes'.format(num,tot)) if tot == 2: print('E por isso ele",
"um número: ')) tot = 0 for i in range(1,num+1): if num %",
"print('\\033[31m', end='') print('{} '.format(i), end='') print('\\n\\033[mO Número {} foi divisível {} vezes'.format(num,tot)) if",
"inteiro e diga se ele é ou não um número primo. num =",
"é ou não um número primo. num = int(input('Digite um número: ')) tot",
"e diga se ele é ou não um número primo. num = int(input('Digite",
"num = int(input('Digite um número: ')) tot = 0 for i in range(1,num+1):",
"print('\\033[33m', end='') tot += 1 else: print('\\033[31m', end='') print('{} '.format(i), end='') print('\\n\\033[mO Número",
"i in range(1,num+1): if num % i == 0: print('\\033[33m', end='') tot +=",
"#Faça um programa que leia um número inteiro e diga se ele é",
"divisível {} vezes'.format(num,tot)) if tot == 2: print('E por isso ele é PRIMO!')"
] |
[
"<reponame>samarv/travo from django.db import models class organization(models.Model): def __str__(self): return self.name name =",
"access_token = models.CharField(max_length=200) installation_date = models.DateTimeField( 'installation date', auto_now_add=True) bot_access_token = models.CharField(max_length=200) class",
"avatar = models.CharField(max_length=500) class shoutout(models.Model): def __str__(self): return self.message giver_id = models.ForeignKey(user, on_delete=models.CASCADE)",
"class shoutout(models.Model): def __str__(self): return self.message giver_id = models.ForeignKey(user, on_delete=models.CASCADE) receiver_id = models.ForeignKey(",
"unique=True) slack_org_id = models.CharField(max_length=50, unique=True) channel_name = models.CharField(max_length=50) channel_id = models.CharField(max_length=50) access_token =",
"from django.db import models class organization(models.Model): def __str__(self): return self.name name = models.CharField(max_length=50,",
"giver_id = models.ForeignKey(user, on_delete=models.CASCADE) receiver_id = models.ForeignKey( user, on_delete=models.CASCADE, related_name=\"r_id\") message = models.CharField(max_length=5000)",
"= models.DateTimeField( 'installation date', auto_now_add=True) bot_access_token = models.CharField(max_length=200) class user(models.Model): def __str__(self): return",
"def __str__(self): return self.name org_id = models.ForeignKey(organization, on_delete=models.CASCADE) slack_mem_id = models.CharField(max_length=50, unique=True) email",
"channel_name = models.CharField(max_length=50) channel_id = models.CharField(max_length=50) access_token = models.CharField(max_length=200) installation_date = models.DateTimeField( 'installation",
"slack_mem_id = models.CharField(max_length=50, unique=True) email = models.CharField(max_length=50, unique=True) name = models.CharField(max_length=50) avatar =",
"user(models.Model): def __str__(self): return self.name org_id = models.ForeignKey(organization, on_delete=models.CASCADE) slack_mem_id = models.CharField(max_length=50, unique=True)",
"= models.ForeignKey( user, on_delete=models.CASCADE, related_name=\"r_id\") message = models.CharField(max_length=5000) timestamps = models.DateTimeField('timestamp', auto_now_add=True) message_ts",
"models.CharField(max_length=200) installation_date = models.DateTimeField( 'installation date', auto_now_add=True) bot_access_token = models.CharField(max_length=200) class user(models.Model): def",
"return self.name name = models.CharField(max_length=50, unique=True) slack_org_id = models.CharField(max_length=50, unique=True) channel_name = models.CharField(max_length=50)",
"receiver_id = models.ForeignKey( user, on_delete=models.CASCADE, related_name=\"r_id\") message = models.CharField(max_length=5000) timestamps = models.DateTimeField('timestamp', auto_now_add=True)",
"= models.CharField(max_length=50) access_token = models.CharField(max_length=200) installation_date = models.DateTimeField( 'installation date', auto_now_add=True) bot_access_token =",
"'installation date', auto_now_add=True) bot_access_token = models.CharField(max_length=200) class user(models.Model): def __str__(self): return self.name org_id",
"= models.CharField(max_length=50, unique=True) slack_org_id = models.CharField(max_length=50, unique=True) channel_name = models.CharField(max_length=50) channel_id = models.CharField(max_length=50)",
"organization(models.Model): def __str__(self): return self.name name = models.CharField(max_length=50, unique=True) slack_org_id = models.CharField(max_length=50, unique=True)",
"installation_date = models.DateTimeField( 'installation date', auto_now_add=True) bot_access_token = models.CharField(max_length=200) class user(models.Model): def __str__(self):",
"shoutout(models.Model): def __str__(self): return self.message giver_id = models.ForeignKey(user, on_delete=models.CASCADE) receiver_id = models.ForeignKey( user,",
"= models.CharField(max_length=50, unique=True) channel_name = models.CharField(max_length=50) channel_id = models.CharField(max_length=50) access_token = models.CharField(max_length=200) installation_date",
"name = models.CharField(max_length=50) avatar = models.CharField(max_length=500) class shoutout(models.Model): def __str__(self): return self.message giver_id",
"models.CharField(max_length=50, unique=True) channel_name = models.CharField(max_length=50) channel_id = models.CharField(max_length=50) access_token = models.CharField(max_length=200) installation_date =",
"bot_access_token = models.CharField(max_length=200) class user(models.Model): def __str__(self): return self.name org_id = models.ForeignKey(organization, on_delete=models.CASCADE)",
"models.CharField(max_length=50) access_token = models.CharField(max_length=200) installation_date = models.DateTimeField( 'installation date', auto_now_add=True) bot_access_token = models.CharField(max_length=200)",
"date', auto_now_add=True) bot_access_token = models.CharField(max_length=200) class user(models.Model): def __str__(self): return self.name org_id =",
"unique=True) email = models.CharField(max_length=50, unique=True) name = models.CharField(max_length=50) avatar = models.CharField(max_length=500) class shoutout(models.Model):",
"email = models.CharField(max_length=50, unique=True) name = models.CharField(max_length=50) avatar = models.CharField(max_length=500) class shoutout(models.Model): def",
"on_delete=models.CASCADE) receiver_id = models.ForeignKey( user, on_delete=models.CASCADE, related_name=\"r_id\") message = models.CharField(max_length=5000) timestamps = models.DateTimeField('timestamp',",
"unique=True) channel_name = models.CharField(max_length=50) channel_id = models.CharField(max_length=50) access_token = models.CharField(max_length=200) installation_date = models.DateTimeField(",
"self.name org_id = models.ForeignKey(organization, on_delete=models.CASCADE) slack_mem_id = models.CharField(max_length=50, unique=True) email = models.CharField(max_length=50, unique=True)",
"models.ForeignKey( user, on_delete=models.CASCADE, related_name=\"r_id\") message = models.CharField(max_length=5000) timestamps = models.DateTimeField('timestamp', auto_now_add=True) message_ts =",
"models.DateTimeField( 'installation date', auto_now_add=True) bot_access_token = models.CharField(max_length=200) class user(models.Model): def __str__(self): return self.name",
"models.CharField(max_length=50) avatar = models.CharField(max_length=500) class shoutout(models.Model): def __str__(self): return self.message giver_id = models.ForeignKey(user,",
"__str__(self): return self.name org_id = models.ForeignKey(organization, on_delete=models.CASCADE) slack_mem_id = models.CharField(max_length=50, unique=True) email =",
"channel_id = models.CharField(max_length=50) access_token = models.CharField(max_length=200) installation_date = models.DateTimeField( 'installation date', auto_now_add=True) bot_access_token",
"= models.CharField(max_length=50, unique=True) email = models.CharField(max_length=50, unique=True) name = models.CharField(max_length=50) avatar = models.CharField(max_length=500)",
"= models.CharField(max_length=50) avatar = models.CharField(max_length=500) class shoutout(models.Model): def __str__(self): return self.message giver_id =",
"self.message giver_id = models.ForeignKey(user, on_delete=models.CASCADE) receiver_id = models.ForeignKey( user, on_delete=models.CASCADE, related_name=\"r_id\") message =",
"def __str__(self): return self.message giver_id = models.ForeignKey(user, on_delete=models.CASCADE) receiver_id = models.ForeignKey( user, on_delete=models.CASCADE,",
"django.db import models class organization(models.Model): def __str__(self): return self.name name = models.CharField(max_length=50, unique=True)",
"def __str__(self): return self.name name = models.CharField(max_length=50, unique=True) slack_org_id = models.CharField(max_length=50, unique=True) channel_name",
"models.CharField(max_length=200) class user(models.Model): def __str__(self): return self.name org_id = models.ForeignKey(organization, on_delete=models.CASCADE) slack_mem_id =",
"= models.CharField(max_length=500) class shoutout(models.Model): def __str__(self): return self.message giver_id = models.ForeignKey(user, on_delete=models.CASCADE) receiver_id",
"= models.CharField(max_length=50) channel_id = models.CharField(max_length=50) access_token = models.CharField(max_length=200) installation_date = models.DateTimeField( 'installation date',",
"class user(models.Model): def __str__(self): return self.name org_id = models.ForeignKey(organization, on_delete=models.CASCADE) slack_mem_id = models.CharField(max_length=50,",
"self.name name = models.CharField(max_length=50, unique=True) slack_org_id = models.CharField(max_length=50, unique=True) channel_name = models.CharField(max_length=50) channel_id",
"name = models.CharField(max_length=50, unique=True) slack_org_id = models.CharField(max_length=50, unique=True) channel_name = models.CharField(max_length=50) channel_id =",
"user, on_delete=models.CASCADE, related_name=\"r_id\") message = models.CharField(max_length=5000) timestamps = models.DateTimeField('timestamp', auto_now_add=True) message_ts = models.CharField(max_length=500)",
"return self.name org_id = models.ForeignKey(organization, on_delete=models.CASCADE) slack_mem_id = models.CharField(max_length=50, unique=True) email = models.CharField(max_length=50,",
"models.CharField(max_length=50) channel_id = models.CharField(max_length=50) access_token = models.CharField(max_length=200) installation_date = models.DateTimeField( 'installation date', auto_now_add=True)",
"= models.ForeignKey(organization, on_delete=models.CASCADE) slack_mem_id = models.CharField(max_length=50, unique=True) email = models.CharField(max_length=50, unique=True) name =",
"on_delete=models.CASCADE) slack_mem_id = models.CharField(max_length=50, unique=True) email = models.CharField(max_length=50, unique=True) name = models.CharField(max_length=50) avatar",
"unique=True) name = models.CharField(max_length=50) avatar = models.CharField(max_length=500) class shoutout(models.Model): def __str__(self): return self.message",
"__str__(self): return self.name name = models.CharField(max_length=50, unique=True) slack_org_id = models.CharField(max_length=50, unique=True) channel_name =",
"models.CharField(max_length=50, unique=True) slack_org_id = models.CharField(max_length=50, unique=True) channel_name = models.CharField(max_length=50) channel_id = models.CharField(max_length=50) access_token",
"import models class organization(models.Model): def __str__(self): return self.name name = models.CharField(max_length=50, unique=True) slack_org_id",
"= models.CharField(max_length=200) installation_date = models.DateTimeField( 'installation date', auto_now_add=True) bot_access_token = models.CharField(max_length=200) class user(models.Model):",
"org_id = models.ForeignKey(organization, on_delete=models.CASCADE) slack_mem_id = models.CharField(max_length=50, unique=True) email = models.CharField(max_length=50, unique=True) name",
"auto_now_add=True) bot_access_token = models.CharField(max_length=200) class user(models.Model): def __str__(self): return self.name org_id = models.ForeignKey(organization,",
"__str__(self): return self.message giver_id = models.ForeignKey(user, on_delete=models.CASCADE) receiver_id = models.ForeignKey( user, on_delete=models.CASCADE, related_name=\"r_id\")",
"models.CharField(max_length=50, unique=True) email = models.CharField(max_length=50, unique=True) name = models.CharField(max_length=50) avatar = models.CharField(max_length=500) class",
"= models.CharField(max_length=200) class user(models.Model): def __str__(self): return self.name org_id = models.ForeignKey(organization, on_delete=models.CASCADE) slack_mem_id",
"class organization(models.Model): def __str__(self): return self.name name = models.CharField(max_length=50, unique=True) slack_org_id = models.CharField(max_length=50,",
"= models.CharField(max_length=50, unique=True) name = models.CharField(max_length=50) avatar = models.CharField(max_length=500) class shoutout(models.Model): def __str__(self):",
"models.ForeignKey(user, on_delete=models.CASCADE) receiver_id = models.ForeignKey( user, on_delete=models.CASCADE, related_name=\"r_id\") message = models.CharField(max_length=5000) timestamps =",
"= models.ForeignKey(user, on_delete=models.CASCADE) receiver_id = models.ForeignKey( user, on_delete=models.CASCADE, related_name=\"r_id\") message = models.CharField(max_length=5000) timestamps",
"models.CharField(max_length=500) class shoutout(models.Model): def __str__(self): return self.message giver_id = models.ForeignKey(user, on_delete=models.CASCADE) receiver_id =",
"slack_org_id = models.CharField(max_length=50, unique=True) channel_name = models.CharField(max_length=50) channel_id = models.CharField(max_length=50) access_token = models.CharField(max_length=200)",
"models.ForeignKey(organization, on_delete=models.CASCADE) slack_mem_id = models.CharField(max_length=50, unique=True) email = models.CharField(max_length=50, unique=True) name = models.CharField(max_length=50)",
"models.CharField(max_length=50, unique=True) name = models.CharField(max_length=50) avatar = models.CharField(max_length=500) class shoutout(models.Model): def __str__(self): return",
"return self.message giver_id = models.ForeignKey(user, on_delete=models.CASCADE) receiver_id = models.ForeignKey( user, on_delete=models.CASCADE, related_name=\"r_id\") message",
"models class organization(models.Model): def __str__(self): return self.name name = models.CharField(max_length=50, unique=True) slack_org_id ="
] |
[
") -> Image: log(\"Dithering\") palette = hitherdither.palette.Palette( inky._palette_blend(SATURATION, dtype=\"uint24\") ) thresholds = [64,",
"image, palette, thresholds, order=8 ) else: image_dithered = hitherdither.ordered.bayer.bayer_dithering( image, palette, thresholds, order=8",
"thresholds, order=8 ) else: image_dithered = hitherdither.ordered.bayer.bayer_dithering( image, palette, thresholds, order=8 ) log(\"Done",
"from inky.inky_uc8159 import Inky WIDTH, HEIGHT = 600, 448 SATURATION = 1.0 start_log",
"image, palette, thresholds, order=4 ) elif mode == DitheringModes.LARGE_DOTS: image_dithered = hitherdither.ordered.cluster.cluster_dot_dithering( image,",
"WIDTH, HEIGHT = 600, 448 SATURATION = 1.0 start_log = datetime.datetime.now() last_log =",
"DitheringModes(Enum): DEFAULT = \"default\" SMALL_DOTS = \"small_dots\" LARGE_DOTS = \"large_dots\" def dithered( inky:",
"datetime from enum import Enum import hitherdither from PIL import Image from inky.inky_uc8159",
"order=8 ) log(\"Done dithering\") return image_dithered def chunks(lst, n): \"\"\"Yield successive n-sized chunks",
"datetime.datetime.now() diff = (now - last_log).total_seconds() from_start = (now - start_log).total_seconds() last_log =",
"hitherdither.palette.Palette( inky._palette_blend(SATURATION, dtype=\"uint24\") ) thresholds = [64, 64, 64] # Threshold for snapping",
"1.0 start_log = datetime.datetime.now() last_log = start_log def log(msg: str) -> None: global",
"dtype=\"uint24\") ) thresholds = [64, 64, 64] # Threshold for snapping colours, I",
"now print(f\"[{from_start:5.2f} +{diff:.2f} ]\\t{msg}\") class DitheringModes(Enum): DEFAULT = \"default\" SMALL_DOTS = \"small_dots\" LARGE_DOTS",
"start_log).total_seconds() last_log = now print(f\"[{from_start:5.2f} +{diff:.2f} ]\\t{msg}\") class DitheringModes(Enum): DEFAULT = \"default\" SMALL_DOTS",
"- last_log).total_seconds() from_start = (now - start_log).total_seconds() last_log = now print(f\"[{from_start:5.2f} +{diff:.2f} ]\\t{msg}\")",
"if mode == DitheringModes.SMALL_DOTS: image_dithered = hitherdither.ordered.cluster.cluster_dot_dithering( image, palette, thresholds, order=4 ) elif",
"elif mode == DitheringModes.LARGE_DOTS: image_dithered = hitherdither.ordered.cluster.cluster_dot_dithering( image, palette, thresholds, order=8 ) else:",
"== DitheringModes.SMALL_DOTS: image_dithered = hitherdither.ordered.cluster.cluster_dot_dithering( image, palette, thresholds, order=4 ) elif mode ==",
"+{diff:.2f} ]\\t{msg}\") class DitheringModes(Enum): DEFAULT = \"default\" SMALL_DOTS = \"small_dots\" LARGE_DOTS = \"large_dots\"",
"(now - last_log).total_seconds() from_start = (now - start_log).total_seconds() last_log = now print(f\"[{from_start:5.2f} +{diff:.2f}",
"colours, I guess? if mode == DitheringModes.SMALL_DOTS: image_dithered = hitherdither.ordered.cluster.cluster_dot_dithering( image, palette, thresholds,",
"image_dithered = hitherdither.ordered.cluster.cluster_dot_dithering( image, palette, thresholds, order=8 ) else: image_dithered = hitherdither.ordered.bayer.bayer_dithering( image,",
"== DitheringModes.LARGE_DOTS: image_dithered = hitherdither.ordered.cluster.cluster_dot_dithering( image, palette, thresholds, order=8 ) else: image_dithered =",
"hitherdither.ordered.bayer.bayer_dithering( image, palette, thresholds, order=8 ) log(\"Done dithering\") return image_dithered def chunks(lst, n):",
"palette, thresholds, order=8 ) log(\"Done dithering\") return image_dithered def chunks(lst, n): \"\"\"Yield successive",
"= [64, 64, 64] # Threshold for snapping colours, I guess? if mode",
"\"\"\"Yield successive n-sized chunks from lst.\"\"\" for i in range(0, len(lst), n): yield",
"(now - start_log).total_seconds() last_log = now print(f\"[{from_start:5.2f} +{diff:.2f} ]\\t{msg}\") class DitheringModes(Enum): DEFAULT =",
"image, palette, thresholds, order=8 ) log(\"Done dithering\") return image_dithered def chunks(lst, n): \"\"\"Yield",
"def log(msg: str) -> None: global last_log now = datetime.datetime.now() diff = (now",
"mode: DitheringModes = DitheringModes.DEFAULT ) -> Image: log(\"Dithering\") palette = hitherdither.palette.Palette( inky._palette_blend(SATURATION, dtype=\"uint24\")",
"Inky WIDTH, HEIGHT = 600, 448 SATURATION = 1.0 start_log = datetime.datetime.now() last_log",
"datetime.datetime.now() last_log = start_log def log(msg: str) -> None: global last_log now =",
"palette, thresholds, order=8 ) else: image_dithered = hitherdither.ordered.bayer.bayer_dithering( image, palette, thresholds, order=8 )",
"log(msg: str) -> None: global last_log now = datetime.datetime.now() diff = (now -",
"hitherdither.ordered.cluster.cluster_dot_dithering( image, palette, thresholds, order=4 ) elif mode == DitheringModes.LARGE_DOTS: image_dithered = hitherdither.ordered.cluster.cluster_dot_dithering(",
"image_dithered = hitherdither.ordered.bayer.bayer_dithering( image, palette, thresholds, order=8 ) log(\"Done dithering\") return image_dithered def",
"= DitheringModes.DEFAULT ) -> Image: log(\"Dithering\") palette = hitherdither.palette.Palette( inky._palette_blend(SATURATION, dtype=\"uint24\") ) thresholds",
"image_dithered = hitherdither.ordered.cluster.cluster_dot_dithering( image, palette, thresholds, order=4 ) elif mode == DitheringModes.LARGE_DOTS: image_dithered",
"chunks(lst, n): \"\"\"Yield successive n-sized chunks from lst.\"\"\" for i in range(0, len(lst),",
"Image, mode: DitheringModes = DitheringModes.DEFAULT ) -> Image: log(\"Dithering\") palette = hitherdither.palette.Palette( inky._palette_blend(SATURATION,",
"start_log = datetime.datetime.now() last_log = start_log def log(msg: str) -> None: global last_log",
"str) -> None: global last_log now = datetime.datetime.now() diff = (now - last_log).total_seconds()",
"now = datetime.datetime.now() diff = (now - last_log).total_seconds() from_start = (now - start_log).total_seconds()",
"]\\t{msg}\") class DitheringModes(Enum): DEFAULT = \"default\" SMALL_DOTS = \"small_dots\" LARGE_DOTS = \"large_dots\" def",
"n-sized chunks from lst.\"\"\" for i in range(0, len(lst), n): yield lst[i:i +",
"= 1.0 start_log = datetime.datetime.now() last_log = start_log def log(msg: str) -> None:",
"diff = (now - last_log).total_seconds() from_start = (now - start_log).total_seconds() last_log = now",
"DitheringModes.DEFAULT ) -> Image: log(\"Dithering\") palette = hitherdither.palette.Palette( inky._palette_blend(SATURATION, dtype=\"uint24\") ) thresholds =",
"from enum import Enum import hitherdither from PIL import Image from inky.inky_uc8159 import",
"class DitheringModes(Enum): DEFAULT = \"default\" SMALL_DOTS = \"small_dots\" LARGE_DOTS = \"large_dots\" def dithered(",
"64, 64] # Threshold for snapping colours, I guess? if mode == DitheringModes.SMALL_DOTS:",
"Threshold for snapping colours, I guess? if mode == DitheringModes.SMALL_DOTS: image_dithered = hitherdither.ordered.cluster.cluster_dot_dithering(",
"448 SATURATION = 1.0 start_log = datetime.datetime.now() last_log = start_log def log(msg: str)",
"= now print(f\"[{from_start:5.2f} +{diff:.2f} ]\\t{msg}\") class DitheringModes(Enum): DEFAULT = \"default\" SMALL_DOTS = \"small_dots\"",
"Inky, image: Image, mode: DitheringModes = DitheringModes.DEFAULT ) -> Image: log(\"Dithering\") palette =",
"start_log def log(msg: str) -> None: global last_log now = datetime.datetime.now() diff =",
"64] # Threshold for snapping colours, I guess? if mode == DitheringModes.SMALL_DOTS: image_dithered",
"inky.inky_uc8159 import Inky WIDTH, HEIGHT = 600, 448 SATURATION = 1.0 start_log =",
") elif mode == DitheringModes.LARGE_DOTS: image_dithered = hitherdither.ordered.cluster.cluster_dot_dithering( image, palette, thresholds, order=8 )",
"n): \"\"\"Yield successive n-sized chunks from lst.\"\"\" for i in range(0, len(lst), n):",
"last_log now = datetime.datetime.now() diff = (now - last_log).total_seconds() from_start = (now -",
"-> None: global last_log now = datetime.datetime.now() diff = (now - last_log).total_seconds() from_start",
"last_log).total_seconds() from_start = (now - start_log).total_seconds() last_log = now print(f\"[{from_start:5.2f} +{diff:.2f} ]\\t{msg}\") class",
"\"small_dots\" LARGE_DOTS = \"large_dots\" def dithered( inky: Inky, image: Image, mode: DitheringModes =",
"SATURATION = 1.0 start_log = datetime.datetime.now() last_log = start_log def log(msg: str) ->",
"600, 448 SATURATION = 1.0 start_log = datetime.datetime.now() last_log = start_log def log(msg:",
"thresholds = [64, 64, 64] # Threshold for snapping colours, I guess? if",
"DitheringModes = DitheringModes.DEFAULT ) -> Image: log(\"Dithering\") palette = hitherdither.palette.Palette( inky._palette_blend(SATURATION, dtype=\"uint24\") )",
"import datetime from enum import Enum import hitherdither from PIL import Image from",
"log(\"Dithering\") palette = hitherdither.palette.Palette( inky._palette_blend(SATURATION, dtype=\"uint24\") ) thresholds = [64, 64, 64] #",
"= (now - start_log).total_seconds() last_log = now print(f\"[{from_start:5.2f} +{diff:.2f} ]\\t{msg}\") class DitheringModes(Enum): DEFAULT",
"image_dithered def chunks(lst, n): \"\"\"Yield successive n-sized chunks from lst.\"\"\" for i in",
"= hitherdither.ordered.cluster.cluster_dot_dithering( image, palette, thresholds, order=8 ) else: image_dithered = hitherdither.ordered.bayer.bayer_dithering( image, palette,",
"= datetime.datetime.now() diff = (now - last_log).total_seconds() from_start = (now - start_log).total_seconds() last_log",
"= \"large_dots\" def dithered( inky: Inky, image: Image, mode: DitheringModes = DitheringModes.DEFAULT )",
"def chunks(lst, n): \"\"\"Yield successive n-sized chunks from lst.\"\"\" for i in range(0,",
"= hitherdither.ordered.bayer.bayer_dithering( image, palette, thresholds, order=8 ) log(\"Done dithering\") return image_dithered def chunks(lst,",
"DitheringModes.SMALL_DOTS: image_dithered = hitherdither.ordered.cluster.cluster_dot_dithering( image, palette, thresholds, order=4 ) elif mode == DitheringModes.LARGE_DOTS:",
"from_start = (now - start_log).total_seconds() last_log = now print(f\"[{from_start:5.2f} +{diff:.2f} ]\\t{msg}\") class DitheringModes(Enum):",
"Image: log(\"Dithering\") palette = hitherdither.palette.Palette( inky._palette_blend(SATURATION, dtype=\"uint24\") ) thresholds = [64, 64, 64]",
"= datetime.datetime.now() last_log = start_log def log(msg: str) -> None: global last_log now",
"= hitherdither.ordered.cluster.cluster_dot_dithering( image, palette, thresholds, order=4 ) elif mode == DitheringModes.LARGE_DOTS: image_dithered =",
"mode == DitheringModes.LARGE_DOTS: image_dithered = hitherdither.ordered.cluster.cluster_dot_dithering( image, palette, thresholds, order=8 ) else: image_dithered",
"SMALL_DOTS = \"small_dots\" LARGE_DOTS = \"large_dots\" def dithered( inky: Inky, image: Image, mode:",
"dithered( inky: Inky, image: Image, mode: DitheringModes = DitheringModes.DEFAULT ) -> Image: log(\"Dithering\")",
") log(\"Done dithering\") return image_dithered def chunks(lst, n): \"\"\"Yield successive n-sized chunks from",
"from PIL import Image from inky.inky_uc8159 import Inky WIDTH, HEIGHT = 600, 448",
"def dithered( inky: Inky, image: Image, mode: DitheringModes = DitheringModes.DEFAULT ) -> Image:",
"- start_log).total_seconds() last_log = now print(f\"[{from_start:5.2f} +{diff:.2f} ]\\t{msg}\") class DitheringModes(Enum): DEFAULT = \"default\"",
"= hitherdither.palette.Palette( inky._palette_blend(SATURATION, dtype=\"uint24\") ) thresholds = [64, 64, 64] # Threshold for",
"global last_log now = datetime.datetime.now() diff = (now - last_log).total_seconds() from_start = (now",
"inky._palette_blend(SATURATION, dtype=\"uint24\") ) thresholds = [64, 64, 64] # Threshold for snapping colours,",
"DEFAULT = \"default\" SMALL_DOTS = \"small_dots\" LARGE_DOTS = \"large_dots\" def dithered( inky: Inky,",
"Image from inky.inky_uc8159 import Inky WIDTH, HEIGHT = 600, 448 SATURATION = 1.0",
") else: image_dithered = hitherdither.ordered.bayer.bayer_dithering( image, palette, thresholds, order=8 ) log(\"Done dithering\") return",
"mode == DitheringModes.SMALL_DOTS: image_dithered = hitherdither.ordered.cluster.cluster_dot_dithering( image, palette, thresholds, order=4 ) elif mode",
"successive n-sized chunks from lst.\"\"\" for i in range(0, len(lst), n): yield lst[i:i",
"\"large_dots\" def dithered( inky: Inky, image: Image, mode: DitheringModes = DitheringModes.DEFAULT ) ->",
"last_log = start_log def log(msg: str) -> None: global last_log now = datetime.datetime.now()",
"for snapping colours, I guess? if mode == DitheringModes.SMALL_DOTS: image_dithered = hitherdither.ordered.cluster.cluster_dot_dithering( image,",
"enum import Enum import hitherdither from PIL import Image from inky.inky_uc8159 import Inky",
"print(f\"[{from_start:5.2f} +{diff:.2f} ]\\t{msg}\") class DitheringModes(Enum): DEFAULT = \"default\" SMALL_DOTS = \"small_dots\" LARGE_DOTS =",
"guess? if mode == DitheringModes.SMALL_DOTS: image_dithered = hitherdither.ordered.cluster.cluster_dot_dithering( image, palette, thresholds, order=4 )",
"\"default\" SMALL_DOTS = \"small_dots\" LARGE_DOTS = \"large_dots\" def dithered( inky: Inky, image: Image,",
"thresholds, order=4 ) elif mode == DitheringModes.LARGE_DOTS: image_dithered = hitherdither.ordered.cluster.cluster_dot_dithering( image, palette, thresholds,",
"None: global last_log now = datetime.datetime.now() diff = (now - last_log).total_seconds() from_start =",
"thresholds, order=8 ) log(\"Done dithering\") return image_dithered def chunks(lst, n): \"\"\"Yield successive n-sized",
"order=4 ) elif mode == DitheringModes.LARGE_DOTS: image_dithered = hitherdither.ordered.cluster.cluster_dot_dithering( image, palette, thresholds, order=8",
"import hitherdither from PIL import Image from inky.inky_uc8159 import Inky WIDTH, HEIGHT =",
"Enum import hitherdither from PIL import Image from inky.inky_uc8159 import Inky WIDTH, HEIGHT",
"dithering\") return image_dithered def chunks(lst, n): \"\"\"Yield successive n-sized chunks from lst.\"\"\" for",
"PIL import Image from inky.inky_uc8159 import Inky WIDTH, HEIGHT = 600, 448 SATURATION",
"return image_dithered def chunks(lst, n): \"\"\"Yield successive n-sized chunks from lst.\"\"\" for i",
"palette = hitherdither.palette.Palette( inky._palette_blend(SATURATION, dtype=\"uint24\") ) thresholds = [64, 64, 64] # Threshold",
"log(\"Done dithering\") return image_dithered def chunks(lst, n): \"\"\"Yield successive n-sized chunks from lst.\"\"\"",
"= \"small_dots\" LARGE_DOTS = \"large_dots\" def dithered( inky: Inky, image: Image, mode: DitheringModes",
"= start_log def log(msg: str) -> None: global last_log now = datetime.datetime.now() diff",
"inky: Inky, image: Image, mode: DitheringModes = DitheringModes.DEFAULT ) -> Image: log(\"Dithering\") palette",
"= 600, 448 SATURATION = 1.0 start_log = datetime.datetime.now() last_log = start_log def",
"import Inky WIDTH, HEIGHT = 600, 448 SATURATION = 1.0 start_log = datetime.datetime.now()",
"LARGE_DOTS = \"large_dots\" def dithered( inky: Inky, image: Image, mode: DitheringModes = DitheringModes.DEFAULT",
"= \"default\" SMALL_DOTS = \"small_dots\" LARGE_DOTS = \"large_dots\" def dithered( inky: Inky, image:",
"order=8 ) else: image_dithered = hitherdither.ordered.bayer.bayer_dithering( image, palette, thresholds, order=8 ) log(\"Done dithering\")",
"# Threshold for snapping colours, I guess? if mode == DitheringModes.SMALL_DOTS: image_dithered =",
"last_log = now print(f\"[{from_start:5.2f} +{diff:.2f} ]\\t{msg}\") class DitheringModes(Enum): DEFAULT = \"default\" SMALL_DOTS =",
"I guess? if mode == DitheringModes.SMALL_DOTS: image_dithered = hitherdither.ordered.cluster.cluster_dot_dithering( image, palette, thresholds, order=4",
"-> Image: log(\"Dithering\") palette = hitherdither.palette.Palette( inky._palette_blend(SATURATION, dtype=\"uint24\") ) thresholds = [64, 64,",
"else: image_dithered = hitherdither.ordered.bayer.bayer_dithering( image, palette, thresholds, order=8 ) log(\"Done dithering\") return image_dithered",
"DitheringModes.LARGE_DOTS: image_dithered = hitherdither.ordered.cluster.cluster_dot_dithering( image, palette, thresholds, order=8 ) else: image_dithered = hitherdither.ordered.bayer.bayer_dithering(",
"chunks from lst.\"\"\" for i in range(0, len(lst), n): yield lst[i:i + n]",
"import Enum import hitherdither from PIL import Image from inky.inky_uc8159 import Inky WIDTH,",
"= (now - last_log).total_seconds() from_start = (now - start_log).total_seconds() last_log = now print(f\"[{from_start:5.2f}",
") thresholds = [64, 64, 64] # Threshold for snapping colours, I guess?",
"hitherdither.ordered.cluster.cluster_dot_dithering( image, palette, thresholds, order=8 ) else: image_dithered = hitherdither.ordered.bayer.bayer_dithering( image, palette, thresholds,",
"import Image from inky.inky_uc8159 import Inky WIDTH, HEIGHT = 600, 448 SATURATION =",
"snapping colours, I guess? if mode == DitheringModes.SMALL_DOTS: image_dithered = hitherdither.ordered.cluster.cluster_dot_dithering( image, palette,",
"HEIGHT = 600, 448 SATURATION = 1.0 start_log = datetime.datetime.now() last_log = start_log",
"image: Image, mode: DitheringModes = DitheringModes.DEFAULT ) -> Image: log(\"Dithering\") palette = hitherdither.palette.Palette(",
"[64, 64, 64] # Threshold for snapping colours, I guess? if mode ==",
"palette, thresholds, order=4 ) elif mode == DitheringModes.LARGE_DOTS: image_dithered = hitherdither.ordered.cluster.cluster_dot_dithering( image, palette,",
"hitherdither from PIL import Image from inky.inky_uc8159 import Inky WIDTH, HEIGHT = 600,"
] |
[
"be used directly \"\"\" yield @contextmanager def test(testName): \"\"\" As TC.test use \"testName\"",
"TC = TeamcityServiceMessages() ctx_mgr_block = TC.block ctx_mgr_test = TC.test else: ctx_mgr_block = block",
"teamcity.messages import TeamcityServiceMessages @contextmanager def block(name): \"\"\" As TC.block use \"name\" as a",
"parameter, contextlib.suppress() can not be used directly \"\"\" yield def get_context_managers(): if is_running_under_teamcity():",
"directly \"\"\" yield def get_context_managers(): if is_running_under_teamcity(): TC = TeamcityServiceMessages() ctx_mgr_block = TC.block",
"\"name\" as a parameter, contextlib.nullcontext() can not be used directly \"\"\" yield @contextmanager",
"\"\"\" As TC.test use \"testName\" as a parameter, contextlib.suppress() can not be used",
"def block(name): \"\"\" As TC.block use \"name\" as a parameter, contextlib.nullcontext() can not",
"= TeamcityServiceMessages() ctx_mgr_block = TC.block ctx_mgr_test = TC.test else: ctx_mgr_block = block ctx_mgr_test",
"= TC.block ctx_mgr_test = TC.test else: ctx_mgr_block = block ctx_mgr_test = test return",
"TC.block ctx_mgr_test = TC.test else: ctx_mgr_block = block ctx_mgr_test = test return ctx_mgr_block,",
"can not be used directly \"\"\" yield def get_context_managers(): if is_running_under_teamcity(): TC =",
"teamcity import is_running_under_teamcity from teamcity.messages import TeamcityServiceMessages @contextmanager def block(name): \"\"\" As TC.block",
"TC.block use \"name\" as a parameter, contextlib.nullcontext() can not be used directly \"\"\"",
"TC.test use \"testName\" as a parameter, contextlib.suppress() can not be used directly \"\"\"",
"def get_context_managers(): if is_running_under_teamcity(): TC = TeamcityServiceMessages() ctx_mgr_block = TC.block ctx_mgr_test = TC.test",
"use \"testName\" as a parameter, contextlib.suppress() can not be used directly \"\"\" yield",
"as a parameter, contextlib.suppress() can not be used directly \"\"\" yield def get_context_managers():",
"as a parameter, contextlib.nullcontext() can not be used directly \"\"\" yield @contextmanager def",
"can not be used directly \"\"\" yield @contextmanager def test(testName): \"\"\" As TC.test",
"contextlib.suppress() can not be used directly \"\"\" yield def get_context_managers(): if is_running_under_teamcity(): TC",
"yield @contextmanager def test(testName): \"\"\" As TC.test use \"testName\" as a parameter, contextlib.suppress()",
"contextlib import contextmanager from teamcity import is_running_under_teamcity from teamcity.messages import TeamcityServiceMessages @contextmanager def",
"@contextmanager def test(testName): \"\"\" As TC.test use \"testName\" as a parameter, contextlib.suppress() can",
"used directly \"\"\" yield def get_context_managers(): if is_running_under_teamcity(): TC = TeamcityServiceMessages() ctx_mgr_block =",
"\"testName\" as a parameter, contextlib.suppress() can not be used directly \"\"\" yield def",
"get_context_managers(): if is_running_under_teamcity(): TC = TeamcityServiceMessages() ctx_mgr_block = TC.block ctx_mgr_test = TC.test else:",
"ctx_mgr_block = TC.block ctx_mgr_test = TC.test else: ctx_mgr_block = block ctx_mgr_test = test",
"contextmanager from teamcity import is_running_under_teamcity from teamcity.messages import TeamcityServiceMessages @contextmanager def block(name): \"\"\"",
"\"\"\" As TC.block use \"name\" as a parameter, contextlib.nullcontext() can not be used",
"is_running_under_teamcity from teamcity.messages import TeamcityServiceMessages @contextmanager def block(name): \"\"\" As TC.block use \"name\"",
"\"\"\" yield def get_context_managers(): if is_running_under_teamcity(): TC = TeamcityServiceMessages() ctx_mgr_block = TC.block ctx_mgr_test",
"<gh_stars>0 from contextlib import contextmanager from teamcity import is_running_under_teamcity from teamcity.messages import TeamcityServiceMessages",
"\"\"\" yield @contextmanager def test(testName): \"\"\" As TC.test use \"testName\" as a parameter,",
"be used directly \"\"\" yield def get_context_managers(): if is_running_under_teamcity(): TC = TeamcityServiceMessages() ctx_mgr_block",
"directly \"\"\" yield @contextmanager def test(testName): \"\"\" As TC.test use \"testName\" as a",
"As TC.test use \"testName\" as a parameter, contextlib.suppress() can not be used directly",
"TeamcityServiceMessages @contextmanager def block(name): \"\"\" As TC.block use \"name\" as a parameter, contextlib.nullcontext()",
"block(name): \"\"\" As TC.block use \"name\" as a parameter, contextlib.nullcontext() can not be",
"import contextmanager from teamcity import is_running_under_teamcity from teamcity.messages import TeamcityServiceMessages @contextmanager def block(name):",
"As TC.block use \"name\" as a parameter, contextlib.nullcontext() can not be used directly",
"from contextlib import contextmanager from teamcity import is_running_under_teamcity from teamcity.messages import TeamcityServiceMessages @contextmanager",
"parameter, contextlib.nullcontext() can not be used directly \"\"\" yield @contextmanager def test(testName): \"\"\"",
"if is_running_under_teamcity(): TC = TeamcityServiceMessages() ctx_mgr_block = TC.block ctx_mgr_test = TC.test else: ctx_mgr_block",
"is_running_under_teamcity(): TC = TeamcityServiceMessages() ctx_mgr_block = TC.block ctx_mgr_test = TC.test else: ctx_mgr_block =",
"use \"name\" as a parameter, contextlib.nullcontext() can not be used directly \"\"\" yield",
"not be used directly \"\"\" yield def get_context_managers(): if is_running_under_teamcity(): TC = TeamcityServiceMessages()",
"TeamcityServiceMessages() ctx_mgr_block = TC.block ctx_mgr_test = TC.test else: ctx_mgr_block = block ctx_mgr_test =",
"a parameter, contextlib.suppress() can not be used directly \"\"\" yield def get_context_managers(): if",
"used directly \"\"\" yield @contextmanager def test(testName): \"\"\" As TC.test use \"testName\" as",
"ctx_mgr_test = TC.test else: ctx_mgr_block = block ctx_mgr_test = test return ctx_mgr_block, ctx_mgr_test",
"contextlib.nullcontext() can not be used directly \"\"\" yield @contextmanager def test(testName): \"\"\" As",
"not be used directly \"\"\" yield @contextmanager def test(testName): \"\"\" As TC.test use",
"def test(testName): \"\"\" As TC.test use \"testName\" as a parameter, contextlib.suppress() can not",
"yield def get_context_managers(): if is_running_under_teamcity(): TC = TeamcityServiceMessages() ctx_mgr_block = TC.block ctx_mgr_test =",
"from teamcity import is_running_under_teamcity from teamcity.messages import TeamcityServiceMessages @contextmanager def block(name): \"\"\" As",
"import is_running_under_teamcity from teamcity.messages import TeamcityServiceMessages @contextmanager def block(name): \"\"\" As TC.block use",
"test(testName): \"\"\" As TC.test use \"testName\" as a parameter, contextlib.suppress() can not be",
"a parameter, contextlib.nullcontext() can not be used directly \"\"\" yield @contextmanager def test(testName):",
"@contextmanager def block(name): \"\"\" As TC.block use \"name\" as a parameter, contextlib.nullcontext() can",
"import TeamcityServiceMessages @contextmanager def block(name): \"\"\" As TC.block use \"name\" as a parameter,",
"from teamcity.messages import TeamcityServiceMessages @contextmanager def block(name): \"\"\" As TC.block use \"name\" as"
] |
[
"see in seeAlso: out += \"* `%s`\\n\" % (see[\"data\"]) return out \"\"\" def",
"= sys.modules['DOCC'].DOC dokumentor.report(\"json\", docs) data = json.loads(sys.stdout.data) sys.stdout = sys.__stdout__ hierarchy = {}",
"arg[\"name\"], parseParamsType(arg[\"typed\"]), arg[\"description\"]) if \"params\" in arg: # Callback function for subArg in",
"in hierarchy[directory][\"children\"]: print(\" - Writing %s\" % subPath + child + \".md\") with",
"out \"\"\" def parseExample(examples): out = \"\" if len(examples) > 0: out +=",
"4) return out def parseParamsType(types): out = \"\" comma = \"\" for t",
"f.write(hierarchy[directory][\"data\"]) for child in hierarchy[directory][\"children\"]: print(\" - Writing %s\" % subPath + child",
"for subArg in arg[\"params\"]: out += parseParam(subArg, indent + 4) elif type(arg[\"typed\"][0]) is",
"\"\", method[\"name\"], fnArgs) if method[\"is_slow\"]: out += \"<!-- YAML\\n- Slow method\\n-->\\n\" out +=",
"= \"\" if len(seeAlso) > 0: out += \"\\nSee also:\\n\" for see in",
"+= \"=%s\" % arg[\"default\"] if arg[\"is_optional\"]: name = \"[%s]\" % name fnArgs +=",
"name fnArgs += name comma = \", \" out += \"\\n## %s%s%s(%s)\\n\" %",
"\"null\": out += t else: out += t if t[0].isupper() else t.capitalize() comma",
"\"\" out += \"\\n## %s%s%s%s (%s)\\n\" % (\"`static` \" if prop[\"is_static\"] else \"\",",
"path + directory + \"/\" try: os.mkdir(subPath) except: pass print(\"Writing %s\" % subPath",
"out += parseParam(subArg, 0 if isReturn else indent + 4) return out def",
"out += parseMethod(ev, isEvent=True) return out print(\"Running dokumentor\") class captureDokumentor: def __init__(self): self.data",
"def flush(self=None): pass sys.stdout = captureDokumentor() dokumentor.process(\"../docs/\") docs = sys.modules['DOCC'].DOC dokumentor.report(\"json\", docs) data",
"for name, method in data[\"static_methods\"].iteritems(): out += parseMethod(method) if data[\"properties\"]: for name, prop",
"data[\"properties\"].iteritems(): out += parseProperty(prop) if data[\"events\"]: for evName, ev in data[\"events\"].iteritems(): out +=",
"else: out += \"%s* `%s` (%s): %s\\n\" % (' ' * indent, arg[\"name\"],",
"% subPath + directory + \".md\") with open(subPath + directory + \".md\", \"w\")",
"sys import re import dokumentor import subprocess def parseParam(arg, indent=0, isReturn=False): out =",
"% (ex[\"language\"], ex[\"data\"]) return out def parse(klass, data): out = \"\" out +=",
"directory + \".md\") with open(path + directory + \".md\", \"w\") as f: f.write(hierarchy[directory][\"data\"])",
"\"[\": out += t[1:-1].capitalize() + \"[]\" else: if t == \"null\": out +=",
"out += \"Object[]\" elif type(t) is dict: out += \"Object\" else: if t[0]",
"else: out += t if t[0].isupper() else t.capitalize() comma = \" | \"",
"docs) data = json.loads(sys.stdout.data) sys.stdout = sys.__stdout__ hierarchy = {} for section, items",
"+= t if t[0].isupper() else t.capitalize() comma = \" | \" return out",
"seeAlso: out += \"* `%s`\\n\" % (see[\"data\"]) return out \"\"\" def parseExample(examples): out",
"def parseParamsType(types): out = \"\" comma = \"\" for t in types: out",
"out += t else: out += t if t[0].isupper() else t.capitalize() comma =",
"msg def flush(self=None): pass sys.stdout = captureDokumentor() dokumentor.process(\"../docs/\") docs = sys.modules['DOCC'].DOC dokumentor.report(\"json\", docs)",
"out += \"\\n\" + tmp out += parseSeeAlso(method[\"sees\"]) return out def parseProperty(prop): out",
"\"Returns (%s): %s\\n\" % (parseParamsType(arg[\"typed\"]), arg[\"description\"]) else: out += \"%s* `%s` (%s): %s\\n\"",
"#!/usr/bin/env python2.7 import json from pprint import pprint import os import sys import",
"else indent + 4) elif type(arg[\"typed\"][0]) is list: # Array of Object for",
"t[0].isupper() else t.capitalize() comma = \" | \" return out def parseMethod(method, isEvent=False):",
"\"\\n\" + tmp out += parseSeeAlso(method[\"sees\"]) return out def parseProperty(prop): out = \"\"",
"else \"\", parseParamsType(prop[\"typed\"])) out += prop[\"description\"] + \"\\n\" out += parseExample(prop[\"examples\"]) out +=",
"python2.7 import json from pprint import pprint import os import sys import re",
"parseMethod(method) if data[\"properties\"]: for name, prop in data[\"properties\"].iteritems(): out += parseProperty(prop) if data[\"events\"]:",
"= \"\" comma = \"\" for t in types: out += comma if",
"type(arg[\"typed\"][0]) is list: # Array of Object for subArg in arg[\"typed\"][0][0][\"details\"]: out +=",
"examples: out += \"\\n```%s\\n%s\\n```\\n\" % (ex[\"language\"], ex[\"data\"]) return out def parse(klass, data): out",
"(ex[\"language\"], ex[\"data\"]) return out def parse(klass, data): out = \"\" out += \"#",
"is dict: # Object for subArg in arg[\"typed\"][0][\"details\"]: out += parseParam(subArg, 0 if",
"class captureDokumentor: def __init__(self): self.data = \"\" def write(self, msg): self.data += msg",
"+= \"* `%s`\\n\" % (see[\"data\"]) return out \"\"\" def parseExample(examples): out = \"\"",
"child + \".md\", \"w\") as f: f.write(hierarchy[directory][\"children\"][child]) else: print(\"Writing %s\" % path +",
"\"Object[]\" elif type(t) is dict: out += \"Object\" else: if t[0] == \"[\":",
"in arg[\"typed\"][0][0][\"details\"]: out += parseParam(subArg, 0 if isReturn else indent + 4) return",
"\"../docs/en/api/\" try: os.mkdir(path) except: pass for directory in hierarchy: if len(hierarchy[directory][\"children\"]) > 1:",
"re import dokumentor import subprocess def parseParam(arg, indent=0, isReturn=False): out = \"\" if",
"!= \"None\" else \"\", parseParamsType(prop[\"typed\"])) out += prop[\"description\"] + \"\\n\" out += parseExample(prop[\"examples\"])",
"isReturn: out += \"Returns (%s): %s\\n\" % (parseParamsType(arg[\"typed\"]), arg[\"description\"]) else: out += \"%s*",
"parseExample(item[\"examples\"]) out += parseSeeAlso(item[\"sees\"]) if data[\"constructors\"]: out += parseMethod(data[\"constructors\"][klass]) if data[\"methods\"]: for name,",
"+= parseExample(prop[\"examples\"]) out += parseSeeAlso(prop[\"sees\"]) return out def parseSeeAlso(seeAlso): return \"\" \"\"\" out",
"if t[0] == \"[\": out += t[1:-1].capitalize() + \"[]\" else: if t ==",
"+= t else: out += t if t[0].isupper() else t.capitalize() comma = \"",
"if method[\"returns\"] and not method[\"is_constructor\"]: if method[\"returns\"][\"nullable\"]: method[\"returns\"][\"typed\"].append(\"null\") tmp = parseParam(method[\"returns\"], isReturn=True) if",
"\"\"\" out = \"\" if len(seeAlso) > 0: out += \"\\nSee also:\\n\" for",
"+= parseSeeAlso(method[\"sees\"]) return out def parseProperty(prop): out = \"\" out += \"\\n## %s%s%s%s",
"\"static_methods\": []} hierarchy[section] = {\"data\": parse(section, data[section])} hierarchy[section][\"children\"] = {} for klass in",
"out += t[1:-1].capitalize() + \"[]\" else: if t == \"null\": out += t",
"prop[\"default\"] if prop[\"default\"] != \"None\" else \"\", parseParamsType(prop[\"typed\"])) out += prop[\"description\"] + \"\\n\"",
"out += \"Object\" else: if t[0] == \"[\": out += t[1:-1].capitalize() + \"[]\"",
"in seeAlso: out += \"* `%s`\\n\" % (see[\"data\"]) return out \"\"\" def parseExample(examples):",
"% arg[\"default\"] if arg[\"is_optional\"]: name = \"[%s]\" % name fnArgs += name comma",
"comma = \", \" out += \"\\n## %s%s%s(%s)\\n\" % (\"`static `\" if method[\"is_static\"]",
"method[\"is_constructor\"] else \"\", method[\"name\"], fnArgs) if method[\"is_slow\"]: out += \"<!-- YAML\\n- Slow method\\n-->\\n\"",
"parseExample(prop[\"examples\"]) out += parseSeeAlso(prop[\"sees\"]) return out def parseSeeAlso(seeAlso): return \"\" \"\"\" out =",
"[], \"properties\": [], \"events\":[], \"static_methods\": []} hierarchy[section] = {\"data\": parse(section, data[section])} hierarchy[section][\"children\"] =",
"subArg in arg[\"typed\"][0][0][\"details\"]: out += parseParam(subArg, 0 if isReturn else indent + 4)",
"in method[\"params\"]: name = comma + arg[\"name\"] if arg[\"default\"] != \"None\": name +=",
"method[\"is_slow\"]: out += \"<!-- YAML\\n- Slow method\\n-->\\n\" out += method[\"description\"] + \"\\n\" if",
"data[\"properties\"]: for name, prop in data[\"properties\"].iteritems(): out += parseProperty(prop) if data[\"events\"]: for evName,",
"in arg: # Callback function for subArg in arg[\"params\"]: out += parseParam(subArg, indent",
"out = \"\" if isEvent: out += \"\\n## Event: %s\\n\" % (re.sub(\"[A-Za-z_0-9]+\\.\", \"\",",
"+= \"<!-- YAML\\n- Slow method\\n-->\\n\" out += method[\"description\"] + \"\\n\" if len(method[\"params\"]) >",
"if data[\"constructors\"]: out += parseMethod(data[\"constructors\"][klass]) if data[\"methods\"]: for name, method in data[\"methods\"].iteritems(): out",
"Callback function for subArg in arg[\"params\"]: out += parseParam(subArg, indent + 4) elif",
"out def parseMethod(method, isEvent=False): out = \"\" if isEvent: out += \"\\n## Event:",
"+ \".md\") with open(subPath + directory + \".md\", \"w\") as f: f.write(hierarchy[directory][\"data\"]) for",
"arg: # Callback function for subArg in arg[\"params\"]: out += parseParam(subArg, indent +",
"\"\" out += \"# Class: %s\" % (klass) + \"\\n\" item = data[\"base\"][klass]",
"{ section: {\"description\": \"\", \"sees\":[], \"examples\": {}}}, \"constructors\": {}, \"methods\": [], \"properties\": [],",
"if prop[\"is_readonly\"] else \"\", prop[\"name\"], \"=\" + prop[\"default\"] if prop[\"default\"] != \"None\" else",
"name = \"[%s]\" % name fnArgs += name comma = \", \" out",
"klass in items: hierarchy[section][\"children\"][klass] = parse(klass, data[klass]) path = \"../docs/en/api/\" try: os.mkdir(path) except:",
"directory + \"/\" try: os.mkdir(subPath) except: pass print(\"Writing %s\" % subPath + directory",
"os.mkdir(subPath) except: pass print(\"Writing %s\" % subPath + directory + \".md\") with open(subPath",
"\"\" comma = \"\" for t in types: out += comma if type(t)",
"also:\\n\" for see in seeAlso: out += \"* `%s`\\n\" % (see[\"data\"]) return out",
"is list: # Array of Object for subArg in arg[\"typed\"][0][0][\"details\"]: out += parseParam(subArg,",
"data[section] = {\"base\": { section: {\"description\": \"\", \"sees\":[], \"examples\": {}}}, \"constructors\": {}, \"methods\":",
"print(\" - Writing %s\" % subPath + child + \".md\") with open(subPath +",
"\"\" for t in types: out += comma if type(t) is list: out",
"= \"\" if len(examples) > 0: out += \"\\n\" for ex in examples:",
"out += parseSeeAlso(prop[\"sees\"]) return out def parseSeeAlso(seeAlso): return \"\" \"\"\" out = \"\"",
"+= \"\\n\" for ex in examples: out += \"\\n```%s\\n%s\\n```\\n\" % (ex[\"language\"], ex[\"data\"]) return",
"= \" | \" return out def parseMethod(method, isEvent=False): out = \"\" if",
"data[\"events\"].iteritems(): out += parseMethod(ev, isEvent=True) return out print(\"Running dokumentor\") class captureDokumentor: def __init__(self):",
"isReturn else indent + 4) return out def parseParamsType(types): out = \"\" comma",
"0: out += \"\\n\" for ex in examples: out += \"\\n```%s\\n%s\\n```\\n\" % (ex[\"language\"],",
"path + directory + \".md\") with open(path + directory + \".md\", \"w\") as",
"if prop[\"is_static\"] else \"\", \"`readonly` \" if prop[\"is_readonly\"] else \"\", prop[\"name\"], \"=\" +",
"# Array of Object for subArg in arg[\"typed\"][0][0][\"details\"]: out += parseParam(subArg, 0 if",
"arg[\"is_optional\"]: name = \"[%s]\" % name fnArgs += name comma = \", \"",
"\"`readonly` \" if prop[\"is_readonly\"] else \"\", prop[\"name\"], \"=\" + prop[\"default\"] if prop[\"default\"] !=",
"parseParam(method[\"returns\"], isReturn=True) if tmp: out += \"\\n\" + tmp out += parseSeeAlso(method[\"sees\"]) return",
"= json.loads(sys.stdout.data) sys.stdout = sys.__stdout__ hierarchy = {} for section, items in data[\"_sections\"].iteritems():",
"out def parseSeeAlso(seeAlso): return \"\" \"\"\" out = \"\" if len(seeAlso) > 0:",
"method[\"returns\"][\"typed\"].append(\"null\") tmp = parseParam(method[\"returns\"], isReturn=True) if tmp: out += \"\\n\" + tmp out",
"elif type(arg[\"typed\"][0]) is dict: # Object for subArg in arg[\"typed\"][0][\"details\"]: out += parseParam(subArg,",
"\"\"\" def parseExample(examples): out = \"\" if len(examples) > 0: out += \"\\n\"",
"flush(self=None): pass sys.stdout = captureDokumentor() dokumentor.process(\"../docs/\") docs = sys.modules['DOCC'].DOC dokumentor.report(\"json\", docs) data =",
"`%s` (%s): %s\\n\" % (' ' * indent, arg[\"name\"], parseParamsType(arg[\"typed\"]), arg[\"description\"]) if \"params\"",
"if len(method[\"params\"]) > 0: comma = \"\" for arg in method[\"params\"]: name =",
"+ 4) elif type(arg[\"typed\"][0]) is list: # Array of Object for subArg in",
"docs = sys.modules['DOCC'].DOC dokumentor.report(\"json\", docs) data = json.loads(sys.stdout.data) sys.stdout = sys.__stdout__ hierarchy =",
"% subPath + child + \".md\") with open(subPath + child + \".md\", \"w\")",
"return \"\" \"\"\" out = \"\" if len(seeAlso) > 0: out += \"\\nSee",
"\"\", method[\"name\"])) else: fnArgs = \"\" if len(method[\"params\"]) > 0: comma = \"\"",
"out print(\"Running dokumentor\") class captureDokumentor: def __init__(self): self.data = \"\" def write(self, msg):",
"section not in data: data[section] = {\"base\": { section: {\"description\": \"\", \"sees\":[], \"examples\":",
"arg[\"name\"] if arg[\"default\"] != \"None\": name += \"=%s\" % arg[\"default\"] if arg[\"is_optional\"]: name",
"\" if method[\"is_constructor\"] else \"\", method[\"name\"], fnArgs) if method[\"is_slow\"]: out += \"<!-- YAML\\n-",
"\"\", parseParamsType(prop[\"typed\"])) out += prop[\"description\"] + \"\\n\" out += parseExample(prop[\"examples\"]) out += parseSeeAlso(prop[\"sees\"])",
"item[\"description\"] out += parseExample(item[\"examples\"]) out += parseSeeAlso(item[\"sees\"]) if data[\"constructors\"]: out += parseMethod(data[\"constructors\"][klass]) if",
"tmp = parseParam(method[\"returns\"], isReturn=True) if tmp: out += \"\\n\" + tmp out +=",
"\"\\n## Event: %s\\n\" % (re.sub(\"[A-Za-z_0-9]+\\.\", \"\", method[\"name\"])) else: fnArgs = \"\" if len(method[\"params\"])",
"t else: out += t if t[0].isupper() else t.capitalize() comma = \" |",
"in data[\"_sections\"].iteritems(): if section not in data: data[section] = {\"base\": { section: {\"description\":",
"not method[\"is_constructor\"]: if method[\"returns\"][\"nullable\"]: method[\"returns\"][\"typed\"].append(\"null\") tmp = parseParam(method[\"returns\"], isReturn=True) if tmp: out +=",
"data[\"methods\"]: for name, method in data[\"methods\"].iteritems(): out += parseMethod(method) if data[\"static_methods\"]: for name,",
"if isReturn: out += \"Returns (%s): %s\\n\" % (parseParamsType(arg[\"typed\"]), arg[\"description\"]) else: out +=",
"directory + \".md\") with open(subPath + directory + \".md\", \"w\") as f: f.write(hierarchy[directory][\"data\"])",
"with open(subPath + directory + \".md\", \"w\") as f: f.write(hierarchy[directory][\"data\"]) for child in",
"captureDokumentor() dokumentor.process(\"../docs/\") docs = sys.modules['DOCC'].DOC dokumentor.report(\"json\", docs) data = json.loads(sys.stdout.data) sys.stdout = sys.__stdout__",
"+= prop[\"description\"] + \"\\n\" out += parseExample(prop[\"examples\"]) out += parseSeeAlso(prop[\"sees\"]) return out def",
"else: if t == \"null\": out += t else: out += t if",
"import pprint import os import sys import re import dokumentor import subprocess def",
"out = \"\" if len(seeAlso) > 0: out += \"\\nSee also:\\n\" for see",
"+= \"\\n\" + tmp out += parseSeeAlso(method[\"sees\"]) return out def parseProperty(prop): out =",
"!= \"None\": name += \"=%s\" % arg[\"default\"] if arg[\"is_optional\"]: name = \"[%s]\" %",
"indent + 4) elif type(arg[\"typed\"][0]) is list: # Array of Object for subArg",
"for subArg in arg[\"typed\"][0][0][\"details\"]: out += parseParam(subArg, 0 if isReturn else indent +",
"in types: out += comma if type(t) is list: out += \"Object[]\" elif",
"elif type(arg[\"typed\"][0]) is list: # Array of Object for subArg in arg[\"typed\"][0][0][\"details\"]: out",
"except: pass for directory in hierarchy: if len(hierarchy[directory][\"children\"]) > 1: subPath = path",
"pass for directory in hierarchy: if len(hierarchy[directory][\"children\"]) > 1: subPath = path +",
"out def parse(klass, data): out = \"\" out += \"# Class: %s\" %",
"out += parseMethod(method) if data[\"static_methods\"]: for name, method in data[\"static_methods\"].iteritems(): out += parseMethod(method)",
"arg[\"typed\"][0][\"details\"]: out += parseParam(subArg, 0 if isReturn else indent + 4) elif type(arg[\"typed\"][0])",
"ex in examples: out += \"\\n```%s\\n%s\\n```\\n\" % (ex[\"language\"], ex[\"data\"]) return out def parse(klass,",
"name, prop in data[\"properties\"].iteritems(): out += parseProperty(prop) if data[\"events\"]: for evName, ev in",
"% name fnArgs += name comma = \", \" out += \"\\n## %s%s%s(%s)\\n\"",
"\"examples\": {}}}, \"constructors\": {}, \"methods\": [], \"properties\": [], \"events\":[], \"static_methods\": []} hierarchy[section] =",
"(\"`static` \" if prop[\"is_static\"] else \"\", \"`readonly` \" if prop[\"is_readonly\"] else \"\", prop[\"name\"],",
"if isReturn else indent + 4) return out def parseParamsType(types): out = \"\"",
"prop[\"is_readonly\"] else \"\", prop[\"name\"], \"=\" + prop[\"default\"] if prop[\"default\"] != \"None\" else \"\",",
"+= parseParam(subArg, indent + 4) elif type(arg[\"typed\"][0]) is dict: # Object for subArg",
"with open(subPath + child + \".md\", \"w\") as f: f.write(hierarchy[directory][\"children\"][child]) else: print(\"Writing %s\"",
"comma if type(t) is list: out += \"Object[]\" elif type(t) is dict: out",
"method[\"returns\"] and not method[\"is_constructor\"]: if method[\"returns\"][\"nullable\"]: method[\"returns\"][\"typed\"].append(\"null\") tmp = parseParam(method[\"returns\"], isReturn=True) if tmp:",
"isReturn else indent + 4) elif type(arg[\"typed\"][0]) is list: # Array of Object",
"= \"[%s]\" % name fnArgs += name comma = \", \" out +=",
"isEvent: out += \"\\n## Event: %s\\n\" % (re.sub(\"[A-Za-z_0-9]+\\.\", \"\", method[\"name\"])) else: fnArgs =",
"else \"\", \"new \" if method[\"is_constructor\"] else \"\", method[\"name\"], fnArgs) if method[\"is_slow\"]: out",
"if arg[\"default\"] != \"None\": name += \"=%s\" % arg[\"default\"] if arg[\"is_optional\"]: name =",
"else: print(\"Writing %s\" % path + directory + \".md\") with open(path + directory",
"subPath + directory + \".md\") with open(subPath + directory + \".md\", \"w\") as",
"return out def parseParamsType(types): out = \"\" comma = \"\" for t in",
"\"\" if isReturn: out += \"Returns (%s): %s\\n\" % (parseParamsType(arg[\"typed\"]), arg[\"description\"]) else: out",
"(%s)\\n\" % (\"`static` \" if prop[\"is_static\"] else \"\", \"`readonly` \" if prop[\"is_readonly\"] else",
"if len(seeAlso) > 0: out += \"\\nSee also:\\n\" for see in seeAlso: out",
"fnArgs) if method[\"is_slow\"]: out += \"<!-- YAML\\n- Slow method\\n-->\\n\" out += method[\"description\"] +",
"if len(examples) > 0: out += \"\\n\" for ex in examples: out +=",
"import re import dokumentor import subprocess def parseParam(arg, indent=0, isReturn=False): out = \"\"",
"+ \"\\n\" if len(method[\"params\"]) > 0: out += \"\\nParams:\\n\" for arg in method[\"params\"]:",
"if tmp: out += \"\\n\" + tmp out += parseSeeAlso(method[\"sees\"]) return out def",
"= parseParam(method[\"returns\"], isReturn=True) if tmp: out += \"\\n\" + tmp out += parseSeeAlso(method[\"sees\"])",
"method[\"is_constructor\"]: if method[\"returns\"][\"nullable\"]: method[\"returns\"][\"typed\"].append(\"null\") tmp = parseParam(method[\"returns\"], isReturn=True) if tmp: out += \"\\n\"",
"not in data: data[section] = {\"base\": { section: {\"description\": \"\", \"sees\":[], \"examples\": {}}},",
"method[\"name\"])) else: fnArgs = \"\" if len(method[\"params\"]) > 0: comma = \"\" for",
"out += \"# Class: %s\" % (klass) + \"\\n\" item = data[\"base\"][klass] out",
"if data[\"events\"]: for evName, ev in data[\"events\"].iteritems(): out += parseMethod(ev, isEvent=True) return out",
"%s\" % subPath + child + \".md\") with open(subPath + child + \".md\",",
"\"\" if len(method[\"params\"]) > 0: comma = \"\" for arg in method[\"params\"]: name",
"\"Object\" else: if t[0] == \"[\": out += t[1:-1].capitalize() + \"[]\" else: if",
"len(hierarchy[directory][\"children\"]) > 1: subPath = path + directory + \"/\" try: os.mkdir(subPath) except:",
"isReturn=False): out = \"\" if isReturn: out += \"Returns (%s): %s\\n\" % (parseParamsType(arg[\"typed\"]),",
"parseParamsType(types): out = \"\" comma = \"\" for t in types: out +=",
"arg in method[\"params\"]: out += parseParam(arg) if method[\"returns\"] and not method[\"is_constructor\"]: if method[\"returns\"][\"nullable\"]:",
"\"params\" in arg: # Callback function for subArg in arg[\"params\"]: out += parseParam(subArg,",
"parseMethod(ev, isEvent=True) return out print(\"Running dokumentor\") class captureDokumentor: def __init__(self): self.data = \"\"",
"\"\" for arg in method[\"params\"]: name = comma + arg[\"name\"] if arg[\"default\"] !=",
"ev in data[\"events\"].iteritems(): out += parseMethod(ev, isEvent=True) return out print(\"Running dokumentor\") class captureDokumentor:",
"if isEvent: out += \"\\n## Event: %s\\n\" % (re.sub(\"[A-Za-z_0-9]+\\.\", \"\", method[\"name\"])) else: fnArgs",
"data[\"methods\"].iteritems(): out += parseMethod(method) if data[\"static_methods\"]: for name, method in data[\"static_methods\"].iteritems(): out +=",
"in data[\"events\"].iteritems(): out += parseMethod(ev, isEvent=True) return out print(\"Running dokumentor\") class captureDokumentor: def",
"prop[\"description\"] + \"\\n\" out += parseExample(prop[\"examples\"]) out += parseSeeAlso(prop[\"sees\"]) return out def parseSeeAlso(seeAlso):",
"0 if isReturn else indent + 4) elif type(arg[\"typed\"][0]) is list: # Array",
"arg[\"params\"]: out += parseParam(subArg, indent + 4) elif type(arg[\"typed\"][0]) is dict: # Object",
"in hierarchy: if len(hierarchy[directory][\"children\"]) > 1: subPath = path + directory + \"/\"",
"arg[\"default\"] if arg[\"is_optional\"]: name = \"[%s]\" % name fnArgs += name comma =",
"hierarchy[section][\"children\"][klass] = parse(klass, data[klass]) path = \"../docs/en/api/\" try: os.mkdir(path) except: pass for directory",
"| \" return out def parseMethod(method, isEvent=False): out = \"\" if isEvent: out",
"out += t if t[0].isupper() else t.capitalize() comma = \" | \" return",
"\"* `%s`\\n\" % (see[\"data\"]) return out \"\"\" def parseExample(examples): out = \"\" if",
"msg): self.data += msg def flush(self=None): pass sys.stdout = captureDokumentor() dokumentor.process(\"../docs/\") docs =",
"\".md\", \"w\") as f: f.write(hierarchy[directory][\"children\"][child]) else: print(\"Writing %s\" % path + directory +",
"= \", \" out += \"\\n## %s%s%s(%s)\\n\" % (\"`static `\" if method[\"is_static\"] else",
"+= msg def flush(self=None): pass sys.stdout = captureDokumentor() dokumentor.process(\"../docs/\") docs = sys.modules['DOCC'].DOC dokumentor.report(\"json\",",
"out += \"\\n```%s\\n%s\\n```\\n\" % (ex[\"language\"], ex[\"data\"]) return out def parse(klass, data): out =",
"{} for klass in items: hierarchy[section][\"children\"][klass] = parse(klass, data[klass]) path = \"../docs/en/api/\" try:",
"(see[\"data\"]) return out \"\"\" def parseExample(examples): out = \"\" if len(examples) > 0:",
"+= \"%s* `%s` (%s): %s\\n\" % (' ' * indent, arg[\"name\"], parseParamsType(arg[\"typed\"]), arg[\"description\"])",
"pprint import pprint import os import sys import re import dokumentor import subprocess",
"write(self, msg): self.data += msg def flush(self=None): pass sys.stdout = captureDokumentor() dokumentor.process(\"../docs/\") docs",
"\"w\") as f: f.write(hierarchy[directory][\"children\"][child]) else: print(\"Writing %s\" % path + directory + \".md\")",
"\".md\") with open(subPath + directory + \".md\", \"w\") as f: f.write(hierarchy[directory][\"data\"]) for child",
"+= parseMethod(ev, isEvent=True) return out print(\"Running dokumentor\") class captureDokumentor: def __init__(self): self.data =",
"indent=0, isReturn=False): out = \"\" if isReturn: out += \"Returns (%s): %s\\n\" %",
"+= \"\\nParams:\\n\" for arg in method[\"params\"]: out += parseParam(arg) if method[\"returns\"] and not",
"return out def parseProperty(prop): out = \"\" out += \"\\n## %s%s%s%s (%s)\\n\" %",
"data[section])} hierarchy[section][\"children\"] = {} for klass in items: hierarchy[section][\"children\"][klass] = parse(klass, data[klass]) path",
"parseParam(arg) if method[\"returns\"] and not method[\"is_constructor\"]: if method[\"returns\"][\"nullable\"]: method[\"returns\"][\"typed\"].append(\"null\") tmp = parseParam(method[\"returns\"], isReturn=True)",
"= \"\" for arg in method[\"params\"]: name = comma + arg[\"name\"] if arg[\"default\"]",
"as f: f.write(hierarchy[directory][\"children\"][child]) else: print(\"Writing %s\" % path + directory + \".md\") with",
"\"\\n\" out += parseExample(prop[\"examples\"]) out += parseSeeAlso(prop[\"sees\"]) return out def parseSeeAlso(seeAlso): return \"\"",
"% (' ' * indent, arg[\"name\"], parseParamsType(arg[\"typed\"]), arg[\"description\"]) if \"params\" in arg: #",
"def parseProperty(prop): out = \"\" out += \"\\n## %s%s%s%s (%s)\\n\" % (\"`static` \"",
"(%s): %s\\n\" % (parseParamsType(arg[\"typed\"]), arg[\"description\"]) else: out += \"%s* `%s` (%s): %s\\n\" %",
"json from pprint import pprint import os import sys import re import dokumentor",
"method[\"params\"]: out += parseParam(arg) if method[\"returns\"] and not method[\"is_constructor\"]: if method[\"returns\"][\"nullable\"]: method[\"returns\"][\"typed\"].append(\"null\") tmp",
"> 0: comma = \"\" for arg in method[\"params\"]: name = comma +",
"= \"\" if isEvent: out += \"\\n## Event: %s\\n\" % (re.sub(\"[A-Za-z_0-9]+\\.\", \"\", method[\"name\"]))",
"method[\"returns\"][\"nullable\"]: method[\"returns\"][\"typed\"].append(\"null\") tmp = parseParam(method[\"returns\"], isReturn=True) if tmp: out += \"\\n\" + tmp",
"* indent, arg[\"name\"], parseParamsType(arg[\"typed\"]), arg[\"description\"]) if \"params\" in arg: # Callback function for",
"name = comma + arg[\"name\"] if arg[\"default\"] != \"None\": name += \"=%s\" %",
"%s\" % (klass) + \"\\n\" item = data[\"base\"][klass] out += item[\"description\"] out +=",
"hierarchy: if len(hierarchy[directory][\"children\"]) > 1: subPath = path + directory + \"/\" try:",
"\"\\n```%s\\n%s\\n```\\n\" % (ex[\"language\"], ex[\"data\"]) return out def parse(klass, data): out = \"\" out",
"ex[\"data\"]) return out def parse(klass, data): out = \"\" out += \"# Class:",
"name, method in data[\"static_methods\"].iteritems(): out += parseMethod(method) if data[\"properties\"]: for name, prop in",
"self.data = \"\" def write(self, msg): self.data += msg def flush(self=None): pass sys.stdout",
"parse(klass, data): out = \"\" out += \"# Class: %s\" % (klass) +",
"(klass) + \"\\n\" item = data[\"base\"][klass] out += item[\"description\"] out += parseExample(item[\"examples\"]) out",
"parse(section, data[section])} hierarchy[section][\"children\"] = {} for klass in items: hierarchy[section][\"children\"][klass] = parse(klass, data[klass])",
"open(subPath + child + \".md\", \"w\") as f: f.write(hierarchy[directory][\"children\"][child]) else: print(\"Writing %s\" %",
"def write(self, msg): self.data += msg def flush(self=None): pass sys.stdout = captureDokumentor() dokumentor.process(\"../docs/\")",
"\"None\" else \"\", parseParamsType(prop[\"typed\"])) out += prop[\"description\"] + \"\\n\" out += parseExample(prop[\"examples\"]) out",
"for arg in method[\"params\"]: name = comma + arg[\"name\"] if arg[\"default\"] != \"None\":",
"if isReturn else indent + 4) elif type(arg[\"typed\"][0]) is list: # Array of",
"comma = \"\" for t in types: out += comma if type(t) is",
"\"[%s]\" % name fnArgs += name comma = \", \" out += \"\\n##",
"hierarchy = {} for section, items in data[\"_sections\"].iteritems(): if section not in data:",
"else \"\", \"`readonly` \" if prop[\"is_readonly\"] else \"\", prop[\"name\"], \"=\" + prop[\"default\"] if",
"+= parseParam(subArg, 0 if isReturn else indent + 4) return out def parseParamsType(types):",
"if method[\"is_slow\"]: out += \"<!-- YAML\\n- Slow method\\n-->\\n\" out += method[\"description\"] + \"\\n\"",
"for name, method in data[\"methods\"].iteritems(): out += parseMethod(method) if data[\"static_methods\"]: for name, method",
"print(\"Running dokumentor\") class captureDokumentor: def __init__(self): self.data = \"\" def write(self, msg): self.data",
"comma = \" | \" return out def parseMethod(method, isEvent=False): out = \"\"",
"for arg in method[\"params\"]: out += parseParam(arg) if method[\"returns\"] and not method[\"is_constructor\"]: if",
"in data[\"properties\"].iteritems(): out += parseProperty(prop) if data[\"events\"]: for evName, ev in data[\"events\"].iteritems(): out",
"\"sees\":[], \"examples\": {}}}, \"constructors\": {}, \"methods\": [], \"properties\": [], \"events\":[], \"static_methods\": []} hierarchy[section]",
"type(t) is list: out += \"Object[]\" elif type(t) is dict: out += \"Object\"",
"if method[\"returns\"][\"nullable\"]: method[\"returns\"][\"typed\"].append(\"null\") tmp = parseParam(method[\"returns\"], isReturn=True) if tmp: out += \"\\n\" +",
"data = json.loads(sys.stdout.data) sys.stdout = sys.__stdout__ hierarchy = {} for section, items in",
"in examples: out += \"\\n```%s\\n%s\\n```\\n\" % (ex[\"language\"], ex[\"data\"]) return out def parse(klass, data):",
"else \"\", prop[\"name\"], \"=\" + prop[\"default\"] if prop[\"default\"] != \"None\" else \"\", parseParamsType(prop[\"typed\"]))",
"self.data += msg def flush(self=None): pass sys.stdout = captureDokumentor() dokumentor.process(\"../docs/\") docs = sys.modules['DOCC'].DOC",
"method\\n-->\\n\" out += method[\"description\"] + \"\\n\" if len(method[\"params\"]) > 0: out += \"\\nParams:\\n\"",
"if data[\"static_methods\"]: for name, method in data[\"static_methods\"].iteritems(): out += parseMethod(method) if data[\"properties\"]: for",
"out += item[\"description\"] out += parseExample(item[\"examples\"]) out += parseSeeAlso(item[\"sees\"]) if data[\"constructors\"]: out +=",
"of Object for subArg in arg[\"typed\"][0][0][\"details\"]: out += parseParam(subArg, 0 if isReturn else",
"= \"\" if isReturn: out += \"Returns (%s): %s\\n\" % (parseParamsType(arg[\"typed\"]), arg[\"description\"]) else:",
"out += \"<!-- YAML\\n- Slow method\\n-->\\n\" out += method[\"description\"] + \"\\n\" if len(method[\"params\"])",
"\"constructors\": {}, \"methods\": [], \"properties\": [], \"events\":[], \"static_methods\": []} hierarchy[section] = {\"data\": parse(section,",
"out = \"\" comma = \"\" for t in types: out += comma",
"if t[0].isupper() else t.capitalize() comma = \" | \" return out def parseMethod(method,",
"def parseMethod(method, isEvent=False): out = \"\" if isEvent: out += \"\\n## Event: %s\\n\"",
"% (\"`static `\" if method[\"is_static\"] else \"\", \"new \" if method[\"is_constructor\"] else \"\",",
"child + \".md\") with open(subPath + child + \".md\", \"w\") as f: f.write(hierarchy[directory][\"children\"][child])",
"isEvent=False): out = \"\" if isEvent: out += \"\\n## Event: %s\\n\" % (re.sub(\"[A-Za-z_0-9]+\\.\",",
"parseExample(examples): out = \"\" if len(examples) > 0: out += \"\\n\" for ex",
"Event: %s\\n\" % (re.sub(\"[A-Za-z_0-9]+\\.\", \"\", method[\"name\"])) else: fnArgs = \"\" if len(method[\"params\"]) >",
"if \"params\" in arg: # Callback function for subArg in arg[\"params\"]: out +=",
"= captureDokumentor() dokumentor.process(\"../docs/\") docs = sys.modules['DOCC'].DOC dokumentor.report(\"json\", docs) data = json.loads(sys.stdout.data) sys.stdout =",
"+= item[\"description\"] out += parseExample(item[\"examples\"]) out += parseSeeAlso(item[\"sees\"]) if data[\"constructors\"]: out += parseMethod(data[\"constructors\"][klass])",
"t == \"null\": out += t else: out += t if t[0].isupper() else",
"fnArgs = \"\" if len(method[\"params\"]) > 0: comma = \"\" for arg in",
"elif type(t) is dict: out += \"Object\" else: if t[0] == \"[\": out",
"= \"../docs/en/api/\" try: os.mkdir(path) except: pass for directory in hierarchy: if len(hierarchy[directory][\"children\"]) >",
"\"\", \"`readonly` \" if prop[\"is_readonly\"] else \"\", prop[\"name\"], \"=\" + prop[\"default\"] if prop[\"default\"]",
"\"w\") as f: f.write(hierarchy[directory][\"data\"]) for child in hierarchy[directory][\"children\"]: print(\" - Writing %s\" %",
"{\"description\": \"\", \"sees\":[], \"examples\": {}}}, \"constructors\": {}, \"methods\": [], \"properties\": [], \"events\":[], \"static_methods\":",
"data[klass]) path = \"../docs/en/api/\" try: os.mkdir(path) except: pass for directory in hierarchy: if",
"\"\\n## %s%s%s(%s)\\n\" % (\"`static `\" if method[\"is_static\"] else \"\", \"new \" if method[\"is_constructor\"]",
"\"\" \"\"\" out = \"\" if len(seeAlso) > 0: out += \"\\nSee also:\\n\"",
"section: {\"description\": \"\", \"sees\":[], \"examples\": {}}}, \"constructors\": {}, \"methods\": [], \"properties\": [], \"events\":[],",
"0: comma = \"\" for arg in method[\"params\"]: name = comma + arg[\"name\"]",
"else indent + 4) return out def parseParamsType(types): out = \"\" comma =",
"Object for subArg in arg[\"typed\"][0][\"details\"]: out += parseParam(subArg, 0 if isReturn else indent",
"item = data[\"base\"][klass] out += item[\"description\"] out += parseExample(item[\"examples\"]) out += parseSeeAlso(item[\"sees\"]) if",
"isReturn=True) if tmp: out += \"\\n\" + tmp out += parseSeeAlso(method[\"sees\"]) return out",
"isEvent=True) return out print(\"Running dokumentor\") class captureDokumentor: def __init__(self): self.data = \"\" def",
"out += \"%s* `%s` (%s): %s\\n\" % (' ' * indent, arg[\"name\"], parseParamsType(arg[\"typed\"]),",
"return out print(\"Running dokumentor\") class captureDokumentor: def __init__(self): self.data = \"\" def write(self,",
"if len(hierarchy[directory][\"children\"]) > 1: subPath = path + directory + \"/\" try: os.mkdir(subPath)",
"+ \".md\", \"w\") as f: f.write(hierarchy[directory][\"children\"][child]) else: print(\"Writing %s\" % path + directory",
"% (klass) + \"\\n\" item = data[\"base\"][klass] out += item[\"description\"] out += parseExample(item[\"examples\"])",
"% (parseParamsType(arg[\"typed\"]), arg[\"description\"]) else: out += \"%s* `%s` (%s): %s\\n\" % (' '",
"\"[]\" else: if t == \"null\": out += t else: out += t",
"\"\", \"sees\":[], \"examples\": {}}}, \"constructors\": {}, \"methods\": [], \"properties\": [], \"events\":[], \"static_methods\": []}",
"+= parseParam(subArg, 0 if isReturn else indent + 4) elif type(arg[\"typed\"][0]) is list:",
"parseMethod(data[\"constructors\"][klass]) if data[\"methods\"]: for name, method in data[\"methods\"].iteritems(): out += parseMethod(method) if data[\"static_methods\"]:",
"else: if t[0] == \"[\": out += t[1:-1].capitalize() + \"[]\" else: if t",
"%s\" % subPath + directory + \".md\") with open(subPath + directory + \".md\",",
"for see in seeAlso: out += \"* `%s`\\n\" % (see[\"data\"]) return out \"\"\"",
"comma = \"\" for arg in method[\"params\"]: name = comma + arg[\"name\"] if",
"= {} for section, items in data[\"_sections\"].iteritems(): if section not in data: data[section]",
"f: f.write(hierarchy[directory][\"children\"][child]) else: print(\"Writing %s\" % path + directory + \".md\") with open(path",
"in data[\"methods\"].iteritems(): out += parseMethod(method) if data[\"static_methods\"]: for name, method in data[\"static_methods\"].iteritems(): out",
"4) elif type(arg[\"typed\"][0]) is list: # Array of Object for subArg in arg[\"typed\"][0][0][\"details\"]:",
"method[\"params\"]: name = comma + arg[\"name\"] if arg[\"default\"] != \"None\": name += \"=%s\"",
"t if t[0].isupper() else t.capitalize() comma = \" | \" return out def",
"import subprocess def parseParam(arg, indent=0, isReturn=False): out = \"\" if isReturn: out +=",
"for directory in hierarchy: if len(hierarchy[directory][\"children\"]) > 1: subPath = path + directory",
"= parse(klass, data[klass]) path = \"../docs/en/api/\" try: os.mkdir(path) except: pass for directory in",
"\"methods\": [], \"properties\": [], \"events\":[], \"static_methods\": []} hierarchy[section] = {\"data\": parse(section, data[section])} hierarchy[section][\"children\"]",
"+ \"/\" try: os.mkdir(subPath) except: pass print(\"Writing %s\" % subPath + directory +",
"subprocess def parseParam(arg, indent=0, isReturn=False): out = \"\" if isReturn: out += \"Returns",
"child in hierarchy[directory][\"children\"]: print(\" - Writing %s\" % subPath + child + \".md\")",
"from pprint import pprint import os import sys import re import dokumentor import",
"parseSeeAlso(method[\"sees\"]) return out def parseProperty(prop): out = \"\" out += \"\\n## %s%s%s%s (%s)\\n\"",
"Slow method\\n-->\\n\" out += method[\"description\"] + \"\\n\" if len(method[\"params\"]) > 0: out +=",
"\"\\n\" for ex in examples: out += \"\\n```%s\\n%s\\n```\\n\" % (ex[\"language\"], ex[\"data\"]) return out",
"parseSeeAlso(prop[\"sees\"]) return out def parseSeeAlso(seeAlso): return \"\" \"\"\" out = \"\" if len(seeAlso)",
"return out \"\"\" def parseExample(examples): out = \"\" if len(examples) > 0: out",
"hierarchy[section][\"children\"] = {} for klass in items: hierarchy[section][\"children\"][klass] = parse(klass, data[klass]) path =",
"\" out += \"\\n## %s%s%s(%s)\\n\" % (\"`static `\" if method[\"is_static\"] else \"\", \"new",
"t[1:-1].capitalize() + \"[]\" else: if t == \"null\": out += t else: out",
"\"\" if len(examples) > 0: out += \"\\n\" for ex in examples: out",
"= sys.__stdout__ hierarchy = {} for section, items in data[\"_sections\"].iteritems(): if section not",
"out = \"\" out += \"# Class: %s\" % (klass) + \"\\n\" item",
"for child in hierarchy[directory][\"children\"]: print(\" - Writing %s\" % subPath + child +",
"{}, \"methods\": [], \"properties\": [], \"events\":[], \"static_methods\": []} hierarchy[section] = {\"data\": parse(section, data[section])}",
"== \"[\": out += t[1:-1].capitalize() + \"[]\" else: if t == \"null\": out",
"1: subPath = path + directory + \"/\" try: os.mkdir(subPath) except: pass print(\"Writing",
"return out def parse(klass, data): out = \"\" out += \"# Class: %s\"",
"(%s): %s\\n\" % (' ' * indent, arg[\"name\"], parseParamsType(arg[\"typed\"]), arg[\"description\"]) if \"params\" in",
"out += method[\"description\"] + \"\\n\" if len(method[\"params\"]) > 0: out += \"\\nParams:\\n\" for",
"print(\"Writing %s\" % path + directory + \".md\") with open(path + directory +",
"else \"\", method[\"name\"], fnArgs) if method[\"is_slow\"]: out += \"<!-- YAML\\n- Slow method\\n-->\\n\" out",
"parseSeeAlso(seeAlso): return \"\" \"\"\" out = \"\" if len(seeAlso) > 0: out +=",
"+= \"# Class: %s\" % (klass) + \"\\n\" item = data[\"base\"][klass] out +=",
"os.mkdir(path) except: pass for directory in hierarchy: if len(hierarchy[directory][\"children\"]) > 1: subPath =",
"t[0] == \"[\": out += t[1:-1].capitalize() + \"[]\" else: if t == \"null\":",
"tmp: out += \"\\n\" + tmp out += parseSeeAlso(method[\"sees\"]) return out def parseProperty(prop):",
"+= \"Object[]\" elif type(t) is dict: out += \"Object\" else: if t[0] ==",
"+= parseMethod(method) if data[\"properties\"]: for name, prop in data[\"properties\"].iteritems(): out += parseProperty(prop) if",
"import dokumentor import subprocess def parseParam(arg, indent=0, isReturn=False): out = \"\" if isReturn:",
"else: fnArgs = \"\" if len(method[\"params\"]) > 0: comma = \"\" for arg",
"if section not in data: data[section] = {\"base\": { section: {\"description\": \"\", \"sees\":[],",
"len(method[\"params\"]) > 0: out += \"\\nParams:\\n\" for arg in method[\"params\"]: out += parseParam(arg)",
"% (re.sub(\"[A-Za-z_0-9]+\\.\", \"\", method[\"name\"])) else: fnArgs = \"\" if len(method[\"params\"]) > 0: comma",
"data[\"static_methods\"]: for name, method in data[\"static_methods\"].iteritems(): out += parseMethod(method) if data[\"properties\"]: for name,",
"out += parseExample(item[\"examples\"]) out += parseSeeAlso(item[\"sees\"]) if data[\"constructors\"]: out += parseMethod(data[\"constructors\"][klass]) if data[\"methods\"]:",
"sys.stdout = sys.__stdout__ hierarchy = {} for section, items in data[\"_sections\"].iteritems(): if section",
"type(arg[\"typed\"][0]) is dict: # Object for subArg in arg[\"typed\"][0][\"details\"]: out += parseParam(subArg, 0",
"__init__(self): self.data = \"\" def write(self, msg): self.data += msg def flush(self=None): pass",
"+= \"\\n```%s\\n%s\\n```\\n\" % (ex[\"language\"], ex[\"data\"]) return out def parse(klass, data): out = \"\"",
"try: os.mkdir(path) except: pass for directory in hierarchy: if len(hierarchy[directory][\"children\"]) > 1: subPath",
"+ arg[\"name\"] if arg[\"default\"] != \"None\": name += \"=%s\" % arg[\"default\"] if arg[\"is_optional\"]:",
"if method[\"is_static\"] else \"\", \"new \" if method[\"is_constructor\"] else \"\", method[\"name\"], fnArgs) if",
"in arg[\"params\"]: out += parseParam(subArg, indent + 4) elif type(arg[\"typed\"][0]) is dict: #",
"out += \"\\n## %s%s%s%s (%s)\\n\" % (\"`static` \" if prop[\"is_static\"] else \"\", \"`readonly`",
"Writing %s\" % subPath + child + \".md\") with open(subPath + child +",
"if len(method[\"params\"]) > 0: out += \"\\nParams:\\n\" for arg in method[\"params\"]: out +=",
"sys.stdout = captureDokumentor() dokumentor.process(\"../docs/\") docs = sys.modules['DOCC'].DOC dokumentor.report(\"json\", docs) data = json.loads(sys.stdout.data) sys.stdout",
"\"\", \"new \" if method[\"is_constructor\"] else \"\", method[\"name\"], fnArgs) if method[\"is_slow\"]: out +=",
"method in data[\"static_methods\"].iteritems(): out += parseMethod(method) if data[\"properties\"]: for name, prop in data[\"properties\"].iteritems():",
"+= parseParam(arg) if method[\"returns\"] and not method[\"is_constructor\"]: if method[\"returns\"][\"nullable\"]: method[\"returns\"][\"typed\"].append(\"null\") tmp = parseParam(method[\"returns\"],",
"function for subArg in arg[\"params\"]: out += parseParam(subArg, indent + 4) elif type(arg[\"typed\"][0])",
"sys.__stdout__ hierarchy = {} for section, items in data[\"_sections\"].iteritems(): if section not in",
"items: hierarchy[section][\"children\"][klass] = parse(klass, data[klass]) path = \"../docs/en/api/\" try: os.mkdir(path) except: pass for",
"parseParamsType(arg[\"typed\"]), arg[\"description\"]) if \"params\" in arg: # Callback function for subArg in arg[\"params\"]:",
"== \"null\": out += t else: out += t if t[0].isupper() else t.capitalize()",
"out += \"\\n\" for ex in examples: out += \"\\n```%s\\n%s\\n```\\n\" % (ex[\"language\"], ex[\"data\"])",
"in items: hierarchy[section][\"children\"][klass] = parse(klass, data[klass]) path = \"../docs/en/api/\" try: os.mkdir(path) except: pass",
"prop[\"name\"], \"=\" + prop[\"default\"] if prop[\"default\"] != \"None\" else \"\", parseParamsType(prop[\"typed\"])) out +=",
"list: # Array of Object for subArg in arg[\"typed\"][0][0][\"details\"]: out += parseParam(subArg, 0",
"= {\"data\": parse(section, data[section])} hierarchy[section][\"children\"] = {} for klass in items: hierarchy[section][\"children\"][klass] =",
"parseParam(subArg, 0 if isReturn else indent + 4) return out def parseParamsType(types): out",
"prop[\"default\"] != \"None\" else \"\", parseParamsType(prop[\"typed\"])) out += prop[\"description\"] + \"\\n\" out +=",
"' * indent, arg[\"name\"], parseParamsType(arg[\"typed\"]), arg[\"description\"]) if \"params\" in arg: # Callback function",
"4) elif type(arg[\"typed\"][0]) is dict: # Object for subArg in arg[\"typed\"][0][\"details\"]: out +=",
"def parseSeeAlso(seeAlso): return \"\" \"\"\" out = \"\" if len(seeAlso) > 0: out",
"out += parseParam(subArg, indent + 4) elif type(arg[\"typed\"][0]) is dict: # Object for",
"%s\\n\" % (parseParamsType(arg[\"typed\"]), arg[\"description\"]) else: out += \"%s* `%s` (%s): %s\\n\" % ('",
"% (\"`static` \" if prop[\"is_static\"] else \"\", \"`readonly` \" if prop[\"is_readonly\"] else \"\",",
"\" if prop[\"is_readonly\"] else \"\", prop[\"name\"], \"=\" + prop[\"default\"] if prop[\"default\"] != \"None\"",
"directory in hierarchy: if len(hierarchy[directory][\"children\"]) > 1: subPath = path + directory +",
"%s\" % path + directory + \".md\") with open(path + directory + \".md\",",
"\" | \" return out def parseMethod(method, isEvent=False): out = \"\" if isEvent:",
"Object for subArg in arg[\"typed\"][0][0][\"details\"]: out += parseParam(subArg, 0 if isReturn else indent",
"data[\"constructors\"]: out += parseMethod(data[\"constructors\"][klass]) if data[\"methods\"]: for name, method in data[\"methods\"].iteritems(): out +=",
"> 0: out += \"\\nParams:\\n\" for arg in method[\"params\"]: out += parseParam(arg) if",
"+ \"\\n\" out += parseExample(prop[\"examples\"]) out += parseSeeAlso(prop[\"sees\"]) return out def parseSeeAlso(seeAlso): return",
"= \"\" for t in types: out += comma if type(t) is list:",
"data[\"events\"]: for evName, ev in data[\"events\"].iteritems(): out += parseMethod(ev, isEvent=True) return out print(\"Running",
"\"\\n## %s%s%s%s (%s)\\n\" % (\"`static` \" if prop[\"is_static\"] else \"\", \"`readonly` \" if",
"out += \"\\nSee also:\\n\" for see in seeAlso: out += \"* `%s`\\n\" %",
"> 0: out += \"\\n\" for ex in examples: out += \"\\n```%s\\n%s\\n```\\n\" %",
"out += comma if type(t) is list: out += \"Object[]\" elif type(t) is",
"if method[\"is_constructor\"] else \"\", method[\"name\"], fnArgs) if method[\"is_slow\"]: out += \"<!-- YAML\\n- Slow",
"+= \"\\n## %s%s%s(%s)\\n\" % (\"`static `\" if method[\"is_static\"] else \"\", \"new \" if",
"out += parseExample(prop[\"examples\"]) out += parseSeeAlso(prop[\"sees\"]) return out def parseSeeAlso(seeAlso): return \"\" \"\"\"",
"+= \"Object\" else: if t[0] == \"[\": out += t[1:-1].capitalize() + \"[]\" else:",
"= comma + arg[\"name\"] if arg[\"default\"] != \"None\": name += \"=%s\" % arg[\"default\"]",
"out = \"\" if isReturn: out += \"Returns (%s): %s\\n\" % (parseParamsType(arg[\"typed\"]), arg[\"description\"])",
"%s\\n\" % (' ' * indent, arg[\"name\"], parseParamsType(arg[\"typed\"]), arg[\"description\"]) if \"params\" in arg:",
"\"=\" + prop[\"default\"] if prop[\"default\"] != \"None\" else \"\", parseParamsType(prop[\"typed\"])) out += prop[\"description\"]",
"comma + arg[\"name\"] if arg[\"default\"] != \"None\": name += \"=%s\" % arg[\"default\"] if",
"+= parseSeeAlso(prop[\"sees\"]) return out def parseSeeAlso(seeAlso): return \"\" \"\"\" out = \"\" if",
"= \"\" def write(self, msg): self.data += msg def flush(self=None): pass sys.stdout =",
"def parse(klass, data): out = \"\" out += \"# Class: %s\" % (klass)",
"+= method[\"description\"] + \"\\n\" if len(method[\"params\"]) > 0: out += \"\\nParams:\\n\" for arg",
"+= parseSeeAlso(item[\"sees\"]) if data[\"constructors\"]: out += parseMethod(data[\"constructors\"][klass]) if data[\"methods\"]: for name, method in",
"def __init__(self): self.data = \"\" def write(self, msg): self.data += msg def flush(self=None):",
"parseParamsType(prop[\"typed\"])) out += prop[\"description\"] + \"\\n\" out += parseExample(prop[\"examples\"]) out += parseSeeAlso(prop[\"sees\"]) return",
"+ 4) elif type(arg[\"typed\"][0]) is dict: # Object for subArg in arg[\"typed\"][0][\"details\"]: out",
"(' ' * indent, arg[\"name\"], parseParamsType(arg[\"typed\"]), arg[\"description\"]) if \"params\" in arg: # Callback",
"subArg in arg[\"params\"]: out += parseParam(subArg, indent + 4) elif type(arg[\"typed\"][0]) is dict:",
"import os import sys import re import dokumentor import subprocess def parseParam(arg, indent=0,",
"\" if prop[\"is_static\"] else \"\", \"`readonly` \" if prop[\"is_readonly\"] else \"\", prop[\"name\"], \"=\"",
"\"\" if len(seeAlso) > 0: out += \"\\nSee also:\\n\" for see in seeAlso:",
"{} for section, items in data[\"_sections\"].iteritems(): if section not in data: data[section] =",
"> 1: subPath = path + directory + \"/\" try: os.mkdir(subPath) except: pass",
"YAML\\n- Slow method\\n-->\\n\" out += method[\"description\"] + \"\\n\" if len(method[\"params\"]) > 0: out",
"sys.modules['DOCC'].DOC dokumentor.report(\"json\", docs) data = json.loads(sys.stdout.data) sys.stdout = sys.__stdout__ hierarchy = {} for",
"\"None\": name += \"=%s\" % arg[\"default\"] if arg[\"is_optional\"]: name = \"[%s]\" % name",
"parseMethod(method) if data[\"static_methods\"]: for name, method in data[\"static_methods\"].iteritems(): out += parseMethod(method) if data[\"properties\"]:",
"{}}}, \"constructors\": {}, \"methods\": [], \"properties\": [], \"events\":[], \"static_methods\": []} hierarchy[section] = {\"data\":",
"and not method[\"is_constructor\"]: if method[\"returns\"][\"nullable\"]: method[\"returns\"][\"typed\"].append(\"null\") tmp = parseParam(method[\"returns\"], isReturn=True) if tmp: out",
"dokumentor.process(\"../docs/\") docs = sys.modules['DOCC'].DOC dokumentor.report(\"json\", docs) data = json.loads(sys.stdout.data) sys.stdout = sys.__stdout__ hierarchy",
"parseSeeAlso(item[\"sees\"]) if data[\"constructors\"]: out += parseMethod(data[\"constructors\"][klass]) if data[\"methods\"]: for name, method in data[\"methods\"].iteritems():",
"out += parseMethod(method) if data[\"properties\"]: for name, prop in data[\"properties\"].iteritems(): out += parseProperty(prop)",
"# Callback function for subArg in arg[\"params\"]: out += parseParam(subArg, indent + 4)",
"t.capitalize() comma = \" | \" return out def parseMethod(method, isEvent=False): out =",
"(\"`static `\" if method[\"is_static\"] else \"\", \"new \" if method[\"is_constructor\"] else \"\", method[\"name\"],",
"pass sys.stdout = captureDokumentor() dokumentor.process(\"../docs/\") docs = sys.modules['DOCC'].DOC dokumentor.report(\"json\", docs) data = json.loads(sys.stdout.data)",
"data[\"static_methods\"].iteritems(): out += parseMethod(method) if data[\"properties\"]: for name, prop in data[\"properties\"].iteritems(): out +=",
"hierarchy[directory][\"children\"]: print(\" - Writing %s\" % subPath + child + \".md\") with open(subPath",
"out += \"Returns (%s): %s\\n\" % (parseParamsType(arg[\"typed\"]), arg[\"description\"]) else: out += \"%s* `%s`",
"Class: %s\" % (klass) + \"\\n\" item = data[\"base\"][klass] out += item[\"description\"] out",
"+ prop[\"default\"] if prop[\"default\"] != \"None\" else \"\", parseParamsType(prop[\"typed\"])) out += prop[\"description\"] +",
"\".md\") with open(subPath + child + \".md\", \"w\") as f: f.write(hierarchy[directory][\"children\"][child]) else: print(\"Writing",
"data): out = \"\" out += \"# Class: %s\" % (klass) + \"\\n\"",
"+ \"\\n\" item = data[\"base\"][klass] out += item[\"description\"] out += parseExample(item[\"examples\"]) out +=",
"parseParam(subArg, indent + 4) elif type(arg[\"typed\"][0]) is dict: # Object for subArg in",
"pass print(\"Writing %s\" % subPath + directory + \".md\") with open(subPath + directory",
"+ \".md\", \"w\") as f: f.write(hierarchy[directory][\"data\"]) for child in hierarchy[directory][\"children\"]: print(\" - Writing",
"len(method[\"params\"]) > 0: comma = \"\" for arg in method[\"params\"]: name = comma",
"def parseParam(arg, indent=0, isReturn=False): out = \"\" if isReturn: out += \"Returns (%s):",
"section, items in data[\"_sections\"].iteritems(): if section not in data: data[section] = {\"base\": {",
"tmp out += parseSeeAlso(method[\"sees\"]) return out def parseProperty(prop): out = \"\" out +=",
"+= parseMethod(method) if data[\"static_methods\"]: for name, method in data[\"static_methods\"].iteritems(): out += parseMethod(method) if",
"= \"\" out += \"# Class: %s\" % (klass) + \"\\n\" item =",
"if prop[\"default\"] != \"None\" else \"\", parseParamsType(prop[\"typed\"])) out += prop[\"description\"] + \"\\n\" out",
"(re.sub(\"[A-Za-z_0-9]+\\.\", \"\", method[\"name\"])) else: fnArgs = \"\" if len(method[\"params\"]) > 0: comma =",
"out += parseSeeAlso(item[\"sees\"]) if data[\"constructors\"]: out += parseMethod(data[\"constructors\"][klass]) if data[\"methods\"]: for name, method",
"parseProperty(prop): out = \"\" out += \"\\n## %s%s%s%s (%s)\\n\" % (\"`static` \" if",
"if data[\"properties\"]: for name, prop in data[\"properties\"].iteritems(): out += parseProperty(prop) if data[\"events\"]: for",
"= \"\" if len(method[\"params\"]) > 0: comma = \"\" for arg in method[\"params\"]:",
"\"\" def write(self, msg): self.data += msg def flush(self=None): pass sys.stdout = captureDokumentor()",
"= {} for klass in items: hierarchy[section][\"children\"][klass] = parse(klass, data[klass]) path = \"../docs/en/api/\"",
"os import sys import re import dokumentor import subprocess def parseParam(arg, indent=0, isReturn=False):",
"import json from pprint import pprint import os import sys import re import",
"subArg in arg[\"typed\"][0][\"details\"]: out += parseParam(subArg, 0 if isReturn else indent + 4)",
"indent, arg[\"name\"], parseParamsType(arg[\"typed\"]), arg[\"description\"]) if \"params\" in arg: # Callback function for subArg",
"\"\", prop[\"name\"], \"=\" + prop[\"default\"] if prop[\"default\"] != \"None\" else \"\", parseParamsType(prop[\"typed\"])) out",
"out += parseParam(arg) if method[\"returns\"] and not method[\"is_constructor\"]: if method[\"returns\"][\"nullable\"]: method[\"returns\"][\"typed\"].append(\"null\") tmp =",
"name += \"=%s\" % arg[\"default\"] if arg[\"is_optional\"]: name = \"[%s]\" % name fnArgs",
"dokumentor.report(\"json\", docs) data = json.loads(sys.stdout.data) sys.stdout = sys.__stdout__ hierarchy = {} for section,",
"out def parseProperty(prop): out = \"\" out += \"\\n## %s%s%s%s (%s)\\n\" % (\"`static`",
"%s%s%s(%s)\\n\" % (\"`static `\" if method[\"is_static\"] else \"\", \"new \" if method[\"is_constructor\"] else",
"arg[\"default\"] != \"None\": name += \"=%s\" % arg[\"default\"] if arg[\"is_optional\"]: name = \"[%s]\"",
"> 0: out += \"\\nSee also:\\n\" for see in seeAlso: out += \"*",
"items in data[\"_sections\"].iteritems(): if section not in data: data[section] = {\"base\": { section:",
"+= name comma = \", \" out += \"\\n## %s%s%s(%s)\\n\" % (\"`static `\"",
"\", \" out += \"\\n## %s%s%s(%s)\\n\" % (\"`static `\" if method[\"is_static\"] else \"\",",
"indent + 4) elif type(arg[\"typed\"][0]) is dict: # Object for subArg in arg[\"typed\"][0][\"details\"]:",
"types: out += comma if type(t) is list: out += \"Object[]\" elif type(t)",
"+ directory + \".md\") with open(subPath + directory + \".md\", \"w\") as f:",
"\"%s* `%s` (%s): %s\\n\" % (' ' * indent, arg[\"name\"], parseParamsType(arg[\"typed\"]), arg[\"description\"]) if",
"arg[\"description\"]) else: out += \"%s* `%s` (%s): %s\\n\" % (' ' * indent,",
"is dict: out += \"Object\" else: if t[0] == \"[\": out += t[1:-1].capitalize()",
"try: os.mkdir(subPath) except: pass print(\"Writing %s\" % subPath + directory + \".md\") with",
"open(subPath + directory + \".md\", \"w\") as f: f.write(hierarchy[directory][\"data\"]) for child in hierarchy[directory][\"children\"]:",
"f: f.write(hierarchy[directory][\"data\"]) for child in hierarchy[directory][\"children\"]: print(\" - Writing %s\" % subPath +",
"directory + \".md\", \"w\") as f: f.write(hierarchy[directory][\"data\"]) for child in hierarchy[directory][\"children\"]: print(\" -",
"arg[\"typed\"][0][0][\"details\"]: out += parseParam(subArg, 0 if isReturn else indent + 4) return out",
"\"\\n\" if len(method[\"params\"]) > 0: out += \"\\nParams:\\n\" for arg in method[\"params\"]: out",
"for name, prop in data[\"properties\"].iteritems(): out += parseProperty(prop) if data[\"events\"]: for evName, ev",
"t in types: out += comma if type(t) is list: out += \"Object[]\"",
"fnArgs += name comma = \", \" out += \"\\n## %s%s%s(%s)\\n\" % (\"`static",
"pprint import os import sys import re import dokumentor import subprocess def parseParam(arg,",
"+= parseMethod(data[\"constructors\"][klass]) if data[\"methods\"]: for name, method in data[\"methods\"].iteritems(): out += parseMethod(method) if",
"prop in data[\"properties\"].iteritems(): out += parseProperty(prop) if data[\"events\"]: for evName, ev in data[\"events\"].iteritems():",
"return out def parseMethod(method, isEvent=False): out = \"\" if isEvent: out += \"\\n##",
"% path + directory + \".md\") with open(path + directory + \".md\", \"w\")",
"except: pass print(\"Writing %s\" % subPath + directory + \".md\") with open(subPath +",
"dokumentor import subprocess def parseParam(arg, indent=0, isReturn=False): out = \"\" if isReturn: out",
"[], \"events\":[], \"static_methods\": []} hierarchy[section] = {\"data\": parse(section, data[section])} hierarchy[section][\"children\"] = {} for",
"parseMethod(method, isEvent=False): out = \"\" if isEvent: out += \"\\n## Event: %s\\n\" %",
"+ directory + \".md\") with open(path + directory + \".md\", \"w\") as f:",
"out += \"\\n## Event: %s\\n\" % (re.sub(\"[A-Za-z_0-9]+\\.\", \"\", method[\"name\"])) else: fnArgs = \"\"",
"+ 4) return out def parseParamsType(types): out = \"\" comma = \"\" for",
"out def parseParamsType(types): out = \"\" comma = \"\" for t in types:",
"len(examples) > 0: out += \"\\n\" for ex in examples: out += \"\\n```%s\\n%s\\n```\\n\"",
"name, method in data[\"methods\"].iteritems(): out += parseMethod(method) if data[\"static_methods\"]: for name, method in",
"if arg[\"is_optional\"]: name = \"[%s]\" % name fnArgs += name comma = \",",
"\"properties\": [], \"events\":[], \"static_methods\": []} hierarchy[section] = {\"data\": parse(section, data[section])} hierarchy[section][\"children\"] = {}",
"\".md\", \"w\") as f: f.write(hierarchy[directory][\"data\"]) for child in hierarchy[directory][\"children\"]: print(\" - Writing %s\"",
"%s%s%s%s (%s)\\n\" % (\"`static` \" if prop[\"is_static\"] else \"\", \"`readonly` \" if prop[\"is_readonly\"]",
"\"\" if isEvent: out += \"\\n## Event: %s\\n\" % (re.sub(\"[A-Za-z_0-9]+\\.\", \"\", method[\"name\"])) else:",
"+ child + \".md\") with open(subPath + child + \".md\", \"w\") as f:",
"# Object for subArg in arg[\"typed\"][0][\"details\"]: out += parseParam(subArg, 0 if isReturn else",
"Array of Object for subArg in arg[\"typed\"][0][0][\"details\"]: out += parseParam(subArg, 0 if isReturn",
"+= comma if type(t) is list: out += \"Object[]\" elif type(t) is dict:",
"% (see[\"data\"]) return out \"\"\" def parseExample(examples): out = \"\" if len(examples) >",
"name comma = \", \" out += \"\\n## %s%s%s(%s)\\n\" % (\"`static `\" if",
"subPath + child + \".md\") with open(subPath + child + \".md\", \"w\") as",
"f.write(hierarchy[directory][\"children\"][child]) else: print(\"Writing %s\" % path + directory + \".md\") with open(path +",
"indent + 4) return out def parseParamsType(types): out = \"\" comma = \"\"",
"out += parseMethod(data[\"constructors\"][klass]) if data[\"methods\"]: for name, method in data[\"methods\"].iteritems(): out += parseMethod(method)",
"print(\"Writing %s\" % subPath + directory + \".md\") with open(subPath + directory +",
"for evName, ev in data[\"events\"].iteritems(): out += parseMethod(ev, isEvent=True) return out print(\"Running dokumentor\")",
"import sys import re import dokumentor import subprocess def parseParam(arg, indent=0, isReturn=False): out",
"+ \"[]\" else: if t == \"null\": out += t else: out +=",
"= \"\" out += \"\\n## %s%s%s%s (%s)\\n\" % (\"`static` \" if prop[\"is_static\"] else",
"out += \"\\nParams:\\n\" for arg in method[\"params\"]: out += parseParam(arg) if method[\"returns\"] and",
"\"new \" if method[\"is_constructor\"] else \"\", method[\"name\"], fnArgs) if method[\"is_slow\"]: out += \"<!--",
"+= parseExample(item[\"examples\"]) out += parseSeeAlso(item[\"sees\"]) if data[\"constructors\"]: out += parseMethod(data[\"constructors\"][klass]) if data[\"methods\"]: for",
"prop[\"is_static\"] else \"\", \"`readonly` \" if prop[\"is_readonly\"] else \"\", prop[\"name\"], \"=\" + prop[\"default\"]",
"if t == \"null\": out += t else: out += t if t[0].isupper()",
"list: out += \"Object[]\" elif type(t) is dict: out += \"Object\" else: if",
"dokumentor\") class captureDokumentor: def __init__(self): self.data = \"\" def write(self, msg): self.data +=",
"out += prop[\"description\"] + \"\\n\" out += parseExample(prop[\"examples\"]) out += parseSeeAlso(prop[\"sees\"]) return out",
"method[\"description\"] + \"\\n\" if len(method[\"params\"]) > 0: out += \"\\nParams:\\n\" for arg in",
"dict: out += \"Object\" else: if t[0] == \"[\": out += t[1:-1].capitalize() +",
"arg in method[\"params\"]: name = comma + arg[\"name\"] if arg[\"default\"] != \"None\": name",
"out = \"\" if len(examples) > 0: out += \"\\n\" for ex in",
"for klass in items: hierarchy[section][\"children\"][klass] = parse(klass, data[klass]) path = \"../docs/en/api/\" try: os.mkdir(path)",
"\"<!-- YAML\\n- Slow method\\n-->\\n\" out += method[\"description\"] + \"\\n\" if len(method[\"params\"]) > 0:",
"subPath = path + directory + \"/\" try: os.mkdir(subPath) except: pass print(\"Writing %s\"",
"\"events\":[], \"static_methods\": []} hierarchy[section] = {\"data\": parse(section, data[section])} hierarchy[section][\"children\"] = {} for klass",
"+= \"\\n## Event: %s\\n\" % (re.sub(\"[A-Za-z_0-9]+\\.\", \"\", method[\"name\"])) else: fnArgs = \"\" if",
"0: out += \"\\nParams:\\n\" for arg in method[\"params\"]: out += parseParam(arg) if method[\"returns\"]",
"parseParam(subArg, 0 if isReturn else indent + 4) elif type(arg[\"typed\"][0]) is list: #",
"+ child + \".md\", \"w\") as f: f.write(hierarchy[directory][\"children\"][child]) else: print(\"Writing %s\" % path",
"out += parseParam(subArg, 0 if isReturn else indent + 4) elif type(arg[\"typed\"][0]) is",
"is list: out += \"Object[]\" elif type(t) is dict: out += \"Object\" else:",
"arg[\"description\"]) if \"params\" in arg: # Callback function for subArg in arg[\"params\"]: out",
"out += \"\\n## %s%s%s(%s)\\n\" % (\"`static `\" if method[\"is_static\"] else \"\", \"new \"",
"in method[\"params\"]: out += parseParam(arg) if method[\"returns\"] and not method[\"is_constructor\"]: if method[\"returns\"][\"nullable\"]: method[\"returns\"][\"typed\"].append(\"null\")",
"+= \"\\nSee also:\\n\" for see in seeAlso: out += \"* `%s`\\n\" % (see[\"data\"])",
"\"\\nSee also:\\n\" for see in seeAlso: out += \"* `%s`\\n\" % (see[\"data\"]) return",
"+= parseProperty(prop) if data[\"events\"]: for evName, ev in data[\"events\"].iteritems(): out += parseMethod(ev, isEvent=True)",
"parse(klass, data[klass]) path = \"../docs/en/api/\" try: os.mkdir(path) except: pass for directory in hierarchy:",
"def parseExample(examples): out = \"\" if len(examples) > 0: out += \"\\n\" for",
"\"=%s\" % arg[\"default\"] if arg[\"is_optional\"]: name = \"[%s]\" % name fnArgs += name",
"out = \"\" out += \"\\n## %s%s%s%s (%s)\\n\" % (\"`static` \" if prop[\"is_static\"]",
"data: data[section] = {\"base\": { section: {\"description\": \"\", \"sees\":[], \"examples\": {}}}, \"constructors\": {},",
"(parseParamsType(arg[\"typed\"]), arg[\"description\"]) else: out += \"%s* `%s` (%s): %s\\n\" % (' ' *",
"\"/\" try: os.mkdir(subPath) except: pass print(\"Writing %s\" % subPath + directory + \".md\")",
"out += parseSeeAlso(method[\"sees\"]) return out def parseProperty(prop): out = \"\" out += \"\\n##",
"+= \"Returns (%s): %s\\n\" % (parseParamsType(arg[\"typed\"]), arg[\"description\"]) else: out += \"%s* `%s` (%s):",
"[]} hierarchy[section] = {\"data\": parse(section, data[section])} hierarchy[section][\"children\"] = {} for klass in items:",
"for subArg in arg[\"typed\"][0][\"details\"]: out += parseParam(subArg, 0 if isReturn else indent +",
"dict: # Object for subArg in arg[\"typed\"][0][\"details\"]: out += parseParam(subArg, 0 if isReturn",
"`\" if method[\"is_static\"] else \"\", \"new \" if method[\"is_constructor\"] else \"\", method[\"name\"], fnArgs)",
"return out def parseSeeAlso(seeAlso): return \"\" \"\"\" out = \"\" if len(seeAlso) >",
"= {\"base\": { section: {\"description\": \"\", \"sees\":[], \"examples\": {}}}, \"constructors\": {}, \"methods\": [],",
"for section, items in data[\"_sections\"].iteritems(): if section not in data: data[section] = {\"base\":",
"if data[\"methods\"]: for name, method in data[\"methods\"].iteritems(): out += parseMethod(method) if data[\"static_methods\"]: for",
"type(t) is dict: out += \"Object\" else: if t[0] == \"[\": out +=",
"{\"base\": { section: {\"description\": \"\", \"sees\":[], \"examples\": {}}}, \"constructors\": {}, \"methods\": [], \"properties\":",
"+= \"\\n## %s%s%s%s (%s)\\n\" % (\"`static` \" if prop[\"is_static\"] else \"\", \"`readonly` \"",
"\"\\nParams:\\n\" for arg in method[\"params\"]: out += parseParam(arg) if method[\"returns\"] and not method[\"is_constructor\"]:",
"path = \"../docs/en/api/\" try: os.mkdir(path) except: pass for directory in hierarchy: if len(hierarchy[directory][\"children\"])",
"parseParam(arg, indent=0, isReturn=False): out = \"\" if isReturn: out += \"Returns (%s): %s\\n\"",
"parseProperty(prop) if data[\"events\"]: for evName, ev in data[\"events\"].iteritems(): out += parseMethod(ev, isEvent=True) return",
"method in data[\"methods\"].iteritems(): out += parseMethod(method) if data[\"static_methods\"]: for name, method in data[\"static_methods\"].iteritems():",
"in arg[\"typed\"][0][\"details\"]: out += parseParam(subArg, 0 if isReturn else indent + 4) elif",
"method[\"is_static\"] else \"\", \"new \" if method[\"is_constructor\"] else \"\", method[\"name\"], fnArgs) if method[\"is_slow\"]:",
"`%s`\\n\" % (see[\"data\"]) return out \"\"\" def parseExample(examples): out = \"\" if len(examples)",
"in data: data[section] = {\"base\": { section: {\"description\": \"\", \"sees\":[], \"examples\": {}}}, \"constructors\":",
"in data[\"static_methods\"].iteritems(): out += parseMethod(method) if data[\"properties\"]: for name, prop in data[\"properties\"].iteritems(): out",
"len(seeAlso) > 0: out += \"\\nSee also:\\n\" for see in seeAlso: out +=",
"+ directory + \"/\" try: os.mkdir(subPath) except: pass print(\"Writing %s\" % subPath +",
"for t in types: out += comma if type(t) is list: out +=",
"else t.capitalize() comma = \" | \" return out def parseMethod(method, isEvent=False): out",
"if type(t) is list: out += \"Object[]\" elif type(t) is dict: out +=",
"out += \"* `%s`\\n\" % (see[\"data\"]) return out \"\"\" def parseExample(examples): out =",
"+= t[1:-1].capitalize() + \"[]\" else: if t == \"null\": out += t else:",
"+ tmp out += parseSeeAlso(method[\"sees\"]) return out def parseProperty(prop): out = \"\" out",
"%s\\n\" % (re.sub(\"[A-Za-z_0-9]+\\.\", \"\", method[\"name\"])) else: fnArgs = \"\" if len(method[\"params\"]) > 0:",
"\" return out def parseMethod(method, isEvent=False): out = \"\" if isEvent: out +=",
"{\"data\": parse(section, data[section])} hierarchy[section][\"children\"] = {} for klass in items: hierarchy[section][\"children\"][klass] = parse(klass,",
"data[\"_sections\"].iteritems(): if section not in data: data[section] = {\"base\": { section: {\"description\": \"\",",
"0 if isReturn else indent + 4) return out def parseParamsType(types): out =",
"0: out += \"\\nSee also:\\n\" for see in seeAlso: out += \"* `%s`\\n\"",
"+ directory + \".md\", \"w\") as f: f.write(hierarchy[directory][\"data\"]) for child in hierarchy[directory][\"children\"]: print(\"",
"json.loads(sys.stdout.data) sys.stdout = sys.__stdout__ hierarchy = {} for section, items in data[\"_sections\"].iteritems(): if",
"evName, ev in data[\"events\"].iteritems(): out += parseMethod(ev, isEvent=True) return out print(\"Running dokumentor\") class",
"hierarchy[section] = {\"data\": parse(section, data[section])} hierarchy[section][\"children\"] = {} for klass in items: hierarchy[section][\"children\"][klass]",
"out += parseProperty(prop) if data[\"events\"]: for evName, ev in data[\"events\"].iteritems(): out += parseMethod(ev,",
"= path + directory + \"/\" try: os.mkdir(subPath) except: pass print(\"Writing %s\" %",
"\"# Class: %s\" % (klass) + \"\\n\" item = data[\"base\"][klass] out += item[\"description\"]",
"= data[\"base\"][klass] out += item[\"description\"] out += parseExample(item[\"examples\"]) out += parseSeeAlso(item[\"sees\"]) if data[\"constructors\"]:",
"captureDokumentor: def __init__(self): self.data = \"\" def write(self, msg): self.data += msg def",
"method[\"name\"], fnArgs) if method[\"is_slow\"]: out += \"<!-- YAML\\n- Slow method\\n-->\\n\" out += method[\"description\"]",
"data[\"base\"][klass] out += item[\"description\"] out += parseExample(item[\"examples\"]) out += parseSeeAlso(item[\"sees\"]) if data[\"constructors\"]: out",
"as f: f.write(hierarchy[directory][\"data\"]) for child in hierarchy[directory][\"children\"]: print(\" - Writing %s\" % subPath",
"\"\\n\" item = data[\"base\"][klass] out += item[\"description\"] out += parseExample(item[\"examples\"]) out += parseSeeAlso(item[\"sees\"])",
"+ \".md\") with open(subPath + child + \".md\", \"w\") as f: f.write(hierarchy[directory][\"children\"][child]) else:",
"- Writing %s\" % subPath + child + \".md\") with open(subPath + child",
"for ex in examples: out += \"\\n```%s\\n%s\\n```\\n\" % (ex[\"language\"], ex[\"data\"]) return out def"
] |
[
"import logging import sys import luigi import gokart from gokart_pipeliner.instantiation_task import InstantiationTask from",
"return_value: output = task.output() if type(output) == list: return [x.load() for x in",
"list()): self.config = ConfigManager(params, config_path_list) def run(self, tasks: List[luigi.task_register.Register], params: TYPING.PARAMS = dict(),",
"run(self, tasks: List[luigi.task_register.Register], params: TYPING.PARAMS = dict(), return_value: bool = False, verbose: bool",
"sys import luigi import gokart from gokart_pipeliner.instantiation_task import InstantiationTask from gokart_pipeliner.enum import TYPING",
"task.output() if type(output) == list: return [x.load() for x in output] return output.load()",
"import InstantiationTask from gokart_pipeliner.enum import TYPING from gokart_pipeliner.config_manager import ConfigManager class GokartPipeliner: def",
"luigi.build([task], local_scheduler=True) luigi.task_register.Register.clear_instance_cache() if return_value: output = task.output() if type(output) == list: return",
"in output] return output.load() return None def print_dependence_tree(self, tasks: List[luigi.task_register.Register], params: TYPING.PARAMS =",
"TYPING.PARAMS = dict(), config_path_list: TYPING.STR_LIST = list()): self.config = ConfigManager(params, config_path_list) def run(self,",
"return [x.load() for x in output] return output.load() return None def print_dependence_tree(self, tasks:",
"__init__(self, params: TYPING.PARAMS = dict(), config_path_list: TYPING.STR_LIST = list()): self.config = ConfigManager(params, config_path_list)",
"[x.load() for x in output] return output.load() return None def print_dependence_tree(self, tasks: List[luigi.task_register.Register],",
"True) -> TYPING.RETURN_VALURE: if verbose: logging.disable(0) else: logging.disable(sys.maxsize) luigi.auto_namespace(scope=__name__) luigi.task_register.Register.disable_instance_cache() params = self.config.make_running_params(params)",
"import sys import luigi import gokart from gokart_pipeliner.instantiation_task import InstantiationTask from gokart_pipeliner.enum import",
"from gokart_pipeliner.enum import TYPING from gokart_pipeliner.config_manager import ConfigManager class GokartPipeliner: def __init__(self, params:",
"TYPING.PARAMS = dict()): params = self.config.make_running_params(params) task = InstantiationTask.run(tasks, params=params) print('//-----[dependence_tree]------') print(gokart.info.make_tree_info(task)) print('//----------------------------')",
"gokart_pipeliner.instantiation_task import InstantiationTask from gokart_pipeliner.enum import TYPING from gokart_pipeliner.config_manager import ConfigManager class GokartPipeliner:",
"= ConfigManager(params, config_path_list) def run(self, tasks: List[luigi.task_register.Register], params: TYPING.PARAMS = dict(), return_value: bool",
"def run(self, tasks: List[luigi.task_register.Register], params: TYPING.PARAMS = dict(), return_value: bool = False, verbose:",
"List[luigi.task_register.Register], params: TYPING.PARAMS = dict(), return_value: bool = False, verbose: bool = True)",
"luigi.task_register.Register.clear_instance_cache() if return_value: output = task.output() if type(output) == list: return [x.load() for",
"params: TYPING.PARAMS = dict(), return_value: bool = False, verbose: bool = True) ->",
"params: TYPING.PARAMS = dict()): params = self.config.make_running_params(params) task = InstantiationTask.run(tasks, params=params) print('//-----[dependence_tree]------') print(gokart.info.make_tree_info(task))",
"= InstantiationTask.run(tasks, params=params) luigi.build([task], local_scheduler=True) luigi.task_register.Register.clear_instance_cache() if return_value: output = task.output() if type(output)",
"if return_value: output = task.output() if type(output) == list: return [x.load() for x",
"output.load() return None def print_dependence_tree(self, tasks: List[luigi.task_register.Register], params: TYPING.PARAMS = dict()): params =",
"params: TYPING.PARAMS = dict(), config_path_list: TYPING.STR_LIST = list()): self.config = ConfigManager(params, config_path_list) def",
"TYPING.PARAMS = dict(), return_value: bool = False, verbose: bool = True) -> TYPING.RETURN_VALURE:",
"InstantiationTask.run(tasks, params=params) luigi.build([task], local_scheduler=True) luigi.task_register.Register.clear_instance_cache() if return_value: output = task.output() if type(output) ==",
"None def print_dependence_tree(self, tasks: List[luigi.task_register.Register], params: TYPING.PARAMS = dict()): params = self.config.make_running_params(params) task",
"verbose: bool = True) -> TYPING.RETURN_VALURE: if verbose: logging.disable(0) else: logging.disable(sys.maxsize) luigi.auto_namespace(scope=__name__) luigi.task_register.Register.disable_instance_cache()",
"self.config = ConfigManager(params, config_path_list) def run(self, tasks: List[luigi.task_register.Register], params: TYPING.PARAMS = dict(), return_value:",
"type(output) == list: return [x.load() for x in output] return output.load() return None",
"gokart_pipeliner.config_manager import ConfigManager class GokartPipeliner: def __init__(self, params: TYPING.PARAMS = dict(), config_path_list: TYPING.STR_LIST",
"-> TYPING.RETURN_VALURE: if verbose: logging.disable(0) else: logging.disable(sys.maxsize) luigi.auto_namespace(scope=__name__) luigi.task_register.Register.disable_instance_cache() params = self.config.make_running_params(params) task",
"= False, verbose: bool = True) -> TYPING.RETURN_VALURE: if verbose: logging.disable(0) else: logging.disable(sys.maxsize)",
"gokart from gokart_pipeliner.instantiation_task import InstantiationTask from gokart_pipeliner.enum import TYPING from gokart_pipeliner.config_manager import ConfigManager",
"config_path_list) def run(self, tasks: List[luigi.task_register.Register], params: TYPING.PARAMS = dict(), return_value: bool = False,",
"from gokart_pipeliner.instantiation_task import InstantiationTask from gokart_pipeliner.enum import TYPING from gokart_pipeliner.config_manager import ConfigManager class",
"output = task.output() if type(output) == list: return [x.load() for x in output]",
"= task.output() if type(output) == list: return [x.load() for x in output] return",
"== list: return [x.load() for x in output] return output.load() return None def",
"= True) -> TYPING.RETURN_VALURE: if verbose: logging.disable(0) else: logging.disable(sys.maxsize) luigi.auto_namespace(scope=__name__) luigi.task_register.Register.disable_instance_cache() params =",
"logging.disable(0) else: logging.disable(sys.maxsize) luigi.auto_namespace(scope=__name__) luigi.task_register.Register.disable_instance_cache() params = self.config.make_running_params(params) task = InstantiationTask.run(tasks, params=params) luigi.build([task],",
"return None def print_dependence_tree(self, tasks: List[luigi.task_register.Register], params: TYPING.PARAMS = dict()): params = self.config.make_running_params(params)",
"logging import sys import luigi import gokart from gokart_pipeliner.instantiation_task import InstantiationTask from gokart_pipeliner.enum",
"config_path_list: TYPING.STR_LIST = list()): self.config = ConfigManager(params, config_path_list) def run(self, tasks: List[luigi.task_register.Register], params:",
"if verbose: logging.disable(0) else: logging.disable(sys.maxsize) luigi.auto_namespace(scope=__name__) luigi.task_register.Register.disable_instance_cache() params = self.config.make_running_params(params) task = InstantiationTask.run(tasks,",
"ConfigManager(params, config_path_list) def run(self, tasks: List[luigi.task_register.Register], params: TYPING.PARAMS = dict(), return_value: bool =",
"params = self.config.make_running_params(params) task = InstantiationTask.run(tasks, params=params) luigi.build([task], local_scheduler=True) luigi.task_register.Register.clear_instance_cache() if return_value: output",
"return output.load() return None def print_dependence_tree(self, tasks: List[luigi.task_register.Register], params: TYPING.PARAMS = dict()): params",
"bool = False, verbose: bool = True) -> TYPING.RETURN_VALURE: if verbose: logging.disable(0) else:",
"else: logging.disable(sys.maxsize) luigi.auto_namespace(scope=__name__) luigi.task_register.Register.disable_instance_cache() params = self.config.make_running_params(params) task = InstantiationTask.run(tasks, params=params) luigi.build([task], local_scheduler=True)",
"def __init__(self, params: TYPING.PARAMS = dict(), config_path_list: TYPING.STR_LIST = list()): self.config = ConfigManager(params,",
"from typing import List import logging import sys import luigi import gokart from",
"TYPING.RETURN_VALURE: if verbose: logging.disable(0) else: logging.disable(sys.maxsize) luigi.auto_namespace(scope=__name__) luigi.task_register.Register.disable_instance_cache() params = self.config.make_running_params(params) task =",
"typing import List import logging import sys import luigi import gokart from gokart_pipeliner.instantiation_task",
"logging.disable(sys.maxsize) luigi.auto_namespace(scope=__name__) luigi.task_register.Register.disable_instance_cache() params = self.config.make_running_params(params) task = InstantiationTask.run(tasks, params=params) luigi.build([task], local_scheduler=True) luigi.task_register.Register.clear_instance_cache()",
"task = InstantiationTask.run(tasks, params=params) luigi.build([task], local_scheduler=True) luigi.task_register.Register.clear_instance_cache() if return_value: output = task.output() if",
"dict(), return_value: bool = False, verbose: bool = True) -> TYPING.RETURN_VALURE: if verbose:",
"= dict(), return_value: bool = False, verbose: bool = True) -> TYPING.RETURN_VALURE: if",
"luigi.auto_namespace(scope=__name__) luigi.task_register.Register.disable_instance_cache() params = self.config.make_running_params(params) task = InstantiationTask.run(tasks, params=params) luigi.build([task], local_scheduler=True) luigi.task_register.Register.clear_instance_cache() if",
"import TYPING from gokart_pipeliner.config_manager import ConfigManager class GokartPipeliner: def __init__(self, params: TYPING.PARAMS =",
"output] return output.load() return None def print_dependence_tree(self, tasks: List[luigi.task_register.Register], params: TYPING.PARAMS = dict()):",
"if type(output) == list: return [x.load() for x in output] return output.load() return",
"gokart_pipeliner.enum import TYPING from gokart_pipeliner.config_manager import ConfigManager class GokartPipeliner: def __init__(self, params: TYPING.PARAMS",
"= list()): self.config = ConfigManager(params, config_path_list) def run(self, tasks: List[luigi.task_register.Register], params: TYPING.PARAMS =",
"x in output] return output.load() return None def print_dependence_tree(self, tasks: List[luigi.task_register.Register], params: TYPING.PARAMS",
"list: return [x.load() for x in output] return output.load() return None def print_dependence_tree(self,",
"from gokart_pipeliner.config_manager import ConfigManager class GokartPipeliner: def __init__(self, params: TYPING.PARAMS = dict(), config_path_list:",
"return_value: bool = False, verbose: bool = True) -> TYPING.RETURN_VALURE: if verbose: logging.disable(0)",
"luigi.task_register.Register.disable_instance_cache() params = self.config.make_running_params(params) task = InstantiationTask.run(tasks, params=params) luigi.build([task], local_scheduler=True) luigi.task_register.Register.clear_instance_cache() if return_value:",
"False, verbose: bool = True) -> TYPING.RETURN_VALURE: if verbose: logging.disable(0) else: logging.disable(sys.maxsize) luigi.auto_namespace(scope=__name__)",
"class GokartPipeliner: def __init__(self, params: TYPING.PARAMS = dict(), config_path_list: TYPING.STR_LIST = list()): self.config",
"import List import logging import sys import luigi import gokart from gokart_pipeliner.instantiation_task import",
"def print_dependence_tree(self, tasks: List[luigi.task_register.Register], params: TYPING.PARAMS = dict()): params = self.config.make_running_params(params) task =",
"for x in output] return output.load() return None def print_dependence_tree(self, tasks: List[luigi.task_register.Register], params:",
"local_scheduler=True) luigi.task_register.Register.clear_instance_cache() if return_value: output = task.output() if type(output) == list: return [x.load()",
"<filename>gokart_pipeliner/pipeliner.py<gh_stars>1-10 from typing import List import logging import sys import luigi import gokart",
"dict(), config_path_list: TYPING.STR_LIST = list()): self.config = ConfigManager(params, config_path_list) def run(self, tasks: List[luigi.task_register.Register],",
"List[luigi.task_register.Register], params: TYPING.PARAMS = dict()): params = self.config.make_running_params(params) task = InstantiationTask.run(tasks, params=params) print('//-----[dependence_tree]------')",
"GokartPipeliner: def __init__(self, params: TYPING.PARAMS = dict(), config_path_list: TYPING.STR_LIST = list()): self.config =",
"self.config.make_running_params(params) task = InstantiationTask.run(tasks, params=params) luigi.build([task], local_scheduler=True) luigi.task_register.Register.clear_instance_cache() if return_value: output = task.output()",
"print_dependence_tree(self, tasks: List[luigi.task_register.Register], params: TYPING.PARAMS = dict()): params = self.config.make_running_params(params) task = InstantiationTask.run(tasks,",
"bool = True) -> TYPING.RETURN_VALURE: if verbose: logging.disable(0) else: logging.disable(sys.maxsize) luigi.auto_namespace(scope=__name__) luigi.task_register.Register.disable_instance_cache() params",
"import ConfigManager class GokartPipeliner: def __init__(self, params: TYPING.PARAMS = dict(), config_path_list: TYPING.STR_LIST =",
"import luigi import gokart from gokart_pipeliner.instantiation_task import InstantiationTask from gokart_pipeliner.enum import TYPING from",
"= self.config.make_running_params(params) task = InstantiationTask.run(tasks, params=params) luigi.build([task], local_scheduler=True) luigi.task_register.Register.clear_instance_cache() if return_value: output =",
"params=params) luigi.build([task], local_scheduler=True) luigi.task_register.Register.clear_instance_cache() if return_value: output = task.output() if type(output) == list:",
"import gokart from gokart_pipeliner.instantiation_task import InstantiationTask from gokart_pipeliner.enum import TYPING from gokart_pipeliner.config_manager import",
"List import logging import sys import luigi import gokart from gokart_pipeliner.instantiation_task import InstantiationTask",
"luigi import gokart from gokart_pipeliner.instantiation_task import InstantiationTask from gokart_pipeliner.enum import TYPING from gokart_pipeliner.config_manager",
"tasks: List[luigi.task_register.Register], params: TYPING.PARAMS = dict(), return_value: bool = False, verbose: bool =",
"tasks: List[luigi.task_register.Register], params: TYPING.PARAMS = dict()): params = self.config.make_running_params(params) task = InstantiationTask.run(tasks, params=params)",
"ConfigManager class GokartPipeliner: def __init__(self, params: TYPING.PARAMS = dict(), config_path_list: TYPING.STR_LIST = list()):",
"= dict(), config_path_list: TYPING.STR_LIST = list()): self.config = ConfigManager(params, config_path_list) def run(self, tasks:",
"verbose: logging.disable(0) else: logging.disable(sys.maxsize) luigi.auto_namespace(scope=__name__) luigi.task_register.Register.disable_instance_cache() params = self.config.make_running_params(params) task = InstantiationTask.run(tasks, params=params)",
"TYPING.STR_LIST = list()): self.config = ConfigManager(params, config_path_list) def run(self, tasks: List[luigi.task_register.Register], params: TYPING.PARAMS",
"TYPING from gokart_pipeliner.config_manager import ConfigManager class GokartPipeliner: def __init__(self, params: TYPING.PARAMS = dict(),",
"InstantiationTask from gokart_pipeliner.enum import TYPING from gokart_pipeliner.config_manager import ConfigManager class GokartPipeliner: def __init__(self,"
] |
[
"data, settings = normalize_data(data, x_column, settings) # x_data = combined_data[x_column].values # Plotting if",
"st.session_state.ever_submitted = submitted | st.session_state.ever_submitted use_plotly = st.checkbox(\"Use plotly?\", value=False) if data is",
"st.markdown(\"### Rescale y-axis\") # st.selectbox(\"Choose y-axis scale:\", value=[0, 3, 6, 9], format_func= def",
"x_max data_out = [] for df in data: mask = (df[x_column].values > x_min)",
"# Plotting if use_plotly: fig = go.Figure() else: fig, ax = plt.subplots() for",
"as plt import plotly.express as px import plotly.graph_objects as go import streamlit as",
"boxes below to change the labels for each line that will go on",
"x_column, settings): st.markdown(\"### Limit x Range\") x_min = st.number_input(\"Choose minimum x:\", value=min([min(df[x_column].values) for",
"as go import streamlit as st import io import base64 from util import",
"x Range\") x_min = st.number_input(\"Choose minimum x:\", value=min([min(df[x_column].values) for df in data])) x_max",
"[] for df in data: df2 = df.copy() df2[y_column] = df2[y_column] * scales[scale]",
"'ever_submitted' not in st.session_state: st.session_state.ever_submitted = False settings = {\"processing\": \"None\"} st.markdown(\"\"\"## Combine",
"= st.file_uploader(\"Upload CSV or Excel Files\", accept_multiple_files=True) if files: st.write(files) filenames = [(i,",
"go.Figure() else: fig, ax = plt.subplots() for df, fname, label in zip(data, filenames,",
"= data[ind_fname[0]] cols = list(df.columns) st.write(\"## Choose columns\") with st.form(\"column_chooser_and_run\"): x_column = st.selectbox(\"Choose",
"(or Excel spreadsheets) for easy plotting. \"\"\") files = st.file_uploader(\"Upload CSV or Excel",
"Rescale y-axis\") # st.selectbox(\"Choose y-axis scale:\", value=[0, 3, 6, 9], format_func= def run():",
"# def process_data(data, y_column, settings): # st.markdown(\"### Rescale y-axis\") # st.selectbox(\"Choose y-axis scale:\",",
"display: \", filenames, format_func=lambda x: x[1], index=0) st.write(\"\"\"## Labels Use the boxes below",
"Plotting if use_plotly: fig = go.Figure() else: fig, ax = plt.subplots() for df,",
"= scale data_out = [] for df in data: df2 = df.copy() df2[y_column]",
"# filename = st.text_input(\"Filename:\", value=\"data\") # write_excel(combined_data, filename) if __name__ == \"__main__\": run()",
"index=len(cols)-1) submitted = st.form_submit_button() st.session_state.ever_submitted = submitted | st.session_state.ever_submitted use_plotly = st.checkbox(\"Use plotly?\",",
"st.text_input(\"x-axis label: \", value=x_column) y_label = st.text_input('y-axis label: ', value=y_label_default) grid = st.checkbox(\"Grid?\",",
"import plotly.graph_objects as go import streamlit as st import io import base64 from",
"for df in data: df2 = df.copy() df2[y_column] = df2[y_column] * scales[scale] data_out.append(df2)",
"use_plotly = st.checkbox(\"Use plotly?\", value=False) if data is not None: data, settings =",
"y_column = None combined_data = None processing=\"None\" if 'ever_submitted' not in st.session_state: st.session_state.ever_submitted",
"import plotly.express as px import plotly.graph_objects as go import streamlit as st import",
"plotting. \"\"\") files = st.file_uploader(\"Upload CSV or Excel Files\", accept_multiple_files=True) if files: st.write(files)",
"y_column = st.selectbox(\"Choose y column: \", cols, index=len(cols)-1) submitted = st.form_submit_button() st.session_state.ever_submitted =",
"st.markdown(\"### Scale Current\") scale = st.selectbox(\"Scale:\", list(scales.keys()), index=1) settings['y_scale'] = scale data_out =",
"return data_out, settings scales = {'A': 1, 'mA': 1e3, 'µA': 1e6} def scale_current(data,",
"x_column = st.selectbox(\"Choose the x column: \", cols) y_column = st.selectbox(\"Choose y column:",
"streamlit as st import io import base64 from util import process_file def limit_x_values(data,",
"'mA': 1e3, 'µA': 1e6} def scale_current(data, y_column, settings): st.markdown(\"### Scale Current\") scale =",
"Saving # st.markdown(\"### Output options\") # st.write(combined_data) # filename = st.text_input(\"Filename:\", value=\"data\") #",
"data_out.append(df2) return data_out, settings # def process_data(data, y_column, settings): # st.markdown(\"### Rescale y-axis\")",
"settings = limit_x_values(data, x_column, settings) data, settings = scale_current(data, y_column, settings) # data,",
"label: \", value=x_column) y_label = st.text_input('y-axis label: ', value=y_label_default) grid = st.checkbox(\"Grid?\", value=False)",
"settings # def process_data(data, y_column, settings): # st.markdown(\"### Rescale y-axis\") # st.selectbox(\"Choose y-axis",
"for i, f in enumerate(files)] data = [process_file(f) for f in files] ind_fname",
"numpy as np import pandas as pd import matplotlib.pyplot as plt import plotly.express",
"df.copy() df2[y_column] = df2[y_column] * scales[scale] data_out.append(df2) return data_out, settings # def process_data(data,",
"settings): st.markdown(\"### Scale Current\") scale = st.selectbox(\"Scale:\", list(scales.keys()), index=1) settings['y_scale'] = scale data_out",
"st.selectbox(\"Scale:\", list(scales.keys()), index=1) settings['y_scale'] = scale data_out = [] for df in data:",
"import numpy as np import pandas as pd import matplotlib.pyplot as plt import",
"st.markdown(\"### Plotting options\") x_label = st.text_input(\"x-axis label: \", value=x_column) y_label = st.text_input('y-axis label:",
"= st.form_submit_button() st.session_state.ever_submitted = submitted | st.session_state.ever_submitted use_plotly = st.checkbox(\"Use plotly?\", value=False) if",
"= x_max data_out = [] for df in data: mask = (df[x_column].values >",
"st.write(files) filenames = [(i, f.name) for i, f in enumerate(files)] data = [process_file(f)",
"fig.update_layout(xaxis_title=x_label, yaxis_title=y_label) st.plotly_chart(fig) else: ax.set_xlabel(x_label) ax.set_ylabel(y_label) ax.legend() st.pyplot(fig) # # Saving # st.markdown(\"###",
"in zip(data, filenames, labels): if use_plotly: fig.add_trace(go.Line(x=df[x_column], y=df[y_column], name=str(fname[0])+\"-\"+label)) else: ax.plot(df[x_column].values, df[y_column].values, label=str(fname[0])+\"-\"+label)",
"* (df[x_column].values < x_max) data_out.append(df[mask]) return data_out, settings scales = {'A': 1, 'mA':",
"= plt.subplots() for df, fname, label in zip(data, filenames, labels): if use_plotly: fig.add_trace(go.Line(x=df[x_column],",
"= [(i, f.name) for i, f in enumerate(files)] data = [process_file(f) for f",
"Files\", accept_multiple_files=True) if files: st.write(files) filenames = [(i, f.name) for i, f in",
"plt.subplots() for df, fname, label in zip(data, filenames, labels): if use_plotly: fig.add_trace(go.Line(x=df[x_column], y=df[y_column],",
"data])) x_max = st.number_input(\"Choose maximum x:\", value=max([max(df[x_column].values) for df in data])) settings['x_min'] =",
"data = [process_file(f) for f in files] ind_fname = st.selectbox(\"Choose data to display:",
"the labels for each line that will go on the graph. \"\"\") labels",
"# data, settings = normalize_data(data, x_column, settings) # x_data = combined_data[x_column].values # Plotting",
"\", filenames, format_func=lambda x: x[1], index=0) st.write(\"\"\"## Labels Use the boxes below to",
"CSV or Excel Files\", accept_multiple_files=True) if files: st.write(files) filenames = [(i, f.name) for",
"f in files] ind_fname = st.selectbox(\"Choose data to display: \", filenames, format_func=lambda x:",
"cols, index=len(cols)-1) submitted = st.form_submit_button() st.session_state.ever_submitted = submitted | st.session_state.ever_submitted use_plotly = st.checkbox(\"Use",
"go import streamlit as st import io import base64 from util import process_file",
"st.selectbox(\"Choose y-axis scale:\", value=[0, 3, 6, 9], format_func= def run(): df = None",
"[st.text_input(f\"{filename[0]}. {filename[1]}\", value=filename[1]) for filename in filenames] if ind_fname: df = data[ind_fname[0]] cols",
"plotly.express as px import plotly.graph_objects as go import streamlit as st import io",
"y=df[y_column], name=str(fname[0])+\"-\"+label)) else: ax.plot(df[x_column].values, df[y_column].values, label=str(fname[0])+\"-\"+label) y_label_default = f\"{y_column} ({settings['y_scale']})\" st.markdown(\"### Plotting options\")",
"if data is not None: data, settings = limit_x_values(data, x_column, settings) data, settings",
"= submitted | st.session_state.ever_submitted use_plotly = st.checkbox(\"Use plotly?\", value=False) if data is not",
"will combine multiple CSV files (or Excel spreadsheets) for easy plotting. \"\"\") files",
"df in data])) x_max = st.number_input(\"Choose maximum x:\", value=max([max(df[x_column].values) for df in data]))",
"not use_plotly: ax.grid() if use_plotly: fig.update_layout(xaxis_title=x_label, yaxis_title=y_label) st.plotly_chart(fig) else: ax.set_xlabel(x_label) ax.set_ylabel(y_label) ax.legend() st.pyplot(fig)",
"value=y_label_default) grid = st.checkbox(\"Grid?\", value=False) if grid and not use_plotly: ax.grid() if use_plotly:",
"in st.session_state: st.session_state.ever_submitted = False settings = {\"processing\": \"None\"} st.markdown(\"\"\"## Combine CSV Electrochemistry",
"df in data])) settings['x_min'] = x_min settings['x_max'] = x_max data_out = [] for",
"= list(df.columns) st.write(\"## Choose columns\") with st.form(\"column_chooser_and_run\"): x_column = st.selectbox(\"Choose the x column:",
"Output options\") # st.write(combined_data) # filename = st.text_input(\"Filename:\", value=\"data\") # write_excel(combined_data, filename) if",
"y_label = st.text_input('y-axis label: ', value=y_label_default) grid = st.checkbox(\"Grid?\", value=False) if grid and",
"= None x_column = y_column = None combined_data = None processing=\"None\" if 'ever_submitted'",
"def run(): df = None cols = None x_column = y_column = None",
"st.selectbox(\"Choose data to display: \", filenames, format_func=lambda x: x[1], index=0) st.write(\"\"\"## Labels Use",
"({settings['y_scale']})\" st.markdown(\"### Plotting options\") x_label = st.text_input(\"x-axis label: \", value=x_column) y_label = st.text_input('y-axis",
"labels): if use_plotly: fig.add_trace(go.Line(x=df[x_column], y=df[y_column], name=str(fname[0])+\"-\"+label)) else: ax.plot(df[x_column].values, df[y_column].values, label=str(fname[0])+\"-\"+label) y_label_default = f\"{y_column}",
"accept_multiple_files=True) if files: st.write(files) filenames = [(i, f.name) for i, f in enumerate(files)]",
"if files: st.write(files) filenames = [(i, f.name) for i, f in enumerate(files)] data",
"Labels Use the boxes below to change the labels for each line that",
"else: ax.plot(df[x_column].values, df[y_column].values, label=str(fname[0])+\"-\"+label) y_label_default = f\"{y_column} ({settings['y_scale']})\" st.markdown(\"### Plotting options\") x_label =",
"for df, fname, label in zip(data, filenames, labels): if use_plotly: fig.add_trace(go.Line(x=df[x_column], y=df[y_column], name=str(fname[0])+\"-\"+label))",
"data_out, settings # def process_data(data, y_column, settings): # st.markdown(\"### Rescale y-axis\") # st.selectbox(\"Choose",
"st.markdown(\"\"\"## Combine CSV Electrochemistry files This helper will combine multiple CSV files (or",
"combined_data = None processing=\"None\" if 'ever_submitted' not in st.session_state: st.session_state.ever_submitted = False settings",
"settings = normalize_data(data, x_column, settings) # x_data = combined_data[x_column].values # Plotting if use_plotly:",
"import matplotlib.pyplot as plt import plotly.express as px import plotly.graph_objects as go import",
"pandas as pd import matplotlib.pyplot as plt import plotly.express as px import plotly.graph_objects",
"process_data(data, y_column, settings): # st.markdown(\"### Rescale y-axis\") # st.selectbox(\"Choose y-axis scale:\", value=[0, 3,",
"files (or Excel spreadsheets) for easy plotting. \"\"\") files = st.file_uploader(\"Upload CSV or",
"| st.session_state.ever_submitted use_plotly = st.checkbox(\"Use plotly?\", value=False) if data is not None: data,",
"st.selectbox(\"Choose y column: \", cols, index=len(cols)-1) submitted = st.form_submit_button() st.session_state.ever_submitted = submitted |",
"index=0) st.write(\"\"\"## Labels Use the boxes below to change the labels for each",
"Use the boxes below to change the labels for each line that will",
"if use_plotly: fig.add_trace(go.Line(x=df[x_column], y=df[y_column], name=str(fname[0])+\"-\"+label)) else: ax.plot(df[x_column].values, df[y_column].values, label=str(fname[0])+\"-\"+label) y_label_default = f\"{y_column} ({settings['y_scale']})\"",
"easy plotting. \"\"\") files = st.file_uploader(\"Upload CSV or Excel Files\", accept_multiple_files=True) if files:",
"Electrochemistry files This helper will combine multiple CSV files (or Excel spreadsheets) for",
"to display: \", filenames, format_func=lambda x: x[1], index=0) st.write(\"\"\"## Labels Use the boxes",
"data_out = [] for df in data: mask = (df[x_column].values > x_min) *",
"= f\"{y_column} ({settings['y_scale']})\" st.markdown(\"### Plotting options\") x_label = st.text_input(\"x-axis label: \", value=x_column) y_label",
"'µA': 1e6} def scale_current(data, y_column, settings): st.markdown(\"### Scale Current\") scale = st.selectbox(\"Scale:\", list(scales.keys()),",
"filename in filenames] if ind_fname: df = data[ind_fname[0]] cols = list(df.columns) st.write(\"## Choose",
"x_max = st.number_input(\"Choose maximum x:\", value=max([max(df[x_column].values) for df in data])) settings['x_min'] = x_min",
"st.checkbox(\"Grid?\", value=False) if grid and not use_plotly: ax.grid() if use_plotly: fig.update_layout(xaxis_title=x_label, yaxis_title=y_label) st.plotly_chart(fig)",
"minimum x:\", value=min([min(df[x_column].values) for df in data])) x_max = st.number_input(\"Choose maximum x:\", value=max([max(df[x_column].values)",
"* scales[scale] data_out.append(df2) return data_out, settings # def process_data(data, y_column, settings): # st.markdown(\"###",
"if use_plotly: fig = go.Figure() else: fig, ax = plt.subplots() for df, fname,",
"value=False) if grid and not use_plotly: ax.grid() if use_plotly: fig.update_layout(xaxis_title=x_label, yaxis_title=y_label) st.plotly_chart(fig) else:",
"settings): st.markdown(\"### Limit x Range\") x_min = st.number_input(\"Choose minimum x:\", value=min([min(df[x_column].values) for df",
"ind_fname: df = data[ind_fname[0]] cols = list(df.columns) st.write(\"## Choose columns\") with st.form(\"column_chooser_and_run\"): x_column",
"= go.Figure() else: fig, ax = plt.subplots() for df, fname, label in zip(data,",
"ax.legend() st.pyplot(fig) # # Saving # st.markdown(\"### Output options\") # st.write(combined_data) # filename",
"\"None\"} st.markdown(\"\"\"## Combine CSV Electrochemistry files This helper will combine multiple CSV files",
"= st.selectbox(\"Choose y column: \", cols, index=len(cols)-1) submitted = st.form_submit_button() st.session_state.ever_submitted = submitted",
"the boxes below to change the labels for each line that will go",
"import streamlit as st import io import base64 from util import process_file def",
"None: data, settings = limit_x_values(data, x_column, settings) data, settings = scale_current(data, y_column, settings)",
"= [] for df in data: mask = (df[x_column].values > x_min) * (df[x_column].values",
"ax.set_ylabel(y_label) ax.legend() st.pyplot(fig) # # Saving # st.markdown(\"### Output options\") # st.write(combined_data) #",
"= st.number_input(\"Choose minimum x:\", value=min([min(df[x_column].values) for df in data])) x_max = st.number_input(\"Choose maximum",
"data_out, settings scales = {'A': 1, 'mA': 1e3, 'µA': 1e6} def scale_current(data, y_column,",
"plotly.graph_objects as go import streamlit as st import io import base64 from util",
"plotly?\", value=False) if data is not None: data, settings = limit_x_values(data, x_column, settings)",
"label=str(fname[0])+\"-\"+label) y_label_default = f\"{y_column} ({settings['y_scale']})\" st.markdown(\"### Plotting options\") x_label = st.text_input(\"x-axis label: \",",
"i, f in enumerate(files)] data = [process_file(f) for f in files] ind_fname =",
"scale data_out = [] for df in data: df2 = df.copy() df2[y_column] =",
"st.session_state.ever_submitted = False settings = {\"processing\": \"None\"} st.markdown(\"\"\"## Combine CSV Electrochemistry files This",
"labels for each line that will go on the graph. \"\"\") labels =",
"label in zip(data, filenames, labels): if use_plotly: fig.add_trace(go.Line(x=df[x_column], y=df[y_column], name=str(fname[0])+\"-\"+label)) else: ax.plot(df[x_column].values, df[y_column].values,",
"filenames] if ind_fname: df = data[ind_fname[0]] cols = list(df.columns) st.write(\"## Choose columns\") with",
"fname, label in zip(data, filenames, labels): if use_plotly: fig.add_trace(go.Line(x=df[x_column], y=df[y_column], name=str(fname[0])+\"-\"+label)) else: ax.plot(df[x_column].values,",
"[process_file(f) for f in files] ind_fname = st.selectbox(\"Choose data to display: \", filenames,",
"x_min) * (df[x_column].values < x_max) data_out.append(df[mask]) return data_out, settings scales = {'A': 1,",
"combined_data[x_column].values # Plotting if use_plotly: fig = go.Figure() else: fig, ax = plt.subplots()",
"the graph. \"\"\") labels = [st.text_input(f\"{filename[0]}. {filename[1]}\", value=filename[1]) for filename in filenames] if",
"= df.copy() df2[y_column] = df2[y_column] * scales[scale] data_out.append(df2) return data_out, settings # def",
"1e6} def scale_current(data, y_column, settings): st.markdown(\"### Scale Current\") scale = st.selectbox(\"Scale:\", list(scales.keys()), index=1)",
"scale = st.selectbox(\"Scale:\", list(scales.keys()), index=1) settings['y_scale'] = scale data_out = [] for df",
"= None combined_data = None processing=\"None\" if 'ever_submitted' not in st.session_state: st.session_state.ever_submitted =",
"in files] ind_fname = st.selectbox(\"Choose data to display: \", filenames, format_func=lambda x: x[1],",
"ind_fname = st.selectbox(\"Choose data to display: \", filenames, format_func=lambda x: x[1], index=0) st.write(\"\"\"##",
"def process_data(data, y_column, settings): # st.markdown(\"### Rescale y-axis\") # st.selectbox(\"Choose y-axis scale:\", value=[0,",
"\", cols) y_column = st.selectbox(\"Choose y column: \", cols, index=len(cols)-1) submitted = st.form_submit_button()",
"value=max([max(df[x_column].values) for df in data])) settings['x_min'] = x_min settings['x_max'] = x_max data_out =",
"data: df2 = df.copy() df2[y_column] = df2[y_column] * scales[scale] data_out.append(df2) return data_out, settings",
"y_label_default = f\"{y_column} ({settings['y_scale']})\" st.markdown(\"### Plotting options\") x_label = st.text_input(\"x-axis label: \", value=x_column)",
"np import pandas as pd import matplotlib.pyplot as plt import plotly.express as px",
"f in enumerate(files)] data = [process_file(f) for f in files] ind_fname = st.selectbox(\"Choose",
"label: ', value=y_label_default) grid = st.checkbox(\"Grid?\", value=False) if grid and not use_plotly: ax.grid()",
"submitted = st.form_submit_button() st.session_state.ever_submitted = submitted | st.session_state.ever_submitted use_plotly = st.checkbox(\"Use plotly?\", value=False)",
"files: st.write(files) filenames = [(i, f.name) for i, f in enumerate(files)] data =",
"value=[0, 3, 6, 9], format_func= def run(): df = None cols = None",
"format_func=lambda x: x[1], index=0) st.write(\"\"\"## Labels Use the boxes below to change the",
"x: x[1], index=0) st.write(\"\"\"## Labels Use the boxes below to change the labels",
"for df in data])) settings['x_min'] = x_min settings['x_max'] = x_max data_out = []",
"processing=\"None\" if 'ever_submitted' not in st.session_state: st.session_state.ever_submitted = False settings = {\"processing\": \"None\"}",
"graph. \"\"\") labels = [st.text_input(f\"{filename[0]}. {filename[1]}\", value=filename[1]) for filename in filenames] if ind_fname:",
"# Saving # st.markdown(\"### Output options\") # st.write(combined_data) # filename = st.text_input(\"Filename:\", value=\"data\")",
"maximum x:\", value=max([max(df[x_column].values) for df in data])) settings['x_min'] = x_min settings['x_max'] = x_max",
"files] ind_fname = st.selectbox(\"Choose data to display: \", filenames, format_func=lambda x: x[1], index=0)",
"use_plotly: fig = go.Figure() else: fig, ax = plt.subplots() for df, fname, label",
"below to change the labels for each line that will go on the",
"CSV files (or Excel spreadsheets) for easy plotting. \"\"\") files = st.file_uploader(\"Upload CSV",
"mask = (df[x_column].values > x_min) * (df[x_column].values < x_max) data_out.append(df[mask]) return data_out, settings",
"CSV Electrochemistry files This helper will combine multiple CSV files (or Excel spreadsheets)",
"= None cols = None x_column = y_column = None combined_data = None",
"in enumerate(files)] data = [process_file(f) for f in files] ind_fname = st.selectbox(\"Choose data",
"x_min settings['x_max'] = x_max data_out = [] for df in data: mask =",
"limit_x_values(data, x_column, settings): st.markdown(\"### Limit x Range\") x_min = st.number_input(\"Choose minimum x:\", value=min([min(df[x_column].values)",
"[] for df in data: mask = (df[x_column].values > x_min) * (df[x_column].values <",
"= False settings = {\"processing\": \"None\"} st.markdown(\"\"\"## Combine CSV Electrochemistry files This helper",
"ax = plt.subplots() for df, fname, label in zip(data, filenames, labels): if use_plotly:",
"for filename in filenames] if ind_fname: df = data[ind_fname[0]] cols = list(df.columns) st.write(\"##",
"options\") x_label = st.text_input(\"x-axis label: \", value=x_column) y_label = st.text_input('y-axis label: ', value=y_label_default)",
"as st import io import base64 from util import process_file def limit_x_values(data, x_column,",
"ax.plot(df[x_column].values, df[y_column].values, label=str(fname[0])+\"-\"+label) y_label_default = f\"{y_column} ({settings['y_scale']})\" st.markdown(\"### Plotting options\") x_label = st.text_input(\"x-axis",
"and not use_plotly: ax.grid() if use_plotly: fig.update_layout(xaxis_title=x_label, yaxis_title=y_label) st.plotly_chart(fig) else: ax.set_xlabel(x_label) ax.set_ylabel(y_label) ax.legend()",
"import pandas as pd import matplotlib.pyplot as plt import plotly.express as px import",
"settings) # data, settings = normalize_data(data, x_column, settings) # x_data = combined_data[x_column].values #",
"helper will combine multiple CSV files (or Excel spreadsheets) for easy plotting. \"\"\")",
"st.number_input(\"Choose maximum x:\", value=max([max(df[x_column].values) for df in data])) settings['x_min'] = x_min settings['x_max'] =",
"None x_column = y_column = None combined_data = None processing=\"None\" if 'ever_submitted' not",
"that will go on the graph. \"\"\") labels = [st.text_input(f\"{filename[0]}. {filename[1]}\", value=filename[1]) for",
"filenames, format_func=lambda x: x[1], index=0) st.write(\"\"\"## Labels Use the boxes below to change",
"def limit_x_values(data, x_column, settings): st.markdown(\"### Limit x Range\") x_min = st.number_input(\"Choose minimum x:\",",
"not None: data, settings = limit_x_values(data, x_column, settings) data, settings = scale_current(data, y_column,",
"data, settings = limit_x_values(data, x_column, settings) data, settings = scale_current(data, y_column, settings) #",
"# st.write(combined_data) # filename = st.text_input(\"Filename:\", value=\"data\") # write_excel(combined_data, filename) if __name__ ==",
"= st.selectbox(\"Choose data to display: \", filenames, format_func=lambda x: x[1], index=0) st.write(\"\"\"## Labels",
"filenames = [(i, f.name) for i, f in enumerate(files)] data = [process_file(f) for",
"Excel spreadsheets) for easy plotting. \"\"\") files = st.file_uploader(\"Upload CSV or Excel Files\",",
"enumerate(files)] data = [process_file(f) for f in files] ind_fname = st.selectbox(\"Choose data to",
"line that will go on the graph. \"\"\") labels = [st.text_input(f\"{filename[0]}. {filename[1]}\", value=filename[1])",
"st.write(combined_data) # filename = st.text_input(\"Filename:\", value=\"data\") # write_excel(combined_data, filename) if __name__ == \"__main__\":",
"x column: \", cols) y_column = st.selectbox(\"Choose y column: \", cols, index=len(cols)-1) submitted",
"= scale_current(data, y_column, settings) # data, settings = normalize_data(data, x_column, settings) # x_data",
"None combined_data = None processing=\"None\" if 'ever_submitted' not in st.session_state: st.session_state.ever_submitted = False",
"grid = st.checkbox(\"Grid?\", value=False) if grid and not use_plotly: ax.grid() if use_plotly: fig.update_layout(xaxis_title=x_label,",
"fig = go.Figure() else: fig, ax = plt.subplots() for df, fname, label in",
"if grid and not use_plotly: ax.grid() if use_plotly: fig.update_layout(xaxis_title=x_label, yaxis_title=y_label) st.plotly_chart(fig) else: ax.set_xlabel(x_label)",
"spreadsheets) for easy plotting. \"\"\") files = st.file_uploader(\"Upload CSV or Excel Files\", accept_multiple_files=True)",
"in data])) settings['x_min'] = x_min settings['x_max'] = x_max data_out = [] for df",
"x_max) data_out.append(df[mask]) return data_out, settings scales = {'A': 1, 'mA': 1e3, 'µA': 1e6}",
"= combined_data[x_column].values # Plotting if use_plotly: fig = go.Figure() else: fig, ax =",
"settings) data, settings = scale_current(data, y_column, settings) # data, settings = normalize_data(data, x_column,",
"is not None: data, settings = limit_x_values(data, x_column, settings) data, settings = scale_current(data,",
"data: mask = (df[x_column].values > x_min) * (df[x_column].values < x_max) data_out.append(df[mask]) return data_out,",
"scales[scale] data_out.append(df2) return data_out, settings # def process_data(data, y_column, settings): # st.markdown(\"### Rescale",
"st.pyplot(fig) # # Saving # st.markdown(\"### Output options\") # st.write(combined_data) # filename =",
"9], format_func= def run(): df = None cols = None x_column = y_column",
"data, settings = scale_current(data, y_column, settings) # data, settings = normalize_data(data, x_column, settings)",
"st.number_input(\"Choose minimum x:\", value=min([min(df[x_column].values) for df in data])) x_max = st.number_input(\"Choose maximum x:\",",
"= df2[y_column] * scales[scale] data_out.append(df2) return data_out, settings # def process_data(data, y_column, settings):",
"else: ax.set_xlabel(x_label) ax.set_ylabel(y_label) ax.legend() st.pyplot(fig) # # Saving # st.markdown(\"### Output options\") #",
"else: fig, ax = plt.subplots() for df, fname, label in zip(data, filenames, labels):",
"{filename[1]}\", value=filename[1]) for filename in filenames] if ind_fname: df = data[ind_fname[0]] cols =",
"cols = None x_column = y_column = None combined_data = None processing=\"None\" if",
"Current\") scale = st.selectbox(\"Scale:\", list(scales.keys()), index=1) settings['y_scale'] = scale data_out = [] for",
"\", value=x_column) y_label = st.text_input('y-axis label: ', value=y_label_default) grid = st.checkbox(\"Grid?\", value=False) if",
"ax.grid() if use_plotly: fig.update_layout(xaxis_title=x_label, yaxis_title=y_label) st.plotly_chart(fig) else: ax.set_xlabel(x_label) ax.set_ylabel(y_label) ax.legend() st.pyplot(fig) # #",
"Combine CSV Electrochemistry files This helper will combine multiple CSV files (or Excel",
"on the graph. \"\"\") labels = [st.text_input(f\"{filename[0]}. {filename[1]}\", value=filename[1]) for filename in filenames]",
"= {'A': 1, 'mA': 1e3, 'µA': 1e6} def scale_current(data, y_column, settings): st.markdown(\"### Scale",
"None processing=\"None\" if 'ever_submitted' not in st.session_state: st.session_state.ever_submitted = False settings = {\"processing\":",
"use_plotly: fig.update_layout(xaxis_title=x_label, yaxis_title=y_label) st.plotly_chart(fig) else: ax.set_xlabel(x_label) ax.set_ylabel(y_label) ax.legend() st.pyplot(fig) # # Saving #",
"settings): # st.markdown(\"### Rescale y-axis\") # st.selectbox(\"Choose y-axis scale:\", value=[0, 3, 6, 9],",
"settings) # x_data = combined_data[x_column].values # Plotting if use_plotly: fig = go.Figure() else:",
"y_column, settings): st.markdown(\"### Scale Current\") scale = st.selectbox(\"Scale:\", list(scales.keys()), index=1) settings['y_scale'] = scale",
"Excel Files\", accept_multiple_files=True) if files: st.write(files) filenames = [(i, f.name) for i, f",
"{\"processing\": \"None\"} st.markdown(\"\"\"## Combine CSV Electrochemistry files This helper will combine multiple CSV",
"= None processing=\"None\" if 'ever_submitted' not in st.session_state: st.session_state.ever_submitted = False settings =",
"= {\"processing\": \"None\"} st.markdown(\"\"\"## Combine CSV Electrochemistry files This helper will combine multiple",
"with st.form(\"column_chooser_and_run\"): x_column = st.selectbox(\"Choose the x column: \", cols) y_column = st.selectbox(\"Choose",
"1, 'mA': 1e3, 'µA': 1e6} def scale_current(data, y_column, settings): st.markdown(\"### Scale Current\") scale",
"# # Saving # st.markdown(\"### Output options\") # st.write(combined_data) # filename = st.text_input(\"Filename:\",",
"x_column, settings) # x_data = combined_data[x_column].values # Plotting if use_plotly: fig = go.Figure()",
"ax.set_xlabel(x_label) ax.set_ylabel(y_label) ax.legend() st.pyplot(fig) # # Saving # st.markdown(\"### Output options\") # st.write(combined_data)",
"x_column = y_column = None combined_data = None processing=\"None\" if 'ever_submitted' not in",
"y_column, settings) # data, settings = normalize_data(data, x_column, settings) # x_data = combined_data[x_column].values",
"3, 6, 9], format_func= def run(): df = None cols = None x_column",
"matplotlib.pyplot as plt import plotly.express as px import plotly.graph_objects as go import streamlit",
"> x_min) * (df[x_column].values < x_max) data_out.append(df[mask]) return data_out, settings scales = {'A':",
"st.checkbox(\"Use plotly?\", value=False) if data is not None: data, settings = limit_x_values(data, x_column,",
"st.text_input('y-axis label: ', value=y_label_default) grid = st.checkbox(\"Grid?\", value=False) if grid and not use_plotly:",
"df = None cols = None x_column = y_column = None combined_data =",
"(df[x_column].values > x_min) * (df[x_column].values < x_max) data_out.append(df[mask]) return data_out, settings scales =",
"io import base64 from util import process_file def limit_x_values(data, x_column, settings): st.markdown(\"### Limit",
"= [st.text_input(f\"{filename[0]}. {filename[1]}\", value=filename[1]) for filename in filenames] if ind_fname: df = data[ind_fname[0]]",
"process_file def limit_x_values(data, x_column, settings): st.markdown(\"### Limit x Range\") x_min = st.number_input(\"Choose minimum",
"will go on the graph. \"\"\") labels = [st.text_input(f\"{filename[0]}. {filename[1]}\", value=filename[1]) for filename",
"1e3, 'µA': 1e6} def scale_current(data, y_column, settings): st.markdown(\"### Scale Current\") scale = st.selectbox(\"Scale:\",",
"x_label = st.text_input(\"x-axis label: \", value=x_column) y_label = st.text_input('y-axis label: ', value=y_label_default) grid",
"name=str(fname[0])+\"-\"+label)) else: ax.plot(df[x_column].values, df[y_column].values, label=str(fname[0])+\"-\"+label) y_label_default = f\"{y_column} ({settings['y_scale']})\" st.markdown(\"### Plotting options\") x_label",
"use_plotly: fig.add_trace(go.Line(x=df[x_column], y=df[y_column], name=str(fname[0])+\"-\"+label)) else: ax.plot(df[x_column].values, df[y_column].values, label=str(fname[0])+\"-\"+label) y_label_default = f\"{y_column} ({settings['y_scale']})\" st.markdown(\"###",
"data is not None: data, settings = limit_x_values(data, x_column, settings) data, settings =",
"= st.text_input('y-axis label: ', value=y_label_default) grid = st.checkbox(\"Grid?\", value=False) if grid and not",
"st.session_state: st.session_state.ever_submitted = False settings = {\"processing\": \"None\"} st.markdown(\"\"\"## Combine CSV Electrochemistry files",
"yaxis_title=y_label) st.plotly_chart(fig) else: ax.set_xlabel(x_label) ax.set_ylabel(y_label) ax.legend() st.pyplot(fig) # # Saving # st.markdown(\"### Output",
"normalize_data(data, x_column, settings) # x_data = combined_data[x_column].values # Plotting if use_plotly: fig =",
"y-axis scale:\", value=[0, 3, 6, 9], format_func= def run(): df = None cols",
"st.markdown(\"### Limit x Range\") x_min = st.number_input(\"Choose minimum x:\", value=min([min(df[x_column].values) for df in",
"data_out = [] for df in data: df2 = df.copy() df2[y_column] = df2[y_column]",
"= normalize_data(data, x_column, settings) # x_data = combined_data[x_column].values # Plotting if use_plotly: fig",
"df2[y_column] * scales[scale] data_out.append(df2) return data_out, settings # def process_data(data, y_column, settings): #",
"# st.selectbox(\"Choose y-axis scale:\", value=[0, 3, 6, 9], format_func= def run(): df =",
"if ind_fname: df = data[ind_fname[0]] cols = list(df.columns) st.write(\"## Choose columns\") with st.form(\"column_chooser_and_run\"):",
"each line that will go on the graph. \"\"\") labels = [st.text_input(f\"{filename[0]}. {filename[1]}\",",
"x_column, settings) data, settings = scale_current(data, y_column, settings) # data, settings = normalize_data(data,",
"cols = list(df.columns) st.write(\"## Choose columns\") with st.form(\"column_chooser_and_run\"): x_column = st.selectbox(\"Choose the x",
"= [process_file(f) for f in files] ind_fname = st.selectbox(\"Choose data to display: \",",
"go on the graph. \"\"\") labels = [st.text_input(f\"{filename[0]}. {filename[1]}\", value=filename[1]) for filename in",
"combine multiple CSV files (or Excel spreadsheets) for easy plotting. \"\"\") files =",
"st.form(\"column_chooser_and_run\"): x_column = st.selectbox(\"Choose the x column: \", cols) y_column = st.selectbox(\"Choose y",
"st.write(\"\"\"## Labels Use the boxes below to change the labels for each line",
"fig, ax = plt.subplots() for df, fname, label in zip(data, filenames, labels): if",
"columns\") with st.form(\"column_chooser_and_run\"): x_column = st.selectbox(\"Choose the x column: \", cols) y_column =",
"px import plotly.graph_objects as go import streamlit as st import io import base64",
"to change the labels for each line that will go on the graph.",
"# st.markdown(\"### Rescale y-axis\") # st.selectbox(\"Choose y-axis scale:\", value=[0, 3, 6, 9], format_func=",
"[(i, f.name) for i, f in enumerate(files)] data = [process_file(f) for f in",
"scale_current(data, y_column, settings) # data, settings = normalize_data(data, x_column, settings) # x_data =",
"y-axis\") # st.selectbox(\"Choose y-axis scale:\", value=[0, 3, 6, 9], format_func= def run(): df",
"import process_file def limit_x_values(data, x_column, settings): st.markdown(\"### Limit x Range\") x_min = st.number_input(\"Choose",
"settings = {\"processing\": \"None\"} st.markdown(\"\"\"## Combine CSV Electrochemistry files This helper will combine",
"in data])) x_max = st.number_input(\"Choose maximum x:\", value=max([max(df[x_column].values) for df in data])) settings['x_min']",
"= [] for df in data: df2 = df.copy() df2[y_column] = df2[y_column] *",
"return data_out, settings # def process_data(data, y_column, settings): # st.markdown(\"### Rescale y-axis\") #",
"def scale_current(data, y_column, settings): st.markdown(\"### Scale Current\") scale = st.selectbox(\"Scale:\", list(scales.keys()), index=1) settings['y_scale']",
"for df in data])) x_max = st.number_input(\"Choose maximum x:\", value=max([max(df[x_column].values) for df in",
"None cols = None x_column = y_column = None combined_data = None processing=\"None\"",
"= st.selectbox(\"Scale:\", list(scales.keys()), index=1) settings['y_scale'] = scale data_out = [] for df in",
"not in st.session_state: st.session_state.ever_submitted = False settings = {\"processing\": \"None\"} st.markdown(\"\"\"## Combine CSV",
"base64 from util import process_file def limit_x_values(data, x_column, settings): st.markdown(\"### Limit x Range\")",
"list(scales.keys()), index=1) settings['y_scale'] = scale data_out = [] for df in data: df2",
"# st.markdown(\"### Output options\") # st.write(combined_data) # filename = st.text_input(\"Filename:\", value=\"data\") # write_excel(combined_data,",
"labels = [st.text_input(f\"{filename[0]}. {filename[1]}\", value=filename[1]) for filename in filenames] if ind_fname: df =",
"st.plotly_chart(fig) else: ax.set_xlabel(x_label) ax.set_ylabel(y_label) ax.legend() st.pyplot(fig) # # Saving # st.markdown(\"### Output options\")",
"options\") # st.write(combined_data) # filename = st.text_input(\"Filename:\", value=\"data\") # write_excel(combined_data, filename) if __name__",
"= (df[x_column].values > x_min) * (df[x_column].values < x_max) data_out.append(df[mask]) return data_out, settings scales",
"\", cols, index=len(cols)-1) submitted = st.form_submit_button() st.session_state.ever_submitted = submitted | st.session_state.ever_submitted use_plotly =",
"df2[y_column] = df2[y_column] * scales[scale] data_out.append(df2) return data_out, settings # def process_data(data, y_column,",
"for f in files] ind_fname = st.selectbox(\"Choose data to display: \", filenames, format_func=lambda",
"column: \", cols, index=len(cols)-1) submitted = st.form_submit_button() st.session_state.ever_submitted = submitted | st.session_state.ever_submitted use_plotly",
"= st.number_input(\"Choose maximum x:\", value=max([max(df[x_column].values) for df in data])) settings['x_min'] = x_min settings['x_max']",
"df2 = df.copy() df2[y_column] = df2[y_column] * scales[scale] data_out.append(df2) return data_out, settings #",
"st.selectbox(\"Choose the x column: \", cols) y_column = st.selectbox(\"Choose y column: \", cols,",
"x:\", value=max([max(df[x_column].values) for df in data])) settings['x_min'] = x_min settings['x_max'] = x_max data_out",
"df = data[ind_fname[0]] cols = list(df.columns) st.write(\"## Choose columns\") with st.form(\"column_chooser_and_run\"): x_column =",
"x_data = combined_data[x_column].values # Plotting if use_plotly: fig = go.Figure() else: fig, ax",
"for df in data: mask = (df[x_column].values > x_min) * (df[x_column].values < x_max)",
"Plotting options\") x_label = st.text_input(\"x-axis label: \", value=x_column) y_label = st.text_input('y-axis label: ',",
"= limit_x_values(data, x_column, settings) data, settings = scale_current(data, y_column, settings) # data, settings",
"scale_current(data, y_column, settings): st.markdown(\"### Scale Current\") scale = st.selectbox(\"Scale:\", list(scales.keys()), index=1) settings['y_scale'] =",
"fig.add_trace(go.Line(x=df[x_column], y=df[y_column], name=str(fname[0])+\"-\"+label)) else: ax.plot(df[x_column].values, df[y_column].values, label=str(fname[0])+\"-\"+label) y_label_default = f\"{y_column} ({settings['y_scale']})\" st.markdown(\"### Plotting",
"{'A': 1, 'mA': 1e3, 'µA': 1e6} def scale_current(data, y_column, settings): st.markdown(\"### Scale Current\")",
"the x column: \", cols) y_column = st.selectbox(\"Choose y column: \", cols, index=len(cols)-1)",
"= st.checkbox(\"Grid?\", value=False) if grid and not use_plotly: ax.grid() if use_plotly: fig.update_layout(xaxis_title=x_label, yaxis_title=y_label)",
"False settings = {\"processing\": \"None\"} st.markdown(\"\"\"## Combine CSV Electrochemistry files This helper will",
"data to display: \", filenames, format_func=lambda x: x[1], index=0) st.write(\"\"\"## Labels Use the",
"f\"{y_column} ({settings['y_scale']})\" st.markdown(\"### Plotting options\") x_label = st.text_input(\"x-axis label: \", value=x_column) y_label =",
"st.markdown(\"### Output options\") # st.write(combined_data) # filename = st.text_input(\"Filename:\", value=\"data\") # write_excel(combined_data, filename)",
"x:\", value=min([min(df[x_column].values) for df in data])) x_max = st.number_input(\"Choose maximum x:\", value=max([max(df[x_column].values) for",
"= x_min settings['x_max'] = x_max data_out = [] for df in data: mask",
"Scale Current\") scale = st.selectbox(\"Scale:\", list(scales.keys()), index=1) settings['y_scale'] = scale data_out = []",
"st.session_state.ever_submitted use_plotly = st.checkbox(\"Use plotly?\", value=False) if data is not None: data, settings",
"zip(data, filenames, labels): if use_plotly: fig.add_trace(go.Line(x=df[x_column], y=df[y_column], name=str(fname[0])+\"-\"+label)) else: ax.plot(df[x_column].values, df[y_column].values, label=str(fname[0])+\"-\"+label) y_label_default",
"\"\"\") files = st.file_uploader(\"Upload CSV or Excel Files\", accept_multiple_files=True) if files: st.write(files) filenames",
"or Excel Files\", accept_multiple_files=True) if files: st.write(files) filenames = [(i, f.name) for i,",
"= st.selectbox(\"Choose the x column: \", cols) y_column = st.selectbox(\"Choose y column: \",",
"multiple CSV files (or Excel spreadsheets) for easy plotting. \"\"\") files = st.file_uploader(\"Upload",
"files = st.file_uploader(\"Upload CSV or Excel Files\", accept_multiple_files=True) if files: st.write(files) filenames =",
"value=filename[1]) for filename in filenames] if ind_fname: df = data[ind_fname[0]] cols = list(df.columns)",
"submitted | st.session_state.ever_submitted use_plotly = st.checkbox(\"Use plotly?\", value=False) if data is not None:",
"grid and not use_plotly: ax.grid() if use_plotly: fig.update_layout(xaxis_title=x_label, yaxis_title=y_label) st.plotly_chart(fig) else: ax.set_xlabel(x_label) ax.set_ylabel(y_label)",
"y column: \", cols, index=len(cols)-1) submitted = st.form_submit_button() st.session_state.ever_submitted = submitted | st.session_state.ever_submitted",
"df in data: mask = (df[x_column].values > x_min) * (df[x_column].values < x_max) data_out.append(df[mask])",
"x_min = st.number_input(\"Choose minimum x:\", value=min([min(df[x_column].values) for df in data])) x_max = st.number_input(\"Choose",
"Choose columns\") with st.form(\"column_chooser_and_run\"): x_column = st.selectbox(\"Choose the x column: \", cols) y_column",
"column: \", cols) y_column = st.selectbox(\"Choose y column: \", cols, index=len(cols)-1) submitted =",
"pd import matplotlib.pyplot as plt import plotly.express as px import plotly.graph_objects as go",
"st import io import base64 from util import process_file def limit_x_values(data, x_column, settings):",
"st.write(\"## Choose columns\") with st.form(\"column_chooser_and_run\"): x_column = st.selectbox(\"Choose the x column: \", cols)",
"as pd import matplotlib.pyplot as plt import plotly.express as px import plotly.graph_objects as",
"list(df.columns) st.write(\"## Choose columns\") with st.form(\"column_chooser_and_run\"): x_column = st.selectbox(\"Choose the x column: \",",
"df[y_column].values, label=str(fname[0])+\"-\"+label) y_label_default = f\"{y_column} ({settings['y_scale']})\" st.markdown(\"### Plotting options\") x_label = st.text_input(\"x-axis label:",
"settings['x_max'] = x_max data_out = [] for df in data: mask = (df[x_column].values",
"(df[x_column].values < x_max) data_out.append(df[mask]) return data_out, settings scales = {'A': 1, 'mA': 1e3,",
"in filenames] if ind_fname: df = data[ind_fname[0]] cols = list(df.columns) st.write(\"## Choose columns\")",
"scale:\", value=[0, 3, 6, 9], format_func= def run(): df = None cols =",
"Limit x Range\") x_min = st.number_input(\"Choose minimum x:\", value=min([min(df[x_column].values) for df in data]))",
"settings['x_min'] = x_min settings['x_max'] = x_max data_out = [] for df in data:",
"settings['y_scale'] = scale data_out = [] for df in data: df2 = df.copy()",
"', value=y_label_default) grid = st.checkbox(\"Grid?\", value=False) if grid and not use_plotly: ax.grid() if",
"f.name) for i, f in enumerate(files)] data = [process_file(f) for f in files]",
"index=1) settings['y_scale'] = scale data_out = [] for df in data: df2 =",
"This helper will combine multiple CSV files (or Excel spreadsheets) for easy plotting.",
"filenames, labels): if use_plotly: fig.add_trace(go.Line(x=df[x_column], y=df[y_column], name=str(fname[0])+\"-\"+label)) else: ax.plot(df[x_column].values, df[y_column].values, label=str(fname[0])+\"-\"+label) y_label_default =",
"Range\") x_min = st.number_input(\"Choose minimum x:\", value=min([min(df[x_column].values) for df in data])) x_max =",
"in data: mask = (df[x_column].values > x_min) * (df[x_column].values < x_max) data_out.append(df[mask]) return",
"x[1], index=0) st.write(\"\"\"## Labels Use the boxes below to change the labels for",
"settings scales = {'A': 1, 'mA': 1e3, 'µA': 1e6} def scale_current(data, y_column, settings):",
"settings = scale_current(data, y_column, settings) # data, settings = normalize_data(data, x_column, settings) #",
"st.form_submit_button() st.session_state.ever_submitted = submitted | st.session_state.ever_submitted use_plotly = st.checkbox(\"Use plotly?\", value=False) if data",
"= y_column = None combined_data = None processing=\"None\" if 'ever_submitted' not in st.session_state:",
"run(): df = None cols = None x_column = y_column = None combined_data",
"= st.text_input(\"x-axis label: \", value=x_column) y_label = st.text_input('y-axis label: ', value=y_label_default) grid =",
"df, fname, label in zip(data, filenames, labels): if use_plotly: fig.add_trace(go.Line(x=df[x_column], y=df[y_column], name=str(fname[0])+\"-\"+label)) else:",
"for each line that will go on the graph. \"\"\") labels = [st.text_input(f\"{filename[0]}.",
"if 'ever_submitted' not in st.session_state: st.session_state.ever_submitted = False settings = {\"processing\": \"None\"} st.markdown(\"\"\"##",
"use_plotly: ax.grid() if use_plotly: fig.update_layout(xaxis_title=x_label, yaxis_title=y_label) st.plotly_chart(fig) else: ax.set_xlabel(x_label) ax.set_ylabel(y_label) ax.legend() st.pyplot(fig) #",
"value=False) if data is not None: data, settings = limit_x_values(data, x_column, settings) data,",
"data_out.append(df[mask]) return data_out, settings scales = {'A': 1, 'mA': 1e3, 'µA': 1e6} def",
"change the labels for each line that will go on the graph. \"\"\")",
"# x_data = combined_data[x_column].values # Plotting if use_plotly: fig = go.Figure() else: fig,",
"as np import pandas as pd import matplotlib.pyplot as plt import plotly.express as",
"\"\"\") labels = [st.text_input(f\"{filename[0]}. {filename[1]}\", value=filename[1]) for filename in filenames] if ind_fname: df",
"df in data: df2 = df.copy() df2[y_column] = df2[y_column] * scales[scale] data_out.append(df2) return",
"from util import process_file def limit_x_values(data, x_column, settings): st.markdown(\"### Limit x Range\") x_min",
"util import process_file def limit_x_values(data, x_column, settings): st.markdown(\"### Limit x Range\") x_min =",
"in data: df2 = df.copy() df2[y_column] = df2[y_column] * scales[scale] data_out.append(df2) return data_out,",
"for easy plotting. \"\"\") files = st.file_uploader(\"Upload CSV or Excel Files\", accept_multiple_files=True) if",
"value=x_column) y_label = st.text_input('y-axis label: ', value=y_label_default) grid = st.checkbox(\"Grid?\", value=False) if grid",
"data])) settings['x_min'] = x_min settings['x_max'] = x_max data_out = [] for df in",
"st.file_uploader(\"Upload CSV or Excel Files\", accept_multiple_files=True) if files: st.write(files) filenames = [(i, f.name)",
"data[ind_fname[0]] cols = list(df.columns) st.write(\"## Choose columns\") with st.form(\"column_chooser_and_run\"): x_column = st.selectbox(\"Choose the",
"6, 9], format_func= def run(): df = None cols = None x_column =",
"cols) y_column = st.selectbox(\"Choose y column: \", cols, index=len(cols)-1) submitted = st.form_submit_button() st.session_state.ever_submitted",
"import base64 from util import process_file def limit_x_values(data, x_column, settings): st.markdown(\"### Limit x",
"y_column, settings): # st.markdown(\"### Rescale y-axis\") # st.selectbox(\"Choose y-axis scale:\", value=[0, 3, 6,",
"scales = {'A': 1, 'mA': 1e3, 'µA': 1e6} def scale_current(data, y_column, settings): st.markdown(\"###",
"= st.checkbox(\"Use plotly?\", value=False) if data is not None: data, settings = limit_x_values(data,",
"as px import plotly.graph_objects as go import streamlit as st import io import",
"plt import plotly.express as px import plotly.graph_objects as go import streamlit as st",
"format_func= def run(): df = None cols = None x_column = y_column =",
"limit_x_values(data, x_column, settings) data, settings = scale_current(data, y_column, settings) # data, settings =",
"value=min([min(df[x_column].values) for df in data])) x_max = st.number_input(\"Choose maximum x:\", value=max([max(df[x_column].values) for df",
"import io import base64 from util import process_file def limit_x_values(data, x_column, settings): st.markdown(\"###",
"if use_plotly: fig.update_layout(xaxis_title=x_label, yaxis_title=y_label) st.plotly_chart(fig) else: ax.set_xlabel(x_label) ax.set_ylabel(y_label) ax.legend() st.pyplot(fig) # # Saving",
"files This helper will combine multiple CSV files (or Excel spreadsheets) for easy",
"< x_max) data_out.append(df[mask]) return data_out, settings scales = {'A': 1, 'mA': 1e3, 'µA':"
] |
[
"mystr_chars[-1]: return palindrome(mystr_chars[1:len(mystr_chars) - 1]) else: return False def main(): print(palindrome(\"racecar\")) print(palindrome(\"kayak\")) print(palindrome(\"Live",
"Write a function that takes a string as a parameter and returns True",
"\"\"\" from string import ascii_lowercase def palindrome(mystr): mystr = mystr.lower() mystr_char_list = []",
"not on evil\")) print(palindrome(\"aibohphobia\")) print(palindrome(\"Reviled did I live, said I, as evil I",
"= [] for char in mystr: if char in ascii_lowercase: mystr_char_list.append(char) mystr_chars =",
"in mystr: if char in ascii_lowercase: mystr_char_list.append(char) mystr_chars = ''.join(mystr_char_list) if len(mystr_chars) ==",
"return False def main(): print(palindrome(\"racecar\")) print(palindrome(\"kayak\")) print(palindrome(\"Live not on evil\")) print(palindrome(\"aibohphobia\")) print(palindrome(\"Reviled did",
"mystr_chars = ''.join(mystr_char_list) if len(mystr_chars) == 0 or len(mystr_chars) == 1: return True",
"a parameter and returns True if the string is a palindrome, False otherwise.",
"I'm a lasagna hog.\")) print(palindrome(\"Able was I ere I saw Elba\")) print(palindrome(\"Kanakanak\")) print(palindrome(\"Wassamassaw\"))",
"if the string is a palindrome, False otherwise. \"\"\" from string import ascii_lowercase",
"a string as a parameter and returns True if the string is a",
"was I ere I saw Elba\")) print(palindrome(\"Kanakanak\")) print(palindrome(\"Wassamassaw\")) if __name__ == \"__main__\": main()",
"mystr = mystr.lower() mystr_char_list = [] for char in mystr: if char in",
"True if the string is a palindrome, False otherwise. \"\"\" from string import",
"hog.\")) print(palindrome(\"Able was I ere I saw Elba\")) print(palindrome(\"Kanakanak\")) print(palindrome(\"Wassamassaw\")) if __name__ ==",
"and returns True if the string is a palindrome, False otherwise. \"\"\" from",
"is a palindrome, False otherwise. \"\"\" from string import ascii_lowercase def palindrome(mystr): mystr",
"if len(mystr_chars) == 0 or len(mystr_chars) == 1: return True else: if mystr_chars[0]",
"= ''.join(mystr_char_list) if len(mystr_chars) == 0 or len(mystr_chars) == 1: return True else:",
"string is a palindrome, False otherwise. \"\"\" from string import ascii_lowercase def palindrome(mystr):",
"print(palindrome(\"racecar\")) print(palindrome(\"kayak\")) print(palindrome(\"Live not on evil\")) print(palindrome(\"aibohphobia\")) print(palindrome(\"Reviled did I live, said I,",
"lasagna hog.\")) print(palindrome(\"Able was I ere I saw Elba\")) print(palindrome(\"Kanakanak\")) print(palindrome(\"Wassamassaw\")) if __name__",
"char in mystr: if char in ascii_lowercase: mystr_char_list.append(char) mystr_chars = ''.join(mystr_char_list) if len(mystr_chars)",
"- 1]) else: return False def main(): print(palindrome(\"racecar\")) print(palindrome(\"kayak\")) print(palindrome(\"Live not on evil\"))",
"otherwise. \"\"\" from string import ascii_lowercase def palindrome(mystr): mystr = mystr.lower() mystr_char_list =",
"palindrome(mystr): mystr = mystr.lower() mystr_char_list = [] for char in mystr: if char",
"False def main(): print(palindrome(\"racecar\")) print(palindrome(\"kayak\")) print(palindrome(\"Live not on evil\")) print(palindrome(\"aibohphobia\")) print(palindrome(\"Reviled did I",
"said I, as evil I did deliver\")) print(palindrome(\"Go hang a salami; I'm a",
"print(palindrome(\"aibohphobia\")) print(palindrome(\"Reviled did I live, said I, as evil I did deliver\")) print(palindrome(\"Go",
"live, said I, as evil I did deliver\")) print(palindrome(\"Go hang a salami; I'm",
"a function that takes a string as a parameter and returns True if",
"salami; I'm a lasagna hog.\")) print(palindrome(\"Able was I ere I saw Elba\")) print(palindrome(\"Kanakanak\"))",
"False otherwise. \"\"\" from string import ascii_lowercase def palindrome(mystr): mystr = mystr.lower() mystr_char_list",
"returns True if the string is a palindrome, False otherwise. \"\"\" from string",
"for char in mystr: if char in ascii_lowercase: mystr_char_list.append(char) mystr_chars = ''.join(mystr_char_list) if",
"''.join(mystr_char_list) if len(mystr_chars) == 0 or len(mystr_chars) == 1: return True else: if",
"True else: if mystr_chars[0] == mystr_chars[-1]: return palindrome(mystr_chars[1:len(mystr_chars) - 1]) else: return False",
"palindrome(mystr_chars[1:len(mystr_chars) - 1]) else: return False def main(): print(palindrome(\"racecar\")) print(palindrome(\"kayak\")) print(palindrome(\"Live not on",
"ascii_lowercase def palindrome(mystr): mystr = mystr.lower() mystr_char_list = [] for char in mystr:",
"did I live, said I, as evil I did deliver\")) print(palindrome(\"Go hang a",
"I live, said I, as evil I did deliver\")) print(palindrome(\"Go hang a salami;",
"as evil I did deliver\")) print(palindrome(\"Go hang a salami; I'm a lasagna hog.\"))",
"= mystr.lower() mystr_char_list = [] for char in mystr: if char in ascii_lowercase:",
"mystr.lower() mystr_char_list = [] for char in mystr: if char in ascii_lowercase: mystr_char_list.append(char)",
"takes a string as a parameter and returns True if the string is",
"0 or len(mystr_chars) == 1: return True else: if mystr_chars[0] == mystr_chars[-1]: return",
"\"\"\" Write a function that takes a string as a parameter and returns",
"evil I did deliver\")) print(palindrome(\"Go hang a salami; I'm a lasagna hog.\")) print(palindrome(\"Able",
"palindrome, False otherwise. \"\"\" from string import ascii_lowercase def palindrome(mystr): mystr = mystr.lower()",
"char in ascii_lowercase: mystr_char_list.append(char) mystr_chars = ''.join(mystr_char_list) if len(mystr_chars) == 0 or len(mystr_chars)",
"mystr_char_list.append(char) mystr_chars = ''.join(mystr_char_list) if len(mystr_chars) == 0 or len(mystr_chars) == 1: return",
"from string import ascii_lowercase def palindrome(mystr): mystr = mystr.lower() mystr_char_list = [] for",
"if char in ascii_lowercase: mystr_char_list.append(char) mystr_chars = ''.join(mystr_char_list) if len(mystr_chars) == 0 or",
"== mystr_chars[-1]: return palindrome(mystr_chars[1:len(mystr_chars) - 1]) else: return False def main(): print(palindrome(\"racecar\")) print(palindrome(\"kayak\"))",
"function that takes a string as a parameter and returns True if the",
"I, as evil I did deliver\")) print(palindrome(\"Go hang a salami; I'm a lasagna",
"== 1: return True else: if mystr_chars[0] == mystr_chars[-1]: return palindrome(mystr_chars[1:len(mystr_chars) - 1])",
"print(palindrome(\"Able was I ere I saw Elba\")) print(palindrome(\"Kanakanak\")) print(palindrome(\"Wassamassaw\")) if __name__ == \"__main__\":",
"did deliver\")) print(palindrome(\"Go hang a salami; I'm a lasagna hog.\")) print(palindrome(\"Able was I",
"print(palindrome(\"Reviled did I live, said I, as evil I did deliver\")) print(palindrome(\"Go hang",
"[] for char in mystr: if char in ascii_lowercase: mystr_char_list.append(char) mystr_chars = ''.join(mystr_char_list)",
"print(palindrome(\"Live not on evil\")) print(palindrome(\"aibohphobia\")) print(palindrome(\"Reviled did I live, said I, as evil",
"the string is a palindrome, False otherwise. \"\"\" from string import ascii_lowercase def",
"mystr_char_list = [] for char in mystr: if char in ascii_lowercase: mystr_char_list.append(char) mystr_chars",
"hang a salami; I'm a lasagna hog.\")) print(palindrome(\"Able was I ere I saw",
"else: return False def main(): print(palindrome(\"racecar\")) print(palindrome(\"kayak\")) print(palindrome(\"Live not on evil\")) print(palindrome(\"aibohphobia\")) print(palindrome(\"Reviled",
"string import ascii_lowercase def palindrome(mystr): mystr = mystr.lower() mystr_char_list = [] for char",
"a salami; I'm a lasagna hog.\")) print(palindrome(\"Able was I ere I saw Elba\"))",
"1]) else: return False def main(): print(palindrome(\"racecar\")) print(palindrome(\"kayak\")) print(palindrome(\"Live not on evil\")) print(palindrome(\"aibohphobia\"))",
"a palindrome, False otherwise. \"\"\" from string import ascii_lowercase def palindrome(mystr): mystr =",
"as a parameter and returns True if the string is a palindrome, False",
"1: return True else: if mystr_chars[0] == mystr_chars[-1]: return palindrome(mystr_chars[1:len(mystr_chars) - 1]) else:",
"mystr: if char in ascii_lowercase: mystr_char_list.append(char) mystr_chars = ''.join(mystr_char_list) if len(mystr_chars) == 0",
"print(palindrome(\"kayak\")) print(palindrome(\"Live not on evil\")) print(palindrome(\"aibohphobia\")) print(palindrome(\"Reviled did I live, said I, as",
"I did deliver\")) print(palindrome(\"Go hang a salami; I'm a lasagna hog.\")) print(palindrome(\"Able was",
"print(palindrome(\"Go hang a salami; I'm a lasagna hog.\")) print(palindrome(\"Able was I ere I",
"def main(): print(palindrome(\"racecar\")) print(palindrome(\"kayak\")) print(palindrome(\"Live not on evil\")) print(palindrome(\"aibohphobia\")) print(palindrome(\"Reviled did I live,",
"len(mystr_chars) == 1: return True else: if mystr_chars[0] == mystr_chars[-1]: return palindrome(mystr_chars[1:len(mystr_chars) -",
"return True else: if mystr_chars[0] == mystr_chars[-1]: return palindrome(mystr_chars[1:len(mystr_chars) - 1]) else: return",
"import ascii_lowercase def palindrome(mystr): mystr = mystr.lower() mystr_char_list = [] for char in",
"a lasagna hog.\")) print(palindrome(\"Able was I ere I saw Elba\")) print(palindrome(\"Kanakanak\")) print(palindrome(\"Wassamassaw\")) if",
"len(mystr_chars) == 0 or len(mystr_chars) == 1: return True else: if mystr_chars[0] ==",
"evil\")) print(palindrome(\"aibohphobia\")) print(palindrome(\"Reviled did I live, said I, as evil I did deliver\"))",
"or len(mystr_chars) == 1: return True else: if mystr_chars[0] == mystr_chars[-1]: return palindrome(mystr_chars[1:len(mystr_chars)",
"return palindrome(mystr_chars[1:len(mystr_chars) - 1]) else: return False def main(): print(palindrome(\"racecar\")) print(palindrome(\"kayak\")) print(palindrome(\"Live not",
"ascii_lowercase: mystr_char_list.append(char) mystr_chars = ''.join(mystr_char_list) if len(mystr_chars) == 0 or len(mystr_chars) == 1:",
"deliver\")) print(palindrome(\"Go hang a salami; I'm a lasagna hog.\")) print(palindrome(\"Able was I ere",
"== 0 or len(mystr_chars) == 1: return True else: if mystr_chars[0] == mystr_chars[-1]:",
"on evil\")) print(palindrome(\"aibohphobia\")) print(palindrome(\"Reviled did I live, said I, as evil I did",
"parameter and returns True if the string is a palindrome, False otherwise. \"\"\"",
"string as a parameter and returns True if the string is a palindrome,",
"def palindrome(mystr): mystr = mystr.lower() mystr_char_list = [] for char in mystr: if",
"main(): print(palindrome(\"racecar\")) print(palindrome(\"kayak\")) print(palindrome(\"Live not on evil\")) print(palindrome(\"aibohphobia\")) print(palindrome(\"Reviled did I live, said",
"that takes a string as a parameter and returns True if the string",
"if mystr_chars[0] == mystr_chars[-1]: return palindrome(mystr_chars[1:len(mystr_chars) - 1]) else: return False def main():",
"in ascii_lowercase: mystr_char_list.append(char) mystr_chars = ''.join(mystr_char_list) if len(mystr_chars) == 0 or len(mystr_chars) ==",
"mystr_chars[0] == mystr_chars[-1]: return palindrome(mystr_chars[1:len(mystr_chars) - 1]) else: return False def main(): print(palindrome(\"racecar\"))",
"else: if mystr_chars[0] == mystr_chars[-1]: return palindrome(mystr_chars[1:len(mystr_chars) - 1]) else: return False def"
] |
[
"from consensus.entities.ranking import Ranking class Member: @property def name(self): return self._name @property def",
"from typing import Sequence, Optional from consensus.entities.alternative import Alternative from consensus.entities.ranking import Ranking",
"@property def ranking(self) -> Ranking: return self._ranking def __init__(self, name: str): self._name =",
"__init__(self, name: str): self._name = name self._ranking: Optional[Ranking] = None def make_ranking(self, alternatives:",
"return self._name @property def ranking(self) -> Ranking: return self._ranking def __init__(self, name: str):",
"None def make_ranking(self, alternatives: Sequence[Alternative], ranking: Sequence[Sequence[str]], intensities=()): self._ranking = Ranking(alternatives, ranking, intensities)",
"= None def make_ranking(self, alternatives: Sequence[Alternative], ranking: Sequence[Sequence[str]], intensities=()): self._ranking = Ranking(alternatives, ranking,",
"= name self._ranking: Optional[Ranking] = None def make_ranking(self, alternatives: Sequence[Alternative], ranking: Sequence[Sequence[str]], intensities=()):",
"@property def name(self): return self._name @property def ranking(self) -> Ranking: return self._ranking def",
"self._name @property def ranking(self) -> Ranking: return self._ranking def __init__(self, name: str): self._name",
"Optional from consensus.entities.alternative import Alternative from consensus.entities.ranking import Ranking class Member: @property def",
"ranking(self) -> Ranking: return self._ranking def __init__(self, name: str): self._name = name self._ranking:",
"Ranking: return self._ranking def __init__(self, name: str): self._name = name self._ranking: Optional[Ranking] =",
"typing import Sequence, Optional from consensus.entities.alternative import Alternative from consensus.entities.ranking import Ranking class",
"Optional[Ranking] = None def make_ranking(self, alternatives: Sequence[Alternative], ranking: Sequence[Sequence[str]], intensities=()): self._ranking = Ranking(alternatives,",
"def ranking(self) -> Ranking: return self._ranking def __init__(self, name: str): self._name = name",
"self._ranking def __init__(self, name: str): self._name = name self._ranking: Optional[Ranking] = None def",
"import Sequence, Optional from consensus.entities.alternative import Alternative from consensus.entities.ranking import Ranking class Member:",
"-> Ranking: return self._ranking def __init__(self, name: str): self._name = name self._ranking: Optional[Ranking]",
"str): self._name = name self._ranking: Optional[Ranking] = None def make_ranking(self, alternatives: Sequence[Alternative], ranking:",
"Sequence, Optional from consensus.entities.alternative import Alternative from consensus.entities.ranking import Ranking class Member: @property",
"from consensus.entities.alternative import Alternative from consensus.entities.ranking import Ranking class Member: @property def name(self):",
"self._ranking: Optional[Ranking] = None def make_ranking(self, alternatives: Sequence[Alternative], ranking: Sequence[Sequence[str]], intensities=()): self._ranking =",
"consensus.entities.alternative import Alternative from consensus.entities.ranking import Ranking class Member: @property def name(self): return",
"import Alternative from consensus.entities.ranking import Ranking class Member: @property def name(self): return self._name",
"def name(self): return self._name @property def ranking(self) -> Ranking: return self._ranking def __init__(self,",
"def __init__(self, name: str): self._name = name self._ranking: Optional[Ranking] = None def make_ranking(self,",
"Member: @property def name(self): return self._name @property def ranking(self) -> Ranking: return self._ranking",
"Ranking class Member: @property def name(self): return self._name @property def ranking(self) -> Ranking:",
"consensus.entities.ranking import Ranking class Member: @property def name(self): return self._name @property def ranking(self)",
"class Member: @property def name(self): return self._name @property def ranking(self) -> Ranking: return",
"<gh_stars>0 from typing import Sequence, Optional from consensus.entities.alternative import Alternative from consensus.entities.ranking import",
"Alternative from consensus.entities.ranking import Ranking class Member: @property def name(self): return self._name @property",
"self._name = name self._ranking: Optional[Ranking] = None def make_ranking(self, alternatives: Sequence[Alternative], ranking: Sequence[Sequence[str]],",
"name(self): return self._name @property def ranking(self) -> Ranking: return self._ranking def __init__(self, name:",
"import Ranking class Member: @property def name(self): return self._name @property def ranking(self) ->",
"name self._ranking: Optional[Ranking] = None def make_ranking(self, alternatives: Sequence[Alternative], ranking: Sequence[Sequence[str]], intensities=()): self._ranking",
"return self._ranking def __init__(self, name: str): self._name = name self._ranking: Optional[Ranking] = None",
"name: str): self._name = name self._ranking: Optional[Ranking] = None def make_ranking(self, alternatives: Sequence[Alternative],"
] |
[
"= threshold self.denoise = denoise def process_file(self, infile: str, outfile: str) -> None:",
"PIL import Image from pipescaler.core import Processor, validate_image class ThresholdProcessor(Processor): \"\"\"Converts image to",
"as np from PIL import Image from pipescaler.core import Processor, validate_image class ThresholdProcessor(Processor):",
"output_data = np.array(output_image) self.denoise_data(output_data) output_image = Image.fromarray(output_data) output_image = output_image.convert(\"L\") # Write image",
"255 else: if (slc == 255).sum() < 4: data[y, x] = 0 if",
"(Any): Additional keyword arguments Returns: parser (ArgumentParser): Argument parser \"\"\" description = kwargs.pop(\"description\",",
"output_image = Image.fromarray(output_data) output_image = output_image.convert(\"L\") # Write image output_image.save(outfile) @classmethod def construct_argparser(cls,",
"argparse import ArgumentParser from inspect import cleandoc from typing import Any, no_type_check import",
"= kwargs.pop(\"description\", cleandoc(cls.__doc__)) parser = super().construct_argparser(description=description, **kwargs) parser.add_argument( \"--threshold\", default=128, type=int, help=\"threshold differentiating",
"nb import numpy as np from PIL import Image from pipescaler.core import Processor,",
"default: \" \"%(default)s)\", ) parser.add_argument( \"--denoise\", default=False, type=bool, help=\"Flip color of pixels bordered",
"+ 2, x - 1 : x + 2] if data[y, x] ==",
"keyword arguments Returns: parser (ArgumentParser): Argument parser \"\"\" description = kwargs.pop(\"description\", cleandoc(cls.__doc__)) parser",
"for x in range(1, data.shape[1] - 1): for y in range(1, data.shape[0] -",
"@no_type_check @staticmethod @nb.jit(nopython=True, nogil=True, cache=True, fastmath=True) def denoise_data(data: np.ndarray) -> None: for x",
"data[y - 1 : y + 2, x - 1 : x +",
"False, **kwargs: Any ) -> None: super().__init__(**kwargs) # Store configuration self.threshold = threshold",
"image output_image = input_image.point(lambda p: p > self.threshold and 255) if self.denoise: output_data",
"parser. Args: kwargs (Any): Additional keyword arguments Returns: parser (ArgumentParser): Argument parser \"\"\"",
"white using threshold, optionally denoising.\"\"\" def __init__( self, threshold: int = 128, denoise:",
"255) if self.denoise: output_data = np.array(output_image) self.denoise_data(output_data) output_image = Image.fromarray(output_data) output_image = output_image.convert(\"L\")",
"Process image output_image = input_image.point(lambda p: p > self.threshold and 255) if self.denoise:",
"Returns: parser (ArgumentParser): Argument parser \"\"\" description = kwargs.pop(\"description\", cleandoc(cls.__doc__)) parser = super().construct_argparser(description=description,",
"class ThresholdProcessor(Processor): \"\"\"Converts image to black and white using threshold, optionally denoising.\"\"\" def",
"optionally denoising.\"\"\" def __init__( self, threshold: int = 128, denoise: bool = False,",
"output_image.save(outfile) @classmethod def construct_argparser(cls, **kwargs: Any) -> ArgumentParser: \"\"\" Constructs argument parser. Args:",
"pixels of \" \"the same color\", ) return parser @no_type_check @staticmethod @nb.jit(nopython=True, nogil=True,",
"self.threshold = threshold self.denoise = denoise def process_file(self, infile: str, outfile: str) ->",
"of \" \"the same color\", ) return parser @no_type_check @staticmethod @nb.jit(nopython=True, nogil=True, cache=True,",
"y + 2, x - 1 : x + 2] if data[y, x]",
"fastmath=True) def denoise_data(data: np.ndarray) -> None: for x in range(1, data.shape[1] - 1):",
"# Process image output_image = input_image.point(lambda p: p > self.threshold and 255) if",
"parser = super().construct_argparser(description=description, **kwargs) parser.add_argument( \"--threshold\", default=128, type=int, help=\"threshold differentiating black and white",
"x - 1 : x + 2] if data[y, x] == 0: if",
"same color\", ) return parser @no_type_check @staticmethod @nb.jit(nopython=True, nogil=True, cache=True, fastmath=True) def denoise_data(data:",
"# This software may be modified and distributed under the terms of the",
"+ 2] if data[y, x] == 0: if (slc == 0).sum() < 4:",
"no_type_check import numba as nb import numpy as np from PIL import Image",
"description = kwargs.pop(\"description\", cleandoc(cls.__doc__)) parser = super().construct_argparser(description=description, **kwargs) parser.add_argument( \"--threshold\", default=128, type=int, help=\"threshold",
"kwargs.pop(\"description\", cleandoc(cls.__doc__)) parser = super().construct_argparser(description=description, **kwargs) parser.add_argument( \"--threshold\", default=128, type=int, help=\"threshold differentiating black",
"and white using threshold, optionally denoising.\"\"\" def __init__( self, threshold: int = 128,",
"parser \"\"\" description = kwargs.pop(\"description\", cleandoc(cls.__doc__)) parser = super().construct_argparser(description=description, **kwargs) parser.add_argument( \"--threshold\", default=128,",
"slc = data[y - 1 : y + 2, x - 1 :",
"(0-255, default: \" \"%(default)s)\", ) parser.add_argument( \"--denoise\", default=False, type=bool, help=\"Flip color of pixels",
"1 : y + 2, x - 1 : x + 2] if",
"# Write image output_image.save(outfile) @classmethod def construct_argparser(cls, **kwargs: Any) -> ArgumentParser: \"\"\" Constructs",
"str, outfile: str) -> None: # Read image input_image = validate_image(infile, \"L\") #",
"== 0).sum() < 4: data[y, x] = 255 else: if (slc == 255).sum()",
"self.denoise = denoise def process_file(self, infile: str, outfile: str) -> None: # Read",
"\"L\") # Process image output_image = input_image.point(lambda p: p > self.threshold and 255)",
"ArgumentParser: \"\"\" Constructs argument parser. Args: kwargs (Any): Additional keyword arguments Returns: parser",
"numpy as np from PIL import Image from pipescaler.core import Processor, validate_image class",
"from __future__ import annotations from argparse import ArgumentParser from inspect import cleandoc from",
"of pixels bordered by less than 5 pixels of \" \"the same color\",",
"1 : x + 2] if data[y, x] == 0: if (slc ==",
"using threshold, optionally denoising.\"\"\" def __init__( self, threshold: int = 128, denoise: bool",
"= data[y - 1 : y + 2, x - 1 : x",
"from pipescaler.core import Processor, validate_image class ThresholdProcessor(Processor): \"\"\"Converts image to black and white",
"- 1): slc = data[y - 1 : y + 2, x -",
"threshold, optionally denoising.\"\"\" def __init__( self, threshold: int = 128, denoise: bool =",
"denoising.\"\"\" def __init__( self, threshold: int = 128, denoise: bool = False, **kwargs:",
"4: data[y, x] = 255 else: if (slc == 255).sum() < 4: data[y,",
"cache=True, fastmath=True) def denoise_data(data: np.ndarray) -> None: for x in range(1, data.shape[1] -",
"# All rights reserved. # # This software may be modified and distributed",
"in range(1, data.shape[1] - 1): for y in range(1, data.shape[0] - 1): slc",
") -> None: super().__init__(**kwargs) # Store configuration self.threshold = threshold self.denoise = denoise",
"#!/usr/bin/env python # pipescaler/processors/threshold_processor.py # # Copyright (C) 2020-2021 <NAME> # All rights",
"license. from __future__ import annotations from argparse import ArgumentParser from inspect import cleandoc",
"threshold: int = 128, denoise: bool = False, **kwargs: Any ) -> None:",
"def process_file(self, infile: str, outfile: str) -> None: # Read image input_image =",
"typing import Any, no_type_check import numba as nb import numpy as np from",
"self.threshold and 255) if self.denoise: output_data = np.array(output_image) self.denoise_data(output_data) output_image = Image.fromarray(output_data) output_image",
"int = 128, denoise: bool = False, **kwargs: Any ) -> None: super().__init__(**kwargs)",
"< 4: data[y, x] = 255 else: if (slc == 255).sum() < 4:",
"pipescaler/processors/threshold_processor.py # # Copyright (C) 2020-2021 <NAME> # All rights reserved. # #",
"parser @no_type_check @staticmethod @nb.jit(nopython=True, nogil=True, cache=True, fastmath=True) def denoise_data(data: np.ndarray) -> None: for",
"# # This software may be modified and distributed under the terms of",
"if (slc == 255).sum() < 4: data[y, x] = 0 if __name__ ==",
"from PIL import Image from pipescaler.core import Processor, validate_image class ThresholdProcessor(Processor): \"\"\"Converts image",
"threshold self.denoise = denoise def process_file(self, infile: str, outfile: str) -> None: #",
"cleandoc(cls.__doc__)) parser = super().construct_argparser(description=description, **kwargs) parser.add_argument( \"--threshold\", default=128, type=int, help=\"threshold differentiating black and",
"2, x - 1 : x + 2] if data[y, x] == 0:",
"else: if (slc == 255).sum() < 4: data[y, x] = 0 if __name__",
"image to black and white using threshold, optionally denoising.\"\"\" def __init__( self, threshold:",
"@nb.jit(nopython=True, nogil=True, cache=True, fastmath=True) def denoise_data(data: np.ndarray) -> None: for x in range(1,",
"default=128, type=int, help=\"threshold differentiating black and white (0-255, default: \" \"%(default)s)\", ) parser.add_argument(",
"output_image = output_image.convert(\"L\") # Write image output_image.save(outfile) @classmethod def construct_argparser(cls, **kwargs: Any) ->",
"black and white (0-255, default: \" \"%(default)s)\", ) parser.add_argument( \"--denoise\", default=False, type=bool, help=\"Flip",
"default=False, type=bool, help=\"Flip color of pixels bordered by less than 5 pixels of",
"__init__( self, threshold: int = 128, denoise: bool = False, **kwargs: Any )",
"# Copyright (C) 2020-2021 <NAME> # All rights reserved. # # This software",
"self.denoise_data(output_data) output_image = Image.fromarray(output_data) output_image = output_image.convert(\"L\") # Write image output_image.save(outfile) @classmethod def",
": x + 2] if data[y, x] == 0: if (slc == 0).sum()",
"**kwargs: Any ) -> None: super().__init__(**kwargs) # Store configuration self.threshold = threshold self.denoise",
"= False, **kwargs: Any ) -> None: super().__init__(**kwargs) # Store configuration self.threshold =",
"Any ) -> None: super().__init__(**kwargs) # Store configuration self.threshold = threshold self.denoise =",
"# pipescaler/processors/threshold_processor.py # # Copyright (C) 2020-2021 <NAME> # All rights reserved. #",
"# Store configuration self.threshold = threshold self.denoise = denoise def process_file(self, infile: str,",
"image input_image = validate_image(infile, \"L\") # Process image output_image = input_image.point(lambda p: p",
"Args: kwargs (Any): Additional keyword arguments Returns: parser (ArgumentParser): Argument parser \"\"\" description",
"be modified and distributed under the terms of the # BSD license. from",
"rights reserved. # # This software may be modified and distributed under the",
"software may be modified and distributed under the terms of the # BSD",
"import Any, no_type_check import numba as nb import numpy as np from PIL",
"def construct_argparser(cls, **kwargs: Any) -> ArgumentParser: \"\"\" Constructs argument parser. Args: kwargs (Any):",
"None: super().__init__(**kwargs) # Store configuration self.threshold = threshold self.denoise = denoise def process_file(self,",
"BSD license. from __future__ import annotations from argparse import ArgumentParser from inspect import",
"data.shape[1] - 1): for y in range(1, data.shape[0] - 1): slc = data[y",
"Store configuration self.threshold = threshold self.denoise = denoise def process_file(self, infile: str, outfile:",
"parser (ArgumentParser): Argument parser \"\"\" description = kwargs.pop(\"description\", cleandoc(cls.__doc__)) parser = super().construct_argparser(description=description, **kwargs)",
"than 5 pixels of \" \"the same color\", ) return parser @no_type_check @staticmethod",
"validate_image(infile, \"L\") # Process image output_image = input_image.point(lambda p: p > self.threshold and",
"white (0-255, default: \" \"%(default)s)\", ) parser.add_argument( \"--denoise\", default=False, type=bool, help=\"Flip color of",
"output_image = input_image.point(lambda p: p > self.threshold and 255) if self.denoise: output_data =",
"- 1 : x + 2] if data[y, x] == 0: if (slc",
"= Image.fromarray(output_data) output_image = output_image.convert(\"L\") # Write image output_image.save(outfile) @classmethod def construct_argparser(cls, **kwargs:",
"arguments Returns: parser (ArgumentParser): Argument parser \"\"\" description = kwargs.pop(\"description\", cleandoc(cls.__doc__)) parser =",
"-> None: # Read image input_image = validate_image(infile, \"L\") # Process image output_image",
"\"--denoise\", default=False, type=bool, help=\"Flip color of pixels bordered by less than 5 pixels",
"str) -> None: # Read image input_image = validate_image(infile, \"L\") # Process image",
"\" \"the same color\", ) return parser @no_type_check @staticmethod @nb.jit(nopython=True, nogil=True, cache=True, fastmath=True)",
"0: if (slc == 0).sum() < 4: data[y, x] = 255 else: if",
"(slc == 0).sum() < 4: data[y, x] = 255 else: if (slc ==",
"np.ndarray) -> None: for x in range(1, data.shape[1] - 1): for y in",
"import ArgumentParser from inspect import cleandoc from typing import Any, no_type_check import numba",
"as nb import numpy as np from PIL import Image from pipescaler.core import",
"import Image from pipescaler.core import Processor, validate_image class ThresholdProcessor(Processor): \"\"\"Converts image to black",
"denoise def process_file(self, infile: str, outfile: str) -> None: # Read image input_image",
"None: # Read image input_image = validate_image(infile, \"L\") # Process image output_image =",
"denoise: bool = False, **kwargs: Any ) -> None: super().__init__(**kwargs) # Store configuration",
"import numba as nb import numpy as np from PIL import Image from",
"== 0: if (slc == 0).sum() < 4: data[y, x] = 255 else:",
"super().construct_argparser(description=description, **kwargs) parser.add_argument( \"--threshold\", default=128, type=int, help=\"threshold differentiating black and white (0-255, default:",
"\"\"\"Converts image to black and white using threshold, optionally denoising.\"\"\" def __init__( self,",
"differentiating black and white (0-255, default: \" \"%(default)s)\", ) parser.add_argument( \"--denoise\", default=False, type=bool,",
"from typing import Any, no_type_check import numba as nb import numpy as np",
"All rights reserved. # # This software may be modified and distributed under",
"\"the same color\", ) return parser @no_type_check @staticmethod @nb.jit(nopython=True, nogil=True, cache=True, fastmath=True) def",
"image output_image.save(outfile) @classmethod def construct_argparser(cls, **kwargs: Any) -> ArgumentParser: \"\"\" Constructs argument parser.",
"import numpy as np from PIL import Image from pipescaler.core import Processor, validate_image",
"output_image.convert(\"L\") # Write image output_image.save(outfile) @classmethod def construct_argparser(cls, **kwargs: Any) -> ArgumentParser: \"\"\"",
"-> ArgumentParser: \"\"\" Constructs argument parser. Args: kwargs (Any): Additional keyword arguments Returns:",
"validate_image class ThresholdProcessor(Processor): \"\"\"Converts image to black and white using threshold, optionally denoising.\"\"\"",
"kwargs (Any): Additional keyword arguments Returns: parser (ArgumentParser): Argument parser \"\"\" description =",
"import annotations from argparse import ArgumentParser from inspect import cleandoc from typing import",
"super().__init__(**kwargs) # Store configuration self.threshold = threshold self.denoise = denoise def process_file(self, infile:",
"This software may be modified and distributed under the terms of the #",
"Any) -> ArgumentParser: \"\"\" Constructs argument parser. Args: kwargs (Any): Additional keyword arguments",
"(slc == 255).sum() < 4: data[y, x] = 0 if __name__ == \"__main__\":",
"== 255).sum() < 4: data[y, x] = 0 if __name__ == \"__main__\": ThresholdProcessor.main()",
"self.denoise: output_data = np.array(output_image) self.denoise_data(output_data) output_image = Image.fromarray(output_data) output_image = output_image.convert(\"L\") # Write",
"input_image.point(lambda p: p > self.threshold and 255) if self.denoise: output_data = np.array(output_image) self.denoise_data(output_data)",
"-> None: for x in range(1, data.shape[1] - 1): for y in range(1,",
"the terms of the # BSD license. from __future__ import annotations from argparse",
"from argparse import ArgumentParser from inspect import cleandoc from typing import Any, no_type_check",
"\"--threshold\", default=128, type=int, help=\"threshold differentiating black and white (0-255, default: \" \"%(default)s)\", )",
"data[y, x] = 255 else: if (slc == 255).sum() < 4: data[y, x]",
"if self.denoise: output_data = np.array(output_image) self.denoise_data(output_data) output_image = Image.fromarray(output_data) output_image = output_image.convert(\"L\") #",
"terms of the # BSD license. from __future__ import annotations from argparse import",
"= 128, denoise: bool = False, **kwargs: Any ) -> None: super().__init__(**kwargs) #",
"128, denoise: bool = False, **kwargs: Any ) -> None: super().__init__(**kwargs) # Store",
"\" \"%(default)s)\", ) parser.add_argument( \"--denoise\", default=False, type=bool, help=\"Flip color of pixels bordered by",
"= 255 else: if (slc == 255).sum() < 4: data[y, x] = 0",
"1): slc = data[y - 1 : y + 2, x - 1",
"<reponame>KarlTDebiec/PipeScaler<gh_stars>1-10 #!/usr/bin/env python # pipescaler/processors/threshold_processor.py # # Copyright (C) 2020-2021 <NAME> # All",
"@classmethod def construct_argparser(cls, **kwargs: Any) -> ArgumentParser: \"\"\" Constructs argument parser. Args: kwargs",
"-> None: super().__init__(**kwargs) # Store configuration self.threshold = threshold self.denoise = denoise def",
"def __init__( self, threshold: int = 128, denoise: bool = False, **kwargs: Any",
"x] == 0: if (slc == 0).sum() < 4: data[y, x] = 255",
"color of pixels bordered by less than 5 pixels of \" \"the same",
"reserved. # # This software may be modified and distributed under the terms",
"**kwargs) parser.add_argument( \"--threshold\", default=128, type=int, help=\"threshold differentiating black and white (0-255, default: \"",
"and distributed under the terms of the # BSD license. from __future__ import",
"if (slc == 0).sum() < 4: data[y, x] = 255 else: if (slc",
"data[y, x] == 0: if (slc == 0).sum() < 4: data[y, x] =",
"parser.add_argument( \"--denoise\", default=False, type=bool, help=\"Flip color of pixels bordered by less than 5",
"= denoise def process_file(self, infile: str, outfile: str) -> None: # Read image",
"input_image = validate_image(infile, \"L\") # Process image output_image = input_image.point(lambda p: p >",
"by less than 5 pixels of \" \"the same color\", ) return parser",
"and 255) if self.denoise: output_data = np.array(output_image) self.denoise_data(output_data) output_image = Image.fromarray(output_data) output_image =",
") parser.add_argument( \"--denoise\", default=False, type=bool, help=\"Flip color of pixels bordered by less than",
"5 pixels of \" \"the same color\", ) return parser @no_type_check @staticmethod @nb.jit(nopython=True,",
"Image from pipescaler.core import Processor, validate_image class ThresholdProcessor(Processor): \"\"\"Converts image to black and",
"= input_image.point(lambda p: p > self.threshold and 255) if self.denoise: output_data = np.array(output_image)",
"2] if data[y, x] == 0: if (slc == 0).sum() < 4: data[y,",
"= np.array(output_image) self.denoise_data(output_data) output_image = Image.fromarray(output_data) output_image = output_image.convert(\"L\") # Write image output_image.save(outfile)",
"np from PIL import Image from pipescaler.core import Processor, validate_image class ThresholdProcessor(Processor): \"\"\"Converts",
"(ArgumentParser): Argument parser \"\"\" description = kwargs.pop(\"description\", cleandoc(cls.__doc__)) parser = super().construct_argparser(description=description, **kwargs) parser.add_argument(",
"ArgumentParser from inspect import cleandoc from typing import Any, no_type_check import numba as",
"help=\"Flip color of pixels bordered by less than 5 pixels of \" \"the",
"= validate_image(infile, \"L\") # Process image output_image = input_image.point(lambda p: p > self.threshold",
"2020-2021 <NAME> # All rights reserved. # # This software may be modified",
"the # BSD license. from __future__ import annotations from argparse import ArgumentParser from",
"argument parser. Args: kwargs (Any): Additional keyword arguments Returns: parser (ArgumentParser): Argument parser",
") return parser @no_type_check @staticmethod @nb.jit(nopython=True, nogil=True, cache=True, fastmath=True) def denoise_data(data: np.ndarray) ->",
"Additional keyword arguments Returns: parser (ArgumentParser): Argument parser \"\"\" description = kwargs.pop(\"description\", cleandoc(cls.__doc__))",
": y + 2, x - 1 : x + 2] if data[y,",
"distributed under the terms of the # BSD license. from __future__ import annotations",
"infile: str, outfile: str) -> None: # Read image input_image = validate_image(infile, \"L\")",
"Image.fromarray(output_data) output_image = output_image.convert(\"L\") # Write image output_image.save(outfile) @classmethod def construct_argparser(cls, **kwargs: Any)",
"and white (0-255, default: \" \"%(default)s)\", ) parser.add_argument( \"--denoise\", default=False, type=bool, help=\"Flip color",
"help=\"threshold differentiating black and white (0-255, default: \" \"%(default)s)\", ) parser.add_argument( \"--denoise\", default=False,",
"def denoise_data(data: np.ndarray) -> None: for x in range(1, data.shape[1] - 1): for",
"denoise_data(data: np.ndarray) -> None: for x in range(1, data.shape[1] - 1): for y",
"**kwargs: Any) -> ArgumentParser: \"\"\" Constructs argument parser. Args: kwargs (Any): Additional keyword",
"Constructs argument parser. Args: kwargs (Any): Additional keyword arguments Returns: parser (ArgumentParser): Argument",
"> self.threshold and 255) if self.denoise: output_data = np.array(output_image) self.denoise_data(output_data) output_image = Image.fromarray(output_data)",
"parser.add_argument( \"--threshold\", default=128, type=int, help=\"threshold differentiating black and white (0-255, default: \" \"%(default)s)\",",
"x in range(1, data.shape[1] - 1): for y in range(1, data.shape[0] - 1):",
"1): for y in range(1, data.shape[0] - 1): slc = data[y - 1",
"python # pipescaler/processors/threshold_processor.py # # Copyright (C) 2020-2021 <NAME> # All rights reserved.",
"black and white using threshold, optionally denoising.\"\"\" def __init__( self, threshold: int =",
"= output_image.convert(\"L\") # Write image output_image.save(outfile) @classmethod def construct_argparser(cls, **kwargs: Any) -> ArgumentParser:",
"return parser @no_type_check @staticmethod @nb.jit(nopython=True, nogil=True, cache=True, fastmath=True) def denoise_data(data: np.ndarray) -> None:",
"range(1, data.shape[0] - 1): slc = data[y - 1 : y + 2,",
"under the terms of the # BSD license. from __future__ import annotations from",
"ThresholdProcessor(Processor): \"\"\"Converts image to black and white using threshold, optionally denoising.\"\"\" def __init__(",
"pipescaler.core import Processor, validate_image class ThresholdProcessor(Processor): \"\"\"Converts image to black and white using",
"None: for x in range(1, data.shape[1] - 1): for y in range(1, data.shape[0]",
"of the # BSD license. from __future__ import annotations from argparse import ArgumentParser",
"# # Copyright (C) 2020-2021 <NAME> # All rights reserved. # # This",
"Write image output_image.save(outfile) @classmethod def construct_argparser(cls, **kwargs: Any) -> ArgumentParser: \"\"\" Constructs argument",
"may be modified and distributed under the terms of the # BSD license.",
"modified and distributed under the terms of the # BSD license. from __future__",
"process_file(self, infile: str, outfile: str) -> None: # Read image input_image = validate_image(infile,",
"y in range(1, data.shape[0] - 1): slc = data[y - 1 : y",
"inspect import cleandoc from typing import Any, no_type_check import numba as nb import",
"x] = 255 else: if (slc == 255).sum() < 4: data[y, x] =",
"data.shape[0] - 1): slc = data[y - 1 : y + 2, x",
"outfile: str) -> None: # Read image input_image = validate_image(infile, \"L\") # Process",
"p > self.threshold and 255) if self.denoise: output_data = np.array(output_image) self.denoise_data(output_data) output_image =",
"range(1, data.shape[1] - 1): for y in range(1, data.shape[0] - 1): slc =",
"nogil=True, cache=True, fastmath=True) def denoise_data(data: np.ndarray) -> None: for x in range(1, data.shape[1]",
"cleandoc from typing import Any, no_type_check import numba as nb import numpy as",
"configuration self.threshold = threshold self.denoise = denoise def process_file(self, infile: str, outfile: str)",
"__future__ import annotations from argparse import ArgumentParser from inspect import cleandoc from typing",
"for y in range(1, data.shape[0] - 1): slc = data[y - 1 :",
"numba as nb import numpy as np from PIL import Image from pipescaler.core",
"\"\"\" description = kwargs.pop(\"description\", cleandoc(cls.__doc__)) parser = super().construct_argparser(description=description, **kwargs) parser.add_argument( \"--threshold\", default=128, type=int,",
"import Processor, validate_image class ThresholdProcessor(Processor): \"\"\"Converts image to black and white using threshold,",
"\"%(default)s)\", ) parser.add_argument( \"--denoise\", default=False, type=bool, help=\"Flip color of pixels bordered by less",
"pixels bordered by less than 5 pixels of \" \"the same color\", )",
"Any, no_type_check import numba as nb import numpy as np from PIL import",
"- 1): for y in range(1, data.shape[0] - 1): slc = data[y -",
"= super().construct_argparser(description=description, **kwargs) parser.add_argument( \"--threshold\", default=128, type=int, help=\"threshold differentiating black and white (0-255,",
"- 1 : y + 2, x - 1 : x + 2]",
"0).sum() < 4: data[y, x] = 255 else: if (slc == 255).sum() <",
"# Read image input_image = validate_image(infile, \"L\") # Process image output_image = input_image.point(lambda",
"Copyright (C) 2020-2021 <NAME> # All rights reserved. # # This software may",
"Processor, validate_image class ThresholdProcessor(Processor): \"\"\"Converts image to black and white using threshold, optionally",
"<NAME> # All rights reserved. # # This software may be modified and",
"p: p > self.threshold and 255) if self.denoise: output_data = np.array(output_image) self.denoise_data(output_data) output_image",
"np.array(output_image) self.denoise_data(output_data) output_image = Image.fromarray(output_data) output_image = output_image.convert(\"L\") # Write image output_image.save(outfile) @classmethod",
"bordered by less than 5 pixels of \" \"the same color\", ) return",
"# BSD license. from __future__ import annotations from argparse import ArgumentParser from inspect",
"color\", ) return parser @no_type_check @staticmethod @nb.jit(nopython=True, nogil=True, cache=True, fastmath=True) def denoise_data(data: np.ndarray)",
"from inspect import cleandoc from typing import Any, no_type_check import numba as nb",
"type=int, help=\"threshold differentiating black and white (0-255, default: \" \"%(default)s)\", ) parser.add_argument( \"--denoise\",",
"to black and white using threshold, optionally denoising.\"\"\" def __init__( self, threshold: int",
"bool = False, **kwargs: Any ) -> None: super().__init__(**kwargs) # Store configuration self.threshold",
"@staticmethod @nb.jit(nopython=True, nogil=True, cache=True, fastmath=True) def denoise_data(data: np.ndarray) -> None: for x in",
"\"\"\" Constructs argument parser. Args: kwargs (Any): Additional keyword arguments Returns: parser (ArgumentParser):",
"Argument parser \"\"\" description = kwargs.pop(\"description\", cleandoc(cls.__doc__)) parser = super().construct_argparser(description=description, **kwargs) parser.add_argument( \"--threshold\",",
"x + 2] if data[y, x] == 0: if (slc == 0).sum() <",
"annotations from argparse import ArgumentParser from inspect import cleandoc from typing import Any,",
"in range(1, data.shape[0] - 1): slc = data[y - 1 : y +",
"type=bool, help=\"Flip color of pixels bordered by less than 5 pixels of \"",
"import cleandoc from typing import Any, no_type_check import numba as nb import numpy",
"construct_argparser(cls, **kwargs: Any) -> ArgumentParser: \"\"\" Constructs argument parser. Args: kwargs (Any): Additional",
"if data[y, x] == 0: if (slc == 0).sum() < 4: data[y, x]",
"Read image input_image = validate_image(infile, \"L\") # Process image output_image = input_image.point(lambda p:",
"less than 5 pixels of \" \"the same color\", ) return parser @no_type_check",
"self, threshold: int = 128, denoise: bool = False, **kwargs: Any ) ->",
"(C) 2020-2021 <NAME> # All rights reserved. # # This software may be"
] |
[
"Getting arcs for _ in range(m): spoon = input().strip() v, u = spoon.split('",
"_ in range(m): spoon = input().strip() v, u = spoon.split(' ') v, u",
"v, u = spoon.split(' ') v, u = int(v), int(u) grafo.add_edge(v, u) #",
"Getting number of nodes if spoon[:len(\"# number of nodes:\")] == \"# number of",
"istruzioni dal servizio while spoon[:len(\"# Tell me\")] != \"# Tell me\": spoon =",
"# Getting response spoon = input().strip() while spoon != \"#end\".strip(): print(spoon) sys.stderr.write(str(spoon)+ \"\\n\")",
"Telling sp tree length print(len(input_spTree)) #printing sp tree for i in range(len(input_spTree)): u,",
"number of arcs: \": m = spoon.split(':')[1] m = int(\"\".join(m.split())) spoon = input().strip()",
"= input().strip() # Checking spanning tree input_spTree, not_visited = grafo.spanning_tree() # Telling sp",
"input().strip() while spoon != \"#end\".strip(): print(spoon) sys.stderr.write(str(spoon)+ \"\\n\") spoon = input().strip() # Main",
"graph_connectivity_lib as gcl def startAlgo(): numNodes = None spoon = input().strip() # Getting",
"startAlgo(): numNodes = None spoon = input().strip() # Getting graph while spoon[:len(\"graph:\")] !=",
"length print(len(input_spTree)) #printing sp tree for i in range(len(input_spTree)): u, v = input_spTree[i]",
"v = input_spTree[i] print(f\"{u} {v}\") # Getting response spoon = input().strip() while spoon",
"spoon = input().strip() v, u = spoon.split(' ') v, u = int(v), int(u)",
"nodes if spoon[:len(\"# number of nodes:\")] == \"# number of nodes:\": numNodes =",
"range(len(input_spTree)): u, v = input_spTree[i] print(f\"{u} {v}\") # Getting response spoon = input().strip()",
"= input().strip() # Main spoon = input().strip() while spoon[:len(\"#start\")] != \"#start\": spoon =",
"of arcs: \": m = spoon.split(':')[1] m = int(\"\".join(m.split())) spoon = input().strip() #",
"arcs: \")] == \"# number of arcs: \": m = spoon.split(':')[1] m =",
"input_spTree, not_visited = grafo.spanning_tree() # Telling sp tree length print(len(input_spTree)) #printing sp tree",
"spoon[:len(\"# number of nodes:\")] == \"# number of nodes:\": numNodes = spoon.split(':')[1] numNodes",
"# Getting number archs if spoon[:len(\"# number of arcs: \")] == \"# number",
"= spoon.split(':')[1] numNodes = int(\"\".join(numNodes.split())) # Getting number archs if spoon[:len(\"# number of",
"{v}\") # Getting response spoon = input().strip() while spoon != \"#end\".strip(): print(spoon) sys.stderr.write(str(spoon)+",
"= None spoon = input().strip() # Getting graph while spoon[:len(\"graph:\")] != \"graph:\": #",
"Main spoon = input().strip() while spoon[:len(\"#start\")] != \"#start\": spoon = input().strip() # Reading",
"numNodes = None spoon = input().strip() # Getting graph while spoon[:len(\"graph:\")] != \"graph:\":",
"\"#end\".strip(): print(spoon) sys.stderr.write(str(spoon)+ \"\\n\") spoon = input().strip() # Main spoon = input().strip() while",
"from sys import stderr, exit import sys import graph_connectivity_lib as gcl def startAlgo():",
"while spoon != \"#end\".strip(): print(spoon) sys.stderr.write(str(spoon)+ \"\\n\") spoon = input().strip() # Main spoon",
"exit import sys import graph_connectivity_lib as gcl def startAlgo(): numNodes = None spoon",
"arcs for _ in range(m): spoon = input().strip() v, u = spoon.split(' ')",
"m = spoon.split(':')[1] m = int(\"\".join(m.split())) spoon = input().strip() # Creating graph grafo",
"while spoon[:len(\"graph:\")] != \"graph:\": # Getting number of nodes if spoon[:len(\"# number of",
"me\": spoon = input().strip() # Checking spanning tree input_spTree, not_visited = grafo.spanning_tree() #",
"gcl def startAlgo(): numNodes = None spoon = input().strip() # Getting graph while",
"of nodes:\")] == \"# number of nodes:\": numNodes = spoon.split(':')[1] numNodes = int(\"\".join(numNodes.split()))",
"sp tree for i in range(len(input_spTree)): u, v = input_spTree[i] print(f\"{u} {v}\") #",
"# Main spoon = input().strip() while spoon[:len(\"#start\")] != \"#start\": spoon = input().strip() #",
"graph grafo = gcl.Graph(numNodes) # Getting arcs for _ in range(m): spoon =",
"= gcl.Graph(numNodes) # Getting arcs for _ in range(m): spoon = input().strip() v,",
"import sys import graph_connectivity_lib as gcl def startAlgo(): numNodes = None spoon =",
"def startAlgo(): numNodes = None spoon = input().strip() # Getting graph while spoon[:len(\"graph:\")]",
"== \"# number of nodes:\": numNodes = spoon.split(':')[1] numNodes = int(\"\".join(numNodes.split())) # Getting",
"Getting number archs if spoon[:len(\"# number of arcs: \")] == \"# number of",
"= grafo.spanning_tree() # Telling sp tree length print(len(input_spTree)) #printing sp tree for i",
"# Getting number of nodes if spoon[:len(\"# number of nodes:\")] == \"# number",
"= spoon.split(':')[1] m = int(\"\".join(m.split())) spoon = input().strip() # Creating graph grafo =",
"u) # Ricevo istruzioni dal servizio while spoon[:len(\"# Tell me\")] != \"# Tell",
"# Telling sp tree length print(len(input_spTree)) #printing sp tree for i in range(len(input_spTree)):",
"spoon = input().strip() # Getting graph while spoon[:len(\"graph:\")] != \"graph:\": # Getting number",
"= input_spTree[i] print(f\"{u} {v}\") # Getting response spoon = input().strip() while spoon !=",
"graph while spoon[:len(\"graph:\")] != \"graph:\": # Getting number of nodes if spoon[:len(\"# number",
"#!/usr/bin/env python3 from sys import stderr, exit import sys import graph_connectivity_lib as gcl",
"input().strip() # Getting graph while spoon[:len(\"graph:\")] != \"graph:\": # Getting number of nodes",
"numNodes = spoon.split(':')[1] numNodes = int(\"\".join(numNodes.split())) # Getting number archs if spoon[:len(\"# number",
"int(\"\".join(numNodes.split())) # Getting number archs if spoon[:len(\"# number of arcs: \")] == \"#",
"Ricevo istruzioni dal servizio while spoon[:len(\"# Tell me\")] != \"# Tell me\": spoon",
"while spoon[:len(\"# Tell me\")] != \"# Tell me\": spoon = input().strip() # Checking",
"u = int(v), int(u) grafo.add_edge(v, u) # Ricevo istruzioni dal servizio while spoon[:len(\"#",
"print(len(input_spTree)) #printing sp tree for i in range(len(input_spTree)): u, v = input_spTree[i] print(f\"{u}",
"input().strip() # Main spoon = input().strip() while spoon[:len(\"#start\")] != \"#start\": spoon = input().strip()",
"Tell me\")] != \"# Tell me\": spoon = input().strip() # Checking spanning tree",
"grafo.spanning_tree() # Telling sp tree length print(len(input_spTree)) #printing sp tree for i in",
"number of nodes:\": numNodes = spoon.split(':')[1] numNodes = int(\"\".join(numNodes.split())) # Getting number archs",
"stderr, exit import sys import graph_connectivity_lib as gcl def startAlgo(): numNodes = None",
"== \"# number of arcs: \": m = spoon.split(':')[1] m = int(\"\".join(m.split())) spoon",
"int(\"\".join(m.split())) spoon = input().strip() # Creating graph grafo = gcl.Graph(numNodes) # Getting arcs",
"in range(len(input_spTree)): u, v = input_spTree[i] print(f\"{u} {v}\") # Getting response spoon =",
"Tell me\": spoon = input().strip() # Checking spanning tree input_spTree, not_visited = grafo.spanning_tree()",
"sp tree length print(len(input_spTree)) #printing sp tree for i in range(len(input_spTree)): u, v",
"\"graph:\": # Getting number of nodes if spoon[:len(\"# number of nodes:\")] == \"#",
"for i in range(len(input_spTree)): u, v = input_spTree[i] print(f\"{u} {v}\") # Getting response",
"Getting response spoon = input().strip() while spoon != \"#end\".strip(): print(spoon) sys.stderr.write(str(spoon)+ \"\\n\") spoon",
"= spoon.split(' ') v, u = int(v), int(u) grafo.add_edge(v, u) # Ricevo istruzioni",
"= int(\"\".join(m.split())) spoon = input().strip() # Creating graph grafo = gcl.Graph(numNodes) # Getting",
"sys import graph_connectivity_lib as gcl def startAlgo(): numNodes = None spoon = input().strip()",
"input().strip() v, u = spoon.split(' ') v, u = int(v), int(u) grafo.add_edge(v, u)",
"spoon != \"#end\".strip(): print(spoon) sys.stderr.write(str(spoon)+ \"\\n\") spoon = input().strip() # Main spoon =",
"\"\\n\") spoon = input().strip() # Main spoon = input().strip() while spoon[:len(\"#start\")] != \"#start\":",
"\"# Tell me\": spoon = input().strip() # Checking spanning tree input_spTree, not_visited =",
"of nodes if spoon[:len(\"# number of nodes:\")] == \"# number of nodes:\": numNodes",
"arcs: \": m = spoon.split(':')[1] m = int(\"\".join(m.split())) spoon = input().strip() # Creating",
"i in range(len(input_spTree)): u, v = input_spTree[i] print(f\"{u} {v}\") # Getting response spoon",
"input().strip() while spoon[:len(\"#start\")] != \"#start\": spoon = input().strip() # Reading the graph startAlgo()",
"number of nodes:\")] == \"# number of nodes:\": numNodes = spoon.split(':')[1] numNodes =",
"as gcl def startAlgo(): numNodes = None spoon = input().strip() # Getting graph",
"grafo = gcl.Graph(numNodes) # Getting arcs for _ in range(m): spoon = input().strip()",
"python3 from sys import stderr, exit import sys import graph_connectivity_lib as gcl def",
"spoon[:len(\"# Tell me\")] != \"# Tell me\": spoon = input().strip() # Checking spanning",
"# Checking spanning tree input_spTree, not_visited = grafo.spanning_tree() # Telling sp tree length",
"spoon = input().strip() # Main spoon = input().strip() while spoon[:len(\"#start\")] != \"#start\": spoon",
"tree length print(len(input_spTree)) #printing sp tree for i in range(len(input_spTree)): u, v =",
"\")] == \"# number of arcs: \": m = spoon.split(':')[1] m = int(\"\".join(m.split()))",
"grafo.add_edge(v, u) # Ricevo istruzioni dal servizio while spoon[:len(\"# Tell me\")] != \"#",
"spoon = input().strip() while spoon != \"#end\".strip(): print(spoon) sys.stderr.write(str(spoon)+ \"\\n\") spoon = input().strip()",
"servizio while spoon[:len(\"# Tell me\")] != \"# Tell me\": spoon = input().strip() #",
"= input().strip() v, u = spoon.split(' ') v, u = int(v), int(u) grafo.add_edge(v,",
"= input().strip() # Getting graph while spoon[:len(\"graph:\")] != \"graph:\": # Getting number of",
"of arcs: \")] == \"# number of arcs: \": m = spoon.split(':')[1] m",
"= input().strip() # Creating graph grafo = gcl.Graph(numNodes) # Getting arcs for _",
"input().strip() # Creating graph grafo = gcl.Graph(numNodes) # Getting arcs for _ in",
"spoon.split(':')[1] numNodes = int(\"\".join(numNodes.split())) # Getting number archs if spoon[:len(\"# number of arcs:",
"dal servizio while spoon[:len(\"# Tell me\")] != \"# Tell me\": spoon = input().strip()",
"spoon.split(' ') v, u = int(v), int(u) grafo.add_edge(v, u) # Ricevo istruzioni dal",
"\"# number of nodes:\": numNodes = spoon.split(':')[1] numNodes = int(\"\".join(numNodes.split())) # Getting number",
"spoon = input().strip() # Checking spanning tree input_spTree, not_visited = grafo.spanning_tree() # Telling",
"number of arcs: \")] == \"# number of arcs: \": m = spoon.split(':')[1]",
"!= \"#end\".strip(): print(spoon) sys.stderr.write(str(spoon)+ \"\\n\") spoon = input().strip() # Main spoon = input().strip()",
"\"# number of arcs: \": m = spoon.split(':')[1] m = int(\"\".join(m.split())) spoon =",
"if spoon[:len(\"# number of nodes:\")] == \"# number of nodes:\": numNodes = spoon.split(':')[1]",
"\": m = spoon.split(':')[1] m = int(\"\".join(m.split())) spoon = input().strip() # Creating graph",
"spoon.split(':')[1] m = int(\"\".join(m.split())) spoon = input().strip() # Creating graph grafo = gcl.Graph(numNodes)",
"# Getting graph while spoon[:len(\"graph:\")] != \"graph:\": # Getting number of nodes if",
"u, v = input_spTree[i] print(f\"{u} {v}\") # Getting response spoon = input().strip() while",
"Getting graph while spoon[:len(\"graph:\")] != \"graph:\": # Getting number of nodes if spoon[:len(\"#",
"response spoon = input().strip() while spoon != \"#end\".strip(): print(spoon) sys.stderr.write(str(spoon)+ \"\\n\") spoon =",
"= int(v), int(u) grafo.add_edge(v, u) # Ricevo istruzioni dal servizio while spoon[:len(\"# Tell",
"= input().strip() while spoon[:len(\"#start\")] != \"#start\": spoon = input().strip() # Reading the graph",
"numNodes = int(\"\".join(numNodes.split())) # Getting number archs if spoon[:len(\"# number of arcs: \")]",
"import stderr, exit import sys import graph_connectivity_lib as gcl def startAlgo(): numNodes =",
"Creating graph grafo = gcl.Graph(numNodes) # Getting arcs for _ in range(m): spoon",
"spanning tree input_spTree, not_visited = grafo.spanning_tree() # Telling sp tree length print(len(input_spTree)) #printing",
"tree for i in range(len(input_spTree)): u, v = input_spTree[i] print(f\"{u} {v}\") # Getting",
"# Ricevo istruzioni dal servizio while spoon[:len(\"# Tell me\")] != \"# Tell me\":",
"!= \"graph:\": # Getting number of nodes if spoon[:len(\"# number of nodes:\")] ==",
"print(spoon) sys.stderr.write(str(spoon)+ \"\\n\") spoon = input().strip() # Main spoon = input().strip() while spoon[:len(\"#start\")]",
"# Getting arcs for _ in range(m): spoon = input().strip() v, u =",
"range(m): spoon = input().strip() v, u = spoon.split(' ') v, u = int(v),",
"#printing sp tree for i in range(len(input_spTree)): u, v = input_spTree[i] print(f\"{u} {v}\")",
"in range(m): spoon = input().strip() v, u = spoon.split(' ') v, u =",
"archs if spoon[:len(\"# number of arcs: \")] == \"# number of arcs: \":",
"int(v), int(u) grafo.add_edge(v, u) # Ricevo istruzioni dal servizio while spoon[:len(\"# Tell me\")]",
"of nodes:\": numNodes = spoon.split(':')[1] numNodes = int(\"\".join(numNodes.split())) # Getting number archs if",
"Checking spanning tree input_spTree, not_visited = grafo.spanning_tree() # Telling sp tree length print(len(input_spTree))",
"import graph_connectivity_lib as gcl def startAlgo(): numNodes = None spoon = input().strip() #",
"') v, u = int(v), int(u) grafo.add_edge(v, u) # Ricevo istruzioni dal servizio",
"v, u = int(v), int(u) grafo.add_edge(v, u) # Ricevo istruzioni dal servizio while",
"sys import stderr, exit import sys import graph_connectivity_lib as gcl def startAlgo(): numNodes",
"!= \"# Tell me\": spoon = input().strip() # Checking spanning tree input_spTree, not_visited",
"spoon = input().strip() while spoon[:len(\"#start\")] != \"#start\": spoon = input().strip() # Reading the",
"number of nodes if spoon[:len(\"# number of nodes:\")] == \"# number of nodes:\":",
"not_visited = grafo.spanning_tree() # Telling sp tree length print(len(input_spTree)) #printing sp tree for",
"u = spoon.split(' ') v, u = int(v), int(u) grafo.add_edge(v, u) # Ricevo",
"spoon = input().strip() # Creating graph grafo = gcl.Graph(numNodes) # Getting arcs for",
"input_spTree[i] print(f\"{u} {v}\") # Getting response spoon = input().strip() while spoon != \"#end\".strip():",
"print(f\"{u} {v}\") # Getting response spoon = input().strip() while spoon != \"#end\".strip(): print(spoon)",
"m = int(\"\".join(m.split())) spoon = input().strip() # Creating graph grafo = gcl.Graph(numNodes) #",
"for _ in range(m): spoon = input().strip() v, u = spoon.split(' ') v,",
"= input().strip() while spoon != \"#end\".strip(): print(spoon) sys.stderr.write(str(spoon)+ \"\\n\") spoon = input().strip() #",
"nodes:\": numNodes = spoon.split(':')[1] numNodes = int(\"\".join(numNodes.split())) # Getting number archs if spoon[:len(\"#",
"sys.stderr.write(str(spoon)+ \"\\n\") spoon = input().strip() # Main spoon = input().strip() while spoon[:len(\"#start\")] !=",
"spoon[:len(\"# number of arcs: \")] == \"# number of arcs: \": m =",
"tree input_spTree, not_visited = grafo.spanning_tree() # Telling sp tree length print(len(input_spTree)) #printing sp",
"number archs if spoon[:len(\"# number of arcs: \")] == \"# number of arcs:",
"None spoon = input().strip() # Getting graph while spoon[:len(\"graph:\")] != \"graph:\": # Getting",
"spoon[:len(\"graph:\")] != \"graph:\": # Getting number of nodes if spoon[:len(\"# number of nodes:\")]",
"if spoon[:len(\"# number of arcs: \")] == \"# number of arcs: \": m",
"# Creating graph grafo = gcl.Graph(numNodes) # Getting arcs for _ in range(m):",
"nodes:\")] == \"# number of nodes:\": numNodes = spoon.split(':')[1] numNodes = int(\"\".join(numNodes.split())) #",
"input().strip() # Checking spanning tree input_spTree, not_visited = grafo.spanning_tree() # Telling sp tree",
"= int(\"\".join(numNodes.split())) # Getting number archs if spoon[:len(\"# number of arcs: \")] ==",
"gcl.Graph(numNodes) # Getting arcs for _ in range(m): spoon = input().strip() v, u",
"int(u) grafo.add_edge(v, u) # Ricevo istruzioni dal servizio while spoon[:len(\"# Tell me\")] !=",
"me\")] != \"# Tell me\": spoon = input().strip() # Checking spanning tree input_spTree,"
] |
[
"predicts = max(logit, 1)[1] corrects = (predicts.view(y_gt.size()).data == y_gt.data).float().sum() accuracy = 100.0 *",
"torch.nn.functional import cross_entropy def compute_acc(logit, y_gt): predicts = max(logit, 1)[1] corrects = (predicts.view(y_gt.size()).data",
"cross_entropy def compute_acc(logit, y_gt): predicts = max(logit, 1)[1] corrects = (predicts.view(y_gt.size()).data == y_gt.data).float().sum()",
"from torch.nn.functional import cross_entropy def compute_acc(logit, y_gt): predicts = max(logit, 1)[1] corrects =",
"<filename>examples/text_classificaiton/functional.py from torch import max from torch.nn.functional import cross_entropy def compute_acc(logit, y_gt): predicts",
"y_gt): predicts = max(logit, 1)[1] corrects = (predicts.view(y_gt.size()).data == y_gt.data).float().sum() accuracy = 100.0",
"= max(logit, 1)[1] corrects = (predicts.view(y_gt.size()).data == y_gt.data).float().sum() accuracy = 100.0 * float(corrects/len(y_gt))",
"max(logit, 1)[1] corrects = (predicts.view(y_gt.size()).data == y_gt.data).float().sum() accuracy = 100.0 * float(corrects/len(y_gt)) return",
"compute_acc(logit, y_gt): predicts = max(logit, 1)[1] corrects = (predicts.view(y_gt.size()).data == y_gt.data).float().sum() accuracy =",
"import cross_entropy def compute_acc(logit, y_gt): predicts = max(logit, 1)[1] corrects = (predicts.view(y_gt.size()).data ==",
"1)[1] corrects = (predicts.view(y_gt.size()).data == y_gt.data).float().sum() accuracy = 100.0 * float(corrects/len(y_gt)) return accuracy",
"torch import max from torch.nn.functional import cross_entropy def compute_acc(logit, y_gt): predicts = max(logit,",
"def compute_acc(logit, y_gt): predicts = max(logit, 1)[1] corrects = (predicts.view(y_gt.size()).data == y_gt.data).float().sum() accuracy",
"import max from torch.nn.functional import cross_entropy def compute_acc(logit, y_gt): predicts = max(logit, 1)[1]",
"from torch import max from torch.nn.functional import cross_entropy def compute_acc(logit, y_gt): predicts =",
"max from torch.nn.functional import cross_entropy def compute_acc(logit, y_gt): predicts = max(logit, 1)[1] corrects"
] |
[
"access_token = r.json()['access_token'] return access_token def hosted_kfp_test(data, context): logging.info('Event ID: {}'.format(context.event_id)) logging.info('Event type:",
"{}'.format(data['metageneration'])) logging.info('Created: {}'.format(data['timeCreated'])) logging.info('Updated: {}'.format(data['updated'])) token = get_access_token() logging.info('attempting to launch pipeline run.')",
"dsl.ContainerOp( name='filechange', image='library/bash:4.4.23', command=['sh', '-c'], arguments=['echo \"%s\" > /tmp/results.txt' % filename], file_outputs={'newfile': '/tmp/results.txt'})",
"@dsl.pipeline( name='Sequential', description='A pipeline with two sequential steps.' ) def sequential_pipeline(filename='gs://ml-pipeline-playground/shakespeare1.txt'): \"\"\"A pipeline",
"# TODO: replace yours # HOST = 'https://<yours>.pipelines.googleusercontent.com' HOST = 'https://7c7f7f3e3d11e1d4-dot-us-central2.pipelines.googleusercontent.com' @dsl.pipeline( name='Sequential',",
"get_access_token(): url = 'http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token' r = requests.get(url, headers={'Metadata-Flavor': 'Google'}) r.raise_for_status() access_token = r.json()['access_token']",
"/tmp/results.txt' % filename], file_outputs={'newfile': '/tmp/results.txt'}) op2 = dsl.ContainerOp( name='echo', image='library/bash:4.4.23', command=['sh', '-c'], arguments=['echo",
"launch pipeline run.') ts = int(datetime.datetime.utcnow().timestamp() * 100000) client = kfp.Client(host=HOST, existing_token=token) compiler.Compiler().compile(sequential_pipeline,",
"HOST = 'https://7c7f7f3e3d11e1d4-dot-us-central2.pipelines.googleusercontent.com' @dsl.pipeline( name='Sequential', description='A pipeline with two sequential steps.' ) def",
"def hosted_kfp_test(data, context): logging.info('Event ID: {}'.format(context.event_id)) logging.info('Event type: {}'.format(context.event_type)) logging.info('Data: {}'.format(data)) logging.info('Bucket: {}'.format(data['bucket']))",
"steps.' ) def sequential_pipeline(filename='gs://ml-pipeline-playground/shakespeare1.txt'): \"\"\"A pipeline with two sequential steps.\"\"\" op1 = dsl.ContainerOp(",
"{}'.format(context.event_type)) logging.info('Data: {}'.format(data)) logging.info('Bucket: {}'.format(data['bucket'])) logging.info('File: {}'.format(data['name'])) file_uri = 'gs://%s/%s' % (data['bucket'], data['name'])",
"= kfp.Client(host=HOST, existing_token=token) compiler.Compiler().compile(sequential_pipeline, '/tmp/sequential.tar.gz') exp = client.create_experiment(name='gcstriggered') # this is a 'get",
"\"\"\"A pipeline with two sequential steps.\"\"\" op1 = dsl.ContainerOp( name='filechange', image='library/bash:4.4.23', command=['sh', '-c'],",
"file_outputs={'newfile': '/tmp/results.txt'}) op2 = dsl.ContainerOp( name='echo', image='library/bash:4.4.23', command=['sh', '-c'], arguments=['echo \"%s\"' % op1.outputs['newfile']]",
"= requests.get(url, headers={'Metadata-Flavor': 'Google'}) r.raise_for_status() access_token = r.json()['access_token'] return access_token def hosted_kfp_test(data, context):",
"pipeline run.') ts = int(datetime.datetime.utcnow().timestamp() * 100000) client = kfp.Client(host=HOST, existing_token=token) compiler.Compiler().compile(sequential_pipeline, '/tmp/sequential.tar.gz')",
"r = requests.get(url, headers={'Metadata-Flavor': 'Google'}) r.raise_for_status() access_token = r.json()['access_token'] return access_token def hosted_kfp_test(data,",
"import logging import datetime import logging import time import kfp import kfp.compiler as",
"{}'.format(data)) logging.info('Bucket: {}'.format(data['bucket'])) logging.info('File: {}'.format(data['name'])) file_uri = 'gs://%s/%s' % (data['bucket'], data['name']) logging.info('Using file",
"= 'gs://%s/%s' % (data['bucket'], data['name']) logging.info('Using file uri: %s', file_uri) logging.info('Metageneration: {}'.format(data['metageneration'])) logging.info('Created:",
"return access_token def hosted_kfp_test(data, context): logging.info('Event ID: {}'.format(context.event_id)) logging.info('Event type: {}'.format(context.event_type)) logging.info('Data: {}'.format(data))",
"* 100000) client = kfp.Client(host=HOST, existing_token=token) compiler.Compiler().compile(sequential_pipeline, '/tmp/sequential.tar.gz') exp = client.create_experiment(name='gcstriggered') # this",
"replace yours # HOST = 'https://<yours>.pipelines.googleusercontent.com' HOST = 'https://7c7f7f3e3d11e1d4-dot-us-central2.pipelines.googleusercontent.com' @dsl.pipeline( name='Sequential', description='A pipeline",
"access_token def hosted_kfp_test(data, context): logging.info('Event ID: {}'.format(context.event_id)) logging.info('Event type: {}'.format(context.event_type)) logging.info('Data: {}'.format(data)) logging.info('Bucket:",
"'https://<yours>.pipelines.googleusercontent.com' HOST = 'https://7c7f7f3e3d11e1d4-dot-us-central2.pipelines.googleusercontent.com' @dsl.pipeline( name='Sequential', description='A pipeline with two sequential steps.' )",
"{}'.format(context.event_id)) logging.info('Event type: {}'.format(context.event_type)) logging.info('Data: {}'.format(data)) logging.info('Bucket: {}'.format(data['bucket'])) logging.info('File: {}'.format(data['name'])) file_uri = 'gs://%s/%s'",
"op1.outputs['newfile']] ) def get_access_token(): url = 'http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token' r = requests.get(url, headers={'Metadata-Flavor': 'Google'}) r.raise_for_status()",
"a 'get or create' op res = client.run_pipeline(exp.id, 'sequential_' + str(ts), '/tmp/sequential.tar.gz', params={'filename':",
"logging.info('Event type: {}'.format(context.event_type)) logging.info('Data: {}'.format(data)) logging.info('Bucket: {}'.format(data['bucket'])) logging.info('File: {}'.format(data['name'])) file_uri = 'gs://%s/%s' %",
"import kfp.compiler as compiler import kfp.dsl as dsl import requests # TODO: replace",
"= 'https://<yours>.pipelines.googleusercontent.com' HOST = 'https://7c7f7f3e3d11e1d4-dot-us-central2.pipelines.googleusercontent.com' @dsl.pipeline( name='Sequential', description='A pipeline with two sequential steps.'",
"name='filechange', image='library/bash:4.4.23', command=['sh', '-c'], arguments=['echo \"%s\" > /tmp/results.txt' % filename], file_outputs={'newfile': '/tmp/results.txt'}) op2",
"kfp import kfp.compiler as compiler import kfp.dsl as dsl import requests # TODO:",
"dsl.ContainerOp( name='echo', image='library/bash:4.4.23', command=['sh', '-c'], arguments=['echo \"%s\"' % op1.outputs['newfile']] ) def get_access_token(): url",
"arguments=['echo \"%s\"' % op1.outputs['newfile']] ) def get_access_token(): url = 'http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token' r = requests.get(url,",
"sequential_pipeline(filename='gs://ml-pipeline-playground/shakespeare1.txt'): \"\"\"A pipeline with two sequential steps.\"\"\" op1 = dsl.ContainerOp( name='filechange', image='library/bash:4.4.23', command=['sh',",
") def sequential_pipeline(filename='gs://ml-pipeline-playground/shakespeare1.txt'): \"\"\"A pipeline with two sequential steps.\"\"\" op1 = dsl.ContainerOp( name='filechange',",
"context): logging.info('Event ID: {}'.format(context.event_id)) logging.info('Event type: {}'.format(context.event_type)) logging.info('Data: {}'.format(data)) logging.info('Bucket: {}'.format(data['bucket'])) logging.info('File: {}'.format(data['name']))",
"'get or create' op res = client.run_pipeline(exp.id, 'sequential_' + str(ts), '/tmp/sequential.tar.gz', params={'filename': file_uri})",
"<filename>ml/notebook_examples/functions/main.py import logging import datetime import logging import time import kfp import kfp.compiler",
"(data['bucket'], data['name']) logging.info('Using file uri: %s', file_uri) logging.info('Metageneration: {}'.format(data['metageneration'])) logging.info('Created: {}'.format(data['timeCreated'])) logging.info('Updated: {}'.format(data['updated']))",
"dsl import requests # TODO: replace yours # HOST = 'https://<yours>.pipelines.googleusercontent.com' HOST =",
"kfp.compiler as compiler import kfp.dsl as dsl import requests # TODO: replace yours",
"logging.info('Bucket: {}'.format(data['bucket'])) logging.info('File: {}'.format(data['name'])) file_uri = 'gs://%s/%s' % (data['bucket'], data['name']) logging.info('Using file uri:",
"url = 'http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token' r = requests.get(url, headers={'Metadata-Flavor': 'Google'}) r.raise_for_status() access_token = r.json()['access_token'] return",
"run.') ts = int(datetime.datetime.utcnow().timestamp() * 100000) client = kfp.Client(host=HOST, existing_token=token) compiler.Compiler().compile(sequential_pipeline, '/tmp/sequential.tar.gz') exp",
"logging.info('Created: {}'.format(data['timeCreated'])) logging.info('Updated: {}'.format(data['updated'])) token = get_access_token() logging.info('attempting to launch pipeline run.') ts",
"token = get_access_token() logging.info('attempting to launch pipeline run.') ts = int(datetime.datetime.utcnow().timestamp() * 100000)",
"filename], file_outputs={'newfile': '/tmp/results.txt'}) op2 = dsl.ContainerOp( name='echo', image='library/bash:4.4.23', command=['sh', '-c'], arguments=['echo \"%s\"' %",
"TODO: replace yours # HOST = 'https://<yours>.pipelines.googleusercontent.com' HOST = 'https://7c7f7f3e3d11e1d4-dot-us-central2.pipelines.googleusercontent.com' @dsl.pipeline( name='Sequential', description='A",
"file_uri) logging.info('Metageneration: {}'.format(data['metageneration'])) logging.info('Created: {}'.format(data['timeCreated'])) logging.info('Updated: {}'.format(data['updated'])) token = get_access_token() logging.info('attempting to launch",
"logging import time import kfp import kfp.compiler as compiler import kfp.dsl as dsl",
"requests.get(url, headers={'Metadata-Flavor': 'Google'}) r.raise_for_status() access_token = r.json()['access_token'] return access_token def hosted_kfp_test(data, context): logging.info('Event",
"logging.info('Event ID: {}'.format(context.event_id)) logging.info('Event type: {}'.format(context.event_type)) logging.info('Data: {}'.format(data)) logging.info('Bucket: {}'.format(data['bucket'])) logging.info('File: {}'.format(data['name'])) file_uri",
"ID: {}'.format(context.event_id)) logging.info('Event type: {}'.format(context.event_type)) logging.info('Data: {}'.format(data)) logging.info('Bucket: {}'.format(data['bucket'])) logging.info('File: {}'.format(data['name'])) file_uri =",
"logging.info('Using file uri: %s', file_uri) logging.info('Metageneration: {}'.format(data['metageneration'])) logging.info('Created: {}'.format(data['timeCreated'])) logging.info('Updated: {}'.format(data['updated'])) token =",
"= dsl.ContainerOp( name='echo', image='library/bash:4.4.23', command=['sh', '-c'], arguments=['echo \"%s\"' % op1.outputs['newfile']] ) def get_access_token():",
"description='A pipeline with two sequential steps.' ) def sequential_pipeline(filename='gs://ml-pipeline-playground/shakespeare1.txt'): \"\"\"A pipeline with two",
"{}'.format(data['updated'])) token = get_access_token() logging.info('attempting to launch pipeline run.') ts = int(datetime.datetime.utcnow().timestamp() *",
"'http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token' r = requests.get(url, headers={'Metadata-Flavor': 'Google'}) r.raise_for_status() access_token = r.json()['access_token'] return access_token def",
"pipeline with two sequential steps.' ) def sequential_pipeline(filename='gs://ml-pipeline-playground/shakespeare1.txt'): \"\"\"A pipeline with two sequential",
"file uri: %s', file_uri) logging.info('Metageneration: {}'.format(data['metageneration'])) logging.info('Created: {}'.format(data['timeCreated'])) logging.info('Updated: {}'.format(data['updated'])) token = get_access_token()",
"exp = client.create_experiment(name='gcstriggered') # this is a 'get or create' op res =",
"to launch pipeline run.') ts = int(datetime.datetime.utcnow().timestamp() * 100000) client = kfp.Client(host=HOST, existing_token=token)",
"# HOST = 'https://<yours>.pipelines.googleusercontent.com' HOST = 'https://7c7f7f3e3d11e1d4-dot-us-central2.pipelines.googleusercontent.com' @dsl.pipeline( name='Sequential', description='A pipeline with two",
"'Google'}) r.raise_for_status() access_token = r.json()['access_token'] return access_token def hosted_kfp_test(data, context): logging.info('Event ID: {}'.format(context.event_id))",
"= client.create_experiment(name='gcstriggered') # this is a 'get or create' op res = client.run_pipeline(exp.id,",
"arguments=['echo \"%s\" > /tmp/results.txt' % filename], file_outputs={'newfile': '/tmp/results.txt'}) op2 = dsl.ContainerOp( name='echo', image='library/bash:4.4.23',",
"uri: %s', file_uri) logging.info('Metageneration: {}'.format(data['metageneration'])) logging.info('Created: {}'.format(data['timeCreated'])) logging.info('Updated: {}'.format(data['updated'])) token = get_access_token() logging.info('attempting",
"'-c'], arguments=['echo \"%s\"' % op1.outputs['newfile']] ) def get_access_token(): url = 'http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token' r =",
"name='Sequential', description='A pipeline with two sequential steps.' ) def sequential_pipeline(filename='gs://ml-pipeline-playground/shakespeare1.txt'): \"\"\"A pipeline with",
"import time import kfp import kfp.compiler as compiler import kfp.dsl as dsl import",
"'/tmp/sequential.tar.gz') exp = client.create_experiment(name='gcstriggered') # this is a 'get or create' op res",
"type: {}'.format(context.event_type)) logging.info('Data: {}'.format(data)) logging.info('Bucket: {}'.format(data['bucket'])) logging.info('File: {}'.format(data['name'])) file_uri = 'gs://%s/%s' % (data['bucket'],",
"logging.info('Updated: {}'.format(data['updated'])) token = get_access_token() logging.info('attempting to launch pipeline run.') ts = int(datetime.datetime.utcnow().timestamp()",
"existing_token=token) compiler.Compiler().compile(sequential_pipeline, '/tmp/sequential.tar.gz') exp = client.create_experiment(name='gcstriggered') # this is a 'get or create'",
"with two sequential steps.' ) def sequential_pipeline(filename='gs://ml-pipeline-playground/shakespeare1.txt'): \"\"\"A pipeline with two sequential steps.\"\"\"",
"logging.info('attempting to launch pipeline run.') ts = int(datetime.datetime.utcnow().timestamp() * 100000) client = kfp.Client(host=HOST,",
"kfp.dsl as dsl import requests # TODO: replace yours # HOST = 'https://<yours>.pipelines.googleusercontent.com'",
"import logging import time import kfp import kfp.compiler as compiler import kfp.dsl as",
"with two sequential steps.\"\"\" op1 = dsl.ContainerOp( name='filechange', image='library/bash:4.4.23', command=['sh', '-c'], arguments=['echo \"%s\"",
"two sequential steps.\"\"\" op1 = dsl.ContainerOp( name='filechange', image='library/bash:4.4.23', command=['sh', '-c'], arguments=['echo \"%s\" >",
"image='library/bash:4.4.23', command=['sh', '-c'], arguments=['echo \"%s\" > /tmp/results.txt' % filename], file_outputs={'newfile': '/tmp/results.txt'}) op2 =",
"'https://7c7f7f3e3d11e1d4-dot-us-central2.pipelines.googleusercontent.com' @dsl.pipeline( name='Sequential', description='A pipeline with two sequential steps.' ) def sequential_pipeline(filename='gs://ml-pipeline-playground/shakespeare1.txt'): \"\"\"A",
"get_access_token() logging.info('attempting to launch pipeline run.') ts = int(datetime.datetime.utcnow().timestamp() * 100000) client =",
"command=['sh', '-c'], arguments=['echo \"%s\"' % op1.outputs['newfile']] ) def get_access_token(): url = 'http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token' r",
"kfp.Client(host=HOST, existing_token=token) compiler.Compiler().compile(sequential_pipeline, '/tmp/sequential.tar.gz') exp = client.create_experiment(name='gcstriggered') # this is a 'get or",
"\"%s\" > /tmp/results.txt' % filename], file_outputs={'newfile': '/tmp/results.txt'}) op2 = dsl.ContainerOp( name='echo', image='library/bash:4.4.23', command=['sh',",
"steps.\"\"\" op1 = dsl.ContainerOp( name='filechange', image='library/bash:4.4.23', command=['sh', '-c'], arguments=['echo \"%s\" > /tmp/results.txt' %",
"ts = int(datetime.datetime.utcnow().timestamp() * 100000) client = kfp.Client(host=HOST, existing_token=token) compiler.Compiler().compile(sequential_pipeline, '/tmp/sequential.tar.gz') exp =",
"{}'.format(data['bucket'])) logging.info('File: {}'.format(data['name'])) file_uri = 'gs://%s/%s' % (data['bucket'], data['name']) logging.info('Using file uri: %s',",
"time import kfp import kfp.compiler as compiler import kfp.dsl as dsl import requests",
"as compiler import kfp.dsl as dsl import requests # TODO: replace yours #",
"import requests # TODO: replace yours # HOST = 'https://<yours>.pipelines.googleusercontent.com' HOST = 'https://7c7f7f3e3d11e1d4-dot-us-central2.pipelines.googleusercontent.com'",
"> /tmp/results.txt' % filename], file_outputs={'newfile': '/tmp/results.txt'}) op2 = dsl.ContainerOp( name='echo', image='library/bash:4.4.23', command=['sh', '-c'],",
"'-c'], arguments=['echo \"%s\" > /tmp/results.txt' % filename], file_outputs={'newfile': '/tmp/results.txt'}) op2 = dsl.ContainerOp( name='echo',",
"{}'.format(data['timeCreated'])) logging.info('Updated: {}'.format(data['updated'])) token = get_access_token() logging.info('attempting to launch pipeline run.') ts =",
"= 'https://7c7f7f3e3d11e1d4-dot-us-central2.pipelines.googleusercontent.com' @dsl.pipeline( name='Sequential', description='A pipeline with two sequential steps.' ) def sequential_pipeline(filename='gs://ml-pipeline-playground/shakespeare1.txt'):",
"'/tmp/results.txt'}) op2 = dsl.ContainerOp( name='echo', image='library/bash:4.4.23', command=['sh', '-c'], arguments=['echo \"%s\"' % op1.outputs['newfile']] )",
"data['name']) logging.info('Using file uri: %s', file_uri) logging.info('Metageneration: {}'.format(data['metageneration'])) logging.info('Created: {}'.format(data['timeCreated'])) logging.info('Updated: {}'.format(data['updated'])) token",
"logging.info('File: {}'.format(data['name'])) file_uri = 'gs://%s/%s' % (data['bucket'], data['name']) logging.info('Using file uri: %s', file_uri)",
"import datetime import logging import time import kfp import kfp.compiler as compiler import",
"sequential steps.\"\"\" op1 = dsl.ContainerOp( name='filechange', image='library/bash:4.4.23', command=['sh', '-c'], arguments=['echo \"%s\" > /tmp/results.txt'",
"hosted_kfp_test(data, context): logging.info('Event ID: {}'.format(context.event_id)) logging.info('Event type: {}'.format(context.event_type)) logging.info('Data: {}'.format(data)) logging.info('Bucket: {}'.format(data['bucket'])) logging.info('File:",
"name='echo', image='library/bash:4.4.23', command=['sh', '-c'], arguments=['echo \"%s\"' % op1.outputs['newfile']] ) def get_access_token(): url =",
"= r.json()['access_token'] return access_token def hosted_kfp_test(data, context): logging.info('Event ID: {}'.format(context.event_id)) logging.info('Event type: {}'.format(context.event_type))",
"% (data['bucket'], data['name']) logging.info('Using file uri: %s', file_uri) logging.info('Metageneration: {}'.format(data['metageneration'])) logging.info('Created: {}'.format(data['timeCreated'])) logging.info('Updated:",
"= 'http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token' r = requests.get(url, headers={'Metadata-Flavor': 'Google'}) r.raise_for_status() access_token = r.json()['access_token'] return access_token",
"= dsl.ContainerOp( name='filechange', image='library/bash:4.4.23', command=['sh', '-c'], arguments=['echo \"%s\" > /tmp/results.txt' % filename], file_outputs={'newfile':",
"= get_access_token() logging.info('attempting to launch pipeline run.') ts = int(datetime.datetime.utcnow().timestamp() * 100000) client",
"pipeline with two sequential steps.\"\"\" op1 = dsl.ContainerOp( name='filechange', image='library/bash:4.4.23', command=['sh', '-c'], arguments=['echo",
"logging.info('Metageneration: {}'.format(data['metageneration'])) logging.info('Created: {}'.format(data['timeCreated'])) logging.info('Updated: {}'.format(data['updated'])) token = get_access_token() logging.info('attempting to launch pipeline",
"file_uri = 'gs://%s/%s' % (data['bucket'], data['name']) logging.info('Using file uri: %s', file_uri) logging.info('Metageneration: {}'.format(data['metageneration']))",
") def get_access_token(): url = 'http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token' r = requests.get(url, headers={'Metadata-Flavor': 'Google'}) r.raise_for_status() access_token",
"= int(datetime.datetime.utcnow().timestamp() * 100000) client = kfp.Client(host=HOST, existing_token=token) compiler.Compiler().compile(sequential_pipeline, '/tmp/sequential.tar.gz') exp = client.create_experiment(name='gcstriggered')",
"or create' op res = client.run_pipeline(exp.id, 'sequential_' + str(ts), '/tmp/sequential.tar.gz', params={'filename': file_uri}) logging.info(res)",
"compiler import kfp.dsl as dsl import requests # TODO: replace yours # HOST",
"as dsl import requests # TODO: replace yours # HOST = 'https://<yours>.pipelines.googleusercontent.com' HOST",
"yours # HOST = 'https://<yours>.pipelines.googleusercontent.com' HOST = 'https://7c7f7f3e3d11e1d4-dot-us-central2.pipelines.googleusercontent.com' @dsl.pipeline( name='Sequential', description='A pipeline with",
"# this is a 'get or create' op res = client.run_pipeline(exp.id, 'sequential_' +",
"r.json()['access_token'] return access_token def hosted_kfp_test(data, context): logging.info('Event ID: {}'.format(context.event_id)) logging.info('Event type: {}'.format(context.event_type)) logging.info('Data:",
"command=['sh', '-c'], arguments=['echo \"%s\" > /tmp/results.txt' % filename], file_outputs={'newfile': '/tmp/results.txt'}) op2 = dsl.ContainerOp(",
"logging.info('Data: {}'.format(data)) logging.info('Bucket: {}'.format(data['bucket'])) logging.info('File: {}'.format(data['name'])) file_uri = 'gs://%s/%s' % (data['bucket'], data['name']) logging.info('Using",
"% filename], file_outputs={'newfile': '/tmp/results.txt'}) op2 = dsl.ContainerOp( name='echo', image='library/bash:4.4.23', command=['sh', '-c'], arguments=['echo \"%s\"'",
"image='library/bash:4.4.23', command=['sh', '-c'], arguments=['echo \"%s\"' % op1.outputs['newfile']] ) def get_access_token(): url = 'http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token'",
"this is a 'get or create' op res = client.run_pipeline(exp.id, 'sequential_' + str(ts),",
"% op1.outputs['newfile']] ) def get_access_token(): url = 'http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token' r = requests.get(url, headers={'Metadata-Flavor': 'Google'})",
"is a 'get or create' op res = client.run_pipeline(exp.id, 'sequential_' + str(ts), '/tmp/sequential.tar.gz',",
"{}'.format(data['name'])) file_uri = 'gs://%s/%s' % (data['bucket'], data['name']) logging.info('Using file uri: %s', file_uri) logging.info('Metageneration:",
"\"%s\"' % op1.outputs['newfile']] ) def get_access_token(): url = 'http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token' r = requests.get(url, headers={'Metadata-Flavor':",
"def sequential_pipeline(filename='gs://ml-pipeline-playground/shakespeare1.txt'): \"\"\"A pipeline with two sequential steps.\"\"\" op1 = dsl.ContainerOp( name='filechange', image='library/bash:4.4.23',",
"op2 = dsl.ContainerOp( name='echo', image='library/bash:4.4.23', command=['sh', '-c'], arguments=['echo \"%s\"' % op1.outputs['newfile']] ) def",
"r.raise_for_status() access_token = r.json()['access_token'] return access_token def hosted_kfp_test(data, context): logging.info('Event ID: {}'.format(context.event_id)) logging.info('Event",
"headers={'Metadata-Flavor': 'Google'}) r.raise_for_status() access_token = r.json()['access_token'] return access_token def hosted_kfp_test(data, context): logging.info('Event ID:",
"int(datetime.datetime.utcnow().timestamp() * 100000) client = kfp.Client(host=HOST, existing_token=token) compiler.Compiler().compile(sequential_pipeline, '/tmp/sequential.tar.gz') exp = client.create_experiment(name='gcstriggered') #",
"client.create_experiment(name='gcstriggered') # this is a 'get or create' op res = client.run_pipeline(exp.id, 'sequential_'",
"%s', file_uri) logging.info('Metageneration: {}'.format(data['metageneration'])) logging.info('Created: {}'.format(data['timeCreated'])) logging.info('Updated: {}'.format(data['updated'])) token = get_access_token() logging.info('attempting to",
"op1 = dsl.ContainerOp( name='filechange', image='library/bash:4.4.23', command=['sh', '-c'], arguments=['echo \"%s\" > /tmp/results.txt' % filename],",
"sequential steps.' ) def sequential_pipeline(filename='gs://ml-pipeline-playground/shakespeare1.txt'): \"\"\"A pipeline with two sequential steps.\"\"\" op1 =",
"def get_access_token(): url = 'http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/token' r = requests.get(url, headers={'Metadata-Flavor': 'Google'}) r.raise_for_status() access_token =",
"import kfp.dsl as dsl import requests # TODO: replace yours # HOST =",
"HOST = 'https://<yours>.pipelines.googleusercontent.com' HOST = 'https://7c7f7f3e3d11e1d4-dot-us-central2.pipelines.googleusercontent.com' @dsl.pipeline( name='Sequential', description='A pipeline with two sequential",
"requests # TODO: replace yours # HOST = 'https://<yours>.pipelines.googleusercontent.com' HOST = 'https://7c7f7f3e3d11e1d4-dot-us-central2.pipelines.googleusercontent.com' @dsl.pipeline(",
"datetime import logging import time import kfp import kfp.compiler as compiler import kfp.dsl",
"compiler.Compiler().compile(sequential_pipeline, '/tmp/sequential.tar.gz') exp = client.create_experiment(name='gcstriggered') # this is a 'get or create' op",
"import kfp import kfp.compiler as compiler import kfp.dsl as dsl import requests #",
"'gs://%s/%s' % (data['bucket'], data['name']) logging.info('Using file uri: %s', file_uri) logging.info('Metageneration: {}'.format(data['metageneration'])) logging.info('Created: {}'.format(data['timeCreated']))",
"100000) client = kfp.Client(host=HOST, existing_token=token) compiler.Compiler().compile(sequential_pipeline, '/tmp/sequential.tar.gz') exp = client.create_experiment(name='gcstriggered') # this is",
"logging import datetime import logging import time import kfp import kfp.compiler as compiler",
"client = kfp.Client(host=HOST, existing_token=token) compiler.Compiler().compile(sequential_pipeline, '/tmp/sequential.tar.gz') exp = client.create_experiment(name='gcstriggered') # this is a",
"two sequential steps.' ) def sequential_pipeline(filename='gs://ml-pipeline-playground/shakespeare1.txt'): \"\"\"A pipeline with two sequential steps.\"\"\" op1"
] |
[
"def __init__(self): super().__init__() @abstractmethod def forward_from_batch(self, batch: List[Tensor]): pass class BatchInputModuleFactory(ModuleFactory): def __init__(self):",
"Tensor from torch.nn import Module from tha2.nn.base.module_factory import ModuleFactory class BatchInputModule(Module, ABC): def",
"from abc import ABC, abstractmethod from typing import List from torch import Tensor",
"from torch.nn import Module from tha2.nn.base.module_factory import ModuleFactory class BatchInputModule(Module, ABC): def __init__(self):",
"torch.nn import Module from tha2.nn.base.module_factory import ModuleFactory class BatchInputModule(Module, ABC): def __init__(self): super().__init__()",
"ABC, abstractmethod from typing import List from torch import Tensor from torch.nn import",
"class BatchInputModule(Module, ABC): def __init__(self): super().__init__() @abstractmethod def forward_from_batch(self, batch: List[Tensor]): pass class",
"super().__init__() @abstractmethod def forward_from_batch(self, batch: List[Tensor]): pass class BatchInputModuleFactory(ModuleFactory): def __init__(self): super().__init__() @abstractmethod",
"abstractmethod from typing import List from torch import Tensor from torch.nn import Module",
"List from torch import Tensor from torch.nn import Module from tha2.nn.base.module_factory import ModuleFactory",
"BatchInputModule(Module, ABC): def __init__(self): super().__init__() @abstractmethod def forward_from_batch(self, batch: List[Tensor]): pass class BatchInputModuleFactory(ModuleFactory):",
"ModuleFactory class BatchInputModule(Module, ABC): def __init__(self): super().__init__() @abstractmethod def forward_from_batch(self, batch: List[Tensor]): pass",
"typing import List from torch import Tensor from torch.nn import Module from tha2.nn.base.module_factory",
"List[Tensor]): pass class BatchInputModuleFactory(ModuleFactory): def __init__(self): super().__init__() @abstractmethod def create(self) -> BatchInputModule: pass",
"batch: List[Tensor]): pass class BatchInputModuleFactory(ModuleFactory): def __init__(self): super().__init__() @abstractmethod def create(self) -> BatchInputModule:",
"tha2.nn.base.module_factory import ModuleFactory class BatchInputModule(Module, ABC): def __init__(self): super().__init__() @abstractmethod def forward_from_batch(self, batch:",
"__init__(self): super().__init__() @abstractmethod def forward_from_batch(self, batch: List[Tensor]): pass class BatchInputModuleFactory(ModuleFactory): def __init__(self): super().__init__()",
"abc import ABC, abstractmethod from typing import List from torch import Tensor from",
"from torch import Tensor from torch.nn import Module from tha2.nn.base.module_factory import ModuleFactory class",
"import Module from tha2.nn.base.module_factory import ModuleFactory class BatchInputModule(Module, ABC): def __init__(self): super().__init__() @abstractmethod",
"from typing import List from torch import Tensor from torch.nn import Module from",
"torch import Tensor from torch.nn import Module from tha2.nn.base.module_factory import ModuleFactory class BatchInputModule(Module,",
"@abstractmethod def forward_from_batch(self, batch: List[Tensor]): pass class BatchInputModuleFactory(ModuleFactory): def __init__(self): super().__init__() @abstractmethod def",
"import ABC, abstractmethod from typing import List from torch import Tensor from torch.nn",
"import List from torch import Tensor from torch.nn import Module from tha2.nn.base.module_factory import",
"ABC): def __init__(self): super().__init__() @abstractmethod def forward_from_batch(self, batch: List[Tensor]): pass class BatchInputModuleFactory(ModuleFactory): def",
"from tha2.nn.base.module_factory import ModuleFactory class BatchInputModule(Module, ABC): def __init__(self): super().__init__() @abstractmethod def forward_from_batch(self,",
"def forward_from_batch(self, batch: List[Tensor]): pass class BatchInputModuleFactory(ModuleFactory): def __init__(self): super().__init__() @abstractmethod def create(self)",
"import ModuleFactory class BatchInputModule(Module, ABC): def __init__(self): super().__init__() @abstractmethod def forward_from_batch(self, batch: List[Tensor]):",
"forward_from_batch(self, batch: List[Tensor]): pass class BatchInputModuleFactory(ModuleFactory): def __init__(self): super().__init__() @abstractmethod def create(self) ->",
"Module from tha2.nn.base.module_factory import ModuleFactory class BatchInputModule(Module, ABC): def __init__(self): super().__init__() @abstractmethod def",
"import Tensor from torch.nn import Module from tha2.nn.base.module_factory import ModuleFactory class BatchInputModule(Module, ABC):"
] |
[
"Maybe you didn't compile \" \\ \"the external tools in smodels/lib?\", self.executablePath) return",
"def __init__(self): ExternalNllFast.__init__(self, 7, \"1.2\", testParams=\"gg cteq 500 600\", testCondition=\"500. 600. 0.193E+00 \"",
"executable and executing it. \"\"\" if not os.path.exists(self.executablePath): logger.error(\"Executable '%s' not found. Maybe",
"if not os.access(self.executablePath, os.X_OK): logger.error(\"%s is not executable\", self.executable) return False out =",
"= self.run_(self.testParams) if out[-1].find(self.testCondition) == -1: logger.error(\"Setup invalid: \" + str(out)) return False",
"= \"http://smodels.hephy.at/externaltools/nllfast%d.tar.gz\" \\ % self.sqrts logger.info(\"fetching tarball from \" + url) R =",
":synopsis: Wrapper for all nllfast versions. .. moduleauthor:: <NAME> <<EMAIL>> \"\"\" from __future__",
"tempfile = \"/tmp/nllfast7.tar.gz\" f = open(tempfile, \"w\") url = \"http://smodels.hephy.at/externaltools/nllfast%d.tar.gz\" \\ % self.sqrts",
"os.path.exists(fname): # os.unlink(fname) def run_(self, params): \"\"\" Execute nllfast7. :params params: parameters used",
"stdout and stderr, or error message \"\"\" cmd = \"cd %s; %s %s\"",
"with? :param testCondition: the line that should be the last output line when",
"from smodels.tools.externalTool import ExternalTool from smodels.tools.smodelsLogging import logger class ExternalNllFast(ExternalTool): \"\"\" An instance",
"f.close() tar = tarfile.open(tempfile) for item in tar: tar.extract(item, self.srcPath + \"/\") def",
"which process: st, sb, gg, gdcpl, sdcpl, ss, sg, tot :params pdf: cteq=cteq6,",
"+ \"/\") def unlink(self, inputFile): \"\"\" Remove inputFile.out \"\"\" return # fname =",
"\"tot\"] if not process in processes: return None if not pdf in [\"cteq\",",
"logger.info(out) return True def fetch(self): \"\"\" Fetch and unpack tarball. \"\"\" import urllib,",
"process: which process: st, sb, gg, gdcpl, sdcpl, ss, sg, tot :params pdf:",
":params pdf: cteq=cteq6, mstw2008 :params squarkmass: squarkmass, None if squark decoupled :params gluinomass:",
"False if not os.access(self.executablePath, os.X_OK): logger.error(\"%s is not executable\", self.executable) return False out",
"ExternalTool from smodels.tools.smodelsLogging import logger class ExternalNllFast(ExternalTool): \"\"\" An instance of this class",
"self.run_(self.testParams) if out[-1].find(self.testCondition) == -1: logger.error(\"Setup invalid: \" + str(out)) return False self.unlink(\"gg\")",
"\" \"0.450E+00 0.497E+00\") class ExternalNllFast8(ExternalNllFast): \"\"\" An instance of this class represents the",
"compile(self): \"\"\" Try to compile nllfast. \"\"\" logger.info(\"Trying to compile %s\", self.name) cmd",
"for item in tar: tar.extract(item, self.srcPath + \"/\") def unlink(self, inputFile): \"\"\" Remove",
"return False self.unlink(\"gg\") return True class ExternalNllFast7(ExternalNllFast): \"\"\" An instance of this class",
"gg, gdcpl, sdcpl, ss, sg, tot :params pdf: cteq=cteq6, mstw2008 :params squarkmass: squarkmass,",
"self.cdPath + \"/nllfast_%dTeV\" % self.sqrts self.testParams = testParams self.testCondition = testCondition self.srcPath =",
"\"0.450E+00 0.497E+00\") class ExternalNllFast8(ExternalNllFast): \"\"\" An instance of this class represents the installation",
") nllFastTools = { 7 : ExternalNllFast7(), 8 : ExternalNllFast8(), 13 : ExternalNllFast13()",
"R = urllib.urlopen(url) l = R.readlines() for line in l: f.write(line) R.close() f.close()",
"subprocess as executor import os from smodels.tools.externalTool import ExternalTool from smodels.tools.smodelsLogging import logger",
"mstw2008 :params squarkmass: squarkmass, None if squark decoupled :params gluinomass: gluinomass, None if",
"\"1.2\", testParams=\"gg cteq 500 600\", testCondition=\"500. 600. 0.193E+00 \" \"0.450E+00 0.497E+00\") class ExternalNllFast8(ExternalNllFast):",
"represents the installation of nllfast 8. \"\"\" def __init__(self): ExternalNllFast.__init__(self, 8, \"2.1\", testParams=\"gg",
":param testCondition: the line that should be the last output line when running",
"squarkmass, None if squark decoupled :params gluinomass: gluinomass, None if gluino decoupled :returns:",
"of nllfast 8. \"\"\" def __init__(self): ExternalNllFast.__init__(self, 8, \"2.1\", testParams=\"gg cteq 500 600\",",
"= subprocess.check_output ( cmd, shell=True, universal_newlines=True ) logger.info(out) return True def fetch(self): \"\"\"",
"def unlink(self, inputFile): \"\"\" Remove inputFile.out \"\"\" return # fname = \"%s/%s.out\" %",
"location = path + self.nllfastVersion + \"/\" self.cdPath = self.absPath(location) self.executablePath = self.cdPath",
"parameters used (e.g. gg cteq5 .... ) :returns: stdout and stderr, or error",
"message \"\"\" processes = [\"st\", \"sb\", \"gg\", \"gdcpl\", \"sdcpl\", \"ss\", \"sg\", \"tot\"] if",
"+ \"/nllfast_%dTeV\" % self.sqrts self.testParams = testParams self.testCondition = testCondition self.srcPath = self.cdPath",
"this class represents the installation of nllfast 8. \"\"\" def __init__(self): ExternalNllFast.__init__(self, 8,",
"that should be the last output line when running executable :srcPath: the path",
"__future__ import print_function try: import commands as executor except ImportError: import subprocess as",
"st, sb, gg, gdcpl, sdcpl, ss, sg, tot :params pdf: cteq=cteq6, mstw2008 :params",
"if not pdf in [\"cteq\", \"cteq6\", \"mstw\", \"mstw2008\"]: return None if not squarkmass:",
"from __future__ import print_function try: import commands as executor except ImportError: import subprocess",
"= open(tempfile, \"w\") url = \"http://smodels.hephy.at/externaltools/nllfast%d.tar.gz\" \\ % self.sqrts logger.info(\"fetching tarball from \"",
"pdf, squarkmass) return self.run_(\"%s %s %s %s\") % \\ (process, pdf, squarkmass, gluinomass)",
"ExternalNllFast13(ExternalNllFast): \"\"\" An instance of this class represents the installation of nllfast 8.",
"\"\"\" def __init__(self): ExternalNllFast.__init__(self, 13, \"3.1\", testParams=\"gg cteq 500 600\", testCondition=\"600. 0.394E+01 0.690E+01",
"the nllfast tool :param testParams: what are the test params we need to",
"= path + self.nllfastVersion + \"/\" self.cdPath = self.absPath(location) self.executablePath = self.cdPath +",
"represents the installation of nllfast. \"\"\" def __init__(self, sqrts, nllfastVersion, testParams, testCondition): \"\"\"",
"= R.readlines() for line in l: f.write(line) R.close() f.close() tar = tarfile.open(tempfile) for",
"import subprocess as executor import os from smodels.tools.externalTool import ExternalTool from smodels.tools.smodelsLogging import",
"out = self.run_(self.testParams) if out[-1].find(self.testCondition) == -1: logger.error(\"Setup invalid: \" + str(out)) return",
"\" + url) R = urllib.urlopen(url) l = R.readlines() for line in l:",
"in [\"cteq\", \"cteq6\", \"mstw\", \"mstw2008\"]: return None if not squarkmass: return self.run_(\"%s %s",
"valid by looking for executable and executing it. \"\"\" if not os.path.exists(self.executablePath): logger.error(\"Executable",
"nllfast versions. .. moduleauthor:: <NAME> <<EMAIL>> \"\"\" from __future__ import print_function try: import",
"inputFile) # if os.path.exists(fname): # os.unlink(fname) def run_(self, params): \"\"\" Execute nllfast7. :params",
"\"3.1\", testParams=\"gg cteq 500 600\", testCondition=\"600. 0.394E+01 0.690E+01 \" \"0.731E+01 0.394E+00\" ) nllFastTools",
"self.executablePath, params) out = executor.getoutput(cmd) # out = subprocess.check_output ( cmd, shell=True, universal_newlines=True",
"% self.sqrts self.testParams = testParams self.testCondition = testCondition self.srcPath = self.cdPath self.executable =",
"Try to compile nllfast. \"\"\" logger.info(\"Trying to compile %s\", self.name) cmd = \"cd",
"= { 7 : ExternalNllFast7(), 8 : ExternalNllFast8(), 13 : ExternalNllFast13() } if",
"last output line when running executable :srcPath: the path of the source code,",
"all nllfast versions. .. moduleauthor:: <NAME> <<EMAIL>> \"\"\" from __future__ import print_function try:",
"open(tempfile, \"w\") url = \"http://smodels.hephy.at/externaltools/nllfast%d.tar.gz\" \\ % self.sqrts logger.info(\"fetching tarball from \" +",
"Wrapper for all nllfast versions. .. moduleauthor:: <NAME> <<EMAIL>> \"\"\" from __future__ import",
"compile \" \\ \"the external tools in smodels/lib?\", self.executablePath) return False if not",
"logger.info(\"fetching tarball from \" + url) R = urllib.urlopen(url) l = R.readlines() for",
"\"%s/%s.out\" % (self.cdPath, inputFile) # if os.path.exists(fname): # os.unlink(fname) def run_(self, params): \"\"\"",
"the test params we need to run things with? :param testCondition: the line",
"testParams=\"gg cteq 500 600\", testCondition=\"600. 0.394E+01 0.690E+01 \" \"0.731E+01 0.394E+00\" ) nllFastTools =",
"600. 0.193E+00 \" \"0.450E+00 0.497E+00\") class ExternalNllFast8(ExternalNllFast): \"\"\" An instance of this class",
"= \"cd %s; make\" % self.srcPath out = executor.getoutput(cmd) # out = subprocess.check_output",
"( cmd, shell=True, universal_newlines=True ) logger.info(out) return True def fetch(self): \"\"\" Fetch and",
"not pdf in [\"cteq\", \"cteq6\", \"mstw\", \"mstw2008\"]: return None if not squarkmass: return",
"import commands as executor except ImportError: import subprocess as executor import os from",
"\"cd %s; %s %s\" % (self.cdPath, self.executablePath, params) out = executor.getoutput(cmd) # out",
"\"gg\", \"gdcpl\", \"sdcpl\", \"ss\", \"sg\", \"tot\"] if not process in processes: return None",
"\"\"\" An instance of this class represents the installation of nllfast 8. \"\"\"",
"to compile %s\", self.name) cmd = \"cd %s; make\" % self.srcPath out =",
"testParams self.testCondition = testCondition self.srcPath = self.cdPath self.executable = \"\" def compile(self): \"\"\"",
"for compilation \"\"\" ExternalTool.__init__(self) self.sqrts = int(sqrts) self.name = \"nllfast%d\" % sqrts self.nllfastVersion",
"if gluino decoupled :returns: stdout and stderr, or error message \"\"\" processes =",
"str(out)) return False self.unlink(\"gg\") return True class ExternalNllFast7(ExternalNllFast): \"\"\" An instance of this",
"sqrt of s, in TeV, as an integer, :param nllfastVersion: version of the",
"def compile(self): \"\"\" Try to compile nllfast. \"\"\" logger.info(\"Trying to compile %s\", self.name)",
"= int(sqrts) self.name = \"nllfast%d\" % sqrts self.nllfastVersion = nllfastVersion path = \"<install>/lib/nllfast/nllfast-\"",
"\"\"\" return # fname = \"%s/%s.out\" % (self.cdPath, inputFile) # if os.path.exists(fname): #",
"os.X_OK): logger.error(\"%s is not executable\", self.executable) return False out = self.run_(self.testParams) if out[-1].find(self.testCondition)",
"%s; %s %s\" % (self.cdPath, self.executablePath, params) out = executor.getoutput(cmd) # out =",
"universal_newlines=True ) logger.info(out) return True def fetch(self): \"\"\" Fetch and unpack tarball. \"\"\"",
"not found. Maybe you didn't compile \" \\ \"the external tools in smodels/lib?\",",
"shell=True, universal_newlines=True ) out = out.split(\"\\n\") return out def run(self, process, pdf, squarkmass,",
"self.sqrts self.testParams = testParams self.testCondition = testCondition self.srcPath = self.cdPath self.executable = \"\"",
"you didn't compile \" \\ \"the external tools in smodels/lib?\", self.executablePath) return False",
"didn't compile \" \\ \"the external tools in smodels/lib?\", self.executablePath) return False if",
"False out = self.run_(self.testParams) if out[-1].find(self.testCondition) == -1: logger.error(\"Setup invalid: \" + str(out))",
"self.executable) return False out = self.run_(self.testParams) if out[-1].find(self.testCondition) == -1: logger.error(\"Setup invalid: \"",
"= subprocess.check_output ( cmd, shell=True, universal_newlines=True ) out = out.split(\"\\n\") return out def",
"executor except ImportError: import subprocess as executor import os from smodels.tools.externalTool import ExternalTool",
"the path of the source code, for compilation \"\"\" ExternalTool.__init__(self) self.sqrts = int(sqrts)",
"represents the installation of nllfast 7. \"\"\" def __init__(self): ExternalNllFast.__init__(self, 7, \"1.2\", testParams=\"gg",
"sqrts, nllfastVersion, testParams, testCondition): \"\"\" :param sqrts: sqrt of s, in TeV, as",
"invalid: \" + str(out)) return False self.unlink(\"gg\") return True class ExternalNllFast7(ExternalNllFast): \"\"\" An",
"+ url) R = urllib.urlopen(url) l = R.readlines() for line in l: f.write(line)",
"executing it. \"\"\" if not os.path.exists(self.executablePath): logger.error(\"Executable '%s' not found. Maybe you didn't",
"\" \"0.731E+01 0.394E+00\" ) nllFastTools = { 7 : ExternalNllFast7(), 8 : ExternalNllFast8(),",
"__init__(self): ExternalNllFast.__init__(self, 7, \"1.2\", testParams=\"gg cteq 500 600\", testCondition=\"500. 600. 0.193E+00 \" \"0.450E+00",
"def __init__(self, sqrts, nllfastVersion, testParams, testCondition): \"\"\" :param sqrts: sqrt of s, in",
"\"/\") def unlink(self, inputFile): \"\"\" Remove inputFile.out \"\"\" return # fname = \"%s/%s.out\"",
"externalNllFast :synopsis: Wrapper for all nllfast versions. .. moduleauthor:: <NAME> <<EMAIL>> \"\"\" from",
"logger.error(\"Setup invalid: \" + str(out)) return False self.unlink(\"gg\") return True class ExternalNllFast7(ExternalNllFast): \"\"\"",
"of tool is valid by looking for executable and executing it. \"\"\" if",
"\" \\ \"the external tools in smodels/lib?\", self.executablePath) return False if not os.access(self.executablePath,",
"if out[-1].find(self.testCondition) == -1: logger.error(\"Setup invalid: \" + str(out)) return False self.unlink(\"gg\") return",
"urllib.urlopen(url) l = R.readlines() for line in l: f.write(line) R.close() f.close() tar =",
"\"sdcpl\", \"ss\", \"sg\", \"tot\"] if not process in processes: return None if not",
"\"w\") url = \"http://smodels.hephy.at/externaltools/nllfast%d.tar.gz\" \\ % self.sqrts logger.info(\"fetching tarball from \" + url)",
"decoupled :params gluinomass: gluinomass, None if gluino decoupled :returns: stdout and stderr, or",
"commands as executor except ImportError: import subprocess as executor import os from smodels.tools.externalTool",
"\"/nllfast_%dTeV\" % self.sqrts self.testParams = testParams self.testCondition = testCondition self.srcPath = self.cdPath self.executable",
"True def fetch(self): \"\"\" Fetch and unpack tarball. \"\"\" import urllib, tarfile tempfile",
"pdf: cteq=cteq6, mstw2008 :params squarkmass: squarkmass, None if squark decoupled :params gluinomass: gluinomass,",
"python \"\"\" .. module:: externalNllFast :synopsis: Wrapper for all nllfast versions. .. moduleauthor::",
"smodels.tools.externalTool import ExternalTool from smodels.tools.smodelsLogging import logger class ExternalNllFast(ExternalTool): \"\"\" An instance of",
":returns: stdout and stderr, or error message \"\"\" processes = [\"st\", \"sb\", \"gg\",",
":returns: stdout and stderr, or error message \"\"\" cmd = \"cd %s; %s",
"gluino decoupled :returns: stdout and stderr, or error message \"\"\" processes = [\"st\",",
"%s\") % (process, pdf, squarkmass) return self.run_(\"%s %s %s %s\") % \\ (process,",
"\"/\" self.cdPath = self.absPath(location) self.executablePath = self.cdPath + \"/nllfast_%dTeV\" % self.sqrts self.testParams =",
"logger.error(\"%s is not executable\", self.executable) return False out = self.run_(self.testParams) if out[-1].find(self.testCondition) ==",
"[\"st\", \"sb\", \"gg\", \"gdcpl\", \"sdcpl\", \"ss\", \"sg\", \"tot\"] if not process in processes:",
"% (self.cdPath, inputFile) # if os.path.exists(fname): # os.unlink(fname) def run_(self, params): \"\"\" Execute",
"tarfile tempfile = \"/tmp/nllfast7.tar.gz\" f = open(tempfile, \"w\") url = \"http://smodels.hephy.at/externaltools/nllfast%d.tar.gz\" \\ %",
"class represents the installation of nllfast 8. \"\"\" def __init__(self): ExternalNllFast.__init__(self, 13, \"3.1\",",
"\"2.1\", testParams=\"gg cteq 500 600\", testCondition=\"500. 600. 0.406E+00 \" \"0.873E+00 0.953E+00\") class ExternalNllFast13(ExternalNllFast):",
"logger.error(\"Executable '%s' not found. Maybe you didn't compile \" \\ \"the external tools",
"{ 7 : ExternalNllFast7(), 8 : ExternalNllFast8(), 13 : ExternalNllFast13() } if __name__",
"f = open(tempfile, \"w\") url = \"http://smodels.hephy.at/externaltools/nllfast%d.tar.gz\" \\ % self.sqrts logger.info(\"fetching tarball from",
"squarkmass: squarkmass, None if squark decoupled :params gluinomass: gluinomass, None if gluino decoupled",
"or error message \"\"\" cmd = \"cd %s; %s %s\" % (self.cdPath, self.executablePath,",
"testCondition=\"500. 600. 0.193E+00 \" \"0.450E+00 0.497E+00\") class ExternalNllFast8(ExternalNllFast): \"\"\" An instance of this",
"# fname = \"%s/%s.out\" % (self.cdPath, inputFile) # if os.path.exists(fname): # os.unlink(fname) def",
"out = subprocess.check_output ( cmd, shell=True, universal_newlines=True ) logger.info(out) return True def fetch(self):",
"as executor import os from smodels.tools.externalTool import ExternalTool from smodels.tools.smodelsLogging import logger class",
"= executor.getoutput(cmd) # out = subprocess.check_output ( cmd, shell=True, universal_newlines=True ) out =",
"of s, in TeV, as an integer, :param nllfastVersion: version of the nllfast",
"nllfast. :params process: which process: st, sb, gg, gdcpl, sdcpl, ss, sg, tot",
"stderr, or error message \"\"\" processes = [\"st\", \"sb\", \"gg\", \"gdcpl\", \"sdcpl\", \"ss\",",
"l = R.readlines() for line in l: f.write(line) R.close() f.close() tar = tarfile.open(tempfile)",
"self.cdPath self.executable = \"\" def compile(self): \"\"\" Try to compile nllfast. \"\"\" logger.info(\"Trying",
"class represents the installation of nllfast 8. \"\"\" def __init__(self): ExternalNllFast.__init__(self, 8, \"2.1\",",
"\"/tmp/nllfast7.tar.gz\" f = open(tempfile, \"w\") url = \"http://smodels.hephy.at/externaltools/nllfast%d.tar.gz\" \\ % self.sqrts logger.info(\"fetching tarball",
"Remove inputFile.out \"\"\" return # fname = \"%s/%s.out\" % (self.cdPath, inputFile) # if",
"run_(self, params): \"\"\" Execute nllfast7. :params params: parameters used (e.g. gg cteq5 ....",
"self.name = \"nllfast%d\" % sqrts self.nllfastVersion = nllfastVersion path = \"<install>/lib/nllfast/nllfast-\" location =",
"\"\"\" cmd = \"cd %s; %s %s\" % (self.cdPath, self.executablePath, params) out =",
"sqrts: sqrt of s, in TeV, as an integer, :param nllfastVersion: version of",
"error message \"\"\" processes = [\"st\", \"sb\", \"gg\", \"gdcpl\", \"sdcpl\", \"ss\", \"sg\", \"tot\"]",
"not os.access(self.executablePath, os.X_OK): logger.error(\"%s is not executable\", self.executable) return False out = self.run_(self.testParams)",
"processes = [\"st\", \"sb\", \"gg\", \"gdcpl\", \"sdcpl\", \"ss\", \"sg\", \"tot\"] if not process",
"= self.cdPath self.executable = \"\" def compile(self): \"\"\" Try to compile nllfast. \"\"\"",
":params params: parameters used (e.g. gg cteq5 .... ) :returns: stdout and stderr,",
"%s\" % (self.cdPath, self.executablePath, params) out = executor.getoutput(cmd) # out = subprocess.check_output (",
"\"\"\" logger.info(\"Trying to compile %s\", self.name) cmd = \"cd %s; make\" % self.srcPath",
"def run_(self, params): \"\"\" Execute nllfast7. :params params: parameters used (e.g. gg cteq5",
"self.absPath(location) self.executablePath = self.cdPath + \"/nllfast_%dTeV\" % self.sqrts self.testParams = testParams self.testCondition =",
"0.690E+01 \" \"0.731E+01 0.394E+00\" ) nllFastTools = { 7 : ExternalNllFast7(), 8 :",
"in smodels/lib?\", self.executablePath) return False if not os.access(self.executablePath, os.X_OK): logger.error(\"%s is not executable\",",
"8. \"\"\" def __init__(self): ExternalNllFast.__init__(self, 8, \"2.1\", testParams=\"gg cteq 500 600\", testCondition=\"500. 600.",
"the source code, for compilation \"\"\" ExternalTool.__init__(self) self.sqrts = int(sqrts) self.name = \"nllfast%d\"",
"in processes: return None if not pdf in [\"cteq\", \"cteq6\", \"mstw\", \"mstw2008\"]: return",
"from \" + url) R = urllib.urlopen(url) l = R.readlines() for line in",
"is valid by looking for executable and executing it. \"\"\" if not os.path.exists(self.executablePath):",
"the installation of nllfast 7. \"\"\" def __init__(self): ExternalNllFast.__init__(self, 7, \"1.2\", testParams=\"gg cteq",
"ss, sg, tot :params pdf: cteq=cteq6, mstw2008 :params squarkmass: squarkmass, None if squark",
"as an integer, :param nllfastVersion: version of the nllfast tool :param testParams: what",
"testParams: what are the test params we need to run things with? :param",
"gdcpl, sdcpl, ss, sg, tot :params pdf: cteq=cteq6, mstw2008 :params squarkmass: squarkmass, None",
"\"the external tools in smodels/lib?\", self.executablePath) return False if not os.access(self.executablePath, os.X_OK): logger.error(\"%s",
"nllfast. \"\"\" logger.info(\"Trying to compile %s\", self.name) cmd = \"cd %s; make\" %",
"cmd, shell=True, universal_newlines=True ) logger.info(out) return True def fetch(self): \"\"\" Fetch and unpack",
"inputFile): \"\"\" Remove inputFile.out \"\"\" return # fname = \"%s/%s.out\" % (self.cdPath, inputFile)",
"import logger class ExternalNllFast(ExternalTool): \"\"\" An instance of this class represents the installation",
"return None if not squarkmass: return self.run_(\"%s %s %s\") % (process, pdf, gluinomass)",
"try: import commands as executor except ImportError: import subprocess as executor import os",
"l: f.write(line) R.close() f.close() tar = tarfile.open(tempfile) for item in tar: tar.extract(item, self.srcPath",
"ExternalNllFast8(ExternalNllFast): \"\"\" An instance of this class represents the installation of nllfast 8.",
"compile nllfast. \"\"\" logger.info(\"Trying to compile %s\", self.name) cmd = \"cd %s; make\"",
".... ) :returns: stdout and stderr, or error message \"\"\" cmd = \"cd",
"gg cteq5 .... ) :returns: stdout and stderr, or error message \"\"\" cmd",
"%s %s\") % \\ (process, pdf, squarkmass, gluinomass) def checkInstallation(self): \"\"\" Checks if",
"what are the test params we need to run things with? :param testCondition:",
"inputFile.out \"\"\" return # fname = \"%s/%s.out\" % (self.cdPath, inputFile) # if os.path.exists(fname):",
"in tar: tar.extract(item, self.srcPath + \"/\") def unlink(self, inputFile): \"\"\" Remove inputFile.out \"\"\"",
"self.nllfastVersion + \"/\" self.cdPath = self.absPath(location) self.executablePath = self.cdPath + \"/nllfast_%dTeV\" % self.sqrts",
"testParams, testCondition): \"\"\" :param sqrts: sqrt of s, in TeV, as an integer,",
"versions. .. moduleauthor:: <NAME> <<EMAIL>> \"\"\" from __future__ import print_function try: import commands",
"int(sqrts) self.name = \"nllfast%d\" % sqrts self.nllfastVersion = nllfastVersion path = \"<install>/lib/nllfast/nllfast-\" location",
"for all nllfast versions. .. moduleauthor:: <NAME> <<EMAIL>> \"\"\" from __future__ import print_function",
"used (e.g. gg cteq5 .... ) :returns: stdout and stderr, or error message",
"600\", testCondition=\"500. 600. 0.193E+00 \" \"0.450E+00 0.497E+00\") class ExternalNllFast8(ExternalNllFast): \"\"\" An instance of",
"executor.getoutput(cmd) # out = subprocess.check_output ( cmd, shell=True, universal_newlines=True ) out = out.split(\"\\n\")",
"run things with? :param testCondition: the line that should be the last output",
"= [\"st\", \"sb\", \"gg\", \"gdcpl\", \"sdcpl\", \"ss\", \"sg\", \"tot\"] if not process in",
"gluinomass) if not gluinomass: return self.run_(\"%s %s %s\") % (process, pdf, squarkmass) return",
"\\ (process, pdf, squarkmass, gluinomass) def checkInstallation(self): \"\"\" Checks if installation of tool",
"= \"/tmp/nllfast7.tar.gz\" f = open(tempfile, \"w\") url = \"http://smodels.hephy.at/externaltools/nllfast%d.tar.gz\" \\ % self.sqrts logger.info(\"fetching",
"\"\"\" An instance of this class represents the installation of nllfast. \"\"\" def",
"installation of nllfast 8. \"\"\" def __init__(self): ExternalNllFast.__init__(self, 13, \"3.1\", testParams=\"gg cteq 500",
"nllFastTools = { 7 : ExternalNllFast7(), 8 : ExternalNllFast8(), 13 : ExternalNllFast13() }",
"% sqrts self.nllfastVersion = nllfastVersion path = \"<install>/lib/nllfast/nllfast-\" location = path + self.nllfastVersion",
"\\ % self.sqrts logger.info(\"fetching tarball from \" + url) R = urllib.urlopen(url) l",
"0.394E+00\" ) nllFastTools = { 7 : ExternalNllFast7(), 8 : ExternalNllFast8(), 13 :",
") out = out.split(\"\\n\") return out def run(self, process, pdf, squarkmass, gluinomass): \"\"\"",
"stderr, or error message \"\"\" cmd = \"cd %s; %s %s\" % (self.cdPath,",
"= \"cd %s; %s %s\" % (self.cdPath, self.executablePath, params) out = executor.getoutput(cmd) #",
"self.srcPath = self.cdPath self.executable = \"\" def compile(self): \"\"\" Try to compile nllfast.",
"module:: externalNllFast :synopsis: Wrapper for all nllfast versions. .. moduleauthor:: <NAME> <<EMAIL>> \"\"\"",
"testCondition: the line that should be the last output line when running executable",
"self.nllfastVersion = nllfastVersion path = \"<install>/lib/nllfast/nllfast-\" location = path + self.nllfastVersion + \"/\"",
"\"\" def compile(self): \"\"\" Try to compile nllfast. \"\"\" logger.info(\"Trying to compile %s\",",
"to run things with? :param testCondition: the line that should be the last",
"\"\"\" if not os.path.exists(self.executablePath): logger.error(\"Executable '%s' not found. Maybe you didn't compile \"",
"squarkmass: return self.run_(\"%s %s %s\") % (process, pdf, gluinomass) if not gluinomass: return",
"compilation \"\"\" ExternalTool.__init__(self) self.sqrts = int(sqrts) self.name = \"nllfast%d\" % sqrts self.nllfastVersion =",
"cmd, shell=True, universal_newlines=True ) out = out.split(\"\\n\") return out def run(self, process, pdf,",
"gluinomass, None if gluino decoupled :returns: stdout and stderr, or error message \"\"\"",
"pdf, gluinomass) if not gluinomass: return self.run_(\"%s %s %s\") % (process, pdf, squarkmass)",
"the installation of nllfast. \"\"\" def __init__(self, sqrts, nllfastVersion, testParams, testCondition): \"\"\" :param",
"nllfastVersion path = \"<install>/lib/nllfast/nllfast-\" location = path + self.nllfastVersion + \"/\" self.cdPath =",
"by looking for executable and executing it. \"\"\" if not os.path.exists(self.executablePath): logger.error(\"Executable '%s'",
"\"gdcpl\", \"sdcpl\", \"ss\", \"sg\", \"tot\"] if not process in processes: return None if",
"\\ \"the external tools in smodels/lib?\", self.executablePath) return False if not os.access(self.executablePath, os.X_OK):",
"TeV, as an integer, :param nllfastVersion: version of the nllfast tool :param testParams:",
"cmd = \"cd %s; %s %s\" % (self.cdPath, self.executablePath, params) out = executor.getoutput(cmd)",
"return self.run_(\"%s %s %s\") % (process, pdf, squarkmass) return self.run_(\"%s %s %s %s\")",
"self.executablePath) return False if not os.access(self.executablePath, os.X_OK): logger.error(\"%s is not executable\", self.executable) return",
"import os from smodels.tools.externalTool import ExternalTool from smodels.tools.smodelsLogging import logger class ExternalNllFast(ExternalTool): \"\"\"",
"if not squarkmass: return self.run_(\"%s %s %s\") % (process, pdf, gluinomass) if not",
"7 : ExternalNllFast7(), 8 : ExternalNllFast8(), 13 : ExternalNllFast13() } if __name__ ==",
"\"sg\", \"tot\"] if not process in processes: return None if not pdf in",
"error message \"\"\" cmd = \"cd %s; %s %s\" % (self.cdPath, self.executablePath, params)",
"installation of nllfast. \"\"\" def __init__(self, sqrts, nllfastVersion, testParams, testCondition): \"\"\" :param sqrts:",
"things with? :param testCondition: the line that should be the last output line",
"500 600\", testCondition=\"600. 0.394E+01 0.690E+01 \" \"0.731E+01 0.394E+00\" ) nllFastTools = { 7",
"testParams=\"gg cteq 500 600\", testCondition=\"500. 600. 0.406E+00 \" \"0.873E+00 0.953E+00\") class ExternalNllFast13(ExternalNllFast): \"\"\"",
"%s %s\") % (process, pdf, gluinomass) if not gluinomass: return self.run_(\"%s %s %s\")",
"need to run things with? :param testCondition: the line that should be the",
"__init__(self): ExternalNllFast.__init__(self, 13, \"3.1\", testParams=\"gg cteq 500 600\", testCondition=\"600. 0.394E+01 0.690E+01 \" \"0.731E+01",
"= \"\" def compile(self): \"\"\" Try to compile nllfast. \"\"\" logger.info(\"Trying to compile",
"\" \"0.873E+00 0.953E+00\") class ExternalNllFast13(ExternalNllFast): \"\"\" An instance of this class represents the",
"self.executablePath = self.cdPath + \"/nllfast_%dTeV\" % self.sqrts self.testParams = testParams self.testCondition = testCondition",
"self.testCondition = testCondition self.srcPath = self.cdPath self.executable = \"\" def compile(self): \"\"\" Try",
"fetch(self): \"\"\" Fetch and unpack tarball. \"\"\" import urllib, tarfile tempfile = \"/tmp/nllfast7.tar.gz\"",
"self.unlink(\"gg\") return True class ExternalNllFast7(ExternalNllFast): \"\"\" An instance of this class represents the",
"cteq 500 600\", testCondition=\"500. 600. 0.193E+00 \" \"0.450E+00 0.497E+00\") class ExternalNllFast8(ExternalNllFast): \"\"\" An",
"sg, tot :params pdf: cteq=cteq6, mstw2008 :params squarkmass: squarkmass, None if squark decoupled",
"%s\") % (process, pdf, gluinomass) if not gluinomass: return self.run_(\"%s %s %s\") %",
"external tools in smodels/lib?\", self.executablePath) return False if not os.access(self.executablePath, os.X_OK): logger.error(\"%s is",
"[\"cteq\", \"cteq6\", \"mstw\", \"mstw2008\"]: return None if not squarkmass: return self.run_(\"%s %s %s\")",
"self.run_(\"%s %s %s\") % (process, pdf, squarkmass) return self.run_(\"%s %s %s %s\") %",
"in TeV, as an integer, :param nllfastVersion: version of the nllfast tool :param",
"self.run_(\"%s %s %s %s\") % \\ (process, pdf, squarkmass, gluinomass) def checkInstallation(self): \"\"\"",
"class represents the installation of nllfast. \"\"\" def __init__(self, sqrts, nllfastVersion, testParams, testCondition):",
"path = \"<install>/lib/nllfast/nllfast-\" location = path + self.nllfastVersion + \"/\" self.cdPath = self.absPath(location)",
"make\" % self.srcPath out = executor.getoutput(cmd) # out = subprocess.check_output ( cmd, shell=True,",
"for executable and executing it. \"\"\" if not os.path.exists(self.executablePath): logger.error(\"Executable '%s' not found.",
"for line in l: f.write(line) R.close() f.close() tar = tarfile.open(tempfile) for item in",
"found. Maybe you didn't compile \" \\ \"the external tools in smodels/lib?\", self.executablePath)",
"checkInstallation(self): \"\"\" Checks if installation of tool is valid by looking for executable",
"import print_function try: import commands as executor except ImportError: import subprocess as executor",
"None if squark decoupled :params gluinomass: gluinomass, None if gluino decoupled :returns: stdout",
"+ self.nllfastVersion + \"/\" self.cdPath = self.absPath(location) self.executablePath = self.cdPath + \"/nllfast_%dTeV\" %",
"executable\", self.executable) return False out = self.run_(self.testParams) if out[-1].find(self.testCondition) == -1: logger.error(\"Setup invalid:",
"executor import os from smodels.tools.externalTool import ExternalTool from smodels.tools.smodelsLogging import logger class ExternalNllFast(ExternalTool):",
"= out.split(\"\\n\") return out def run(self, process, pdf, squarkmass, gluinomass): \"\"\" Execute nllfast.",
"if os.path.exists(fname): # os.unlink(fname) def run_(self, params): \"\"\" Execute nllfast7. :params params: parameters",
"#!/usr/bin/env python \"\"\" .. module:: externalNllFast :synopsis: Wrapper for all nllfast versions. ..",
"self.srcPath out = executor.getoutput(cmd) # out = subprocess.check_output ( cmd, shell=True, universal_newlines=True )",
"# if os.path.exists(fname): # os.unlink(fname) def run_(self, params): \"\"\" Execute nllfast7. :params params:",
"executor.getoutput(cmd) # out = subprocess.check_output ( cmd, shell=True, universal_newlines=True ) logger.info(out) return True",
"return False if not os.access(self.executablePath, os.X_OK): logger.error(\"%s is not executable\", self.executable) return False",
"None if not pdf in [\"cteq\", \"cteq6\", \"mstw\", \"mstw2008\"]: return None if not",
"line when running executable :srcPath: the path of the source code, for compilation",
"out.split(\"\\n\") return out def run(self, process, pdf, squarkmass, gluinomass): \"\"\" Execute nllfast. :params",
"tar = tarfile.open(tempfile) for item in tar: tar.extract(item, self.srcPath + \"/\") def unlink(self,",
"7. \"\"\" def __init__(self): ExternalNllFast.__init__(self, 7, \"1.2\", testParams=\"gg cteq 500 600\", testCondition=\"500. 600.",
"source code, for compilation \"\"\" ExternalTool.__init__(self) self.sqrts = int(sqrts) self.name = \"nllfast%d\" %",
"self.srcPath + \"/\") def unlink(self, inputFile): \"\"\" Remove inputFile.out \"\"\" return # fname",
"os.access(self.executablePath, os.X_OK): logger.error(\"%s is not executable\", self.executable) return False out = self.run_(self.testParams) if",
"installation of nllfast 7. \"\"\" def __init__(self): ExternalNllFast.__init__(self, 7, \"1.2\", testParams=\"gg cteq 500",
"\"0.873E+00 0.953E+00\") class ExternalNllFast13(ExternalNllFast): \"\"\" An instance of this class represents the installation",
"\"nllfast%d\" % sqrts self.nllfastVersion = nllfastVersion path = \"<install>/lib/nllfast/nllfast-\" location = path +",
"Execute nllfast7. :params params: parameters used (e.g. gg cteq5 .... ) :returns: stdout",
"if squark decoupled :params gluinomass: gluinomass, None if gluino decoupled :returns: stdout and",
"0.953E+00\") class ExternalNllFast13(ExternalNllFast): \"\"\" An instance of this class represents the installation of",
"sqrts self.nllfastVersion = nllfastVersion path = \"<install>/lib/nllfast/nllfast-\" location = path + self.nllfastVersion +",
"= self.absPath(location) self.executablePath = self.cdPath + \"/nllfast_%dTeV\" % self.sqrts self.testParams = testParams self.testCondition",
"class ExternalNllFast(ExternalTool): \"\"\" An instance of this class represents the installation of nllfast.",
"tarball. \"\"\" import urllib, tarfile tempfile = \"/tmp/nllfast7.tar.gz\" f = open(tempfile, \"w\") url",
"and stderr, or error message \"\"\" cmd = \"cd %s; %s %s\" %",
"out[-1].find(self.testCondition) == -1: logger.error(\"Setup invalid: \" + str(out)) return False self.unlink(\"gg\") return True",
"if not process in processes: return None if not pdf in [\"cteq\", \"cteq6\",",
"% (process, pdf, squarkmass) return self.run_(\"%s %s %s %s\") % \\ (process, pdf,",
"installation of nllfast 8. \"\"\" def __init__(self): ExternalNllFast.__init__(self, 8, \"2.1\", testParams=\"gg cteq 500",
"% (self.cdPath, self.executablePath, params) out = executor.getoutput(cmd) # out = subprocess.check_output ( cmd,",
"An instance of this class represents the installation of nllfast 7. \"\"\" def",
": ExternalNllFast8(), 13 : ExternalNllFast13() } if __name__ == \"__main__\": for (sqrts, tool)",
"import ExternalTool from smodels.tools.smodelsLogging import logger class ExternalNllFast(ExternalTool): \"\"\" An instance of this",
"os.path.exists(self.executablePath): logger.error(\"Executable '%s' not found. Maybe you didn't compile \" \\ \"the external",
"def checkInstallation(self): \"\"\" Checks if installation of tool is valid by looking for",
"+ str(out)) return False self.unlink(\"gg\") return True class ExternalNllFast7(ExternalNllFast): \"\"\" An instance of",
"return self.run_(\"%s %s %s\") % (process, pdf, gluinomass) if not gluinomass: return self.run_(\"%s",
"<gh_stars>0 #!/usr/bin/env python \"\"\" .. module:: externalNllFast :synopsis: Wrapper for all nllfast versions.",
"unlink(self, inputFile): \"\"\" Remove inputFile.out \"\"\" return # fname = \"%s/%s.out\" % (self.cdPath,",
"__init__(self): ExternalNllFast.__init__(self, 8, \"2.1\", testParams=\"gg cteq 500 600\", testCondition=\"500. 600. 0.406E+00 \" \"0.873E+00",
"pdf, squarkmass, gluinomass): \"\"\" Execute nllfast. :params process: which process: st, sb, gg,",
"of the nllfast tool :param testParams: what are the test params we need",
"pdf, squarkmass, gluinomass) def checkInstallation(self): \"\"\" Checks if installation of tool is valid",
"squarkmass, gluinomass): \"\"\" Execute nllfast. :params process: which process: st, sb, gg, gdcpl,",
"\"\"\" :param sqrts: sqrt of s, in TeV, as an integer, :param nllfastVersion:",
"R.readlines() for line in l: f.write(line) R.close() f.close() tar = tarfile.open(tempfile) for item",
"None if not squarkmass: return self.run_(\"%s %s %s\") % (process, pdf, gluinomass) if",
"return out def run(self, process, pdf, squarkmass, gluinomass): \"\"\" Execute nllfast. :params process:",
"of this class represents the installation of nllfast 7. \"\"\" def __init__(self): ExternalNllFast.__init__(self,",
"of this class represents the installation of nllfast 8. \"\"\" def __init__(self): ExternalNllFast.__init__(self,",
"cteq=cteq6, mstw2008 :params squarkmass: squarkmass, None if squark decoupled :params gluinomass: gluinomass, None",
"8, \"2.1\", testParams=\"gg cteq 500 600\", testCondition=\"500. 600. 0.406E+00 \" \"0.873E+00 0.953E+00\") class",
"% self.srcPath out = executor.getoutput(cmd) # out = subprocess.check_output ( cmd, shell=True, universal_newlines=True",
"params): \"\"\" Execute nllfast7. :params params: parameters used (e.g. gg cteq5 .... )",
"out = executor.getoutput(cmd) # out = subprocess.check_output ( cmd, shell=True, universal_newlines=True ) logger.info(out)",
"return self.run_(\"%s %s %s %s\") % \\ (process, pdf, squarkmass, gluinomass) def checkInstallation(self):",
"= self.cdPath + \"/nllfast_%dTeV\" % self.sqrts self.testParams = testParams self.testCondition = testCondition self.srcPath",
"shell=True, universal_newlines=True ) logger.info(out) return True def fetch(self): \"\"\" Fetch and unpack tarball.",
"it. \"\"\" if not os.path.exists(self.executablePath): logger.error(\"Executable '%s' not found. Maybe you didn't compile",
"self.cdPath = self.absPath(location) self.executablePath = self.cdPath + \"/nllfast_%dTeV\" % self.sqrts self.testParams = testParams",
"this class represents the installation of nllfast 7. \"\"\" def __init__(self): ExternalNllFast.__init__(self, 7,",
"or error message \"\"\" processes = [\"st\", \"sb\", \"gg\", \"gdcpl\", \"sdcpl\", \"ss\", \"sg\",",
"the installation of nllfast 8. \"\"\" def __init__(self): ExternalNllFast.__init__(self, 8, \"2.1\", testParams=\"gg cteq",
"500 600\", testCondition=\"500. 600. 0.406E+00 \" \"0.873E+00 0.953E+00\") class ExternalNllFast13(ExternalNllFast): \"\"\" An instance",
"self.testParams = testParams self.testCondition = testCondition self.srcPath = self.cdPath self.executable = \"\" def",
"os from smodels.tools.externalTool import ExternalTool from smodels.tools.smodelsLogging import logger class ExternalNllFast(ExternalTool): \"\"\" An",
"instance of this class represents the installation of nllfast 7. \"\"\" def __init__(self):",
"13 : ExternalNllFast13() } if __name__ == \"__main__\": for (sqrts, tool) in nllFastTools.items():",
"<<EMAIL>> \"\"\" from __future__ import print_function try: import commands as executor except ImportError:",
"def fetch(self): \"\"\" Fetch and unpack tarball. \"\"\" import urllib, tarfile tempfile =",
"url = \"http://smodels.hephy.at/externaltools/nllfast%d.tar.gz\" \\ % self.sqrts logger.info(\"fetching tarball from \" + url) R",
"Execute nllfast. :params process: which process: st, sb, gg, gdcpl, sdcpl, ss, sg,",
"the installation of nllfast 8. \"\"\" def __init__(self): ExternalNllFast.__init__(self, 13, \"3.1\", testParams=\"gg cteq",
"tool :param testParams: what are the test params we need to run things",
"def __init__(self): ExternalNllFast.__init__(self, 8, \"2.1\", testParams=\"gg cteq 500 600\", testCondition=\"500. 600. 0.406E+00 \"",
"message \"\"\" cmd = \"cd %s; %s %s\" % (self.cdPath, self.executablePath, params) out",
"squark decoupled :params gluinomass: gluinomass, None if gluino decoupled :returns: stdout and stderr,",
"\"mstw\", \"mstw2008\"]: return None if not squarkmass: return self.run_(\"%s %s %s\") % (process,",
"An instance of this class represents the installation of nllfast. \"\"\" def __init__(self,",
"\"__main__\": for (sqrts, tool) in nllFastTools.items(): print(\"%s: installed in %s\" % (tool.name, tool.installDirectory()))",
"0.406E+00 \" \"0.873E+00 0.953E+00\") class ExternalNllFast13(ExternalNllFast): \"\"\" An instance of this class represents",
"and executing it. \"\"\" if not os.path.exists(self.executablePath): logger.error(\"Executable '%s' not found. Maybe you",
"testCondition=\"500. 600. 0.406E+00 \" \"0.873E+00 0.953E+00\") class ExternalNllFast13(ExternalNllFast): \"\"\" An instance of this",
"% \\ (process, pdf, squarkmass, gluinomass) def checkInstallation(self): \"\"\" Checks if installation of",
"line in l: f.write(line) R.close() f.close() tar = tarfile.open(tempfile) for item in tar:",
"ExternalNllFast7(ExternalNllFast): \"\"\" An instance of this class represents the installation of nllfast 7.",
"= \"%s/%s.out\" % (self.cdPath, inputFile) # if os.path.exists(fname): # os.unlink(fname) def run_(self, params):",
"Checks if installation of tool is valid by looking for executable and executing",
"stdout and stderr, or error message \"\"\" processes = [\"st\", \"sb\", \"gg\", \"gdcpl\",",
"= testParams self.testCondition = testCondition self.srcPath = self.cdPath self.executable = \"\" def compile(self):",
"\"\"\" Remove inputFile.out \"\"\" return # fname = \"%s/%s.out\" % (self.cdPath, inputFile) #",
"nllfast 8. \"\"\" def __init__(self): ExternalNllFast.__init__(self, 13, \"3.1\", testParams=\"gg cteq 500 600\", testCondition=\"600.",
"line that should be the last output line when running executable :srcPath: the",
"# out = subprocess.check_output ( cmd, shell=True, universal_newlines=True ) logger.info(out) return True def",
"'%s' not found. Maybe you didn't compile \" \\ \"the external tools in",
"ExternalNllFast(ExternalTool): \"\"\" An instance of this class represents the installation of nllfast. \"\"\"",
"out = subprocess.check_output ( cmd, shell=True, universal_newlines=True ) out = out.split(\"\\n\") return out",
"tools in smodels/lib?\", self.executablePath) return False if not os.access(self.executablePath, os.X_OK): logger.error(\"%s is not",
":params squarkmass: squarkmass, None if squark decoupled :params gluinomass: gluinomass, None if gluino",
"out = executor.getoutput(cmd) # out = subprocess.check_output ( cmd, shell=True, universal_newlines=True ) out",
"testParams=\"gg cteq 500 600\", testCondition=\"500. 600. 0.193E+00 \" \"0.450E+00 0.497E+00\") class ExternalNllFast8(ExternalNllFast): \"\"\"",
"An instance of this class represents the installation of nllfast 8. \"\"\" def",
"= tarfile.open(tempfile) for item in tar: tar.extract(item, self.srcPath + \"/\") def unlink(self, inputFile):",
"as executor except ImportError: import subprocess as executor import os from smodels.tools.externalTool import",
"= executor.getoutput(cmd) # out = subprocess.check_output ( cmd, shell=True, universal_newlines=True ) logger.info(out) return",
"we need to run things with? :param testCondition: the line that should be",
"13, \"3.1\", testParams=\"gg cteq 500 600\", testCondition=\"600. 0.394E+01 0.690E+01 \" \"0.731E+01 0.394E+00\" )",
"subprocess.check_output ( cmd, shell=True, universal_newlines=True ) out = out.split(\"\\n\") return out def run(self,",
"False self.unlink(\"gg\") return True class ExternalNllFast7(ExternalNllFast): \"\"\" An instance of this class represents",
"not os.path.exists(self.executablePath): logger.error(\"Executable '%s' not found. Maybe you didn't compile \" \\ \"the",
"item in tar: tar.extract(item, self.srcPath + \"/\") def unlink(self, inputFile): \"\"\" Remove inputFile.out",
") :returns: stdout and stderr, or error message \"\"\" cmd = \"cd %s;",
"class represents the installation of nllfast 7. \"\"\" def __init__(self): ExternalNllFast.__init__(self, 7, \"1.2\",",
"\"\"\" def __init__(self, sqrts, nllfastVersion, testParams, testCondition): \"\"\" :param sqrts: sqrt of s,",
": ExternalNllFast13() } if __name__ == \"__main__\": for (sqrts, tool) in nllFastTools.items(): print(\"%s:",
"not gluinomass: return self.run_(\"%s %s %s\") % (process, pdf, squarkmass) return self.run_(\"%s %s",
"this class represents the installation of nllfast. \"\"\" def __init__(self, sqrts, nllfastVersion, testParams,",
"= urllib.urlopen(url) l = R.readlines() for line in l: f.write(line) R.close() f.close() tar",
"fname = \"%s/%s.out\" % (self.cdPath, inputFile) # if os.path.exists(fname): # os.unlink(fname) def run_(self,",
"looking for executable and executing it. \"\"\" if not os.path.exists(self.executablePath): logger.error(\"Executable '%s' not",
"\"\"\" Fetch and unpack tarball. \"\"\" import urllib, tarfile tempfile = \"/tmp/nllfast7.tar.gz\" f",
"class ExternalNllFast8(ExternalNllFast): \"\"\" An instance of this class represents the installation of nllfast",
"of nllfast. \"\"\" def __init__(self, sqrts, nllfastVersion, testParams, testCondition): \"\"\" :param sqrts: sqrt",
"moduleauthor:: <NAME> <<EMAIL>> \"\"\" from __future__ import print_function try: import commands as executor",
"\"\"\" Execute nllfast7. :params params: parameters used (e.g. gg cteq5 .... ) :returns:",
"to compile nllfast. \"\"\" logger.info(\"Trying to compile %s\", self.name) cmd = \"cd %s;",
"nllfastVersion, testParams, testCondition): \"\"\" :param sqrts: sqrt of s, in TeV, as an",
"True class ExternalNllFast7(ExternalNllFast): \"\"\" An instance of this class represents the installation of",
"logger class ExternalNllFast(ExternalTool): \"\"\" An instance of this class represents the installation of",
"when running executable :srcPath: the path of the source code, for compilation \"\"\"",
"of this class represents the installation of nllfast. \"\"\" def __init__(self, sqrts, nllfastVersion,",
"( cmd, shell=True, universal_newlines=True ) out = out.split(\"\\n\") return out def run(self, process,",
"class ExternalNllFast13(ExternalNllFast): \"\"\" An instance of this class represents the installation of nllfast",
"cteq 500 600\", testCondition=\"600. 0.394E+01 0.690E+01 \" \"0.731E+01 0.394E+00\" ) nllFastTools = {",
"decoupled :returns: stdout and stderr, or error message \"\"\" processes = [\"st\", \"sb\",",
"__name__ == \"__main__\": for (sqrts, tool) in nllFastTools.items(): print(\"%s: installed in %s\" %",
"(process, pdf, squarkmass, gluinomass) def checkInstallation(self): \"\"\" Checks if installation of tool is",
"instance of this class represents the installation of nllfast 8. \"\"\" def __init__(self):",
"\"\"\" Checks if installation of tool is valid by looking for executable and",
"output line when running executable :srcPath: the path of the source code, for",
"500 600\", testCondition=\"500. 600. 0.193E+00 \" \"0.450E+00 0.497E+00\") class ExternalNllFast8(ExternalNllFast): \"\"\" An instance",
"600. 0.406E+00 \" \"0.873E+00 0.953E+00\") class ExternalNllFast13(ExternalNllFast): \"\"\" An instance of this class",
"% (process, pdf, gluinomass) if not gluinomass: return self.run_(\"%s %s %s\") % (process,",
"return False out = self.run_(self.testParams) if out[-1].find(self.testCondition) == -1: logger.error(\"Setup invalid: \" +",
"self.name) cmd = \"cd %s; make\" % self.srcPath out = executor.getoutput(cmd) # out",
"class ExternalNllFast7(ExternalNllFast): \"\"\" An instance of this class represents the installation of nllfast",
"%s\") % \\ (process, pdf, squarkmass, gluinomass) def checkInstallation(self): \"\"\" Checks if installation",
"the last output line when running executable :srcPath: the path of the source",
":srcPath: the path of the source code, for compilation \"\"\" ExternalTool.__init__(self) self.sqrts =",
"process in processes: return None if not pdf in [\"cteq\", \"cteq6\", \"mstw\", \"mstw2008\"]:",
"if installation of tool is valid by looking for executable and executing it.",
"pdf in [\"cteq\", \"cteq6\", \"mstw\", \"mstw2008\"]: return None if not squarkmass: return self.run_(\"%s",
"= \"<install>/lib/nllfast/nllfast-\" location = path + self.nllfastVersion + \"/\" self.cdPath = self.absPath(location) self.executablePath",
"are the test params we need to run things with? :param testCondition: the",
"\" + str(out)) return False self.unlink(\"gg\") return True class ExternalNllFast7(ExternalNllFast): \"\"\" An instance",
"(e.g. gg cteq5 .... ) :returns: stdout and stderr, or error message \"\"\"",
"this class represents the installation of nllfast 8. \"\"\" def __init__(self): ExternalNllFast.__init__(self, 13,",
"(process, pdf, gluinomass) if not gluinomass: return self.run_(\"%s %s %s\") % (process, pdf,",
"<NAME> <<EMAIL>> \"\"\" from __future__ import print_function try: import commands as executor except",
") logger.info(out) return True def fetch(self): \"\"\" Fetch and unpack tarball. \"\"\" import",
"gluinomass): \"\"\" Execute nllfast. :params process: which process: st, sb, gg, gdcpl, sdcpl,",
"nllfast 7. \"\"\" def __init__(self): ExternalNllFast.__init__(self, 7, \"1.2\", testParams=\"gg cteq 500 600\", testCondition=\"500.",
"if not gluinomass: return self.run_(\"%s %s %s\") % (process, pdf, squarkmass) return self.run_(\"%s",
"ExternalNllFast.__init__(self, 8, \"2.1\", testParams=\"gg cteq 500 600\", testCondition=\"500. 600. 0.406E+00 \" \"0.873E+00 0.953E+00\")",
"instance of this class represents the installation of nllfast. \"\"\" def __init__(self, sqrts,",
"test params we need to run things with? :param testCondition: the line that",
"nllfast 8. \"\"\" def __init__(self): ExternalNllFast.__init__(self, 8, \"2.1\", testParams=\"gg cteq 500 600\", testCondition=\"500.",
"process: st, sb, gg, gdcpl, sdcpl, ss, sg, tot :params pdf: cteq=cteq6, mstw2008",
"\"cteq6\", \"mstw\", \"mstw2008\"]: return None if not squarkmass: return self.run_(\"%s %s %s\") %",
"600\", testCondition=\"600. 0.394E+01 0.690E+01 \" \"0.731E+01 0.394E+00\" ) nllFastTools = { 7 :",
"path + self.nllfastVersion + \"/\" self.cdPath = self.absPath(location) self.executablePath = self.cdPath + \"/nllfast_%dTeV\"",
"cteq5 .... ) :returns: stdout and stderr, or error message \"\"\" cmd =",
"unpack tarball. \"\"\" import urllib, tarfile tempfile = \"/tmp/nllfast7.tar.gz\" f = open(tempfile, \"w\")",
": ExternalNllFast7(), 8 : ExternalNllFast8(), 13 : ExternalNllFast13() } if __name__ == \"__main__\":",
"\"\"\" ExternalTool.__init__(self) self.sqrts = int(sqrts) self.name = \"nllfast%d\" % sqrts self.nllfastVersion = nllfastVersion",
"return # fname = \"%s/%s.out\" % (self.cdPath, inputFile) # if os.path.exists(fname): # os.unlink(fname)",
"ExternalNllFast8(), 13 : ExternalNllFast13() } if __name__ == \"__main__\": for (sqrts, tool) in",
"squarkmass, gluinomass) def checkInstallation(self): \"\"\" Checks if installation of tool is valid by",
"if not os.path.exists(self.executablePath): logger.error(\"Executable '%s' not found. Maybe you didn't compile \" \\",
"ExternalNllFast.__init__(self, 7, \"1.2\", testParams=\"gg cteq 500 600\", testCondition=\"500. 600. 0.193E+00 \" \"0.450E+00 0.497E+00\")",
"out = out.split(\"\\n\") return out def run(self, process, pdf, squarkmass, gluinomass): \"\"\" Execute",
"ImportError: import subprocess as executor import os from smodels.tools.externalTool import ExternalTool from smodels.tools.smodelsLogging",
"tar: tar.extract(item, self.srcPath + \"/\") def unlink(self, inputFile): \"\"\" Remove inputFile.out \"\"\" return",
"return True class ExternalNllFast7(ExternalNllFast): \"\"\" An instance of this class represents the installation",
"subprocess.check_output ( cmd, shell=True, universal_newlines=True ) logger.info(out) return True def fetch(self): \"\"\" Fetch",
"\"0.731E+01 0.394E+00\" ) nllFastTools = { 7 : ExternalNllFast7(), 8 : ExternalNllFast8(), 13",
"\"http://smodels.hephy.at/externaltools/nllfast%d.tar.gz\" \\ % self.sqrts logger.info(\"fetching tarball from \" + url) R = urllib.urlopen(url)",
"params we need to run things with? :param testCondition: the line that should",
"not process in processes: return None if not pdf in [\"cteq\", \"cteq6\", \"mstw\",",
".. moduleauthor:: <NAME> <<EMAIL>> \"\"\" from __future__ import print_function try: import commands as",
"tar.extract(item, self.srcPath + \"/\") def unlink(self, inputFile): \"\"\" Remove inputFile.out \"\"\" return #",
"\"\"\" def __init__(self): ExternalNllFast.__init__(self, 7, \"1.2\", testParams=\"gg cteq 500 600\", testCondition=\"500. 600. 0.193E+00",
"cteq 500 600\", testCondition=\"500. 600. 0.406E+00 \" \"0.873E+00 0.953E+00\") class ExternalNllFast13(ExternalNllFast): \"\"\" An",
":params gluinomass: gluinomass, None if gluino decoupled :returns: stdout and stderr, or error",
"nllfast tool :param testParams: what are the test params we need to run",
"\"\"\" from __future__ import print_function try: import commands as executor except ImportError: import",
"(process, pdf, squarkmass) return self.run_(\"%s %s %s %s\") % \\ (process, pdf, squarkmass,",
"should be the last output line when running executable :srcPath: the path of",
"self.run_(\"%s %s %s\") % (process, pdf, gluinomass) if not gluinomass: return self.run_(\"%s %s",
"f.write(line) R.close() f.close() tar = tarfile.open(tempfile) for item in tar: tar.extract(item, self.srcPath +",
"\"\"\" def __init__(self): ExternalNllFast.__init__(self, 8, \"2.1\", testParams=\"gg cteq 500 600\", testCondition=\"500. 600. 0.406E+00",
"= nllfastVersion path = \"<install>/lib/nllfast/nllfast-\" location = path + self.nllfastVersion + \"/\" self.cdPath",
"600\", testCondition=\"500. 600. 0.406E+00 \" \"0.873E+00 0.953E+00\") class ExternalNllFast13(ExternalNllFast): \"\"\" An instance of",
"squarkmass) return self.run_(\"%s %s %s %s\") % \\ (process, pdf, squarkmass, gluinomass) def",
"if __name__ == \"__main__\": for (sqrts, tool) in nllFastTools.items(): print(\"%s: installed in %s\"",
"(self.cdPath, inputFile) # if os.path.exists(fname): # os.unlink(fname) def run_(self, params): \"\"\" Execute nllfast7.",
"+ \"/\" self.cdPath = self.absPath(location) self.executablePath = self.cdPath + \"/nllfast_%dTeV\" % self.sqrts self.testParams",
"nllfastVersion: version of the nllfast tool :param testParams: what are the test params",
"self.executable = \"\" def compile(self): \"\"\" Try to compile nllfast. \"\"\" logger.info(\"Trying to",
"and stderr, or error message \"\"\" processes = [\"st\", \"sb\", \"gg\", \"gdcpl\", \"sdcpl\",",
"running executable :srcPath: the path of the source code, for compilation \"\"\" ExternalTool.__init__(self)",
".. module:: externalNllFast :synopsis: Wrapper for all nllfast versions. .. moduleauthor:: <NAME> <<EMAIL>>",
"== \"__main__\": for (sqrts, tool) in nllFastTools.items(): print(\"%s: installed in %s\" % (tool.name,",
"urllib, tarfile tempfile = \"/tmp/nllfast7.tar.gz\" f = open(tempfile, \"w\") url = \"http://smodels.hephy.at/externaltools/nllfast%d.tar.gz\" \\",
"out def run(self, process, pdf, squarkmass, gluinomass): \"\"\" Execute nllfast. :params process: which",
"== -1: logger.error(\"Setup invalid: \" + str(out)) return False self.unlink(\"gg\") return True class",
"code, for compilation \"\"\" ExternalTool.__init__(self) self.sqrts = int(sqrts) self.name = \"nllfast%d\" % sqrts",
"except ImportError: import subprocess as executor import os from smodels.tools.externalTool import ExternalTool from",
"gluinomass) def checkInstallation(self): \"\"\" Checks if installation of tool is valid by looking",
"return True def fetch(self): \"\"\" Fetch and unpack tarball. \"\"\" import urllib, tarfile",
"tarball from \" + url) R = urllib.urlopen(url) l = R.readlines() for line",
"cmd = \"cd %s; make\" % self.srcPath out = executor.getoutput(cmd) # out =",
"from smodels.tools.smodelsLogging import logger class ExternalNllFast(ExternalTool): \"\"\" An instance of this class represents",
"run(self, process, pdf, squarkmass, gluinomass): \"\"\" Execute nllfast. :params process: which process: st,",
"(self.cdPath, self.executablePath, params) out = executor.getoutput(cmd) # out = subprocess.check_output ( cmd, shell=True,",
":param testParams: what are the test params we need to run things with?",
"-1: logger.error(\"Setup invalid: \" + str(out)) return False self.unlink(\"gg\") return True class ExternalNllFast7(ExternalNllFast):",
"\"cd %s; make\" % self.srcPath out = executor.getoutput(cmd) # out = subprocess.check_output (",
"path of the source code, for compilation \"\"\" ExternalTool.__init__(self) self.sqrts = int(sqrts) self.name",
"import urllib, tarfile tempfile = \"/tmp/nllfast7.tar.gz\" f = open(tempfile, \"w\") url = \"http://smodels.hephy.at/externaltools/nllfast%d.tar.gz\"",
"%s %s\") % (process, pdf, squarkmass) return self.run_(\"%s %s %s %s\") % \\",
"R.close() f.close() tar = tarfile.open(tempfile) for item in tar: tar.extract(item, self.srcPath + \"/\")",
"# out = subprocess.check_output ( cmd, shell=True, universal_newlines=True ) out = out.split(\"\\n\") return",
"def __init__(self): ExternalNllFast.__init__(self, 13, \"3.1\", testParams=\"gg cteq 500 600\", testCondition=\"600. 0.394E+01 0.690E+01 \"",
"ExternalNllFast7(), 8 : ExternalNllFast8(), 13 : ExternalNllFast13() } if __name__ == \"__main__\": for",
"tarfile.open(tempfile) for item in tar: tar.extract(item, self.srcPath + \"/\") def unlink(self, inputFile): \"\"\"",
"smodels.tools.smodelsLogging import logger class ExternalNllFast(ExternalTool): \"\"\" An instance of this class represents the",
"\"\"\" Try to compile nllfast. \"\"\" logger.info(\"Trying to compile %s\", self.name) cmd =",
"not executable\", self.executable) return False out = self.run_(self.testParams) if out[-1].find(self.testCondition) == -1: logger.error(\"Setup",
"params: parameters used (e.g. gg cteq5 .... ) :returns: stdout and stderr, or",
"executable :srcPath: the path of the source code, for compilation \"\"\" ExternalTool.__init__(self) self.sqrts",
"testCondition=\"600. 0.394E+01 0.690E+01 \" \"0.731E+01 0.394E+00\" ) nllFastTools = { 7 : ExternalNllFast7(),",
"be the last output line when running executable :srcPath: the path of the",
"an integer, :param nllfastVersion: version of the nllfast tool :param testParams: what are",
"nllfast7. :params params: parameters used (e.g. gg cteq5 .... ) :returns: stdout and",
"sb, gg, gdcpl, sdcpl, ss, sg, tot :params pdf: cteq=cteq6, mstw2008 :params squarkmass:",
"self.sqrts = int(sqrts) self.name = \"nllfast%d\" % sqrts self.nllfastVersion = nllfastVersion path =",
"url) R = urllib.urlopen(url) l = R.readlines() for line in l: f.write(line) R.close()",
"Fetch and unpack tarball. \"\"\" import urllib, tarfile tempfile = \"/tmp/nllfast7.tar.gz\" f =",
"universal_newlines=True ) out = out.split(\"\\n\") return out def run(self, process, pdf, squarkmass, gluinomass):",
"process, pdf, squarkmass, gluinomass): \"\"\" Execute nllfast. :params process: which process: st, sb,",
"sdcpl, ss, sg, tot :params pdf: cteq=cteq6, mstw2008 :params squarkmass: squarkmass, None if",
"ExternalNllFast13() } if __name__ == \"__main__\": for (sqrts, tool) in nllFastTools.items(): print(\"%s: installed",
"8. \"\"\" def __init__(self): ExternalNllFast.__init__(self, 13, \"3.1\", testParams=\"gg cteq 500 600\", testCondition=\"600. 0.394E+01",
"s, in TeV, as an integer, :param nllfastVersion: version of the nllfast tool",
"\"\"\" An instance of this class represents the installation of nllfast 7. \"\"\"",
"ExternalTool.__init__(self) self.sqrts = int(sqrts) self.name = \"nllfast%d\" % sqrts self.nllfastVersion = nllfastVersion path",
"None if gluino decoupled :returns: stdout and stderr, or error message \"\"\" processes",
"\"\"\" processes = [\"st\", \"sb\", \"gg\", \"gdcpl\", \"sdcpl\", \"ss\", \"sg\", \"tot\"] if not",
"represents the installation of nllfast 8. \"\"\" def __init__(self): ExternalNllFast.__init__(self, 13, \"3.1\", testParams=\"gg",
"version of the nllfast tool :param testParams: what are the test params we",
"= \"nllfast%d\" % sqrts self.nllfastVersion = nllfastVersion path = \"<install>/lib/nllfast/nllfast-\" location = path",
"%s %s\" % (self.cdPath, self.executablePath, params) out = executor.getoutput(cmd) # out = subprocess.check_output",
"logger.info(\"Trying to compile %s\", self.name) cmd = \"cd %s; make\" % self.srcPath out",
"\"sb\", \"gg\", \"gdcpl\", \"sdcpl\", \"ss\", \"sg\", \"tot\"] if not process in processes: return",
"# os.unlink(fname) def run_(self, params): \"\"\" Execute nllfast7. :params params: parameters used (e.g.",
"of nllfast 7. \"\"\" def __init__(self): ExternalNllFast.__init__(self, 7, \"1.2\", testParams=\"gg cteq 500 600\",",
"ExternalNllFast.__init__(self, 13, \"3.1\", testParams=\"gg cteq 500 600\", testCondition=\"600. 0.394E+01 0.690E+01 \" \"0.731E+01 0.394E+00\"",
":param sqrts: sqrt of s, in TeV, as an integer, :param nllfastVersion: version",
"print_function try: import commands as executor except ImportError: import subprocess as executor import",
"in l: f.write(line) R.close() f.close() tar = tarfile.open(tempfile) for item in tar: tar.extract(item,",
"testCondition self.srcPath = self.cdPath self.executable = \"\" def compile(self): \"\"\" Try to compile",
"__init__(self, sqrts, nllfastVersion, testParams, testCondition): \"\"\" :param sqrts: sqrt of s, in TeV,",
":param nllfastVersion: version of the nllfast tool :param testParams: what are the test",
"%s %s %s\") % \\ (process, pdf, squarkmass, gluinomass) def checkInstallation(self): \"\"\" Checks",
"\"\"\" .. module:: externalNllFast :synopsis: Wrapper for all nllfast versions. .. moduleauthor:: <NAME>",
":params process: which process: st, sb, gg, gdcpl, sdcpl, ss, sg, tot :params",
"integer, :param nllfastVersion: version of the nllfast tool :param testParams: what are the",
"\"\"\" import urllib, tarfile tempfile = \"/tmp/nllfast7.tar.gz\" f = open(tempfile, \"w\") url =",
"not squarkmass: return self.run_(\"%s %s %s\") % (process, pdf, gluinomass) if not gluinomass:",
"the line that should be the last output line when running executable :srcPath:",
"def run(self, process, pdf, squarkmass, gluinomass): \"\"\" Execute nllfast. :params process: which process:",
"nllfast. \"\"\" def __init__(self, sqrts, nllfastVersion, testParams, testCondition): \"\"\" :param sqrts: sqrt of",
"of the source code, for compilation \"\"\" ExternalTool.__init__(self) self.sqrts = int(sqrts) self.name =",
"smodels/lib?\", self.executablePath) return False if not os.access(self.executablePath, os.X_OK): logger.error(\"%s is not executable\", self.executable)",
"0.193E+00 \" \"0.450E+00 0.497E+00\") class ExternalNllFast8(ExternalNllFast): \"\"\" An instance of this class represents",
"0.497E+00\") class ExternalNllFast8(ExternalNllFast): \"\"\" An instance of this class represents the installation of",
"params) out = executor.getoutput(cmd) # out = subprocess.check_output ( cmd, shell=True, universal_newlines=True )",
"\"ss\", \"sg\", \"tot\"] if not process in processes: return None if not pdf",
"8 : ExternalNllFast8(), 13 : ExternalNllFast13() } if __name__ == \"__main__\": for (sqrts,",
"return None if not pdf in [\"cteq\", \"cteq6\", \"mstw\", \"mstw2008\"]: return None if",
"and unpack tarball. \"\"\" import urllib, tarfile tempfile = \"/tmp/nllfast7.tar.gz\" f = open(tempfile,",
"% self.sqrts logger.info(\"fetching tarball from \" + url) R = urllib.urlopen(url) l =",
"installation of tool is valid by looking for executable and executing it. \"\"\"",
"0.394E+01 0.690E+01 \" \"0.731E+01 0.394E+00\" ) nllFastTools = { 7 : ExternalNllFast7(), 8",
"gluinomass: return self.run_(\"%s %s %s\") % (process, pdf, squarkmass) return self.run_(\"%s %s %s",
"7, \"1.2\", testParams=\"gg cteq 500 600\", testCondition=\"500. 600. 0.193E+00 \" \"0.450E+00 0.497E+00\") class",
"\"<install>/lib/nllfast/nllfast-\" location = path + self.nllfastVersion + \"/\" self.cdPath = self.absPath(location) self.executablePath =",
"\"\"\" Execute nllfast. :params process: which process: st, sb, gg, gdcpl, sdcpl, ss,",
"compile %s\", self.name) cmd = \"cd %s; make\" % self.srcPath out = executor.getoutput(cmd)",
"= testCondition self.srcPath = self.cdPath self.executable = \"\" def compile(self): \"\"\" Try to",
"%s; make\" % self.srcPath out = executor.getoutput(cmd) # out = subprocess.check_output ( cmd,",
"processes: return None if not pdf in [\"cteq\", \"cteq6\", \"mstw\", \"mstw2008\"]: return None",
"tot :params pdf: cteq=cteq6, mstw2008 :params squarkmass: squarkmass, None if squark decoupled :params",
"testCondition): \"\"\" :param sqrts: sqrt of s, in TeV, as an integer, :param",
"of nllfast 8. \"\"\" def __init__(self): ExternalNllFast.__init__(self, 13, \"3.1\", testParams=\"gg cteq 500 600\",",
"} if __name__ == \"__main__\": for (sqrts, tool) in nllFastTools.items(): print(\"%s: installed in",
"self.sqrts logger.info(\"fetching tarball from \" + url) R = urllib.urlopen(url) l = R.readlines()",
"tool is valid by looking for executable and executing it. \"\"\" if not",
"%s\", self.name) cmd = \"cd %s; make\" % self.srcPath out = executor.getoutput(cmd) #",
"gluinomass: gluinomass, None if gluino decoupled :returns: stdout and stderr, or error message",
"is not executable\", self.executable) return False out = self.run_(self.testParams) if out[-1].find(self.testCondition) == -1:",
"os.unlink(fname) def run_(self, params): \"\"\" Execute nllfast7. :params params: parameters used (e.g. gg",
"\"mstw2008\"]: return None if not squarkmass: return self.run_(\"%s %s %s\") % (process, pdf,"
] |
[] |
[
"On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python",
"NotificationGroup, ModuleCompliance = mibBuilder.importSymbols(\"SNMPv2-CONF\", \"NotificationGroup\", \"ModuleCompliance\") Bits, Counter64, Gauge32, ObjectIdentity, Counter32, NotificationType, IpAddress,",
"= mibBuilder.importSymbols(\"ASN1-ENUMERATION\", \"NamedValues\") SingleValueConstraint, ConstraintsIntersection, ValueSizeConstraint, ConstraintsUnion, ValueRangeConstraint = mibBuilder.importSymbols(\"ASN1-REFINEMENT\", \"SingleValueConstraint\", \"ConstraintsIntersection\", \"ValueSizeConstraint\",",
"\"ValueSizeConstraint\", \"ConstraintsUnion\", \"ValueRangeConstraint\") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols(\"SNMPv2-CONF\", \"NotificationGroup\", \"ModuleCompliance\") Bits, Counter64, Gauge32, ObjectIdentity,",
"NotificationType((1, 3, 6, 1, 4, 1, 6101, 2500, 251, 1)) if mibBuilder.loadTexts: oppOn.setStatus('current')",
"6, 1, 4, 1, 6101, 2500, 1), Integer32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: nvwScanCurrConn.setStatus('mandatory') nvwScanCurrMem =",
"= NotificationType((1, 3, 6, 1, 4, 1, 6101, 2500, 251, 5)) if mibBuilder.loadTexts:",
"mibBuilder.loadTexts: oppOn.setStatus('current') oppOff = NotificationType((1, 3, 6, 1, 4, 1, 6101, 2500, 251,",
"user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) #",
"2500, 251, 5)) if mibBuilder.loadTexts: haFailover.setStatus('current') mibBuilder.exportSymbols(\"TRENDMICRO-NVW-MIB\", nvwPolicyCurrConn=nvwPolicyCurrConn, nvwScanCurrMem=nvwScanCurrMem, oppOn=oppOn, bootFactory=bootFactory, nvwTraps=nvwTraps, oppOff=oppOff,",
"6101, 2500, 251, 5)) if mibBuilder.loadTexts: haFailover.setStatus('current') mibBuilder.exportSymbols(\"TRENDMICRO-NVW-MIB\", nvwPolicyCurrConn=nvwPolicyCurrConn, nvwScanCurrMem=nvwScanCurrMem, oppOn=oppOn, bootFactory=bootFactory, nvwTraps=nvwTraps,",
"\"IpAddress\", \"iso\", \"ModuleIdentity\", \"Unsigned32\", \"MibIdentifier\", \"MibScalar\", \"MibTable\", \"MibTableRow\", \"MibTableColumn\", \"TimeTicks\", \"Integer32\") TextualConvention, DisplayString",
"2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 #",
"\"NamedValues\") SingleValueConstraint, ConstraintsIntersection, ValueSizeConstraint, ConstraintsUnion, ValueRangeConstraint = mibBuilder.importSymbols(\"ASN1-REFINEMENT\", \"SingleValueConstraint\", \"ConstraintsIntersection\", \"ValueSizeConstraint\", \"ConstraintsUnion\", \"ValueRangeConstraint\")",
"if mibBuilder.loadTexts: nvwScanCurrMem.setStatus('mandatory') nvwPolicyCurrConn = MibScalar((1, 3, 6, 1, 4, 1, 6101, 2500,",
"6, 1, 4, 1, 6101, 2500, 3), Integer32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: nvwPolicyCurrConn.setStatus('mandatory') nvwTraps =",
"mibBuilder.importSymbols(\"SNMPv2-CONF\", \"NotificationGroup\", \"ModuleCompliance\") Bits, Counter64, Gauge32, ObjectIdentity, Counter32, NotificationType, IpAddress, iso, ModuleIdentity, Unsigned32,",
"Mar 27 2019, 09:23:15) # ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols(\"ASN1\", \"ObjectIdentifier\", \"OctetString\", \"Integer\")",
"MibTable, MibTableRow, MibTableColumn, TimeTicks, Integer32 = mibBuilder.importSymbols(\"SNMPv2-SMI\", \"Bits\", \"Counter64\", \"Gauge32\", \"ObjectIdentity\", \"Counter32\", \"NotificationType\",",
"1, 4, 1, 6101, 2500, 1), Integer32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: nvwScanCurrConn.setStatus('mandatory') nvwScanCurrMem = MibScalar((1,",
"2500, 251, 2)) if mibBuilder.loadTexts: oppOff.setStatus('current') bootFactory = NotificationType((1, 3, 6, 1, 4,",
"Bits, Counter64, Gauge32, ObjectIdentity, Counter32, NotificationType, IpAddress, iso, ModuleIdentity, Unsigned32, MibIdentifier, MibScalar, MibTable,",
"6, 1, 4, 1, 6101, 2500, 251, 5)) if mibBuilder.loadTexts: haFailover.setStatus('current') mibBuilder.exportSymbols(\"TRENDMICRO-NVW-MIB\", nvwPolicyCurrConn=nvwPolicyCurrConn,",
"\"Bits\", \"Counter64\", \"Gauge32\", \"ObjectIdentity\", \"Counter32\", \"NotificationType\", \"IpAddress\", \"iso\", \"ModuleIdentity\", \"Unsigned32\", \"MibIdentifier\", \"MibScalar\", \"MibTable\",",
"\"Integer\") NamedValues, = mibBuilder.importSymbols(\"ASN1-ENUMERATION\", \"NamedValues\") SingleValueConstraint, ConstraintsIntersection, ValueSizeConstraint, ConstraintsUnion, ValueRangeConstraint = mibBuilder.importSymbols(\"ASN1-REFINEMENT\", \"SingleValueConstraint\",",
"MibTableRow, MibTableColumn, TimeTicks, Integer32 = mibBuilder.importSymbols(\"SNMPv2-SMI\", \"Bits\", \"Counter64\", \"Gauge32\", \"ObjectIdentity\", \"Counter32\", \"NotificationType\", \"IpAddress\",",
"1, 6101, 2500, 251, 2)) if mibBuilder.loadTexts: oppOff.setStatus('current') bootFactory = NotificationType((1, 3, 6,",
"3, 6, 1, 4, 1, 6101, 2500, 251, 3)) if mibBuilder.loadTexts: bootFactory.setStatus('current') bootPrevious",
"1, 4, 1, 6101, 2500, 251)) oppOn = NotificationType((1, 3, 6, 1, 4,",
"mibBuilder.loadTexts: oppOff.setStatus('current') bootFactory = NotificationType((1, 3, 6, 1, 4, 1, 6101, 2500, 251,",
"mibBuilder.loadTexts: nvwScanCurrMem.setStatus('mandatory') nvwPolicyCurrConn = MibScalar((1, 3, 6, 1, 4, 1, 6101, 2500, 3),",
"TextualConvention, DisplayString = mibBuilder.importSymbols(\"SNMPv2-TC\", \"TextualConvention\", \"DisplayString\") tmNVW, = mibBuilder.importSymbols(\"TRENDMICRO-SMI\", \"tmNVW\") nvwScanCurrConn = MibScalar((1,",
"# Produced by pysmi-0.3.4 at Mon Apr 29 21:20:11 2019 # On host",
"3, 6, 1, 4, 1, 6101, 2500, 251, 4)) if mibBuilder.loadTexts: bootPrevious.setStatus('current') haFailover",
"= NotificationType((1, 3, 6, 1, 4, 1, 6101, 2500, 251, 1)) if mibBuilder.loadTexts:",
"version 3.7.3 (default, Mar 27 2019, 09:23:15) # ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols(\"ASN1\",",
"\"NotificationGroup\", \"ModuleCompliance\") Bits, Counter64, Gauge32, ObjectIdentity, Counter32, NotificationType, IpAddress, iso, ModuleIdentity, Unsigned32, MibIdentifier,",
"\"Integer32\") TextualConvention, DisplayString = mibBuilder.importSymbols(\"SNMPv2-TC\", \"TextualConvention\", \"DisplayString\") tmNVW, = mibBuilder.importSymbols(\"TRENDMICRO-SMI\", \"tmNVW\") nvwScanCurrConn =",
"1, 6101, 2500, 1), Integer32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: nvwScanCurrConn.setStatus('mandatory') nvwScanCurrMem = MibScalar((1, 3, 6,",
"1, 4, 1, 6101, 2500, 251, 3)) if mibBuilder.loadTexts: bootFactory.setStatus('current') bootPrevious = NotificationType((1,",
"\"ObjectIdentifier\", \"OctetString\", \"Integer\") NamedValues, = mibBuilder.importSymbols(\"ASN1-ENUMERATION\", \"NamedValues\") SingleValueConstraint, ConstraintsIntersection, ValueSizeConstraint, ConstraintsUnion, ValueRangeConstraint =",
"nvwPolicyCurrConn.setStatus('mandatory') nvwTraps = MibIdentifier((1, 3, 6, 1, 4, 1, 6101, 2500, 251)) oppOn",
"= mibBuilder.importSymbols(\"TRENDMICRO-SMI\", \"tmNVW\") nvwScanCurrConn = MibScalar((1, 3, 6, 1, 4, 1, 6101, 2500,",
"mibBuilder.loadTexts: nvwScanCurrConn.setStatus('mandatory') nvwScanCurrMem = MibScalar((1, 3, 6, 1, 4, 1, 6101, 2500, 2),",
"= NotificationType((1, 3, 6, 1, 4, 1, 6101, 2500, 251, 2)) if mibBuilder.loadTexts:",
"18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019,",
"3), Integer32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: nvwPolicyCurrConn.setStatus('mandatory') nvwTraps = MibIdentifier((1, 3, 6, 1, 4, 1,",
"1, 4, 1, 6101, 2500, 251, 1)) if mibBuilder.loadTexts: oppOn.setStatus('current') oppOff = NotificationType((1,",
"1, 6101, 2500, 251, 1)) if mibBuilder.loadTexts: oppOn.setStatus('current') oppOff = NotificationType((1, 3, 6,",
"IpAddress, iso, ModuleIdentity, Unsigned32, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, Integer32 = mibBuilder.importSymbols(\"SNMPv2-SMI\",",
"ConstraintsUnion, ValueRangeConstraint = mibBuilder.importSymbols(\"ASN1-REFINEMENT\", \"SingleValueConstraint\", \"ConstraintsIntersection\", \"ValueSizeConstraint\", \"ConstraintsUnion\", \"ValueRangeConstraint\") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols(\"SNMPv2-CONF\",",
"at Mon Apr 29 21:20:11 2019 # On host DAVWANG4-M-1475 platform Darwin version",
"(http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TRENDMICRO-NVW-MIB # Produced by pysmi-0.3.4 at Mon Apr 29",
"Mon Apr 29 21:20:11 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0",
"4, 1, 6101, 2500, 251, 4)) if mibBuilder.loadTexts: bootPrevious.setStatus('current') haFailover = NotificationType((1, 3,",
"\"iso\", \"ModuleIdentity\", \"Unsigned32\", \"MibIdentifier\", \"MibScalar\", \"MibTable\", \"MibTableRow\", \"MibTableColumn\", \"TimeTicks\", \"Integer32\") TextualConvention, DisplayString =",
"6101, 2500, 1), Integer32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: nvwScanCurrConn.setStatus('mandatory') nvwScanCurrMem = MibScalar((1, 3, 6, 1,",
"nvwScanCurrMem.setStatus('mandatory') nvwPolicyCurrConn = MibScalar((1, 3, 6, 1, 4, 1, 6101, 2500, 3), Integer32()).setMaxAccess(\"readonly\")",
"oppOff = NotificationType((1, 3, 6, 1, 4, 1, 6101, 2500, 251, 2)) if",
"Integer = mibBuilder.importSymbols(\"ASN1\", \"ObjectIdentifier\", \"OctetString\", \"Integer\") NamedValues, = mibBuilder.importSymbols(\"ASN1-ENUMERATION\", \"NamedValues\") SingleValueConstraint, ConstraintsIntersection, ValueSizeConstraint,",
"ModuleCompliance = mibBuilder.importSymbols(\"SNMPv2-CONF\", \"NotificationGroup\", \"ModuleCompliance\") Bits, Counter64, Gauge32, ObjectIdentity, Counter32, NotificationType, IpAddress, iso,",
"6101, 2500, 251)) oppOn = NotificationType((1, 3, 6, 1, 4, 1, 6101, 2500,",
"2500, 2), Integer32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: nvwScanCurrMem.setStatus('mandatory') nvwPolicyCurrConn = MibScalar((1, 3, 6, 1, 4,",
"if mibBuilder.loadTexts: haFailover.setStatus('current') mibBuilder.exportSymbols(\"TRENDMICRO-NVW-MIB\", nvwPolicyCurrConn=nvwPolicyCurrConn, nvwScanCurrMem=nvwScanCurrMem, oppOn=oppOn, bootFactory=bootFactory, nvwTraps=nvwTraps, oppOff=oppOff, bootPrevious=bootPrevious, nvwScanCurrConn=nvwScanCurrConn, haFailover=haFailover)",
"nvwScanCurrMem = MibScalar((1, 3, 6, 1, 4, 1, 6101, 2500, 2), Integer32()).setMaxAccess(\"readonly\") if",
"Gauge32, ObjectIdentity, Counter32, NotificationType, IpAddress, iso, ModuleIdentity, Unsigned32, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn,",
"6, 1, 4, 1, 6101, 2500, 251)) oppOn = NotificationType((1, 3, 6, 1,",
"= mibBuilder.importSymbols(\"ASN1-REFINEMENT\", \"SingleValueConstraint\", \"ConstraintsIntersection\", \"ValueSizeConstraint\", \"ConstraintsUnion\", \"ValueRangeConstraint\") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols(\"SNMPv2-CONF\", \"NotificationGroup\", \"ModuleCompliance\")",
"2500, 3), Integer32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: nvwPolicyCurrConn.setStatus('mandatory') nvwTraps = MibIdentifier((1, 3, 6, 1, 4,",
"1, 4, 1, 6101, 2500, 251, 2)) if mibBuilder.loadTexts: oppOff.setStatus('current') bootFactory = NotificationType((1,",
"if mibBuilder.loadTexts: bootFactory.setStatus('current') bootPrevious = NotificationType((1, 3, 6, 1, 4, 1, 6101, 2500,",
"\"ConstraintsUnion\", \"ValueRangeConstraint\") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols(\"SNMPv2-CONF\", \"NotificationGroup\", \"ModuleCompliance\") Bits, Counter64, Gauge32, ObjectIdentity, Counter32,",
"\"ValueRangeConstraint\") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols(\"SNMPv2-CONF\", \"NotificationGroup\", \"ModuleCompliance\") Bits, Counter64, Gauge32, ObjectIdentity, Counter32, NotificationType,",
"oppOn = NotificationType((1, 3, 6, 1, 4, 1, 6101, 2500, 251, 1)) if",
"251, 1)) if mibBuilder.loadTexts: oppOn.setStatus('current') oppOff = NotificationType((1, 3, 6, 1, 4, 1,",
"mibBuilder.importSymbols(\"ASN1\", \"ObjectIdentifier\", \"OctetString\", \"Integer\") NamedValues, = mibBuilder.importSymbols(\"ASN1-ENUMERATION\", \"NamedValues\") SingleValueConstraint, ConstraintsIntersection, ValueSizeConstraint, ConstraintsUnion, ValueRangeConstraint",
"if mibBuilder.loadTexts: nvwScanCurrConn.setStatus('mandatory') nvwScanCurrMem = MibScalar((1, 3, 6, 1, 4, 1, 6101, 2500,",
"1, 6101, 2500, 2), Integer32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: nvwScanCurrMem.setStatus('mandatory') nvwPolicyCurrConn = MibScalar((1, 3, 6,",
"mibBuilder.loadTexts: nvwPolicyCurrConn.setStatus('mandatory') nvwTraps = MibIdentifier((1, 3, 6, 1, 4, 1, 6101, 2500, 251))",
"if mibBuilder.loadTexts: oppOn.setStatus('current') oppOff = NotificationType((1, 3, 6, 1, 4, 1, 6101, 2500,",
"4, 1, 6101, 2500, 251)) oppOn = NotificationType((1, 3, 6, 1, 4, 1,",
"oppOff.setStatus('current') bootFactory = NotificationType((1, 3, 6, 1, 4, 1, 6101, 2500, 251, 3))",
"4, 1, 6101, 2500, 251, 5)) if mibBuilder.loadTexts: haFailover.setStatus('current') mibBuilder.exportSymbols(\"TRENDMICRO-NVW-MIB\", nvwPolicyCurrConn=nvwPolicyCurrConn, nvwScanCurrMem=nvwScanCurrMem, oppOn=oppOn,",
"4, 1, 6101, 2500, 251, 1)) if mibBuilder.loadTexts: oppOn.setStatus('current') oppOff = NotificationType((1, 3,",
"mibBuilder.loadTexts: bootFactory.setStatus('current') bootPrevious = NotificationType((1, 3, 6, 1, 4, 1, 6101, 2500, 251,",
"\"TextualConvention\", \"DisplayString\") tmNVW, = mibBuilder.importSymbols(\"TRENDMICRO-SMI\", \"tmNVW\") nvwScanCurrConn = MibScalar((1, 3, 6, 1, 4,",
"NotificationType((1, 3, 6, 1, 4, 1, 6101, 2500, 251, 2)) if mibBuilder.loadTexts: oppOff.setStatus('current')",
"ValueRangeConstraint = mibBuilder.importSymbols(\"ASN1-REFINEMENT\", \"SingleValueConstraint\", \"ConstraintsIntersection\", \"ValueSizeConstraint\", \"ConstraintsUnion\", \"ValueRangeConstraint\") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols(\"SNMPv2-CONF\", \"NotificationGroup\",",
"source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TRENDMICRO-NVW-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 21:20:11 2019 #",
"\"SingleValueConstraint\", \"ConstraintsIntersection\", \"ValueSizeConstraint\", \"ConstraintsUnion\", \"ValueRangeConstraint\") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols(\"SNMPv2-CONF\", \"NotificationGroup\", \"ModuleCompliance\") Bits, Counter64,",
"27 2019, 09:23:15) # ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols(\"ASN1\", \"ObjectIdentifier\", \"OctetString\", \"Integer\") NamedValues,",
"\"ModuleCompliance\") Bits, Counter64, Gauge32, ObjectIdentity, Counter32, NotificationType, IpAddress, iso, ModuleIdentity, Unsigned32, MibIdentifier, MibScalar,",
"\"MibIdentifier\", \"MibScalar\", \"MibTable\", \"MibTableRow\", \"MibTableColumn\", \"TimeTicks\", \"Integer32\") TextualConvention, DisplayString = mibBuilder.importSymbols(\"SNMPv2-TC\", \"TextualConvention\", \"DisplayString\")",
"1, 4, 1, 6101, 2500, 3), Integer32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: nvwPolicyCurrConn.setStatus('mandatory') nvwTraps = MibIdentifier((1,",
"3, 6, 1, 4, 1, 6101, 2500, 3), Integer32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: nvwPolicyCurrConn.setStatus('mandatory') nvwTraps",
"1, 6101, 2500, 3), Integer32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: nvwPolicyCurrConn.setStatus('mandatory') nvwTraps = MibIdentifier((1, 3, 6,",
"251)) oppOn = NotificationType((1, 3, 6, 1, 4, 1, 6101, 2500, 251, 1))",
"tmNVW, = mibBuilder.importSymbols(\"TRENDMICRO-SMI\", \"tmNVW\") nvwScanCurrConn = MibScalar((1, 3, 6, 1, 4, 1, 6101,",
"host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version",
"by pysmi-0.3.4 at Mon Apr 29 21:20:11 2019 # On host DAVWANG4-M-1475 platform",
"Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # ObjectIdentifier, OctetString, Integer",
"mibBuilder.importSymbols(\"ASN1-REFINEMENT\", \"SingleValueConstraint\", \"ConstraintsIntersection\", \"ValueSizeConstraint\", \"ConstraintsUnion\", \"ValueRangeConstraint\") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols(\"SNMPv2-CONF\", \"NotificationGroup\", \"ModuleCompliance\") Bits,",
"\"OctetString\", \"Integer\") NamedValues, = mibBuilder.importSymbols(\"ASN1-ENUMERATION\", \"NamedValues\") SingleValueConstraint, ConstraintsIntersection, ValueSizeConstraint, ConstraintsUnion, ValueRangeConstraint = mibBuilder.importSymbols(\"ASN1-REFINEMENT\",",
"\"Counter64\", \"Gauge32\", \"ObjectIdentity\", \"Counter32\", \"NotificationType\", \"IpAddress\", \"iso\", \"ModuleIdentity\", \"Unsigned32\", \"MibIdentifier\", \"MibScalar\", \"MibTable\", \"MibTableRow\",",
"1, 6101, 2500, 251)) oppOn = NotificationType((1, 3, 6, 1, 4, 1, 6101,",
"bootFactory.setStatus('current') bootPrevious = NotificationType((1, 3, 6, 1, 4, 1, 6101, 2500, 251, 4))",
"1, 4, 1, 6101, 2500, 251, 5)) if mibBuilder.loadTexts: haFailover.setStatus('current') mibBuilder.exportSymbols(\"TRENDMICRO-NVW-MIB\", nvwPolicyCurrConn=nvwPolicyCurrConn, nvwScanCurrMem=nvwScanCurrMem,",
"Counter64, Gauge32, ObjectIdentity, Counter32, NotificationType, IpAddress, iso, ModuleIdentity, Unsigned32, MibIdentifier, MibScalar, MibTable, MibTableRow,",
"ConstraintsIntersection, ValueSizeConstraint, ConstraintsUnion, ValueRangeConstraint = mibBuilder.importSymbols(\"ASN1-REFINEMENT\", \"SingleValueConstraint\", \"ConstraintsIntersection\", \"ValueSizeConstraint\", \"ConstraintsUnion\", \"ValueRangeConstraint\") NotificationGroup, ModuleCompliance",
"mibBuilder.importSymbols(\"SNMPv2-SMI\", \"Bits\", \"Counter64\", \"Gauge32\", \"ObjectIdentity\", \"Counter32\", \"NotificationType\", \"IpAddress\", \"iso\", \"ModuleIdentity\", \"Unsigned32\", \"MibIdentifier\", \"MibScalar\",",
"= MibScalar((1, 3, 6, 1, 4, 1, 6101, 2500, 2), Integer32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts:",
"5)) if mibBuilder.loadTexts: haFailover.setStatus('current') mibBuilder.exportSymbols(\"TRENDMICRO-NVW-MIB\", nvwPolicyCurrConn=nvwPolicyCurrConn, nvwScanCurrMem=nvwScanCurrMem, oppOn=oppOn, bootFactory=bootFactory, nvwTraps=nvwTraps, oppOff=oppOff, bootPrevious=bootPrevious, nvwScanCurrConn=nvwScanCurrConn,",
"\"Unsigned32\", \"MibIdentifier\", \"MibScalar\", \"MibTable\", \"MibTableRow\", \"MibTableColumn\", \"TimeTicks\", \"Integer32\") TextualConvention, DisplayString = mibBuilder.importSymbols(\"SNMPv2-TC\", \"TextualConvention\",",
"Unsigned32, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, Integer32 = mibBuilder.importSymbols(\"SNMPv2-SMI\", \"Bits\", \"Counter64\", \"Gauge32\",",
"\"NotificationType\", \"IpAddress\", \"iso\", \"ModuleIdentity\", \"Unsigned32\", \"MibIdentifier\", \"MibScalar\", \"MibTable\", \"MibTableRow\", \"MibTableColumn\", \"TimeTicks\", \"Integer32\") TextualConvention,",
"MibScalar((1, 3, 6, 1, 4, 1, 6101, 2500, 1), Integer32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: nvwScanCurrConn.setStatus('mandatory')",
"MibIdentifier((1, 3, 6, 1, 4, 1, 6101, 2500, 251)) oppOn = NotificationType((1, 3,",
"4, 1, 6101, 2500, 2), Integer32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: nvwScanCurrMem.setStatus('mandatory') nvwPolicyCurrConn = MibScalar((1, 3,",
"6, 1, 4, 1, 6101, 2500, 251, 2)) if mibBuilder.loadTexts: oppOff.setStatus('current') bootFactory =",
"09:23:15) # ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols(\"ASN1\", \"ObjectIdentifier\", \"OctetString\", \"Integer\") NamedValues, = mibBuilder.importSymbols(\"ASN1-ENUMERATION\",",
"3)) if mibBuilder.loadTexts: bootFactory.setStatus('current') bootPrevious = NotificationType((1, 3, 6, 1, 4, 1, 6101,",
"Integer32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: nvwScanCurrConn.setStatus('mandatory') nvwScanCurrMem = MibScalar((1, 3, 6, 1, 4, 1, 6101,",
"mibBuilder.loadTexts: bootPrevious.setStatus('current') haFailover = NotificationType((1, 3, 6, 1, 4, 1, 6101, 2500, 251,",
"251, 3)) if mibBuilder.loadTexts: bootFactory.setStatus('current') bootPrevious = NotificationType((1, 3, 6, 1, 4, 1,",
"mibBuilder.importSymbols(\"ASN1-ENUMERATION\", \"NamedValues\") SingleValueConstraint, ConstraintsIntersection, ValueSizeConstraint, ConstraintsUnion, ValueRangeConstraint = mibBuilder.importSymbols(\"ASN1-REFINEMENT\", \"SingleValueConstraint\", \"ConstraintsIntersection\", \"ValueSizeConstraint\", \"ConstraintsUnion\",",
"iso, ModuleIdentity, Unsigned32, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, Integer32 = mibBuilder.importSymbols(\"SNMPv2-SMI\", \"Bits\",",
"ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TRENDMICRO-NVW-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 21:20:11 2019",
"platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default,",
"1), Integer32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: nvwScanCurrConn.setStatus('mandatory') nvwScanCurrMem = MibScalar((1, 3, 6, 1, 4, 1,",
"1, 6101, 2500, 251, 4)) if mibBuilder.loadTexts: bootPrevious.setStatus('current') haFailover = NotificationType((1, 3, 6,",
"2500, 251, 3)) if mibBuilder.loadTexts: bootFactory.setStatus('current') bootPrevious = NotificationType((1, 3, 6, 1, 4,",
"= mibBuilder.importSymbols(\"SNMPv2-TC\", \"TextualConvention\", \"DisplayString\") tmNVW, = mibBuilder.importSymbols(\"TRENDMICRO-SMI\", \"tmNVW\") nvwScanCurrConn = MibScalar((1, 3, 6,",
"if mibBuilder.loadTexts: bootPrevious.setStatus('current') haFailover = NotificationType((1, 3, 6, 1, 4, 1, 6101, 2500,",
"Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar",
"21:20:11 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4",
"bootFactory = NotificationType((1, 3, 6, 1, 4, 1, 6101, 2500, 251, 3)) if",
"\"DisplayString\") tmNVW, = mibBuilder.importSymbols(\"TRENDMICRO-SMI\", \"tmNVW\") nvwScanCurrConn = MibScalar((1, 3, 6, 1, 4, 1,",
"\"tmNVW\") nvwScanCurrConn = MibScalar((1, 3, 6, 1, 4, 1, 6101, 2500, 1), Integer32()).setMaxAccess(\"readonly\")",
"bootPrevious.setStatus('current') haFailover = NotificationType((1, 3, 6, 1, 4, 1, 6101, 2500, 251, 5))",
"2)) if mibBuilder.loadTexts: oppOff.setStatus('current') bootFactory = NotificationType((1, 3, 6, 1, 4, 1, 6101,",
"2), Integer32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: nvwScanCurrMem.setStatus('mandatory') nvwPolicyCurrConn = MibScalar((1, 3, 6, 1, 4, 1,",
"= MibScalar((1, 3, 6, 1, 4, 1, 6101, 2500, 3), Integer32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts:",
"davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # ObjectIdentifier,",
"3.7.3 (default, Mar 27 2019, 09:23:15) # ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols(\"ASN1\", \"ObjectIdentifier\",",
"251, 4)) if mibBuilder.loadTexts: bootPrevious.setStatus('current') haFailover = NotificationType((1, 3, 6, 1, 4, 1,",
"NotificationType((1, 3, 6, 1, 4, 1, 6101, 2500, 251, 5)) if mibBuilder.loadTexts: haFailover.setStatus('current')",
"3, 6, 1, 4, 1, 6101, 2500, 251, 5)) if mibBuilder.loadTexts: haFailover.setStatus('current') mibBuilder.exportSymbols(\"TRENDMICRO-NVW-MIB\",",
"1, 4, 1, 6101, 2500, 251, 4)) if mibBuilder.loadTexts: bootPrevious.setStatus('current') haFailover = NotificationType((1,",
"= mibBuilder.importSymbols(\"SNMPv2-SMI\", \"Bits\", \"Counter64\", \"Gauge32\", \"ObjectIdentity\", \"Counter32\", \"NotificationType\", \"IpAddress\", \"iso\", \"ModuleIdentity\", \"Unsigned32\", \"MibIdentifier\",",
"1)) if mibBuilder.loadTexts: oppOn.setStatus('current') oppOff = NotificationType((1, 3, 6, 1, 4, 1, 6101,",
"2500, 251)) oppOn = NotificationType((1, 3, 6, 1, 4, 1, 6101, 2500, 251,",
"(default, Mar 27 2019, 09:23:15) # ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols(\"ASN1\", \"ObjectIdentifier\", \"OctetString\",",
"MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, Integer32 = mibBuilder.importSymbols(\"SNMPv2-SMI\", \"Bits\", \"Counter64\", \"Gauge32\", \"ObjectIdentity\", \"Counter32\",",
"TimeTicks, Integer32 = mibBuilder.importSymbols(\"SNMPv2-SMI\", \"Bits\", \"Counter64\", \"Gauge32\", \"ObjectIdentity\", \"Counter32\", \"NotificationType\", \"IpAddress\", \"iso\", \"ModuleIdentity\",",
"\"ObjectIdentity\", \"Counter32\", \"NotificationType\", \"IpAddress\", \"iso\", \"ModuleIdentity\", \"Unsigned32\", \"MibIdentifier\", \"MibScalar\", \"MibTable\", \"MibTableRow\", \"MibTableColumn\", \"TimeTicks\",",
"6, 1, 4, 1, 6101, 2500, 2), Integer32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: nvwScanCurrMem.setStatus('mandatory') nvwPolicyCurrConn =",
"haFailover = NotificationType((1, 3, 6, 1, 4, 1, 6101, 2500, 251, 5)) if",
"= mibBuilder.importSymbols(\"SNMPv2-CONF\", \"NotificationGroup\", \"ModuleCompliance\") Bits, Counter64, Gauge32, ObjectIdentity, Counter32, NotificationType, IpAddress, iso, ModuleIdentity,",
"NamedValues, = mibBuilder.importSymbols(\"ASN1-ENUMERATION\", \"NamedValues\") SingleValueConstraint, ConstraintsIntersection, ValueSizeConstraint, ConstraintsUnion, ValueRangeConstraint = mibBuilder.importSymbols(\"ASN1-REFINEMENT\", \"SingleValueConstraint\", \"ConstraintsIntersection\",",
"MibScalar((1, 3, 6, 1, 4, 1, 6101, 2500, 2), Integer32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: nvwScanCurrMem.setStatus('mandatory')",
"Integer32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: nvwPolicyCurrConn.setStatus('mandatory') nvwTraps = MibIdentifier((1, 3, 6, 1, 4, 1, 6101,",
"version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27",
"Produced by pysmi-0.3.4 at Mon Apr 29 21:20:11 2019 # On host DAVWANG4-M-1475",
"MibScalar((1, 3, 6, 1, 4, 1, 6101, 2500, 3), Integer32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: nvwPolicyCurrConn.setStatus('mandatory')",
"3, 6, 1, 4, 1, 6101, 2500, 251)) oppOn = NotificationType((1, 3, 6,",
"mibBuilder.importSymbols(\"TRENDMICRO-SMI\", \"tmNVW\") nvwScanCurrConn = MibScalar((1, 3, 6, 1, 4, 1, 6101, 2500, 1),",
"NotificationType((1, 3, 6, 1, 4, 1, 6101, 2500, 251, 4)) if mibBuilder.loadTexts: bootPrevious.setStatus('current')",
"OctetString, Integer = mibBuilder.importSymbols(\"ASN1\", \"ObjectIdentifier\", \"OctetString\", \"Integer\") NamedValues, = mibBuilder.importSymbols(\"ASN1-ENUMERATION\", \"NamedValues\") SingleValueConstraint, ConstraintsIntersection,",
"SingleValueConstraint, ConstraintsIntersection, ValueSizeConstraint, ConstraintsUnion, ValueRangeConstraint = mibBuilder.importSymbols(\"ASN1-REFINEMENT\", \"SingleValueConstraint\", \"ConstraintsIntersection\", \"ValueSizeConstraint\", \"ConstraintsUnion\", \"ValueRangeConstraint\") NotificationGroup,",
"3, 6, 1, 4, 1, 6101, 2500, 251, 2)) if mibBuilder.loadTexts: oppOff.setStatus('current') bootFactory",
"if mibBuilder.loadTexts: oppOff.setStatus('current') bootFactory = NotificationType((1, 3, 6, 1, 4, 1, 6101, 2500,",
"Apr 29 21:20:11 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by",
"oppOn.setStatus('current') oppOff = NotificationType((1, 3, 6, 1, 4, 1, 6101, 2500, 251, 2))",
"pysmi-0.3.4 at Mon Apr 29 21:20:11 2019 # On host DAVWANG4-M-1475 platform Darwin",
"\"Gauge32\", \"ObjectIdentity\", \"Counter32\", \"NotificationType\", \"IpAddress\", \"iso\", \"ModuleIdentity\", \"Unsigned32\", \"MibIdentifier\", \"MibScalar\", \"MibTable\", \"MibTableRow\", \"MibTableColumn\",",
"= MibScalar((1, 3, 6, 1, 4, 1, 6101, 2500, 1), Integer32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts:",
"4, 1, 6101, 2500, 3), Integer32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: nvwPolicyCurrConn.setStatus('mandatory') nvwTraps = MibIdentifier((1, 3,",
"nvwTraps = MibIdentifier((1, 3, 6, 1, 4, 1, 6101, 2500, 251)) oppOn =",
"6101, 2500, 3), Integer32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: nvwPolicyCurrConn.setStatus('mandatory') nvwTraps = MibIdentifier((1, 3, 6, 1,",
"1, 4, 1, 6101, 2500, 2), Integer32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: nvwScanCurrMem.setStatus('mandatory') nvwPolicyCurrConn = MibScalar((1,",
"\"MibTableColumn\", \"TimeTicks\", \"Integer32\") TextualConvention, DisplayString = mibBuilder.importSymbols(\"SNMPv2-TC\", \"TextualConvention\", \"DisplayString\") tmNVW, = mibBuilder.importSymbols(\"TRENDMICRO-SMI\", \"tmNVW\")",
"\"MibScalar\", \"MibTable\", \"MibTableRow\", \"MibTableColumn\", \"TimeTicks\", \"Integer32\") TextualConvention, DisplayString = mibBuilder.importSymbols(\"SNMPv2-TC\", \"TextualConvention\", \"DisplayString\") tmNVW,",
"3, 6, 1, 4, 1, 6101, 2500, 2), Integer32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: nvwScanCurrMem.setStatus('mandatory') nvwPolicyCurrConn",
"ValueSizeConstraint, ConstraintsUnion, ValueRangeConstraint = mibBuilder.importSymbols(\"ASN1-REFINEMENT\", \"SingleValueConstraint\", \"ConstraintsIntersection\", \"ValueSizeConstraint\", \"ConstraintsUnion\", \"ValueRangeConstraint\") NotificationGroup, ModuleCompliance =",
"ObjectIdentity, Counter32, NotificationType, IpAddress, iso, ModuleIdentity, Unsigned32, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks,",
"nvwScanCurrConn.setStatus('mandatory') nvwScanCurrMem = MibScalar((1, 3, 6, 1, 4, 1, 6101, 2500, 2), Integer32()).setMaxAccess(\"readonly\")",
"251, 5)) if mibBuilder.loadTexts: haFailover.setStatus('current') mibBuilder.exportSymbols(\"TRENDMICRO-NVW-MIB\", nvwPolicyCurrConn=nvwPolicyCurrConn, nvwScanCurrMem=nvwScanCurrMem, oppOn=oppOn, bootFactory=bootFactory, nvwTraps=nvwTraps, oppOff=oppOff, bootPrevious=bootPrevious,",
"MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, Integer32 = mibBuilder.importSymbols(\"SNMPv2-SMI\", \"Bits\", \"Counter64\", \"Gauge32\", \"ObjectIdentity\",",
"file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TRENDMICRO-NVW-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 21:20:11 2019 # On",
"# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TRENDMICRO-NVW-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 21:20:11",
"ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols(\"ASN1\", \"ObjectIdentifier\", \"OctetString\", \"Integer\") NamedValues, = mibBuilder.importSymbols(\"ASN1-ENUMERATION\", \"NamedValues\") SingleValueConstraint,",
"MibTableColumn, TimeTicks, Integer32 = mibBuilder.importSymbols(\"SNMPv2-SMI\", \"Bits\", \"Counter64\", \"Gauge32\", \"ObjectIdentity\", \"Counter32\", \"NotificationType\", \"IpAddress\", \"iso\",",
"# # PySNMP MIB module TRENDMICRO-NVW-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TRENDMICRO-NVW-MIB # Produced",
"# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using",
"mibBuilder.importSymbols(\"SNMPv2-TC\", \"TextualConvention\", \"DisplayString\") tmNVW, = mibBuilder.importSymbols(\"TRENDMICRO-SMI\", \"tmNVW\") nvwScanCurrConn = MibScalar((1, 3, 6, 1,",
"2500, 251, 1)) if mibBuilder.loadTexts: oppOn.setStatus('current') oppOff = NotificationType((1, 3, 6, 1, 4,",
"6101, 2500, 2), Integer32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: nvwScanCurrMem.setStatus('mandatory') nvwPolicyCurrConn = MibScalar((1, 3, 6, 1,",
"6, 1, 4, 1, 6101, 2500, 251, 1)) if mibBuilder.loadTexts: oppOn.setStatus('current') oppOff =",
"# ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols(\"ASN1\", \"ObjectIdentifier\", \"OctetString\", \"Integer\") NamedValues, = mibBuilder.importSymbols(\"ASN1-ENUMERATION\", \"NamedValues\")",
"\"MibTable\", \"MibTableRow\", \"MibTableColumn\", \"TimeTicks\", \"Integer32\") TextualConvention, DisplayString = mibBuilder.importSymbols(\"SNMPv2-TC\", \"TextualConvention\", \"DisplayString\") tmNVW, =",
"2019, 09:23:15) # ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols(\"ASN1\", \"ObjectIdentifier\", \"OctetString\", \"Integer\") NamedValues, =",
"DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3",
"\"ModuleIdentity\", \"Unsigned32\", \"MibIdentifier\", \"MibScalar\", \"MibTable\", \"MibTableRow\", \"MibTableColumn\", \"TimeTicks\", \"Integer32\") TextualConvention, DisplayString = mibBuilder.importSymbols(\"SNMPv2-TC\",",
"6101, 2500, 251, 1)) if mibBuilder.loadTexts: oppOn.setStatus('current') oppOff = NotificationType((1, 3, 6, 1,",
"= NotificationType((1, 3, 6, 1, 4, 1, 6101, 2500, 251, 4)) if mibBuilder.loadTexts:",
"ModuleIdentity, Unsigned32, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, Integer32 = mibBuilder.importSymbols(\"SNMPv2-SMI\", \"Bits\", \"Counter64\",",
"6, 1, 4, 1, 6101, 2500, 251, 3)) if mibBuilder.loadTexts: bootFactory.setStatus('current') bootPrevious =",
"\"ConstraintsIntersection\", \"ValueSizeConstraint\", \"ConstraintsUnion\", \"ValueRangeConstraint\") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols(\"SNMPv2-CONF\", \"NotificationGroup\", \"ModuleCompliance\") Bits, Counter64, Gauge32,",
"6101, 2500, 251, 2)) if mibBuilder.loadTexts: oppOff.setStatus('current') bootFactory = NotificationType((1, 3, 6, 1,",
"# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # ObjectIdentifier, OctetString,",
"6101, 2500, 251, 4)) if mibBuilder.loadTexts: bootPrevious.setStatus('current') haFailover = NotificationType((1, 3, 6, 1,",
"2500, 251, 4)) if mibBuilder.loadTexts: bootPrevious.setStatus('current') haFailover = NotificationType((1, 3, 6, 1, 4,",
"= mibBuilder.importSymbols(\"ASN1\", \"ObjectIdentifier\", \"OctetString\", \"Integer\") NamedValues, = mibBuilder.importSymbols(\"ASN1-ENUMERATION\", \"NamedValues\") SingleValueConstraint, ConstraintsIntersection, ValueSizeConstraint, ConstraintsUnion,",
"3, 6, 1, 4, 1, 6101, 2500, 251, 1)) if mibBuilder.loadTexts: oppOn.setStatus('current') oppOff",
"NotificationType, IpAddress, iso, ModuleIdentity, Unsigned32, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, Integer32 =",
"Integer32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: nvwScanCurrMem.setStatus('mandatory') nvwPolicyCurrConn = MibScalar((1, 3, 6, 1, 4, 1, 6101,",
"= MibIdentifier((1, 3, 6, 1, 4, 1, 6101, 2500, 251)) oppOn = NotificationType((1,",
"4, 1, 6101, 2500, 251, 3)) if mibBuilder.loadTexts: bootFactory.setStatus('current') bootPrevious = NotificationType((1, 3,",
"Counter32, NotificationType, IpAddress, iso, ModuleIdentity, Unsigned32, MibIdentifier, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, Integer32",
"6, 1, 4, 1, 6101, 2500, 251, 4)) if mibBuilder.loadTexts: bootPrevious.setStatus('current') haFailover =",
"bootPrevious = NotificationType((1, 3, 6, 1, 4, 1, 6101, 2500, 251, 4)) if",
"nvwScanCurrConn = MibScalar((1, 3, 6, 1, 4, 1, 6101, 2500, 1), Integer32()).setMaxAccess(\"readonly\") if",
"4, 1, 6101, 2500, 1), Integer32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: nvwScanCurrConn.setStatus('mandatory') nvwScanCurrMem = MibScalar((1, 3,",
"MIB module TRENDMICRO-NVW-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TRENDMICRO-NVW-MIB # Produced by pysmi-0.3.4 at",
"\"MibTableRow\", \"MibTableColumn\", \"TimeTicks\", \"Integer32\") TextualConvention, DisplayString = mibBuilder.importSymbols(\"SNMPv2-TC\", \"TextualConvention\", \"DisplayString\") tmNVW, = mibBuilder.importSymbols(\"TRENDMICRO-SMI\",",
"\"TimeTicks\", \"Integer32\") TextualConvention, DisplayString = mibBuilder.importSymbols(\"SNMPv2-TC\", \"TextualConvention\", \"DisplayString\") tmNVW, = mibBuilder.importSymbols(\"TRENDMICRO-SMI\", \"tmNVW\") nvwScanCurrConn",
"DisplayString = mibBuilder.importSymbols(\"SNMPv2-TC\", \"TextualConvention\", \"DisplayString\") tmNVW, = mibBuilder.importSymbols(\"TRENDMICRO-SMI\", \"tmNVW\") nvwScanCurrConn = MibScalar((1, 3,",
"Integer32 = mibBuilder.importSymbols(\"SNMPv2-SMI\", \"Bits\", \"Counter64\", \"Gauge32\", \"ObjectIdentity\", \"Counter32\", \"NotificationType\", \"IpAddress\", \"iso\", \"ModuleIdentity\", \"Unsigned32\",",
"TRENDMICRO-NVW-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TRENDMICRO-NVW-MIB # Produced by pysmi-0.3.4 at Mon Apr",
"module TRENDMICRO-NVW-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TRENDMICRO-NVW-MIB # Produced by pysmi-0.3.4 at Mon",
"by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)",
"4, 1, 6101, 2500, 251, 2)) if mibBuilder.loadTexts: oppOff.setStatus('current') bootFactory = NotificationType((1, 3,",
"3, 6, 1, 4, 1, 6101, 2500, 1), Integer32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: nvwScanCurrConn.setStatus('mandatory') nvwScanCurrMem",
"2500, 1), Integer32()).setMaxAccess(\"readonly\") if mibBuilder.loadTexts: nvwScanCurrConn.setStatus('mandatory') nvwScanCurrMem = MibScalar((1, 3, 6, 1, 4,",
"nvwPolicyCurrConn = MibScalar((1, 3, 6, 1, 4, 1, 6101, 2500, 3), Integer32()).setMaxAccess(\"readonly\") if",
"1, 6101, 2500, 251, 3)) if mibBuilder.loadTexts: bootFactory.setStatus('current') bootPrevious = NotificationType((1, 3, 6,",
"# PySNMP MIB module TRENDMICRO-NVW-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TRENDMICRO-NVW-MIB # Produced by",
"1, 6101, 2500, 251, 5)) if mibBuilder.loadTexts: haFailover.setStatus('current') mibBuilder.exportSymbols(\"TRENDMICRO-NVW-MIB\", nvwPolicyCurrConn=nvwPolicyCurrConn, nvwScanCurrMem=nvwScanCurrMem, oppOn=oppOn, bootFactory=bootFactory,",
"Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # ObjectIdentifier, OctetString, Integer =",
"251, 2)) if mibBuilder.loadTexts: oppOff.setStatus('current') bootFactory = NotificationType((1, 3, 6, 1, 4, 1,",
"29 21:20:11 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user",
"6101, 2500, 251, 3)) if mibBuilder.loadTexts: bootFactory.setStatus('current') bootPrevious = NotificationType((1, 3, 6, 1,",
"<reponame>agustinhenze/mibs.snmplabs.com # # PySNMP MIB module TRENDMICRO-NVW-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TRENDMICRO-NVW-MIB #",
"= NotificationType((1, 3, 6, 1, 4, 1, 6101, 2500, 251, 3)) if mibBuilder.loadTexts:",
"NotificationType((1, 3, 6, 1, 4, 1, 6101, 2500, 251, 3)) if mibBuilder.loadTexts: bootFactory.setStatus('current')",
"4)) if mibBuilder.loadTexts: bootPrevious.setStatus('current') haFailover = NotificationType((1, 3, 6, 1, 4, 1, 6101,",
"PySNMP MIB module TRENDMICRO-NVW-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TRENDMICRO-NVW-MIB # Produced by pysmi-0.3.4",
"\"Counter32\", \"NotificationType\", \"IpAddress\", \"iso\", \"ModuleIdentity\", \"Unsigned32\", \"MibIdentifier\", \"MibScalar\", \"MibTable\", \"MibTableRow\", \"MibTableColumn\", \"TimeTicks\", \"Integer32\")",
"if mibBuilder.loadTexts: nvwPolicyCurrConn.setStatus('mandatory') nvwTraps = MibIdentifier((1, 3, 6, 1, 4, 1, 6101, 2500,"
] |
[
"last code cell. # All args should have a default value if the",
"KIND, either express or implied. # See the License for the specific language",
"Unless required by applicable law or agreed to in writing, software # distributed",
"import yyy import zzz # Top level classes, function definitions, and expressions are",
"A() print(a) # This is a markdown cell. def main(args): help(func) # The",
"( some_function) import yyy import zzz # Top level classes, function definitions, and",
"new cell to be created, but blank lines between imports are ignored. #",
"is\"\"\" def inner_func(): print(arg) return inner_func a = A() print(a) # This is",
"import ...` # Code manipulation is registered in `samples.yaml`. from module.helpers import (",
"this file except in compliance with the License. # You may obtain a",
"inner_func(): print(arg) return inner_func a = A() print(a) # This is a markdown",
"`if __name__ == '__main__':` block. if __name__ == '__main__': # Its content is",
"# Consecutive Comments are grouped into the same markdown cell. # The leading",
"governing permissions and # limitations under the License. \"\"\"Multiline docstrings should work but",
"the specific language governing permissions and # limitations under the License. \"\"\"Multiline docstrings",
"License. \"\"\"Multiline docstrings should work but could be problematic. \"\"\" # This is",
"runnable without code change. parser = argparse.ArgumentParser() parser.add_argument( '--job-dir', type=str, help='Job dir', default='/tmp/sample'",
"ANY KIND, either express or implied. # See the License for the specific",
"a markdown cell. def main(args): help(func) # The last thing of the .py",
"code cell. # All args should have a default value if the notebook",
"Inline comments are left as is. # Inner comments are left as is.",
"This is safer. \"\"\"Sample of what to_ipynb.py does\"\"\" # Consecutive Comments are grouped",
"2018 Google LLC # # Licensed under the Apache License, Version 2.0 (the",
"are left as is\"\"\" def inner_func(): print(arg) return inner_func a = A() print(a)",
"look better. # *It is okay to use [markdown](https://www.google.com/search?q=markdown).* import argparse import os",
"WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See",
"have a default value if the notebook is expected to be runnable without",
"but could be problematic. \"\"\" # This is safer. \"\"\"Sample of what to_ipynb.py",
"without code change. parser = argparse.ArgumentParser() parser.add_argument( '--job-dir', type=str, help='Job dir', default='/tmp/sample' )",
"IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or",
"work but could be problematic. \"\"\" # This is safer. \"\"\"Sample of what",
"help(func) # The last thing of the .py file must be the `if",
"are left as is. # Inner comments are left as is. def __init__(self):",
"# Code manipulation is registered in `samples.yaml`. from module.helpers import ( some_function) import",
"OF ANY KIND, either express or implied. # See the License for the",
"cells. class A(object): # Inline comments are left as is. # Inner comments",
"docstrings should work but could be problematic. \"\"\" # This is safer. \"\"\"Sample",
"args passed in when running as a notebook. args, _ = parser.parse_known_args() main(args)",
"dir', default='/tmp/sample' ) # Use parse_known_args to ignore args passed in when running",
"# Use parse_known_args to ignore args passed in when running as a notebook.",
"import zzz # Top level classes, function definitions, and expressions are in their",
"Top level classes, function definitions, and expressions are in their own cells. class",
"parser = argparse.ArgumentParser() parser.add_argument( '--job-dir', type=str, help='Job dir', default='/tmp/sample' ) # Use parse_known_args",
"__name__ == '__main__':` block. if __name__ == '__main__': # Its content is grouped",
"grouped into a cell. # Comments cause a new cell to be created,",
"if its source says `from module.helpers import ...` # Code manipulation is registered",
"LLC # # Licensed under the Apache License, Version 2.0 (the \"License\"); #",
"say `from helpers import ...` even if its source says `from module.helpers import",
"software # distributed under the License is distributed on an \"AS IS\" BASIS,",
"is okay to use [markdown](https://www.google.com/search?q=markdown).* import argparse import os # Consecutive imports are",
"print(a) # This is a markdown cell. def main(args): help(func) # The last",
"# # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to",
"*It is okay to use [markdown](https://www.google.com/search?q=markdown).* import argparse import os # Consecutive imports",
"is safer. \"\"\"Sample of what to_ipynb.py does\"\"\" # Consecutive Comments are grouped into",
"All args should have a default value if the notebook is expected to",
"is removed so the markdown cells look better. # *It is okay to",
"helpers import ...` even if its source says `from module.helpers import ...` #",
"to_ipynb.py does\"\"\" # Consecutive Comments are grouped into the same markdown cell. #",
"Comments are grouped into the same markdown cell. # The leading '#' symbol",
"should work but could be problematic. \"\"\" # This is safer. \"\"\"Sample of",
"and # limitations under the License. \"\"\"Multiline docstrings should work but could be",
") # Use parse_known_args to ignore args passed in when running as a",
"under the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES",
"to use [markdown](https://www.google.com/search?q=markdown).* import argparse import os # Consecutive imports are grouped into",
"into the last code cell. # All args should have a default value",
"the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law",
"is. def __init__(self): pass class B(object): pass def func(arg): \"\"\"Docstrings are left as",
"are grouped into a cell. # Comments cause a new cell to be",
"cell. # The leading '#' symbol is removed so the markdown cells look",
"\"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express",
"and expressions are in their own cells. class A(object): # Inline comments are",
"be runnable without code change. parser = argparse.ArgumentParser() parser.add_argument( '--job-dir', type=str, help='Job dir',",
"# Consecutive imports are grouped into a cell. # Comments cause a new",
"grouped into the last code cell. # All args should have a default",
"Consecutive Comments are grouped into the same markdown cell. # The leading '#'",
"required by applicable law or agreed to in writing, software # distributed under",
"code change. parser = argparse.ArgumentParser() parser.add_argument( '--job-dir', type=str, help='Job dir', default='/tmp/sample' ) #",
"<gh_stars>1000+ # Copyright 2018 Google LLC # # Licensed under the Apache License,",
"def inner_func(): print(arg) return inner_func a = A() print(a) # This is a",
"applicable law or agreed to in writing, software # distributed under the License",
"manipulation is registered in `samples.yaml`. from module.helpers import ( some_function) import yyy import",
"its source says `from module.helpers import ...` # Code manipulation is registered in",
"`from module.helpers import ...` # Code manipulation is registered in `samples.yaml`. from module.helpers",
"or agreed to in writing, software # distributed under the License is distributed",
"CONDITIONS OF ANY KIND, either express or implied. # See the License for",
"some_function) import yyy import zzz # Top level classes, function definitions, and expressions",
"expressions are in their own cells. class A(object): # Inline comments are left",
"imports are grouped into a cell. # Comments cause a new cell to",
"Consecutive imports are grouped into a cell. # Comments cause a new cell",
"under the Apache License, Version 2.0 (the \"License\"); # you may not use",
"import ...` even if its source says `from module.helpers import ...` # Code",
"writing, software # distributed under the License is distributed on an \"AS IS\"",
"__name__ == '__main__': # Its content is grouped into the last code cell.",
"You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 #",
"License. # You may obtain a copy of the License at # #",
"should say `from helpers import ...` even if its source says `from module.helpers",
"compliance with the License. # You may obtain a copy of the License",
"pass def func(arg): \"\"\"Docstrings are left as is\"\"\" def inner_func(): print(arg) return inner_func",
"if the notebook is expected to be runnable without code change. parser =",
"definitions, and expressions are in their own cells. class A(object): # Inline comments",
"Inner comments are left as is. def __init__(self): pass class B(object): pass def",
"args should have a default value if the notebook is expected to be",
"notebook is expected to be runnable without code change. parser = argparse.ArgumentParser() parser.add_argument(",
"# The leading '#' symbol is removed so the markdown cells look better.",
"are left as is. def __init__(self): pass class B(object): pass def func(arg): \"\"\"Docstrings",
"of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable",
"left as is. def __init__(self): pass class B(object): pass def func(arg): \"\"\"Docstrings are",
"Its content is grouped into the last code cell. # All args should",
"cell to be created, but blank lines between imports are ignored. # This",
"removed so the markdown cells look better. # *It is okay to use",
"not use this file except in compliance with the License. # You may",
"leading '#' symbol is removed so the markdown cells look better. # *It",
"for the specific language governing permissions and # limitations under the License. \"\"\"Multiline",
"must be the `if __name__ == '__main__':` block. if __name__ == '__main__': #",
"= argparse.ArgumentParser() parser.add_argument( '--job-dir', type=str, help='Job dir', default='/tmp/sample' ) # Use parse_known_args to",
"B(object): pass def func(arg): \"\"\"Docstrings are left as is\"\"\" def inner_func(): print(arg) return",
"License, Version 2.0 (the \"License\"); # you may not use this file except",
"import argparse import os # Consecutive imports are grouped into a cell. #",
"are in their own cells. class A(object): # Inline comments are left as",
"distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY",
"problematic. \"\"\" # This is safer. \"\"\"Sample of what to_ipynb.py does\"\"\" # Consecutive",
"\"\"\" # This is safer. \"\"\"Sample of what to_ipynb.py does\"\"\" # Consecutive Comments",
"# you may not use this file except in compliance with the License.",
"cell. def main(args): help(func) # The last thing of the .py file must",
"better. # *It is okay to use [markdown](https://www.google.com/search?q=markdown).* import argparse import os #",
"agreed to in writing, software # distributed under the License is distributed on",
"# This next import should say `from helpers import ...` even if its",
"is grouped into the last code cell. # All args should have a",
"(the \"License\"); # you may not use this file except in compliance with",
"between imports are ignored. # This next import should say `from helpers import",
"= A() print(a) # This is a markdown cell. def main(args): help(func) #",
"# Unless required by applicable law or agreed to in writing, software #",
"their own cells. class A(object): # Inline comments are left as is. #",
"by applicable law or agreed to in writing, software # distributed under the",
"yyy import zzz # Top level classes, function definitions, and expressions are in",
"Use parse_known_args to ignore args passed in when running as a notebook. args,",
"comments are left as is. # Inner comments are left as is. def",
"\"\"\"Docstrings are left as is\"\"\" def inner_func(): print(arg) return inner_func a = A()",
"copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by",
"cell. # Comments cause a new cell to be created, but blank lines",
"in their own cells. class A(object): # Inline comments are left as is.",
"is a markdown cell. def main(args): help(func) # The last thing of the",
"the License. \"\"\"Multiline docstrings should work but could be problematic. \"\"\" # This",
"symbol is removed so the markdown cells look better. # *It is okay",
"ignore args passed in when running as a notebook. args, _ = parser.parse_known_args()",
"# Inline comments are left as is. # Inner comments are left as",
"# *It is okay to use [markdown](https://www.google.com/search?q=markdown).* import argparse import os # Consecutive",
"a new cell to be created, but blank lines between imports are ignored.",
"file except in compliance with the License. # You may obtain a copy",
"default value if the notebook is expected to be runnable without code change.",
"'#' symbol is removed so the markdown cells look better. # *It is",
"from module.helpers import ( some_function) import yyy import zzz # Top level classes,",
"def func(arg): \"\"\"Docstrings are left as is\"\"\" def inner_func(): print(arg) return inner_func a",
"License for the specific language governing permissions and # limitations under the License.",
"Copyright 2018 Google LLC # # Licensed under the Apache License, Version 2.0",
"to in writing, software # distributed under the License is distributed on an",
"parse_known_args to ignore args passed in when running as a notebook. args, _",
"argparse.ArgumentParser() parser.add_argument( '--job-dir', type=str, help='Job dir', default='/tmp/sample' ) # Use parse_known_args to ignore",
"specific language governing permissions and # limitations under the License. \"\"\"Multiline docstrings should",
"is registered in `samples.yaml`. from module.helpers import ( some_function) import yyy import zzz",
"implied. # See the License for the specific language governing permissions and #",
"\"License\"); # you may not use this file except in compliance with the",
"# limitations under the License. \"\"\"Multiline docstrings should work but could be problematic.",
"...` even if its source says `from module.helpers import ...` # Code manipulation",
"obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless",
"but blank lines between imports are ignored. # This next import should say",
"are ignored. # This next import should say `from helpers import ...` even",
"are grouped into the same markdown cell. # The leading '#' symbol is",
"cause a new cell to be created, but blank lines between imports are",
"is. # Inner comments are left as is. def __init__(self): pass class B(object):",
"`from helpers import ...` even if its source says `from module.helpers import ...`",
"'__main__':` block. if __name__ == '__main__': # Its content is grouped into the",
"use [markdown](https://www.google.com/search?q=markdown).* import argparse import os # Consecutive imports are grouped into a",
"module.helpers import ...` # Code manipulation is registered in `samples.yaml`. from module.helpers import",
"or implied. # See the License for the specific language governing permissions and",
"imports are ignored. # This next import should say `from helpers import ...`",
"Apache License, Version 2.0 (the \"License\"); # you may not use this file",
"This is a markdown cell. def main(args): help(func) # The last thing of",
"OR CONDITIONS OF ANY KIND, either express or implied. # See the License",
"may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # #",
"what to_ipynb.py does\"\"\" # Consecutive Comments are grouped into the same markdown cell.",
"class A(object): # Inline comments are left as is. # Inner comments are",
"if __name__ == '__main__': # Its content is grouped into the last code",
"http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing,",
"in writing, software # distributed under the License is distributed on an \"AS",
"classes, function definitions, and expressions are in their own cells. class A(object): #",
"blank lines between imports are ignored. # This next import should say `from",
"print(arg) return inner_func a = A() print(a) # This is a markdown cell.",
"the .py file must be the `if __name__ == '__main__':` block. if __name__",
"# See the License for the specific language governing permissions and # limitations",
"the License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR",
"the notebook is expected to be runnable without code change. parser = argparse.ArgumentParser()",
"default='/tmp/sample' ) # Use parse_known_args to ignore args passed in when running as",
"type=str, help='Job dir', default='/tmp/sample' ) # Use parse_known_args to ignore args passed in",
"# Copyright 2018 Google LLC # # Licensed under the Apache License, Version",
"'__main__': # Its content is grouped into the last code cell. # All",
"the Apache License, Version 2.0 (the \"License\"); # you may not use this",
"== '__main__': # Its content is grouped into the last code cell. #",
"you may not use this file except in compliance with the License. #",
"module.helpers import ( some_function) import yyy import zzz # Top level classes, function",
"Google LLC # # Licensed under the Apache License, Version 2.0 (the \"License\");",
"a default value if the notebook is expected to be runnable without code",
"use this file except in compliance with the License. # You may obtain",
"# All args should have a default value if the notebook is expected",
"thing of the .py file must be the `if __name__ == '__main__':` block.",
"__init__(self): pass class B(object): pass def func(arg): \"\"\"Docstrings are left as is\"\"\" def",
"# Licensed under the Apache License, Version 2.0 (the \"License\"); # you may",
"should have a default value if the notebook is expected to be runnable",
"be the `if __name__ == '__main__':` block. if __name__ == '__main__': # Its",
"says `from module.helpers import ...` # Code manipulation is registered in `samples.yaml`. from",
"2.0 (the \"License\"); # you may not use this file except in compliance",
"the same markdown cell. # The leading '#' symbol is removed so the",
"class B(object): pass def func(arg): \"\"\"Docstrings are left as is\"\"\" def inner_func(): print(arg)",
"func(arg): \"\"\"Docstrings are left as is\"\"\" def inner_func(): print(arg) return inner_func a =",
"Code manipulation is registered in `samples.yaml`. from module.helpers import ( some_function) import yyy",
"WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the",
"as is\"\"\" def inner_func(): print(arg) return inner_func a = A() print(a) # This",
"# # Unless required by applicable law or agreed to in writing, software",
"express or implied. # See the License for the specific language governing permissions",
"`samples.yaml`. from module.helpers import ( some_function) import yyy import zzz # Top level",
"a cell. # Comments cause a new cell to be created, but blank",
"either express or implied. # See the License for the specific language governing",
"ignored. # This next import should say `from helpers import ...` even if",
"a = A() print(a) # This is a markdown cell. def main(args): help(func)",
"markdown cells look better. # *It is okay to use [markdown](https://www.google.com/search?q=markdown).* import argparse",
"of the .py file must be the `if __name__ == '__main__':` block. if",
"Licensed under the Apache License, Version 2.0 (the \"License\"); # you may not",
"an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either",
"zzz # Top level classes, function definitions, and expressions are in their own",
"parser.add_argument( '--job-dir', type=str, help='Job dir', default='/tmp/sample' ) # Use parse_known_args to ignore args",
"The leading '#' symbol is removed so the markdown cells look better. #",
"even if its source says `from module.helpers import ...` # Code manipulation is",
"def main(args): help(func) # The last thing of the .py file must be",
"os # Consecutive imports are grouped into a cell. # Comments cause a",
"# Top level classes, function definitions, and expressions are in their own cells.",
"to be created, but blank lines between imports are ignored. # This next",
"the License. # You may obtain a copy of the License at #",
"last thing of the .py file must be the `if __name__ == '__main__':`",
"could be problematic. \"\"\" # This is safer. \"\"\"Sample of what to_ipynb.py does\"\"\"",
"to ignore args passed in when running as a notebook. args, _ =",
"# distributed under the License is distributed on an \"AS IS\" BASIS, #",
"is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF",
"...` # Code manipulation is registered in `samples.yaml`. from module.helpers import ( some_function)",
"so the markdown cells look better. # *It is okay to use [markdown](https://www.google.com/search?q=markdown).*",
"file must be the `if __name__ == '__main__':` block. if __name__ == '__main__':",
"next import should say `from helpers import ...` even if its source says",
"import should say `from helpers import ...` even if its source says `from",
"'--job-dir', type=str, help='Job dir', default='/tmp/sample' ) # Use parse_known_args to ignore args passed",
"change. parser = argparse.ArgumentParser() parser.add_argument( '--job-dir', type=str, help='Job dir', default='/tmp/sample' ) # Use",
"\"\"\"Multiline docstrings should work but could be problematic. \"\"\" # This is safer.",
"help='Job dir', default='/tmp/sample' ) # Use parse_known_args to ignore args passed in when",
"own cells. class A(object): # Inline comments are left as is. # Inner",
"block. if __name__ == '__main__': # Its content is grouped into the last",
"is expected to be runnable without code change. parser = argparse.ArgumentParser() parser.add_argument( '--job-dir',",
"with the License. # You may obtain a copy of the License at",
"pass class B(object): pass def func(arg): \"\"\"Docstrings are left as is\"\"\" def inner_func():",
"be problematic. \"\"\" # This is safer. \"\"\"Sample of what to_ipynb.py does\"\"\" #",
"[markdown](https://www.google.com/search?q=markdown).* import argparse import os # Consecutive imports are grouped into a cell.",
"# # Licensed under the Apache License, Version 2.0 (the \"License\"); # you",
"be created, but blank lines between imports are ignored. # This next import",
"\"\"\"Sample of what to_ipynb.py does\"\"\" # Consecutive Comments are grouped into the same",
"the markdown cells look better. # *It is okay to use [markdown](https://www.google.com/search?q=markdown).* import",
"law or agreed to in writing, software # distributed under the License is",
"the License for the specific language governing permissions and # limitations under the",
"on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,",
"the last code cell. # All args should have a default value if",
"A(object): # Inline comments are left as is. # Inner comments are left",
"does\"\"\" # Consecutive Comments are grouped into the same markdown cell. # The",
"same markdown cell. # The leading '#' symbol is removed so the markdown",
"language governing permissions and # limitations under the License. \"\"\"Multiline docstrings should work",
"return inner_func a = A() print(a) # This is a markdown cell. def",
"left as is\"\"\" def inner_func(): print(arg) return inner_func a = A() print(a) #",
"source says `from module.helpers import ...` # Code manipulation is registered in `samples.yaml`.",
"in compliance with the License. # You may obtain a copy of the",
"of what to_ipynb.py does\"\"\" # Consecutive Comments are grouped into the same markdown",
"License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or",
"# The last thing of the .py file must be the `if __name__",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. #",
"at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed",
"safer. \"\"\"Sample of what to_ipynb.py does\"\"\" # Consecutive Comments are grouped into the",
"See the License for the specific language governing permissions and # limitations under",
"cell. # All args should have a default value if the notebook is",
"BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.",
"as is. def __init__(self): pass class B(object): pass def func(arg): \"\"\"Docstrings are left",
"a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required",
"# This is safer. \"\"\"Sample of what to_ipynb.py does\"\"\" # Consecutive Comments are",
"import ( some_function) import yyy import zzz # Top level classes, function definitions,",
"This next import should say `from helpers import ...` even if its source",
"in `samples.yaml`. from module.helpers import ( some_function) import yyy import zzz # Top",
"# http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in",
"as is. # Inner comments are left as is. def __init__(self): pass class",
"def __init__(self): pass class B(object): pass def func(arg): \"\"\"Docstrings are left as is\"\"\"",
"inner_func a = A() print(a) # This is a markdown cell. def main(args):",
"# Inner comments are left as is. def __init__(self): pass class B(object): pass",
"content is grouped into the last code cell. # All args should have",
"Comments cause a new cell to be created, but blank lines between imports",
"level classes, function definitions, and expressions are in their own cells. class A(object):",
".py file must be the `if __name__ == '__main__':` block. if __name__ ==",
"limitations under the License. \"\"\"Multiline docstrings should work but could be problematic. \"\"\"",
"cells look better. # *It is okay to use [markdown](https://www.google.com/search?q=markdown).* import argparse import",
"registered in `samples.yaml`. from module.helpers import ( some_function) import yyy import zzz #",
"under the License. \"\"\"Multiline docstrings should work but could be problematic. \"\"\" #",
"function definitions, and expressions are in their own cells. class A(object): # Inline",
"Version 2.0 (the \"License\"); # you may not use this file except in",
"except in compliance with the License. # You may obtain a copy of",
"comments are left as is. def __init__(self): pass class B(object): pass def func(arg):",
"# You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0",
"may not use this file except in compliance with the License. # You",
"License is distributed on an \"AS IS\" BASIS, # WITHOUT WARRANTIES OR CONDITIONS",
"into a cell. # Comments cause a new cell to be created, but",
"okay to use [markdown](https://www.google.com/search?q=markdown).* import argparse import os # Consecutive imports are grouped",
"# Comments cause a new cell to be created, but blank lines between",
"into the same markdown cell. # The leading '#' symbol is removed so",
"value if the notebook is expected to be runnable without code change. parser",
"main(args): help(func) # The last thing of the .py file must be the",
"# Its content is grouped into the last code cell. # All args",
"lines between imports are ignored. # This next import should say `from helpers",
"markdown cell. # The leading '#' symbol is removed so the markdown cells",
"the `if __name__ == '__main__':` block. if __name__ == '__main__': # Its content",
"grouped into the same markdown cell. # The leading '#' symbol is removed",
"left as is. # Inner comments are left as is. def __init__(self): pass",
"expected to be runnable without code change. parser = argparse.ArgumentParser() parser.add_argument( '--job-dir', type=str,",
"import os # Consecutive imports are grouped into a cell. # Comments cause",
"# This is a markdown cell. def main(args): help(func) # The last thing",
"The last thing of the .py file must be the `if __name__ ==",
"distributed under the License is distributed on an \"AS IS\" BASIS, # WITHOUT",
"permissions and # limitations under the License. \"\"\"Multiline docstrings should work but could",
"== '__main__':` block. if __name__ == '__main__': # Its content is grouped into",
"to be runnable without code change. parser = argparse.ArgumentParser() parser.add_argument( '--job-dir', type=str, help='Job",
"markdown cell. def main(args): help(func) # The last thing of the .py file",
"created, but blank lines between imports are ignored. # This next import should",
"argparse import os # Consecutive imports are grouped into a cell. # Comments"
] |
[
"inheriting Chef class from ChineseChef class class ChineseChef(Chef): def make_special_dish(self): print(\"The chef makes",
"from ChineseChef class class ChineseChef(Chef): def make_special_dish(self): print(\"The chef makes orange chicken\") def",
"make_special_dish(self): print(\"The chef makes orange chicken\") def make_fried_rice(self): print(\"The Chef makes fried rice.\")",
"# inheriting Chef class from ChineseChef class class ChineseChef(Chef): def make_special_dish(self): print(\"The chef",
"class from ChineseChef class class ChineseChef(Chef): def make_special_dish(self): print(\"The chef makes orange chicken\")",
"import Chef # inheriting Chef class from ChineseChef class class ChineseChef(Chef): def make_special_dish(self):",
"ChineseChef class class ChineseChef(Chef): def make_special_dish(self): print(\"The chef makes orange chicken\") def make_fried_rice(self):",
"Chef class from ChineseChef class class ChineseChef(Chef): def make_special_dish(self): print(\"The chef makes orange",
"Chef # inheriting Chef class from ChineseChef class class ChineseChef(Chef): def make_special_dish(self): print(\"The",
"from Chef import Chef # inheriting Chef class from ChineseChef class class ChineseChef(Chef):",
"ChineseChef(Chef): def make_special_dish(self): print(\"The chef makes orange chicken\") def make_fried_rice(self): print(\"The Chef makes",
"def make_special_dish(self): print(\"The chef makes orange chicken\") def make_fried_rice(self): print(\"The Chef makes fried",
"Chef import Chef # inheriting Chef class from ChineseChef class class ChineseChef(Chef): def",
"class class ChineseChef(Chef): def make_special_dish(self): print(\"The chef makes orange chicken\") def make_fried_rice(self): print(\"The",
"class ChineseChef(Chef): def make_special_dish(self): print(\"The chef makes orange chicken\") def make_fried_rice(self): print(\"The Chef"
] |
[
"Solution(object): def findMaxLength(self, nums): \"\"\" :type nums: List[int] :rtype: int \"\"\" \"\"\" Method",
"num in enumerate(nums): if num == 0: count -= 1 else: count +=",
"[0, 1] is the longest contiguous subarray with equal number of 0 and",
"[0,1,0] Output: 2 Explanation: [0, 1] (or [1, 0]) is a longest contiguous",
"length of a contiguous subarray with equal number of 0 and 1. Example",
"2: Input: [0,1,0] Output: 2 Explanation: [0, 1] (or [1, 0]) is a",
"table. If it does then we update the length as the maximum between",
"{0: 0} * Enumerate When we come across the number 0, we subtract",
"of python submissions \"\"\" count = 0 max_length = 0 table = {0:",
"1] is the longest contiguous subarray with equal number of 0 and 1.",
"Given a binary array, find the maximum length of a contiguous subarray with",
"count = 0 max_length = 0 table = {0: 0} for index, num",
"\"\"\" class Solution(object): def findMaxLength(self, nums): \"\"\" :type nums: List[int] :rtype: int \"\"\"",
"subarray with equal number of 0 and 1. Example 1: Input: [0,1] Output:",
"binary array will not exceed 50,000. \"\"\" class Solution(object): def findMaxLength(self, nums): \"\"\"",
"count When we come across the number 1, we add 1 to count",
"each stage, we check if count exists in the hash table. If it",
"of a contiguous subarray with equal number of 0 and 1. Example 1:",
"find the maximum length of a contiguous subarray with equal number of 0",
"max length variable - hash table with {0: 0} * Enumerate When we",
"int \"\"\" \"\"\" Method 1: Hash Table * Initialize - counter - max",
"80.81 % of python submissions \"\"\" count = 0 max_length = 0 table",
"in the hash table. If it does then we update the length as",
"hash table with {0: 0} * Enumerate When we come across the number",
"\"\"\" :type nums: List[int] :rtype: int \"\"\" \"\"\" Method 1: Hash Table *",
"2 Explanation: [0, 1] is the longest contiguous subarray with equal number of",
"it does then we update the length as the maximum between max_length and",
"of 0 and 1. Example 1: Input: [0,1] Output: 2 Explanation: [0, 1]",
"will not exceed 50,000. \"\"\" class Solution(object): def findMaxLength(self, nums): \"\"\" :type nums:",
"and 1. Note: The length of the given binary array will not exceed",
"Example 1: Input: [0,1] Output: 2 Explanation: [0, 1] is the longest contiguous",
"Input: [0,1] Output: 2 Explanation: [0, 1] is the longest contiguous subarray with",
"enumerate(nums): if num == 0: count -= 1 else: count += 1 if",
"0: count -= 1 else: count += 1 if count in table: print(table)",
"1: Input: [0,1] Output: 2 Explanation: [0, 1] is the longest contiguous subarray",
"from count When we come across the number 1, we add 1 to",
"+= 1 if count in table: print(table) max_length = max(max_length, index + 1",
"between max_length and index-table[count] Reference:https://discuss.leetcode.com/topic/80056/python-o-n-solution-with-visual-explanation/2 Your runtime beats 80.81 % of python submissions",
"the length as the maximum between max_length and index-table[count] Reference:https://discuss.leetcode.com/topic/80056/python-o-n-solution-with-visual-explanation/2 Your runtime beats",
"exists in the hash table. If it does then we update the length",
"runtime beats 80.81 % of python submissions \"\"\" count = 0 max_length =",
"Input: [0,1,0] Output: 2 Explanation: [0, 1] (or [1, 0]) is a longest",
"if num == 0: count -= 1 else: count += 1 if count",
"= 0 max_length = 0 table = {0: 0} for index, num in",
"nums: List[int] :rtype: int \"\"\" \"\"\" Method 1: Hash Table * Initialize -",
"Initialize - counter - max length variable - hash table with {0: 0}",
"1 from count When we come across the number 1, we add 1",
"Reference:https://discuss.leetcode.com/topic/80056/python-o-n-solution-with-visual-explanation/2 Your runtime beats 80.81 % of python submissions \"\"\" count = 0",
"When we come across the number 1, we add 1 to count At",
"Your runtime beats 80.81 % of python submissions \"\"\" count = 0 max_length",
"max_length and index-table[count] Reference:https://discuss.leetcode.com/topic/80056/python-o-n-solution-with-visual-explanation/2 Your runtime beats 80.81 % of python submissions \"\"\"",
"== 0: count -= 1 else: count += 1 if count in table:",
"0 and 1. Example 2: Input: [0,1,0] Output: 2 Explanation: [0, 1] (or",
"length as the maximum between max_length and index-table[count] Reference:https://discuss.leetcode.com/topic/80056/python-o-n-solution-with-visual-explanation/2 Your runtime beats 80.81",
"hash table. If it does then we update the length as the maximum",
"with equal number of 0 and 1. Example 2: Input: [0,1,0] Output: 2",
"we subtract 1 from count When we come across the number 1, we",
"1, we add 1 to count At each stage, we check if count",
"[1, 0]) is a longest contiguous subarray with equal number of 0 and",
"we update the length as the maximum between max_length and index-table[count] Reference:https://discuss.leetcode.com/topic/80056/python-o-n-solution-with-visual-explanation/2 Your",
"a contiguous subarray with equal number of 0 and 1. Example 1: Input:",
"we come across the number 1, we add 1 to count At each",
"findMaxLength(self, nums): \"\"\" :type nums: List[int] :rtype: int \"\"\" \"\"\" Method 1: Hash",
":type nums: List[int] :rtype: int \"\"\" \"\"\" Method 1: Hash Table * Initialize",
"in table: print(table) max_length = max(max_length, index + 1 - table[count]) else: table[count]",
"the longest contiguous subarray with equal number of 0 and 1. Example 2:",
"a longest contiguous subarray with equal number of 0 and 1. Note: The",
"across the number 0, we subtract 1 from count When we come across",
"if count in table: print(table) max_length = max(max_length, index + 1 - table[count])",
"1. Example 1: Input: [0,1] Output: 2 Explanation: [0, 1] is the longest",
"in enumerate(nums): if num == 0: count -= 1 else: count += 1",
"* Enumerate When we come across the number 0, we subtract 1 from",
"subarray with equal number of 0 and 1. Example 2: Input: [0,1,0] Output:",
"the maximum length of a contiguous subarray with equal number of 0 and",
"counter - max length variable - hash table with {0: 0} * Enumerate",
"subtract 1 from count When we come across the number 1, we add",
"count += 1 if count in table: print(table) max_length = max(max_length, index +",
"variable - hash table with {0: 0} * Enumerate When we come across",
"count -= 1 else: count += 1 if count in table: print(table) max_length",
"the maximum between max_length and index-table[count] Reference:https://discuss.leetcode.com/topic/80056/python-o-n-solution-with-visual-explanation/2 Your runtime beats 80.81 % of",
"check if count exists in the hash table. If it does then we",
"- hash table with {0: 0} * Enumerate When we come across the",
"a binary array, find the maximum length of a contiguous subarray with equal",
"is the longest contiguous subarray with equal number of 0 and 1. Example",
"equal number of 0 and 1. Example 2: Input: [0,1,0] Output: 2 Explanation:",
"exceed 50,000. \"\"\" class Solution(object): def findMaxLength(self, nums): \"\"\" :type nums: List[int] :rtype:",
"table: print(table) max_length = max(max_length, index + 1 - table[count]) else: table[count] =",
"update the length as the maximum between max_length and index-table[count] Reference:https://discuss.leetcode.com/topic/80056/python-o-n-solution-with-visual-explanation/2 Your runtime",
"with {0: 0} * Enumerate When we come across the number 0, we",
"the number 1, we add 1 to count At each stage, we check",
"not exceed 50,000. \"\"\" class Solution(object): def findMaxLength(self, nums): \"\"\" :type nums: List[int]",
"index, num in enumerate(nums): if num == 0: count -= 1 else: count",
"1. Note: The length of the given binary array will not exceed 50,000.",
"% of python submissions \"\"\" count = 0 max_length = 0 table =",
"number of 0 and 1. Example 2: Input: [0,1,0] Output: 2 Explanation: [0,",
"and 1. Example 1: Input: [0,1] Output: 2 Explanation: [0, 1] is the",
"Table * Initialize - counter - max length variable - hash table with",
"\"\"\" \"\"\" Method 1: Hash Table * Initialize - counter - max length",
"0, we subtract 1 from count When we come across the number 1,",
"-= 1 else: count += 1 if count in table: print(table) max_length =",
"contiguous subarray with equal number of 0 and 1. Example 2: Input: [0,1,0]",
"else: count += 1 if count in table: print(table) max_length = max(max_length, index",
"Output: 2 Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray",
"Output: 2 Explanation: [0, 1] is the longest contiguous subarray with equal number",
"array will not exceed 50,000. \"\"\" class Solution(object): def findMaxLength(self, nums): \"\"\" :type",
"0} * Enumerate When we come across the number 0, we subtract 1",
"0 and 1. Example 1: Input: [0,1] Output: 2 Explanation: [0, 1] is",
"the hash table. If it does then we update the length as the",
"Example 2: Input: [0,1,0] Output: 2 Explanation: [0, 1] (or [1, 0]) is",
"index-table[count] Reference:https://discuss.leetcode.com/topic/80056/python-o-n-solution-with-visual-explanation/2 Your runtime beats 80.81 % of python submissions \"\"\" count =",
"- max length variable - hash table with {0: 0} * Enumerate When",
"beats 80.81 % of python submissions \"\"\" count = 0 max_length = 0",
"= {0: 0} for index, num in enumerate(nums): if num == 0: count",
"The length of the given binary array will not exceed 50,000. \"\"\" class",
"0 max_length = 0 table = {0: 0} for index, num in enumerate(nums):",
"number 0, we subtract 1 from count When we come across the number",
"to count At each stage, we check if count exists in the hash",
"\"\"\" Given a binary array, find the maximum length of a contiguous subarray",
"for index, num in enumerate(nums): if num == 0: count -= 1 else:",
"At each stage, we check if count exists in the hash table. If",
"count exists in the hash table. If it does then we update the",
"we check if count exists in the hash table. If it does then",
"{0: 0} for index, num in enumerate(nums): if num == 0: count -=",
"print(table) max_length = max(max_length, index + 1 - table[count]) else: table[count] = index",
"1] (or [1, 0]) is a longest contiguous subarray with equal number of",
"number 1, we add 1 to count At each stage, we check if",
"Method 1: Hash Table * Initialize - counter - max length variable -",
"count in table: print(table) max_length = max(max_length, index + 1 - table[count]) else:",
"python submissions \"\"\" count = 0 max_length = 0 table = {0: 0}",
"stage, we check if count exists in the hash table. If it does",
"2 Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with",
"1 to count At each stage, we check if count exists in the",
"List[int] :rtype: int \"\"\" \"\"\" Method 1: Hash Table * Initialize - counter",
"given binary array will not exceed 50,000. \"\"\" class Solution(object): def findMaxLength(self, nums):",
"When we come across the number 0, we subtract 1 from count When",
"\"\"\" count = 0 max_length = 0 table = {0: 0} for index,",
"* Initialize - counter - max length variable - hash table with {0:",
"equal number of 0 and 1. Example 1: Input: [0,1] Output: 2 Explanation:",
"1: Hash Table * Initialize - counter - max length variable - hash",
"- counter - max length variable - hash table with {0: 0} *",
"add 1 to count At each stage, we check if count exists in",
"contiguous subarray with equal number of 0 and 1. Example 1: Input: [0,1]",
"then we update the length as the maximum between max_length and index-table[count] Reference:https://discuss.leetcode.com/topic/80056/python-o-n-solution-with-visual-explanation/2",
"0]) is a longest contiguous subarray with equal number of 0 and 1.",
"(or [1, 0]) is a longest contiguous subarray with equal number of 0",
"Note: The length of the given binary array will not exceed 50,000. \"\"\"",
"Hash Table * Initialize - counter - max length variable - hash table",
"the given binary array will not exceed 50,000. \"\"\" class Solution(object): def findMaxLength(self,",
"maximum between max_length and index-table[count] Reference:https://discuss.leetcode.com/topic/80056/python-o-n-solution-with-visual-explanation/2 Your runtime beats 80.81 % of python",
"num == 0: count -= 1 else: count += 1 if count in",
"come across the number 0, we subtract 1 from count When we come",
"= max(max_length, index + 1 - table[count]) else: table[count] = index + 1",
"binary array, find the maximum length of a contiguous subarray with equal number",
"[0, 1] (or [1, 0]) is a longest contiguous subarray with equal number",
"[0,1] Output: 2 Explanation: [0, 1] is the longest contiguous subarray with equal",
"1 if count in table: print(table) max_length = max(max_length, index + 1 -",
"Enumerate When we come across the number 0, we subtract 1 from count",
"the number 0, we subtract 1 from count When we come across the",
"if count exists in the hash table. If it does then we update",
"we come across the number 0, we subtract 1 from count When we",
"and index-table[count] Reference:https://discuss.leetcode.com/topic/80056/python-o-n-solution-with-visual-explanation/2 Your runtime beats 80.81 % of python submissions \"\"\" count",
"0} for index, num in enumerate(nums): if num == 0: count -= 1",
"equal number of 0 and 1. Note: The length of the given binary",
"0 and 1. Note: The length of the given binary array will not",
"as the maximum between max_length and index-table[count] Reference:https://discuss.leetcode.com/topic/80056/python-o-n-solution-with-visual-explanation/2 Your runtime beats 80.81 %",
"table with {0: 0} * Enumerate When we come across the number 0,",
"Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal",
"does then we update the length as the maximum between max_length and index-table[count]",
"number of 0 and 1. Note: The length of the given binary array",
"50,000. \"\"\" class Solution(object): def findMaxLength(self, nums): \"\"\" :type nums: List[int] :rtype: int",
"max_length = max(max_length, index + 1 - table[count]) else: table[count] = index +",
"with equal number of 0 and 1. Example 1: Input: [0,1] Output: 2",
"longest contiguous subarray with equal number of 0 and 1. Example 2: Input:",
"If it does then we update the length as the maximum between max_length",
"Explanation: [0, 1] is the longest contiguous subarray with equal number of 0",
":rtype: int \"\"\" \"\"\" Method 1: Hash Table * Initialize - counter -",
"maximum length of a contiguous subarray with equal number of 0 and 1.",
"length of the given binary array will not exceed 50,000. \"\"\" class Solution(object):",
"submissions \"\"\" count = 0 max_length = 0 table = {0: 0} for",
"subarray with equal number of 0 and 1. Note: The length of the",
"across the number 1, we add 1 to count At each stage, we",
"0 table = {0: 0} for index, num in enumerate(nums): if num ==",
"max_length = 0 table = {0: 0} for index, num in enumerate(nums): if",
"index + 1 - table[count]) else: table[count] = index + 1 return max_length",
"count At each stage, we check if count exists in the hash table.",
"length variable - hash table with {0: 0} * Enumerate When we come",
"come across the number 1, we add 1 to count At each stage,",
"longest contiguous subarray with equal number of 0 and 1. Note: The length",
"of the given binary array will not exceed 50,000. \"\"\" class Solution(object): def",
"1. Example 2: Input: [0,1,0] Output: 2 Explanation: [0, 1] (or [1, 0])",
"= 0 table = {0: 0} for index, num in enumerate(nums): if num",
"1 else: count += 1 if count in table: print(table) max_length = max(max_length,",
"of 0 and 1. Example 2: Input: [0,1,0] Output: 2 Explanation: [0, 1]",
"of 0 and 1. Note: The length of the given binary array will",
"array, find the maximum length of a contiguous subarray with equal number of",
"is a longest contiguous subarray with equal number of 0 and 1. Note:",
"def findMaxLength(self, nums): \"\"\" :type nums: List[int] :rtype: int \"\"\" \"\"\" Method 1:",
"with equal number of 0 and 1. Note: The length of the given",
"\"\"\" Method 1: Hash Table * Initialize - counter - max length variable",
"max(max_length, index + 1 - table[count]) else: table[count] = index + 1 return",
"and 1. Example 2: Input: [0,1,0] Output: 2 Explanation: [0, 1] (or [1,",
"table = {0: 0} for index, num in enumerate(nums): if num == 0:",
"nums): \"\"\" :type nums: List[int] :rtype: int \"\"\" \"\"\" Method 1: Hash Table",
"contiguous subarray with equal number of 0 and 1. Note: The length of",
"number of 0 and 1. Example 1: Input: [0,1] Output: 2 Explanation: [0,",
"class Solution(object): def findMaxLength(self, nums): \"\"\" :type nums: List[int] :rtype: int \"\"\" \"\"\"",
"we add 1 to count At each stage, we check if count exists"
] |
[
"import upy2 from upy2 import u, U from upy2.typesetting import ScientificTypesetter # This",
"anymore since :func:`upy2.numpy_operators.install_numpy_operators` # is now called unconditionally upon importing ``upy2``. U(2).default() ScientificTypesetter(stddevs=2,",
":func:`upy2.numpy_operators.install_numpy_operators` # is now called unconditionally upon importing ``upy2``. U(2).default() ScientificTypesetter(stddevs=2, precision=2).default() wavelength",
"upy2 from upy2 import u, U from upy2.typesetting import ScientificTypesetter # This test",
"print compound print \"-----\" #upy2.install_numpy_operators() compound2 = numpy.asarray([[100], [42]]) +- u([[1], [1.5]]) print",
"test probably doesn't demonstrate the intended behaviour # anymore since :func:`upy2.numpy_operators.install_numpy_operators` # is",
"2]) print compound print \"-----\" #upy2.install_numpy_operators() compound2 = numpy.asarray([[100], [42]]) +- u([[1], [1.5]])",
"** 0.5 print \"-----\" compound = numpy.asarray([10, 11]) +- u([1, 2]) print compound",
"This test probably doesn't demonstrate the intended behaviour # anymore since :func:`upy2.numpy_operators.install_numpy_operators` #",
"upy2 import u, U from upy2.typesetting import ScientificTypesetter # This test probably doesn't",
"compound print \"-----\" #upy2.install_numpy_operators() compound2 = numpy.asarray([[100], [42]]) +- u([[1], [1.5]]) print compound2",
"numpy.asarray([10, 11]) +- u([1, 2]) print compound print \"-----\" #upy2.install_numpy_operators() compound2 = numpy.asarray([[100],",
"ScientificTypesetter # This test probably doesn't demonstrate the intended behaviour # anymore since",
"11]) +- u([1, 2]) print compound print \"-----\" #upy2.install_numpy_operators() compound2 = numpy.asarray([[100], [42]])",
"ScientificTypesetter(stddevs=2, precision=2).default() wavelength = 420 +- u(10) print wavelength print wavelength ** 0.5",
"wavelength = 420 +- u(10) print wavelength print wavelength ** 0.5 print \"-----\"",
"behaviour # anymore since :func:`upy2.numpy_operators.install_numpy_operators` # is now called unconditionally upon importing ``upy2``.",
"= numpy.asarray([10, 11]) +- u([1, 2]) print compound print \"-----\" #upy2.install_numpy_operators() compound2 =",
"from upy2.typesetting import ScientificTypesetter # This test probably doesn't demonstrate the intended behaviour",
"is now called unconditionally upon importing ``upy2``. U(2).default() ScientificTypesetter(stddevs=2, precision=2).default() wavelength = 420",
"= 420 +- u(10) print wavelength print wavelength ** 0.5 print \"-----\" compound",
"print wavelength print wavelength ** 0.5 print \"-----\" compound = numpy.asarray([10, 11]) +-",
"from upy2 import u, U from upy2.typesetting import ScientificTypesetter # This test probably",
"unconditionally upon importing ``upy2``. U(2).default() ScientificTypesetter(stddevs=2, precision=2).default() wavelength = 420 +- u(10) print",
"# This test probably doesn't demonstrate the intended behaviour # anymore since :func:`upy2.numpy_operators.install_numpy_operators`",
"import numpy import upy2 from upy2 import u, U from upy2.typesetting import ScientificTypesetter",
"0.5 print \"-----\" compound = numpy.asarray([10, 11]) +- u([1, 2]) print compound print",
"import u, U from upy2.typesetting import ScientificTypesetter # This test probably doesn't demonstrate",
"demonstrate the intended behaviour # anymore since :func:`upy2.numpy_operators.install_numpy_operators` # is now called unconditionally",
"numpy import upy2 from upy2 import u, U from upy2.typesetting import ScientificTypesetter #",
"import ScientificTypesetter # This test probably doesn't demonstrate the intended behaviour # anymore",
"# is now called unconditionally upon importing ``upy2``. U(2).default() ScientificTypesetter(stddevs=2, precision=2).default() wavelength =",
"upon importing ``upy2``. U(2).default() ScientificTypesetter(stddevs=2, precision=2).default() wavelength = 420 +- u(10) print wavelength",
"``upy2``. U(2).default() ScientificTypesetter(stddevs=2, precision=2).default() wavelength = 420 +- u(10) print wavelength print wavelength",
"420 +- u(10) print wavelength print wavelength ** 0.5 print \"-----\" compound =",
"+- u([1, 2]) print compound print \"-----\" #upy2.install_numpy_operators() compound2 = numpy.asarray([[100], [42]]) +-",
"wavelength ** 0.5 print \"-----\" compound = numpy.asarray([10, 11]) +- u([1, 2]) print",
"U(2).default() ScientificTypesetter(stddevs=2, precision=2).default() wavelength = 420 +- u(10) print wavelength print wavelength **",
"u(10) print wavelength print wavelength ** 0.5 print \"-----\" compound = numpy.asarray([10, 11])",
"probably doesn't demonstrate the intended behaviour # anymore since :func:`upy2.numpy_operators.install_numpy_operators` # is now",
"wavelength print wavelength ** 0.5 print \"-----\" compound = numpy.asarray([10, 11]) +- u([1,",
"U from upy2.typesetting import ScientificTypesetter # This test probably doesn't demonstrate the intended",
"the intended behaviour # anymore since :func:`upy2.numpy_operators.install_numpy_operators` # is now called unconditionally upon",
"precision=2).default() wavelength = 420 +- u(10) print wavelength print wavelength ** 0.5 print",
"u([1, 2]) print compound print \"-----\" #upy2.install_numpy_operators() compound2 = numpy.asarray([[100], [42]]) +- u([[1],",
"print \"-----\" compound = numpy.asarray([10, 11]) +- u([1, 2]) print compound print \"-----\"",
"\"-----\" compound = numpy.asarray([10, 11]) +- u([1, 2]) print compound print \"-----\" #upy2.install_numpy_operators()",
"compound = numpy.asarray([10, 11]) +- u([1, 2]) print compound print \"-----\" #upy2.install_numpy_operators() compound2",
"+- u(10) print wavelength print wavelength ** 0.5 print \"-----\" compound = numpy.asarray([10,",
"intended behaviour # anymore since :func:`upy2.numpy_operators.install_numpy_operators` # is now called unconditionally upon importing",
"doesn't demonstrate the intended behaviour # anymore since :func:`upy2.numpy_operators.install_numpy_operators` # is now called",
"called unconditionally upon importing ``upy2``. U(2).default() ScientificTypesetter(stddevs=2, precision=2).default() wavelength = 420 +- u(10)",
"u, U from upy2.typesetting import ScientificTypesetter # This test probably doesn't demonstrate the",
"upy2.typesetting import ScientificTypesetter # This test probably doesn't demonstrate the intended behaviour #",
"since :func:`upy2.numpy_operators.install_numpy_operators` # is now called unconditionally upon importing ``upy2``. U(2).default() ScientificTypesetter(stddevs=2, precision=2).default()",
"now called unconditionally upon importing ``upy2``. U(2).default() ScientificTypesetter(stddevs=2, precision=2).default() wavelength = 420 +-",
"importing ``upy2``. U(2).default() ScientificTypesetter(stddevs=2, precision=2).default() wavelength = 420 +- u(10) print wavelength print",
"# anymore since :func:`upy2.numpy_operators.install_numpy_operators` # is now called unconditionally upon importing ``upy2``. U(2).default()",
"print wavelength ** 0.5 print \"-----\" compound = numpy.asarray([10, 11]) +- u([1, 2])"
] |
[
"check each piece has a reasonable size batch_size = 1000 max_piece_size = 100",
"import random import pytest import pandas as pd def build_random_filecounts(min_count=100, max_count=10000): count_before =",
"random import pytest import pandas as pd def build_random_filecounts(min_count=100, max_count=10000): count_before = 0",
"100000), (10000, 300000)]) def test_piece_builder(start, end): # generate random file counts # call",
"pieces = build_pieces( file_counts, batch_size, start, end, max_piece_size=max_piece_size, metadata_columns=[\"custommeta\"] ) assert pieces[\"piece_length\"].sum() ==",
"100000), (100, 100000), (10000, 300000)]) def test_piece_builder(start, end): # generate random file counts",
"pieces[\"filename\"], ): assert 0 < piece_length <= max_piece_size assert piece_start >= 0 assert",
"for piece_start, piece_end, piece_length, batch_start, batch_end, batch_length, filename in zip( pieces[\"piece_start\"], pieces[\"piece_end\"], pieces[\"piece_length\"],",
"file counts # call piece builder # check piece length is not empty",
">= 0 assert piece_start < piece_end assert batch_start < batch_end assert batch_length <=",
"batch_size assert batch_end <= end assert batch_end - batch_start <= batch_size assert piece_end",
"# check each piece has a reasonable size assert pieces[\"piece_length\"].max() <= max_piece_size @pytest.mark.parametrize([\"start\",",
"piece has a reasonable size assert pieces[\"piece_length\"].max() <= max_piece_size @pytest.mark.parametrize([\"start\", \"end\"], [(9, 15)])",
"assert piece_start < piece_end assert batch_start < batch_end assert batch_length <= batch_size assert",
"# check sum is correct # check each piece has a reasonable size",
"+= r return pd.DataFrame(results, columns=[\"count\", \"count_before\", \"filename\", \"custommeta\"]) @pytest.mark.parametrize([\"start\", \"end\"], [(0, 100000), (100,",
"r return pd.DataFrame(results, columns=[\"count\", \"count_before\", \"filename\", \"custommeta\"]) @pytest.mark.parametrize([\"start\", \"end\"], [(0, 100000), (100, 100000),",
"def build_random_filecounts(min_count=100, max_count=10000): count_before = 0 results = [] for i in range(1000):",
"sum is correct # check each piece has a reasonable size batch_size =",
"= 1000 max_piece_size = 100 file_counts = build_random_filecounts() pieces = build_pieces( file_counts, batch_size,",
"assert batch_length <= batch_size assert batch_end <= end assert batch_end - batch_start <=",
"piece length is not empty batch_size = 1000 max_piece_size = 100 file_counts =",
"build_pieces( file_counts, batch_size, start, end, max_piece_size=max_piece_size, metadata_columns=[\"custommeta\"] ) for piece_start, piece_end, piece_length, batch_start,",
"[(0, 100000), (100, 100000), (10000, 300000)]) def test_piece_builder(start, end): # generate random file",
"in zip( pieces[\"piece_start\"], pieces[\"piece_end\"], pieces[\"piece_length\"], pieces[\"batch_start\"], pieces[\"batch_end\"], pieces[\"batch_length\"], pieces[\"filename\"], ): assert 0 <",
"def test_piece_builder(start, end): # generate random file counts # call piece builder #",
"filename in zip(file_counts[\"count\"], file_counts[\"filename\"])} for piece_start, piece_end, piece_length, batch_start, batch_end, batch_length, filename in",
"# check each piece has a reasonable size batch_size = 1000 max_piece_size =",
"assert pieces[\"piece_length\"].max() <= max_piece_size @pytest.mark.parametrize([\"start\", \"end\"], [(9, 15)]) def test_piece_builder_with_empty_file(start, end): # generate",
"[(9, 15)]) def test_piece_builder_with_empty_file(start, end): # generate random file counts # call piece",
"start filename_to_count = {filename: count for count, filename in zip(file_counts[\"count\"], file_counts[\"filename\"])} for piece_start,",
"length is not empty batch_size = 1000 max_piece_size = 100 file_counts = build_random_filecounts(min_count=0,",
"max_count) results.append([r, count_before, str(i) + \".npy\", \"someval\" + str(i)]) count_before += r return",
"file_counts = build_random_filecounts(min_count=0, max_count=1) pieces = build_pieces( file_counts, batch_size, start, end, max_piece_size=max_piece_size, metadata_columns=[\"custommeta\"]",
"+ \".npy\", \"someval\" + str(i)]) count_before += r return pd.DataFrame(results, columns=[\"count\", \"count_before\", \"filename\",",
"test_piece_builder_with_empty_file(start, end): # generate random file counts # call piece builder # check",
"for i in range(1000): r = random.randint(min_count, max_count) results.append([r, count_before, str(i) + \".npy\",",
"file counts # call piece builder # check sum is correct # check",
"batch_size = 1000 max_piece_size = 100 file_counts = build_random_filecounts() pieces = build_pieces( file_counts,",
"piece_start >= 0 assert piece_start < piece_end assert batch_start < batch_end assert batch_length",
"# generate random file counts # call piece builder # check sum is",
"file_counts, batch_size, start, end, max_piece_size=max_piece_size, metadata_columns=[\"custommeta\"] ) for piece_start, piece_end, piece_length, batch_start, batch_end,",
"as pd def build_random_filecounts(min_count=100, max_count=10000): count_before = 0 results = [] for i",
"[] for i in range(1000): r = random.randint(min_count, max_count) results.append([r, count_before, str(i) +",
"# check piece length is not empty batch_size = 1000 max_piece_size = 100",
"pd.DataFrame(results, columns=[\"count\", \"count_before\", \"filename\", \"custommeta\"]) @pytest.mark.parametrize([\"start\", \"end\"], [(0, 100000), (100, 100000), (10000, 300000)])",
"# call piece builder # check piece length is not empty batch_size =",
"assert 0 < piece_length <= max_piece_size assert piece_start >= 0 assert piece_start <",
"end assert batch_end - batch_start <= batch_size assert piece_end <= filename_to_count[filename] # check",
"assert piece_start >= 0 assert piece_start < piece_end assert batch_start < batch_end assert",
"filename_to_count = {filename: count for count, filename in zip(file_counts[\"count\"], file_counts[\"filename\"])} for piece_start, piece_end,",
"random file counts # call piece builder # check sum is correct #",
"max_count=10000): count_before = 0 results = [] for i in range(1000): r =",
"pieces[\"piece_length\"].sum() == end - start filename_to_count = {filename: count for count, filename in",
"range(1000): r = random.randint(min_count, max_count) results.append([r, count_before, str(i) + \".npy\", \"someval\" + str(i)])",
"import pandas as pd def build_random_filecounts(min_count=100, max_count=10000): count_before = 0 results = []",
"columns=[\"count\", \"count_before\", \"filename\", \"custommeta\"]) @pytest.mark.parametrize([\"start\", \"end\"], [(0, 100000), (100, 100000), (10000, 300000)]) def",
"not empty batch_size = 1000 max_piece_size = 100 file_counts = build_random_filecounts(min_count=0, max_count=1) pieces",
"batch_size = 1000 max_piece_size = 100 file_counts = build_random_filecounts(min_count=0, max_count=1) pieces = build_pieces(",
"assert batch_start < batch_end assert batch_length <= batch_size assert batch_end <= end assert",
"pieces[\"batch_length\"], pieces[\"filename\"], ): assert 0 < piece_length <= max_piece_size assert piece_start >= 0",
"generate random file counts # call piece builder # check piece length is",
"= build_random_filecounts(min_count=0, max_count=1) pieces = build_pieces( file_counts, batch_size, start, end, max_piece_size=max_piece_size, metadata_columns=[\"custommeta\"] )",
") assert pieces[\"piece_length\"].sum() == end - start filename_to_count = {filename: count for count,",
"piece builder # check piece length is not empty batch_size = 1000 max_piece_size",
"count, filename in zip(file_counts[\"count\"], file_counts[\"filename\"])} for piece_start, piece_end, piece_length, batch_start, batch_end, batch_length, filename",
"for count, filename in zip(file_counts[\"count\"], file_counts[\"filename\"])} for piece_start, piece_end, piece_length, batch_start, batch_end, batch_length,",
"check sum is correct # check each piece has a reasonable size batch_size",
"@pytest.mark.parametrize([\"start\", \"end\"], [(9, 15)]) def test_piece_builder_with_empty_file(start, end): # generate random file counts #",
"max_piece_size = 100 file_counts = build_random_filecounts(min_count=0, max_count=1) pieces = build_pieces( file_counts, batch_size, start,",
"pandas as pd def build_random_filecounts(min_count=100, max_count=10000): count_before = 0 results = [] for",
"results = [] for i in range(1000): r = random.randint(min_count, max_count) results.append([r, count_before,",
"pieces[\"batch_end\"], pieces[\"batch_length\"], pieces[\"filename\"], ): assert 0 < piece_length <= max_piece_size assert piece_start >=",
"from embedding_reader.piece_builder import build_pieces import random import pytest import pandas as pd def",
"generate random file counts # call piece builder # check sum is correct",
"filename_to_count[filename] # check each piece has a reasonable size assert pieces[\"piece_length\"].max() <= max_piece_size",
"results.append([r, count_before, str(i) + \".npy\", \"someval\" + str(i)]) count_before += r return pd.DataFrame(results,",
"build_pieces import random import pytest import pandas as pd def build_random_filecounts(min_count=100, max_count=10000): count_before",
"\"end\"], [(9, 15)]) def test_piece_builder_with_empty_file(start, end): # generate random file counts # call",
"counts # call piece builder # check piece length is not empty batch_size",
"piece_end, piece_length, batch_start, batch_end, batch_length, filename in zip( pieces[\"piece_start\"], pieces[\"piece_end\"], pieces[\"piece_length\"], pieces[\"batch_start\"], pieces[\"batch_end\"],",
"check piece length is not empty batch_size = 1000 max_piece_size = 100 file_counts",
"call piece builder # check sum is correct # check each piece has",
"counts # call piece builder # check sum is correct # check each",
"= {filename: count for count, filename in zip(file_counts[\"count\"], file_counts[\"filename\"])} for piece_start, piece_end, piece_length,",
"correct # check each piece has a reasonable size batch_size = 1000 max_piece_size",
"100 file_counts = build_random_filecounts(min_count=0, max_count=1) pieces = build_pieces( file_counts, batch_size, start, end, max_piece_size=max_piece_size,",
"pieces[\"batch_start\"], pieces[\"batch_end\"], pieces[\"batch_length\"], pieces[\"filename\"], ): assert 0 < piece_length <= max_piece_size assert piece_start",
"# call piece builder # check sum is correct # check each piece",
"0 < piece_length <= max_piece_size assert piece_start >= 0 assert piece_start < piece_end",
"piece_start < piece_end assert batch_start < batch_end assert batch_length <= batch_size assert batch_end",
"batch_start < batch_end assert batch_length <= batch_size assert batch_end <= end assert batch_end",
"each piece has a reasonable size batch_size = 1000 max_piece_size = 100 file_counts",
"in zip(file_counts[\"count\"], file_counts[\"filename\"])} for piece_start, piece_end, piece_length, batch_start, batch_end, batch_length, filename in zip(",
"max_piece_size @pytest.mark.parametrize([\"start\", \"end\"], [(9, 15)]) def test_piece_builder_with_empty_file(start, end): # generate random file counts",
"batch_end, batch_length, filename in zip( pieces[\"piece_start\"], pieces[\"piece_end\"], pieces[\"piece_length\"], pieces[\"batch_start\"], pieces[\"batch_end\"], pieces[\"batch_length\"], pieces[\"filename\"], ):",
"<= filename_to_count[filename] # check each piece has a reasonable size assert pieces[\"piece_length\"].max() <=",
"start, end, max_piece_size=max_piece_size, metadata_columns=[\"custommeta\"] ) assert pieces[\"piece_length\"].sum() == end - start filename_to_count =",
"build_random_filecounts() pieces = build_pieces( file_counts, batch_size, start, end, max_piece_size=max_piece_size, metadata_columns=[\"custommeta\"] ) assert pieces[\"piece_length\"].sum()",
"batch_size, start, end, max_piece_size=max_piece_size, metadata_columns=[\"custommeta\"] ) assert pieces[\"piece_length\"].sum() == end - start filename_to_count",
"- batch_start <= batch_size assert piece_end <= filename_to_count[filename] # check each piece has",
"piece_length <= max_piece_size assert piece_start >= 0 assert piece_start < piece_end assert batch_start",
"in zip( pieces[\"piece_start\"], pieces[\"piece_end\"], pieces[\"piece_length\"], pieces[\"batch_start\"], pieces[\"batch_end\"], pieces[\"batch_length\"], pieces[\"filename\"], ): assert piece_length !=",
"end, max_piece_size=max_piece_size, metadata_columns=[\"custommeta\"] ) assert pieces[\"piece_length\"].sum() == end - start filename_to_count = {filename:",
"\".npy\", \"someval\" + str(i)]) count_before += r return pd.DataFrame(results, columns=[\"count\", \"count_before\", \"filename\", \"custommeta\"])",
"return pd.DataFrame(results, columns=[\"count\", \"count_before\", \"filename\", \"custommeta\"]) @pytest.mark.parametrize([\"start\", \"end\"], [(0, 100000), (100, 100000), (10000,",
"(10000, 300000)]) def test_piece_builder(start, end): # generate random file counts # call piece",
"import build_pieces import random import pytest import pandas as pd def build_random_filecounts(min_count=100, max_count=10000):",
"zip(file_counts[\"count\"], file_counts[\"filename\"])} for piece_start, piece_end, piece_length, batch_start, batch_end, batch_length, filename in zip( pieces[\"piece_start\"],",
"15)]) def test_piece_builder_with_empty_file(start, end): # generate random file counts # call piece builder",
"file_counts[\"filename\"])} for piece_start, piece_end, piece_length, batch_start, batch_end, batch_length, filename in zip( pieces[\"piece_start\"], pieces[\"piece_end\"],",
"file_counts = build_random_filecounts() pieces = build_pieces( file_counts, batch_size, start, end, max_piece_size=max_piece_size, metadata_columns=[\"custommeta\"] )",
"assert batch_end <= end assert batch_end - batch_start <= batch_size assert piece_end <=",
"1000 max_piece_size = 100 file_counts = build_random_filecounts(min_count=0, max_count=1) pieces = build_pieces( file_counts, batch_size,",
"zip( pieces[\"piece_start\"], pieces[\"piece_end\"], pieces[\"piece_length\"], pieces[\"batch_start\"], pieces[\"batch_end\"], pieces[\"batch_length\"], pieces[\"filename\"], ): assert piece_length != 0",
"pieces[\"batch_start\"], pieces[\"batch_end\"], pieces[\"batch_length\"], pieces[\"filename\"], ): assert piece_length != 0 assert piece_start < piece_end",
"end - start filename_to_count = {filename: count for count, filename in zip(file_counts[\"count\"], file_counts[\"filename\"])}",
"@pytest.mark.parametrize([\"start\", \"end\"], [(0, 100000), (100, 100000), (10000, 300000)]) def test_piece_builder(start, end): # generate",
"pieces[\"piece_length\"].max() <= max_piece_size @pytest.mark.parametrize([\"start\", \"end\"], [(9, 15)]) def test_piece_builder_with_empty_file(start, end): # generate random",
"builder # check piece length is not empty batch_size = 1000 max_piece_size =",
"filename in zip( pieces[\"piece_start\"], pieces[\"piece_end\"], pieces[\"piece_length\"], pieces[\"batch_start\"], pieces[\"batch_end\"], pieces[\"batch_length\"], pieces[\"filename\"], ): assert piece_length",
"i in range(1000): r = random.randint(min_count, max_count) results.append([r, count_before, str(i) + \".npy\", \"someval\"",
"piece_end assert batch_start < batch_end assert batch_length <= batch_size assert batch_end <= end",
"is not empty batch_size = 1000 max_piece_size = 100 file_counts = build_random_filecounts(min_count=0, max_count=1)",
"max_count=1) pieces = build_pieces( file_counts, batch_size, start, end, max_piece_size=max_piece_size, metadata_columns=[\"custommeta\"] ) for piece_start,",
"= build_random_filecounts() pieces = build_pieces( file_counts, batch_size, start, end, max_piece_size=max_piece_size, metadata_columns=[\"custommeta\"] ) assert",
"check each piece has a reasonable size assert pieces[\"piece_length\"].max() <= max_piece_size @pytest.mark.parametrize([\"start\", \"end\"],",
"\"custommeta\"]) @pytest.mark.parametrize([\"start\", \"end\"], [(0, 100000), (100, 100000), (10000, 300000)]) def test_piece_builder(start, end): #",
"pytest import pandas as pd def build_random_filecounts(min_count=100, max_count=10000): count_before = 0 results =",
"<= max_piece_size assert piece_start >= 0 assert piece_start < piece_end assert batch_start <",
"max_piece_size = 100 file_counts = build_random_filecounts() pieces = build_pieces( file_counts, batch_size, start, end,",
"\"count_before\", \"filename\", \"custommeta\"]) @pytest.mark.parametrize([\"start\", \"end\"], [(0, 100000), (100, 100000), (10000, 300000)]) def test_piece_builder(start,",
"max_piece_size assert piece_start >= 0 assert piece_start < piece_end assert batch_start < batch_end",
"end): # generate random file counts # call piece builder # check piece",
"= random.randint(min_count, max_count) results.append([r, count_before, str(i) + \".npy\", \"someval\" + str(i)]) count_before +=",
"# generate random file counts # call piece builder # check piece length",
"start, end, max_piece_size=max_piece_size, metadata_columns=[\"custommeta\"] ) for piece_start, piece_end, piece_length, batch_start, batch_end, batch_length, filename",
"count_before = 0 results = [] for i in range(1000): r = random.randint(min_count,",
"r = random.randint(min_count, max_count) results.append([r, count_before, str(i) + \".npy\", \"someval\" + str(i)]) count_before",
"0 assert piece_start < piece_end assert batch_start < batch_end assert batch_length <= batch_size",
"count_before, str(i) + \".npy\", \"someval\" + str(i)]) count_before += r return pd.DataFrame(results, columns=[\"count\",",
"file_counts, batch_size, start, end, max_piece_size=max_piece_size, metadata_columns=[\"custommeta\"] ) assert pieces[\"piece_length\"].sum() == end - start",
"- start filename_to_count = {filename: count for count, filename in zip(file_counts[\"count\"], file_counts[\"filename\"])} for",
"count for count, filename in zip(file_counts[\"count\"], file_counts[\"filename\"])} for piece_start, piece_end, piece_length, batch_start, batch_end,",
"embedding_reader.piece_builder import build_pieces import random import pytest import pandas as pd def build_random_filecounts(min_count=100,",
"str(i)]) count_before += r return pd.DataFrame(results, columns=[\"count\", \"count_before\", \"filename\", \"custommeta\"]) @pytest.mark.parametrize([\"start\", \"end\"], [(0,",
"<= end assert batch_end - batch_start <= batch_size assert piece_end <= filename_to_count[filename] #",
"<= max_piece_size @pytest.mark.parametrize([\"start\", \"end\"], [(9, 15)]) def test_piece_builder_with_empty_file(start, end): # generate random file",
"max_piece_size=max_piece_size, metadata_columns=[\"custommeta\"] ) assert pieces[\"piece_length\"].sum() == end - start filename_to_count = {filename: count",
"import pytest import pandas as pd def build_random_filecounts(min_count=100, max_count=10000): count_before = 0 results",
"= 0 results = [] for i in range(1000): r = random.randint(min_count, max_count)",
"end, max_piece_size=max_piece_size, metadata_columns=[\"custommeta\"] ) for piece_start, piece_end, piece_length, batch_start, batch_end, batch_length, filename in",
"batch_size, start, end, max_piece_size=max_piece_size, metadata_columns=[\"custommeta\"] ) for piece_start, piece_end, piece_length, batch_start, batch_end, batch_length,",
"has a reasonable size batch_size = 1000 max_piece_size = 100 file_counts = build_random_filecounts()",
"piece_length, batch_start, batch_end, batch_length, filename in zip( pieces[\"piece_start\"], pieces[\"piece_end\"], pieces[\"piece_length\"], pieces[\"batch_start\"], pieces[\"batch_end\"], pieces[\"batch_length\"],",
"piece_end <= filename_to_count[filename] # check each piece has a reasonable size assert pieces[\"piece_length\"].max()",
"batch_end <= end assert batch_end - batch_start <= batch_size assert piece_end <= filename_to_count[filename]",
"test_piece_builder(start, end): # generate random file counts # call piece builder # check",
"in range(1000): r = random.randint(min_count, max_count) results.append([r, count_before, str(i) + \".npy\", \"someval\" +",
"piece builder # check sum is correct # check each piece has a",
"<= batch_size assert piece_end <= filename_to_count[filename] # check each piece has a reasonable",
"1000 max_piece_size = 100 file_counts = build_random_filecounts() pieces = build_pieces( file_counts, batch_size, start,",
"pd def build_random_filecounts(min_count=100, max_count=10000): count_before = 0 results = [] for i in",
"< piece_end assert batch_start < batch_end assert batch_length <= batch_size assert batch_end <=",
"batch_length, filename in zip( pieces[\"piece_start\"], pieces[\"piece_end\"], pieces[\"piece_length\"], pieces[\"batch_start\"], pieces[\"batch_end\"], pieces[\"batch_length\"], pieces[\"filename\"], ): assert",
"batch_start <= batch_size assert piece_end <= filename_to_count[filename] # check each piece has a",
"== end - start filename_to_count = {filename: count for count, filename in zip(file_counts[\"count\"],",
"metadata_columns=[\"custommeta\"] ) assert pieces[\"piece_length\"].sum() == end - start filename_to_count = {filename: count for",
"zip( pieces[\"piece_start\"], pieces[\"piece_end\"], pieces[\"piece_length\"], pieces[\"batch_start\"], pieces[\"batch_end\"], pieces[\"batch_length\"], pieces[\"filename\"], ): assert 0 < piece_length",
"metadata_columns=[\"custommeta\"] ) for piece_start, piece_end, piece_length, batch_start, batch_end, batch_length, filename in zip( pieces[\"piece_start\"],",
"batch_end - batch_start <= batch_size assert piece_end <= filename_to_count[filename] # check each piece",
"assert batch_end - batch_start <= batch_size assert piece_end <= filename_to_count[filename] # check each",
"assert pieces[\"piece_length\"].sum() == end - start filename_to_count = {filename: count for count, filename",
"end): # generate random file counts # call piece builder # check sum",
"size assert pieces[\"piece_length\"].max() <= max_piece_size @pytest.mark.parametrize([\"start\", \"end\"], [(9, 15)]) def test_piece_builder_with_empty_file(start, end): #",
"random file counts # call piece builder # check piece length is not",
"pieces[\"piece_end\"], pieces[\"piece_length\"], pieces[\"batch_start\"], pieces[\"batch_end\"], pieces[\"batch_length\"], pieces[\"filename\"], ): assert piece_length != 0 assert piece_start",
"\"end\"], [(0, 100000), (100, 100000), (10000, 300000)]) def test_piece_builder(start, end): # generate random",
") for piece_start, piece_end, piece_length, batch_start, batch_end, batch_length, filename in zip( pieces[\"piece_start\"], pieces[\"piece_end\"],",
"pieces[\"piece_start\"], pieces[\"piece_end\"], pieces[\"piece_length\"], pieces[\"batch_start\"], pieces[\"batch_end\"], pieces[\"batch_length\"], pieces[\"filename\"], ): assert 0 < piece_length <=",
"< batch_end assert batch_length <= batch_size assert batch_end <= end assert batch_end -",
"0 results = [] for i in range(1000): r = random.randint(min_count, max_count) results.append([r,",
"count_before += r return pd.DataFrame(results, columns=[\"count\", \"count_before\", \"filename\", \"custommeta\"]) @pytest.mark.parametrize([\"start\", \"end\"], [(0, 100000),",
"size batch_size = 1000 max_piece_size = 100 file_counts = build_random_filecounts() pieces = build_pieces(",
"batch_start, batch_end, batch_length, filename in zip( pieces[\"piece_start\"], pieces[\"piece_end\"], pieces[\"piece_length\"], pieces[\"batch_start\"], pieces[\"batch_end\"], pieces[\"batch_length\"], pieces[\"filename\"],",
"call piece builder # check piece length is not empty batch_size = 1000",
"reasonable size assert pieces[\"piece_length\"].max() <= max_piece_size @pytest.mark.parametrize([\"start\", \"end\"], [(9, 15)]) def test_piece_builder_with_empty_file(start, end):",
"= [] for i in range(1000): r = random.randint(min_count, max_count) results.append([r, count_before, str(i)",
"random.randint(min_count, max_count) results.append([r, count_before, str(i) + \".npy\", \"someval\" + str(i)]) count_before += r",
"pieces[\"piece_length\"], pieces[\"batch_start\"], pieces[\"batch_end\"], pieces[\"batch_length\"], pieces[\"filename\"], ): assert 0 < piece_length <= max_piece_size assert",
"= 1000 max_piece_size = 100 file_counts = build_random_filecounts(min_count=0, max_count=1) pieces = build_pieces( file_counts,",
"piece_start, piece_end, piece_length, batch_start, batch_end, batch_length, filename in zip( pieces[\"piece_start\"], pieces[\"piece_end\"], pieces[\"piece_length\"], pieces[\"batch_start\"],",
"300000)]) def test_piece_builder(start, end): # generate random file counts # call piece builder",
"builder # check sum is correct # check each piece has a reasonable",
"build_random_filecounts(min_count=100, max_count=10000): count_before = 0 results = [] for i in range(1000): r",
"\"someval\" + str(i)]) count_before += r return pd.DataFrame(results, columns=[\"count\", \"count_before\", \"filename\", \"custommeta\"]) @pytest.mark.parametrize([\"start\",",
"reasonable size batch_size = 1000 max_piece_size = 100 file_counts = build_random_filecounts() pieces =",
"batch_size assert piece_end <= filename_to_count[filename] # check each piece has a reasonable size",
"max_piece_size=max_piece_size, metadata_columns=[\"custommeta\"] ) for piece_start, piece_end, piece_length, batch_start, batch_end, batch_length, filename in zip(",
"= build_pieces( file_counts, batch_size, start, end, max_piece_size=max_piece_size, metadata_columns=[\"custommeta\"] ) for piece_start, piece_end, piece_length,",
"piece has a reasonable size batch_size = 1000 max_piece_size = 100 file_counts =",
"<filename>tests/test_piece_builder.py from embedding_reader.piece_builder import build_pieces import random import pytest import pandas as pd",
"{filename: count for count, filename in zip(file_counts[\"count\"], file_counts[\"filename\"])} for piece_start, piece_end, piece_length, batch_start,",
"a reasonable size assert pieces[\"piece_length\"].max() <= max_piece_size @pytest.mark.parametrize([\"start\", \"end\"], [(9, 15)]) def test_piece_builder_with_empty_file(start,",
"assert piece_end <= filename_to_count[filename] # check each piece has a reasonable size assert",
"): assert 0 < piece_length <= max_piece_size assert piece_start >= 0 assert piece_start",
"batch_end assert batch_length <= batch_size assert batch_end <= end assert batch_end - batch_start",
"= build_pieces( file_counts, batch_size, start, end, max_piece_size=max_piece_size, metadata_columns=[\"custommeta\"] ) assert pieces[\"piece_length\"].sum() == end",
"def test_piece_builder_with_empty_file(start, end): # generate random file counts # call piece builder #",
"a reasonable size batch_size = 1000 max_piece_size = 100 file_counts = build_random_filecounts() pieces",
"pieces[\"piece_end\"], pieces[\"piece_length\"], pieces[\"batch_start\"], pieces[\"batch_end\"], pieces[\"batch_length\"], pieces[\"filename\"], ): assert 0 < piece_length <= max_piece_size",
"(100, 100000), (10000, 300000)]) def test_piece_builder(start, end): # generate random file counts #",
"= 100 file_counts = build_random_filecounts() pieces = build_pieces( file_counts, batch_size, start, end, max_piece_size=max_piece_size,",
"<= batch_size assert batch_end <= end assert batch_end - batch_start <= batch_size assert",
"\"filename\", \"custommeta\"]) @pytest.mark.parametrize([\"start\", \"end\"], [(0, 100000), (100, 100000), (10000, 300000)]) def test_piece_builder(start, end):",
"has a reasonable size assert pieces[\"piece_length\"].max() <= max_piece_size @pytest.mark.parametrize([\"start\", \"end\"], [(9, 15)]) def",
"each piece has a reasonable size assert pieces[\"piece_length\"].max() <= max_piece_size @pytest.mark.parametrize([\"start\", \"end\"], [(9,",
"= 100 file_counts = build_random_filecounts(min_count=0, max_count=1) pieces = build_pieces( file_counts, batch_size, start, end,",
"pieces[\"piece_length\"], pieces[\"batch_start\"], pieces[\"batch_end\"], pieces[\"batch_length\"], pieces[\"filename\"], ): assert piece_length != 0 assert piece_start <",
"batch_length <= batch_size assert batch_end <= end assert batch_end - batch_start <= batch_size",
"is correct # check each piece has a reasonable size batch_size = 1000",
"< piece_length <= max_piece_size assert piece_start >= 0 assert piece_start < piece_end assert",
"pieces[\"piece_start\"], pieces[\"piece_end\"], pieces[\"piece_length\"], pieces[\"batch_start\"], pieces[\"batch_end\"], pieces[\"batch_length\"], pieces[\"filename\"], ): assert piece_length != 0 assert",
"100 file_counts = build_random_filecounts() pieces = build_pieces( file_counts, batch_size, start, end, max_piece_size=max_piece_size, metadata_columns=[\"custommeta\"]",
"str(i) + \".npy\", \"someval\" + str(i)]) count_before += r return pd.DataFrame(results, columns=[\"count\", \"count_before\",",
"+ str(i)]) count_before += r return pd.DataFrame(results, columns=[\"count\", \"count_before\", \"filename\", \"custommeta\"]) @pytest.mark.parametrize([\"start\", \"end\"],",
"build_pieces( file_counts, batch_size, start, end, max_piece_size=max_piece_size, metadata_columns=[\"custommeta\"] ) assert pieces[\"piece_length\"].sum() == end -",
"pieces = build_pieces( file_counts, batch_size, start, end, max_piece_size=max_piece_size, metadata_columns=[\"custommeta\"] ) for piece_start, piece_end,",
"build_random_filecounts(min_count=0, max_count=1) pieces = build_pieces( file_counts, batch_size, start, end, max_piece_size=max_piece_size, metadata_columns=[\"custommeta\"] ) for",
"empty batch_size = 1000 max_piece_size = 100 file_counts = build_random_filecounts(min_count=0, max_count=1) pieces =",
"filename in zip( pieces[\"piece_start\"], pieces[\"piece_end\"], pieces[\"piece_length\"], pieces[\"batch_start\"], pieces[\"batch_end\"], pieces[\"batch_length\"], pieces[\"filename\"], ): assert 0"
] |
[
"coroutines to the already running event loop await asyncio.gather( BroadcastTransactionsCommand(self.adapter)(**request), StoreTransactionsCommand(self.adapter)(**request), ) return",
"already running event loop await asyncio.gather( BroadcastTransactionsCommand(self.adapter)(**request), StoreTransactionsCommand(self.adapter)(**request), ) return { 'trytes': request['trytes'],",
"\"\"\" Executes ``broadcastAndStore`` extended API command. See :py:meth:`iota.api.Iota.broadcast_and_store` for more info. \"\"\" command",
"dict) -> dict: # Submit the two coroutines to the already running event",
"pass def get_response_filter(self): pass async def _execute(self, request: dict) -> dict: # Submit",
"from iota.commands import FilterCommand from iota.commands.core.broadcast_transactions import \\ BroadcastTransactionsCommand from iota.commands.core.store_transactions import StoreTransactionsCommand",
"import asyncio __all__ = [ 'BroadcastAndStoreCommand', ] class BroadcastAndStoreCommand(FilterCommand): \"\"\" Executes ``broadcastAndStore`` extended",
"] class BroadcastAndStoreCommand(FilterCommand): \"\"\" Executes ``broadcastAndStore`` extended API command. See :py:meth:`iota.api.Iota.broadcast_and_store` for more",
"info. \"\"\" command = 'broadcastAndStore' def get_request_filter(self): pass def get_response_filter(self): pass async def",
"command = 'broadcastAndStore' def get_request_filter(self): pass def get_response_filter(self): pass async def _execute(self, request:",
"iota.commands.core.broadcast_transactions import \\ BroadcastTransactionsCommand from iota.commands.core.store_transactions import StoreTransactionsCommand import asyncio __all__ = [",
"= 'broadcastAndStore' def get_request_filter(self): pass def get_response_filter(self): pass async def _execute(self, request: dict)",
"FilterCommand from iota.commands.core.broadcast_transactions import \\ BroadcastTransactionsCommand from iota.commands.core.store_transactions import StoreTransactionsCommand import asyncio __all__",
":py:meth:`iota.api.Iota.broadcast_and_store` for more info. \"\"\" command = 'broadcastAndStore' def get_request_filter(self): pass def get_response_filter(self):",
"running event loop await asyncio.gather( BroadcastTransactionsCommand(self.adapter)(**request), StoreTransactionsCommand(self.adapter)(**request), ) return { 'trytes': request['trytes'], }",
"more info. \"\"\" command = 'broadcastAndStore' def get_request_filter(self): pass def get_response_filter(self): pass async",
"class BroadcastAndStoreCommand(FilterCommand): \"\"\" Executes ``broadcastAndStore`` extended API command. See :py:meth:`iota.api.Iota.broadcast_and_store` for more info.",
"iota.commands.core.store_transactions import StoreTransactionsCommand import asyncio __all__ = [ 'BroadcastAndStoreCommand', ] class BroadcastAndStoreCommand(FilterCommand): \"\"\"",
"API command. See :py:meth:`iota.api.Iota.broadcast_and_store` for more info. \"\"\" command = 'broadcastAndStore' def get_request_filter(self):",
"StoreTransactionsCommand import asyncio __all__ = [ 'BroadcastAndStoreCommand', ] class BroadcastAndStoreCommand(FilterCommand): \"\"\" Executes ``broadcastAndStore``",
"'BroadcastAndStoreCommand', ] class BroadcastAndStoreCommand(FilterCommand): \"\"\" Executes ``broadcastAndStore`` extended API command. See :py:meth:`iota.api.Iota.broadcast_and_store` for",
"import StoreTransactionsCommand import asyncio __all__ = [ 'BroadcastAndStoreCommand', ] class BroadcastAndStoreCommand(FilterCommand): \"\"\" Executes",
"BroadcastAndStoreCommand(FilterCommand): \"\"\" Executes ``broadcastAndStore`` extended API command. See :py:meth:`iota.api.Iota.broadcast_and_store` for more info. \"\"\"",
"async def _execute(self, request: dict) -> dict: # Submit the two coroutines to",
"iota.commands import FilterCommand from iota.commands.core.broadcast_transactions import \\ BroadcastTransactionsCommand from iota.commands.core.store_transactions import StoreTransactionsCommand import",
"the two coroutines to the already running event loop await asyncio.gather( BroadcastTransactionsCommand(self.adapter)(**request), StoreTransactionsCommand(self.adapter)(**request),",
"asyncio __all__ = [ 'BroadcastAndStoreCommand', ] class BroadcastAndStoreCommand(FilterCommand): \"\"\" Executes ``broadcastAndStore`` extended API",
"extended API command. See :py:meth:`iota.api.Iota.broadcast_and_store` for more info. \"\"\" command = 'broadcastAndStore' def",
"import \\ BroadcastTransactionsCommand from iota.commands.core.store_transactions import StoreTransactionsCommand import asyncio __all__ = [ 'BroadcastAndStoreCommand',",
"import FilterCommand from iota.commands.core.broadcast_transactions import \\ BroadcastTransactionsCommand from iota.commands.core.store_transactions import StoreTransactionsCommand import asyncio",
"pass async def _execute(self, request: dict) -> dict: # Submit the two coroutines",
"for more info. \"\"\" command = 'broadcastAndStore' def get_request_filter(self): pass def get_response_filter(self): pass",
"request: dict) -> dict: # Submit the two coroutines to the already running",
"two coroutines to the already running event loop await asyncio.gather( BroadcastTransactionsCommand(self.adapter)(**request), StoreTransactionsCommand(self.adapter)(**request), )",
"# Submit the two coroutines to the already running event loop await asyncio.gather(",
"[ 'BroadcastAndStoreCommand', ] class BroadcastAndStoreCommand(FilterCommand): \"\"\" Executes ``broadcastAndStore`` extended API command. See :py:meth:`iota.api.Iota.broadcast_and_store`",
"__all__ = [ 'BroadcastAndStoreCommand', ] class BroadcastAndStoreCommand(FilterCommand): \"\"\" Executes ``broadcastAndStore`` extended API command.",
"``broadcastAndStore`` extended API command. See :py:meth:`iota.api.Iota.broadcast_and_store` for more info. \"\"\" command = 'broadcastAndStore'",
"'broadcastAndStore' def get_request_filter(self): pass def get_response_filter(self): pass async def _execute(self, request: dict) ->",
"Executes ``broadcastAndStore`` extended API command. See :py:meth:`iota.api.Iota.broadcast_and_store` for more info. \"\"\" command =",
"to the already running event loop await asyncio.gather( BroadcastTransactionsCommand(self.adapter)(**request), StoreTransactionsCommand(self.adapter)(**request), ) return {",
"def get_response_filter(self): pass async def _execute(self, request: dict) -> dict: # Submit the",
"dict: # Submit the two coroutines to the already running event loop await",
"def get_request_filter(self): pass def get_response_filter(self): pass async def _execute(self, request: dict) -> dict:",
"get_request_filter(self): pass def get_response_filter(self): pass async def _execute(self, request: dict) -> dict: #",
"-> dict: # Submit the two coroutines to the already running event loop",
"the already running event loop await asyncio.gather( BroadcastTransactionsCommand(self.adapter)(**request), StoreTransactionsCommand(self.adapter)(**request), ) return { 'trytes':",
"\"\"\" command = 'broadcastAndStore' def get_request_filter(self): pass def get_response_filter(self): pass async def _execute(self,",
"Submit the two coroutines to the already running event loop await asyncio.gather( BroadcastTransactionsCommand(self.adapter)(**request),",
"command. See :py:meth:`iota.api.Iota.broadcast_and_store` for more info. \"\"\" command = 'broadcastAndStore' def get_request_filter(self): pass",
"= [ 'BroadcastAndStoreCommand', ] class BroadcastAndStoreCommand(FilterCommand): \"\"\" Executes ``broadcastAndStore`` extended API command. See",
"get_response_filter(self): pass async def _execute(self, request: dict) -> dict: # Submit the two",
"from iota.commands.core.broadcast_transactions import \\ BroadcastTransactionsCommand from iota.commands.core.store_transactions import StoreTransactionsCommand import asyncio __all__ =",
"from iota.commands.core.store_transactions import StoreTransactionsCommand import asyncio __all__ = [ 'BroadcastAndStoreCommand', ] class BroadcastAndStoreCommand(FilterCommand):",
"<reponame>EasonC13/iota.py<gh_stars>100-1000 from iota.commands import FilterCommand from iota.commands.core.broadcast_transactions import \\ BroadcastTransactionsCommand from iota.commands.core.store_transactions import",
"_execute(self, request: dict) -> dict: # Submit the two coroutines to the already",
"def _execute(self, request: dict) -> dict: # Submit the two coroutines to the",
"BroadcastTransactionsCommand from iota.commands.core.store_transactions import StoreTransactionsCommand import asyncio __all__ = [ 'BroadcastAndStoreCommand', ] class",
"See :py:meth:`iota.api.Iota.broadcast_and_store` for more info. \"\"\" command = 'broadcastAndStore' def get_request_filter(self): pass def",
"\\ BroadcastTransactionsCommand from iota.commands.core.store_transactions import StoreTransactionsCommand import asyncio __all__ = [ 'BroadcastAndStoreCommand', ]"
] |
[
"True while check: if len(driver.window_handles) > 1: driver.switch_to.window(driver.window_handles[1]) driver.close() else: check = False",
"time from selenium import webdriver import requests driver = webdriver.Chrome(\"driver.exe\") def main(): url",
"webdriver.Chrome(\"driver.exe\") def main(): url = input(\"URL: \") driver.get(url) count = 0 input() tap_closer()",
"tap_closer() while True: count += 1 r = requests.get(url) print(str(count) + \" :",
"> 1: driver.switch_to.window(driver.window_handles[1]) driver.close() else: check = False if __name__ == \"__main__\": main()",
"requests.get(url) print(str(count) + \" : \" + str(r.status_code)) driver.switch_to.window(driver.window_handles[0]) driver.refresh() # Change the",
"reloads # time.sleep(0.5) tap_closer() def tap_closer(): check = True while check: if len(driver.window_handles)",
"check = True while check: if len(driver.window_handles) > 1: driver.switch_to.window(driver.window_handles[1]) driver.close() else: check",
"count = 0 input() tap_closer() while True: count += 1 r = requests.get(url)",
"while True: count += 1 r = requests.get(url) print(str(count) + \" : \"",
"selenium import webdriver import requests driver = webdriver.Chrome(\"driver.exe\") def main(): url = input(\"URL:",
"the \"0.5\" to how many seconds you want in between reloads # time.sleep(0.5)",
"# time.sleep(0.5) tap_closer() def tap_closer(): check = True while check: if len(driver.window_handles) >",
"= input(\"URL: \") driver.get(url) count = 0 input() tap_closer() while True: count +=",
"str(r.status_code)) driver.switch_to.window(driver.window_handles[0]) driver.refresh() # Change the \"0.5\" to how many seconds you want",
"1 r = requests.get(url) print(str(count) + \" : \" + str(r.status_code)) driver.switch_to.window(driver.window_handles[0]) driver.refresh()",
"tap_closer(): check = True while check: if len(driver.window_handles) > 1: driver.switch_to.window(driver.window_handles[1]) driver.close() else:",
"driver.get(url) count = 0 input() tap_closer() while True: count += 1 r =",
"seconds you want in between reloads # time.sleep(0.5) tap_closer() def tap_closer(): check =",
": \" + str(r.status_code)) driver.switch_to.window(driver.window_handles[0]) driver.refresh() # Change the \"0.5\" to how many",
"requests driver = webdriver.Chrome(\"driver.exe\") def main(): url = input(\"URL: \") driver.get(url) count =",
"url = input(\"URL: \") driver.get(url) count = 0 input() tap_closer() while True: count",
"input(\"URL: \") driver.get(url) count = 0 input() tap_closer() while True: count += 1",
"\" : \" + str(r.status_code)) driver.switch_to.window(driver.window_handles[0]) driver.refresh() # Change the \"0.5\" to how",
"def main(): url = input(\"URL: \") driver.get(url) count = 0 input() tap_closer() while",
"Change the \"0.5\" to how many seconds you want in between reloads #",
"how many seconds you want in between reloads # time.sleep(0.5) tap_closer() def tap_closer():",
"input() tap_closer() while True: count += 1 r = requests.get(url) print(str(count) + \"",
"while check: if len(driver.window_handles) > 1: driver.switch_to.window(driver.window_handles[1]) driver.close() else: check = False if",
"def tap_closer(): check = True while check: if len(driver.window_handles) > 1: driver.switch_to.window(driver.window_handles[1]) driver.close()",
"main(): url = input(\"URL: \") driver.get(url) count = 0 input() tap_closer() while True:",
"len(driver.window_handles) > 1: driver.switch_to.window(driver.window_handles[1]) driver.close() else: check = False if __name__ == \"__main__\":",
"you want in between reloads # time.sleep(0.5) tap_closer() def tap_closer(): check = True",
"= True while check: if len(driver.window_handles) > 1: driver.switch_to.window(driver.window_handles[1]) driver.close() else: check =",
"webdriver import requests driver = webdriver.Chrome(\"driver.exe\") def main(): url = input(\"URL: \") driver.get(url)",
"import webdriver import requests driver = webdriver.Chrome(\"driver.exe\") def main(): url = input(\"URL: \")",
"to how many seconds you want in between reloads # time.sleep(0.5) tap_closer() def",
"between reloads # time.sleep(0.5) tap_closer() def tap_closer(): check = True while check: if",
"# Change the \"0.5\" to how many seconds you want in between reloads",
"+ \" : \" + str(r.status_code)) driver.switch_to.window(driver.window_handles[0]) driver.refresh() # Change the \"0.5\" to",
"r = requests.get(url) print(str(count) + \" : \" + str(r.status_code)) driver.switch_to.window(driver.window_handles[0]) driver.refresh() #",
"many seconds you want in between reloads # time.sleep(0.5) tap_closer() def tap_closer(): check",
"count += 1 r = requests.get(url) print(str(count) + \" : \" + str(r.status_code))",
"<filename>lol.py import time from selenium import webdriver import requests driver = webdriver.Chrome(\"driver.exe\") def",
"= 0 input() tap_closer() while True: count += 1 r = requests.get(url) print(str(count)",
"time.sleep(0.5) tap_closer() def tap_closer(): check = True while check: if len(driver.window_handles) > 1:",
"True: count += 1 r = requests.get(url) print(str(count) + \" : \" +",
"if len(driver.window_handles) > 1: driver.switch_to.window(driver.window_handles[1]) driver.close() else: check = False if __name__ ==",
"= webdriver.Chrome(\"driver.exe\") def main(): url = input(\"URL: \") driver.get(url) count = 0 input()",
"\") driver.get(url) count = 0 input() tap_closer() while True: count += 1 r",
"+ str(r.status_code)) driver.switch_to.window(driver.window_handles[0]) driver.refresh() # Change the \"0.5\" to how many seconds you",
"import requests driver = webdriver.Chrome(\"driver.exe\") def main(): url = input(\"URL: \") driver.get(url) count",
"\"0.5\" to how many seconds you want in between reloads # time.sleep(0.5) tap_closer()",
"from selenium import webdriver import requests driver = webdriver.Chrome(\"driver.exe\") def main(): url =",
"want in between reloads # time.sleep(0.5) tap_closer() def tap_closer(): check = True while",
"= requests.get(url) print(str(count) + \" : \" + str(r.status_code)) driver.switch_to.window(driver.window_handles[0]) driver.refresh() # Change",
"print(str(count) + \" : \" + str(r.status_code)) driver.switch_to.window(driver.window_handles[0]) driver.refresh() # Change the \"0.5\"",
"in between reloads # time.sleep(0.5) tap_closer() def tap_closer(): check = True while check:",
"tap_closer() def tap_closer(): check = True while check: if len(driver.window_handles) > 1: driver.switch_to.window(driver.window_handles[1])",
"driver.switch_to.window(driver.window_handles[0]) driver.refresh() # Change the \"0.5\" to how many seconds you want in",
"0 input() tap_closer() while True: count += 1 r = requests.get(url) print(str(count) +",
"driver = webdriver.Chrome(\"driver.exe\") def main(): url = input(\"URL: \") driver.get(url) count = 0",
"+= 1 r = requests.get(url) print(str(count) + \" : \" + str(r.status_code)) driver.switch_to.window(driver.window_handles[0])",
"\" + str(r.status_code)) driver.switch_to.window(driver.window_handles[0]) driver.refresh() # Change the \"0.5\" to how many seconds",
"import time from selenium import webdriver import requests driver = webdriver.Chrome(\"driver.exe\") def main():",
"check: if len(driver.window_handles) > 1: driver.switch_to.window(driver.window_handles[1]) driver.close() else: check = False if __name__",
"driver.refresh() # Change the \"0.5\" to how many seconds you want in between"
] |
[
"= cube_size[2] # 64 self.L = cube_size[0]*cube_size[1] # 90 self.R = self.L*self.D #",
"# * cell ~ [1,batch,H] hidden,cell = self.initializeLSTM(xt) # Prediction container if self.training:",
"hidden ~ [ layers ,batch,H] # * cell ~ [ layers ,batch,H] _,(ht,ct)=",
"# [sequence,batch,4] # Prediction container st_,ht_ = list(),list() # State initialization if self.training:",
"hidden [1,batch,H] * Output: alpha [batch,L,1] \"\"\" class TVADecoder(nn.Module): \"\"\" Constructor \"\"\" def",
"class DualDecoder(nn.Module): \"\"\" Constructor \"\"\" def __init__(self,AttentionNet,ControlNet,cube_size,n_hidden): super(DualDecoder, self).__init__() # Parameters self.D =",
"Parameters sequence_len = self.sequence_len if self.training: batch_size = int(feature.shape[0]/sequence_len) else : batch_size =",
"* hidden ~ [ layers ,batch,H] # * cell ~ [ layers ,batch,H]",
"# [sequence,batch, ...] else : sequence = feature # [batch, ...] # Inicialize",
"visual = visual.unsqueeze(0) # [1,batch,R] # LSTM # * yt ~ [sequence,batch,H] #",
"if self.training: self.pred = self.pred.view(sequence_len,batch_size, n_out) self. map = self. map.view(sequence_len,batch_size,self.L) # Sequence",
"self.R, hidden_size = self.H, num_layers = 1) self.init_Wh = nn.Linear(self.D,self.H,bias=True ) self.init_Wc =",
"* Output: hidden [1,batch,H] cell [1,batch,H] \"\"\" def initializeLSTM(self,feature): with torch.no_grad(): # Mean",
"bet_.transpose(0,1).contiguous().view(batch_size*sequence_len,self.D) hdd_ = hdd_.transpose(0,1).contiguous().view(batch_size*sequence_len,self.H) return vis_, hdd_, {'alpha': alp_, 'beta': bet_}, {'control': hc}",
"= nn.LSTM( input_size = self.R, hidden_size = self.H, num_layers = 1) self.init_Wh =",
"LSTM # * yt ~ [sequence,batch,H] # * hidden ~ [ layers ,batch,H]",
"Output vis_[k] = visual # [1,batch,R] alp_[k] = alpha.squeeze() # [1,batch,L] bet_[k] =",
"Output: hidden [1,batch,H] cell [1,batch,H] \"\"\" def initializeLSTM(self,feature): with torch.no_grad(): # Mean features",
"cell = self.init_tanh(cell) # [batch,H] cell = cell.unsqueeze(0) # [1,batch,H] # (h,c) ~",
"hidden_size = self.H, num_layers = 1) self.init_Wh = nn.Linear(self.D,self.H,bias=True ) self.init_Wc = nn.Linear(self.D,self.H,bias=True",
"Study rountime if self.study: action = torch.zeros([self.batch_size,self.H]).to( torch.device('cuda:0') ) atten = torch.zeros([self.batch_size,self.H]).to( torch.device('cuda:0')",
"torch.zeros([self.batch_size,self. L ]) # Declare layers self.attn = AttentionNet self.ctrl = ControlNet self.lstm",
"self.training: xt = sequence[0] else : xt = sequence[0].unsqueeze(0) # Inicialize hidden state",
"alpha [batch,L,1] \"\"\" class TVADecoder(nn.Module): \"\"\" Constructor \"\"\" def __init__(self,AttentionNet,cube_size,n_hidden): super(TVADecoder, self).__init__() #",
"with torch.no_grad(): # Mean features feature = torch.mean(feature,(2,3)) # [batch,D,h,w] -> [batch,D] hidden",
"by visualizing causal attention\". In Proceedings of the IEEE international conference on computer",
") self.init_Wc = nn.Linear(self.D,self.H,bias=True ) self.init_tanh = nn.Tanh() # Initialization torch.nn.init.xavier_uniform_(self.init_Wh.weight) torch.nn.init.xavier_uniform_(self.init_Wc.weight) self.lstm.reset_parameters()",
"= ControlNet self.lstm = nn.LSTM( input_size = self.R, hidden_size = self.H, num_layers =",
"nn.Conv2d(HighLevelDim,self.R, kernel_size=1, bias=False) self.lstm = nn.LSTM( input_size = self.R, hidden_size = self.H, num_layers",
"if self.training: st_ = st_.transpose(0,1).reshape(batch_size*sequence_len,self.n_task,self.S) ht_ = ht_.transpose(0,1).reshape(batch_size*sequence_len, self.H) # Compile study if",
"= torch.zeros([self.batch_size,self.H]).to( torch.device('cuda:0') ) atten = torch.zeros([self.batch_size,self.H]).to( torch.device('cuda:0') ) else: action,atten = (None,None)",
"120 self.n_out = 3 self.study = False # Declare layers self.attn = AttentionNet",
"self.HighEncoder(xt) # Feature-based attention # s[t] = f(z[t],h[t-1]) _zt = self.avgpool1( zt) _zt",
"nn.AdaptiveAvgPool2d((1, 1)) self.normSpa = nn.BatchNorm2d(LowLevelDim) self.ReLU = nn.ReLU() # Initialization torch.nn.init.xavier_uniform_(self.dimReduction.weight) torch.nn.init.xavier_uniform_(self. init_Wh.weight)",
"k in range(n_range): # One time if self.training: ηt = sequence[k] # [batch,L,D]",
"= self. avgpool2(rt) rt = torch.flatten(rt , 1) rt = rt.unsqueeze(0) # LSTM",
"torch.no_grad(): # Mean features feature = torch.mean(feature,1) # [batch,L,D] -> [batch,D] hidden =",
"self.D = cube_size[2] # 64 # cube_size[0] self.L = cube_size[0]*cube_size[1] # 90 #",
"~ [ layers ,batch,H] _,(hidden,cell) = self.lstm(visual,(hidden,cell)) # Control self.pred[k] = self.ctrl(visual, hidden,",
"self.init_Wh = nn.Linear(LowLevelDim,self.H,bias=True ) self.init_Wc = nn.Linear(LowLevelDim,self.H,bias=True ) self.init_tanh = nn.Tanh() self.avgpool1 =",
"decoder cmd = self.CmdDecoder(command) if self.training: cmd = cmd.view(batch_size,sequence_len,-1).transpose(0,1) # [sequence,batch,4] # Prediction",
"# Parameters self.D = cube_size[2] # 64 self.L = cube_size[0]*cube_size[1] # 90 self.R",
"= nn.Tanh() self.avgpool1 = nn.AdaptiveAvgPool2d((1, 1)) self.avgpool2 = nn.AdaptiveAvgPool2d((1, 1)) self.normSpa = nn.BatchNorm2d(LowLevelDim)",
"* cell ~ [ layers ,batch,H] _,(hidden,cell) = self.lstm(visual,(hidden,cell)) # Control self.pred[k] =",
"\"\"\" def __init__(self, HighEncoderNet, SpatialNet, FeatureNet, CommandNet, LowLevelDim=128, HighLevelDim=512, n_hidden=1024, n_state=64,n_task=3, study=False): super(CatDecoder,",
"[ layers ,batch,H] _,(hidden,cell) = self.lstm(visual,(hidden,cell)) # Output vis_[k] = visual # [1,batch,R]",
"self.ReLU = nn.ReLU() # Initialization torch.nn.init.xavier_uniform_(self.dimReduction.weight) torch.nn.init.xavier_uniform_(self. init_Wh.weight) torch.nn.init.xavier_uniform_(self. init_Wc.weight) self.lstm.reset_parameters() \"\"\" Initialize",
"= f(z[t],h[t-1]) _zt = self.avgpool1( zt) _zt = torch.flatten(_zt, 1) st, βt, Ft",
"None, None # Sequence loop n_range = self.sequence_len if self.training else batch_size for",
"= sequence[k].unsqueeze(0) # [ 1 ,L,D] # Visual Attention alpha = self.attn(xt,hidden[1].unsqueeze(0))# [batch,L,1]",
"hidden_size = self.H, num_layers = 1) self.init_Wh = nn.Linear(LowLevelDim,self.H,bias=True ) self.init_Wc = nn.Linear(LowLevelDim,self.H,bias=True",
"# Initialization torch.nn.init.xavier_uniform_(self.init_Wh1.weight) torch.nn.init.xavier_uniform_(self.init_Wh2.weight) torch.nn.init.xavier_uniform_(self.init_Wc1.weight) torch.nn.init.xavier_uniform_(self.init_Wc2.weight) self.lstm.reset_parameters() \"\"\" Initialize LSTM: hidden state and",
"hidden = self.init_Wh(feature) # [batch,D]*[D,H] -> [batch,H] hidden = self.init_tanh(hidden) # [batch,H] hidden",
"visual = visual * beta # [batch,L,D]x[batch,1,D] = [batch,L,D] visual = visual.reshape(n_visual,self.R) #",
"torch.device('cuda:0') ) map_ = torch.zeros([batch_size,self.L]).to( torch.device('cuda:0') ) # Study rountime if self.study: action",
"spatial = xt * alpha # [batch,L,D]x[batch,L,1] = [batch,L,D] visual = spatial +",
"IPython.core.debugger import set_trace import ImitationLearning.VisualAttention.network.Gate as G \"\"\" Basic Decoder Module -------------------- Ref:",
"beta.squeeze() # [1,batch,D] hdd_[k] = hidden[0].unsqueeze(0) # [1,batch,H] if self.study: hc[k] = hidden[0].squeeze()",
"= hidden[0].squeeze() atten [k] = hidden[1].squeeze() if self.training: pred = pred.transpose(0,1).contiguous().view(batch_size*sequence_len, n_out) map_",
"rt = rt.unsqueeze(0) # LSTM # * yt ~ [sequence,batch,H] # * hidden",
"# Sequence loop n_range = self.sequence_len if self.training else batch_size for k in",
"512 self.M = n_hidden # 512 self.sequence_len = 20 self.batch_size = 120 self.n_out",
"_,(ht,ct)= self.lstm(rt,(ht,ct)) # Output st_.append(st.squeeze()) # [batch,n_task,S] ht_.append(ht.squeeze()) # [batch, H] # Study",
"[batch,L,D] -> [batch,D] hidden1 = self.init_Wh1 (feature) # [batch,D]*[D,H] -> [batch,H] hidden1 =",
"α,β,F = list(),list(),list() else : α,β,F = None, None, None # Sequence loop",
"HighLevelDim=512, n_hidden=1024, n_state=64,n_task=3, study=False): super(CatDecoder, self).__init__() self.study = study # Parameters self.H =",
"torch.stack(st_,dim=0) ht_ = torch.stack(ht_,dim=0) if self.training: st_ = st_.transpose(0,1).reshape(batch_size*sequence_len,self.n_task,self.S) ht_ = ht_.transpose(0,1).reshape(batch_size*sequence_len, self.H)",
"~ [num_layers, batch, hidden_size] return hidden.contiguous(),cell.contiguous() \"\"\" Forward \"\"\" def forward(self,feature): # Parameters",
"90 # cube_size[1]*cube_size[2] self.R = self.L*self.D # 5760 # self.L*self.D self.H = n_hidden",
"def forward(self,feature): # Parameters sequence_len = self.sequence_len n_out = self.n_out if self.training: batch_size",
"self.pred.transpose(0,1).contiguous().view(batch_size*sequence_len, n_out) self. map = self. map.transpose(0,1).contiguous().view(batch_size*sequence_len,self.L) return self.pred, self.map \"\"\" Dual Decoder",
"self.init_tanh(cell) # [batch,H] cell = cell.unsqueeze(0) # [1,batch,H] # (h,c) ~ [num_layers, batch,",
"hidden [1,batch,H] cell [1,batch,H] \"\"\" def initializeLSTM(self,feature): with torch.no_grad(): # Mean features feature",
"# [batch,L,D] # Input to inicialize LSTM if self.training: xt = sequence[0] else",
"= self.avgpool1( zt) _zt = torch.flatten(_zt, 1) st, βt, Ft = self.FeatureAttn(_zt,ht[0],cm) #",
"# Input to inicialize LSTM if self.training: xt = sequence[0] else : xt",
"Initialization torch.nn.init.xavier_uniform_(self.dimReduction.weight) torch.nn.init.xavier_uniform_(self. init_Wh.weight) torch.nn.init.xavier_uniform_(self. init_Wc.weight) self.lstm.reset_parameters() \"\"\" Initialize LSTM: hidden state and",
"else : cm = cmd[k].unsqueeze(0) # [ 1 , 4 ] # Spatial",
"Compile study if self.study: α = torch.stack(α, dim=0) β = torch.stack(β, dim=0) F",
"n_hidden # 1024 # hidden_size self.sequence_len = 20 self.batch_size = 120 self.n_out =",
"self.attn(xt,hidden) # [batch,L,1] # Spatial spatial = xt * alpha # [batch,L,D]x[batch,L,1] =",
"torch.nn.init.xavier_uniform_(self.dimReduction.weight) torch.nn.init.xavier_uniform_(self. init_Wh.weight) torch.nn.init.xavier_uniform_(self. init_Wc.weight) self.lstm.reset_parameters() \"\"\" Initialize LSTM: hidden state and cell",
"~ [sequence,batch,H] # * hidden ~ [ layers ,batch,H] # * cell ~",
"ηt = sequence[k] # [batch,L,D] else : ηt = sequence[k].unsqueeze(0) # [ 1",
"[batch,L,D]x[batch,L,1] = [batch,L,D] visual = visual.reshape(n_visual,self.R) # [batch,R] visual = visual.unsqueeze(0) # [1,batch,R]",
"self.study: action[k] = hidden[0].squeeze() atten [k] = hidden[1].squeeze() if self.training: pred = pred.transpose(0,1).contiguous().view(batch_size*sequence_len,",
"torch.stack([hidden1,hidden2], dim=0).contiguous() # [2,batch,H] cell = torch.stack([ cell1, cell2], dim=0).contiguous() # [2,batch,H] #",
"initializeLSTM(self,feature): with torch.no_grad(): # Mean features feature = torch.mean(feature,(2,3)) # [batch,D,h,w] -> [batch,D]",
") hdd_ = torch.zeros([batch_size,self.H]).to( torch.device('cuda:0') ) # Study rountime if self.study: hc =",
"sequence[k] # [batch,L,D] else : xt = sequence[k].unsqueeze(0) # [ 1 ,L,D] #",
"cell2 ) # [batch,H] hidden = torch.stack([hidden1,hidden2], dim=0).contiguous() # [2,batch,H] cell = torch.stack([",
"def initializeLSTM(self,feature): with torch.no_grad(): # Mean features feature = torch.mean(feature,1) # [batch,L,D] ->",
"cell2 = self.init_Wc2 ( cell1 ) # [batch,H]*[H,H] -> [batch,H] cell2 = self.init_tanh(",
"Decoder Module -------------------- Ref: <NAME>., & <NAME>. (2017). \"Interpretable learning for self-driving cars",
"= 1) self.init_Wh = nn.Linear(self.D,self.H,bias=True ) self.init_Wc = nn.Linear(self.D,self.H,bias=True ) self.init_tanh = nn.Tanh()",
"# Attention self.HighEncoder = HighEncoderNet self.SpatialAttn = SpatialNet self.FeatureAttn = FeatureNet self. CmdDecoder",
"n_hidden=1024, n_state=64,n_task=3, study=False): super(CatDecoder, self).__init__() self.study = study # Parameters self.H = n_hidden",
"hidden state and cell state Ref: <NAME>, et al. \"Show, attend and tell:",
"= n_hidden # 512 self.M = n_hidden # 512 self.sequence_len = 20 self.batch_size",
"nn.Linear(LowLevelDim,self.H,bias=True ) self.init_tanh = nn.Tanh() self.avgpool1 = nn.AdaptiveAvgPool2d((1, 1)) self.avgpool2 = nn.AdaptiveAvgPool2d((1, 1))",
"~ [1,batch,H] hidden,cell = self.initializeLSTM(xt) # Prediction container if self.training: self.pred = self.pred.view(sequence_len,batch_size,",
"Neural image caption generation with visual attention.\" International conference on machine learning. 2015.",
"Data if self.training: sequence = feature.view(batch_size,sequence_len,C,H,W).transpose(0,1) # [sequence,batch, ...] else : sequence =",
"if self.training: cmd = cmd.view(batch_size,sequence_len,-1).transpose(0,1) # [sequence,batch,4] # Prediction container st_,ht_ = list(),list()",
"layers self.attn = AttentionNet self.lstm = nn.LSTM( input_size = self.R, hidden_size = self.H,",
"Study if self.study: α,β,F = list(),list(),list() else : α,β,F = None, None, None",
"~ [1,batch,H] hidden,cell = self.initializeLSTM(xt) # Prediction container if self.training: pred = torch.zeros([sequence_len,batch_size,",
"hidden [1,batch,H] * Output: alpha [batch,L,1] \"\"\" class DualDecoder(nn.Module): \"\"\" Constructor \"\"\" def",
"pred.transpose(0,1).contiguous().view(batch_size*sequence_len, n_out) map_ = map_.transpose(0,1).contiguous().view(batch_size*sequence_len,self.L) # Return return pred, map_, {'action': action, 'attention':",
"of (B, C, H, W) shape # Data if self.training: sequence = feature.view(batch_size,sequence_len,C,H,W).transpose(0,1)",
"vis_, hdd_, {'alpha': alp_, 'beta': bet_}, {'control': hc} # ------------------------------------------------------------------------------------------------ # # #",
"hidden.contiguous(),cell.contiguous() \"\"\" Forward - eta [batch,channel,high,width] \"\"\" def forward(self,feature,command): # Parameters sequence_len =",
"CmdDecoder = CommandNet self.Gate = G.GRUGate(LowLevelDim) # Output self.dimReduction = nn.Conv2d(HighLevelDim,self.R, kernel_size=1, bias=False)",
"self. CmdDecoder = CommandNet self.Gate = G.GRUGate(LowLevelDim) # Output self.dimReduction = nn.Conv2d(HighLevelDim,self.R, kernel_size=1,",
"batch_size if self.training else 1 for k in range(n_range): # One time if",
"= 3 self.study = False # Declare layers self.attn = AttentionNet self.lstm =",
"[batch,L,D] hidden [1,batch,H] * Output: alpha [batch,L,1] \"\"\" class BasicDecoder(nn.Module): \"\"\" Constructor \"\"\"",
"[ layers ,batch,H] # * cell ~ [ layers ,batch,H] _,(hidden,cell) = self.lstm(visual,(hidden,cell))",
"# [batch, H] # Study if self.study: α.append(αt) β.append(βt) F.append(Ft) # Concatenate st_",
"self.init_Wc = nn.Linear(self.D,self.H,bias=True ) self.init_tanh = nn.Tanh() # Initialization torch.nn.init.xavier_uniform_(self.init_Wh.weight) torch.nn.init.xavier_uniform_(self.init_Wc.weight) self.lstm.reset_parameters() \"\"\"",
"= torch.zeros([sequence_len,batch_size,self.L]).to( torch.device('cuda:0') ) bet_ = torch.zeros([sequence_len,batch_size,self.D]).to( torch.device('cuda:0') ) hdd_ = torch.zeros([sequence_len,batch_size,self.H]).to( torch.device('cuda:0')",
"state and cell state Ref: <NAME>, et al. \"Show, attend and tell: Neural",
"# cube_size[0] self.L = cube_size[0]*cube_size[1] # 90 # cube_size[1]*cube_size[2] self.R = self.L*self.D #",
"[1,batch,L] bet_[k] = beta.squeeze() # [1,batch,D] hdd_[k] = hidden[0].unsqueeze(0) # [1,batch,H] if self.study:",
"if self.training: batch_size = int(feature.shape[0]/sequence_len) else : batch_size = feature.shape[0] _,C,H,W = feature.shape",
"= self.initializeLSTM(xt) # Command decoder cmd = self.CmdDecoder(command) if self.training: cmd = cmd.view(batch_size,sequence_len,-1).transpose(0,1)",
"cube_size[2] # 64 # cube_size[0] self.L = cube_size[0]*cube_size[1] # 90 # cube_size[1]*cube_size[2] self.R",
"\"\"\" Forward \"\"\" def forward(self,feature): # Parameters sequence_len = self.sequence_len n_out = self.n_out",
"container self.pred = torch.zeros([self.batch_size,self.n_out]) self. map = torch.zeros([self.batch_size,self. L ]) # Declare layers",
"~ [ layers ,batch,H] _,(hidden,cell) = self.lstm(visual,(hidden,cell)) # Control pred[k] = self.ctrl(visual, hidden[0].unsqueeze(0))",
"# Control pred[k] = self.ctrl(visual, hidden[0].unsqueeze(0)) map_[k] = alpha.squeeze() if self.study: action[k] =",
"n_out]).to( torch.device('cuda:0') ) map_ = torch.zeros([batch_size,self.L]).to( torch.device('cuda:0') ) # Study rountime if self.study:",
"ht,ct = self.initializeLSTM(xt) # Command decoder cmd = self.CmdDecoder(command) if self.training: cmd =",
"= self.init_Wc(feature) # [batch,D]*[D,H] -> [batch,H] cell = self.init_tanh(cell) # [batch,H] cell =",
"cell [1,batch,H] \"\"\" def initializeLSTM(self,feature): with torch.no_grad(): # Mean features feature = torch.mean(feature,(2,3))",
"= torch.mean(feature,1) # [batch,L,D] -> [batch,D] hidden1 = self.init_Wh1 (feature) # [batch,D]*[D,H] ->",
"LSTM 256 512 self.S = n_state self.n_task = n_task self.sequence_len = 20 #",
"= torch.stack(F, dim=0) return st_, {'hidden': ht_, 'feature': F}, {'alpha': α, 'beta': β}",
"[batch,L,D] * Output: hidden [1,batch,H] cell [1,batch,H] \"\"\" def initializeLSTM(self,feature): with torch.no_grad(): #",
"else : ηt = sequence[k].unsqueeze(0) # [ 1 ,L,D] if self.training: cm =",
"input_size=self.R, hidden_size=self.H, num_layers=2 ) self.init_Wh1 = nn.Linear(self.D,self.H,bias=True ) self.init_Wh2 = nn.Linear(self.H,self.H,bias=True ) self.init_Wc1",
"# Spatial Attention xt, αt = self.SpatialAttn(ηt,st) xt = self.Gate(ηt,xt) # High-level encoder",
"alpha = self.attn(xt,hidden[1].unsqueeze(0))# [batch,L,1] visual = xt * alpha # [batch,L,D]x[batch,L,1] = [batch,L,D]",
"= spatial + xt # Categorical visual = visual * beta # [batch,L,D]x[batch,1,D]",
"# Command decoder cmd = self.CmdDecoder(command) if self.training: cmd = cmd.view(batch_size,sequence_len,-1).transpose(0,1) # [sequence,batch,4]",
"~ [1,batch,H] if self.training: xt = sequence[0] # Input to inicialize LSTM else",
"feature = torch.mean(feature,1) # [batch,L,D] -> [batch,D] hidden = self.init_Wh(feature) # [batch,D]*[D,H] ->",
"to inicialize LSTM if self.training: xt = sequence[0] else : xt = sequence[0].unsqueeze(0)",
"rountime if self.study: hc = torch.zeros([self.batch_size,self.H]).to( torch.device('cuda:0') ) else: hc = None #",
"# s[t] = f(z[t],h[t-1]) _zt = self.avgpool1( zt) _zt = torch.flatten(_zt, 1) st,",
"st_ = torch.stack(st_,dim=0) ht_ = torch.stack(ht_,dim=0) if self.training: st_ = st_.transpose(0,1).reshape(batch_size*sequence_len,self.n_task,self.S) ht_ =",
"state # * hidden ~ [1,batch,H] # * cell ~ [1,batch,H] if self.training:",
"pred, map_, {'action': action, 'attention': atten} \"\"\" TVA Decoder Module ------------------ Ref: <NAME>.,",
"vis_ = vis_.transpose(0,1).contiguous().view(batch_size*sequence_len,self.R) alp_ = alp_.transpose(0,1).contiguous().view(batch_size*sequence_len,self.L) bet_ = bet_.transpose(0,1).contiguous().view(batch_size*sequence_len,self.D) hdd_ = hdd_.transpose(0,1).contiguous().view(batch_size*sequence_len,self.H) return",
"[1,batch,H] hidden,cell = self.initializeLSTM(xt) # Prediction container if self.training: self.pred = self.pred.view(sequence_len,batch_size, n_out)",
"output LSTM 1024 2048 self.R = int(n_hidden/4) # input LSTM 256 512 self.S",
"sequence[0] else : xt = sequence[0].unsqueeze(0) # Inicialize hidden state and cell state",
"bet_ = torch.zeros([batch_size,self.D]).to( torch.device('cuda:0') ) hdd_ = torch.zeros([batch_size,self.H]).to( torch.device('cuda:0') ) # Study rountime",
"= (None,None) # Sequence loop n_range = self.sequence_len if self.training else batch_size n_visual",
"= ControlNet self.lstm = nn.LSTM( input_size=self.R, hidden_size=self.H, num_layers=2 ) self.init_Wh1 = nn.Linear(self.D,self.H,bias=True )",
"# Study rountime if self.study: action = torch.zeros([self.batch_size,self.H]).to( torch.device('cuda:0') ) atten = torch.zeros([self.batch_size,self.H]).to(",
"= self.attn(xt,hidden) # [batch,L,1] # Spatial spatial = xt * alpha # [batch,L,D]x[batch,L,1]",
"hdd_ = torch.zeros([sequence_len,batch_size,self.H]).to( torch.device('cuda:0') ) else: vis_ = torch.zeros([batch_size,self.R]).to( torch.device('cuda:0') ) alp_ =",
"self.training: pred = torch.zeros([sequence_len,batch_size, n_out]).to( torch.device('cuda:0') ) map_ = torch.zeros([sequence_len,batch_size,self.L]).to( torch.device('cuda:0') ) else:",
"= 20 self.batch_size = 120 self.n_out = 3 self.study = False # Declare",
"[ 1 ,L,D] # Visual Attention alpha = self.attn(xt,hidden[1].unsqueeze(0))# [batch,L,1] visual = xt",
"Input: feature [batch,L,D] hidden [1,batch,H] * Output: alpha [batch,L,1] \"\"\" class TVADecoder(nn.Module): \"\"\"",
"# [batch,H] cell1 = self.init_Wc1 (feature) # [batch,D]*[D,H] -> [batch,H] cell1 = self.init_tanh(",
"map.view(sequence_len,batch_size,self.L) # Sequence loop n_range = self.sequence_len if self.training else batch_size n_visual =",
"self.avgpool1 = nn.AdaptiveAvgPool2d((1, 1)) self.avgpool2 = nn.AdaptiveAvgPool2d((1, 1)) self.normSpa = nn.BatchNorm2d(LowLevelDim) self.ReLU =",
"st = torch.cuda.FloatTensor(batch_size,self.n_task,self.S).uniform_() else : st = torch.cuda.FloatTensor( 1,self.n_task,self.S).uniform_() # Study if self.study:",
": α,β,F = None, None, None # Sequence loop n_range = self.sequence_len if",
"self.init_Wh2 (hidden1) # [batch,H]*[H,H] -> [batch,H] hidden2 = self.init_tanh(hidden2) # [batch,H] cell1 =",
"-> [batch,H] cell2 = self.init_tanh( cell2 ) # [batch,H] hidden = torch.stack([hidden1,hidden2], dim=0).contiguous()",
"= self.init_tanh( cell1 ) # [batch,H] cell2 = self.init_Wc2 ( cell1 ) #",
"# 1024 # hidden_size self.sequence_len = 20 self.batch_size = 120 self.n_out = 3",
"cars by visualizing causal attention\". In Proceedings of the IEEE international conference on",
"if self.training: vis_ = vis_.transpose(0,1).contiguous().view(batch_size*sequence_len,self.R) alp_ = alp_.transpose(0,1).contiguous().view(batch_size*sequence_len,self.L) bet_ = bet_.transpose(0,1).contiguous().view(batch_size*sequence_len,self.D) hdd_ =",
"bet_ = bet_.transpose(0,1).contiguous().view(batch_size*sequence_len,self.D) hdd_ = hdd_.transpose(0,1).contiguous().view(batch_size*sequence_len,self.H) return vis_, hdd_, {'alpha': alp_, 'beta': bet_},",
"rt = self. avgpool2(rt) rt = torch.flatten(rt , 1) rt = rt.unsqueeze(0) #",
"batch_size = int(feature.shape[0]/sequence_len) else : batch_size = feature.shape[0] _,C,H,W = feature.shape # Batch",
"torch.zeros([sequence_len,batch_size,self.D]).to( torch.device('cuda:0') ) hdd_ = torch.zeros([sequence_len,batch_size,self.H]).to( torch.device('cuda:0') ) else: vis_ = torch.zeros([batch_size,self.R]).to( torch.device('cuda:0')",
"Input: feature [batch,L,D] hidden [1,batch,H] * Output: alpha [batch,L,1] \"\"\" class DualDecoder(nn.Module): \"\"\"",
"map.transpose(0,1).contiguous().view(batch_size*sequence_len,self.L) return self.pred, self.map \"\"\" Dual Decoder Module ------------------- * Input: feature [batch,L,D]",
"[2,batch,H] cell = torch.stack([ cell1, cell2], dim=0).contiguous() # [2,batch,H] # (h,c) ~ [num_layers,",
"= n_state self.n_task = n_task self.sequence_len = 20 # Attention self.HighEncoder = HighEncoderNet",
"= torch.zeros([self.batch_size,self.H]).to( torch.device('cuda:0') ) else: hc = None # hc,ha,hb = (None,None,None) #",
"self.sequence_len = 20 self.batch_size = 120 self.n_out = 3 # Output container self.pred",
"feature [batch,L,D] * Output: hidden [1,batch,H] cell [1,batch,H] \"\"\" def initializeLSTM(self,feature): with torch.no_grad():",
"n_task self.sequence_len = 20 # Attention self.HighEncoder = HighEncoderNet self.SpatialAttn = SpatialNet self.FeatureAttn",
"= xt * alpha # [batch,L,D]x[batch,L,1] = [batch,L,D] visual = visual.reshape(n_visual,self.R) # [batch,R]",
"self.init_Wc(feature) # [batch,D]*[D,H] -> [batch,H] cell = self.init_tanh(cell) # [batch,H] cell = cell.unsqueeze(0)",
"alpha.squeeze() if self.study: action[k] = hidden[0].squeeze() atten [k] = hidden[1].squeeze() if self.training: pred",
"super(TVADecoder, self).__init__() # Parameters self.D = cube_size[2] # 64 self.L = cube_size[0]*cube_size[1] #",
"torch.zeros([sequence_len,batch_size,self.L]).to( torch.device('cuda:0') ) bet_ = torch.zeros([sequence_len,batch_size,self.D]).to( torch.device('cuda:0') ) hdd_ = torch.zeros([sequence_len,batch_size,self.H]).to( torch.device('cuda:0') )",
"torch.zeros([batch_size,self.L]).to( torch.device('cuda:0') ) # Study rountime if self.study: action = torch.zeros([self.batch_size,self.H]).to( torch.device('cuda:0') )",
"= torch.stack(st_,dim=0) ht_ = torch.stack(ht_,dim=0) if self.training: st_ = st_.transpose(0,1).reshape(batch_size*sequence_len,self.n_task,self.S) ht_ = ht_.transpose(0,1).reshape(batch_size*sequence_len,",
"= torch.stack(β, dim=0) F = torch.stack(F, dim=0) return st_, {'hidden': ht_, 'feature': F},",
"st_ = st_.transpose(0,1).reshape(batch_size*sequence_len,self.n_task,self.S) ht_ = ht_.transpose(0,1).reshape(batch_size*sequence_len, self.H) # Compile study if self.study: α",
"\"\"\" def forward(self,feature): # Parameters sequence_len = self.sequence_len if self.training: batch_size = int(feature.shape[0]/sequence_len)",
"# One time if self.training: xt = sequence[k] # [batch,L,D] else : xt",
"torch.device('cuda:0') ) hdd_ = torch.zeros([batch_size,self.H]).to( torch.device('cuda:0') ) # Study rountime if self.study: hc",
"cell ~ [ layers ,batch,H] _,(hidden,cell) = self.lstm(visual,(hidden,cell)) # Control self.pred[k] = self.ctrl(visual,",
"~ [ layers ,batch,H] # * cell ~ [ layers ,batch,H] _,(hidden,cell) =",
"= feature # [batch, ...] # Inicialize hidden state and cell state #",
"(None,None) # Sequence loop n_range = self.sequence_len if self.training else batch_size n_visual =",
"if self.study: α = torch.stack(α, dim=0) β = torch.stack(β, dim=0) F = torch.stack(F,",
"= cube_size[2] # 64 # cube_size[0] self.L = cube_size[0]*cube_size[1] # 90 # cube_size[1]*cube_size[2]",
"layers self.attn = AttentionNet self.ctrl = ControlNet self.lstm = nn.LSTM( input_size=self.R, hidden_size=self.H, num_layers=2",
"-> [batch,H] hidden1 = self.init_tanh(hidden1) # [batch,H] hidden2 = self.init_Wh2 (hidden1) # [batch,H]*[H,H]",
"# Declare layers self.attn = AttentionNet self.ctrl = ControlNet self.lstm = nn.LSTM( input_size=self.R,",
"= n_hidden # 1024 # hidden_size self.sequence_len = 20 self.batch_size = 120 self.n_out",
"= torch.stack([hidden1,hidden2], dim=0).contiguous() # [2,batch,H] cell = torch.stack([ cell1, cell2], dim=0).contiguous() # [2,batch,H]",
"[batch,channel,high,width] \"\"\" def forward(self,feature,command): # Parameters sequence_len = self.sequence_len if self.training: batch_size =",
"= CommandNet self.Gate = G.GRUGate(LowLevelDim) # Output self.dimReduction = nn.Conv2d(HighLevelDim,self.R, kernel_size=1, bias=False) self.lstm",
"= 1) self.init_Wh = nn.Linear(LowLevelDim,self.H,bias=True ) self.init_Wc = nn.Linear(LowLevelDim,self.H,bias=True ) self.init_tanh = nn.Tanh()",
"batch_size n_visual = batch_size if self.training else 1 for k in range(n_range): #",
"* Output: alpha [batch,L,1] \"\"\" class TVADecoder(nn.Module): \"\"\" Constructor \"\"\" def __init__(self,AttentionNet,cube_size,n_hidden): super(TVADecoder,",
"torch.nn as nn from IPython.core.debugger import set_trace import ImitationLearning.VisualAttention.network.Gate as G \"\"\" Basic",
"computer vision (pp. 2942-2950). * Input: feature [batch,L,D] hidden [1,batch,H] * Output: alpha",
"cell1, cell2], dim=0).contiguous() # [2,batch,H] # (h,c) ~ [num_layers, batch, hidden_size] return hidden,cell",
"self.init_tanh( cell2 ) # [batch,H] hidden = torch.stack([hidden1,hidden2], dim=0).contiguous() # [2,batch,H] cell =",
"1 , 4 ] # Spatial Attention xt, αt = self.SpatialAttn(ηt,st) xt =",
"def __init__(self,AttentionNet,cube_size,n_hidden): super(TVADecoder, self).__init__() # Parameters self.D = cube_size[2] # 64 self.L =",
"# [ 1 ,L,D] # Visual Attention alpha = self.attn(xt,hidden[1].unsqueeze(0))# [batch,L,1] visual =",
"hidden.contiguous(),cell.contiguous() \"\"\" Forward \"\"\" def forward(self,feature): # Parameters sequence_len = self.sequence_len n_out =",
"= feature.shape # Batch of Tensor Images is a tensor of (B, C,",
"= batch_size if self.training else 1 for k in range(n_range): # One time",
"# Dimension reduction to LSTM rt = self.dimReduction(zt) rt = self. avgpool2(rt) rt",
"self.L = cube_size[0]*cube_size[1] # 90 self.R = self.L*self.D # 5760 self.H = n_hidden",
"= n_hidden # output LSTM 1024 2048 self.R = int(n_hidden/4) # input LSTM",
"bias=False) self.lstm = nn.LSTM( input_size = self.R, hidden_size = self.H, num_layers = 1)",
"1) self.init_Wh = nn.Linear(LowLevelDim,self.H,bias=True ) self.init_Wc = nn.Linear(LowLevelDim,self.H,bias=True ) self.init_tanh = nn.Tanh() self.avgpool1",
"= self.init_tanh(cell) # [batch,H] cell = cell.unsqueeze(0) # [1,batch,H] # (h,c) ~ [num_layers,",
"Basic Decoder Module -------------------- Ref: <NAME>., & <NAME>. (2017). \"Interpretable learning for self-driving",
"= self.H, num_layers = 1) self.init_Wh = nn.Linear(self.D,self.H,bias=True ) self.init_Wc = nn.Linear(self.D,self.H,bias=True )",
"loop n_range = self.sequence_len if self.training else batch_size for k in range(n_range): #",
"reduction to LSTM rt = self.dimReduction(zt) rt = self. avgpool2(rt) rt = torch.flatten(rt",
"= visual * beta # [batch,L,D]x[batch,1,D] = [batch,L,D] visual = visual.reshape(n_visual,self.R) # [batch,R]",
"import ImitationLearning.VisualAttention.network.Gate as G \"\"\" Basic Decoder Module -------------------- Ref: <NAME>., & <NAME>.",
"torch.cuda.FloatTensor(batch_size,self.n_task,self.S).uniform_() else : st = torch.cuda.FloatTensor( 1,self.n_task,self.S).uniform_() # Study if self.study: α,β,F =",
"[batch,D]*[D,H] -> [batch,H] hidden1 = self.init_tanh(hidden1) # [batch,H] hidden2 = self.init_Wh2 (hidden1) #",
"[batch,D] hidden1 = self.init_Wh1 (feature) # [batch,D]*[D,H] -> [batch,H] hidden1 = self.init_tanh(hidden1) #",
"container if self.training: self.pred = self.pred.view(sequence_len,batch_size, n_out) self. map = self. map.view(sequence_len,batch_size,self.L) #",
"self.L*self.D self.H = n_hidden # 1024 # hidden_size self.M = n_hidden # 1024",
"20 # Attention self.HighEncoder = HighEncoderNet self.SpatialAttn = SpatialNet self.FeatureAttn = FeatureNet self.",
"self.FeatureAttn = FeatureNet self. CmdDecoder = CommandNet self.Gate = G.GRUGate(LowLevelDim) # Output self.dimReduction",
"feature [batch,D,h,w] * Output: hidden [1,batch,H] cell [1,batch,H] \"\"\" def initializeLSTM(self,feature): with torch.no_grad():",
"512 self.sequence_len = 20 self.batch_size = 120 self.n_out = 3 # Output container",
"of Tensor Images is a tensor of (B, C, H, W) shape #",
"self.training else 1 for k in range(n_range): # One time if self.training: xt",
"vis_[k] = visual # [1,batch,R] alp_[k] = alpha.squeeze() # [1,batch,L] bet_[k] = beta.squeeze()",
"[ 1 ,L,D] # Visual Attention alpha,beta = self.attn(xt,hidden) # [batch,L,1] # Spatial",
"-> [batch,H] cell1 = self.init_tanh( cell1 ) # [batch,H] cell2 = self.init_Wc2 (",
"self.training: st = torch.cuda.FloatTensor(batch_size,self.n_task,self.S).uniform_() else : st = torch.cuda.FloatTensor( 1,self.n_task,self.S).uniform_() # Study if",
"# Prediction container if self.training: self.pred = self.pred.view(sequence_len,batch_size, n_out) self. map = self.",
"# Mean features feature = torch.mean(feature,1) # [batch,L,D] -> [batch,D] hidden = self.init_Wh(feature)",
"= alpha.squeeze() if self.training: self.pred = self.pred.transpose(0,1).contiguous().view(batch_size*sequence_len, n_out) self. map = self. map.transpose(0,1).contiguous().view(batch_size*sequence_len,self.L)",
"[batch,L,D] else : ηt = sequence[k].unsqueeze(0) # [ 1 ,L,D] if self.training: cm",
"{'control': hc} # ------------------------------------------------------------------------------------------------ # # # ------------------------------------------------------------------------------------------------ class CatDecoder(nn.Module): \"\"\" Constructor \"\"\"",
"self.n_out if self.training: batch_size = int(feature.shape[0]/sequence_len) else : batch_size = feature.shape[0] # Data",
"self.initializeLSTM(xt) # Prediction container if self.training: vis_ = torch.zeros([sequence_len,batch_size,self.R]).to( torch.device('cuda:0') ) alp_ =",
") map_ = torch.zeros([batch_size,self.L]).to( torch.device('cuda:0') ) # Study rountime if self.study: action =",
"hidden[0].unsqueeze(0) # [1,batch,H] if self.study: hc[k] = hidden[0].squeeze() if self.training: vis_ = vis_.transpose(0,1).contiguous().view(batch_size*sequence_len,self.R)",
"ht_ = torch.stack(ht_,dim=0) if self.training: st_ = st_.transpose(0,1).reshape(batch_size*sequence_len,self.n_task,self.S) ht_ = ht_.transpose(0,1).reshape(batch_size*sequence_len, self.H) #",
"Initialization torch.nn.init.xavier_uniform_(self.init_Wh.weight) torch.nn.init.xavier_uniform_(self.init_Wc.weight) self.lstm.reset_parameters() \"\"\" Initialize LSTM: hidden state and cell state Ref:",
"[batch,D]*[D,H] -> [batch,H] cell = self.init_tanh(cell) # [batch,H] cell = cell.unsqueeze(0) # [1,batch,H]",
"ControlNet self.lstm = nn.LSTM( input_size = self.R, hidden_size = self.H, num_layers = 1)",
"4 ] else : cm = cmd[k].unsqueeze(0) # [ 1 , 4 ]",
"...] else : sequence = feature # [batch, ...] # Inicialize hidden state",
"hidden_size self.sequence_len = 20 self.batch_size = 120 self.n_out = 3 self.study = False",
"# [batch,R] visual = visual.unsqueeze(0) # [1,batch,R] # LSTM # * yt ~",
"self.lstm(visual,(hidden,cell)) # Output vis_[k] = visual # [1,batch,R] alp_[k] = alpha.squeeze() # [1,batch,L]",
"------------------------------------------------------------------------------------------------ # # # ------------------------------------------------------------------------------------------------ class CatDecoder(nn.Module): \"\"\" Constructor \"\"\" def __init__(self, HighEncoderNet,",
"2048 self.R = int(n_hidden/4) # input LSTM 256 512 self.S = n_state self.n_task",
"machine learning. 2015. * Input: feature [batch,L,D] * Output: hidden [1,batch,H] cell [1,batch,H]",
"3 # Output container self.pred = torch.zeros([self.batch_size,self.n_out]) self. map = torch.zeros([self.batch_size,self. L ])",
"self.H = n_hidden # output LSTM 1024 2048 self.R = int(n_hidden/4) # input",
"= nn.Linear(self.D,self.H,bias=True ) self.init_Wc2 = nn.Linear(self.H,self.H,bias=True ) self.init_tanh = nn.Tanh() # Initialization torch.nn.init.xavier_uniform_(self.init_Wh1.weight)",
"self.Gate = G.GRUGate(LowLevelDim) # Output self.dimReduction = nn.Conv2d(HighLevelDim,self.R, kernel_size=1, bias=False) self.lstm = nn.LSTM(",
"hidden ~ [ layers ,batch,H] # * cell ~ [ layers ,batch,H] _,(hidden,cell)",
"ht_.append(ht.squeeze()) # [batch, H] # Study if self.study: α.append(αt) β.append(βt) F.append(Ft) # Concatenate",
",batch,H] _,(hidden,cell) = self.lstm(visual,(hidden,cell)) # Control pred[k] = self.ctrl(visual, hidden[0].unsqueeze(0)) map_[k] = alpha.squeeze()",
"torch.device('cuda:0') ) else: hc = None # hc,ha,hb = (None,None,None) # Sequence loop",
"1) rt = rt.unsqueeze(0) # LSTM # * yt ~ [sequence,batch,H] # *",
"Proceedings of the IEEE international conference on computer vision (pp. 2942-2950). * Input:",
"torch.device('cuda:0') ) alp_ = torch.zeros([sequence_len,batch_size,self.L]).to( torch.device('cuda:0') ) bet_ = torch.zeros([sequence_len,batch_size,self.D]).to( torch.device('cuda:0') ) hdd_",
"self.dimReduction(zt) rt = self. avgpool2(rt) rt = torch.flatten(rt , 1) rt = rt.unsqueeze(0)",
"ControlNet self.lstm = nn.LSTM( input_size=self.R, hidden_size=self.H, num_layers=2 ) self.init_Wh1 = nn.Linear(self.D,self.H,bias=True ) self.init_Wh2",
"self.sequence_len if self.training else batch_size n_visual = batch_size if self.training else 1 for",
"torch.device('cuda:0') ) bet_ = torch.zeros([sequence_len,batch_size,self.D]).to( torch.device('cuda:0') ) hdd_ = torch.zeros([sequence_len,batch_size,self.H]).to( torch.device('cuda:0') ) else:",
"# [1,batch,H] # (h,c) ~ [num_layers, batch, hidden_size] return hidden.contiguous(),cell.contiguous() \"\"\" Forward \"\"\"",
"= self.init_tanh( cell2 ) # [batch,H] hidden = torch.stack([hidden1,hidden2], dim=0).contiguous() # [2,batch,H] cell",
"[1,batch,R] alp_[k] = alpha.squeeze() # [1,batch,L] bet_[k] = beta.squeeze() # [1,batch,D] hdd_[k] =",
"visualizing causal attention\". In Proceedings of the IEEE international conference on computer vision",
"state and cell state # * hidden ~ [1,batch,H] # * cell ~",
"to LSTM rt = self.dimReduction(zt) rt = self. avgpool2(rt) rt = torch.flatten(rt ,",
"self.init_tanh(hidden2) # [batch,H] cell1 = self.init_Wc1 (feature) # [batch,D]*[D,H] -> [batch,H] cell1 =",
"= nn.AdaptiveAvgPool2d((1, 1)) self.normSpa = nn.BatchNorm2d(LowLevelDim) self.ReLU = nn.ReLU() # Initialization torch.nn.init.xavier_uniform_(self.dimReduction.weight) torch.nn.init.xavier_uniform_(self.",
"<reponame>Suryavf/SelfDrivingCar<gh_stars>10-100 import torch import torch.nn as nn from IPython.core.debugger import set_trace import ImitationLearning.VisualAttention.network.Gate",
"nn.ReLU() # Initialization torch.nn.init.xavier_uniform_(self.dimReduction.weight) torch.nn.init.xavier_uniform_(self. init_Wh.weight) torch.nn.init.xavier_uniform_(self. init_Wc.weight) self.lstm.reset_parameters() \"\"\" Initialize LSTM: hidden",
"= torch.zeros([batch_size,self.D]).to( torch.device('cuda:0') ) hdd_ = torch.zeros([batch_size,self.H]).to( torch.device('cuda:0') ) # Study rountime if",
"atten} \"\"\" TVA Decoder Module ------------------ Ref: <NAME>., & <NAME>. (2017). \"Interpretable learning",
"self.training: pred = pred.transpose(0,1).contiguous().view(batch_size*sequence_len, n_out) map_ = map_.transpose(0,1).contiguous().view(batch_size*sequence_len,self.L) # Return return pred, map_,",
"Output: alpha [batch,L,1] \"\"\" class DualDecoder(nn.Module): \"\"\" Constructor \"\"\" def __init__(self,AttentionNet,ControlNet,cube_size,n_hidden): super(DualDecoder, self).__init__()",
"# Return return pred, map_, {'action': action, 'attention': atten} \"\"\" TVA Decoder Module",
"= self.ctrl(visual, hidden[0].unsqueeze(0)) map_[k] = alpha.squeeze() if self.study: action[k] = hidden[0].squeeze() atten [k]",
"state Ref: Xu, Kelvin, et al. \"Show, attend and tell: Neural image caption",
"1 for k in range(n_range): # One time if self.training: xt = sequence[k]",
"self.sequence_len = 20 self.batch_size = 120 self.n_out = 3 self.study = False #",
"nn.Linear(self.D,self.H,bias=True ) self.init_Wc2 = nn.Linear(self.H,self.H,bias=True ) self.init_tanh = nn.Tanh() # Initialization torch.nn.init.xavier_uniform_(self.init_Wh1.weight) torch.nn.init.xavier_uniform_(self.init_Wh2.weight)",
"International conference on machine learning. 2015. * Input: feature [batch,L,D] * Output: hidden",
"torch.zeros([batch_size,self.L]).to( torch.device('cuda:0') ) bet_ = torch.zeros([batch_size,self.D]).to( torch.device('cuda:0') ) hdd_ = torch.zeros([batch_size,self.H]).to( torch.device('cuda:0') )",
"of the IEEE international conference on computer vision (pp. 2942-2950). * Input: feature",
"pred[k] = self.ctrl(visual, hidden[0].unsqueeze(0)) map_[k] = alpha.squeeze() if self.study: action[k] = hidden[0].squeeze() atten",
"layers ,batch,H] _,(hidden,cell) = self.lstm(visual,(hidden,cell)) # Output vis_[k] = visual # [1,batch,R] alp_[k]",
"xt # Categorical visual = visual * beta # [batch,L,D]x[batch,1,D] = [batch,L,D] visual",
"cube_size[0] self.L = cube_size[0]*cube_size[1] # 90 # cube_size[1]*cube_size[2] self.R = self.L*self.D # 5760",
"[num_layers, batch, hidden_size] return hidden.contiguous(),cell.contiguous() \"\"\" Forward - eta [batch,channel,high,width] \"\"\" def forward(self,feature,command):",
"self.ctrl = ControlNet self.lstm = nn.LSTM( input_size = self.R, hidden_size = self.H, num_layers",
"hidden1 = self.init_Wh1 (feature) # [batch,D]*[D,H] -> [batch,H] hidden1 = self.init_tanh(hidden1) # [batch,H]",
"alp_ = torch.zeros([sequence_len,batch_size,self.L]).to( torch.device('cuda:0') ) bet_ = torch.zeros([sequence_len,batch_size,self.D]).to( torch.device('cuda:0') ) hdd_ = torch.zeros([sequence_len,batch_size,self.H]).to(",
"inicialize LSTM else : xt = sequence[0].unsqueeze(0) ht,ct = self.initializeLSTM(xt) # Command decoder",
"α = torch.stack(α, dim=0) β = torch.stack(β, dim=0) F = torch.stack(F, dim=0) return",
"* Input: feature [batch,D,h,w] * Output: hidden [1,batch,H] cell [1,batch,H] \"\"\" def initializeLSTM(self,feature):",
"spatial + xt # Categorical visual = visual * beta # [batch,L,D]x[batch,1,D] =",
"sequence[k].unsqueeze(0) # [ 1 ,L,D] # Visual Attention alpha = self.attn(xt,hidden[1].unsqueeze(0))# [batch,L,1] visual",
"# self.L*self.D self.H = n_hidden # 1024 # hidden_size self.M = n_hidden #",
"[1,batch,H] # (h,c) ~ [num_layers, batch, hidden_size] return hidden.contiguous(),cell.contiguous() \"\"\" Forward \"\"\" def",
"else batch_size n_visual = batch_size if self.training else 1 for k in range(n_range):",
"Declare layers self.attn = AttentionNet self.lstm = nn.LSTM( input_size = self.R, hidden_size =",
"1,self.n_task,self.S).uniform_() # Study if self.study: α,β,F = list(),list(),list() else : α,β,F = None,",
"= self.sequence_len if self.training else batch_size for k in range(n_range): # One time",
"# [batch,D]*[D,H] -> [batch,H] hidden = self.init_tanh(hidden) # [batch,H] hidden = hidden.unsqueeze(0) #",
"β.append(βt) F.append(Ft) # Concatenate st_ = torch.stack(st_,dim=0) ht_ = torch.stack(ht_,dim=0) if self.training: st_",
"self.attn = AttentionNet self.ctrl = ControlNet self.lstm = nn.LSTM( input_size=self.R, hidden_size=self.H, num_layers=2 )",
"LSTM rt = self.dimReduction(zt) rt = self. avgpool2(rt) rt = torch.flatten(rt , 1)",
"self.training: self.pred = self.pred.transpose(0,1).contiguous().view(batch_size*sequence_len, n_out) self. map = self. map.transpose(0,1).contiguous().view(batch_size*sequence_len,self.L) return self.pred, self.map",
"attention.\" International conference on machine learning. 2015. * Input: feature [batch,L,D] * Output:",
"nn from IPython.core.debugger import set_trace import ImitationLearning.VisualAttention.network.Gate as G \"\"\" Basic Decoder Module",
"[batch,L,D] hidden [1,batch,H] * Output: alpha [batch,L,1] \"\"\" class DualDecoder(nn.Module): \"\"\" Constructor \"\"\"",
"_zt = torch.flatten(_zt, 1) st, βt, Ft = self.FeatureAttn(_zt,ht[0],cm) # [batch,S] # Dimension",
"action,atten = (None,None) # Sequence loop n_range = self.sequence_len if self.training else batch_size",
"batch, hidden_size] return hidden.contiguous(),cell.contiguous() \"\"\" Forward - eta [batch,channel,high,width] \"\"\" def forward(self,feature,command): #",
"# [batch,L,D] else : ηt = sequence[k].unsqueeze(0) # [ 1 ,L,D] if self.training:",
"# High-level encoder zt = self.HighEncoder(xt) # Feature-based attention # s[t] = f(z[t],h[t-1])",
"- eta [batch,channel,high,width] \"\"\" def forward(self,feature,command): # Parameters sequence_len = self.sequence_len if self.training:",
") self.init_Wc = nn.Linear(LowLevelDim,self.H,bias=True ) self.init_tanh = nn.Tanh() self.avgpool1 = nn.AdaptiveAvgPool2d((1, 1)) self.avgpool2",
"# 64 self.L = cube_size[0]*cube_size[1] # 90 self.R = self.L*self.D # 5760 self.H",
"with torch.no_grad(): # Mean features feature = torch.mean(feature,1) # [batch,L,D] -> [batch,D] hidden",
"hdd_ = hdd_.transpose(0,1).contiguous().view(batch_size*sequence_len,self.H) return vis_, hdd_, {'alpha': alp_, 'beta': bet_}, {'control': hc} #",
"# Data if self.training: sequence = feature.view(batch_size,sequence_len,self.L,self.D).transpose_(0,1) # [sequence,batch,L,D] else : sequence =",
"= self. map.view(sequence_len,batch_size,self.L) # Sequence loop n_range = self.sequence_len if self.training else batch_size",
"\"\"\" Constructor \"\"\" def __init__(self,AttentionNet,cube_size,n_hidden): super(TVADecoder, self).__init__() # Parameters self.D = cube_size[2] #",
"Attention alpha = self.attn(xt,hidden)# [batch,L,1] visual = xt * alpha # [batch,L,D]x[batch,L,1] =",
"else : α,β,F = None, None, None # Sequence loop n_range = self.sequence_len",
"return hidden.contiguous(),cell.contiguous() \"\"\" Forward \"\"\" def forward(self,feature): # Parameters sequence_len = self.sequence_len if",
"torch.flatten(rt , 1) rt = rt.unsqueeze(0) # LSTM # * yt ~ [sequence,batch,H]",
"[batch,H] cell2 = self.init_tanh( cell2 ) # [batch,H] hidden = torch.stack([hidden1,hidden2], dim=0).contiguous() #",
"[batch, H] # Study if self.study: α.append(αt) β.append(βt) F.append(Ft) # Concatenate st_ =",
"self.study: α.append(αt) β.append(βt) F.append(Ft) # Concatenate st_ = torch.stack(st_,dim=0) ht_ = torch.stack(ht_,dim=0) if",
"= self.init_Wh2 (hidden1) # [batch,H]*[H,H] -> [batch,H] hidden2 = self.init_tanh(hidden2) # [batch,H] cell1",
"__init__(self,AttentionNet,cube_size,n_hidden): super(TVADecoder, self).__init__() # Parameters self.D = cube_size[2] # 64 self.L = cube_size[0]*cube_size[1]",
"Decoder Module ------------------ Ref: <NAME>., & <NAME>. (2017). \"Interpretable learning for self-driving cars",
"cmd.view(batch_size,sequence_len,-1).transpose(0,1) # [sequence,batch,4] # Prediction container st_,ht_ = list(),list() # State initialization if",
"hidden, training=self.training) self. map[k] = alpha.squeeze() if self.training: self.pred = self.pred.transpose(0,1).contiguous().view(batch_size*sequence_len, n_out) self.",
"cell ~ [1,batch,H] hidden,cell = self.initializeLSTM(xt) # Prediction container if self.training: vis_ =",
"for k in range(n_range): # One time if self.training: ηt = sequence[k] #",
"= nn.Linear(self.H,self.H,bias=True ) self.init_tanh = nn.Tanh() # Initialization torch.nn.init.xavier_uniform_(self.init_Wh1.weight) torch.nn.init.xavier_uniform_(self.init_Wh2.weight) torch.nn.init.xavier_uniform_(self.init_Wc1.weight) torch.nn.init.xavier_uniform_(self.init_Wc2.weight) self.lstm.reset_parameters()",
"= self. map.transpose(0,1).contiguous().view(batch_size*sequence_len,self.L) return self.pred, self.map \"\"\" Dual Decoder Module ------------------- * Input:",
"# [batch,H] cell2 = self.init_Wc2 ( cell1 ) # [batch,H]*[H,H] -> [batch,H] cell2",
"[sequence,batch, ...] else : sequence = feature # [batch, ...] # Inicialize hidden",
"# Output container self.pred = torch.zeros([self.batch_size,self.n_out]) self. map = torch.zeros([self.batch_size,self. L ]) #",
"= self.lstm(visual,(hidden,cell)) # Control pred[k] = self.ctrl(visual, hidden[0].unsqueeze(0)) map_[k] = alpha.squeeze() if self.study:",
"alp_, 'beta': bet_}, {'control': hc} # ------------------------------------------------------------------------------------------------ # # # ------------------------------------------------------------------------------------------------ class CatDecoder(nn.Module):",
"return pred, map_, {'action': action, 'attention': atten} \"\"\" TVA Decoder Module ------------------ Ref:",
"alp_ = torch.zeros([batch_size,self.L]).to( torch.device('cuda:0') ) bet_ = torch.zeros([batch_size,self.D]).to( torch.device('cuda:0') ) hdd_ = torch.zeros([batch_size,self.H]).to(",
"else : batch_size = feature.shape[0] _,C,H,W = feature.shape # Batch of Tensor Images",
"= cube_size[0]*cube_size[1] # 90 # cube_size[1]*cube_size[2] self.R = self.L*self.D # 5760 # self.L*self.D",
"on computer vision (pp. 2942-2950). * Input: feature [batch,L,D] hidden [1,batch,H] * Output:",
"Command decoder cmd = self.CmdDecoder(command) if self.training: cmd = cmd.view(batch_size,sequence_len,-1).transpose(0,1) # [sequence,batch,4] #",
"state # * hidden ~ [1,batch,H] # * cell ~ [1,batch,H] hidden,cell =",
"alp_[k] = alpha.squeeze() # [1,batch,L] bet_[k] = beta.squeeze() # [1,batch,D] hdd_[k] = hidden[0].unsqueeze(0)",
"self. avgpool2(rt) rt = torch.flatten(rt , 1) rt = rt.unsqueeze(0) # LSTM #",
"G.GRUGate(LowLevelDim) # Output self.dimReduction = nn.Conv2d(HighLevelDim,self.R, kernel_size=1, bias=False) self.lstm = nn.LSTM( input_size =",
"α,β,F = None, None, None # Sequence loop n_range = self.sequence_len if self.training",
",batch,H] _,(hidden,cell) = self.lstm(visual,(hidden,cell)) # Control self.pred[k] = self.ctrl(visual, hidden, training=self.training) self. map[k]",
"bet_}, {'control': hc} # ------------------------------------------------------------------------------------------------ # # # ------------------------------------------------------------------------------------------------ class CatDecoder(nn.Module): \"\"\" Constructor",
"1024 # hidden_size self.sequence_len = 20 self.batch_size = 120 self.n_out = 3 self.study",
"xt * alpha # [batch,L,D]x[batch,L,1] = [batch,L,D] visual = visual.reshape(n_visual,self.R) # [batch,R] visual",
"batch, hidden_size] return hidden.contiguous(),cell.contiguous() \"\"\" Forward \"\"\" def forward(self,feature): # Parameters sequence_len =",
"ImitationLearning.VisualAttention.network.Gate as G \"\"\" Basic Decoder Module -------------------- Ref: <NAME>., & <NAME>. (2017).",
"(h,c) ~ [num_layers, batch, hidden_size] return hidden.contiguous(),cell.contiguous() \"\"\" Forward \"\"\" def forward(self,feature): #",
"atten = torch.zeros([self.batch_size,self.H]).to( torch.device('cuda:0') ) else: action,atten = (None,None) # Sequence loop n_range",
"# Categorical visual = visual * beta # [batch,L,D]x[batch,1,D] = [batch,L,D] visual =",
"hidden,cell = self.initializeLSTM(xt) # Prediction container if self.training: pred = torch.zeros([sequence_len,batch_size, n_out]).to( torch.device('cuda:0')",
"[batch, ...] # Inicialize hidden state and cell state # * hidden ~",
"cell = self.init_Wc(feature) # [batch,D]*[D,H] -> [batch,H] cell = self.init_tanh(cell) # [batch,H] cell",
"self.study = study # Parameters self.H = n_hidden # output LSTM 1024 2048",
"image caption generation with visual attention.\" International conference on machine learning. 2015. *",
"= self.SpatialAttn(ηt,st) xt = self.Gate(ηt,xt) # High-level encoder zt = self.HighEncoder(xt) # Feature-based",
"+ xt # Categorical visual = visual * beta # [batch,L,D]x[batch,1,D] = [batch,L,D]",
"= hdd_.transpose(0,1).contiguous().view(batch_size*sequence_len,self.H) return vis_, hdd_, {'alpha': alp_, 'beta': bet_}, {'control': hc} # ------------------------------------------------------------------------------------------------",
"for k in range(n_range): # One time if self.training: xt = sequence[k] #",
"= self.sequence_len if self.training else batch_size n_visual = batch_size if self.training else 1",
"hidden = self.init_tanh(hidden) # [batch,H] hidden = hidden.unsqueeze(0) # [1,batch,H] cell = self.init_Wc(feature)",
"torch.nn.init.xavier_uniform_(self.init_Wc.weight) self.lstm.reset_parameters() \"\"\" Initialize LSTM: hidden state and cell state Ref: <NAME>, et",
"from IPython.core.debugger import set_trace import ImitationLearning.VisualAttention.network.Gate as G \"\"\" Basic Decoder Module --------------------",
"if self.training: xt = sequence[k] # [batch,L,D] else : xt = sequence[k].unsqueeze(0) #",
": xt = sequence[0].unsqueeze(0) ht,ct = self.initializeLSTM(xt) # Command decoder cmd = self.CmdDecoder(command)",
",batch,H] # * cell ~ [ layers ,batch,H] _,(ht,ct)= self.lstm(rt,(ht,ct)) # Output st_.append(st.squeeze())",
"self.pred = torch.zeros([self.batch_size,self.n_out]) self. map = torch.zeros([self.batch_size,self. L ]) # Declare layers self.attn",
"~ [1,batch,H] # * cell ~ [1,batch,H] hidden,cell = self.initializeLSTM(xt) # Prediction container",
"sequence[k].unsqueeze(0) # [ 1 ,L,D] # Visual Attention alpha = self.attn(xt,hidden)# [batch,L,1] visual",
"alpha,beta = self.attn(xt,hidden) # [batch,L,1] # Spatial spatial = xt * alpha #",
"pred = pred.transpose(0,1).contiguous().view(batch_size*sequence_len, n_out) map_ = map_.transpose(0,1).contiguous().view(batch_size*sequence_len,self.L) # Return return pred, map_, {'action':",
"* Input: feature [batch,L,D] hidden [1,batch,H] * Output: alpha [batch,L,1] \"\"\" class BasicDecoder(nn.Module):",
"cube_size[1]*cube_size[2] self.R = self.L*self.D # 5760 # self.L*self.D self.H = n_hidden # 1024",
"Parameters sequence_len = self.sequence_len n_out = self.n_out if self.training: batch_size = int(feature.shape[0]/sequence_len) else",
"= cmd[k] # [batch, 4 ] else : cm = cmd[k].unsqueeze(0) # [",
"= (None,None,None) # Sequence loop n_range = self.sequence_len if self.training else batch_size n_visual",
"n_out) self. map = self. map.transpose(0,1).contiguous().view(batch_size*sequence_len,self.L) return self.pred, self.map \"\"\" Dual Decoder Module",
"[batch,H] hidden1 = self.init_tanh(hidden1) # [batch,H] hidden2 = self.init_Wh2 (hidden1) # [batch,H]*[H,H] ->",
"self.pred = self.pred.transpose(0,1).contiguous().view(batch_size*sequence_len, n_out) self. map = self. map.transpose(0,1).contiguous().view(batch_size*sequence_len,self.L) return self.pred, self.map \"\"\"",
") self.init_tanh = nn.Tanh() # Initialization torch.nn.init.xavier_uniform_(self.init_Wh.weight) torch.nn.init.xavier_uniform_(self.init_Wc.weight) self.lstm.reset_parameters() \"\"\" Initialize LSTM: hidden",
"causal attention\". In Proceedings of the IEEE international conference on computer vision (pp.",
"βt, Ft = self.FeatureAttn(_zt,ht[0],cm) # [batch,S] # Dimension reduction to LSTM rt =",
"self.init_Wh = nn.Linear(self.D,self.H,bias=True ) self.init_Wc = nn.Linear(self.D,self.H,bias=True ) self.init_tanh = nn.Tanh() # Initialization",
"Attention alpha,beta = self.attn(xt,hidden) # [batch,L,1] # Spatial spatial = xt * alpha",
"n_out = self.n_out if self.training: batch_size = int(feature.shape[0]/sequence_len) else : batch_size = feature.shape[0]",
"xt = sequence[k].unsqueeze(0) # [ 1 ,L,D] # Visual Attention alpha = self.attn(xt,hidden[1].unsqueeze(0))#",
"# [batch,D]*[D,H] -> [batch,H] cell1 = self.init_tanh( cell1 ) # [batch,H] cell2 =",
"* beta # [batch,L,D]x[batch,1,D] = [batch,L,D] visual = visual.reshape(n_visual,self.R) # [batch,R] visual =",
"hidden,cell = self.initializeLSTM(xt) # Prediction container if self.training: self.pred = self.pred.view(sequence_len,batch_size, n_out) self.",
"# 512 self.M = n_hidden # 512 self.sequence_len = 20 self.batch_size = 120",
"= cmd[k].unsqueeze(0) # [ 1 , 4 ] # Spatial Attention xt, αt",
"# [batch,S] # Dimension reduction to LSTM rt = self.dimReduction(zt) rt = self.",
"= torch.zeros([batch_size,self.R]).to( torch.device('cuda:0') ) alp_ = torch.zeros([batch_size,self.L]).to( torch.device('cuda:0') ) bet_ = torch.zeros([batch_size,self.D]).to( torch.device('cuda:0')",
"return hidden.contiguous(),cell.contiguous() \"\"\" Forward \"\"\" def forward(self,feature): # Parameters sequence_len = self.sequence_len n_out",
"hidden [1,batch,H] * Output: alpha [batch,L,1] \"\"\" class BasicDecoder(nn.Module): \"\"\" Constructor \"\"\" def",
"[batch,R] visual = visual.unsqueeze(0) # [1,batch,R] # LSTM # * yt ~ [sequence,batch,H]",
"* hidden ~ [1,batch,H] # * cell ~ [1,batch,H] if self.training: xt =",
"= ht_.transpose(0,1).reshape(batch_size*sequence_len, self.H) # Compile study if self.study: α = torch.stack(α, dim=0) β",
"# Declare layers self.attn = AttentionNet self.lstm = nn.LSTM( input_size = self.R, hidden_size",
"attention # s[t] = f(z[t],h[t-1]) _zt = self.avgpool1( zt) _zt = torch.flatten(_zt, 1)",
"attention.\" International conference on machine learning. 2015. * Input: feature [batch,D,h,w] * Output:",
"return self.pred, self.map \"\"\" Dual Decoder Module ------------------- * Input: feature [batch,L,D] hidden",
"# hidden_size self.M = n_hidden # 1024 # hidden_size self.sequence_len = 20 self.batch_size",
"False # Declare layers self.attn = AttentionNet self.ctrl = ControlNet self.lstm = nn.LSTM(",
"super(DualDecoder, self).__init__() # Parameters self.D = cube_size[2] # 64 # cube_size[0] self.L =",
"self.training: cm = cmd[k] # [batch, 4 ] else : cm = cmd[k].unsqueeze(0)",
"self.attn(xt,hidden[1].unsqueeze(0))# [batch,L,1] visual = xt * alpha # [batch,L,D]x[batch,L,1] = [batch,L,D] visual =",
"= self.init_tanh(hidden2) # [batch,H] cell1 = self.init_Wc1 (feature) # [batch,D]*[D,H] -> [batch,H] cell1",
") # Study rountime if self.study: action = torch.zeros([self.batch_size,self.H]).to( torch.device('cuda:0') ) atten =",
"torch.mean(feature,(2,3)) # [batch,D,h,w] -> [batch,D] hidden = self.init_Wh(feature) # [batch,D]*[D,H] -> [batch,H] hidden",
"[batch,L,D] visual = visual.reshape(n_visual,self.R) # [batch,R] visual = visual.unsqueeze(0) # [1,batch,R] # LSTM",
"= self.init_tanh(hidden1) # [batch,H] hidden2 = self.init_Wh2 (hidden1) # [batch,H]*[H,H] -> [batch,H] hidden2",
"hdd_.transpose(0,1).contiguous().view(batch_size*sequence_len,self.H) return vis_, hdd_, {'alpha': alp_, 'beta': bet_}, {'control': hc} # ------------------------------------------------------------------------------------------------ #",
"1 ,L,D] # Visual Attention alpha = self.attn(xt,hidden[1].unsqueeze(0))# [batch,L,1] visual = xt *",
"self.sequence_len = 20 # Attention self.HighEncoder = HighEncoderNet self.SpatialAttn = SpatialNet self.FeatureAttn =",
"# [batch,D]*[D,H] -> [batch,H] cell = self.init_tanh(cell) # [batch,H] cell = cell.unsqueeze(0) #",
"LSTM: hidden state and cell state Ref: <NAME>, et al. \"Show, attend and",
",batch,H] _,(ht,ct)= self.lstm(rt,(ht,ct)) # Output st_.append(st.squeeze()) # [batch,n_task,S] ht_.append(ht.squeeze()) # [batch, H] #",
"= visual.unsqueeze(0) # [1,batch,R] # LSTM # * yt ~ [sequence,batch,H] # *",
": xt = sequence[k].unsqueeze(0) # [ 1 ,L,D] # Visual Attention alpha,beta =",
"= list(),list(),list() else : α,β,F = None, None, None # Sequence loop n_range",
"= 3 self.study = False # Declare layers self.attn = AttentionNet self.ctrl =",
"# Parameters sequence_len = self.sequence_len if self.training: batch_size = int(feature.shape[0]/sequence_len) else : batch_size",
"= self.sequence_len if self.training: batch_size = int(feature.shape[0]/sequence_len) else : batch_size = feature.shape[0] #",
"None # hc,ha,hb = (None,None,None) # Sequence loop n_range = self.sequence_len if self.training",
"nn.Tanh() self.avgpool1 = nn.AdaptiveAvgPool2d((1, 1)) self.avgpool2 = nn.AdaptiveAvgPool2d((1, 1)) self.normSpa = nn.BatchNorm2d(LowLevelDim) self.ReLU",
"= nn.Linear(self.D,self.H,bias=True ) self.init_Wc = nn.Linear(self.D,self.H,bias=True ) self.init_tanh = nn.Tanh() # Initialization torch.nn.init.xavier_uniform_(self.init_Wh.weight)",
"self.FeatureAttn(_zt,ht[0],cm) # [batch,S] # Dimension reduction to LSTM rt = self.dimReduction(zt) rt =",
"= nn.Linear(self.D,self.H,bias=True ) self.init_tanh = nn.Tanh() # Initialization torch.nn.init.xavier_uniform_(self.init_Wh.weight) torch.nn.init.xavier_uniform_(self.init_Wc.weight) self.lstm.reset_parameters() \"\"\" Initialize",
"n_out]).to( torch.device('cuda:0') ) map_ = torch.zeros([sequence_len,batch_size,self.L]).to( torch.device('cuda:0') ) else: pred = torch.zeros([batch_size, n_out]).to(",
"* Input: feature [batch,L,D] hidden [1,batch,H] * Output: alpha [batch,L,1] \"\"\" class TVADecoder(nn.Module):",
"3 self.study = False # Declare layers self.attn = AttentionNet self.ctrl = ControlNet",
"None # Sequence loop n_range = self.sequence_len if self.training else batch_size for k",
"self.init_tanh(hidden1) # [batch,H] hidden2 = self.init_Wh2 (hidden1) # [batch,H]*[H,H] -> [batch,H] hidden2 =",
"self.R = self.L*self.D # 5760 self.H = n_hidden # 512 self.M = n_hidden",
"4 ] # Spatial Attention xt, αt = self.SpatialAttn(ηt,st) xt = self.Gate(ηt,xt) #",
"torch.nn.init.xavier_uniform_(self.init_Wc2.weight) self.lstm.reset_parameters() \"\"\" Initialize LSTM: hidden state and cell state Ref: <NAME>, et",
"init_Wc.weight) self.lstm.reset_parameters() \"\"\" Initialize LSTM: hidden state and cell state Ref: Xu, Kelvin,",
"LSTM 1024 2048 self.R = int(n_hidden/4) # input LSTM 256 512 self.S =",
"hc} # ------------------------------------------------------------------------------------------------ # # # ------------------------------------------------------------------------------------------------ class CatDecoder(nn.Module): \"\"\" Constructor \"\"\" def",
",L,D] # Visual Attention alpha = self.attn(xt,hidden)# [batch,L,1] visual = xt * alpha",
"[1,batch,H] if self.training: xt = sequence[0] # Input to inicialize LSTM else :",
"k in range(n_range): # One time if self.training: xt = sequence[k] # [batch,L,D]",
"# [1,batch,L] bet_[k] = beta.squeeze() # [1,batch,D] hdd_[k] = hidden[0].unsqueeze(0) # [1,batch,H] if",
"SpatialNet, FeatureNet, CommandNet, LowLevelDim=128, HighLevelDim=512, n_hidden=1024, n_state=64,n_task=3, study=False): super(CatDecoder, self).__init__() self.study = study",
"vis_.transpose(0,1).contiguous().view(batch_size*sequence_len,self.R) alp_ = alp_.transpose(0,1).contiguous().view(batch_size*sequence_len,self.L) bet_ = bet_.transpose(0,1).contiguous().view(batch_size*sequence_len,self.D) hdd_ = hdd_.transpose(0,1).contiguous().view(batch_size*sequence_len,self.H) return vis_, hdd_,",
"training=self.training) self. map[k] = alpha.squeeze() if self.training: self.pred = self.pred.transpose(0,1).contiguous().view(batch_size*sequence_len, n_out) self. map",
"Sequence loop n_range = self.sequence_len if self.training else batch_size for k in range(n_range):",
"# [batch,H] hidden = hidden.unsqueeze(0) # [1,batch,H] cell = self.init_Wc(feature) # [batch,D]*[D,H] ->",
"# Prediction container st_,ht_ = list(),list() # State initialization if self.training: st =",
"if self.training: sequence = feature.view(batch_size,sequence_len,self.L,self.D).transpose_(0,1) # [sequence,batch,L,D] else : sequence = feature #",
"β = torch.stack(β, dim=0) F = torch.stack(F, dim=0) return st_, {'hidden': ht_, 'feature':",
": ηt = sequence[k].unsqueeze(0) # [ 1 ,L,D] if self.training: cm = cmd[k]",
"# [batch,L,D]x[batch,L,1] = [batch,L,D] visual = spatial + xt # Categorical visual =",
") self.init_Wc2 = nn.Linear(self.H,self.H,bias=True ) self.init_tanh = nn.Tanh() # Initialization torch.nn.init.xavier_uniform_(self.init_Wh1.weight) torch.nn.init.xavier_uniform_(self.init_Wh2.weight) torch.nn.init.xavier_uniform_(self.init_Wc1.weight)",
"Module -------------------- Ref: <NAME>., & <NAME>. (2017). \"Interpretable learning for self-driving cars by",
") self.init_Wh2 = nn.Linear(self.H,self.H,bias=True ) self.init_Wc1 = nn.Linear(self.D,self.H,bias=True ) self.init_Wc2 = nn.Linear(self.H,self.H,bias=True )",
"self.attn = AttentionNet self.lstm = nn.LSTM( input_size = self.R, hidden_size = self.H, num_layers",
"# [batch,L,D]x[batch,L,1] = [batch,L,D] visual = visual.reshape(n_visual,self.R) # [batch,R] visual = visual.unsqueeze(0) #",
"cube_size[0]*cube_size[1] # 90 # cube_size[1]*cube_size[2] self.R = self.L*self.D # 5760 # self.L*self.D self.H",
"else batch_size for k in range(n_range): # One time if self.training: ηt =",
"& <NAME>. (2017). \"Interpretable learning for self-driving cars by visualizing causal attention\". In",
"Data if self.training: sequence = feature.view(batch_size,sequence_len,self.L,self.D).transpose_(0,1) # [sequence,batch,L,D] else : sequence = feature",
"= self.pred.view(sequence_len,batch_size, n_out) self. map = self. map.view(sequence_len,batch_size,self.L) # Sequence loop n_range =",
"LSTM else : xt = sequence[0].unsqueeze(0) ht,ct = self.initializeLSTM(xt) # Command decoder cmd",
"torch.mean(feature,1) # [batch,L,D] -> [batch,D] hidden1 = self.init_Wh1 (feature) # [batch,D]*[D,H] -> [batch,H]",
"[1,batch,H] \"\"\" def initializeLSTM(self,feature): with torch.no_grad(): # Mean features feature = torch.mean(feature,1) #",
"torch.nn.init.xavier_uniform_(self.init_Wh1.weight) torch.nn.init.xavier_uniform_(self.init_Wh2.weight) torch.nn.init.xavier_uniform_(self.init_Wc1.weight) torch.nn.init.xavier_uniform_(self.init_Wc2.weight) self.lstm.reset_parameters() \"\"\" Initialize LSTM: hidden state and cell state",
"conference on machine learning. 2015. * Input: feature [batch,L,D] * Output: hidden [1,batch,H]",
"* cell ~ [1,batch,H] hidden,cell = self.initializeLSTM(xt) # Prediction container if self.training: vis_",
"for self-driving cars by visualizing causal attention\". In Proceedings of the IEEE international",
"Declare layers self.attn = AttentionNet self.ctrl = ControlNet self.lstm = nn.LSTM( input_size =",
"xt = sequence[0].unsqueeze(0) # Inicialize hidden state and cell state # * hidden",
"batch, hidden_size] return hidden,cell \"\"\" Forward \"\"\" def forward(self,feature): # Parameters sequence_len =",
"256 512 self.S = n_state self.n_task = n_task self.sequence_len = 20 # Attention",
"shape # Data if self.training: sequence = feature.view(batch_size,sequence_len,C,H,W).transpose(0,1) # [sequence,batch, ...] else :",
"[batch,L,1] visual = xt * alpha # [batch,L,D]x[batch,L,1] = [batch,L,D] visual = visual.reshape(n_visual,self.R)",
"self.training: xt = sequence[0] # Input to inicialize LSTM else : xt =",
"# [batch,H] hidden2 = self.init_Wh2 (hidden1) # [batch,H]*[H,H] -> [batch,H] hidden2 = self.init_tanh(hidden2)",
"else : sequence = feature # [batch,L,D] # Input to inicialize LSTM if",
"\"\"\" Dual Decoder Module ------------------- * Input: feature [batch,L,D] hidden [1,batch,H] * Output:",
"= False # Declare layers self.attn = AttentionNet self.lstm = nn.LSTM( input_size =",
"= self.init_Wc1 (feature) # [batch,D]*[D,H] -> [batch,H] cell1 = self.init_tanh( cell1 ) #",
"torch.zeros([sequence_len,batch_size, n_out]).to( torch.device('cuda:0') ) map_ = torch.zeros([sequence_len,batch_size,self.L]).to( torch.device('cuda:0') ) else: pred = torch.zeros([batch_size,",
"* Input: feature [batch,L,D] hidden [1,batch,H] * Output: alpha [batch,L,1] \"\"\" class DualDecoder(nn.Module):",
"import torch.nn as nn from IPython.core.debugger import set_trace import ImitationLearning.VisualAttention.network.Gate as G \"\"\"",
"= self.initializeLSTM(xt) # Prediction container if self.training: self.pred = self.pred.view(sequence_len,batch_size, n_out) self. map",
"* alpha # [batch,L,D]x[batch,L,1] = [batch,L,D] visual = spatial + xt # Categorical",
"_,(hidden,cell) = self.lstm(visual,(hidden,cell)) # Control pred[k] = self.ctrl(visual, hidden[0].unsqueeze(0)) map_[k] = alpha.squeeze() if",
"# One time if self.training: ηt = sequence[k] # [batch,L,D] else : ηt",
"Kelvin, et al. \"Show, attend and tell: Neural image caption generation with visual",
"AttentionNet self.ctrl = ControlNet self.lstm = nn.LSTM( input_size = self.R, hidden_size = self.H,",
"L ]) # Declare layers self.attn = AttentionNet self.ctrl = ControlNet self.lstm =",
"cell state # * hidden ~ [1,batch,H] # * cell ~ [1,batch,H] hidden,cell",
"if self.training else 1 for k in range(n_range): # One time if self.training:",
"CommandNet, LowLevelDim=128, HighLevelDim=512, n_hidden=1024, n_state=64,n_task=3, study=False): super(CatDecoder, self).__init__() self.study = study # Parameters",
"nn.AdaptiveAvgPool2d((1, 1)) self.avgpool2 = nn.AdaptiveAvgPool2d((1, 1)) self.normSpa = nn.BatchNorm2d(LowLevelDim) self.ReLU = nn.ReLU() #",
"class BasicDecoder(nn.Module): \"\"\" Constructor \"\"\" def __init__(self,AttentionNet,ControlNet,cube_size,n_hidden): super(BasicDecoder, self).__init__() # Parameters self.D =",
"self. map[k] = alpha.squeeze() if self.training: self.pred = self.pred.transpose(0,1).contiguous().view(batch_size*sequence_len, n_out) self. map =",
"= feature.view(batch_size,sequence_len,self.L,self.D).transpose_(0,1) # [sequence,batch,L,D] else : sequence = feature # [batch,L,D] # Input",
"= self.n_out if self.training: batch_size = int(feature.shape[0]/sequence_len) else : batch_size = feature.shape[0] #",
"self.attn = AttentionNet self.ctrl = ControlNet self.lstm = nn.LSTM( input_size = self.R, hidden_size",
"hdd_ = torch.zeros([batch_size,self.H]).to( torch.device('cuda:0') ) # Study rountime if self.study: hc = torch.zeros([self.batch_size,self.H]).to(",
"<NAME>., & <NAME>. (2017). \"Interpretable learning for self-driving cars by visualizing causal attention\".",
"n_hidden # 512 self.sequence_len = 20 self.batch_size = 120 self.n_out = 3 self.study",
"2942-2950). * Input: feature [batch,L,D] hidden [1,batch,H] * Output: alpha [batch,L,1] \"\"\" class",
"LowLevelDim=128, HighLevelDim=512, n_hidden=1024, n_state=64,n_task=3, study=False): super(CatDecoder, self).__init__() self.study = study # Parameters self.H",
"= nn.Conv2d(HighLevelDim,self.R, kernel_size=1, bias=False) self.lstm = nn.LSTM( input_size = self.R, hidden_size = self.H,",
"[1,batch,D] hdd_[k] = hidden[0].unsqueeze(0) # [1,batch,H] if self.study: hc[k] = hidden[0].squeeze() if self.training:",
"# hidden_size self.sequence_len = 20 self.batch_size = 120 self.n_out = 3 self.study =",
"120 self.n_out = 3 # Output container self.pred = torch.zeros([self.batch_size,self.n_out]) self. map =",
"container if self.training: vis_ = torch.zeros([sequence_len,batch_size,self.R]).to( torch.device('cuda:0') ) alp_ = torch.zeros([sequence_len,batch_size,self.L]).to( torch.device('cuda:0') )",
"DualDecoder(nn.Module): \"\"\" Constructor \"\"\" def __init__(self,AttentionNet,ControlNet,cube_size,n_hidden): super(DualDecoder, self).__init__() # Parameters self.D = cube_size[2]",
"= alp_.transpose(0,1).contiguous().view(batch_size*sequence_len,self.L) bet_ = bet_.transpose(0,1).contiguous().view(batch_size*sequence_len,self.D) hdd_ = hdd_.transpose(0,1).contiguous().view(batch_size*sequence_len,self.H) return vis_, hdd_, {'alpha': alp_,",
"torch.device('cuda:0') ) alp_ = torch.zeros([batch_size,self.L]).to( torch.device('cuda:0') ) bet_ = torch.zeros([batch_size,self.D]).to( torch.device('cuda:0') ) hdd_",
"# Mean features feature = torch.mean(feature,1) # [batch,L,D] -> [batch,D] hidden1 = self.init_Wh1",
"= nn.Linear(LowLevelDim,self.H,bias=True ) self.init_Wc = nn.Linear(LowLevelDim,self.H,bias=True ) self.init_tanh = nn.Tanh() self.avgpool1 = nn.AdaptiveAvgPool2d((1,",
"kernel_size=1, bias=False) self.lstm = nn.LSTM( input_size = self.R, hidden_size = self.H, num_layers =",
"= self.init_Wc2 ( cell1 ) # [batch,H]*[H,H] -> [batch,H] cell2 = self.init_tanh( cell2",
"self.training: xt = sequence[k] # [batch,L,D] else : xt = sequence[k].unsqueeze(0) # [",
"torch.zeros([batch_size,self.H]).to( torch.device('cuda:0') ) # Study rountime if self.study: hc = torch.zeros([self.batch_size,self.H]).to( torch.device('cuda:0') )",
"feature = torch.mean(feature,(2,3)) # [batch,D,h,w] -> [batch,D] hidden = self.init_Wh(feature) # [batch,D]*[D,H] ->",
"= self.init_Wh(feature) # [batch,D]*[D,H] -> [batch,H] hidden = self.init_tanh(hidden) # [batch,H] hidden =",
"zt) _zt = torch.flatten(_zt, 1) st, βt, Ft = self.FeatureAttn(_zt,ht[0],cm) # [batch,S] #",
"# (h,c) ~ [num_layers, batch, hidden_size] return hidden.contiguous(),cell.contiguous() \"\"\" Forward - eta [batch,channel,high,width]",
"rt.unsqueeze(0) # LSTM # * yt ~ [sequence,batch,H] # * hidden ~ [",
"if self.training: ηt = sequence[k] # [batch,L,D] else : ηt = sequence[k].unsqueeze(0) #",
"(None,None,None) # Sequence loop n_range = self.sequence_len if self.training else batch_size n_visual =",
"torch.nn.init.xavier_uniform_(self.init_Wh2.weight) torch.nn.init.xavier_uniform_(self.init_Wc1.weight) torch.nn.init.xavier_uniform_(self.init_Wc2.weight) self.lstm.reset_parameters() \"\"\" Initialize LSTM: hidden state and cell state Ref:",
"self.lstm = nn.LSTM( input_size=self.R, hidden_size=self.H, num_layers=2 ) self.init_Wh1 = nn.Linear(self.D,self.H,bias=True ) self.init_Wh2 =",
"[1,batch,H] cell [1,batch,H] \"\"\" def initializeLSTM(self,feature): with torch.no_grad(): # Mean features feature =",
"cube_size[0]*cube_size[1] # 90 self.R = self.L*self.D # 5760 self.H = n_hidden # 512",
"visual = visual.reshape(n_visual,self.R) # [batch,R] visual = visual.unsqueeze(0) # [1,batch,R] # LSTM #",
"torch.stack(ht_,dim=0) if self.training: st_ = st_.transpose(0,1).reshape(batch_size*sequence_len,self.n_task,self.S) ht_ = ht_.transpose(0,1).reshape(batch_size*sequence_len, self.H) # Compile study",
"{'action': action, 'attention': atten} \"\"\" TVA Decoder Module ------------------ Ref: <NAME>., & <NAME>.",
"self.training else batch_size for k in range(n_range): # One time if self.training: ηt",
"Spatial spatial = xt * alpha # [batch,L,D]x[batch,L,1] = [batch,L,D] visual = spatial",
"] else : cm = cmd[k].unsqueeze(0) # [ 1 , 4 ] #",
"Prediction container if self.training: vis_ = torch.zeros([sequence_len,batch_size,self.R]).to( torch.device('cuda:0') ) alp_ = torch.zeros([sequence_len,batch_size,self.L]).to( torch.device('cuda:0')",
"self.initializeLSTM(xt) # Prediction container if self.training: pred = torch.zeros([sequence_len,batch_size, n_out]).to( torch.device('cuda:0') ) map_",
"[batch,L,D]x[batch,L,1] = [batch,L,D] visual = spatial + xt # Categorical visual = visual",
"= self.attn(xt,hidden[1].unsqueeze(0))# [batch,L,1] visual = xt * alpha # [batch,L,D]x[batch,L,1] = [batch,L,D] visual",
"time if self.training: xt = sequence[k] # [batch,L,D] else : xt = sequence[k].unsqueeze(0)",
"Input to inicialize LSTM if self.training: xt = sequence[0] else : xt =",
"cell [1,batch,H] \"\"\" def initializeLSTM(self,feature): with torch.no_grad(): # Mean features feature = torch.mean(feature,1)",
"[batch,L,1] \"\"\" class TVADecoder(nn.Module): \"\"\" Constructor \"\"\" def __init__(self,AttentionNet,cube_size,n_hidden): super(TVADecoder, self).__init__() # Parameters",
") bet_ = torch.zeros([batch_size,self.D]).to( torch.device('cuda:0') ) hdd_ = torch.zeros([batch_size,self.H]).to( torch.device('cuda:0') ) # Study",
"self.n_out = 3 self.study = False # Declare layers self.attn = AttentionNet self.lstm",
"[ layers ,batch,H] _,(hidden,cell) = self.lstm(visual,(hidden,cell)) # Control self.pred[k] = self.ctrl(visual, hidden, training=self.training)",
"LSTM: hidden state and cell state Ref: Xu, Kelvin, et al. \"Show, attend",
"if self.training: pred = pred.transpose(0,1).contiguous().view(batch_size*sequence_len, n_out) map_ = map_.transpose(0,1).contiguous().view(batch_size*sequence_len,self.L) # Return return pred,",
"torch.stack(β, dim=0) F = torch.stack(F, dim=0) return st_, {'hidden': ht_, 'feature': F}, {'alpha':",
"int(feature.shape[0]/sequence_len) else : batch_size = feature.shape[0] # Data if self.training: sequence = feature.view(batch_size,sequence_len,self.L,self.D).transpose_(0,1)",
": sequence = feature # [batch, ...] # Inicialize hidden state and cell",
"# (h,c) ~ [num_layers, batch, hidden_size] return hidden,cell \"\"\" Forward \"\"\" def forward(self,feature):",
"= self.pred.transpose(0,1).contiguous().view(batch_size*sequence_len, n_out) self. map = self. map.transpose(0,1).contiguous().view(batch_size*sequence_len,self.L) return self.pred, self.map \"\"\" Dual",
"= nn.ReLU() # Initialization torch.nn.init.xavier_uniform_(self.dimReduction.weight) torch.nn.init.xavier_uniform_(self. init_Wh.weight) torch.nn.init.xavier_uniform_(self. init_Wc.weight) self.lstm.reset_parameters() \"\"\" Initialize LSTM:",
"# [batch,L,D]x[batch,1,D] = [batch,L,D] visual = visual.reshape(n_visual,self.R) # [batch,R] visual = visual.unsqueeze(0) #",
"= self.init_tanh(hidden) # [batch,H] hidden = hidden.unsqueeze(0) # [1,batch,H] cell = self.init_Wc(feature) #",
"n_out) map_ = map_.transpose(0,1).contiguous().view(batch_size*sequence_len,self.L) # Return return pred, map_, {'action': action, 'attention': atten}",
"[1,batch,H] * Output: alpha [batch,L,1] \"\"\" class DualDecoder(nn.Module): \"\"\" Constructor \"\"\" def __init__(self,AttentionNet,ControlNet,cube_size,n_hidden):",
"= list(),list() # State initialization if self.training: st = torch.cuda.FloatTensor(batch_size,self.n_task,self.S).uniform_() else : st",
"= n_task self.sequence_len = 20 # Attention self.HighEncoder = HighEncoderNet self.SpatialAttn = SpatialNet",
"_,(hidden,cell) = self.lstm(visual,(hidden,cell)) # Control self.pred[k] = self.ctrl(visual, hidden, training=self.training) self. map[k] =",
"Output st_.append(st.squeeze()) # [batch,n_task,S] ht_.append(ht.squeeze()) # [batch, H] # Study if self.study: α.append(αt)",
"n_hidden # 512 self.M = n_hidden # 512 self.sequence_len = 20 self.batch_size =",
"= SpatialNet self.FeatureAttn = FeatureNet self. CmdDecoder = CommandNet self.Gate = G.GRUGate(LowLevelDim) #",
"self. map.view(sequence_len,batch_size,self.L) # Sequence loop n_range = self.sequence_len if self.training else batch_size n_visual",
"[1,batch,H] \"\"\" def initializeLSTM(self,feature): with torch.no_grad(): # Mean features feature = torch.mean(feature,(2,3)) #",
"= self.init_Wh1 (feature) # [batch,D]*[D,H] -> [batch,H] hidden1 = self.init_tanh(hidden1) # [batch,H] hidden2",
"hidden,cell = self.initializeLSTM(xt) # Prediction container if self.training: vis_ = torch.zeros([sequence_len,batch_size,self.R]).to( torch.device('cuda:0') )",
"\"\"\" class BasicDecoder(nn.Module): \"\"\" Constructor \"\"\" def __init__(self,AttentionNet,ControlNet,cube_size,n_hidden): super(BasicDecoder, self).__init__() # Parameters self.D",
"Concatenate st_ = torch.stack(st_,dim=0) ht_ = torch.stack(ht_,dim=0) if self.training: st_ = st_.transpose(0,1).reshape(batch_size*sequence_len,self.n_task,self.S) ht_",
"and tell: Neural image caption generation with visual attention.\" International conference on machine",
"FeatureNet self. CmdDecoder = CommandNet self.Gate = G.GRUGate(LowLevelDim) # Output self.dimReduction = nn.Conv2d(HighLevelDim,self.R,",
": xt = sequence[0].unsqueeze(0) # Inicialize hidden state and cell state # *",
"self.dimReduction = nn.Conv2d(HighLevelDim,self.R, kernel_size=1, bias=False) self.lstm = nn.LSTM( input_size = self.R, hidden_size =",
"# 5760 # self.L*self.D self.H = n_hidden # 1024 # hidden_size self.M =",
"'attention': atten} \"\"\" TVA Decoder Module ------------------ Ref: <NAME>., & <NAME>. (2017). \"Interpretable",
"<NAME>, et al. \"Show, attend and tell: Neural image caption generation with visual",
"state Ref: <NAME>, et al. \"Show, attend and tell: Neural image caption generation",
"nn.Linear(self.H,self.H,bias=True ) self.init_Wc1 = nn.Linear(self.D,self.H,bias=True ) self.init_Wc2 = nn.Linear(self.H,self.H,bias=True ) self.init_tanh = nn.Tanh()",
"# Prediction container if self.training: pred = torch.zeros([sequence_len,batch_size, n_out]).to( torch.device('cuda:0') ) map_ =",
"else : xt = sequence[0].unsqueeze(0) # Inicialize hidden state and cell state #",
"* alpha # [batch,L,D]x[batch,L,1] = [batch,L,D] visual = visual.reshape(n_visual,self.R) # [batch,R] visual =",
"xt = sequence[0] else : xt = sequence[0].unsqueeze(0) # Inicialize hidden state and",
"self.init_Wh2 = nn.Linear(self.H,self.H,bias=True ) self.init_Wc1 = nn.Linear(self.D,self.H,bias=True ) self.init_Wc2 = nn.Linear(self.H,self.H,bias=True ) self.init_tanh",
"= sequence[0] # Input to inicialize LSTM else : xt = sequence[0].unsqueeze(0) ht,ct",
"= self.R, hidden_size = self.H, num_layers = 1) self.init_Wh = nn.Linear(LowLevelDim,self.H,bias=True ) self.init_Wc",
"= None # hc,ha,hb = (None,None,None) # Sequence loop n_range = self.sequence_len if",
"_,(hidden,cell) = self.lstm(visual,(hidden,cell)) # Output vis_[k] = visual # [1,batch,R] alp_[k] = alpha.squeeze()",
"# [batch,H] hidden = torch.stack([hidden1,hidden2], dim=0).contiguous() # [2,batch,H] cell = torch.stack([ cell1, cell2],",
",batch,H] # * cell ~ [ layers ,batch,H] _,(hidden,cell) = self.lstm(visual,(hidden,cell)) # Control",
"n_hidden # 1024 # hidden_size self.M = n_hidden # 1024 # hidden_size self.sequence_len",
"G \"\"\" Basic Decoder Module -------------------- Ref: <NAME>., & <NAME>. (2017). \"Interpretable learning",
"self.init_Wc2 = nn.Linear(self.H,self.H,bias=True ) self.init_tanh = nn.Tanh() # Initialization torch.nn.init.xavier_uniform_(self.init_Wh1.weight) torch.nn.init.xavier_uniform_(self.init_Wh2.weight) torch.nn.init.xavier_uniform_(self.init_Wc1.weight) torch.nn.init.xavier_uniform_(self.init_Wc2.weight)",
"= torch.zeros([self.batch_size,self.H]).to( torch.device('cuda:0') ) else: action,atten = (None,None) # Sequence loop n_range =",
"map[k] = alpha.squeeze() if self.training: self.pred = self.pred.transpose(0,1).contiguous().view(batch_size*sequence_len, n_out) self. map = self.",
") else: action,atten = (None,None) # Sequence loop n_range = self.sequence_len if self.training",
"torch.zeros([self.batch_size,self.H]).to( torch.device('cuda:0') ) else: hc = None # hc,ha,hb = (None,None,None) # Sequence",
"= nn.LSTM( input_size=self.R, hidden_size=self.H, num_layers=2 ) self.init_Wh1 = nn.Linear(self.D,self.H,bias=True ) self.init_Wh2 = nn.Linear(self.H,self.H,bias=True",
"= hidden[0].unsqueeze(0) # [1,batch,H] if self.study: hc[k] = hidden[0].squeeze() if self.training: vis_ =",
": st = torch.cuda.FloatTensor( 1,self.n_task,self.S).uniform_() # Study if self.study: α,β,F = list(),list(),list() else",
"Output container self.pred = torch.zeros([self.batch_size,self.n_out]) self. map = torch.zeros([self.batch_size,self. L ]) # Declare",
"study if self.study: α = torch.stack(α, dim=0) β = torch.stack(β, dim=0) F =",
"self.init_tanh( cell1 ) # [batch,H] cell2 = self.init_Wc2 ( cell1 ) # [batch,H]*[H,H]",
"= self.initializeLSTM(xt) # Prediction container if self.training: vis_ = torch.zeros([sequence_len,batch_size,self.R]).to( torch.device('cuda:0') ) alp_",
"self.study = False # Declare layers self.attn = AttentionNet self.lstm = nn.LSTM( input_size",
"\"Interpretable learning for self-driving cars by visualizing causal attention\". In Proceedings of the",
"= self.lstm(visual,(hidden,cell)) # Output vis_[k] = visual # [1,batch,R] alp_[k] = alpha.squeeze() #",
"[ layers ,batch,H] _,(hidden,cell) = self.lstm(visual,(hidden,cell)) # Control pred[k] = self.ctrl(visual, hidden[0].unsqueeze(0)) map_[k]",
"[ 1 , 4 ] # Spatial Attention xt, αt = self.SpatialAttn(ηt,st) xt",
"int(n_hidden/4) # input LSTM 256 512 self.S = n_state self.n_task = n_task self.sequence_len",
"if self.training: xt = sequence[0] # Input to inicialize LSTM else : xt",
"H, W) shape # Data if self.training: sequence = feature.view(batch_size,sequence_len,C,H,W).transpose(0,1) # [sequence,batch, ...]",
"512 self.S = n_state self.n_task = n_task self.sequence_len = 20 # Attention self.HighEncoder",
"= self.attn(xt,hidden)# [batch,L,1] visual = xt * alpha # [batch,L,D]x[batch,L,1] = [batch,L,D] visual",
"[batch,H] hidden2 = self.init_Wh2 (hidden1) # [batch,H]*[H,H] -> [batch,H] hidden2 = self.init_tanh(hidden2) #",
"= nn.Linear(self.D,self.H,bias=True ) self.init_Wh2 = nn.Linear(self.H,self.H,bias=True ) self.init_Wc1 = nn.Linear(self.D,self.H,bias=True ) self.init_Wc2 =",
"5760 self.H = n_hidden # 512 self.M = n_hidden # 512 self.sequence_len =",
"self.initializeLSTM(xt) # Prediction container if self.training: self.pred = self.pred.view(sequence_len,batch_size, n_out) self. map =",
"# * hidden ~ [1,batch,H] # * cell ~ [1,batch,H] if self.training: xt",
"[batch,H] hidden = torch.stack([hidden1,hidden2], dim=0).contiguous() # [2,batch,H] cell = torch.stack([ cell1, cell2], dim=0).contiguous()",
"# [1,batch,H] if self.study: hc[k] = hidden[0].squeeze() if self.training: vis_ = vis_.transpose(0,1).contiguous().view(batch_size*sequence_len,self.R) alp_",
"= map_.transpose(0,1).contiguous().view(batch_size*sequence_len,self.L) # Return return pred, map_, {'action': action, 'attention': atten} \"\"\" TVA",
"ht_ = ht_.transpose(0,1).reshape(batch_size*sequence_len, self.H) # Compile study if self.study: α = torch.stack(α, dim=0)",
"if self.training else batch_size n_visual = batch_size if self.training else 1 for k",
"return hidden.contiguous(),cell.contiguous() \"\"\" Forward - eta [batch,channel,high,width] \"\"\" def forward(self,feature,command): # Parameters sequence_len",
"* cell ~ [ layers ,batch,H] _,(hidden,cell) = self.lstm(visual,(hidden,cell)) # Output vis_[k] =",
"super(CatDecoder, self).__init__() self.study = study # Parameters self.H = n_hidden # output LSTM",
"[1,batch,H] * Output: alpha [batch,L,1] \"\"\" class BasicDecoder(nn.Module): \"\"\" Constructor \"\"\" def __init__(self,AttentionNet,ControlNet,cube_size,n_hidden):",
"# * cell ~ [1,batch,H] if self.training: xt = sequence[0] # Input to",
"= nn.AdaptiveAvgPool2d((1, 1)) self.avgpool2 = nn.AdaptiveAvgPool2d((1, 1)) self.normSpa = nn.BatchNorm2d(LowLevelDim) self.ReLU = nn.ReLU()",
"[1,batch,R] # LSTM # * yt ~ [sequence,batch,H] # * hidden ~ [",
"Batch of Tensor Images is a tensor of (B, C, H, W) shape",
"# [batch, 4 ] else : cm = cmd[k].unsqueeze(0) # [ 1 ,",
"cube_size[2] # 64 self.L = cube_size[0]*cube_size[1] # 90 self.R = self.L*self.D # 5760",
"num_layers = 1) self.init_Wh = nn.Linear(LowLevelDim,self.H,bias=True ) self.init_Wc = nn.Linear(LowLevelDim,self.H,bias=True ) self.init_tanh =",
"torch.zeros([self.batch_size,self.H]).to( torch.device('cuda:0') ) else: action,atten = (None,None) # Sequence loop n_range = self.sequence_len",
"ht_.transpose(0,1).reshape(batch_size*sequence_len, self.H) # Compile study if self.study: α = torch.stack(α, dim=0) β =",
"= torch.zeros([sequence_len,batch_size,self.H]).to( torch.device('cuda:0') ) else: vis_ = torch.zeros([batch_size,self.R]).to( torch.device('cuda:0') ) alp_ = torch.zeros([batch_size,self.L]).to(",
"if self.training else batch_size for k in range(n_range): # One time if self.training:",
"rt = torch.flatten(rt , 1) rt = rt.unsqueeze(0) # LSTM # * yt",
"visual attention.\" International conference on machine learning. 2015. * Input: feature [batch,L,D] *",
") # [batch,H] cell2 = self.init_Wc2 ( cell1 ) # [batch,H]*[H,H] -> [batch,H]",
",L,D] if self.training: cm = cmd[k] # [batch, 4 ] else : cm",
"map_ = torch.zeros([batch_size,self.L]).to( torch.device('cuda:0') ) # Study rountime if self.study: action = torch.zeros([self.batch_size,self.H]).to(",
"else : xt = sequence[k].unsqueeze(0) # [ 1 ,L,D] # Visual Attention alpha",
"return hidden,cell \"\"\" Forward \"\"\" def forward(self,feature): # Parameters sequence_len = self.sequence_len n_out",
"n_visual = batch_size if self.training else 1 for k in range(n_range): # One",
"# Mean features feature = torch.mean(feature,(2,3)) # [batch,D,h,w] -> [batch,D] hidden = self.init_Wh(feature)",
"= vis_.transpose(0,1).contiguous().view(batch_size*sequence_len,self.R) alp_ = alp_.transpose(0,1).contiguous().view(batch_size*sequence_len,self.L) bet_ = bet_.transpose(0,1).contiguous().view(batch_size*sequence_len,self.D) hdd_ = hdd_.transpose(0,1).contiguous().view(batch_size*sequence_len,self.H) return vis_,",
"# Visual Attention alpha,beta = self.attn(xt,hidden) # [batch,L,1] # Spatial spatial = xt",
"sequence[0].unsqueeze(0) # Inicialize hidden state and cell state # * hidden ~ [1,batch,H]",
"batch_size for k in range(n_range): # One time if self.training: ηt = sequence[k]",
"on machine learning. 2015. * Input: feature [batch,D,h,w] * Output: hidden [1,batch,H] cell",
"Xu, Kelvin, et al. \"Show, attend and tell: Neural image caption generation with",
") self.init_Wc1 = nn.Linear(self.D,self.H,bias=True ) self.init_Wc2 = nn.Linear(self.H,self.H,bias=True ) self.init_tanh = nn.Tanh() #",
"self.init_tanh = nn.Tanh() self.avgpool1 = nn.AdaptiveAvgPool2d((1, 1)) self.avgpool2 = nn.AdaptiveAvgPool2d((1, 1)) self.normSpa =",
"nn.BatchNorm2d(LowLevelDim) self.ReLU = nn.ReLU() # Initialization torch.nn.init.xavier_uniform_(self.dimReduction.weight) torch.nn.init.xavier_uniform_(self. init_Wh.weight) torch.nn.init.xavier_uniform_(self. init_Wc.weight) self.lstm.reset_parameters() \"\"\"",
"α.append(αt) β.append(βt) F.append(Ft) # Concatenate st_ = torch.stack(st_,dim=0) ht_ = torch.stack(ht_,dim=0) if self.training:",
"nn.Linear(self.D,self.H,bias=True ) self.init_Wc = nn.Linear(self.D,self.H,bias=True ) self.init_tanh = nn.Tanh() # Initialization torch.nn.init.xavier_uniform_(self.init_Wh.weight) torch.nn.init.xavier_uniform_(self.init_Wc.weight)",
"= self.L*self.D # 5760 # self.L*self.D self.H = n_hidden # 1024 # hidden_size",
"[1,batch,H] # * cell ~ [1,batch,H] hidden,cell = self.initializeLSTM(xt) # Prediction container if",
"[batch,H] hidden2 = self.init_tanh(hidden2) # [batch,H] cell1 = self.init_Wc1 (feature) # [batch,D]*[D,H] ->",
"xt = sequence[k].unsqueeze(0) # [ 1 ,L,D] # Visual Attention alpha = self.attn(xt,hidden)#",
"# [ 1 , 4 ] # Spatial Attention xt, αt = self.SpatialAttn(ηt,st)",
"# 512 self.sequence_len = 20 self.batch_size = 120 self.n_out = 3 self.study =",
"torch.nn.init.xavier_uniform_(self.init_Wc.weight) self.lstm.reset_parameters() \"\"\" Initialize LSTM: hidden state and cell state Ref: Xu, Kelvin,",
"xt = sequence[k].unsqueeze(0) # [ 1 ,L,D] # Visual Attention alpha,beta = self.attn(xt,hidden)",
"input_size = self.R, hidden_size = self.H, num_layers = 1) self.init_Wh = nn.Linear(LowLevelDim,self.H,bias=True )",
"= alpha.squeeze() if self.study: action[k] = hidden[0].squeeze() atten [k] = hidden[1].squeeze() if self.training:",
"= visual # [1,batch,R] alp_[k] = alpha.squeeze() # [1,batch,L] bet_[k] = beta.squeeze() #",
"= torch.zeros([sequence_len,batch_size,self.R]).to( torch.device('cuda:0') ) alp_ = torch.zeros([sequence_len,batch_size,self.L]).to( torch.device('cuda:0') ) bet_ = torch.zeros([sequence_len,batch_size,self.D]).to( torch.device('cuda:0')",
"F.append(Ft) # Concatenate st_ = torch.stack(st_,dim=0) ht_ = torch.stack(ht_,dim=0) if self.training: st_ =",
"torch.stack(α, dim=0) β = torch.stack(β, dim=0) F = torch.stack(F, dim=0) return st_, {'hidden':",
"Mean features feature = torch.mean(feature,1) # [batch,L,D] -> [batch,D] hidden1 = self.init_Wh1 (feature)",
"Dual Decoder Module ------------------- * Input: feature [batch,L,D] hidden [1,batch,H] * Output: alpha",
") self.init_Wh1 = nn.Linear(self.D,self.H,bias=True ) self.init_Wh2 = nn.Linear(self.H,self.H,bias=True ) self.init_Wc1 = nn.Linear(self.D,self.H,bias=True )",
"Constructor \"\"\" def __init__(self,AttentionNet,ControlNet,cube_size,n_hidden): super(BasicDecoder, self).__init__() # Parameters self.D = cube_size[2] # 64",
"tensor of (B, C, H, W) shape # Data if self.training: sequence =",
"cm = cmd[k] # [batch, 4 ] else : cm = cmd[k].unsqueeze(0) #",
"class TVADecoder(nn.Module): \"\"\" Constructor \"\"\" def __init__(self,AttentionNet,cube_size,n_hidden): super(TVADecoder, self).__init__() # Parameters self.D =",
"= sequence[k].unsqueeze(0) # [ 1 ,L,D] # Visual Attention alpha = self.attn(xt,hidden)# [batch,L,1]",
"self.lstm.reset_parameters() \"\"\" Initialize LSTM: hidden state and cell state Ref: Xu, Kelvin, et",
"# [1,batch,D] hdd_[k] = hidden[0].unsqueeze(0) # [1,batch,H] if self.study: hc[k] = hidden[0].squeeze() if",
"self).__init__() # Parameters self.D = cube_size[2] # 64 # cube_size[0] self.L = cube_size[0]*cube_size[1]",
"torch.nn.init.xavier_uniform_(self.init_Wh.weight) torch.nn.init.xavier_uniform_(self.init_Wc.weight) self.lstm.reset_parameters() \"\"\" Initialize LSTM: hidden state and cell state Ref: <NAME>,",
"(pp. 2942-2950). * Input: feature [batch,L,D] hidden [1,batch,H] * Output: alpha [batch,L,1] \"\"\"",
"rt = self.dimReduction(zt) rt = self. avgpool2(rt) rt = torch.flatten(rt , 1) rt",
"512 self.sequence_len = 20 self.batch_size = 120 self.n_out = 3 self.study = False",
"# * cell ~ [ layers ,batch,H] _,(hidden,cell) = self.lstm(visual,(hidden,cell)) # Control pred[k]",
"# ------------------------------------------------------------------------------------------------ # # # ------------------------------------------------------------------------------------------------ class CatDecoder(nn.Module): \"\"\" Constructor \"\"\" def __init__(self,",
"Mean features feature = torch.mean(feature,1) # [batch,L,D] -> [batch,D] hidden = self.init_Wh(feature) #",
"cell state Ref: <NAME>, et al. \"Show, attend and tell: Neural image caption",
"self.avgpool1( zt) _zt = torch.flatten(_zt, 1) st, βt, Ft = self.FeatureAttn(_zt,ht[0],cm) # [batch,S]",
", 1) rt = rt.unsqueeze(0) # LSTM # * yt ~ [sequence,batch,H] #",
"= torch.stack(α, dim=0) β = torch.stack(β, dim=0) F = torch.stack(F, dim=0) return st_,",
"study # Parameters self.H = n_hidden # output LSTM 1024 2048 self.R =",
"cell ~ [1,batch,H] if self.training: xt = sequence[0] # Input to inicialize LSTM",
"= AttentionNet self.ctrl = ControlNet self.lstm = nn.LSTM( input_size = self.R, hidden_size =",
"= self.HighEncoder(xt) # Feature-based attention # s[t] = f(z[t],h[t-1]) _zt = self.avgpool1( zt)",
"pred = torch.zeros([batch_size, n_out]).to( torch.device('cuda:0') ) map_ = torch.zeros([batch_size,self.L]).to( torch.device('cuda:0') ) # Study",
"self.training: sequence = feature.view(batch_size,sequence_len,C,H,W).transpose(0,1) # [sequence,batch, ...] else : sequence = feature #",
"= torch.mean(feature,1) # [batch,L,D] -> [batch,D] hidden = self.init_Wh(feature) # [batch,D]*[D,H] -> [batch,H]",
"\"\"\" def __init__(self,AttentionNet,ControlNet,cube_size,n_hidden): super(DualDecoder, self).__init__() # Parameters self.D = cube_size[2] # 64 #",
"Module ------------------- * Input: feature [batch,L,D] hidden [1,batch,H] * Output: alpha [batch,L,1] \"\"\"",
"xt = self.Gate(ηt,xt) # High-level encoder zt = self.HighEncoder(xt) # Feature-based attention #",
"[1,batch,H] * Output: alpha [batch,L,1] \"\"\" class TVADecoder(nn.Module): \"\"\" Constructor \"\"\" def __init__(self,AttentionNet,cube_size,n_hidden):",
"# [2,batch,H] # (h,c) ~ [num_layers, batch, hidden_size] return hidden,cell \"\"\" Forward \"\"\"",
"------------------------------------------------------------------------------------------------ class CatDecoder(nn.Module): \"\"\" Constructor \"\"\" def __init__(self, HighEncoderNet, SpatialNet, FeatureNet, CommandNet, LowLevelDim=128,",
"self.sequence_len if self.training else batch_size for k in range(n_range): # One time if",
"~ [ layers ,batch,H] # * cell ~ [ layers ,batch,H] _,(ht,ct)= self.lstm(rt,(ht,ct))",
"self.init_Wc1 (feature) # [batch,D]*[D,H] -> [batch,H] cell1 = self.init_tanh( cell1 ) # [batch,H]",
"map_ = map_.transpose(0,1).contiguous().view(batch_size*sequence_len,self.L) # Return return pred, map_, {'action': action, 'attention': atten} \"\"\"",
"feature # [batch,L,D] # Input to inicialize LSTM if self.training: xt = sequence[0]",
"20 self.batch_size = 120 self.n_out = 3 # Output container self.pred = torch.zeros([self.batch_size,self.n_out])",
"self.init_Wh1 (feature) # [batch,D]*[D,H] -> [batch,H] hidden1 = self.init_tanh(hidden1) # [batch,H] hidden2 =",
"= sequence[0].unsqueeze(0) # Inicialize hidden state and cell state # * hidden ~",
"= AttentionNet self.lstm = nn.LSTM( input_size = self.R, hidden_size = self.H, num_layers =",
"[batch,n_task,S] ht_.append(ht.squeeze()) # [batch, H] # Study if self.study: α.append(αt) β.append(βt) F.append(Ft) #",
"# Parameters self.H = n_hidden # output LSTM 1024 2048 self.R = int(n_hidden/4)",
"hidden[0].unsqueeze(0)) map_[k] = alpha.squeeze() if self.study: action[k] = hidden[0].squeeze() atten [k] = hidden[1].squeeze()",
"] # Spatial Attention xt, αt = self.SpatialAttn(ηt,st) xt = self.Gate(ηt,xt) # High-level",
"State initialization if self.training: st = torch.cuda.FloatTensor(batch_size,self.n_task,self.S).uniform_() else : st = torch.cuda.FloatTensor( 1,self.n_task,self.S).uniform_()",
"eta [batch,channel,high,width] \"\"\" def forward(self,feature,command): # Parameters sequence_len = self.sequence_len if self.training: batch_size",
"self.M = n_hidden # 512 self.sequence_len = 20 self.batch_size = 120 self.n_out =",
"# # ------------------------------------------------------------------------------------------------ class CatDecoder(nn.Module): \"\"\" Constructor \"\"\" def __init__(self, HighEncoderNet, SpatialNet, FeatureNet,",
"self.HighEncoder = HighEncoderNet self.SpatialAttn = SpatialNet self.FeatureAttn = FeatureNet self. CmdDecoder = CommandNet",
"= n_hidden # 1024 # hidden_size self.M = n_hidden # 1024 # hidden_size",
"# Inicialize hidden state and cell state # * hidden ~ [1,batch,H] #",
"# [sequence,batch,L,D] else : sequence = feature # [batch,L,D] # Input to inicialize",
",batch,H] # * cell ~ [ layers ,batch,H] _,(hidden,cell) = self.lstm(visual,(hidden,cell)) # Output",
",batch,H] _,(hidden,cell) = self.lstm(visual,(hidden,cell)) # Output vis_[k] = visual # [1,batch,R] alp_[k] =",
"torch.mean(feature,1) # [batch,L,D] -> [batch,D] hidden = self.init_Wh(feature) # [batch,D]*[D,H] -> [batch,H] hidden",
"_zt = self.avgpool1( zt) _zt = torch.flatten(_zt, 1) st, βt, Ft = self.FeatureAttn(_zt,ht[0],cm)",
"Parameters self.D = cube_size[2] # 64 self.L = cube_size[0]*cube_size[1] # 90 self.R =",
"ηt = sequence[k].unsqueeze(0) # [ 1 ,L,D] if self.training: cm = cmd[k] #",
"container st_,ht_ = list(),list() # State initialization if self.training: st = torch.cuda.FloatTensor(batch_size,self.n_task,self.S).uniform_() else",
"time if self.training: ηt = sequence[k] # [batch,L,D] else : ηt = sequence[k].unsqueeze(0)",
"else: action,atten = (None,None) # Sequence loop n_range = self.sequence_len if self.training else",
"= self.sequence_len if self.training: batch_size = int(feature.shape[0]/sequence_len) else : batch_size = feature.shape[0] _,C,H,W",
"range(n_range): # One time if self.training: ηt = sequence[k] # [batch,L,D] else :",
"cell state # * hidden ~ [1,batch,H] # * cell ~ [1,batch,H] if",
"__init__(self, HighEncoderNet, SpatialNet, FeatureNet, CommandNet, LowLevelDim=128, HighLevelDim=512, n_hidden=1024, n_state=64,n_task=3, study=False): super(CatDecoder, self).__init__() self.study",
"Parameters self.D = cube_size[2] # 64 # cube_size[0] self.L = cube_size[0]*cube_size[1] # 90",
"# LSTM # * yt ~ [sequence,batch,H] # * hidden ~ [ layers",
"In Proceedings of the IEEE international conference on computer vision (pp. 2942-2950). *",
"Spatial Attention xt, αt = self.SpatialAttn(ηt,st) xt = self.Gate(ηt,xt) # High-level encoder zt",
"cell ~ [1,batch,H] hidden,cell = self.initializeLSTM(xt) # Prediction container if self.training: self.pred =",
"self.H, num_layers = 1) self.init_Wh = nn.Linear(LowLevelDim,self.H,bias=True ) self.init_Wc = nn.Linear(LowLevelDim,self.H,bias=True ) self.init_tanh",
"torch.device('cuda:0') ) map_ = torch.zeros([sequence_len,batch_size,self.L]).to( torch.device('cuda:0') ) else: pred = torch.zeros([batch_size, n_out]).to( torch.device('cuda:0')",
"W) shape # Data if self.training: sequence = feature.view(batch_size,sequence_len,C,H,W).transpose(0,1) # [sequence,batch, ...] else",
"-> [batch,H] cell = self.init_tanh(cell) # [batch,H] cell = cell.unsqueeze(0) # [1,batch,H] #",
"self.training: vis_ = vis_.transpose(0,1).contiguous().view(batch_size*sequence_len,self.R) alp_ = alp_.transpose(0,1).contiguous().view(batch_size*sequence_len,self.L) bet_ = bet_.transpose(0,1).contiguous().view(batch_size*sequence_len,self.D) hdd_ = hdd_.transpose(0,1).contiguous().view(batch_size*sequence_len,self.H)",
"# Output self.dimReduction = nn.Conv2d(HighLevelDim,self.R, kernel_size=1, bias=False) self.lstm = nn.LSTM( input_size = self.R,",
"else : batch_size = feature.shape[0] # Data if self.training: sequence = feature.view(batch_size,sequence_len,self.L,self.D).transpose_(0,1) #",
"hidden[1].squeeze() if self.training: pred = pred.transpose(0,1).contiguous().view(batch_size*sequence_len, n_out) map_ = map_.transpose(0,1).contiguous().view(batch_size*sequence_len,self.L) # Return return",
"90 self.R = self.L*self.D # 5760 self.H = n_hidden # 512 self.M =",
"Control self.pred[k] = self.ctrl(visual, hidden, training=self.training) self. map[k] = alpha.squeeze() if self.training: self.pred",
"self.L*self.D # 5760 # self.L*self.D self.H = n_hidden # 1024 # hidden_size self.M",
"= self.ctrl(visual, hidden, training=self.training) self. map[k] = alpha.squeeze() if self.training: self.pred = self.pred.transpose(0,1).contiguous().view(batch_size*sequence_len,",
"nn.Tanh() # Initialization torch.nn.init.xavier_uniform_(self.init_Wh.weight) torch.nn.init.xavier_uniform_(self.init_Wc.weight) self.lstm.reset_parameters() \"\"\" Initialize LSTM: hidden state and cell",
"# [batch,L,D] -> [batch,D] hidden = self.init_Wh(feature) # [batch,D]*[D,H] -> [batch,H] hidden =",
"else : st = torch.cuda.FloatTensor( 1,self.n_task,self.S).uniform_() # Study if self.study: α,β,F = list(),list(),list()",
"= cell.unsqueeze(0) # [1,batch,H] # (h,c) ~ [num_layers, batch, hidden_size] return hidden.contiguous(),cell.contiguous() \"\"\"",
"(h,c) ~ [num_layers, batch, hidden_size] return hidden,cell \"\"\" Forward \"\"\" def forward(self,feature): #",
") else: pred = torch.zeros([batch_size, n_out]).to( torch.device('cuda:0') ) map_ = torch.zeros([batch_size,self.L]).to( torch.device('cuda:0') )",
"vis_ = torch.zeros([sequence_len,batch_size,self.R]).to( torch.device('cuda:0') ) alp_ = torch.zeros([sequence_len,batch_size,self.L]).to( torch.device('cuda:0') ) bet_ = torch.zeros([sequence_len,batch_size,self.D]).to(",
"sequence[k] # [batch,L,D] else : ηt = sequence[k].unsqueeze(0) # [ 1 ,L,D] if",
"vis_ = torch.zeros([batch_size,self.R]).to( torch.device('cuda:0') ) alp_ = torch.zeros([batch_size,self.L]).to( torch.device('cuda:0') ) bet_ = torch.zeros([batch_size,self.D]).to(",
"------------------- * Input: feature [batch,L,D] hidden [1,batch,H] * Output: alpha [batch,L,1] \"\"\" class",
"if self.training: sequence = feature.view(batch_size,sequence_len,C,H,W).transpose(0,1) # [sequence,batch, ...] else : sequence = feature",
"self).__init__() self.study = study # Parameters self.H = n_hidden # output LSTM 1024",
") alp_ = torch.zeros([batch_size,self.L]).to( torch.device('cuda:0') ) bet_ = torch.zeros([batch_size,self.D]).to( torch.device('cuda:0') ) hdd_ =",
"# Spatial spatial = xt * alpha # [batch,L,D]x[batch,L,1] = [batch,L,D] visual =",
"torch.nn.init.xavier_uniform_(self.init_Wc1.weight) torch.nn.init.xavier_uniform_(self.init_Wc2.weight) self.lstm.reset_parameters() \"\"\" Initialize LSTM: hidden state and cell state Ref: <NAME>,",
"attention\". In Proceedings of the IEEE international conference on computer vision (pp. 2942-2950).",
"\"\"\" def __init__(self,AttentionNet,ControlNet,cube_size,n_hidden): super(BasicDecoder, self).__init__() # Parameters self.D = cube_size[2] # 64 self.L",
"rountime if self.study: action = torch.zeros([self.batch_size,self.H]).to( torch.device('cuda:0') ) atten = torch.zeros([self.batch_size,self.H]).to( torch.device('cuda:0') )",
"action[k] = hidden[0].squeeze() atten [k] = hidden[1].squeeze() if self.training: pred = pred.transpose(0,1).contiguous().view(batch_size*sequence_len, n_out)",
"if self.training: self.pred = self.pred.transpose(0,1).contiguous().view(batch_size*sequence_len, n_out) self. map = self. map.transpose(0,1).contiguous().view(batch_size*sequence_len,self.L) return self.pred,",
"bet_ = torch.zeros([sequence_len,batch_size,self.D]).to( torch.device('cuda:0') ) hdd_ = torch.zeros([sequence_len,batch_size,self.H]).to( torch.device('cuda:0') ) else: vis_ =",
"Input: feature [batch,L,D] hidden [1,batch,H] * Output: alpha [batch,L,1] \"\"\" class BasicDecoder(nn.Module): \"\"\"",
"\"\"\" Basic Decoder Module -------------------- Ref: <NAME>., & <NAME>. (2017). \"Interpretable learning for",
"= self.CmdDecoder(command) if self.training: cmd = cmd.view(batch_size,sequence_len,-1).transpose(0,1) # [sequence,batch,4] # Prediction container st_,ht_",
"and cell state Ref: Xu, Kelvin, et al. \"Show, attend and tell: Neural",
"learning for self-driving cars by visualizing causal attention\". In Proceedings of the IEEE",
"with visual attention.\" International conference on machine learning. 2015. * Input: feature [batch,L,D]",
"if self.study: hc[k] = hidden[0].squeeze() if self.training: vis_ = vis_.transpose(0,1).contiguous().view(batch_size*sequence_len,self.R) alp_ = alp_.transpose(0,1).contiguous().view(batch_size*sequence_len,self.L)",
"xt = sequence[0].unsqueeze(0) ht,ct = self.initializeLSTM(xt) # Command decoder cmd = self.CmdDecoder(command) if",
"cell ~ [ layers ,batch,H] _,(hidden,cell) = self.lstm(visual,(hidden,cell)) # Output vis_[k] = visual",
"visual attention.\" International conference on machine learning. 2015. * Input: feature [batch,D,h,w] *",
"# Parameters self.D = cube_size[2] # 64 # cube_size[0] self.L = cube_size[0]*cube_size[1] #",
"hc[k] = hidden[0].squeeze() if self.training: vis_ = vis_.transpose(0,1).contiguous().view(batch_size*sequence_len,self.R) alp_ = alp_.transpose(0,1).contiguous().view(batch_size*sequence_len,self.L) bet_ =",
"= torch.zeros([sequence_len,batch_size,self.D]).to( torch.device('cuda:0') ) hdd_ = torch.zeros([sequence_len,batch_size,self.H]).to( torch.device('cuda:0') ) else: vis_ = torch.zeros([batch_size,self.R]).to(",
"self.study = False # Declare layers self.attn = AttentionNet self.ctrl = ControlNet self.lstm",
"(2017). \"Interpretable learning for self-driving cars by visualizing causal attention\". In Proceedings of",
"self.training else batch_size n_visual = batch_size if self.training else 1 for k in",
"* cell ~ [1,batch,H] if self.training: xt = sequence[0] # Input to inicialize",
"Output: alpha [batch,L,1] \"\"\" class TVADecoder(nn.Module): \"\"\" Constructor \"\"\" def __init__(self,AttentionNet,cube_size,n_hidden): super(TVADecoder, self).__init__()",
"num_layers = 1) self.init_Wh = nn.Linear(self.D,self.H,bias=True ) self.init_Wc = nn.Linear(self.D,self.H,bias=True ) self.init_tanh =",
"self.normSpa = nn.BatchNorm2d(LowLevelDim) self.ReLU = nn.ReLU() # Initialization torch.nn.init.xavier_uniform_(self.dimReduction.weight) torch.nn.init.xavier_uniform_(self. init_Wh.weight) torch.nn.init.xavier_uniform_(self. init_Wc.weight)",
"= self.dimReduction(zt) rt = self. avgpool2(rt) rt = torch.flatten(rt , 1) rt =",
"self.training: self.pred = self.pred.view(sequence_len,batch_size, n_out) self. map = self. map.view(sequence_len,batch_size,self.L) # Sequence loop",
"hidden state and cell state Ref: Xu, Kelvin, et al. \"Show, attend and",
"torch.cuda.FloatTensor( 1,self.n_task,self.S).uniform_() # Study if self.study: α,β,F = list(),list(),list() else : α,β,F =",
"with torch.no_grad(): # Mean features feature = torch.mean(feature,1) # [batch,L,D] -> [batch,D] hidden1",
"if self.study: action = torch.zeros([self.batch_size,self.H]).to( torch.device('cuda:0') ) atten = torch.zeros([self.batch_size,self.H]).to( torch.device('cuda:0') ) else:",
"BasicDecoder(nn.Module): \"\"\" Constructor \"\"\" def __init__(self,AttentionNet,ControlNet,cube_size,n_hidden): super(BasicDecoder, self).__init__() # Parameters self.D = cube_size[2]",
"# Output vis_[k] = visual # [1,batch,R] alp_[k] = alpha.squeeze() # [1,batch,L] bet_[k]",
"= feature.view(batch_size,sequence_len,C,H,W).transpose(0,1) # [sequence,batch, ...] else : sequence = feature # [batch, ...]",
"nn.Linear(LowLevelDim,self.H,bias=True ) self.init_Wc = nn.Linear(LowLevelDim,self.H,bias=True ) self.init_tanh = nn.Tanh() self.avgpool1 = nn.AdaptiveAvgPool2d((1, 1))",
"self.L*self.D # 5760 self.H = n_hidden # 512 self.M = n_hidden # 512",
"layers ,batch,H] _,(hidden,cell) = self.lstm(visual,(hidden,cell)) # Control self.pred[k] = self.ctrl(visual, hidden, training=self.training) self.",
"generation with visual attention.\" International conference on machine learning. 2015. * Input: feature",
"hidden ~ [1,batch,H] # * cell ~ [1,batch,H] hidden,cell = self.initializeLSTM(xt) # Prediction",
"= self.H, num_layers = 1) self.init_Wh = nn.Linear(LowLevelDim,self.H,bias=True ) self.init_Wc = nn.Linear(LowLevelDim,self.H,bias=True )",
"Decoder Module ------------------- * Input: feature [batch,L,D] hidden [1,batch,H] * Output: alpha [batch,L,1]",
"[batch,S] # Dimension reduction to LSTM rt = self.dimReduction(zt) rt = self. avgpool2(rt)",
"= torch.zeros([self.batch_size,self. L ]) # Declare layers self.attn = AttentionNet self.ctrl = ControlNet",
"1 ,L,D] if self.training: cm = cmd[k] # [batch, 4 ] else :",
"self.training: batch_size = int(feature.shape[0]/sequence_len) else : batch_size = feature.shape[0] # Data if self.training:",
"* Input: feature [batch,L,D] * Output: hidden [1,batch,H] cell [1,batch,H] \"\"\" def initializeLSTM(self,feature):",
"Output: alpha [batch,L,1] \"\"\" class BasicDecoder(nn.Module): \"\"\" Constructor \"\"\" def __init__(self,AttentionNet,ControlNet,cube_size,n_hidden): super(BasicDecoder, self).__init__()",
"sequence[0] # Input to inicialize LSTM else : xt = sequence[0].unsqueeze(0) ht,ct =",
"the IEEE international conference on computer vision (pp. 2942-2950). * Input: feature [batch,L,D]",
") # Study rountime if self.study: hc = torch.zeros([self.batch_size,self.H]).to( torch.device('cuda:0') ) else: hc",
"else : sequence = feature # [batch, ...] # Inicialize hidden state and",
"[num_layers, batch, hidden_size] return hidden.contiguous(),cell.contiguous() \"\"\" Forward \"\"\" def forward(self,feature): # Parameters sequence_len",
"self.CmdDecoder(command) if self.training: cmd = cmd.view(batch_size,sequence_len,-1).transpose(0,1) # [sequence,batch,4] # Prediction container st_,ht_ =",
"Input to inicialize LSTM else : xt = sequence[0].unsqueeze(0) ht,ct = self.initializeLSTM(xt) #",
"feature.shape[0] # Data if self.training: sequence = feature.view(batch_size,sequence_len,self.L,self.D).transpose_(0,1) # [sequence,batch,L,D] else : sequence",
"self.batch_size = 120 self.n_out = 3 # Output container self.pred = torch.zeros([self.batch_size,self.n_out]) self.",
"# [ 1 ,L,D] if self.training: cm = cmd[k] # [batch, 4 ]",
"map = self. map.view(sequence_len,batch_size,self.L) # Sequence loop n_range = self.sequence_len if self.training else",
"Study if self.study: α.append(αt) β.append(βt) F.append(Ft) # Concatenate st_ = torch.stack(st_,dim=0) ht_ =",
"# [ 1 ,L,D] # Visual Attention alpha,beta = self.attn(xt,hidden) # [batch,L,1] #",
"self.H) # Compile study if self.study: α = torch.stack(α, dim=0) β = torch.stack(β,",
"= torch.zeros([batch_size,self.L]).to( torch.device('cuda:0') ) # Study rountime if self.study: action = torch.zeros([self.batch_size,self.H]).to( torch.device('cuda:0')",
"\"\"\" Initialize LSTM: hidden state and cell state Ref: <NAME>, et al. \"Show,",
"tell: Neural image caption generation with visual attention.\" International conference on machine learning.",
"\"\"\" Forward \"\"\" def forward(self,feature): # Parameters sequence_len = self.sequence_len if self.training: batch_size",
"= 120 self.n_out = 3 self.study = False # Declare layers self.attn =",
"= sequence[k].unsqueeze(0) # [ 1 ,L,D] if self.training: cm = cmd[k] # [batch,",
"[sequence,batch,H] # * hidden ~ [ layers ,batch,H] # * cell ~ [",
"# Output st_.append(st.squeeze()) # [batch,n_task,S] ht_.append(ht.squeeze()) # [batch, H] # Study if self.study:",
"= int(feature.shape[0]/sequence_len) else : batch_size = feature.shape[0] _,C,H,W = feature.shape # Batch of",
"cell2], dim=0).contiguous() # [2,batch,H] # (h,c) ~ [num_layers, batch, hidden_size] return hidden,cell \"\"\"",
"forward(self,feature,command): # Parameters sequence_len = self.sequence_len if self.training: batch_size = int(feature.shape[0]/sequence_len) else :",
"AttentionNet self.lstm = nn.LSTM( input_size = self.R, hidden_size = self.H, num_layers = 1)",
"feature.view(batch_size,sequence_len,self.L,self.D).transpose_(0,1) # [sequence,batch,L,D] else : sequence = feature # [batch,L,D] # Input to",
"# * cell ~ [ layers ,batch,H] _,(ht,ct)= self.lstm(rt,(ht,ct)) # Output st_.append(st.squeeze()) #",
"Mean features feature = torch.mean(feature,(2,3)) # [batch,D,h,w] -> [batch,D] hidden = self.init_Wh(feature) #",
"self.R, hidden_size = self.H, num_layers = 1) self.init_Wh = nn.Linear(LowLevelDim,self.H,bias=True ) self.init_Wc =",
"cell1 ) # [batch,H]*[H,H] -> [batch,H] cell2 = self.init_tanh( cell2 ) # [batch,H]",
"Ft = self.FeatureAttn(_zt,ht[0],cm) # [batch,S] # Dimension reduction to LSTM rt = self.dimReduction(zt)",
"sequence = feature # [batch, ...] # Inicialize hidden state and cell state",
"self.init_Wh1 = nn.Linear(self.D,self.H,bias=True ) self.init_Wh2 = nn.Linear(self.H,self.H,bias=True ) self.init_Wc1 = nn.Linear(self.D,self.H,bias=True ) self.init_Wc2",
"self.lstm(rt,(ht,ct)) # Output st_.append(st.squeeze()) # [batch,n_task,S] ht_.append(ht.squeeze()) # [batch, H] # Study if",
"cmd[k].unsqueeze(0) # [ 1 , 4 ] # Spatial Attention xt, αt =",
"= bet_.transpose(0,1).contiguous().view(batch_size*sequence_len,self.D) hdd_ = hdd_.transpose(0,1).contiguous().view(batch_size*sequence_len,self.H) return vis_, hdd_, {'alpha': alp_, 'beta': bet_}, {'control':",
"Ref: <NAME>, et al. \"Show, attend and tell: Neural image caption generation with",
"False # Declare layers self.attn = AttentionNet self.lstm = nn.LSTM( input_size = self.R,",
"= 3 # Output container self.pred = torch.zeros([self.batch_size,self.n_out]) self. map = torch.zeros([self.batch_size,self. L",
"[num_layers, batch, hidden_size] return hidden,cell \"\"\" Forward \"\"\" def forward(self,feature): # Parameters sequence_len",
"TVADecoder(nn.Module): \"\"\" Constructor \"\"\" def __init__(self,AttentionNet,cube_size,n_hidden): super(TVADecoder, self).__init__() # Parameters self.D = cube_size[2]",
"# Prediction container if self.training: vis_ = torch.zeros([sequence_len,batch_size,self.R]).to( torch.device('cuda:0') ) alp_ = torch.zeros([sequence_len,batch_size,self.L]).to(",
"C, H, W) shape # Data if self.training: sequence = feature.view(batch_size,sequence_len,C,H,W).transpose(0,1) # [sequence,batch,",
"# (h,c) ~ [num_layers, batch, hidden_size] return hidden.contiguous(),cell.contiguous() \"\"\" Forward \"\"\" def forward(self,feature):",
"[batch,D]*[D,H] -> [batch,H] cell1 = self.init_tanh( cell1 ) # [batch,H] cell2 = self.init_Wc2",
"self.ctrl = ControlNet self.lstm = nn.LSTM( input_size=self.R, hidden_size=self.H, num_layers=2 ) self.init_Wh1 = nn.Linear(self.D,self.H,bias=True",
"map_, {'action': action, 'attention': atten} \"\"\" TVA Decoder Module ------------------ Ref: <NAME>., &",
"* cell ~ [1,batch,H] hidden,cell = self.initializeLSTM(xt) # Prediction container if self.training: pred",
"= self.Gate(ηt,xt) # High-level encoder zt = self.HighEncoder(xt) # Feature-based attention # s[t]",
"torch.device('cuda:0') ) bet_ = torch.zeros([batch_size,self.D]).to( torch.device('cuda:0') ) hdd_ = torch.zeros([batch_size,self.H]).to( torch.device('cuda:0') ) #",
"# Concatenate st_ = torch.stack(st_,dim=0) ht_ = torch.stack(ht_,dim=0) if self.training: st_ = st_.transpose(0,1).reshape(batch_size*sequence_len,self.n_task,self.S)",
"self.M = n_hidden # 1024 # hidden_size self.sequence_len = 20 self.batch_size = 120",
"action, 'attention': atten} \"\"\" TVA Decoder Module ------------------ Ref: <NAME>., & <NAME>. (2017).",
", 4 ] # Spatial Attention xt, αt = self.SpatialAttn(ηt,st) xt = self.Gate(ηt,xt)",
"-> [batch,D] hidden = self.init_Wh(feature) # [batch,D]*[D,H] -> [batch,H] hidden = self.init_tanh(hidden) #",
"self.init_Wc = nn.Linear(LowLevelDim,self.H,bias=True ) self.init_tanh = nn.Tanh() self.avgpool1 = nn.AdaptiveAvgPool2d((1, 1)) self.avgpool2 =",
"# ------------------------------------------------------------------------------------------------ class CatDecoder(nn.Module): \"\"\" Constructor \"\"\" def __init__(self, HighEncoderNet, SpatialNet, FeatureNet, CommandNet,",
"self.H = n_hidden # 1024 # hidden_size self.M = n_hidden # 1024 #",
"feature = torch.mean(feature,1) # [batch,L,D] -> [batch,D] hidden1 = self.init_Wh1 (feature) # [batch,D]*[D,H]",
"cell ~ [1,batch,H] hidden,cell = self.initializeLSTM(xt) # Prediction container if self.training: pred =",
"visual = xt * alpha # [batch,L,D]x[batch,L,1] = [batch,L,D] visual = visual.reshape(n_visual,self.R) #",
"\"\"\" TVA Decoder Module ------------------ Ref: <NAME>., & <NAME>. (2017). \"Interpretable learning for",
") hdd_ = torch.zeros([sequence_len,batch_size,self.H]).to( torch.device('cuda:0') ) else: vis_ = torch.zeros([batch_size,self.R]).to( torch.device('cuda:0') ) alp_",
"[batch,L,1] \"\"\" class DualDecoder(nn.Module): \"\"\" Constructor \"\"\" def __init__(self,AttentionNet,ControlNet,cube_size,n_hidden): super(DualDecoder, self).__init__() # Parameters",
"# Visual Attention alpha = self.attn(xt,hidden[1].unsqueeze(0))# [batch,L,1] visual = xt * alpha #",
"features feature = torch.mean(feature,(2,3)) # [batch,D,h,w] -> [batch,D] hidden = self.init_Wh(feature) # [batch,D]*[D,H]",
"High-level encoder zt = self.HighEncoder(xt) # Feature-based attention # s[t] = f(z[t],h[t-1]) _zt",
"xt, αt = self.SpatialAttn(ηt,st) xt = self.Gate(ηt,xt) # High-level encoder zt = self.HighEncoder(xt)",
"= int(n_hidden/4) # input LSTM 256 512 self.S = n_state self.n_task = n_task",
"~ [num_layers, batch, hidden_size] return hidden,cell \"\"\" Forward \"\"\" def forward(self,feature): # Parameters",
"\"\"\" def forward(self,feature,command): # Parameters sequence_len = self.sequence_len if self.training: batch_size = int(feature.shape[0]/sequence_len)",
"n_hidden # output LSTM 1024 2048 self.R = int(n_hidden/4) # input LSTM 256",
"[1,batch,H] # (h,c) ~ [num_layers, batch, hidden_size] return hidden.contiguous(),cell.contiguous() \"\"\" Forward - eta",
"# Initialization torch.nn.init.xavier_uniform_(self.init_Wh.weight) torch.nn.init.xavier_uniform_(self.init_Wc.weight) self.lstm.reset_parameters() \"\"\" Initialize LSTM: hidden state and cell state",
"self.init_tanh(hidden) # [batch,H] hidden = hidden.unsqueeze(0) # [1,batch,H] cell = self.init_Wc(feature) # [batch,D]*[D,H]",
"nn.Linear(self.D,self.H,bias=True ) self.init_tanh = nn.Tanh() # Initialization torch.nn.init.xavier_uniform_(self.init_Wh.weight) torch.nn.init.xavier_uniform_(self.init_Wc.weight) self.lstm.reset_parameters() \"\"\" Initialize LSTM:",
"n_out) self. map = self. map.view(sequence_len,batch_size,self.L) # Sequence loop n_range = self.sequence_len if",
"* cell ~ [ layers ,batch,H] _,(ht,ct)= self.lstm(rt,(ht,ct)) # Output st_.append(st.squeeze()) # [batch,n_task,S]",
"# [2,batch,H] cell = torch.stack([ cell1, cell2], dim=0).contiguous() # [2,batch,H] # (h,c) ~",
"= torch.zeros([batch_size,self.H]).to( torch.device('cuda:0') ) # Study rountime if self.study: hc = torch.zeros([self.batch_size,self.H]).to( torch.device('cuda:0')",
"layers ,batch,H] # * cell ~ [ layers ,batch,H] _,(hidden,cell) = self.lstm(visual,(hidden,cell)) #",
"3 self.study = False # Declare layers self.attn = AttentionNet self.lstm = nn.LSTM(",
"International conference on machine learning. 2015. * Input: feature [batch,D,h,w] * Output: hidden",
"in range(n_range): # One time if self.training: ηt = sequence[k] # [batch,L,D] else",
"* cell ~ [1,batch,H] hidden,cell = self.initializeLSTM(xt) # Prediction container if self.training: self.pred",
"range(n_range): # One time if self.training: xt = sequence[k] # [batch,L,D] else :",
"hdd_, {'alpha': alp_, 'beta': bet_}, {'control': hc} # ------------------------------------------------------------------------------------------------ # # # ------------------------------------------------------------------------------------------------",
"self.lstm = nn.LSTM( input_size = self.R, hidden_size = self.H, num_layers = 1) self.init_Wh",
") self.init_tanh = nn.Tanh() self.avgpool1 = nn.AdaptiveAvgPool2d((1, 1)) self.avgpool2 = nn.AdaptiveAvgPool2d((1, 1)) self.normSpa",
"= 20 # Attention self.HighEncoder = HighEncoderNet self.SpatialAttn = SpatialNet self.FeatureAttn = FeatureNet",
"= None, None, None # Sequence loop n_range = self.sequence_len if self.training else",
"Initialization torch.nn.init.xavier_uniform_(self.init_Wh1.weight) torch.nn.init.xavier_uniform_(self.init_Wh2.weight) torch.nn.init.xavier_uniform_(self.init_Wc1.weight) torch.nn.init.xavier_uniform_(self.init_Wc2.weight) self.lstm.reset_parameters() \"\"\" Initialize LSTM: hidden state and cell",
"atten [k] = hidden[1].squeeze() if self.training: pred = pred.transpose(0,1).contiguous().view(batch_size*sequence_len, n_out) map_ = map_.transpose(0,1).contiguous().view(batch_size*sequence_len,self.L)",
"hidden2 = self.init_tanh(hidden2) # [batch,H] cell1 = self.init_Wc1 (feature) # [batch,D]*[D,H] -> [batch,H]",
"def __init__(self,AttentionNet,ControlNet,cube_size,n_hidden): super(BasicDecoder, self).__init__() # Parameters self.D = cube_size[2] # 64 self.L =",
"xt = sequence[k] # [batch,L,D] else : xt = sequence[k].unsqueeze(0) # [ 1",
"= torch.zeros([self.batch_size,self.n_out]) self. map = torch.zeros([self.batch_size,self. L ]) # Declare layers self.attn =",
"nn.LSTM( input_size=self.R, hidden_size=self.H, num_layers=2 ) self.init_Wh1 = nn.Linear(self.D,self.H,bias=True ) self.init_Wh2 = nn.Linear(self.H,self.H,bias=True )",
"self.init_Wh(feature) # [batch,D]*[D,H] -> [batch,H] hidden = self.init_tanh(hidden) # [batch,H] hidden = hidden.unsqueeze(0)",
"hc = torch.zeros([self.batch_size,self.H]).to( torch.device('cuda:0') ) else: hc = None # hc,ha,hb = (None,None,None)",
"if self.study: action[k] = hidden[0].squeeze() atten [k] = hidden[1].squeeze() if self.training: pred =",
"alpha # [batch,L,D]x[batch,L,1] = [batch,L,D] visual = visual.reshape(n_visual,self.R) # [batch,R] visual = visual.unsqueeze(0)",
"feature [batch,L,D] hidden [1,batch,H] * Output: alpha [batch,L,1] \"\"\" class DualDecoder(nn.Module): \"\"\" Constructor",
"# 512 self.sequence_len = 20 self.batch_size = 120 self.n_out = 3 # Output",
": batch_size = feature.shape[0] # Data if self.training: sequence = feature.view(batch_size,sequence_len,self.L,self.D).transpose_(0,1) # [sequence,batch,L,D]",
"[1,batch,H] hidden,cell = self.initializeLSTM(xt) # Prediction container if self.training: vis_ = torch.zeros([sequence_len,batch_size,self.R]).to( torch.device('cuda:0')",
"encoder zt = self.HighEncoder(xt) # Feature-based attention # s[t] = f(z[t],h[t-1]) _zt =",
"layers ,batch,H] _,(hidden,cell) = self.lstm(visual,(hidden,cell)) # Control pred[k] = self.ctrl(visual, hidden[0].unsqueeze(0)) map_[k] =",
"= nn.Tanh() # Initialization torch.nn.init.xavier_uniform_(self.init_Wh1.weight) torch.nn.init.xavier_uniform_(self.init_Wh2.weight) torch.nn.init.xavier_uniform_(self.init_Wc1.weight) torch.nn.init.xavier_uniform_(self.init_Wc2.weight) self.lstm.reset_parameters() \"\"\" Initialize LSTM: hidden",
"cell ~ [ layers ,batch,H] _,(hidden,cell) = self.lstm(visual,(hidden,cell)) # Control pred[k] = self.ctrl(visual,",
"[batch,L,D] hidden [1,batch,H] * Output: alpha [batch,L,1] \"\"\" class TVADecoder(nn.Module): \"\"\" Constructor \"\"\"",
"# State initialization if self.training: st = torch.cuda.FloatTensor(batch_size,self.n_task,self.S).uniform_() else : st = torch.cuda.FloatTensor(",
"cell ~ [ layers ,batch,H] _,(ht,ct)= self.lstm(rt,(ht,ct)) # Output st_.append(st.squeeze()) # [batch,n_task,S] ht_.append(ht.squeeze())",
"Prediction container if self.training: self.pred = self.pred.view(sequence_len,batch_size, n_out) self. map = self. map.view(sequence_len,batch_size,self.L)",
"self.training: st_ = st_.transpose(0,1).reshape(batch_size*sequence_len,self.n_task,self.S) ht_ = ht_.transpose(0,1).reshape(batch_size*sequence_len, self.H) # Compile study if self.study:",
"= nn.BatchNorm2d(LowLevelDim) self.ReLU = nn.ReLU() # Initialization torch.nn.init.xavier_uniform_(self.dimReduction.weight) torch.nn.init.xavier_uniform_(self. init_Wh.weight) torch.nn.init.xavier_uniform_(self. init_Wc.weight) self.lstm.reset_parameters()",
"# Study if self.study: α,β,F = list(),list(),list() else : α,β,F = None, None,",
"[ layers ,batch,H] # * cell ~ [ layers ,batch,H] _,(ht,ct)= self.lstm(rt,(ht,ct)) #",
"sequence = feature.view(batch_size,sequence_len,C,H,W).transpose(0,1) # [sequence,batch, ...] else : sequence = feature # [batch,",
"Constructor \"\"\" def __init__(self,AttentionNet,ControlNet,cube_size,n_hidden): super(DualDecoder, self).__init__() # Parameters self.D = cube_size[2] # 64",
"as nn from IPython.core.debugger import set_trace import ImitationLearning.VisualAttention.network.Gate as G \"\"\" Basic Decoder",
"* hidden ~ [1,batch,H] # * cell ~ [1,batch,H] hidden,cell = self.initializeLSTM(xt) #",
"Prediction container if self.training: pred = torch.zeros([sequence_len,batch_size, n_out]).to( torch.device('cuda:0') ) map_ = torch.zeros([sequence_len,batch_size,self.L]).to(",
"= beta.squeeze() # [1,batch,D] hdd_[k] = hidden[0].unsqueeze(0) # [1,batch,H] if self.study: hc[k] =",
"# cube_size[1]*cube_size[2] self.R = self.L*self.D # 5760 # self.L*self.D self.H = n_hidden #",
"initialization if self.training: st = torch.cuda.FloatTensor(batch_size,self.n_task,self.S).uniform_() else : st = torch.cuda.FloatTensor( 1,self.n_task,self.S).uniform_() #",
"batch_size = feature.shape[0] # Data if self.training: sequence = feature.view(batch_size,sequence_len,self.L,self.D).transpose_(0,1) # [sequence,batch,L,D] else",
"self.training: batch_size = int(feature.shape[0]/sequence_len) else : batch_size = feature.shape[0] _,C,H,W = feature.shape #",
"= study # Parameters self.H = n_hidden # output LSTM 1024 2048 self.R",
"cell1 ) # [batch,H] cell2 = self.init_Wc2 ( cell1 ) # [batch,H]*[H,H] ->",
"# [batch,L,D] else : xt = sequence[k].unsqueeze(0) # [ 1 ,L,D] # Visual",
"# Declare layers self.attn = AttentionNet self.ctrl = ControlNet self.lstm = nn.LSTM( input_size",
"self.D = cube_size[2] # 64 self.L = cube_size[0]*cube_size[1] # 90 self.R = self.L*self.D",
"sequence_len = self.sequence_len n_out = self.n_out if self.training: batch_size = int(feature.shape[0]/sequence_len) else :",
"(feature) # [batch,D]*[D,H] -> [batch,H] hidden1 = self.init_tanh(hidden1) # [batch,H] hidden2 = self.init_Wh2",
"alpha [batch,L,1] \"\"\" class DualDecoder(nn.Module): \"\"\" Constructor \"\"\" def __init__(self,AttentionNet,ControlNet,cube_size,n_hidden): super(DualDecoder, self).__init__() #",
"[batch,L,D] # Input to inicialize LSTM if self.training: xt = sequence[0] else :",
"Initialize LSTM: hidden state and cell state Ref: <NAME>, et al. \"Show, attend",
",L,D] # Visual Attention alpha = self.attn(xt,hidden[1].unsqueeze(0))# [batch,L,1] visual = xt * alpha",
"as G \"\"\" Basic Decoder Module -------------------- Ref: <NAME>., & <NAME>. (2017). \"Interpretable",
"hc,ha,hb = (None,None,None) # Sequence loop n_range = self.sequence_len if self.training else batch_size",
"= rt.unsqueeze(0) # LSTM # * yt ~ [sequence,batch,H] # * hidden ~",
"self.L = cube_size[0]*cube_size[1] # 90 # cube_size[1]*cube_size[2] self.R = self.L*self.D # 5760 #",
"sequence = feature # [batch,L,D] # Input to inicialize LSTM if self.training: xt",
"torch.device('cuda:0') ) else: action,atten = (None,None) # Sequence loop n_range = self.sequence_len if",
"self.init_Wc1 = nn.Linear(self.D,self.H,bias=True ) self.init_Wc2 = nn.Linear(self.H,self.H,bias=True ) self.init_tanh = nn.Tanh() # Initialization",
"self.map \"\"\" Dual Decoder Module ------------------- * Input: feature [batch,L,D] hidden [1,batch,H] *",
"set_trace import ImitationLearning.VisualAttention.network.Gate as G \"\"\" Basic Decoder Module -------------------- Ref: <NAME>., &",
"if self.training: batch_size = int(feature.shape[0]/sequence_len) else : batch_size = feature.shape[0] # Data if",
"= self.FeatureAttn(_zt,ht[0],cm) # [batch,S] # Dimension reduction to LSTM rt = self.dimReduction(zt) rt",
"hidden state and cell state # * hidden ~ [1,batch,H] # * cell",
"# [batch,L,1] # Spatial spatial = xt * alpha # [batch,L,D]x[batch,L,1] = [batch,L,D]",
"self.init_tanh = nn.Tanh() # Initialization torch.nn.init.xavier_uniform_(self.init_Wh.weight) torch.nn.init.xavier_uniform_(self.init_Wc.weight) self.lstm.reset_parameters() \"\"\" Initialize LSTM: hidden state",
"hidden_size] return hidden.contiguous(),cell.contiguous() \"\"\" Forward - eta [batch,channel,high,width] \"\"\" def forward(self,feature,command): # Parameters",
"st_.transpose(0,1).reshape(batch_size*sequence_len,self.n_task,self.S) ht_ = ht_.transpose(0,1).reshape(batch_size*sequence_len, self.H) # Compile study if self.study: α = torch.stack(α,",
"1) self.init_Wh = nn.Linear(self.D,self.H,bias=True ) self.init_Wc = nn.Linear(self.D,self.H,bias=True ) self.init_tanh = nn.Tanh() #",
"alpha = self.attn(xt,hidden)# [batch,L,1] visual = xt * alpha # [batch,L,D]x[batch,L,1] = [batch,L,D]",
"= st_.transpose(0,1).reshape(batch_size*sequence_len,self.n_task,self.S) ht_ = ht_.transpose(0,1).reshape(batch_size*sequence_len, self.H) # Compile study if self.study: α =",
"[batch,H] cell = cell.unsqueeze(0) # [1,batch,H] # (h,c) ~ [num_layers, batch, hidden_size] return",
"= torch.zeros([batch_size, n_out]).to( torch.device('cuda:0') ) map_ = torch.zeros([batch_size,self.L]).to( torch.device('cuda:0') ) # Study rountime",
"__init__(self,AttentionNet,ControlNet,cube_size,n_hidden): super(DualDecoder, self).__init__() # Parameters self.D = cube_size[2] # 64 # cube_size[0] self.L",
"and cell state # * hidden ~ [1,batch,H] # * cell ~ [1,batch,H]",
"self.R = self.L*self.D # 5760 # self.L*self.D self.H = n_hidden # 1024 #",
"HighEncoderNet, SpatialNet, FeatureNet, CommandNet, LowLevelDim=128, HighLevelDim=512, n_hidden=1024, n_state=64,n_task=3, study=False): super(CatDecoder, self).__init__() self.study =",
"\"\"\" class TVADecoder(nn.Module): \"\"\" Constructor \"\"\" def __init__(self,AttentionNet,cube_size,n_hidden): super(TVADecoder, self).__init__() # Parameters self.D",
"Visual Attention alpha = self.attn(xt,hidden[1].unsqueeze(0))# [batch,L,1] visual = xt * alpha # [batch,L,D]x[batch,L,1]",
"s[t] = f(z[t],h[t-1]) _zt = self.avgpool1( zt) _zt = torch.flatten(_zt, 1) st, βt,",
"self.ctrl(visual, hidden, training=self.training) self. map[k] = alpha.squeeze() if self.training: self.pred = self.pred.transpose(0,1).contiguous().view(batch_size*sequence_len, n_out)",
"= AttentionNet self.ctrl = ControlNet self.lstm = nn.LSTM( input_size=self.R, hidden_size=self.H, num_layers=2 ) self.init_Wh1",
"(B, C, H, W) shape # Data if self.training: sequence = feature.view(batch_size,sequence_len,C,H,W).transpose(0,1) #",
"torch.nn.init.xavier_uniform_(self. init_Wc.weight) self.lstm.reset_parameters() \"\"\" Initialize LSTM: hidden state and cell state Ref: Xu,",
") atten = torch.zeros([self.batch_size,self.H]).to( torch.device('cuda:0') ) else: action,atten = (None,None) # Sequence loop",
"st, βt, Ft = self.FeatureAttn(_zt,ht[0],cm) # [batch,S] # Dimension reduction to LSTM rt",
"in range(n_range): # One time if self.training: xt = sequence[k] # [batch,L,D] else",
"alpha.squeeze() # [1,batch,L] bet_[k] = beta.squeeze() # [1,batch,D] hdd_[k] = hidden[0].unsqueeze(0) # [1,batch,H]",
"container if self.training: pred = torch.zeros([sequence_len,batch_size, n_out]).to( torch.device('cuda:0') ) map_ = torch.zeros([sequence_len,batch_size,self.L]).to( torch.device('cuda:0')",
"[batch,L,D] else : xt = sequence[k].unsqueeze(0) # [ 1 ,L,D] # Visual Attention",
"torch.no_grad(): # Mean features feature = torch.mean(feature,1) # [batch,L,D] -> [batch,D] hidden1 =",
"self.pred[k] = self.ctrl(visual, hidden, training=self.training) self. map[k] = alpha.squeeze() if self.training: self.pred =",
"Initialize LSTM: hidden state and cell state Ref: Xu, Kelvin, et al. \"Show,",
"sequence_len = self.sequence_len if self.training: batch_size = int(feature.shape[0]/sequence_len) else : batch_size = feature.shape[0]",
"inicialize LSTM if self.training: xt = sequence[0] else : xt = sequence[0].unsqueeze(0) #",
"self.training: ηt = sequence[k] # [batch,L,D] else : ηt = sequence[k].unsqueeze(0) # [",
"sequence[k].unsqueeze(0) # [ 1 ,L,D] if self.training: cm = cmd[k] # [batch, 4",
"Visual Attention alpha = self.attn(xt,hidden)# [batch,L,1] visual = xt * alpha # [batch,L,D]x[batch,L,1]",
"'beta': bet_}, {'control': hc} # ------------------------------------------------------------------------------------------------ # # # ------------------------------------------------------------------------------------------------ class CatDecoder(nn.Module): \"\"\"",
"Constructor \"\"\" def __init__(self,AttentionNet,cube_size,n_hidden): super(TVADecoder, self).__init__() # Parameters self.D = cube_size[2] # 64",
"\"Show, attend and tell: Neural image caption generation with visual attention.\" International conference",
"self.attn(xt,hidden)# [batch,L,1] visual = xt * alpha # [batch,L,D]x[batch,L,1] = [batch,L,D] visual =",
"nn.Tanh() # Initialization torch.nn.init.xavier_uniform_(self.init_Wh1.weight) torch.nn.init.xavier_uniform_(self.init_Wh2.weight) torch.nn.init.xavier_uniform_(self.init_Wc1.weight) torch.nn.init.xavier_uniform_(self.init_Wc2.weight) self.lstm.reset_parameters() \"\"\" Initialize LSTM: hidden state",
"= nn.Linear(LowLevelDim,self.H,bias=True ) self.init_tanh = nn.Tanh() self.avgpool1 = nn.AdaptiveAvgPool2d((1, 1)) self.avgpool2 = nn.AdaptiveAvgPool2d((1,",
"# output LSTM 1024 2048 self.R = int(n_hidden/4) # input LSTM 256 512",
"\"\"\" class DualDecoder(nn.Module): \"\"\" Constructor \"\"\" def __init__(self,AttentionNet,ControlNet,cube_size,n_hidden): super(DualDecoder, self).__init__() # Parameters self.D",
"conference on machine learning. 2015. * Input: feature [batch,D,h,w] * Output: hidden [1,batch,H]",
"et al. \"Show, attend and tell: Neural image caption generation with visual attention.\"",
"[batch,H] hidden = hidden.unsqueeze(0) # [1,batch,H] cell = self.init_Wc(feature) # [batch,D]*[D,H] -> [batch,H]",
"Feature-based attention # s[t] = f(z[t],h[t-1]) _zt = self.avgpool1( zt) _zt = torch.flatten(_zt,",
"[batch,H] cell1 = self.init_tanh( cell1 ) # [batch,H] cell2 = self.init_Wc2 ( cell1",
"~ [1,batch,H] # * cell ~ [1,batch,H] if self.training: xt = sequence[0] #",
"else: hc = None # hc,ha,hb = (None,None,None) # Sequence loop n_range =",
"\"\"\" Constructor \"\"\" def __init__(self,AttentionNet,ControlNet,cube_size,n_hidden): super(BasicDecoder, self).__init__() # Parameters self.D = cube_size[2] #",
"_,C,H,W = feature.shape # Batch of Tensor Images is a tensor of (B,",
"= torch.stack(ht_,dim=0) if self.training: st_ = st_.transpose(0,1).reshape(batch_size*sequence_len,self.n_task,self.S) ht_ = ht_.transpose(0,1).reshape(batch_size*sequence_len, self.H) # Compile",
"64 self.L = cube_size[0]*cube_size[1] # 90 self.R = self.L*self.D # 5760 self.H =",
"self.training: cmd = cmd.view(batch_size,sequence_len,-1).transpose(0,1) # [sequence,batch,4] # Prediction container st_,ht_ = list(),list() #",
"Tensor Images is a tensor of (B, C, H, W) shape # Data",
"Forward - eta [batch,channel,high,width] \"\"\" def forward(self,feature,command): # Parameters sequence_len = self.sequence_len if",
"hidden2 = self.init_Wh2 (hidden1) # [batch,H]*[H,H] -> [batch,H] hidden2 = self.init_tanh(hidden2) # [batch,H]",
"visual * beta # [batch,L,D]x[batch,1,D] = [batch,L,D] visual = visual.reshape(n_visual,self.R) # [batch,R] visual",
"1 ,L,D] # Visual Attention alpha,beta = self.attn(xt,hidden) # [batch,L,1] # Spatial spatial",
"# [batch,D,h,w] -> [batch,D] hidden = self.init_Wh(feature) # [batch,D]*[D,H] -> [batch,H] hidden =",
"= self.R, hidden_size = self.H, num_layers = 1) self.init_Wh = nn.Linear(self.D,self.H,bias=True ) self.init_Wc",
"visual = spatial + xt # Categorical visual = visual * beta #",
"[batch,L,D]x[batch,1,D] = [batch,L,D] visual = visual.reshape(n_visual,self.R) # [batch,R] visual = visual.unsqueeze(0) # [1,batch,R]",
"1024 # hidden_size self.M = n_hidden # 1024 # hidden_size self.sequence_len = 20",
"input LSTM 256 512 self.S = n_state self.n_task = n_task self.sequence_len = 20",
"cm = cmd[k].unsqueeze(0) # [ 1 , 4 ] # Spatial Attention xt,",
"torch.nn.init.xavier_uniform_(self.init_Wh.weight) torch.nn.init.xavier_uniform_(self.init_Wc.weight) self.lstm.reset_parameters() \"\"\" Initialize LSTM: hidden state and cell state Ref: Xu,",
"# [batch, ...] # Inicialize hidden state and cell state # * hidden",
"One time if self.training: ηt = sequence[k] # [batch,L,D] else : ηt =",
"# [batch,H] cell = cell.unsqueeze(0) # [1,batch,H] # (h,c) ~ [num_layers, batch, hidden_size]",
"Module ------------------ Ref: <NAME>., & <NAME>. (2017). \"Interpretable learning for self-driving cars by",
"# # # ------------------------------------------------------------------------------------------------ class CatDecoder(nn.Module): \"\"\" Constructor \"\"\" def __init__(self, HighEncoderNet, SpatialNet,",
"[batch,L,1] # Spatial spatial = xt * alpha # [batch,L,D]x[batch,L,1] = [batch,L,D] visual",
"-> [batch,D] hidden1 = self.init_Wh1 (feature) # [batch,D]*[D,H] -> [batch,H] hidden1 = self.init_tanh(hidden1)",
"# Sequence loop n_range = self.sequence_len if self.training else batch_size n_visual = batch_size",
"st_,ht_ = list(),list() # State initialization if self.training: st = torch.cuda.FloatTensor(batch_size,self.n_task,self.S).uniform_() else :",
"feature.shape # Batch of Tensor Images is a tensor of (B, C, H,",
"= 20 self.batch_size = 120 self.n_out = 3 # Output container self.pred =",
"= G.GRUGate(LowLevelDim) # Output self.dimReduction = nn.Conv2d(HighLevelDim,self.R, kernel_size=1, bias=False) self.lstm = nn.LSTM( input_size",
"Return return pred, map_, {'action': action, 'attention': atten} \"\"\" TVA Decoder Module ------------------",
"self. map.transpose(0,1).contiguous().view(batch_size*sequence_len,self.L) return self.pred, self.map \"\"\" Dual Decoder Module ------------------- * Input: feature",
"cell2 = self.init_tanh( cell2 ) # [batch,H] hidden = torch.stack([hidden1,hidden2], dim=0).contiguous() # [2,batch,H]",
"# [batch,L,D] -> [batch,D] hidden1 = self.init_Wh1 (feature) # [batch,D]*[D,H] -> [batch,H] hidden1",
"~ [ layers ,batch,H] _,(ht,ct)= self.lstm(rt,(ht,ct)) # Output st_.append(st.squeeze()) # [batch,n_task,S] ht_.append(ht.squeeze()) #",
"[batch, 4 ] else : cm = cmd[k].unsqueeze(0) # [ 1 , 4",
"= feature.shape[0] # Data if self.training: sequence = feature.view(batch_size,sequence_len,self.L,self.D).transpose_(0,1) # [sequence,batch,L,D] else :",
"= torch.cuda.FloatTensor( 1,self.n_task,self.S).uniform_() # Study if self.study: α,β,F = list(),list(),list() else : α,β,F",
"torch.device('cuda:0') ) atten = torch.zeros([self.batch_size,self.H]).to( torch.device('cuda:0') ) else: action,atten = (None,None) # Sequence",
"alpha # [batch,L,D]x[batch,L,1] = [batch,L,D] visual = spatial + xt # Categorical visual",
"(feature) # [batch,D]*[D,H] -> [batch,H] cell1 = self.init_tanh( cell1 ) # [batch,H] cell2",
"hidden[0].squeeze() atten [k] = hidden[1].squeeze() if self.training: pred = pred.transpose(0,1).contiguous().view(batch_size*sequence_len, n_out) map_ =",
"nn.LSTM( input_size = self.R, hidden_size = self.H, num_layers = 1) self.init_Wh = nn.Linear(self.D,self.H,bias=True",
"international conference on computer vision (pp. 2942-2950). * Input: feature [batch,L,D] hidden [1,batch,H]",
"self.lstm(visual,(hidden,cell)) # Control pred[k] = self.ctrl(visual, hidden[0].unsqueeze(0)) map_[k] = alpha.squeeze() if self.study: action[k]",
"<NAME>. (2017). \"Interpretable learning for self-driving cars by visualizing causal attention\". In Proceedings",
"# [1,batch,R] # LSTM # * yt ~ [sequence,batch,H] # * hidden ~",
"def __init__(self, HighEncoderNet, SpatialNet, FeatureNet, CommandNet, LowLevelDim=128, HighLevelDim=512, n_hidden=1024, n_state=64,n_task=3, study=False): super(CatDecoder, self).__init__()",
"xt = sequence[0] # Input to inicialize LSTM else : xt = sequence[0].unsqueeze(0)",
"if self.study: α.append(αt) β.append(βt) F.append(Ft) # Concatenate st_ = torch.stack(st_,dim=0) ht_ = torch.stack(ht_,dim=0)",
"init_Wh.weight) torch.nn.init.xavier_uniform_(self. init_Wc.weight) self.lstm.reset_parameters() \"\"\" Initialize LSTM: hidden state and cell state Ref:",
") self.init_tanh = nn.Tanh() # Initialization torch.nn.init.xavier_uniform_(self.init_Wh1.weight) torch.nn.init.xavier_uniform_(self.init_Wh2.weight) torch.nn.init.xavier_uniform_(self.init_Wc1.weight) torch.nn.init.xavier_uniform_(self.init_Wc2.weight) self.lstm.reset_parameters() \"\"\" Initialize",
"= [batch,L,D] visual = spatial + xt # Categorical visual = visual *",
"= visual.reshape(n_visual,self.R) # [batch,R] visual = visual.unsqueeze(0) # [1,batch,R] # LSTM # *",
"action = torch.zeros([self.batch_size,self.H]).to( torch.device('cuda:0') ) atten = torch.zeros([self.batch_size,self.H]).to( torch.device('cuda:0') ) else: action,atten =",
": xt = sequence[k].unsqueeze(0) # [ 1 ,L,D] # Visual Attention alpha =",
"[batch,H] hidden = self.init_tanh(hidden) # [batch,H] hidden = hidden.unsqueeze(0) # [1,batch,H] cell =",
"alpha [batch,L,1] \"\"\" class BasicDecoder(nn.Module): \"\"\" Constructor \"\"\" def __init__(self,AttentionNet,ControlNet,cube_size,n_hidden): super(BasicDecoder, self).__init__() #",
"------------------ Ref: <NAME>., & <NAME>. (2017). \"Interpretable learning for self-driving cars by visualizing",
"# Input to inicialize LSTM else : xt = sequence[0].unsqueeze(0) ht,ct = self.initializeLSTM(xt)",
"batch_size = feature.shape[0] _,C,H,W = feature.shape # Batch of Tensor Images is a",
"self.training: vis_ = torch.zeros([sequence_len,batch_size,self.R]).to( torch.device('cuda:0') ) alp_ = torch.zeros([sequence_len,batch_size,self.L]).to( torch.device('cuda:0') ) bet_ =",
"Attention alpha = self.attn(xt,hidden[1].unsqueeze(0))# [batch,L,1] visual = xt * alpha # [batch,L,D]x[batch,L,1] =",
"{'alpha': alp_, 'beta': bet_}, {'control': hc} # ------------------------------------------------------------------------------------------------ # # # ------------------------------------------------------------------------------------------------ class",
"\"\"\" def initializeLSTM(self,feature): with torch.no_grad(): # Mean features feature = torch.mean(feature,1) # [batch,L,D]",
"# 64 # cube_size[0] self.L = cube_size[0]*cube_size[1] # 90 # cube_size[1]*cube_size[2] self.R =",
"Inicialize hidden state and cell state # * hidden ~ [1,batch,H] # *",
"[1,batch,H] # * cell ~ [1,batch,H] if self.training: xt = sequence[0] # Input",
"self. map = self. map.view(sequence_len,batch_size,self.L) # Sequence loop n_range = self.sequence_len if self.training",
"# [1,batch,H] # (h,c) ~ [num_layers, batch, hidden_size] return hidden.contiguous(),cell.contiguous() \"\"\" Forward -",
"visual.unsqueeze(0) # [1,batch,R] # LSTM # * yt ~ [sequence,batch,H] # * hidden",
"Images is a tensor of (B, C, H, W) shape # Data if",
") # [batch,H] hidden = torch.stack([hidden1,hidden2], dim=0).contiguous() # [2,batch,H] cell = torch.stack([ cell1,",
"map_[k] = alpha.squeeze() if self.study: action[k] = hidden[0].squeeze() atten [k] = hidden[1].squeeze() if",
"= torch.zeros([sequence_len,batch_size,self.L]).to( torch.device('cuda:0') ) else: pred = torch.zeros([batch_size, n_out]).to( torch.device('cuda:0') ) map_ =",
"= sequence[k] # [batch,L,D] else : xt = sequence[k].unsqueeze(0) # [ 1 ,L,D]",
"torch.zeros([batch_size,self.D]).to( torch.device('cuda:0') ) hdd_ = torch.zeros([batch_size,self.H]).to( torch.device('cuda:0') ) # Study rountime if self.study:",
"n_range = self.sequence_len if self.training else batch_size n_visual = batch_size if self.training else",
"HighEncoderNet self.SpatialAttn = SpatialNet self.FeatureAttn = FeatureNet self. CmdDecoder = CommandNet self.Gate =",
"dim=0) F = torch.stack(F, dim=0) return st_, {'hidden': ht_, 'feature': F}, {'alpha': α,",
"~ [num_layers, batch, hidden_size] return hidden.contiguous(),cell.contiguous() \"\"\" Forward - eta [batch,channel,high,width] \"\"\" def",
"= sequence[0].unsqueeze(0) ht,ct = self.initializeLSTM(xt) # Command decoder cmd = self.CmdDecoder(command) if self.training:",
"hidden = torch.stack([hidden1,hidden2], dim=0).contiguous() # [2,batch,H] cell = torch.stack([ cell1, cell2], dim=0).contiguous() #",
"[sequence,batch,4] # Prediction container st_,ht_ = list(),list() # State initialization if self.training: st",
"feature # [batch, ...] # Inicialize hidden state and cell state # *",
"Input: feature [batch,L,D] * Output: hidden [1,batch,H] cell [1,batch,H] \"\"\" def initializeLSTM(self,feature): with",
"= cmd.view(batch_size,sequence_len,-1).transpose(0,1) # [sequence,batch,4] # Prediction container st_,ht_ = list(),list() # State initialization",
"= FeatureNet self. CmdDecoder = CommandNet self.Gate = G.GRUGate(LowLevelDim) # Output self.dimReduction =",
"[batch,H] cell2 = self.init_Wc2 ( cell1 ) # [batch,H]*[H,H] -> [batch,H] cell2 =",
"torch.zeros([self.batch_size,self.n_out]) self. map = torch.zeros([self.batch_size,self. L ]) # Declare layers self.attn = AttentionNet",
"if self.training: cm = cmd[k] # [batch, 4 ] else : cm =",
"nn.Linear(self.D,self.H,bias=True ) self.init_Wh2 = nn.Linear(self.H,self.H,bias=True ) self.init_Wc1 = nn.Linear(self.D,self.H,bias=True ) self.init_Wc2 = nn.Linear(self.H,self.H,bias=True",
"# Parameters sequence_len = self.sequence_len n_out = self.n_out if self.training: batch_size = int(feature.shape[0]/sequence_len)",
"[ 1 ,L,D] if self.training: cm = cmd[k] # [batch, 4 ] else",
"map_ = torch.zeros([sequence_len,batch_size,self.L]).to( torch.device('cuda:0') ) else: pred = torch.zeros([batch_size, n_out]).to( torch.device('cuda:0') ) map_",
"# * hidden ~ [1,batch,H] # * cell ~ [1,batch,H] hidden,cell = self.initializeLSTM(xt)",
"= self.lstm(visual,(hidden,cell)) # Control self.pred[k] = self.ctrl(visual, hidden, training=self.training) self. map[k] = alpha.squeeze()",
"= self.L*self.D # 5760 self.H = n_hidden # 512 self.M = n_hidden #",
"cell1 = self.init_tanh( cell1 ) # [batch,H] cell2 = self.init_Wc2 ( cell1 )",
"features feature = torch.mean(feature,1) # [batch,L,D] -> [batch,D] hidden1 = self.init_Wh1 (feature) #",
"list(),list(),list() else : α,β,F = None, None, None # Sequence loop n_range =",
"[batch,D]*[D,H] -> [batch,H] hidden = self.init_tanh(hidden) # [batch,H] hidden = hidden.unsqueeze(0) # [1,batch,H]",
"__init__(self,AttentionNet,ControlNet,cube_size,n_hidden): super(BasicDecoder, self).__init__() # Parameters self.D = cube_size[2] # 64 self.L = cube_size[0]*cube_size[1]",
"= self.sequence_len n_out = self.n_out if self.training: batch_size = int(feature.shape[0]/sequence_len) else : batch_size",
"Sequence loop n_range = self.sequence_len if self.training else batch_size n_visual = batch_size if",
"[k] = hidden[1].squeeze() if self.training: pred = pred.transpose(0,1).contiguous().view(batch_size*sequence_len, n_out) map_ = map_.transpose(0,1).contiguous().view(batch_size*sequence_len,self.L) #",
"alpha.squeeze() if self.training: self.pred = self.pred.transpose(0,1).contiguous().view(batch_size*sequence_len, n_out) self. map = self. map.transpose(0,1).contiguous().view(batch_size*sequence_len,self.L) return",
"Study rountime if self.study: hc = torch.zeros([self.batch_size,self.H]).to( torch.device('cuda:0') ) else: hc = None",
"]) # Declare layers self.attn = AttentionNet self.ctrl = ControlNet self.lstm = nn.LSTM(",
"layers ,batch,H] _,(ht,ct)= self.lstm(rt,(ht,ct)) # Output st_.append(st.squeeze()) # [batch,n_task,S] ht_.append(ht.squeeze()) # [batch, H]",
"H] # Study if self.study: α.append(αt) β.append(βt) F.append(Ft) # Concatenate st_ = torch.stack(st_,dim=0)",
"self.ctrl(visual, hidden[0].unsqueeze(0)) map_[k] = alpha.squeeze() if self.study: action[k] = hidden[0].squeeze() atten [k] =",
"# Batch of Tensor Images is a tensor of (B, C, H, W)",
"[batch,H]*[H,H] -> [batch,H] cell2 = self.init_tanh( cell2 ) # [batch,H] hidden = torch.stack([hidden1,hidden2],",
"1024 2048 self.R = int(n_hidden/4) # input LSTM 256 512 self.S = n_state",
"[batch,H] cell1 = self.init_Wc1 (feature) # [batch,D]*[D,H] -> [batch,H] cell1 = self.init_tanh( cell1",
"torch.zeros([sequence_len,batch_size,self.H]).to( torch.device('cuda:0') ) else: vis_ = torch.zeros([batch_size,self.R]).to( torch.device('cuda:0') ) alp_ = torch.zeros([batch_size,self.L]).to( torch.device('cuda:0')",
"nn.LSTM( input_size = self.R, hidden_size = self.H, num_layers = 1) self.init_Wh = nn.Linear(LowLevelDim,self.H,bias=True",
"= [batch,L,D] visual = visual.reshape(n_visual,self.R) # [batch,R] visual = visual.unsqueeze(0) # [1,batch,R] #",
"= torch.cuda.FloatTensor(batch_size,self.n_task,self.S).uniform_() else : st = torch.cuda.FloatTensor( 1,self.n_task,self.S).uniform_() # Study if self.study: α,β,F",
"xt * alpha # [batch,L,D]x[batch,L,1] = [batch,L,D] visual = spatial + xt #",
"self.sequence_len if self.training: batch_size = int(feature.shape[0]/sequence_len) else : batch_size = feature.shape[0] _,C,H,W =",
": sequence = feature # [batch,L,D] # Input to inicialize LSTM if self.training:",
"= sequence[k] # [batch,L,D] else : ηt = sequence[k].unsqueeze(0) # [ 1 ,L,D]",
"dim=0).contiguous() # [2,batch,H] # (h,c) ~ [num_layers, batch, hidden_size] return hidden,cell \"\"\" Forward",
"IEEE international conference on computer vision (pp. 2942-2950). * Input: feature [batch,L,D] hidden",
"hidden.contiguous(),cell.contiguous() \"\"\" Forward \"\"\" def forward(self,feature): # Parameters sequence_len = self.sequence_len if self.training:",
"\"\"\" def initializeLSTM(self,feature): with torch.no_grad(): # Mean features feature = torch.mean(feature,(2,3)) # [batch,D,h,w]",
"cmd = cmd.view(batch_size,sequence_len,-1).transpose(0,1) # [sequence,batch,4] # Prediction container st_,ht_ = list(),list() # State",
"torch.device('cuda:0') ) hdd_ = torch.zeros([sequence_len,batch_size,self.H]).to( torch.device('cuda:0') ) else: vis_ = torch.zeros([batch_size,self.R]).to( torch.device('cuda:0') )",
"# [batch,H]*[H,H] -> [batch,H] cell2 = self.init_tanh( cell2 ) # [batch,H] hidden =",
"forward(self,feature): # Parameters sequence_len = self.sequence_len n_out = self.n_out if self.training: batch_size =",
"torch.zeros([sequence_len,batch_size,self.R]).to( torch.device('cuda:0') ) alp_ = torch.zeros([sequence_len,batch_size,self.L]).to( torch.device('cuda:0') ) bet_ = torch.zeros([sequence_len,batch_size,self.D]).to( torch.device('cuda:0') )",
"sequence[k].unsqueeze(0) # [ 1 ,L,D] # Visual Attention alpha,beta = self.attn(xt,hidden) # [batch,L,1]",
"sequence = feature.view(batch_size,sequence_len,self.L,self.D).transpose_(0,1) # [sequence,batch,L,D] else : sequence = feature # [batch,L,D] #",
"conference on computer vision (pp. 2942-2950). * Input: feature [batch,L,D] hidden [1,batch,H] *",
"batch_size = int(feature.shape[0]/sequence_len) else : batch_size = feature.shape[0] # Data if self.training: sequence",
"FeatureNet, CommandNet, LowLevelDim=128, HighLevelDim=512, n_hidden=1024, n_state=64,n_task=3, study=False): super(CatDecoder, self).__init__() self.study = study #",
"is a tensor of (B, C, H, W) shape # Data if self.training:",
"cell1 = self.init_Wc1 (feature) # [batch,D]*[D,H] -> [batch,H] cell1 = self.init_tanh( cell1 )",
"alp_.transpose(0,1).contiguous().view(batch_size*sequence_len,self.L) bet_ = bet_.transpose(0,1).contiguous().view(batch_size*sequence_len,self.D) hdd_ = hdd_.transpose(0,1).contiguous().view(batch_size*sequence_len,self.H) return vis_, hdd_, {'alpha': alp_, 'beta':",
"[batch,L,D] visual = spatial + xt # Categorical visual = visual * beta",
"# * cell ~ [ layers ,batch,H] _,(hidden,cell) = self.lstm(visual,(hidden,cell)) # Control self.pred[k]",
"and cell state Ref: <NAME>, et al. \"Show, attend and tell: Neural image",
"with visual attention.\" International conference on machine learning. 2015. * Input: feature [batch,D,h,w]",
"map_.transpose(0,1).contiguous().view(batch_size*sequence_len,self.L) # Return return pred, map_, {'action': action, 'attention': atten} \"\"\" TVA Decoder",
"zt = self.HighEncoder(xt) # Feature-based attention # s[t] = f(z[t],h[t-1]) _zt = self.avgpool1(",
"Forward \"\"\" def forward(self,feature): # Parameters sequence_len = self.sequence_len if self.training: batch_size =",
"self.pred.view(sequence_len,batch_size, n_out) self. map = self. map.view(sequence_len,batch_size,self.L) # Sequence loop n_range = self.sequence_len",
"if self.training: pred = torch.zeros([sequence_len,batch_size, n_out]).to( torch.device('cuda:0') ) map_ = torch.zeros([sequence_len,batch_size,self.L]).to( torch.device('cuda:0') )",
"Constructor \"\"\" def __init__(self, HighEncoderNet, SpatialNet, FeatureNet, CommandNet, LowLevelDim=128, HighLevelDim=512, n_hidden=1024, n_state=64,n_task=3, study=False):",
"avgpool2(rt) rt = torch.flatten(rt , 1) rt = rt.unsqueeze(0) # LSTM # *",
"# 90 self.R = self.L*self.D # 5760 self.H = n_hidden # 512 self.M",
"~ [1,batch,H] hidden,cell = self.initializeLSTM(xt) # Prediction container if self.training: vis_ = torch.zeros([sequence_len,batch_size,self.R]).to(",
") else: vis_ = torch.zeros([batch_size,self.R]).to( torch.device('cuda:0') ) alp_ = torch.zeros([batch_size,self.L]).to( torch.device('cuda:0') ) bet_",
"= hidden[1].squeeze() if self.training: pred = pred.transpose(0,1).contiguous().view(batch_size*sequence_len, n_out) map_ = map_.transpose(0,1).contiguous().view(batch_size*sequence_len,self.L) # Return",
"# Compile study if self.study: α = torch.stack(α, dim=0) β = torch.stack(β, dim=0)",
"cmd = self.CmdDecoder(command) if self.training: cmd = cmd.view(batch_size,sequence_len,-1).transpose(0,1) # [sequence,batch,4] # Prediction container",
"self.batch_size = 120 self.n_out = 3 self.study = False # Declare layers self.attn",
"else 1 for k in range(n_range): # One time if self.training: xt =",
"* Output: alpha [batch,L,1] \"\"\" class BasicDecoder(nn.Module): \"\"\" Constructor \"\"\" def __init__(self,AttentionNet,ControlNet,cube_size,n_hidden): super(BasicDecoder,",
"study=False): super(CatDecoder, self).__init__() self.study = study # Parameters self.H = n_hidden # output",
"alp_ = alp_.transpose(0,1).contiguous().view(batch_size*sequence_len,self.L) bet_ = bet_.transpose(0,1).contiguous().view(batch_size*sequence_len,self.D) hdd_ = hdd_.transpose(0,1).contiguous().view(batch_size*sequence_len,self.H) return vis_, hdd_, {'alpha':",
"cell = torch.stack([ cell1, cell2], dim=0).contiguous() # [2,batch,H] # (h,c) ~ [num_layers, batch,",
"self.H, num_layers = 1) self.init_Wh = nn.Linear(self.D,self.H,bias=True ) self.init_Wc = nn.Linear(self.D,self.H,bias=True ) self.init_tanh",
"# [batch,n_task,S] ht_.append(ht.squeeze()) # [batch, H] # Study if self.study: α.append(αt) β.append(βt) F.append(Ft)",
"self.init_tanh = nn.Tanh() # Initialization torch.nn.init.xavier_uniform_(self.init_Wh1.weight) torch.nn.init.xavier_uniform_(self.init_Wh2.weight) torch.nn.init.xavier_uniform_(self.init_Wc1.weight) torch.nn.init.xavier_uniform_(self.init_Wc2.weight) self.lstm.reset_parameters() \"\"\" Initialize LSTM:",
"self.n_out = 3 self.study = False # Declare layers self.attn = AttentionNet self.ctrl",
"Ref: Xu, Kelvin, et al. \"Show, attend and tell: Neural image caption generation",
"self.lstm(visual,(hidden,cell)) # Control self.pred[k] = self.ctrl(visual, hidden, training=self.training) self. map[k] = alpha.squeeze() if",
"self.study: hc = torch.zeros([self.batch_size,self.H]).to( torch.device('cuda:0') ) else: hc = None # hc,ha,hb =",
"else : xt = sequence[k].unsqueeze(0) # [ 1 ,L,D] # Visual Attention alpha,beta",
"* yt ~ [sequence,batch,H] # * hidden ~ [ layers ,batch,H] # *",
"visual # [1,batch,R] alp_[k] = alpha.squeeze() # [1,batch,L] bet_[k] = beta.squeeze() # [1,batch,D]",
"# Study if self.study: α.append(αt) β.append(βt) F.append(Ft) # Concatenate st_ = torch.stack(st_,dim=0) ht_",
"yt ~ [sequence,batch,H] # * hidden ~ [ layers ,batch,H] # * cell",
"-> [batch,H] hidden = self.init_tanh(hidden) # [batch,H] hidden = hidden.unsqueeze(0) # [1,batch,H] cell",
"64 # cube_size[0] self.L = cube_size[0]*cube_size[1] # 90 # cube_size[1]*cube_size[2] self.R = self.L*self.D",
"map = self. map.transpose(0,1).contiguous().view(batch_size*sequence_len,self.L) return self.pred, self.map \"\"\" Dual Decoder Module ------------------- *",
"\"\"\" def forward(self,feature): # Parameters sequence_len = self.sequence_len n_out = self.n_out if self.training:",
"hidden_size] return hidden.contiguous(),cell.contiguous() \"\"\" Forward \"\"\" def forward(self,feature): # Parameters sequence_len = self.sequence_len",
"torch.zeros([batch_size,self.R]).to( torch.device('cuda:0') ) alp_ = torch.zeros([batch_size,self.L]).to( torch.device('cuda:0') ) bet_ = torch.zeros([batch_size,self.D]).to( torch.device('cuda:0') )",
"self.study: hc[k] = hidden[0].squeeze() if self.training: vis_ = vis_.transpose(0,1).contiguous().view(batch_size*sequence_len,self.R) alp_ = alp_.transpose(0,1).contiguous().view(batch_size*sequence_len,self.L) bet_",
") bet_ = torch.zeros([sequence_len,batch_size,self.D]).to( torch.device('cuda:0') ) hdd_ = torch.zeros([sequence_len,batch_size,self.H]).to( torch.device('cuda:0') ) else: vis_",
"torch.no_grad(): # Mean features feature = torch.mean(feature,(2,3)) # [batch,D,h,w] -> [batch,D] hidden =",
"5760 # self.L*self.D self.H = n_hidden # 1024 # hidden_size self.M = n_hidden",
"self.S = n_state self.n_task = n_task self.sequence_len = 20 # Attention self.HighEncoder =",
"SpatialNet self.FeatureAttn = FeatureNet self. CmdDecoder = CommandNet self.Gate = G.GRUGate(LowLevelDim) # Output",
"self.lstm.reset_parameters() \"\"\" Initialize LSTM: hidden state and cell state Ref: <NAME>, et al.",
"= torch.flatten(_zt, 1) st, βt, Ft = self.FeatureAttn(_zt,ht[0],cm) # [batch,S] # Dimension reduction",
"= torch.zeros([sequence_len,batch_size, n_out]).to( torch.device('cuda:0') ) map_ = torch.zeros([sequence_len,batch_size,self.L]).to( torch.device('cuda:0') ) else: pred =",
"Attention xt, αt = self.SpatialAttn(ηt,st) xt = self.Gate(ηt,xt) # High-level encoder zt =",
"CommandNet self.Gate = G.GRUGate(LowLevelDim) # Output self.dimReduction = nn.Conv2d(HighLevelDim,self.R, kernel_size=1, bias=False) self.lstm =",
": cm = cmd[k].unsqueeze(0) # [ 1 , 4 ] # Spatial Attention",
"st = torch.cuda.FloatTensor( 1,self.n_task,self.S).uniform_() # Study if self.study: α,β,F = list(),list(),list() else :",
"= nn.Tanh() # Initialization torch.nn.init.xavier_uniform_(self.init_Wh.weight) torch.nn.init.xavier_uniform_(self.init_Wc.weight) self.lstm.reset_parameters() \"\"\" Initialize LSTM: hidden state and",
"def __init__(self,AttentionNet,ControlNet,cube_size,n_hidden): super(DualDecoder, self).__init__() # Parameters self.D = cube_size[2] # 64 # cube_size[0]",
"# Initialization torch.nn.init.xavier_uniform_(self.dimReduction.weight) torch.nn.init.xavier_uniform_(self. init_Wh.weight) torch.nn.init.xavier_uniform_(self. init_Wc.weight) self.lstm.reset_parameters() \"\"\" Initialize LSTM: hidden state",
"[batch,L,D] -> [batch,D] hidden = self.init_Wh(feature) # [batch,D]*[D,H] -> [batch,H] hidden = self.init_tanh(hidden)",
"= cube_size[0]*cube_size[1] # 90 self.R = self.L*self.D # 5760 self.H = n_hidden #",
": batch_size = feature.shape[0] _,C,H,W = feature.shape # Batch of Tensor Images is",
"# Data if self.training: sequence = feature.view(batch_size,sequence_len,C,H,W).transpose(0,1) # [sequence,batch, ...] else : sequence",
"= sequence[k].unsqueeze(0) # [ 1 ,L,D] # Visual Attention alpha,beta = self.attn(xt,hidden) #",
"cmd[k] # [batch, 4 ] else : cm = cmd[k].unsqueeze(0) # [ 1",
"return vis_, hdd_, {'alpha': alp_, 'beta': bet_}, {'control': hc} # ------------------------------------------------------------------------------------------------ # #",
"self).__init__() # Parameters self.D = cube_size[2] # 64 self.L = cube_size[0]*cube_size[1] # 90",
"f(z[t],h[t-1]) _zt = self.avgpool1( zt) _zt = torch.flatten(_zt, 1) st, βt, Ft =",
"caption generation with visual attention.\" International conference on machine learning. 2015. * Input:",
"2015. * Input: feature [batch,L,D] * Output: hidden [1,batch,H] cell [1,batch,H] \"\"\" def",
"# 1024 # hidden_size self.M = n_hidden # 1024 # hidden_size self.sequence_len =",
"[ 1 ,L,D] # Visual Attention alpha = self.attn(xt,hidden)# [batch,L,1] visual = xt",
"[batch,D] hidden = self.init_Wh(feature) # [batch,D]*[D,H] -> [batch,H] hidden = self.init_tanh(hidden) # [batch,H]",
"n_hidden # 512 self.sequence_len = 20 self.batch_size = 120 self.n_out = 3 #",
"torch.device('cuda:0') ) else: vis_ = torch.zeros([batch_size,self.R]).to( torch.device('cuda:0') ) alp_ = torch.zeros([batch_size,self.L]).to( torch.device('cuda:0') )",
"st_.append(st.squeeze()) # [batch,n_task,S] ht_.append(ht.squeeze()) # [batch, H] # Study if self.study: α.append(αt) β.append(βt)",
"Declare layers self.attn = AttentionNet self.ctrl = ControlNet self.lstm = nn.LSTM( input_size=self.R, hidden_size=self.H,",
"torch.zeros([batch_size, n_out]).to( torch.device('cuda:0') ) map_ = torch.zeros([batch_size,self.L]).to( torch.device('cuda:0') ) # Study rountime if",
"cell = cell.unsqueeze(0) # [1,batch,H] # (h,c) ~ [num_layers, batch, hidden_size] return hidden.contiguous(),cell.contiguous()",
"hidden ~ [1,batch,H] # * cell ~ [1,batch,H] if self.training: xt = sequence[0]",
"self.n_out = 3 # Output container self.pred = torch.zeros([self.batch_size,self.n_out]) self. map = torch.zeros([self.batch_size,self.",
"= pred.transpose(0,1).contiguous().view(batch_size*sequence_len, n_out) map_ = map_.transpose(0,1).contiguous().view(batch_size*sequence_len,self.L) # Return return pred, map_, {'action': action,",
"= False # Declare layers self.attn = AttentionNet self.ctrl = ControlNet self.lstm =",
"loop n_range = self.sequence_len if self.training else batch_size n_visual = batch_size if self.training",
"self.SpatialAttn = SpatialNet self.FeatureAttn = FeatureNet self. CmdDecoder = CommandNet self.Gate = G.GRUGate(LowLevelDim)",
"= feature.shape[0] _,C,H,W = feature.shape # Batch of Tensor Images is a tensor",
"\"\"\" def __init__(self,AttentionNet,cube_size,n_hidden): super(TVADecoder, self).__init__() # Parameters self.D = cube_size[2] # 64 self.L",
") map_ = torch.zeros([sequence_len,batch_size,self.L]).to( torch.device('cuda:0') ) else: pred = torch.zeros([batch_size, n_out]).to( torch.device('cuda:0') )",
"Categorical visual = visual * beta # [batch,L,D]x[batch,1,D] = [batch,L,D] visual = visual.reshape(n_visual,self.R)",
"beta # [batch,L,D]x[batch,1,D] = [batch,L,D] visual = visual.reshape(n_visual,self.R) # [batch,R] visual = visual.unsqueeze(0)",
"torch.nn.init.xavier_uniform_(self. init_Wh.weight) torch.nn.init.xavier_uniform_(self. init_Wc.weight) self.lstm.reset_parameters() \"\"\" Initialize LSTM: hidden state and cell state",
"Dimension reduction to LSTM rt = self.dimReduction(zt) rt = self. avgpool2(rt) rt =",
"feature.view(batch_size,sequence_len,C,H,W).transpose(0,1) # [sequence,batch, ...] else : sequence = feature # [batch, ...] #",
"= sequence[0] else : xt = sequence[0].unsqueeze(0) # Inicialize hidden state and cell",
"# Feature-based attention # s[t] = f(z[t],h[t-1]) _zt = self.avgpool1( zt) _zt =",
"One time if self.training: xt = sequence[k] # [batch,L,D] else : xt =",
"[1,batch,H] if self.study: hc[k] = hidden[0].squeeze() if self.training: vis_ = vis_.transpose(0,1).contiguous().view(batch_size*sequence_len,self.R) alp_ =",
"class CatDecoder(nn.Module): \"\"\" Constructor \"\"\" def __init__(self, HighEncoderNet, SpatialNet, FeatureNet, CommandNet, LowLevelDim=128, HighLevelDim=512,",
"self.study: α = torch.stack(α, dim=0) β = torch.stack(β, dim=0) F = torch.stack(F, dim=0)",
"# * hidden ~ [ layers ,batch,H] # * cell ~ [ layers",
"= hidden[0].squeeze() if self.training: vis_ = vis_.transpose(0,1).contiguous().view(batch_size*sequence_len,self.R) alp_ = alp_.transpose(0,1).contiguous().view(batch_size*sequence_len,self.L) bet_ = bet_.transpose(0,1).contiguous().view(batch_size*sequence_len,self.D)",
"= alpha.squeeze() # [1,batch,L] bet_[k] = beta.squeeze() # [1,batch,D] hdd_[k] = hidden[0].unsqueeze(0) #",
"# [ 1 ,L,D] # Visual Attention alpha = self.attn(xt,hidden)# [batch,L,1] visual =",
"torch.stack([ cell1, cell2], dim=0).contiguous() # [2,batch,H] # (h,c) ~ [num_layers, batch, hidden_size] return",
"Forward \"\"\" def forward(self,feature): # Parameters sequence_len = self.sequence_len n_out = self.n_out if",
"[1,batch,H] hidden,cell = self.initializeLSTM(xt) # Prediction container if self.training: pred = torch.zeros([sequence_len,batch_size, n_out]).to(",
"attend and tell: Neural image caption generation with visual attention.\" International conference on",
"self.n_task = n_task self.sequence_len = 20 # Attention self.HighEncoder = HighEncoderNet self.SpatialAttn =",
"# [1,batch,R] alp_[k] = alpha.squeeze() # [1,batch,L] bet_[k] = beta.squeeze() # [1,batch,D] hdd_[k]",
"else : xt = sequence[0].unsqueeze(0) ht,ct = self.initializeLSTM(xt) # Command decoder cmd =",
"self.init_Wc2 ( cell1 ) # [batch,H]*[H,H] -> [batch,H] cell2 = self.init_tanh( cell2 )",
"hidden_size self.M = n_hidden # 1024 # hidden_size self.sequence_len = 20 self.batch_size =",
"self. map = self. map.transpose(0,1).contiguous().view(batch_size*sequence_len,self.L) return self.pred, self.map \"\"\" Dual Decoder Module -------------------",
"# hc,ha,hb = (None,None,None) # Sequence loop n_range = self.sequence_len if self.training else",
"hdd_[k] = hidden[0].unsqueeze(0) # [1,batch,H] if self.study: hc[k] = hidden[0].squeeze() if self.training: vis_",
"super(BasicDecoder, self).__init__() # Parameters self.D = cube_size[2] # 64 self.L = cube_size[0]*cube_size[1] #",
"def forward(self,feature): # Parameters sequence_len = self.sequence_len if self.training: batch_size = int(feature.shape[0]/sequence_len) else",
"feature [batch,L,D] hidden [1,batch,H] * Output: alpha [batch,L,1] \"\"\" class TVADecoder(nn.Module): \"\"\" Constructor",
"Parameters self.H = n_hidden # output LSTM 1024 2048 self.R = int(n_hidden/4) #",
"None, None, None # Sequence loop n_range = self.sequence_len if self.training else batch_size",
"torch.zeros([sequence_len,batch_size,self.L]).to( torch.device('cuda:0') ) else: pred = torch.zeros([batch_size, n_out]).to( torch.device('cuda:0') ) map_ = torch.zeros([batch_size,self.L]).to(",
"def initializeLSTM(self,feature): with torch.no_grad(): # Mean features feature = torch.mean(feature,(2,3)) # [batch,D,h,w] ->",
"self.pred = self.pred.view(sequence_len,batch_size, n_out) self. map = self. map.view(sequence_len,batch_size,self.L) # Sequence loop n_range",
"= 120 self.n_out = 3 # Output container self.pred = torch.zeros([self.batch_size,self.n_out]) self. map",
"self.Gate(ηt,xt) # High-level encoder zt = self.HighEncoder(xt) # Feature-based attention # s[t] =",
"20 self.batch_size = 120 self.n_out = 3 self.study = False # Declare layers",
"# [batch,D]*[D,H] -> [batch,H] hidden1 = self.init_tanh(hidden1) # [batch,H] hidden2 = self.init_Wh2 (hidden1)",
"learning. 2015. * Input: feature [batch,L,D] * Output: hidden [1,batch,H] cell [1,batch,H] \"\"\"",
"= xt * alpha # [batch,L,D]x[batch,L,1] = [batch,L,D] visual = spatial + xt",
"feature [batch,L,D] hidden [1,batch,H] * Output: alpha [batch,L,1] \"\"\" class BasicDecoder(nn.Module): \"\"\" Constructor",
"forward(self,feature): # Parameters sequence_len = self.sequence_len if self.training: batch_size = int(feature.shape[0]/sequence_len) else :",
"[1,batch,H] cell = self.init_Wc(feature) # [batch,D]*[D,H] -> [batch,H] cell = self.init_tanh(cell) # [batch,H]",
"Prediction container st_,ht_ = list(),list() # State initialization if self.training: st = torch.cuda.FloatTensor(batch_size,self.n_task,self.S).uniform_()",
"self.R = int(n_hidden/4) # input LSTM 256 512 self.S = n_state self.n_task =",
"[ layers ,batch,H] _,(ht,ct)= self.lstm(rt,(ht,ct)) # Output st_.append(st.squeeze()) # [batch,n_task,S] ht_.append(ht.squeeze()) # [batch,",
"[batch,L,1] \"\"\" class BasicDecoder(nn.Module): \"\"\" Constructor \"\"\" def __init__(self,AttentionNet,ControlNet,cube_size,n_hidden): super(BasicDecoder, self).__init__() # Parameters",
"self.H = n_hidden # 512 self.M = n_hidden # 512 self.sequence_len = 20",
"[2,batch,H] # (h,c) ~ [num_layers, batch, hidden_size] return hidden,cell \"\"\" Forward \"\"\" def",
"import set_trace import ImitationLearning.VisualAttention.network.Gate as G \"\"\" Basic Decoder Module -------------------- Ref: <NAME>.,",
"Visual Attention alpha,beta = self.attn(xt,hidden) # [batch,L,1] # Spatial spatial = xt *",
"learning. 2015. * Input: feature [batch,D,h,w] * Output: hidden [1,batch,H] cell [1,batch,H] \"\"\"",
"else: vis_ = torch.zeros([batch_size,self.R]).to( torch.device('cuda:0') ) alp_ = torch.zeros([batch_size,self.L]).to( torch.device('cuda:0') ) bet_ =",
"initializeLSTM(self,feature): with torch.no_grad(): # Mean features feature = torch.mean(feature,1) # [batch,L,D] -> [batch,D]",
"* Output: alpha [batch,L,1] \"\"\" class DualDecoder(nn.Module): \"\"\" Constructor \"\"\" def __init__(self,AttentionNet,ControlNet,cube_size,n_hidden): super(DualDecoder,",
"n_range = self.sequence_len if self.training else batch_size for k in range(n_range): # One",
") else: hc = None # hc,ha,hb = (None,None,None) # Sequence loop n_range",
"al. \"Show, attend and tell: Neural image caption generation with visual attention.\" International",
"\"\"\" Initialize LSTM: hidden state and cell state Ref: Xu, Kelvin, et al.",
"1) st, βt, Ft = self.FeatureAttn(_zt,ht[0],cm) # [batch,S] # Dimension reduction to LSTM",
"hidden,cell \"\"\" Forward \"\"\" def forward(self,feature): # Parameters sequence_len = self.sequence_len n_out =",
"layers ,batch,H] # * cell ~ [ layers ,batch,H] _,(ht,ct)= self.lstm(rt,(ht,ct)) # Output",
"F = torch.stack(F, dim=0) return st_, {'hidden': ht_, 'feature': F}, {'alpha': α, 'beta':",
"a tensor of (B, C, H, W) shape # Data if self.training: sequence",
",L,D] # Visual Attention alpha,beta = self.attn(xt,hidden) # [batch,L,1] # Spatial spatial =",
"self.pred, self.map \"\"\" Dual Decoder Module ------------------- * Input: feature [batch,L,D] hidden [1,batch,H]",
"hidden[0].squeeze() if self.training: vis_ = vis_.transpose(0,1).contiguous().view(batch_size*sequence_len,self.R) alp_ = alp_.transpose(0,1).contiguous().view(batch_size*sequence_len,self.L) bet_ = bet_.transpose(0,1).contiguous().view(batch_size*sequence_len,self.D) hdd_",
"AttentionNet self.ctrl = ControlNet self.lstm = nn.LSTM( input_size=self.R, hidden_size=self.H, num_layers=2 ) self.init_Wh1 =",
") # [batch,H]*[H,H] -> [batch,H] cell2 = self.init_tanh( cell2 ) # [batch,H] hidden",
"pred = torch.zeros([sequence_len,batch_size, n_out]).to( torch.device('cuda:0') ) map_ = torch.zeros([sequence_len,batch_size,self.L]).to( torch.device('cuda:0') ) else: pred",
"int(feature.shape[0]/sequence_len) else : batch_size = feature.shape[0] _,C,H,W = feature.shape # Batch of Tensor",
"# * yt ~ [sequence,batch,H] # * hidden ~ [ layers ,batch,H] #",
"to inicialize LSTM else : xt = sequence[0].unsqueeze(0) ht,ct = self.initializeLSTM(xt) # Command",
"hidden.unsqueeze(0) # [1,batch,H] cell = self.init_Wc(feature) # [batch,D]*[D,H] -> [batch,H] cell = self.init_tanh(cell)",
"1)) self.normSpa = nn.BatchNorm2d(LowLevelDim) self.ReLU = nn.ReLU() # Initialization torch.nn.init.xavier_uniform_(self.dimReduction.weight) torch.nn.init.xavier_uniform_(self. init_Wh.weight) torch.nn.init.xavier_uniform_(self.",
"torch.device('cuda:0') ) # Study rountime if self.study: hc = torch.zeros([self.batch_size,self.H]).to( torch.device('cuda:0') ) else:",
"self.initializeLSTM(xt) # Command decoder cmd = self.CmdDecoder(command) if self.training: cmd = cmd.view(batch_size,sequence_len,-1).transpose(0,1) #",
"machine learning. 2015. * Input: feature [batch,D,h,w] * Output: hidden [1,batch,H] cell [1,batch,H]",
"Input: feature [batch,D,h,w] * Output: hidden [1,batch,H] cell [1,batch,H] \"\"\" def initializeLSTM(self,feature): with",
"αt = self.SpatialAttn(ηt,st) xt = self.Gate(ηt,xt) # High-level encoder zt = self.HighEncoder(xt) #",
"TVA Decoder Module ------------------ Ref: <NAME>., & <NAME>. (2017). \"Interpretable learning for self-driving",
"* cell ~ [ layers ,batch,H] _,(hidden,cell) = self.lstm(visual,(hidden,cell)) # Control pred[k] =",
"cell state Ref: Xu, Kelvin, et al. \"Show, attend and tell: Neural image",
"~ [ layers ,batch,H] _,(hidden,cell) = self.lstm(visual,(hidden,cell)) # Output vis_[k] = visual #",
"# input LSTM 256 512 self.S = n_state self.n_task = n_task self.sequence_len =",
"list(),list() # State initialization if self.training: st = torch.cuda.FloatTensor(batch_size,self.n_task,self.S).uniform_() else : st =",
"feature.shape[0] _,C,H,W = feature.shape # Batch of Tensor Images is a tensor of",
"[batch,H] cell = self.init_tanh(cell) # [batch,H] cell = cell.unsqueeze(0) # [1,batch,H] # (h,c)",
"torch.flatten(_zt, 1) st, βt, Ft = self.FeatureAttn(_zt,ht[0],cm) # [batch,S] # Dimension reduction to",
"bet_[k] = beta.squeeze() # [1,batch,D] hdd_[k] = hidden[0].unsqueeze(0) # [1,batch,H] if self.study: hc[k]",
"# [batch,H]*[H,H] -> [batch,H] hidden2 = self.init_tanh(hidden2) # [batch,H] cell1 = self.init_Wc1 (feature)",
"layers self.attn = AttentionNet self.ctrl = ControlNet self.lstm = nn.LSTM( input_size = self.R,",
"self.sequence_len n_out = self.n_out if self.training: batch_size = int(feature.shape[0]/sequence_len) else : batch_size =",
"= HighEncoderNet self.SpatialAttn = SpatialNet self.FeatureAttn = FeatureNet self. CmdDecoder = CommandNet self.Gate",
"map = torch.zeros([self.batch_size,self. L ]) # Declare layers self.attn = AttentionNet self.ctrl =",
"= torch.zeros([batch_size,self.L]).to( torch.device('cuda:0') ) bet_ = torch.zeros([batch_size,self.D]).to( torch.device('cuda:0') ) hdd_ = torch.zeros([batch_size,self.H]).to( torch.device('cuda:0')",
"[batch,D,h,w] * Output: hidden [1,batch,H] cell [1,batch,H] \"\"\" def initializeLSTM(self,feature): with torch.no_grad(): #",
"= torch.mean(feature,(2,3)) # [batch,D,h,w] -> [batch,D] hidden = self.init_Wh(feature) # [batch,D]*[D,H] -> [batch,H]",
"( cell1 ) # [batch,H]*[H,H] -> [batch,H] cell2 = self.init_tanh( cell2 ) #",
"[batch,H]*[H,H] -> [batch,H] hidden2 = self.init_tanh(hidden2) # [batch,H] cell1 = self.init_Wc1 (feature) #",
"(h,c) ~ [num_layers, batch, hidden_size] return hidden.contiguous(),cell.contiguous() \"\"\" Forward - eta [batch,channel,high,width] \"\"\"",
"[sequence,batch,L,D] else : sequence = feature # [batch,L,D] # Input to inicialize LSTM",
"self.training: sequence = feature.view(batch_size,sequence_len,self.L,self.D).transpose_(0,1) # [sequence,batch,L,D] else : sequence = feature # [batch,L,D]",
"# [1,batch,H] cell = self.init_Wc(feature) # [batch,D]*[D,H] -> [batch,H] cell = self.init_tanh(cell) #",
"self-driving cars by visualizing causal attention\". In Proceedings of the IEEE international conference",
") alp_ = torch.zeros([sequence_len,batch_size,self.L]).to( torch.device('cuda:0') ) bet_ = torch.zeros([sequence_len,batch_size,self.D]).to( torch.device('cuda:0') ) hdd_ =",
"1)) self.avgpool2 = nn.AdaptiveAvgPool2d((1, 1)) self.normSpa = nn.BatchNorm2d(LowLevelDim) self.ReLU = nn.ReLU() # Initialization",
"n_state self.n_task = n_task self.sequence_len = 20 # Attention self.HighEncoder = HighEncoderNet self.SpatialAttn",
"-------------------- Ref: <NAME>., & <NAME>. (2017). \"Interpretable learning for self-driving cars by visualizing",
"vision (pp. 2942-2950). * Input: feature [batch,L,D] hidden [1,batch,H] * Output: alpha [batch,L,1]",
"2015. * Input: feature [batch,D,h,w] * Output: hidden [1,batch,H] cell [1,batch,H] \"\"\" def",
"torch.device('cuda:0') ) # Study rountime if self.study: action = torch.zeros([self.batch_size,self.H]).to( torch.device('cuda:0') ) atten",
"def forward(self,feature,command): # Parameters sequence_len = self.sequence_len if self.training: batch_size = int(feature.shape[0]/sequence_len) else",
"num_layers=2 ) self.init_Wh1 = nn.Linear(self.D,self.H,bias=True ) self.init_Wh2 = nn.Linear(self.H,self.H,bias=True ) self.init_Wc1 = nn.Linear(self.D,self.H,bias=True",
"\"\"\" Forward - eta [batch,channel,high,width] \"\"\" def forward(self,feature,command): # Parameters sequence_len = self.sequence_len",
"state and cell state Ref: Xu, Kelvin, et al. \"Show, attend and tell:",
"dim=0) β = torch.stack(β, dim=0) F = torch.stack(F, dim=0) return st_, {'hidden': ht_,",
"if self.training: st = torch.cuda.FloatTensor(batch_size,self.n_task,self.S).uniform_() else : st = torch.cuda.FloatTensor( 1,self.n_task,self.S).uniform_() # Study",
"(hidden1) # [batch,H]*[H,H] -> [batch,H] hidden2 = self.init_tanh(hidden2) # [batch,H] cell1 = self.init_Wc1",
"cell.unsqueeze(0) # [1,batch,H] # (h,c) ~ [num_layers, batch, hidden_size] return hidden.contiguous(),cell.contiguous() \"\"\" Forward",
"if self.training: vis_ = torch.zeros([sequence_len,batch_size,self.R]).to( torch.device('cuda:0') ) alp_ = torch.zeros([sequence_len,batch_size,self.L]).to( torch.device('cuda:0') ) bet_",
"Attention self.HighEncoder = HighEncoderNet self.SpatialAttn = SpatialNet self.FeatureAttn = FeatureNet self. CmdDecoder =",
"self. map = torch.zeros([self.batch_size,self. L ]) # Declare layers self.attn = AttentionNet self.ctrl",
"...] # Inicialize hidden state and cell state # * hidden ~ [1,batch,H]",
"if self.study: α,β,F = list(),list(),list() else : α,β,F = None, None, None #",
"# Visual Attention alpha = self.attn(xt,hidden)# [batch,L,1] visual = xt * alpha #",
"hc = None # hc,ha,hb = (None,None,None) # Sequence loop n_range = self.sequence_len",
"= nn.Linear(self.H,self.H,bias=True ) self.init_Wc1 = nn.Linear(self.D,self.H,bias=True ) self.init_Wc2 = nn.Linear(self.H,self.H,bias=True ) self.init_tanh =",
"dim=0).contiguous() # [2,batch,H] cell = torch.stack([ cell1, cell2], dim=0).contiguous() # [2,batch,H] # (h,c)",
"= torch.flatten(rt , 1) rt = rt.unsqueeze(0) # LSTM # * yt ~",
"# 90 # cube_size[1]*cube_size[2] self.R = self.L*self.D # 5760 # self.L*self.D self.H =",
"Ref: <NAME>., & <NAME>. (2017). \"Interpretable learning for self-driving cars by visualizing causal",
"# Control self.pred[k] = self.ctrl(visual, hidden, training=self.training) self. map[k] = alpha.squeeze() if self.training:",
"torch.device('cuda:0') ) else: pred = torch.zeros([batch_size, n_out]).to( torch.device('cuda:0') ) map_ = torch.zeros([batch_size,self.L]).to( torch.device('cuda:0')",
"= torch.stack([ cell1, cell2], dim=0).contiguous() # [2,batch,H] # (h,c) ~ [num_layers, batch, hidden_size]",
"visual.reshape(n_visual,self.R) # [batch,R] visual = visual.unsqueeze(0) # [1,batch,R] # LSTM # * yt",
"nn.Linear(self.H,self.H,bias=True ) self.init_tanh = nn.Tanh() # Initialization torch.nn.init.xavier_uniform_(self.init_Wh1.weight) torch.nn.init.xavier_uniform_(self.init_Wh2.weight) torch.nn.init.xavier_uniform_(self.init_Wc1.weight) torch.nn.init.xavier_uniform_(self.init_Wc2.weight) self.lstm.reset_parameters() \"\"\"",
"-> [batch,H] hidden2 = self.init_tanh(hidden2) # [batch,H] cell1 = self.init_Wc1 (feature) # [batch,D]*[D,H]",
"CatDecoder(nn.Module): \"\"\" Constructor \"\"\" def __init__(self, HighEncoderNet, SpatialNet, FeatureNet, CommandNet, LowLevelDim=128, HighLevelDim=512, n_hidden=1024,",
"# 5760 self.H = n_hidden # 512 self.M = n_hidden # 512 self.sequence_len",
"1 ,L,D] # Visual Attention alpha = self.attn(xt,hidden)# [batch,L,1] visual = xt *",
"import torch import torch.nn as nn from IPython.core.debugger import set_trace import ImitationLearning.VisualAttention.network.Gate as",
"self.SpatialAttn(ηt,st) xt = self.Gate(ηt,xt) # High-level encoder zt = self.HighEncoder(xt) # Feature-based attention",
"= n_hidden # 512 self.sequence_len = 20 self.batch_size = 120 self.n_out = 3",
"# Study rountime if self.study: hc = torch.zeros([self.batch_size,self.H]).to( torch.device('cuda:0') ) else: hc =",
"if self.study: hc = torch.zeros([self.batch_size,self.H]).to( torch.device('cuda:0') ) else: hc = None # hc,ha,hb",
"Output self.dimReduction = nn.Conv2d(HighLevelDim,self.R, kernel_size=1, bias=False) self.lstm = nn.LSTM( input_size = self.R, hidden_size",
"hidden1 = self.init_tanh(hidden1) # [batch,H] hidden2 = self.init_Wh2 (hidden1) # [batch,H]*[H,H] -> [batch,H]",
"hidden_size=self.H, num_layers=2 ) self.init_Wh1 = nn.Linear(self.D,self.H,bias=True ) self.init_Wh2 = nn.Linear(self.H,self.H,bias=True ) self.init_Wc1 =",
"sequence[0].unsqueeze(0) ht,ct = self.initializeLSTM(xt) # Command decoder cmd = self.CmdDecoder(command) if self.training: cmd",
"torch.zeros([self.batch_size,self.H]).to( torch.device('cuda:0') ) atten = torch.zeros([self.batch_size,self.H]).to( torch.device('cuda:0') ) else: action,atten = (None,None) #",
"self.study: action = torch.zeros([self.batch_size,self.H]).to( torch.device('cuda:0') ) atten = torch.zeros([self.batch_size,self.H]).to( torch.device('cuda:0') ) else: action,atten",
"features feature = torch.mean(feature,1) # [batch,L,D] -> [batch,D] hidden = self.init_Wh(feature) # [batch,D]*[D,H]",
"n_state=64,n_task=3, study=False): super(CatDecoder, self).__init__() self.study = study # Parameters self.H = n_hidden #",
"= self.initializeLSTM(xt) # Prediction container if self.training: pred = torch.zeros([sequence_len,batch_size, n_out]).to( torch.device('cuda:0') )",
"if self.training: xt = sequence[0] else : xt = sequence[0].unsqueeze(0) # Inicialize hidden",
"on machine learning. 2015. * Input: feature [batch,L,D] * Output: hidden [1,batch,H] cell",
"# * cell ~ [ layers ,batch,H] _,(hidden,cell) = self.lstm(visual,(hidden,cell)) # Output vis_[k]",
"= int(feature.shape[0]/sequence_len) else : batch_size = feature.shape[0] # Data if self.training: sequence =",
"[batch,D,h,w] -> [batch,D] hidden = self.init_Wh(feature) # [batch,D]*[D,H] -> [batch,H] hidden = self.init_tanh(hidden)",
"self.study: α,β,F = list(),list(),list() else : α,β,F = None, None, None # Sequence",
"\"\"\" Constructor \"\"\" def __init__(self, HighEncoderNet, SpatialNet, FeatureNet, CommandNet, LowLevelDim=128, HighLevelDim=512, n_hidden=1024, n_state=64,n_task=3,",
"torch import torch.nn as nn from IPython.core.debugger import set_trace import ImitationLearning.VisualAttention.network.Gate as G",
"input_size = self.R, hidden_size = self.H, num_layers = 1) self.init_Wh = nn.Linear(self.D,self.H,bias=True )",
"\"\"\" Constructor \"\"\" def __init__(self,AttentionNet,ControlNet,cube_size,n_hidden): super(DualDecoder, self).__init__() # Parameters self.D = cube_size[2] #",
"hidden_size] return hidden,cell \"\"\" Forward \"\"\" def forward(self,feature): # Parameters sequence_len = self.sequence_len",
"Control pred[k] = self.ctrl(visual, hidden[0].unsqueeze(0)) map_[k] = alpha.squeeze() if self.study: action[k] = hidden[0].squeeze()",
"hidden = hidden.unsqueeze(0) # [1,batch,H] cell = self.init_Wc(feature) # [batch,D]*[D,H] -> [batch,H] cell",
"else: pred = torch.zeros([batch_size, n_out]).to( torch.device('cuda:0') ) map_ = torch.zeros([batch_size,self.L]).to( torch.device('cuda:0') ) #",
"= hidden.unsqueeze(0) # [1,batch,H] cell = self.init_Wc(feature) # [batch,D]*[D,H] -> [batch,H] cell =",
"= feature # [batch,L,D] # Input to inicialize LSTM if self.training: xt =",
"self.sequence_len if self.training: batch_size = int(feature.shape[0]/sequence_len) else : batch_size = feature.shape[0] # Data",
"LSTM if self.training: xt = sequence[0] else : xt = sequence[0].unsqueeze(0) # Inicialize",
"self.avgpool2 = nn.AdaptiveAvgPool2d((1, 1)) self.normSpa = nn.BatchNorm2d(LowLevelDim) self.ReLU = nn.ReLU() # Initialization torch.nn.init.xavier_uniform_(self.dimReduction.weight)"
] |
[
"''' <NAME> Email: <EMAIL> ''' def retorna_pessoas_preferem_um_unico_palco(quantidade_pessoas_evento): return int ( 25 / 100",
"<EMAIL> ''' def retorna_pessoas_preferem_um_unico_palco(quantidade_pessoas_evento): return int ( 25 / 100 * quantidade_pessoas_evento )",
"<NAME> Email: <EMAIL> ''' def retorna_pessoas_preferem_um_unico_palco(quantidade_pessoas_evento): return int ( 25 / 100 *",
"Email: <EMAIL> ''' def retorna_pessoas_preferem_um_unico_palco(quantidade_pessoas_evento): return int ( 25 / 100 * quantidade_pessoas_evento"
] |
[
"value=\"tochigi\">Tochigi</option> <option value=\"gunma\">Gunma</option> <option value=\"saitama\">Saitama</option> <option value=\"chiba\">Chiba</option> <option value=\"tokyo\">Tokyo</option> <option value=\"kanagawa\" selected=\"selected\">Kanagawa</option> <option",
"<option value=\"osaka\">Osaka</option> <option value=\"hyogo\">Hyogo</option> <option value=\"nara\">Nara</option> <option value=\"wakayama\">Wakayama</option> <option value=\"tottori\">Tottori</option> <option value=\"shimane\">Shimane</option> <option",
"XXX-XXXX.'] >>> f.clean('251a0032') Traceback (most recent call last): ... ValidationError: [u'Enter a postal",
"value=\"hokkaido\">Hokkaido</option> <option value=\"aomori\">Aomori</option> <option value=\"iwate\">Iwate</option> <option value=\"miyagi\">Miyagi</option> <option value=\"akita\">Akita</option> <option value=\"yamagata\">Yamagata</option> <option value=\"fukushima\">Fukushima</option>",
">>> f = JPPostalCodeField(required=False) >>> f.clean('251-0032') u'2510032' >>> f.clean('2510032') u'2510032' >>> f.clean('2510-032') Traceback",
">>> f.clean(None) u'' # JPPrefectureSelect ############################################################### A Select widget that uses a list",
"code in the format XXXXXXX or XXX-XXXX.'] >>> f.clean('251a0032') Traceback (most recent call",
"value=\"iwate\">Iwate</option> <option value=\"miyagi\">Miyagi</option> <option value=\"akita\">Akita</option> <option value=\"yamagata\">Yamagata</option> <option value=\"fukushima\">Fukushima</option> <option value=\"ibaraki\">Ibaraki</option> <option value=\"tochigi\">Tochigi</option>",
"coding: utf-8 -*- # Tests for the contrib/localflavor/ JP form fields. tests =",
"the format XXXXXXX or XXX-XXXX.'] >>> f.clean('') Traceback (most recent call last): ...",
"<option value=\"tochigi\">Tochigi</option> <option value=\"gunma\">Gunma</option> <option value=\"saitama\">Saitama</option> <option value=\"chiba\">Chiba</option> <option value=\"tokyo\">Tokyo</option> <option value=\"kanagawa\" selected=\"selected\">Kanagawa</option>",
"<filename>tests/regressiontests/forms/localflavor/jp.py # -*- coding: utf-8 -*- # Tests for the contrib/localflavor/ JP form",
"############################################################### A Select widget that uses a list of Japanese prefectures as its",
"Select widget that uses a list of Japanese prefectures as its choices. >>>",
"(most recent call last): ... ValidationError: [u'Enter a postal code in the format",
"ValidationError: [u'Enter a postal code in the format XXXXXXX or XXX-XXXX.'] >>> f.clean('251a0032')",
"JPPostalCodeField(required=False) >>> f.clean('251-0032') u'2510032' >>> f.clean('2510032') u'2510032' >>> f.clean('2510-032') Traceback (most recent call",
"in the format XXXXXXX or XXX-XXXX.'] >>> f.clean('') u'' >>> f.clean(None) u'' #",
"value=\"nagasaki\">Nagasaki</option> <option value=\"kumamoto\">Kumamoto</option> <option value=\"oita\">Oita</option> <option value=\"miyazaki\">Miyazaki</option> <option value=\"kagoshima\">Kagoshima</option> <option value=\"okinawa\">Okinawa</option> </select> \"\"\"",
"django.contrib.localflavor.jp.forms import JPPrefectureSelect >>> w = JPPrefectureSelect() >>> print w.render('prefecture', 'kanagawa') <select name=\"prefecture\">",
"<option value=\"fukuoka\">Fukuoka</option> <option value=\"saga\">Saga</option> <option value=\"nagasaki\">Nagasaki</option> <option value=\"kumamoto\">Kumamoto</option> <option value=\"oita\">Oita</option> <option value=\"miyazaki\">Miyazaki</option> <option",
"or XXX-XXXX.'] >>> f.clean('a51-0032') Traceback (most recent call last): ... ValidationError: [u'Enter a",
"name=\"prefecture\"> <option value=\"hokkaido\">Hokkaido</option> <option value=\"aomori\">Aomori</option> <option value=\"iwate\">Iwate</option> <option value=\"miyagi\">Miyagi</option> <option value=\"akita\">Akita</option> <option value=\"yamagata\">Yamagata</option>",
"value=\"fukui\">Fukui</option> <option value=\"gifu\">Gifu</option> <option value=\"shizuoka\">Shizuoka</option> <option value=\"aichi\">Aichi</option> <option value=\"mie\">Mie</option> <option value=\"shiga\">Shiga</option> <option value=\"kyoto\">Kyoto</option>",
"value=\"miyagi\">Miyagi</option> <option value=\"akita\">Akita</option> <option value=\"yamagata\">Yamagata</option> <option value=\"fukushima\">Fukushima</option> <option value=\"ibaraki\">Ibaraki</option> <option value=\"tochigi\">Tochigi</option> <option value=\"gunma\">Gunma</option>",
"<option value=\"ishikawa\">Ishikawa</option> <option value=\"fukui\">Fukui</option> <option value=\"gifu\">Gifu</option> <option value=\"shizuoka\">Shizuoka</option> <option value=\"aichi\">Aichi</option> <option value=\"mie\">Mie</option> <option",
"in the format XXXXXXX or XXX-XXXX.'] >>> f.clean('251a0032') Traceback (most recent call last):",
"[u'Enter a postal code in the format XXXXXXX or XXX-XXXX.'] >>> f.clean('') u''",
"code in the format XXXXXXX or XXX-XXXX.'] >>> f.clean('') u'' >>> f.clean(None) u''",
"value=\"tottori\">Tottori</option> <option value=\"shimane\">Shimane</option> <option value=\"okayama\">Okayama</option> <option value=\"hiroshima\">Hiroshima</option> <option value=\"yamaguchi\">Yamaguchi</option> <option value=\"tokushima\">Tokushima</option> <option value=\"kagawa\">Kagawa</option>",
"postal code in the format XXXXXXX or XXX-XXXX.'] >>> f.clean('') u'' >>> f.clean(None)",
"= r\"\"\" # JPPostalCodeField ############################################################### A form field that validates its input is",
"<option value=\"tokyo\">Tokyo</option> <option value=\"kanagawa\" selected=\"selected\">Kanagawa</option> <option value=\"yamanashi\">Yamanashi</option> <option value=\"nagano\">Nagano</option> <option value=\"niigata\">Niigata</option> <option value=\"toyama\">Toyama</option>",
"JPPrefectureSelect ############################################################### A Select widget that uses a list of Japanese prefectures as",
"value=\"tokyo\">Tokyo</option> <option value=\"kanagawa\" selected=\"selected\">Kanagawa</option> <option value=\"yamanashi\">Yamanashi</option> <option value=\"nagano\">Nagano</option> <option value=\"niigata\">Niigata</option> <option value=\"toyama\">Toyama</option> <option",
"ValidationError: [u'This field is required.'] >>> f = JPPostalCodeField(required=False) >>> f.clean('251-0032') u'2510032' >>>",
"a postal code in the format XXXXXXX or XXX-XXXX.'] >>> f.clean('a51-0032') Traceback (most",
"<option value=\"fukui\">Fukui</option> <option value=\"gifu\">Gifu</option> <option value=\"shizuoka\">Shizuoka</option> <option value=\"aichi\">Aichi</option> <option value=\"mie\">Mie</option> <option value=\"shiga\">Shiga</option> <option",
"import JPPrefectureSelect >>> w = JPPrefectureSelect() >>> print w.render('prefecture', 'kanagawa') <select name=\"prefecture\"> <option",
"[u'Enter a postal code in the format XXXXXXX or XXX-XXXX.'] >>> f.clean('25100321') Traceback",
"XXX-XXXX.'] >>> f.clean('') Traceback (most recent call last): ... ValidationError: [u'This field is",
"u'' >>> f.clean(None) u'' # JPPrefectureSelect ############################################################### A Select widget that uses a",
"<option value=\"iwate\">Iwate</option> <option value=\"miyagi\">Miyagi</option> <option value=\"akita\">Akita</option> <option value=\"yamagata\">Yamagata</option> <option value=\"fukushima\">Fukushima</option> <option value=\"ibaraki\">Ibaraki</option> <option",
"<option value=\"ibaraki\">Ibaraki</option> <option value=\"tochigi\">Tochigi</option> <option value=\"gunma\">Gunma</option> <option value=\"saitama\">Saitama</option> <option value=\"chiba\">Chiba</option> <option value=\"tokyo\">Tokyo</option> <option",
"<option value=\"kochi\">Kochi</option> <option value=\"fukuoka\">Fukuoka</option> <option value=\"saga\">Saga</option> <option value=\"nagasaki\">Nagasaki</option> <option value=\"kumamoto\">Kumamoto</option> <option value=\"oita\">Oita</option> <option",
"[u'Enter a postal code in the format XXXXXXX or XXX-XXXX.'] >>> f.clean('a51-0032') Traceback",
"value=\"osaka\">Osaka</option> <option value=\"hyogo\">Hyogo</option> <option value=\"nara\">Nara</option> <option value=\"wakayama\">Wakayama</option> <option value=\"tottori\">Tottori</option> <option value=\"shimane\">Shimane</option> <option value=\"okayama\">Okayama</option>",
"<option value=\"nara\">Nara</option> <option value=\"wakayama\">Wakayama</option> <option value=\"tottori\">Tottori</option> <option value=\"shimane\">Shimane</option> <option value=\"okayama\">Okayama</option> <option value=\"hiroshima\">Hiroshima</option> <option",
"# JPPostalCodeField ############################################################### A form field that validates its input is a Japanese",
"<option value=\"akita\">Akita</option> <option value=\"yamagata\">Yamagata</option> <option value=\"fukushima\">Fukushima</option> <option value=\"ibaraki\">Ibaraki</option> <option value=\"tochigi\">Tochigi</option> <option value=\"gunma\">Gunma</option> <option",
"is a Japanese postcode. Accepts 7 digits(with/out hyphen). >>> from django.contrib.localflavor.jp.forms import JPPostalCodeField",
"f.clean('') u'' >>> f.clean(None) u'' # JPPrefectureSelect ############################################################### A Select widget that uses",
"value=\"gunma\">Gunma</option> <option value=\"saitama\">Saitama</option> <option value=\"chiba\">Chiba</option> <option value=\"tokyo\">Tokyo</option> <option value=\"kanagawa\" selected=\"selected\">Kanagawa</option> <option value=\"yamanashi\">Yamanashi</option> <option",
"that validates its input is a Japanese postcode. Accepts 7 digits(with/out hyphen). >>>",
">>> f = JPPostalCodeField() >>> f.clean('251-0032') u'2510032' >>> f.clean('2510032') u'2510032' >>> f.clean('2510-032') Traceback",
"format XXXXXXX or XXX-XXXX.'] >>> f.clean('251a0032') Traceback (most recent call last): ... ValidationError:",
"f.clean('2510-032') Traceback (most recent call last): ... ValidationError: [u'Enter a postal code in",
"print w.render('prefecture', 'kanagawa') <select name=\"prefecture\"> <option value=\"hokkaido\">Hokkaido</option> <option value=\"aomori\">Aomori</option> <option value=\"iwate\">Iwate</option> <option value=\"miyagi\">Miyagi</option>",
"value=\"akita\">Akita</option> <option value=\"yamagata\">Yamagata</option> <option value=\"fukushima\">Fukushima</option> <option value=\"ibaraki\">Ibaraki</option> <option value=\"tochigi\">Tochigi</option> <option value=\"gunma\">Gunma</option> <option value=\"saitama\">Saitama</option>",
"XXXXXXX or XXX-XXXX.'] >>> f.clean('a51-0032') Traceback (most recent call last): ... ValidationError: [u'Enter",
"<option value=\"toyama\">Toyama</option> <option value=\"ishikawa\">Ishikawa</option> <option value=\"fukui\">Fukui</option> <option value=\"gifu\">Gifu</option> <option value=\"shizuoka\">Shizuoka</option> <option value=\"aichi\">Aichi</option> <option",
"value=\"fukuoka\">Fukuoka</option> <option value=\"saga\">Saga</option> <option value=\"nagasaki\">Nagasaki</option> <option value=\"kumamoto\">Kumamoto</option> <option value=\"oita\">Oita</option> <option value=\"miyazaki\">Miyazaki</option> <option value=\"kagoshima\">Kagoshima</option>",
"in the format XXXXXXX or XXX-XXXX.'] >>> f.clean('') Traceback (most recent call last):",
"value=\"hiroshima\">Hiroshima</option> <option value=\"yamaguchi\">Yamaguchi</option> <option value=\"tokushima\">Tokushima</option> <option value=\"kagawa\">Kagawa</option> <option value=\"ehime\">Ehime</option> <option value=\"kochi\">Kochi</option> <option value=\"fukuoka\">Fukuoka</option>",
"value=\"yamagata\">Yamagata</option> <option value=\"fukushima\">Fukushima</option> <option value=\"ibaraki\">Ibaraki</option> <option value=\"tochigi\">Tochigi</option> <option value=\"gunma\">Gunma</option> <option value=\"saitama\">Saitama</option> <option value=\"chiba\">Chiba</option>",
"value=\"yamanashi\">Yamanashi</option> <option value=\"nagano\">Nagano</option> <option value=\"niigata\">Niigata</option> <option value=\"toyama\">Toyama</option> <option value=\"ishikawa\">Ishikawa</option> <option value=\"fukui\">Fukui</option> <option value=\"gifu\">Gifu</option>",
"JPPostalCodeField ############################################################### A form field that validates its input is a Japanese postcode.",
"<option value=\"ehime\">Ehime</option> <option value=\"kochi\">Kochi</option> <option value=\"fukuoka\">Fukuoka</option> <option value=\"saga\">Saga</option> <option value=\"nagasaki\">Nagasaki</option> <option value=\"kumamoto\">Kumamoto</option> <option",
"<option value=\"mie\">Mie</option> <option value=\"shiga\">Shiga</option> <option value=\"kyoto\">Kyoto</option> <option value=\"osaka\">Osaka</option> <option value=\"hyogo\">Hyogo</option> <option value=\"nara\">Nara</option> <option",
"tests = r\"\"\" # JPPostalCodeField ############################################################### A form field that validates its input",
"value=\"ishikawa\">Ishikawa</option> <option value=\"fukui\">Fukui</option> <option value=\"gifu\">Gifu</option> <option value=\"shizuoka\">Shizuoka</option> <option value=\"aichi\">Aichi</option> <option value=\"mie\">Mie</option> <option value=\"shiga\">Shiga</option>",
">>> f.clean('a51-0032') Traceback (most recent call last): ... ValidationError: [u'Enter a postal code",
"r\"\"\" # JPPostalCodeField ############################################################### A form field that validates its input is a",
"django.contrib.localflavor.jp.forms import JPPostalCodeField >>> f = JPPostalCodeField() >>> f.clean('251-0032') u'2510032' >>> f.clean('2510032') u'2510032'",
"value=\"wakayama\">Wakayama</option> <option value=\"tottori\">Tottori</option> <option value=\"shimane\">Shimane</option> <option value=\"okayama\">Okayama</option> <option value=\"hiroshima\">Hiroshima</option> <option value=\"yamaguchi\">Yamaguchi</option> <option value=\"tokushima\">Tokushima</option>",
"its input is a Japanese postcode. Accepts 7 digits(with/out hyphen). >>> from django.contrib.localflavor.jp.forms",
"format XXXXXXX or XXX-XXXX.'] >>> f.clean('') u'' >>> f.clean(None) u'' # JPPrefectureSelect ###############################################################",
"<option value=\"niigata\">Niigata</option> <option value=\"toyama\">Toyama</option> <option value=\"ishikawa\">Ishikawa</option> <option value=\"fukui\">Fukui</option> <option value=\"gifu\">Gifu</option> <option value=\"shizuoka\">Shizuoka</option> <option",
"[u'Enter a postal code in the format XXXXXXX or XXX-XXXX.'] >>> f.clean('251a0032') Traceback",
"prefectures as its choices. >>> from django.contrib.localflavor.jp.forms import JPPrefectureSelect >>> w = JPPrefectureSelect()",
"= JPPostalCodeField(required=False) >>> f.clean('251-0032') u'2510032' >>> f.clean('2510032') u'2510032' >>> f.clean('2510-032') Traceback (most recent",
"f.clean('251a0032') Traceback (most recent call last): ... ValidationError: [u'Enter a postal code in",
"or XXX-XXXX.'] >>> f.clean('251a0032') Traceback (most recent call last): ... ValidationError: [u'Enter a",
"format XXXXXXX or XXX-XXXX.'] >>> f.clean('a51-0032') Traceback (most recent call last): ... ValidationError:",
"fields. tests = r\"\"\" # JPPostalCodeField ############################################################### A form field that validates its",
">>> from django.contrib.localflavor.jp.forms import JPPrefectureSelect >>> w = JPPrefectureSelect() >>> print w.render('prefecture', 'kanagawa')",
"u'' # JPPrefectureSelect ############################################################### A Select widget that uses a list of Japanese",
">>> w = JPPrefectureSelect() >>> print w.render('prefecture', 'kanagawa') <select name=\"prefecture\"> <option value=\"hokkaido\">Hokkaido</option> <option",
"value=\"fukushima\">Fukushima</option> <option value=\"ibaraki\">Ibaraki</option> <option value=\"tochigi\">Tochigi</option> <option value=\"gunma\">Gunma</option> <option value=\"saitama\">Saitama</option> <option value=\"chiba\">Chiba</option> <option value=\"tokyo\">Tokyo</option>",
"<option value=\"saitama\">Saitama</option> <option value=\"chiba\">Chiba</option> <option value=\"tokyo\">Tokyo</option> <option value=\"kanagawa\" selected=\"selected\">Kanagawa</option> <option value=\"yamanashi\">Yamanashi</option> <option value=\"nagano\">Nagano</option>",
"value=\"saga\">Saga</option> <option value=\"nagasaki\">Nagasaki</option> <option value=\"kumamoto\">Kumamoto</option> <option value=\"oita\">Oita</option> <option value=\"miyazaki\">Miyazaki</option> <option value=\"kagoshima\">Kagoshima</option> <option value=\"okinawa\">Okinawa</option>",
"(most recent call last): ... ValidationError: [u'This field is required.'] >>> f =",
"a postal code in the format XXXXXXX or XXX-XXXX.'] >>> f.clean('251a0032') Traceback (most",
"Accepts 7 digits(with/out hyphen). >>> from django.contrib.localflavor.jp.forms import JPPostalCodeField >>> f = JPPostalCodeField()",
"widget that uses a list of Japanese prefectures as its choices. >>> from",
"call last): ... ValidationError: [u'Enter a postal code in the format XXXXXXX or",
"XXX-XXXX.'] >>> f.clean('25100321') Traceback (most recent call last): ... ValidationError: [u'Enter a postal",
"XXXXXXX or XXX-XXXX.'] >>> f.clean('') u'' >>> f.clean(None) u'' # JPPrefectureSelect ############################################################### A",
"JPPostalCodeField() >>> f.clean('251-0032') u'2510032' >>> f.clean('2510032') u'2510032' >>> f.clean('2510-032') Traceback (most recent call",
"form fields. tests = r\"\"\" # JPPostalCodeField ############################################################### A form field that validates",
">>> f.clean('25100321') Traceback (most recent call last): ... ValidationError: [u'Enter a postal code",
"<option value=\"aichi\">Aichi</option> <option value=\"mie\">Mie</option> <option value=\"shiga\">Shiga</option> <option value=\"kyoto\">Kyoto</option> <option value=\"osaka\">Osaka</option> <option value=\"hyogo\">Hyogo</option> <option",
"hyphen). >>> from django.contrib.localflavor.jp.forms import JPPostalCodeField >>> f = JPPostalCodeField() >>> f.clean('251-0032') u'2510032'",
"value=\"toyama\">Toyama</option> <option value=\"ishikawa\">Ishikawa</option> <option value=\"fukui\">Fukui</option> <option value=\"gifu\">Gifu</option> <option value=\"shizuoka\">Shizuoka</option> <option value=\"aichi\">Aichi</option> <option value=\"mie\">Mie</option>",
"value=\"chiba\">Chiba</option> <option value=\"tokyo\">Tokyo</option> <option value=\"kanagawa\" selected=\"selected\">Kanagawa</option> <option value=\"yamanashi\">Yamanashi</option> <option value=\"nagano\">Nagano</option> <option value=\"niigata\">Niigata</option> <option",
"f = JPPostalCodeField() >>> f.clean('251-0032') u'2510032' >>> f.clean('2510032') u'2510032' >>> f.clean('2510-032') Traceback (most",
"value=\"kyoto\">Kyoto</option> <option value=\"osaka\">Osaka</option> <option value=\"hyogo\">Hyogo</option> <option value=\"nara\">Nara</option> <option value=\"wakayama\">Wakayama</option> <option value=\"tottori\">Tottori</option> <option value=\"shimane\">Shimane</option>",
"required.'] >>> f = JPPostalCodeField(required=False) >>> f.clean('251-0032') u'2510032' >>> f.clean('2510032') u'2510032' >>> f.clean('2510-032')",
"value=\"ehime\">Ehime</option> <option value=\"kochi\">Kochi</option> <option value=\"fukuoka\">Fukuoka</option> <option value=\"saga\">Saga</option> <option value=\"nagasaki\">Nagasaki</option> <option value=\"kumamoto\">Kumamoto</option> <option value=\"oita\">Oita</option>",
"digits(with/out hyphen). >>> from django.contrib.localflavor.jp.forms import JPPostalCodeField >>> f = JPPostalCodeField() >>> f.clean('251-0032')",
"the format XXXXXXX or XXX-XXXX.'] >>> f.clean('a51-0032') Traceback (most recent call last): ...",
"f.clean('251-0032') u'2510032' >>> f.clean('2510032') u'2510032' >>> f.clean('2510-032') Traceback (most recent call last): ...",
"input is a Japanese postcode. Accepts 7 digits(with/out hyphen). >>> from django.contrib.localflavor.jp.forms import",
"the format XXXXXXX or XXX-XXXX.'] >>> f.clean('25100321') Traceback (most recent call last): ...",
"recent call last): ... ValidationError: [u'This field is required.'] >>> f = JPPostalCodeField(required=False)",
"# JPPrefectureSelect ############################################################### A Select widget that uses a list of Japanese prefectures",
"############################################################### A form field that validates its input is a Japanese postcode. Accepts",
"<option value=\"chiba\">Chiba</option> <option value=\"tokyo\">Tokyo</option> <option value=\"kanagawa\" selected=\"selected\">Kanagawa</option> <option value=\"yamanashi\">Yamanashi</option> <option value=\"nagano\">Nagano</option> <option value=\"niigata\">Niigata</option>",
"<option value=\"kanagawa\" selected=\"selected\">Kanagawa</option> <option value=\"yamanashi\">Yamanashi</option> <option value=\"nagano\">Nagano</option> <option value=\"niigata\">Niigata</option> <option value=\"toyama\">Toyama</option> <option value=\"ishikawa\">Ishikawa</option>",
"<option value=\"tokushima\">Tokushima</option> <option value=\"kagawa\">Kagawa</option> <option value=\"ehime\">Ehime</option> <option value=\"kochi\">Kochi</option> <option value=\"fukuoka\">Fukuoka</option> <option value=\"saga\">Saga</option> <option",
"or XXX-XXXX.'] >>> f.clean('25100321') Traceback (most recent call last): ... ValidationError: [u'Enter a",
"value=\"niigata\">Niigata</option> <option value=\"toyama\">Toyama</option> <option value=\"ishikawa\">Ishikawa</option> <option value=\"fukui\">Fukui</option> <option value=\"gifu\">Gifu</option> <option value=\"shizuoka\">Shizuoka</option> <option value=\"aichi\">Aichi</option>",
"import JPPostalCodeField >>> f = JPPostalCodeField() >>> f.clean('251-0032') u'2510032' >>> f.clean('2510032') u'2510032' >>>",
"of Japanese prefectures as its choices. >>> from django.contrib.localflavor.jp.forms import JPPrefectureSelect >>> w",
"value=\"aomori\">Aomori</option> <option value=\"iwate\">Iwate</option> <option value=\"miyagi\">Miyagi</option> <option value=\"akita\">Akita</option> <option value=\"yamagata\">Yamagata</option> <option value=\"fukushima\">Fukushima</option> <option value=\"ibaraki\">Ibaraki</option>",
"... ValidationError: [u'This field is required.'] >>> f = JPPostalCodeField(required=False) >>> f.clean('251-0032') u'2510032'",
"w = JPPrefectureSelect() >>> print w.render('prefecture', 'kanagawa') <select name=\"prefecture\"> <option value=\"hokkaido\">Hokkaido</option> <option value=\"aomori\">Aomori</option>",
"<option value=\"nagano\">Nagano</option> <option value=\"niigata\">Niigata</option> <option value=\"toyama\">Toyama</option> <option value=\"ishikawa\">Ishikawa</option> <option value=\"fukui\">Fukui</option> <option value=\"gifu\">Gifu</option> <option",
"JP form fields. tests = r\"\"\" # JPPostalCodeField ############################################################### A form field that",
"postal code in the format XXXXXXX or XXX-XXXX.'] >>> f.clean('251a0032') Traceback (most recent",
"Japanese postcode. Accepts 7 digits(with/out hyphen). >>> from django.contrib.localflavor.jp.forms import JPPostalCodeField >>> f",
">>> f.clean('251-0032') u'2510032' >>> f.clean('2510032') u'2510032' >>> f.clean('2510-032') Traceback (most recent call last):",
"<option value=\"saga\">Saga</option> <option value=\"nagasaki\">Nagasaki</option> <option value=\"kumamoto\">Kumamoto</option> <option value=\"oita\">Oita</option> <option value=\"miyazaki\">Miyazaki</option> <option value=\"kagoshima\">Kagoshima</option> <option",
"format XXXXXXX or XXX-XXXX.'] >>> f.clean('25100321') Traceback (most recent call last): ... ValidationError:",
"f.clean('a51-0032') Traceback (most recent call last): ... ValidationError: [u'Enter a postal code in",
"'kanagawa') <select name=\"prefecture\"> <option value=\"hokkaido\">Hokkaido</option> <option value=\"aomori\">Aomori</option> <option value=\"iwate\">Iwate</option> <option value=\"miyagi\">Miyagi</option> <option value=\"akita\">Akita</option>",
"code in the format XXXXXXX or XXX-XXXX.'] >>> f.clean('25100321') Traceback (most recent call",
"list of Japanese prefectures as its choices. >>> from django.contrib.localflavor.jp.forms import JPPrefectureSelect >>>",
"-*- # Tests for the contrib/localflavor/ JP form fields. tests = r\"\"\" #",
">>> f.clean('') Traceback (most recent call last): ... ValidationError: [u'This field is required.']",
"value=\"shiga\">Shiga</option> <option value=\"kyoto\">Kyoto</option> <option value=\"osaka\">Osaka</option> <option value=\"hyogo\">Hyogo</option> <option value=\"nara\">Nara</option> <option value=\"wakayama\">Wakayama</option> <option value=\"tottori\">Tottori</option>",
"u'2510032' >>> f.clean('2510032') u'2510032' >>> f.clean('2510-032') Traceback (most recent call last): ... ValidationError:",
"field is required.'] >>> f = JPPostalCodeField(required=False) >>> f.clean('251-0032') u'2510032' >>> f.clean('2510032') u'2510032'",
"<option value=\"tottori\">Tottori</option> <option value=\"shimane\">Shimane</option> <option value=\"okayama\">Okayama</option> <option value=\"hiroshima\">Hiroshima</option> <option value=\"yamaguchi\">Yamaguchi</option> <option value=\"tokushima\">Tokushima</option> <option",
"u'2510032' >>> f.clean('2510-032') Traceback (most recent call last): ... ValidationError: [u'Enter a postal",
"<option value=\"aomori\">Aomori</option> <option value=\"iwate\">Iwate</option> <option value=\"miyagi\">Miyagi</option> <option value=\"akita\">Akita</option> <option value=\"yamagata\">Yamagata</option> <option value=\"fukushima\">Fukushima</option> <option",
"<option value=\"shizuoka\">Shizuoka</option> <option value=\"aichi\">Aichi</option> <option value=\"mie\">Mie</option> <option value=\"shiga\">Shiga</option> <option value=\"kyoto\">Kyoto</option> <option value=\"osaka\">Osaka</option> <option",
"utf-8 -*- # Tests for the contrib/localflavor/ JP form fields. tests = r\"\"\"",
"<option value=\"fukushima\">Fukushima</option> <option value=\"ibaraki\">Ibaraki</option> <option value=\"tochigi\">Tochigi</option> <option value=\"gunma\">Gunma</option> <option value=\"saitama\">Saitama</option> <option value=\"chiba\">Chiba</option> <option",
"value=\"tokushima\">Tokushima</option> <option value=\"kagawa\">Kagawa</option> <option value=\"ehime\">Ehime</option> <option value=\"kochi\">Kochi</option> <option value=\"fukuoka\">Fukuoka</option> <option value=\"saga\">Saga</option> <option value=\"nagasaki\">Nagasaki</option>",
"postcode. Accepts 7 digits(with/out hyphen). >>> from django.contrib.localflavor.jp.forms import JPPostalCodeField >>> f =",
"a postal code in the format XXXXXXX or XXX-XXXX.'] >>> f.clean('') u'' >>>",
"value=\"yamaguchi\">Yamaguchi</option> <option value=\"tokushima\">Tokushima</option> <option value=\"kagawa\">Kagawa</option> <option value=\"ehime\">Ehime</option> <option value=\"kochi\">Kochi</option> <option value=\"fukuoka\">Fukuoka</option> <option value=\"saga\">Saga</option>",
"XXXXXXX or XXX-XXXX.'] >>> f.clean('25100321') Traceback (most recent call last): ... ValidationError: [u'Enter",
"value=\"kochi\">Kochi</option> <option value=\"fukuoka\">Fukuoka</option> <option value=\"saga\">Saga</option> <option value=\"nagasaki\">Nagasaki</option> <option value=\"kumamoto\">Kumamoto</option> <option value=\"oita\">Oita</option> <option value=\"miyazaki\">Miyazaki</option>",
"<option value=\"miyagi\">Miyagi</option> <option value=\"akita\">Akita</option> <option value=\"yamagata\">Yamagata</option> <option value=\"fukushima\">Fukushima</option> <option value=\"ibaraki\">Ibaraki</option> <option value=\"tochigi\">Tochigi</option> <option",
"in the format XXXXXXX or XXX-XXXX.'] >>> f.clean('25100321') Traceback (most recent call last):",
"... ValidationError: [u'Enter a postal code in the format XXXXXXX or XXX-XXXX.'] >>>",
"call last): ... ValidationError: [u'This field is required.'] >>> f = JPPostalCodeField(required=False) >>>",
"ValidationError: [u'Enter a postal code in the format XXXXXXX or XXX-XXXX.'] >>> f.clean('25100321')",
"is required.'] >>> f = JPPostalCodeField(required=False) >>> f.clean('251-0032') u'2510032' >>> f.clean('2510032') u'2510032' >>>",
"a list of Japanese prefectures as its choices. >>> from django.contrib.localflavor.jp.forms import JPPrefectureSelect",
"for the contrib/localflavor/ JP form fields. tests = r\"\"\" # JPPostalCodeField ############################################################### A",
"-*- coding: utf-8 -*- # Tests for the contrib/localflavor/ JP form fields. tests",
"Traceback (most recent call last): ... ValidationError: [u'Enter a postal code in the",
"JPPostalCodeField >>> f = JPPostalCodeField() >>> f.clean('251-0032') u'2510032' >>> f.clean('2510032') u'2510032' >>> f.clean('2510-032')",
"<option value=\"kyoto\">Kyoto</option> <option value=\"osaka\">Osaka</option> <option value=\"hyogo\">Hyogo</option> <option value=\"nara\">Nara</option> <option value=\"wakayama\">Wakayama</option> <option value=\"tottori\">Tottori</option> <option",
"value=\"saitama\">Saitama</option> <option value=\"chiba\">Chiba</option> <option value=\"tokyo\">Tokyo</option> <option value=\"kanagawa\" selected=\"selected\">Kanagawa</option> <option value=\"yamanashi\">Yamanashi</option> <option value=\"nagano\">Nagano</option> <option",
"A form field that validates its input is a Japanese postcode. Accepts 7",
"choices. >>> from django.contrib.localflavor.jp.forms import JPPrefectureSelect >>> w = JPPrefectureSelect() >>> print w.render('prefecture',",
"XXX-XXXX.'] >>> f.clean('') u'' >>> f.clean(None) u'' # JPPrefectureSelect ############################################################### A Select widget",
"<option value=\"okayama\">Okayama</option> <option value=\"hiroshima\">Hiroshima</option> <option value=\"yamaguchi\">Yamaguchi</option> <option value=\"tokushima\">Tokushima</option> <option value=\"kagawa\">Kagawa</option> <option value=\"ehime\">Ehime</option> <option",
"f.clean('2510032') u'2510032' >>> f.clean('2510-032') Traceback (most recent call last): ... ValidationError: [u'Enter a",
"the format XXXXXXX or XXX-XXXX.'] >>> f.clean('251a0032') Traceback (most recent call last): ...",
"value=\"gifu\">Gifu</option> <option value=\"shizuoka\">Shizuoka</option> <option value=\"aichi\">Aichi</option> <option value=\"mie\">Mie</option> <option value=\"shiga\">Shiga</option> <option value=\"kyoto\">Kyoto</option> <option value=\"osaka\">Osaka</option>",
">>> f.clean('251a0032') Traceback (most recent call last): ... ValidationError: [u'Enter a postal code",
"contrib/localflavor/ JP form fields. tests = r\"\"\" # JPPostalCodeField ############################################################### A form field",
"Traceback (most recent call last): ... ValidationError: [u'This field is required.'] >>> f",
"Japanese prefectures as its choices. >>> from django.contrib.localflavor.jp.forms import JPPrefectureSelect >>> w =",
"# -*- coding: utf-8 -*- # Tests for the contrib/localflavor/ JP form fields.",
"ValidationError: [u'Enter a postal code in the format XXXXXXX or XXX-XXXX.'] >>> f.clean('a51-0032')",
"recent call last): ... ValidationError: [u'Enter a postal code in the format XXXXXXX",
"f = JPPostalCodeField(required=False) >>> f.clean('251-0032') u'2510032' >>> f.clean('2510032') u'2510032' >>> f.clean('2510-032') Traceback (most",
">>> from django.contrib.localflavor.jp.forms import JPPostalCodeField >>> f = JPPostalCodeField() >>> f.clean('251-0032') u'2510032' >>>",
"the format XXXXXXX or XXX-XXXX.'] >>> f.clean('') u'' >>> f.clean(None) u'' # JPPrefectureSelect",
">>> print w.render('prefecture', 'kanagawa') <select name=\"prefecture\"> <option value=\"hokkaido\">Hokkaido</option> <option value=\"aomori\">Aomori</option> <option value=\"iwate\">Iwate</option> <option",
"<option value=\"hiroshima\">Hiroshima</option> <option value=\"yamaguchi\">Yamaguchi</option> <option value=\"tokushima\">Tokushima</option> <option value=\"kagawa\">Kagawa</option> <option value=\"ehime\">Ehime</option> <option value=\"kochi\">Kochi</option> <option",
"last): ... ValidationError: [u'Enter a postal code in the format XXXXXXX or XXX-XXXX.']",
"value=\"nagano\">Nagano</option> <option value=\"niigata\">Niigata</option> <option value=\"toyama\">Toyama</option> <option value=\"ishikawa\">Ishikawa</option> <option value=\"fukui\">Fukui</option> <option value=\"gifu\">Gifu</option> <option value=\"shizuoka\">Shizuoka</option>",
"<option value=\"shiga\">Shiga</option> <option value=\"kyoto\">Kyoto</option> <option value=\"osaka\">Osaka</option> <option value=\"hyogo\">Hyogo</option> <option value=\"nara\">Nara</option> <option value=\"wakayama\">Wakayama</option> <option",
"value=\"shimane\">Shimane</option> <option value=\"okayama\">Okayama</option> <option value=\"hiroshima\">Hiroshima</option> <option value=\"yamaguchi\">Yamaguchi</option> <option value=\"tokushima\">Tokushima</option> <option value=\"kagawa\">Kagawa</option> <option value=\"ehime\">Ehime</option>",
"code in the format XXXXXXX or XXX-XXXX.'] >>> f.clean('') Traceback (most recent call",
"or XXX-XXXX.'] >>> f.clean('') u'' >>> f.clean(None) u'' # JPPrefectureSelect ############################################################### A Select",
"validates its input is a Japanese postcode. Accepts 7 digits(with/out hyphen). >>> from",
"XXXXXXX or XXX-XXXX.'] >>> f.clean('') Traceback (most recent call last): ... ValidationError: [u'This",
"as its choices. >>> from django.contrib.localflavor.jp.forms import JPPrefectureSelect >>> w = JPPrefectureSelect() >>>",
"[u'Enter a postal code in the format XXXXXXX or XXX-XXXX.'] >>> f.clean('') Traceback",
">>> f.clean('') u'' >>> f.clean(None) u'' # JPPrefectureSelect ############################################################### A Select widget that",
"<option value=\"yamagata\">Yamagata</option> <option value=\"fukushima\">Fukushima</option> <option value=\"ibaraki\">Ibaraki</option> <option value=\"tochigi\">Tochigi</option> <option value=\"gunma\">Gunma</option> <option value=\"saitama\">Saitama</option> <option",
"<option value=\"gifu\">Gifu</option> <option value=\"shizuoka\">Shizuoka</option> <option value=\"aichi\">Aichi</option> <option value=\"mie\">Mie</option> <option value=\"shiga\">Shiga</option> <option value=\"kyoto\">Kyoto</option> <option",
"<option value=\"hyogo\">Hyogo</option> <option value=\"nara\">Nara</option> <option value=\"wakayama\">Wakayama</option> <option value=\"tottori\">Tottori</option> <option value=\"shimane\">Shimane</option> <option value=\"okayama\">Okayama</option> <option",
"a postal code in the format XXXXXXX or XXX-XXXX.'] >>> f.clean('25100321') Traceback (most",
">>> f.clean('2510-032') Traceback (most recent call last): ... ValidationError: [u'Enter a postal code",
"format XXXXXXX or XXX-XXXX.'] >>> f.clean('') Traceback (most recent call last): ... ValidationError:",
"postal code in the format XXXXXXX or XXX-XXXX.'] >>> f.clean('') Traceback (most recent",
"in the format XXXXXXX or XXX-XXXX.'] >>> f.clean('a51-0032') Traceback (most recent call last):",
"A Select widget that uses a list of Japanese prefectures as its choices.",
"value=\"hyogo\">Hyogo</option> <option value=\"nara\">Nara</option> <option value=\"wakayama\">Wakayama</option> <option value=\"tottori\">Tottori</option> <option value=\"shimane\">Shimane</option> <option value=\"okayama\">Okayama</option> <option value=\"hiroshima\">Hiroshima</option>",
"<option value=\"yamanashi\">Yamanashi</option> <option value=\"nagano\">Nagano</option> <option value=\"niigata\">Niigata</option> <option value=\"toyama\">Toyama</option> <option value=\"ishikawa\">Ishikawa</option> <option value=\"fukui\">Fukui</option> <option",
"<option value=\"gunma\">Gunma</option> <option value=\"saitama\">Saitama</option> <option value=\"chiba\">Chiba</option> <option value=\"tokyo\">Tokyo</option> <option value=\"kanagawa\" selected=\"selected\">Kanagawa</option> <option value=\"yamanashi\">Yamanashi</option>",
"postal code in the format XXXXXXX or XXX-XXXX.'] >>> f.clean('a51-0032') Traceback (most recent",
"postal code in the format XXXXXXX or XXX-XXXX.'] >>> f.clean('25100321') Traceback (most recent",
"<option value=\"yamaguchi\">Yamaguchi</option> <option value=\"tokushima\">Tokushima</option> <option value=\"kagawa\">Kagawa</option> <option value=\"ehime\">Ehime</option> <option value=\"kochi\">Kochi</option> <option value=\"fukuoka\">Fukuoka</option> <option",
"from django.contrib.localflavor.jp.forms import JPPrefectureSelect >>> w = JPPrefectureSelect() >>> print w.render('prefecture', 'kanagawa') <select",
"<option value=\"nagasaki\">Nagasaki</option> <option value=\"kumamoto\">Kumamoto</option> <option value=\"oita\">Oita</option> <option value=\"miyazaki\">Miyazaki</option> <option value=\"kagoshima\">Kagoshima</option> <option value=\"okinawa\">Okinawa</option> </select>",
"last): ... ValidationError: [u'This field is required.'] >>> f = JPPostalCodeField(required=False) >>> f.clean('251-0032')",
"value=\"shizuoka\">Shizuoka</option> <option value=\"aichi\">Aichi</option> <option value=\"mie\">Mie</option> <option value=\"shiga\">Shiga</option> <option value=\"kyoto\">Kyoto</option> <option value=\"osaka\">Osaka</option> <option value=\"hyogo\">Hyogo</option>",
"XXXXXXX or XXX-XXXX.'] >>> f.clean('251a0032') Traceback (most recent call last): ... ValidationError: [u'Enter",
"or XXX-XXXX.'] >>> f.clean('') Traceback (most recent call last): ... ValidationError: [u'This field",
"selected=\"selected\">Kanagawa</option> <option value=\"yamanashi\">Yamanashi</option> <option value=\"nagano\">Nagano</option> <option value=\"niigata\">Niigata</option> <option value=\"toyama\">Toyama</option> <option value=\"ishikawa\">Ishikawa</option> <option value=\"fukui\">Fukui</option>",
"<option value=\"shimane\">Shimane</option> <option value=\"okayama\">Okayama</option> <option value=\"hiroshima\">Hiroshima</option> <option value=\"yamaguchi\">Yamaguchi</option> <option value=\"tokushima\">Tokushima</option> <option value=\"kagawa\">Kagawa</option> <option",
"value=\"kanagawa\" selected=\"selected\">Kanagawa</option> <option value=\"yamanashi\">Yamanashi</option> <option value=\"nagano\">Nagano</option> <option value=\"niigata\">Niigata</option> <option value=\"toyama\">Toyama</option> <option value=\"ishikawa\">Ishikawa</option> <option",
"the contrib/localflavor/ JP form fields. tests = r\"\"\" # JPPostalCodeField ############################################################### A form",
"code in the format XXXXXXX or XXX-XXXX.'] >>> f.clean('a51-0032') Traceback (most recent call",
"ValidationError: [u'Enter a postal code in the format XXXXXXX or XXX-XXXX.'] >>> f.clean('')",
"that uses a list of Japanese prefectures as its choices. >>> from django.contrib.localflavor.jp.forms",
"JPPrefectureSelect() >>> print w.render('prefecture', 'kanagawa') <select name=\"prefecture\"> <option value=\"hokkaido\">Hokkaido</option> <option value=\"aomori\">Aomori</option> <option value=\"iwate\">Iwate</option>",
"field that validates its input is a Japanese postcode. Accepts 7 digits(with/out hyphen).",
"uses a list of Japanese prefectures as its choices. >>> from django.contrib.localflavor.jp.forms import",
"<option value=\"kagawa\">Kagawa</option> <option value=\"ehime\">Ehime</option> <option value=\"kochi\">Kochi</option> <option value=\"fukuoka\">Fukuoka</option> <option value=\"saga\">Saga</option> <option value=\"nagasaki\">Nagasaki</option> <option",
"XXX-XXXX.'] >>> f.clean('a51-0032') Traceback (most recent call last): ... ValidationError: [u'Enter a postal",
"f.clean(None) u'' # JPPrefectureSelect ############################################################### A Select widget that uses a list of",
"from django.contrib.localflavor.jp.forms import JPPostalCodeField >>> f = JPPostalCodeField() >>> f.clean('251-0032') u'2510032' >>> f.clean('2510032')",
">>> f.clean('2510032') u'2510032' >>> f.clean('2510-032') Traceback (most recent call last): ... ValidationError: [u'Enter",
"a postal code in the format XXXXXXX or XXX-XXXX.'] >>> f.clean('') Traceback (most",
"its choices. >>> from django.contrib.localflavor.jp.forms import JPPrefectureSelect >>> w = JPPrefectureSelect() >>> print",
"value=\"nara\">Nara</option> <option value=\"wakayama\">Wakayama</option> <option value=\"tottori\">Tottori</option> <option value=\"shimane\">Shimane</option> <option value=\"okayama\">Okayama</option> <option value=\"hiroshima\">Hiroshima</option> <option value=\"yamaguchi\">Yamaguchi</option>",
"value=\"aichi\">Aichi</option> <option value=\"mie\">Mie</option> <option value=\"shiga\">Shiga</option> <option value=\"kyoto\">Kyoto</option> <option value=\"osaka\">Osaka</option> <option value=\"hyogo\">Hyogo</option> <option value=\"nara\">Nara</option>",
"[u'This field is required.'] >>> f = JPPostalCodeField(required=False) >>> f.clean('251-0032') u'2510032' >>> f.clean('2510032')",
"Tests for the contrib/localflavor/ JP form fields. tests = r\"\"\" # JPPostalCodeField ###############################################################",
"<select name=\"prefecture\"> <option value=\"hokkaido\">Hokkaido</option> <option value=\"aomori\">Aomori</option> <option value=\"iwate\">Iwate</option> <option value=\"miyagi\">Miyagi</option> <option value=\"akita\">Akita</option> <option",
"= JPPrefectureSelect() >>> print w.render('prefecture', 'kanagawa') <select name=\"prefecture\"> <option value=\"hokkaido\">Hokkaido</option> <option value=\"aomori\">Aomori</option> <option",
"value=\"ibaraki\">Ibaraki</option> <option value=\"tochigi\">Tochigi</option> <option value=\"gunma\">Gunma</option> <option value=\"saitama\">Saitama</option> <option value=\"chiba\">Chiba</option> <option value=\"tokyo\">Tokyo</option> <option value=\"kanagawa\"",
"# Tests for the contrib/localflavor/ JP form fields. tests = r\"\"\" # JPPostalCodeField",
"<option value=\"hokkaido\">Hokkaido</option> <option value=\"aomori\">Aomori</option> <option value=\"iwate\">Iwate</option> <option value=\"miyagi\">Miyagi</option> <option value=\"akita\">Akita</option> <option value=\"yamagata\">Yamagata</option> <option",
"value=\"mie\">Mie</option> <option value=\"shiga\">Shiga</option> <option value=\"kyoto\">Kyoto</option> <option value=\"osaka\">Osaka</option> <option value=\"hyogo\">Hyogo</option> <option value=\"nara\">Nara</option> <option value=\"wakayama\">Wakayama</option>",
"form field that validates its input is a Japanese postcode. Accepts 7 digits(with/out",
"value=\"kagawa\">Kagawa</option> <option value=\"ehime\">Ehime</option> <option value=\"kochi\">Kochi</option> <option value=\"fukuoka\">Fukuoka</option> <option value=\"saga\">Saga</option> <option value=\"nagasaki\">Nagasaki</option> <option value=\"kumamoto\">Kumamoto</option>",
"f.clean('') Traceback (most recent call last): ... ValidationError: [u'This field is required.'] >>>",
"w.render('prefecture', 'kanagawa') <select name=\"prefecture\"> <option value=\"hokkaido\">Hokkaido</option> <option value=\"aomori\">Aomori</option> <option value=\"iwate\">Iwate</option> <option value=\"miyagi\">Miyagi</option> <option",
"JPPrefectureSelect >>> w = JPPrefectureSelect() >>> print w.render('prefecture', 'kanagawa') <select name=\"prefecture\"> <option value=\"hokkaido\">Hokkaido</option>",
"= JPPostalCodeField() >>> f.clean('251-0032') u'2510032' >>> f.clean('2510032') u'2510032' >>> f.clean('2510-032') Traceback (most recent",
"7 digits(with/out hyphen). >>> from django.contrib.localflavor.jp.forms import JPPostalCodeField >>> f = JPPostalCodeField() >>>",
"value=\"okayama\">Okayama</option> <option value=\"hiroshima\">Hiroshima</option> <option value=\"yamaguchi\">Yamaguchi</option> <option value=\"tokushima\">Tokushima</option> <option value=\"kagawa\">Kagawa</option> <option value=\"ehime\">Ehime</option> <option value=\"kochi\">Kochi</option>",
"f.clean('25100321') Traceback (most recent call last): ... ValidationError: [u'Enter a postal code in",
"<option value=\"wakayama\">Wakayama</option> <option value=\"tottori\">Tottori</option> <option value=\"shimane\">Shimane</option> <option value=\"okayama\">Okayama</option> <option value=\"hiroshima\">Hiroshima</option> <option value=\"yamaguchi\">Yamaguchi</option> <option",
"a Japanese postcode. Accepts 7 digits(with/out hyphen). >>> from django.contrib.localflavor.jp.forms import JPPostalCodeField >>>"
] |
[] |
[
"import csv import numpy as np def generate_training_data(folder): r=0 print(\"Generating encodings for db",
"en=face_recognition.face_encodings(known_img)[0] except: print(\"can't generate encodings for \"+img_name+\", give another image\") pass #en=np.array(en) for",
"generate encodings for \"+img_name+\", give another image\") pass #en=np.array(en) for e in en:",
"known_img=face_recognition.load_image_file(img) try: en=face_recognition.face_encodings(known_img)[0] except: print(\"can't generate encodings for \"+img_name+\", give another image\") pass",
"face_recognition import glob import csv import numpy as np def generate_training_data(folder): r=0 print(\"Generating",
"csvfile = \"Encodings/encodings.csv\" i=0 with open(csvfile, \"w\") as output: writer = csv.writer(output, lineterminator='\\n')",
"enc.append(e) image_encodings.append([img_name,enc]) pbar.update(1) return image_encodings encodings=generate_training_data(\"db\") #print(encodings[0]) csvfile = \"Encodings/encodings.csv\" i=0 with open(csvfile,",
"<gh_stars>0 from tqdm import tqdm import face_recognition import glob import csv import numpy",
"encodings=generate_training_data(\"db\") #print(encodings[0]) csvfile = \"Encodings/encodings.csv\" i=0 with open(csvfile, \"w\") as output: writer =",
"= \"Encodings/encodings.csv\" i=0 with open(csvfile, \"w\") as output: writer = csv.writer(output, lineterminator='\\n') if(i==0):",
"\"w\") as output: writer = csv.writer(output, lineterminator='\\n') if(i==0): writer.writerow([\"Img_Name\",\"Encoding\"]) i+=1 writer.writerows(encodings) print(\"Encodings updated",
"open(csvfile, \"w\") as output: writer = csv.writer(output, lineterminator='\\n') if(i==0): writer.writerow([\"Img_Name\",\"Encoding\"]) i+=1 writer.writerows(encodings) print(\"Encodings",
"print(\"Generating encodings for db images..\") image_encodings=[] with tqdm(total=len(glob.glob(folder+\"/*.jpg\"))) as pbar: for img in",
"for db images..\") image_encodings=[] with tqdm(total=len(glob.glob(folder+\"/*.jpg\"))) as pbar: for img in glob.glob(folder+\"/*.jpg\"): enc=[]",
"images..\") image_encodings=[] with tqdm(total=len(glob.glob(folder+\"/*.jpg\"))) as pbar: for img in glob.glob(folder+\"/*.jpg\"): enc=[] img_name=img[3:] known_img=face_recognition.load_image_file(img)",
"print(\"can't generate encodings for \"+img_name+\", give another image\") pass #en=np.array(en) for e in",
"another image\") pass #en=np.array(en) for e in en: enc.append(e) image_encodings.append([img_name,enc]) pbar.update(1) return image_encodings",
"#print(encodings[0]) csvfile = \"Encodings/encodings.csv\" i=0 with open(csvfile, \"w\") as output: writer = csv.writer(output,",
"csv import numpy as np def generate_training_data(folder): r=0 print(\"Generating encodings for db images..\")",
"encodings for \"+img_name+\", give another image\") pass #en=np.array(en) for e in en: enc.append(e)",
"generate_training_data(folder): r=0 print(\"Generating encodings for db images..\") image_encodings=[] with tqdm(total=len(glob.glob(folder+\"/*.jpg\"))) as pbar: for",
"tqdm(total=len(glob.glob(folder+\"/*.jpg\"))) as pbar: for img in glob.glob(folder+\"/*.jpg\"): enc=[] img_name=img[3:] known_img=face_recognition.load_image_file(img) try: en=face_recognition.face_encodings(known_img)[0] except:",
"output: writer = csv.writer(output, lineterminator='\\n') if(i==0): writer.writerow([\"Img_Name\",\"Encoding\"]) i+=1 writer.writerows(encodings) print(\"Encodings updated for all",
"pbar: for img in glob.glob(folder+\"/*.jpg\"): enc=[] img_name=img[3:] known_img=face_recognition.load_image_file(img) try: en=face_recognition.face_encodings(known_img)[0] except: print(\"can't generate",
"for \"+img_name+\", give another image\") pass #en=np.array(en) for e in en: enc.append(e) image_encodings.append([img_name,enc])",
"image_encodings encodings=generate_training_data(\"db\") #print(encodings[0]) csvfile = \"Encodings/encodings.csv\" i=0 with open(csvfile, \"w\") as output: writer",
"except: print(\"can't generate encodings for \"+img_name+\", give another image\") pass #en=np.array(en) for e",
"in en: enc.append(e) image_encodings.append([img_name,enc]) pbar.update(1) return image_encodings encodings=generate_training_data(\"db\") #print(encodings[0]) csvfile = \"Encodings/encodings.csv\" i=0",
"tqdm import face_recognition import glob import csv import numpy as np def generate_training_data(folder):",
"try: en=face_recognition.face_encodings(known_img)[0] except: print(\"can't generate encodings for \"+img_name+\", give another image\") pass #en=np.array(en)",
"encodings for db images..\") image_encodings=[] with tqdm(total=len(glob.glob(folder+\"/*.jpg\"))) as pbar: for img in glob.glob(folder+\"/*.jpg\"):",
"with tqdm(total=len(glob.glob(folder+\"/*.jpg\"))) as pbar: for img in glob.glob(folder+\"/*.jpg\"): enc=[] img_name=img[3:] known_img=face_recognition.load_image_file(img) try: en=face_recognition.face_encodings(known_img)[0]",
"pass #en=np.array(en) for e in en: enc.append(e) image_encodings.append([img_name,enc]) pbar.update(1) return image_encodings encodings=generate_training_data(\"db\") #print(encodings[0])",
"enc=[] img_name=img[3:] known_img=face_recognition.load_image_file(img) try: en=face_recognition.face_encodings(known_img)[0] except: print(\"can't generate encodings for \"+img_name+\", give another",
"import face_recognition import glob import csv import numpy as np def generate_training_data(folder): r=0",
"image_encodings=[] with tqdm(total=len(glob.glob(folder+\"/*.jpg\"))) as pbar: for img in glob.glob(folder+\"/*.jpg\"): enc=[] img_name=img[3:] known_img=face_recognition.load_image_file(img) try:",
"from tqdm import tqdm import face_recognition import glob import csv import numpy as",
"image_encodings.append([img_name,enc]) pbar.update(1) return image_encodings encodings=generate_training_data(\"db\") #print(encodings[0]) csvfile = \"Encodings/encodings.csv\" i=0 with open(csvfile, \"w\")",
"as output: writer = csv.writer(output, lineterminator='\\n') if(i==0): writer.writerow([\"Img_Name\",\"Encoding\"]) i+=1 writer.writerows(encodings) print(\"Encodings updated for",
"tqdm import tqdm import face_recognition import glob import csv import numpy as np",
"for e in en: enc.append(e) image_encodings.append([img_name,enc]) pbar.update(1) return image_encodings encodings=generate_training_data(\"db\") #print(encodings[0]) csvfile =",
"for img in glob.glob(folder+\"/*.jpg\"): enc=[] img_name=img[3:] known_img=face_recognition.load_image_file(img) try: en=face_recognition.face_encodings(known_img)[0] except: print(\"can't generate encodings",
"return image_encodings encodings=generate_training_data(\"db\") #print(encodings[0]) csvfile = \"Encodings/encodings.csv\" i=0 with open(csvfile, \"w\") as output:",
"#en=np.array(en) for e in en: enc.append(e) image_encodings.append([img_name,enc]) pbar.update(1) return image_encodings encodings=generate_training_data(\"db\") #print(encodings[0]) csvfile",
"e in en: enc.append(e) image_encodings.append([img_name,enc]) pbar.update(1) return image_encodings encodings=generate_training_data(\"db\") #print(encodings[0]) csvfile = \"Encodings/encodings.csv\"",
"img_name=img[3:] known_img=face_recognition.load_image_file(img) try: en=face_recognition.face_encodings(known_img)[0] except: print(\"can't generate encodings for \"+img_name+\", give another image\")",
"as np def generate_training_data(folder): r=0 print(\"Generating encodings for db images..\") image_encodings=[] with tqdm(total=len(glob.glob(folder+\"/*.jpg\")))",
"pbar.update(1) return image_encodings encodings=generate_training_data(\"db\") #print(encodings[0]) csvfile = \"Encodings/encodings.csv\" i=0 with open(csvfile, \"w\") as",
"\"+img_name+\", give another image\") pass #en=np.array(en) for e in en: enc.append(e) image_encodings.append([img_name,enc]) pbar.update(1)",
"with open(csvfile, \"w\") as output: writer = csv.writer(output, lineterminator='\\n') if(i==0): writer.writerow([\"Img_Name\",\"Encoding\"]) i+=1 writer.writerows(encodings)",
"as pbar: for img in glob.glob(folder+\"/*.jpg\"): enc=[] img_name=img[3:] known_img=face_recognition.load_image_file(img) try: en=face_recognition.face_encodings(known_img)[0] except: print(\"can't",
"numpy as np def generate_training_data(folder): r=0 print(\"Generating encodings for db images..\") image_encodings=[] with",
"glob.glob(folder+\"/*.jpg\"): enc=[] img_name=img[3:] known_img=face_recognition.load_image_file(img) try: en=face_recognition.face_encodings(known_img)[0] except: print(\"can't generate encodings for \"+img_name+\", give",
"def generate_training_data(folder): r=0 print(\"Generating encodings for db images..\") image_encodings=[] with tqdm(total=len(glob.glob(folder+\"/*.jpg\"))) as pbar:",
"image\") pass #en=np.array(en) for e in en: enc.append(e) image_encodings.append([img_name,enc]) pbar.update(1) return image_encodings encodings=generate_training_data(\"db\")",
"i=0 with open(csvfile, \"w\") as output: writer = csv.writer(output, lineterminator='\\n') if(i==0): writer.writerow([\"Img_Name\",\"Encoding\"]) i+=1",
"r=0 print(\"Generating encodings for db images..\") image_encodings=[] with tqdm(total=len(glob.glob(folder+\"/*.jpg\"))) as pbar: for img",
"import glob import csv import numpy as np def generate_training_data(folder): r=0 print(\"Generating encodings",
"import tqdm import face_recognition import glob import csv import numpy as np def",
"in glob.glob(folder+\"/*.jpg\"): enc=[] img_name=img[3:] known_img=face_recognition.load_image_file(img) try: en=face_recognition.face_encodings(known_img)[0] except: print(\"can't generate encodings for \"+img_name+\",",
"glob import csv import numpy as np def generate_training_data(folder): r=0 print(\"Generating encodings for",
"\"Encodings/encodings.csv\" i=0 with open(csvfile, \"w\") as output: writer = csv.writer(output, lineterminator='\\n') if(i==0): writer.writerow([\"Img_Name\",\"Encoding\"])",
"np def generate_training_data(folder): r=0 print(\"Generating encodings for db images..\") image_encodings=[] with tqdm(total=len(glob.glob(folder+\"/*.jpg\"))) as",
"writer = csv.writer(output, lineterminator='\\n') if(i==0): writer.writerow([\"Img_Name\",\"Encoding\"]) i+=1 writer.writerows(encodings) print(\"Encodings updated for all images\")",
"import numpy as np def generate_training_data(folder): r=0 print(\"Generating encodings for db images..\") image_encodings=[]",
"en: enc.append(e) image_encodings.append([img_name,enc]) pbar.update(1) return image_encodings encodings=generate_training_data(\"db\") #print(encodings[0]) csvfile = \"Encodings/encodings.csv\" i=0 with",
"db images..\") image_encodings=[] with tqdm(total=len(glob.glob(folder+\"/*.jpg\"))) as pbar: for img in glob.glob(folder+\"/*.jpg\"): enc=[] img_name=img[3:]",
"img in glob.glob(folder+\"/*.jpg\"): enc=[] img_name=img[3:] known_img=face_recognition.load_image_file(img) try: en=face_recognition.face_encodings(known_img)[0] except: print(\"can't generate encodings for",
"give another image\") pass #en=np.array(en) for e in en: enc.append(e) image_encodings.append([img_name,enc]) pbar.update(1) return"
] |
[
"claims_to_quality.lib.util import new_relic_insights, slack import mock def test_new_relic_insights_payload(): \"\"\"Test NR insights payload creation.\"\"\"",
"assert json.loads(payload) == event @mock.patch('subprocess.call') def test_new_relic_insights_post(call): \"\"\"Test NR insights post.\"\"\" payload =",
"in checks: assert check in kwargs['args'][0] @mock.patch('subprocess.call') def test_slack_post(call): \"\"\"Test Slack.\"\"\" slack.post_to_slack(message='hello') subprocess_calls",
"1 _, kwargs = subprocess_calls[0] checks = [ '{\"environment\": \"TEST\", \"success\": \"True\", \"eventType\":",
"-H 'Content-type: application/json'\", \"\"\"--data \\'{\"text\":\"hello\"}\\'\"\"\" ] for check in checks: assert check in",
"'{\"environment\": \"TEST\", \"success\": \"True\", \"eventType\": \"analyzerStartup\"}', ] for check in checks: assert check",
"subprocess.call was triggered only once. assert len(subprocess_calls) == 1 _, kwargs = subprocess_calls[0]",
"len(subprocess_calls) == 1 _, kwargs = subprocess_calls[0] checks = [ '{\"environment\": \"TEST\", \"success\":",
"kwargs = subprocess_calls[0] checks = [ '{\"environment\": \"TEST\", \"success\": \"True\", \"eventType\": \"analyzerStartup\"}', ]",
"== event @mock.patch('subprocess.call') def test_new_relic_insights_post(call): \"\"\"Test NR insights post.\"\"\" payload = json.dumps({ 'environment':",
"application/json'\", \"\"\"--data \\'{\"text\":\"<!here> hello\"}\\'\"\"\" ] for check in checks: assert check in kwargs['args'][0]",
"\"\"\"Test NR insights payload creation.\"\"\" event = { 'environment': 'TEST', 'success': 'True' }",
"'True' } payload = new_relic_insights.build_new_relic_insights_payload( event_type='analyzerStartup', event_body=event ) event['eventType'] = 'analyzerStartup' assert json.loads(payload)",
"test_new_relic_insights_post(call): \"\"\"Test NR insights post.\"\"\" payload = json.dumps({ 'environment': 'TEST', 'success': 'True', 'eventType':",
"POST -H 'Content-type: application/json'\", \"\"\"--data \\'{\"text\":\"<!here> hello\"}\\'\"\"\" ] for check in checks: assert",
"from claims_to_quality.lib.util import new_relic_insights, slack import mock def test_new_relic_insights_payload(): \"\"\"Test NR insights payload",
"post.\"\"\" payload = json.dumps({ 'environment': 'TEST', 'success': 'True', 'eventType': 'analyzerStartup' }) new_relic_insights.post_to_new_relic(payload=payload) subprocess_calls",
"\"analyzerStartup\"}', ] for check in checks: assert check in kwargs['args'][0] @mock.patch('subprocess.call') def test_slack_post(call):",
"Slack.\"\"\" slack.post_to_slack_tagging_here(message='hello') subprocess_calls = call.call_args_list # Check that subprocess.call was triggered only once.",
"@mock.patch('subprocess.call') def test_slack_post_here(call): \"\"\"Test Slack.\"\"\" slack.post_to_slack_tagging_here(message='hello') subprocess_calls = call.call_args_list # Check that subprocess.call",
"triggered only once. assert len(subprocess_calls) == 1 _, kwargs = subprocess_calls[0] checks =",
"\\'{\"text\":\"hello\"}\\'\"\"\" ] for check in checks: assert check in kwargs['args'][0] @mock.patch('subprocess.call') def test_slack_post_here(call):",
"'Content-type: application/json'\", \"\"\"--data \\'{\"text\":\"hello\"}\\'\"\"\" ] for check in checks: assert check in kwargs['args'][0]",
"\"TEST\", \"success\": \"True\", \"eventType\": \"analyzerStartup\"}', ] for check in checks: assert check in",
"\"\"\"Test util files.\"\"\" import json from claims_to_quality.lib.util import new_relic_insights, slack import mock def",
"check in kwargs['args'][0] @mock.patch('subprocess.call') def test_slack_post_here(call): \"\"\"Test Slack.\"\"\" slack.post_to_slack_tagging_here(message='hello') subprocess_calls = call.call_args_list #",
"was triggered only once. assert len(subprocess_calls) == 1 _, kwargs = subprocess_calls[0] checks",
"slack.post_to_slack_tagging_here(message='hello') subprocess_calls = call.call_args_list # Check that subprocess.call was triggered only once. assert",
"== 1 _, kwargs = subprocess_calls[0] checks = [ '{\"environment\": \"TEST\", \"success\": \"True\",",
"'environment': 'TEST', 'success': 'True' } payload = new_relic_insights.build_new_relic_insights_payload( event_type='analyzerStartup', event_body=event ) event['eventType'] =",
"checks = [ '{\"environment\": \"TEST\", \"success\": \"True\", \"eventType\": \"analyzerStartup\"}', ] for check in",
"json.loads(payload) == event @mock.patch('subprocess.call') def test_new_relic_insights_post(call): \"\"\"Test NR insights post.\"\"\" payload = json.dumps({",
"\"success\": \"True\", \"eventType\": \"analyzerStartup\"}', ] for check in checks: assert check in kwargs['args'][0]",
"subprocess_calls[0] checks = [ '{\"environment\": \"TEST\", \"success\": \"True\", \"eventType\": \"analyzerStartup\"}', ] for check",
"'Content-type: application/json'\", \"\"\"--data \\'{\"text\":\"<!here> hello\"}\\'\"\"\" ] for check in checks: assert check in",
"len(subprocess_calls) == 1 _, kwargs = subprocess_calls[0] checks = [ \"curl -X POST",
"Check that subprocess.call was triggered only once. assert len(subprocess_calls) == 1 _, kwargs",
"in checks: assert check in kwargs['args'][0] @mock.patch('subprocess.call') def test_slack_post_here(call): \"\"\"Test Slack.\"\"\" slack.post_to_slack_tagging_here(message='hello') subprocess_calls",
"# Check that subprocess.call was triggered only once. assert len(subprocess_calls) == 1 _,",
"new_relic_insights.post_to_new_relic(payload=payload) subprocess_calls = call.call_args_list # Check that subprocess.call was triggered only once. assert",
"in kwargs['args'][0] @mock.patch('subprocess.call') def test_slack_post_here(call): \"\"\"Test Slack.\"\"\" slack.post_to_slack_tagging_here(message='hello') subprocess_calls = call.call_args_list # Check",
"payload = new_relic_insights.build_new_relic_insights_payload( event_type='analyzerStartup', event_body=event ) event['eventType'] = 'analyzerStartup' assert json.loads(payload) == event",
"event_body=event ) event['eventType'] = 'analyzerStartup' assert json.loads(payload) == event @mock.patch('subprocess.call') def test_new_relic_insights_post(call): \"\"\"Test",
"kwargs = subprocess_calls[0] checks = [ \"curl -X POST -H 'Content-type: application/json'\", \"\"\"--data",
"}) new_relic_insights.post_to_new_relic(payload=payload) subprocess_calls = call.call_args_list # Check that subprocess.call was triggered only once.",
"\"\"\"--data \\'{\"text\":\"hello\"}\\'\"\"\" ] for check in checks: assert check in kwargs['args'][0] @mock.patch('subprocess.call') def",
"check in kwargs['args'][0] @mock.patch('subprocess.call') def test_slack_post(call): \"\"\"Test Slack.\"\"\" slack.post_to_slack(message='hello') subprocess_calls = call.call_args_list #",
"json from claims_to_quality.lib.util import new_relic_insights, slack import mock def test_new_relic_insights_payload(): \"\"\"Test NR insights",
"@mock.patch('subprocess.call') def test_slack_post(call): \"\"\"Test Slack.\"\"\" slack.post_to_slack(message='hello') subprocess_calls = call.call_args_list # Check that subprocess.call",
"<filename>tests/lib/util/test_utils.py \"\"\"Test util files.\"\"\" import json from claims_to_quality.lib.util import new_relic_insights, slack import mock",
"check in checks: assert check in kwargs['args'][0] @mock.patch('subprocess.call') def test_slack_post_here(call): \"\"\"Test Slack.\"\"\" slack.post_to_slack_tagging_here(message='hello')",
"assert check in kwargs['args'][0] @mock.patch('subprocess.call') def test_slack_post_here(call): \"\"\"Test Slack.\"\"\" slack.post_to_slack_tagging_here(message='hello') subprocess_calls = call.call_args_list",
"kwargs['args'][0] @mock.patch('subprocess.call') def test_slack_post_here(call): \"\"\"Test Slack.\"\"\" slack.post_to_slack_tagging_here(message='hello') subprocess_calls = call.call_args_list # Check that",
"\"True\", \"eventType\": \"analyzerStartup\"}', ] for check in checks: assert check in kwargs['args'][0] @mock.patch('subprocess.call')",
"test_slack_post(call): \"\"\"Test Slack.\"\"\" slack.post_to_slack(message='hello') subprocess_calls = call.call_args_list # Check that subprocess.call was triggered",
"= subprocess_calls[0] checks = [ '{\"environment\": \"TEST\", \"success\": \"True\", \"eventType\": \"analyzerStartup\"}', ] for",
"subprocess_calls[0] checks = [ \"curl -X POST -H 'Content-type: application/json'\", \"\"\"--data \\'{\"text\":\"<!here> hello\"}\\'\"\"\"",
"= [ '{\"environment\": \"TEST\", \"success\": \"True\", \"eventType\": \"analyzerStartup\"}', ] for check in checks:",
"in kwargs['args'][0] @mock.patch('subprocess.call') def test_slack_post(call): \"\"\"Test Slack.\"\"\" slack.post_to_slack(message='hello') subprocess_calls = call.call_args_list # Check",
"mock def test_new_relic_insights_payload(): \"\"\"Test NR insights payload creation.\"\"\" event = { 'environment': 'TEST',",
") event['eventType'] = 'analyzerStartup' assert json.loads(payload) == event @mock.patch('subprocess.call') def test_new_relic_insights_post(call): \"\"\"Test NR",
"event['eventType'] = 'analyzerStartup' assert json.loads(payload) == event @mock.patch('subprocess.call') def test_new_relic_insights_post(call): \"\"\"Test NR insights",
"= subprocess_calls[0] checks = [ \"curl -X POST -H 'Content-type: application/json'\", \"\"\"--data \\'{\"text\":\"hello\"}\\'\"\"\"",
"assert len(subprocess_calls) == 1 _, kwargs = subprocess_calls[0] checks = [ \"curl -X",
"files.\"\"\" import json from claims_to_quality.lib.util import new_relic_insights, slack import mock def test_new_relic_insights_payload(): \"\"\"Test",
"json.dumps({ 'environment': 'TEST', 'success': 'True', 'eventType': 'analyzerStartup' }) new_relic_insights.post_to_new_relic(payload=payload) subprocess_calls = call.call_args_list #",
"'TEST', 'success': 'True' } payload = new_relic_insights.build_new_relic_insights_payload( event_type='analyzerStartup', event_body=event ) event['eventType'] = 'analyzerStartup'",
"kwargs['args'][0] @mock.patch('subprocess.call') def test_slack_post(call): \"\"\"Test Slack.\"\"\" slack.post_to_slack(message='hello') subprocess_calls = call.call_args_list # Check that",
"Slack.\"\"\" slack.post_to_slack(message='hello') subprocess_calls = call.call_args_list # Check that subprocess.call was triggered only once.",
"import new_relic_insights, slack import mock def test_new_relic_insights_payload(): \"\"\"Test NR insights payload creation.\"\"\" event",
"test_slack_post_here(call): \"\"\"Test Slack.\"\"\" slack.post_to_slack_tagging_here(message='hello') subprocess_calls = call.call_args_list # Check that subprocess.call was triggered",
"= { 'environment': 'TEST', 'success': 'True' } payload = new_relic_insights.build_new_relic_insights_payload( event_type='analyzerStartup', event_body=event )",
"assert len(subprocess_calls) == 1 _, kwargs = subprocess_calls[0] checks = [ '{\"environment\": \"TEST\",",
"'environment': 'TEST', 'success': 'True', 'eventType': 'analyzerStartup' }) new_relic_insights.post_to_new_relic(payload=payload) subprocess_calls = call.call_args_list # Check",
"] for check in checks: assert check in kwargs['args'][0] @mock.patch('subprocess.call') def test_slack_post(call): \"\"\"Test",
"once. assert len(subprocess_calls) == 1 _, kwargs = subprocess_calls[0] checks = [ '{\"environment\":",
"for check in checks: assert check in kwargs['args'][0] @mock.patch('subprocess.call') def test_slack_post(call): \"\"\"Test Slack.\"\"\"",
"\"curl -X POST -H 'Content-type: application/json'\", \"\"\"--data \\'{\"text\":\"hello\"}\\'\"\"\" ] for check in checks:",
"def test_slack_post(call): \"\"\"Test Slack.\"\"\" slack.post_to_slack(message='hello') subprocess_calls = call.call_args_list # Check that subprocess.call was",
"def test_new_relic_insights_post(call): \"\"\"Test NR insights post.\"\"\" payload = json.dumps({ 'environment': 'TEST', 'success': 'True',",
"once. assert len(subprocess_calls) == 1 _, kwargs = subprocess_calls[0] checks = [ \"curl",
"'TEST', 'success': 'True', 'eventType': 'analyzerStartup' }) new_relic_insights.post_to_new_relic(payload=payload) subprocess_calls = call.call_args_list # Check that",
"] for check in checks: assert check in kwargs['args'][0] @mock.patch('subprocess.call') def test_slack_post_here(call): \"\"\"Test",
"-X POST -H 'Content-type: application/json'\", \"\"\"--data \\'{\"text\":\"<!here> hello\"}\\'\"\"\" ] for check in checks:",
"subprocess_calls[0] checks = [ \"curl -X POST -H 'Content-type: application/json'\", \"\"\"--data \\'{\"text\":\"hello\"}\\'\"\"\" ]",
"\"curl -X POST -H 'Content-type: application/json'\", \"\"\"--data \\'{\"text\":\"<!here> hello\"}\\'\"\"\" ] for check in",
"util files.\"\"\" import json from claims_to_quality.lib.util import new_relic_insights, slack import mock def test_new_relic_insights_payload():",
"== 1 _, kwargs = subprocess_calls[0] checks = [ \"curl -X POST -H",
"for check in checks: assert check in kwargs['args'][0] @mock.patch('subprocess.call') def test_slack_post_here(call): \"\"\"Test Slack.\"\"\"",
"NR insights payload creation.\"\"\" event = { 'environment': 'TEST', 'success': 'True' } payload",
"= [ \"curl -X POST -H 'Content-type: application/json'\", \"\"\"--data \\'{\"text\":\"hello\"}\\'\"\"\" ] for check",
"_, kwargs = subprocess_calls[0] checks = [ \"curl -X POST -H 'Content-type: application/json'\",",
"checks: assert check in kwargs['args'][0] @mock.patch('subprocess.call') def test_slack_post_here(call): \"\"\"Test Slack.\"\"\" slack.post_to_slack_tagging_here(message='hello') subprocess_calls =",
"= json.dumps({ 'environment': 'TEST', 'success': 'True', 'eventType': 'analyzerStartup' }) new_relic_insights.post_to_new_relic(payload=payload) subprocess_calls = call.call_args_list",
"'True', 'eventType': 'analyzerStartup' }) new_relic_insights.post_to_new_relic(payload=payload) subprocess_calls = call.call_args_list # Check that subprocess.call was",
"= 'analyzerStartup' assert json.loads(payload) == event @mock.patch('subprocess.call') def test_new_relic_insights_post(call): \"\"\"Test NR insights post.\"\"\"",
"payload = json.dumps({ 'environment': 'TEST', 'success': 'True', 'eventType': 'analyzerStartup' }) new_relic_insights.post_to_new_relic(payload=payload) subprocess_calls =",
"= call.call_args_list # Check that subprocess.call was triggered only once. assert len(subprocess_calls) ==",
"that subprocess.call was triggered only once. assert len(subprocess_calls) == 1 _, kwargs =",
"slack import mock def test_new_relic_insights_payload(): \"\"\"Test NR insights payload creation.\"\"\" event = {",
"'analyzerStartup' assert json.loads(payload) == event @mock.patch('subprocess.call') def test_new_relic_insights_post(call): \"\"\"Test NR insights post.\"\"\" payload",
"{ 'environment': 'TEST', 'success': 'True' } payload = new_relic_insights.build_new_relic_insights_payload( event_type='analyzerStartup', event_body=event ) event['eventType']",
"-H 'Content-type: application/json'\", \"\"\"--data \\'{\"text\":\"<!here> hello\"}\\'\"\"\" ] for check in checks: assert check",
"} payload = new_relic_insights.build_new_relic_insights_payload( event_type='analyzerStartup', event_body=event ) event['eventType'] = 'analyzerStartup' assert json.loads(payload) ==",
"insights post.\"\"\" payload = json.dumps({ 'environment': 'TEST', 'success': 'True', 'eventType': 'analyzerStartup' }) new_relic_insights.post_to_new_relic(payload=payload)",
"new_relic_insights.build_new_relic_insights_payload( event_type='analyzerStartup', event_body=event ) event['eventType'] = 'analyzerStartup' assert json.loads(payload) == event @mock.patch('subprocess.call') def",
"'eventType': 'analyzerStartup' }) new_relic_insights.post_to_new_relic(payload=payload) subprocess_calls = call.call_args_list # Check that subprocess.call was triggered",
"[ '{\"environment\": \"TEST\", \"success\": \"True\", \"eventType\": \"analyzerStartup\"}', ] for check in checks: assert",
"-X POST -H 'Content-type: application/json'\", \"\"\"--data \\'{\"text\":\"hello\"}\\'\"\"\" ] for check in checks: assert",
"'success': 'True' } payload = new_relic_insights.build_new_relic_insights_payload( event_type='analyzerStartup', event_body=event ) event['eventType'] = 'analyzerStartup' assert",
"checks = [ \"curl -X POST -H 'Content-type: application/json'\", \"\"\"--data \\'{\"text\":\"<!here> hello\"}\\'\"\"\" ]",
"call.call_args_list # Check that subprocess.call was triggered only once. assert len(subprocess_calls) == 1",
"only once. assert len(subprocess_calls) == 1 _, kwargs = subprocess_calls[0] checks = [",
"\"\"\"Test NR insights post.\"\"\" payload = json.dumps({ 'environment': 'TEST', 'success': 'True', 'eventType': 'analyzerStartup'",
"check in checks: assert check in kwargs['args'][0] @mock.patch('subprocess.call') def test_slack_post(call): \"\"\"Test Slack.\"\"\" slack.post_to_slack(message='hello')",
"assert check in kwargs['args'][0] @mock.patch('subprocess.call') def test_slack_post(call): \"\"\"Test Slack.\"\"\" slack.post_to_slack(message='hello') subprocess_calls = call.call_args_list",
"= [ \"curl -X POST -H 'Content-type: application/json'\", \"\"\"--data \\'{\"text\":\"<!here> hello\"}\\'\"\"\" ] for",
"creation.\"\"\" event = { 'environment': 'TEST', 'success': 'True' } payload = new_relic_insights.build_new_relic_insights_payload( event_type='analyzerStartup',",
"[ \"curl -X POST -H 'Content-type: application/json'\", \"\"\"--data \\'{\"text\":\"hello\"}\\'\"\"\" ] for check in",
"POST -H 'Content-type: application/json'\", \"\"\"--data \\'{\"text\":\"hello\"}\\'\"\"\" ] for check in checks: assert check",
"new_relic_insights, slack import mock def test_new_relic_insights_payload(): \"\"\"Test NR insights payload creation.\"\"\" event =",
"\"\"\"Test Slack.\"\"\" slack.post_to_slack(message='hello') subprocess_calls = call.call_args_list # Check that subprocess.call was triggered only",
"1 _, kwargs = subprocess_calls[0] checks = [ \"curl -X POST -H 'Content-type:",
"checks = [ \"curl -X POST -H 'Content-type: application/json'\", \"\"\"--data \\'{\"text\":\"hello\"}\\'\"\"\" ] for",
"slack.post_to_slack(message='hello') subprocess_calls = call.call_args_list # Check that subprocess.call was triggered only once. assert",
"NR insights post.\"\"\" payload = json.dumps({ 'environment': 'TEST', 'success': 'True', 'eventType': 'analyzerStartup' })",
"insights payload creation.\"\"\" event = { 'environment': 'TEST', 'success': 'True' } payload =",
"\"eventType\": \"analyzerStartup\"}', ] for check in checks: assert check in kwargs['args'][0] @mock.patch('subprocess.call') def",
"[ \"curl -X POST -H 'Content-type: application/json'\", \"\"\"--data \\'{\"text\":\"<!here> hello\"}\\'\"\"\" ] for check",
"@mock.patch('subprocess.call') def test_new_relic_insights_post(call): \"\"\"Test NR insights post.\"\"\" payload = json.dumps({ 'environment': 'TEST', 'success':",
"payload creation.\"\"\" event = { 'environment': 'TEST', 'success': 'True' } payload = new_relic_insights.build_new_relic_insights_payload(",
"'success': 'True', 'eventType': 'analyzerStartup' }) new_relic_insights.post_to_new_relic(payload=payload) subprocess_calls = call.call_args_list # Check that subprocess.call",
"event @mock.patch('subprocess.call') def test_new_relic_insights_post(call): \"\"\"Test NR insights post.\"\"\" payload = json.dumps({ 'environment': 'TEST',",
"event = { 'environment': 'TEST', 'success': 'True' } payload = new_relic_insights.build_new_relic_insights_payload( event_type='analyzerStartup', event_body=event",
"application/json'\", \"\"\"--data \\'{\"text\":\"hello\"}\\'\"\"\" ] for check in checks: assert check in kwargs['args'][0] @mock.patch('subprocess.call')",
"test_new_relic_insights_payload(): \"\"\"Test NR insights payload creation.\"\"\" event = { 'environment': 'TEST', 'success': 'True'",
"def test_slack_post_here(call): \"\"\"Test Slack.\"\"\" slack.post_to_slack_tagging_here(message='hello') subprocess_calls = call.call_args_list # Check that subprocess.call was",
"event_type='analyzerStartup', event_body=event ) event['eventType'] = 'analyzerStartup' assert json.loads(payload) == event @mock.patch('subprocess.call') def test_new_relic_insights_post(call):",
"\"\"\"Test Slack.\"\"\" slack.post_to_slack_tagging_here(message='hello') subprocess_calls = call.call_args_list # Check that subprocess.call was triggered only",
"import mock def test_new_relic_insights_payload(): \"\"\"Test NR insights payload creation.\"\"\" event = { 'environment':",
"checks: assert check in kwargs['args'][0] @mock.patch('subprocess.call') def test_slack_post(call): \"\"\"Test Slack.\"\"\" slack.post_to_slack(message='hello') subprocess_calls =",
"= subprocess_calls[0] checks = [ \"curl -X POST -H 'Content-type: application/json'\", \"\"\"--data \\'{\"text\":\"<!here>",
"_, kwargs = subprocess_calls[0] checks = [ '{\"environment\": \"TEST\", \"success\": \"True\", \"eventType\": \"analyzerStartup\"}',",
"import json from claims_to_quality.lib.util import new_relic_insights, slack import mock def test_new_relic_insights_payload(): \"\"\"Test NR",
"= new_relic_insights.build_new_relic_insights_payload( event_type='analyzerStartup', event_body=event ) event['eventType'] = 'analyzerStartup' assert json.loads(payload) == event @mock.patch('subprocess.call')",
"subprocess_calls = call.call_args_list # Check that subprocess.call was triggered only once. assert len(subprocess_calls)",
"def test_new_relic_insights_payload(): \"\"\"Test NR insights payload creation.\"\"\" event = { 'environment': 'TEST', 'success':",
"'analyzerStartup' }) new_relic_insights.post_to_new_relic(payload=payload) subprocess_calls = call.call_args_list # Check that subprocess.call was triggered only"
] |
[
"shellcraft.pushstr('/home/pwn/flag') sc += shellcraft.open(\"esp\", 0, 0) # fd = open(\"./flag\", 0, 0); sc",
"pwn import * context.log_level = 'debug' e = ELF('./test_shellcode32') r = remote(\"sunrin.site\", 9017)#process('./test_shellcode32')",
"0, 0) # fd = open(\"./flag\", 0, 0); sc += shellcraft.read(\"eax\", \"esp\", 100)",
"100) # read(fd, esp, 100); sc += shellcraft.write(1, \"esp\", 100) # write(1, esp,",
"os='linux') sc = shellcraft.pushstr('/home/pwn/flag') sc += shellcraft.open(\"esp\", 0, 0) # fd = open(\"./flag\",",
"import * context.log_level = 'debug' e = ELF('./test_shellcode32') r = remote(\"sunrin.site\", 9017)#process('./test_shellcode32') context(arch='i386',",
"\"esp\", 100) # read(fd, esp, 100); sc += shellcraft.write(1, \"esp\", 100) # write(1,",
"shellcraft.read(\"eax\", \"esp\", 100) # read(fd, esp, 100); sc += shellcraft.write(1, \"esp\", 100) #",
"9017)#process('./test_shellcode32') context(arch='i386', os='linux') sc = shellcraft.pushstr('/home/pwn/flag') sc += shellcraft.open(\"esp\", 0, 0) # fd",
"0) # fd = open(\"./flag\", 0, 0); sc += shellcraft.read(\"eax\", \"esp\", 100) #",
"r = remote(\"sunrin.site\", 9017)#process('./test_shellcode32') context(arch='i386', os='linux') sc = shellcraft.pushstr('/home/pwn/flag') sc += shellcraft.open(\"esp\", 0,",
"context(arch='i386', os='linux') sc = shellcraft.pushstr('/home/pwn/flag') sc += shellcraft.open(\"esp\", 0, 0) # fd =",
"+= shellcraft.open(\"esp\", 0, 0) # fd = open(\"./flag\", 0, 0); sc += shellcraft.read(\"eax\",",
"read(fd, esp, 100); sc += shellcraft.write(1, \"esp\", 100) # write(1, esp, 100); r.sendline(asm(sc))",
"shellcraft.open(\"esp\", 0, 0) # fd = open(\"./flag\", 0, 0); sc += shellcraft.read(\"eax\", \"esp\",",
"fd = open(\"./flag\", 0, 0); sc += shellcraft.read(\"eax\", \"esp\", 100) # read(fd, esp,",
"context.log_level = 'debug' e = ELF('./test_shellcode32') r = remote(\"sunrin.site\", 9017)#process('./test_shellcode32') context(arch='i386', os='linux') sc",
"= open(\"./flag\", 0, 0); sc += shellcraft.read(\"eax\", \"esp\", 100) # read(fd, esp, 100);",
"'debug' e = ELF('./test_shellcode32') r = remote(\"sunrin.site\", 9017)#process('./test_shellcode32') context(arch='i386', os='linux') sc = shellcraft.pushstr('/home/pwn/flag')",
"* context.log_level = 'debug' e = ELF('./test_shellcode32') r = remote(\"sunrin.site\", 9017)#process('./test_shellcode32') context(arch='i386', os='linux')",
"# fd = open(\"./flag\", 0, 0); sc += shellcraft.read(\"eax\", \"esp\", 100) # read(fd,",
"remote(\"sunrin.site\", 9017)#process('./test_shellcode32') context(arch='i386', os='linux') sc = shellcraft.pushstr('/home/pwn/flag') sc += shellcraft.open(\"esp\", 0, 0) #",
"sc = shellcraft.pushstr('/home/pwn/flag') sc += shellcraft.open(\"esp\", 0, 0) # fd = open(\"./flag\", 0,",
"= ELF('./test_shellcode32') r = remote(\"sunrin.site\", 9017)#process('./test_shellcode32') context(arch='i386', os='linux') sc = shellcraft.pushstr('/home/pwn/flag') sc +=",
"= remote(\"sunrin.site\", 9017)#process('./test_shellcode32') context(arch='i386', os='linux') sc = shellcraft.pushstr('/home/pwn/flag') sc += shellcraft.open(\"esp\", 0, 0)",
"+= shellcraft.read(\"eax\", \"esp\", 100) # read(fd, esp, 100); sc += shellcraft.write(1, \"esp\", 100)",
"esp, 100); sc += shellcraft.write(1, \"esp\", 100) # write(1, esp, 100); r.sendline(asm(sc)) r.interactive()",
"sc += shellcraft.open(\"esp\", 0, 0) # fd = open(\"./flag\", 0, 0); sc +=",
"= shellcraft.pushstr('/home/pwn/flag') sc += shellcraft.open(\"esp\", 0, 0) # fd = open(\"./flag\", 0, 0);",
"from pwn import * context.log_level = 'debug' e = ELF('./test_shellcode32') r = remote(\"sunrin.site\",",
"ELF('./test_shellcode32') r = remote(\"sunrin.site\", 9017)#process('./test_shellcode32') context(arch='i386', os='linux') sc = shellcraft.pushstr('/home/pwn/flag') sc += shellcraft.open(\"esp\",",
"0, 0); sc += shellcraft.read(\"eax\", \"esp\", 100) # read(fd, esp, 100); sc +=",
"e = ELF('./test_shellcode32') r = remote(\"sunrin.site\", 9017)#process('./test_shellcode32') context(arch='i386', os='linux') sc = shellcraft.pushstr('/home/pwn/flag') sc",
"= 'debug' e = ELF('./test_shellcode32') r = remote(\"sunrin.site\", 9017)#process('./test_shellcode32') context(arch='i386', os='linux') sc =",
"sc += shellcraft.read(\"eax\", \"esp\", 100) # read(fd, esp, 100); sc += shellcraft.write(1, \"esp\",",
"# read(fd, esp, 100); sc += shellcraft.write(1, \"esp\", 100) # write(1, esp, 100);",
"0); sc += shellcraft.read(\"eax\", \"esp\", 100) # read(fd, esp, 100); sc += shellcraft.write(1,",
"open(\"./flag\", 0, 0); sc += shellcraft.read(\"eax\", \"esp\", 100) # read(fd, esp, 100); sc"
] |
[
"import LaunchConfiguration, ThisLaunchFileDir config = LaunchConfiguration( 'params', default=[ThisLaunchFileDir(), '/teleop.yaml']) def generate_launch_description(): return LaunchDescription([",
"import Node from launch.actions import DeclareLaunchArgument, SetEnvironmentVariable from launch.substitutions import LaunchConfiguration, ThisLaunchFileDir config",
"= LaunchConfiguration( 'params', default=[ThisLaunchFileDir(), '/teleop.yaml']) def generate_launch_description(): return LaunchDescription([ Node( package='joy', node_executable='joy_node'), Node(",
"launch.substitutions import LaunchConfiguration, ThisLaunchFileDir config = LaunchConfiguration( 'params', default=[ThisLaunchFileDir(), '/teleop.yaml']) def generate_launch_description(): return",
"'/teleop.yaml']) def generate_launch_description(): return LaunchDescription([ Node( package='joy', node_executable='joy_node'), Node( package='roomba_600_driver', node_executable='teleop_node', output=\"screen\", parameters=[config]),",
"LaunchConfiguration, ThisLaunchFileDir config = LaunchConfiguration( 'params', default=[ThisLaunchFileDir(), '/teleop.yaml']) def generate_launch_description(): return LaunchDescription([ Node(",
"ThisLaunchFileDir config = LaunchConfiguration( 'params', default=[ThisLaunchFileDir(), '/teleop.yaml']) def generate_launch_description(): return LaunchDescription([ Node( package='joy',",
"default=[ThisLaunchFileDir(), '/teleop.yaml']) def generate_launch_description(): return LaunchDescription([ Node( package='joy', node_executable='joy_node'), Node( package='roomba_600_driver', node_executable='teleop_node', output=\"screen\",",
"def generate_launch_description(): return LaunchDescription([ Node( package='joy', node_executable='joy_node'), Node( package='roomba_600_driver', node_executable='teleop_node', output=\"screen\", parameters=[config]), ])",
"import DeclareLaunchArgument, SetEnvironmentVariable from launch.substitutions import LaunchConfiguration, ThisLaunchFileDir config = LaunchConfiguration( 'params', default=[ThisLaunchFileDir(),",
"from launch.substitutions import LaunchConfiguration, ThisLaunchFileDir config = LaunchConfiguration( 'params', default=[ThisLaunchFileDir(), '/teleop.yaml']) def generate_launch_description():",
"Node from launch.actions import DeclareLaunchArgument, SetEnvironmentVariable from launch.substitutions import LaunchConfiguration, ThisLaunchFileDir config =",
"LaunchDescription from launch_ros.actions import Node from launch.actions import DeclareLaunchArgument, SetEnvironmentVariable from launch.substitutions import",
"launch_ros.actions import Node from launch.actions import DeclareLaunchArgument, SetEnvironmentVariable from launch.substitutions import LaunchConfiguration, ThisLaunchFileDir",
"<reponame>3ccd/create_autonomy from launch import LaunchDescription from launch_ros.actions import Node from launch.actions import DeclareLaunchArgument,",
"from launch_ros.actions import Node from launch.actions import DeclareLaunchArgument, SetEnvironmentVariable from launch.substitutions import LaunchConfiguration,",
"LaunchConfiguration( 'params', default=[ThisLaunchFileDir(), '/teleop.yaml']) def generate_launch_description(): return LaunchDescription([ Node( package='joy', node_executable='joy_node'), Node( package='roomba_600_driver',",
"'params', default=[ThisLaunchFileDir(), '/teleop.yaml']) def generate_launch_description(): return LaunchDescription([ Node( package='joy', node_executable='joy_node'), Node( package='roomba_600_driver', node_executable='teleop_node',",
"from launch import LaunchDescription from launch_ros.actions import Node from launch.actions import DeclareLaunchArgument, SetEnvironmentVariable",
"config = LaunchConfiguration( 'params', default=[ThisLaunchFileDir(), '/teleop.yaml']) def generate_launch_description(): return LaunchDescription([ Node( package='joy', node_executable='joy_node'),",
"launch import LaunchDescription from launch_ros.actions import Node from launch.actions import DeclareLaunchArgument, SetEnvironmentVariable from",
"SetEnvironmentVariable from launch.substitutions import LaunchConfiguration, ThisLaunchFileDir config = LaunchConfiguration( 'params', default=[ThisLaunchFileDir(), '/teleop.yaml']) def",
"launch.actions import DeclareLaunchArgument, SetEnvironmentVariable from launch.substitutions import LaunchConfiguration, ThisLaunchFileDir config = LaunchConfiguration( 'params',",
"from launch.actions import DeclareLaunchArgument, SetEnvironmentVariable from launch.substitutions import LaunchConfiguration, ThisLaunchFileDir config = LaunchConfiguration(",
"import LaunchDescription from launch_ros.actions import Node from launch.actions import DeclareLaunchArgument, SetEnvironmentVariable from launch.substitutions",
"DeclareLaunchArgument, SetEnvironmentVariable from launch.substitutions import LaunchConfiguration, ThisLaunchFileDir config = LaunchConfiguration( 'params', default=[ThisLaunchFileDir(), '/teleop.yaml'])"
] |
[
"Pillow #from colors.py import generate_colors import colorthief from colorthief import ColorThief import glob",
"def get_files(): files = list(Path('blockchains').glob('**/*.png')) return files #print (get_files()) def main(): colors_list =",
"= get_colors(i) name = str(i).split('/')[-2] if name == 'info': name = str(i).split('/')[-3] tmp",
"def get_colors(image): dominant_color = ColorThief(image).get_palette(color_count=3, quality=3) return dominant_color #print (get_colors('blockchains/polygon/info/logo.png')) def get_files(): files",
"if name == 'info': name = str(i).split('/')[-3] tmp = {name: color} print(tmp) colors_list.append(tmp)",
"import colorthief from colorthief import ColorThief import glob from pathlib import Path def",
"files #print (get_files()) def main(): colors_list = [] for i in get_files(): color",
"#import Pillow #from colors.py import generate_colors import colorthief from colorthief import ColorThief import",
"pathlib import Path def get_colors(image): dominant_color = ColorThief(image).get_palette(color_count=3, quality=3) return dominant_color #print (get_colors('blockchains/polygon/info/logo.png'))",
"ColorThief(image).get_palette(color_count=3, quality=3) return dominant_color #print (get_colors('blockchains/polygon/info/logo.png')) def get_files(): files = list(Path('blockchains').glob('**/*.png')) return files",
"name == 'info': name = str(i).split('/')[-3] tmp = {name: color} print(tmp) colors_list.append(tmp) print(colors_list)",
"[] for i in get_files(): color = get_colors(i) name = str(i).split('/')[-2] if name",
"= ColorThief(image).get_palette(color_count=3, quality=3) return dominant_color #print (get_colors('blockchains/polygon/info/logo.png')) def get_files(): files = list(Path('blockchains').glob('**/*.png')) return",
"generate_colors import colorthief from colorthief import ColorThief import glob from pathlib import Path",
"#print (get_colors('blockchains/polygon/info/logo.png')) def get_files(): files = list(Path('blockchains').glob('**/*.png')) return files #print (get_files()) def main():",
"#from colors.py import generate_colors import colorthief from colorthief import ColorThief import glob from",
"colors_list = [] for i in get_files(): color = get_colors(i) name = str(i).split('/')[-2]",
"import Path def get_colors(image): dominant_color = ColorThief(image).get_palette(color_count=3, quality=3) return dominant_color #print (get_colors('blockchains/polygon/info/logo.png')) def",
"in get_files(): color = get_colors(i) name = str(i).split('/')[-2] if name == 'info': name",
"name = str(i).split('/')[-2] if name == 'info': name = str(i).split('/')[-3] tmp = {name:",
"str(i).split('/')[-2] if name == 'info': name = str(i).split('/')[-3] tmp = {name: color} print(tmp)",
"get_files(): files = list(Path('blockchains').glob('**/*.png')) return files #print (get_files()) def main(): colors_list = []",
"(get_colors('blockchains/polygon/info/logo.png')) def get_files(): files = list(Path('blockchains').glob('**/*.png')) return files #print (get_files()) def main(): colors_list",
"= [] for i in get_files(): color = get_colors(i) name = str(i).split('/')[-2] if",
"main(): colors_list = [] for i in get_files(): color = get_colors(i) name =",
"import ColorThief import glob from pathlib import Path def get_colors(image): dominant_color = ColorThief(image).get_palette(color_count=3,",
"def main(): colors_list = [] for i in get_files(): color = get_colors(i) name",
"import generate_colors import colorthief from colorthief import ColorThief import glob from pathlib import",
"dominant_color #print (get_colors('blockchains/polygon/info/logo.png')) def get_files(): files = list(Path('blockchains').glob('**/*.png')) return files #print (get_files()) def",
"== 'info': name = str(i).split('/')[-3] tmp = {name: color} print(tmp) colors_list.append(tmp) print(colors_list) main()",
"files = list(Path('blockchains').glob('**/*.png')) return files #print (get_files()) def main(): colors_list = [] for",
"import glob from pathlib import Path def get_colors(image): dominant_color = ColorThief(image).get_palette(color_count=3, quality=3) return",
"#print (get_files()) def main(): colors_list = [] for i in get_files(): color =",
"colorthief import ColorThief import glob from pathlib import Path def get_colors(image): dominant_color =",
"from pathlib import Path def get_colors(image): dominant_color = ColorThief(image).get_palette(color_count=3, quality=3) return dominant_color #print",
"for i in get_files(): color = get_colors(i) name = str(i).split('/')[-2] if name ==",
"get_colors(image): dominant_color = ColorThief(image).get_palette(color_count=3, quality=3) return dominant_color #print (get_colors('blockchains/polygon/info/logo.png')) def get_files(): files =",
"colors.py import generate_colors import colorthief from colorthief import ColorThief import glob from pathlib",
"Path def get_colors(image): dominant_color = ColorThief(image).get_palette(color_count=3, quality=3) return dominant_color #print (get_colors('blockchains/polygon/info/logo.png')) def get_files():",
"get_files(): color = get_colors(i) name = str(i).split('/')[-2] if name == 'info': name =",
"quality=3) return dominant_color #print (get_colors('blockchains/polygon/info/logo.png')) def get_files(): files = list(Path('blockchains').glob('**/*.png')) return files #print",
"return files #print (get_files()) def main(): colors_list = [] for i in get_files():",
"i in get_files(): color = get_colors(i) name = str(i).split('/')[-2] if name == 'info':",
"get_colors(i) name = str(i).split('/')[-2] if name == 'info': name = str(i).split('/')[-3] tmp =",
"= list(Path('blockchains').glob('**/*.png')) return files #print (get_files()) def main(): colors_list = [] for i",
"= str(i).split('/')[-2] if name == 'info': name = str(i).split('/')[-3] tmp = {name: color}",
"return dominant_color #print (get_colors('blockchains/polygon/info/logo.png')) def get_files(): files = list(Path('blockchains').glob('**/*.png')) return files #print (get_files())",
"(get_files()) def main(): colors_list = [] for i in get_files(): color = get_colors(i)",
"colorthief from colorthief import ColorThief import glob from pathlib import Path def get_colors(image):",
"from colorthief import ColorThief import glob from pathlib import Path def get_colors(image): dominant_color",
"color = get_colors(i) name = str(i).split('/')[-2] if name == 'info': name = str(i).split('/')[-3]",
"dominant_color = ColorThief(image).get_palette(color_count=3, quality=3) return dominant_color #print (get_colors('blockchains/polygon/info/logo.png')) def get_files(): files = list(Path('blockchains').glob('**/*.png'))",
"list(Path('blockchains').glob('**/*.png')) return files #print (get_files()) def main(): colors_list = [] for i in",
"glob from pathlib import Path def get_colors(image): dominant_color = ColorThief(image).get_palette(color_count=3, quality=3) return dominant_color",
"ColorThief import glob from pathlib import Path def get_colors(image): dominant_color = ColorThief(image).get_palette(color_count=3, quality=3)"
] |
[
"= input(\"请输入查询的单词/输入‘886’离开:\") if unknown_word == '886': empty = input(\"将要替代上次记录的结果,按回车继续...\") df.to_csv('./save_recode_english.csv', index=False, header=False, encoding='utf-8_sig')",
"is None: return None phonetic_symbols = phonetic_symbols.find_all('li') if len(phonetic_symbols) < 2: return None",
"continue sentence = input(\"输入例句/输入'N'不保存:\") if sentence != 'N': source = input(\"输入例句来源(可选):\") df =",
"raw_definitions = m.find_all('span') sub_definitions = [lexical_category] for d in raw_definitions: sub_definitions.append(d.text) definitions.append(' '.join(sub_definitions))",
"output if __name__ == '__main__': df = pd.DataFrame(columns=[\"Word\", \"Audio\", \"Meaning\", \"Example\", \"Source\"]) dictionary",
"m.find('i').string raw_definitions = m.find_all('span') sub_definitions = [lexical_category] for d in raw_definitions: sub_definitions.append(d.text) definitions.append('",
"__name__ == '__main__': df = pd.DataFrame(columns=[\"Word\", \"Audio\", \"Meaning\", \"Example\", \"Source\"]) dictionary = MyEnglishDict(\"http://www.iciba.com/word?w=\")",
"m.find_all('span') sub_definitions = [lexical_category] for d in raw_definitions: sub_definitions.append(d.text) definitions.append(' '.join(sub_definitions)) output['definitions'] =",
"while True: print(\"//--------------------------------------\") unknown_word = input(\"请输入查询的单词/输入‘886’离开:\") if unknown_word == '886': empty = input(\"将要替代上次记录的结果,按回车继续...\")",
"print(\"//--------------------------------------\") unknown_word = input(\"请输入查询的单词/输入‘886’离开:\") if unknown_word == '886': empty = input(\"将要替代上次记录的结果,按回车继续...\") df.to_csv('./save_recode_english.csv', index=False,",
"print(output['phonetic_symbol']) meanings = raw_text.find(name='ul', class_='Mean_part__1RA2V').find_all('li') if meanings is None: return None definitions =",
"input(\"输入例句/输入'N'不保存:\") if sentence != 'N': source = input(\"输入例句来源(可选):\") df = df.append([{'Word': unknown_word, \"Audio\":",
"pd from crawler import MyDict class MyEnglishDict(MyDict): def __init__(self, url): super(MyEnglishDict, self).__init__(url) def",
"if result is None: print(\"找不到单词TAT\") continue sentence = input(\"输入例句/输入'N'不保存:\") if sentence != 'N':",
"sub_definitions.append(d.text) definitions.append(' '.join(sub_definitions)) output['definitions'] = '\\n'.join(definitions) print(output['definitions']) return output if __name__ == '__main__':",
"phonetic_symbols is None: return None phonetic_symbols = phonetic_symbols.find_all('li') if len(phonetic_symbols) < 2: return",
"dictionary.lookup(unknown_word) if result is None: print(\"找不到单词TAT\") continue sentence = input(\"输入例句/输入'N'不保存:\") if sentence !=",
"= [lexical_category] for d in raw_definitions: sub_definitions.append(d.text) definitions.append(' '.join(sub_definitions)) output['definitions'] = '\\n'.join(definitions) print(output['definitions'])",
"None phonetic_symbols = phonetic_symbols.find_all('li') if len(phonetic_symbols) < 2: return None phonetic_symbols_text = [x",
"= m.find_all('span') sub_definitions = [lexical_category] for d in raw_definitions: sub_definitions.append(d.text) definitions.append(' '.join(sub_definitions)) output['definitions']",
"return None phonetic_symbols = phonetic_symbols.find_all('li') if len(phonetic_symbols) < 2: return None phonetic_symbols_text =",
"print(\"找不到单词TAT\") continue sentence = input(\"输入例句/输入'N'不保存:\") if sentence != 'N': source = input(\"输入例句来源(可选):\") df",
"d in raw_definitions: sub_definitions.append(d.text) definitions.append(' '.join(sub_definitions)) output['definitions'] = '\\n'.join(definitions) print(output['definitions']) return output if",
"as pd from crawler import MyDict class MyEnglishDict(MyDict): def __init__(self, url): super(MyEnglishDict, self).__init__(url)",
"encoding='utf-8_sig') break result = dictionary.lookup(unknown_word) if result is None: print(\"找不到单词TAT\") continue sentence =",
"= MyEnglishDict(\"http://www.iciba.com/word?w=\") while True: print(\"//--------------------------------------\") unknown_word = input(\"请输入查询的单词/输入‘886’离开:\") if unknown_word == '886': empty",
"= {} raw_text = self.get_web_result(self.url, word) phonetic_symbols = raw_text.find(name='ul', class_='Mean_symbols__5dQX7') if phonetic_symbols is",
"'.join(sub_definitions)) output['definitions'] = '\\n'.join(definitions) print(output['definitions']) return output if __name__ == '__main__': df =",
"class_='Mean_symbols__5dQX7') if phonetic_symbols is None: return None phonetic_symbols = phonetic_symbols.find_all('li') if len(phonetic_symbols) <",
"None phonetic_symbols_text = [x for x in phonetic_symbols[1].strings] output['phonetic_symbol'] = phonetic_symbols_text[1] print(output['phonetic_symbol']) meanings",
"if phonetic_symbols is None: return None phonetic_symbols = phonetic_symbols.find_all('li') if len(phonetic_symbols) < 2:",
"is None: return None definitions = [] for m in meanings: lexical_category =",
"output['phonetic_symbol'] = phonetic_symbols_text[1] print(output['phonetic_symbol']) meanings = raw_text.find(name='ul', class_='Mean_part__1RA2V').find_all('li') if meanings is None: return",
"word) phonetic_symbols = raw_text.find(name='ul', class_='Mean_symbols__5dQX7') if phonetic_symbols is None: return None phonetic_symbols =",
"result is None: print(\"找不到单词TAT\") continue sentence = input(\"输入例句/输入'N'不保存:\") if sentence != 'N': source",
"output = {} raw_text = self.get_web_result(self.url, word) phonetic_symbols = raw_text.find(name='ul', class_='Mean_symbols__5dQX7') if phonetic_symbols",
"lookup(self, word): output = {} raw_text = self.get_web_result(self.url, word) phonetic_symbols = raw_text.find(name='ul', class_='Mean_symbols__5dQX7')",
"class MyEnglishDict(MyDict): def __init__(self, url): super(MyEnglishDict, self).__init__(url) def lookup(self, word): output = {}",
"in meanings: lexical_category = m.find('i').string raw_definitions = m.find_all('span') sub_definitions = [lexical_category] for d",
"result = dictionary.lookup(unknown_word) if result is None: print(\"找不到单词TAT\") continue sentence = input(\"输入例句/输入'N'不保存:\") if",
"df = pd.DataFrame(columns=[\"Word\", \"Audio\", \"Meaning\", \"Example\", \"Source\"]) dictionary = MyEnglishDict(\"http://www.iciba.com/word?w=\") while True: print(\"//--------------------------------------\")",
"if len(phonetic_symbols) < 2: return None phonetic_symbols_text = [x for x in phonetic_symbols[1].strings]",
"= [x for x in phonetic_symbols[1].strings] output['phonetic_symbol'] = phonetic_symbols_text[1] print(output['phonetic_symbol']) meanings = raw_text.find(name='ul',",
"= input(\"输入例句/输入'N'不保存:\") if sentence != 'N': source = input(\"输入例句来源(可选):\") df = df.append([{'Word': unknown_word,",
"sentence != 'N': source = input(\"输入例句来源(可选):\") df = df.append([{'Word': unknown_word, \"Audio\": result['phonetic_symbol'], \"Meaning\":",
"None: return None phonetic_symbols = phonetic_symbols.find_all('li') if len(phonetic_symbols) < 2: return None phonetic_symbols_text",
"phonetic_symbols_text = [x for x in phonetic_symbols[1].strings] output['phonetic_symbol'] = phonetic_symbols_text[1] print(output['phonetic_symbol']) meanings =",
"\"Meaning\", \"Example\", \"Source\"]) dictionary = MyEnglishDict(\"http://www.iciba.com/word?w=\") while True: print(\"//--------------------------------------\") unknown_word = input(\"请输入查询的单词/输入‘886’离开:\") if",
"= raw_text.find(name='ul', class_='Mean_part__1RA2V').find_all('li') if meanings is None: return None definitions = [] for",
"word): output = {} raw_text = self.get_web_result(self.url, word) phonetic_symbols = raw_text.find(name='ul', class_='Mean_symbols__5dQX7') if",
"input(\"将要替代上次记录的结果,按回车继续...\") df.to_csv('./save_recode_english.csv', index=False, header=False, encoding='utf-8_sig') break result = dictionary.lookup(unknown_word) if result is None:",
"import MyDict class MyEnglishDict(MyDict): def __init__(self, url): super(MyEnglishDict, self).__init__(url) def lookup(self, word): output",
"raw_text.find(name='ul', class_='Mean_symbols__5dQX7') if phonetic_symbols is None: return None phonetic_symbols = phonetic_symbols.find_all('li') if len(phonetic_symbols)",
"phonetic_symbols[1].strings] output['phonetic_symbol'] = phonetic_symbols_text[1] print(output['phonetic_symbol']) meanings = raw_text.find(name='ul', class_='Mean_part__1RA2V').find_all('li') if meanings is None:",
"definitions.append(' '.join(sub_definitions)) output['definitions'] = '\\n'.join(definitions) print(output['definitions']) return output if __name__ == '__main__': df",
"'N': source = input(\"输入例句来源(可选):\") df = df.append([{'Word': unknown_word, \"Audio\": result['phonetic_symbol'], \"Meaning\": result['definitions'], \"Example\":",
"= input(\"输入例句来源(可选):\") df = df.append([{'Word': unknown_word, \"Audio\": result['phonetic_symbol'], \"Meaning\": result['definitions'], \"Example\": sentence, \"Source\":",
"for m in meanings: lexical_category = m.find('i').string raw_definitions = m.find_all('span') sub_definitions = [lexical_category]",
"None: return None definitions = [] for m in meanings: lexical_category = m.find('i').string",
"len(phonetic_symbols) < 2: return None phonetic_symbols_text = [x for x in phonetic_symbols[1].strings] output['phonetic_symbol']",
"self).__init__(url) def lookup(self, word): output = {} raw_text = self.get_web_result(self.url, word) phonetic_symbols =",
"meanings = raw_text.find(name='ul', class_='Mean_part__1RA2V').find_all('li') if meanings is None: return None definitions = []",
"pd.DataFrame(columns=[\"Word\", \"Audio\", \"Meaning\", \"Example\", \"Source\"]) dictionary = MyEnglishDict(\"http://www.iciba.com/word?w=\") while True: print(\"//--------------------------------------\") unknown_word =",
"'\\n'.join(definitions) print(output['definitions']) return output if __name__ == '__main__': df = pd.DataFrame(columns=[\"Word\", \"Audio\", \"Meaning\",",
"in phonetic_symbols[1].strings] output['phonetic_symbol'] = phonetic_symbols_text[1] print(output['phonetic_symbol']) meanings = raw_text.find(name='ul', class_='Mean_part__1RA2V').find_all('li') if meanings is",
"lexical_category = m.find('i').string raw_definitions = m.find_all('span') sub_definitions = [lexical_category] for d in raw_definitions:",
"= input(\"将要替代上次记录的结果,按回车继续...\") df.to_csv('./save_recode_english.csv', index=False, header=False, encoding='utf-8_sig') break result = dictionary.lookup(unknown_word) if result is",
"= raw_text.find(name='ul', class_='Mean_symbols__5dQX7') if phonetic_symbols is None: return None phonetic_symbols = phonetic_symbols.find_all('li') if",
"\"Example\", \"Source\"]) dictionary = MyEnglishDict(\"http://www.iciba.com/word?w=\") while True: print(\"//--------------------------------------\") unknown_word = input(\"请输入查询的单词/输入‘886’离开:\") if unknown_word",
"MyEnglishDict(MyDict): def __init__(self, url): super(MyEnglishDict, self).__init__(url) def lookup(self, word): output = {} raw_text",
"meanings is None: return None definitions = [] for m in meanings: lexical_category",
"= m.find('i').string raw_definitions = m.find_all('span') sub_definitions = [lexical_category] for d in raw_definitions: sub_definitions.append(d.text)",
"__init__(self, url): super(MyEnglishDict, self).__init__(url) def lookup(self, word): output = {} raw_text = self.get_web_result(self.url,",
"url): super(MyEnglishDict, self).__init__(url) def lookup(self, word): output = {} raw_text = self.get_web_result(self.url, word)",
"= pd.DataFrame(columns=[\"Word\", \"Audio\", \"Meaning\", \"Example\", \"Source\"]) dictionary = MyEnglishDict(\"http://www.iciba.com/word?w=\") while True: print(\"//--------------------------------------\") unknown_word",
"class_='Mean_part__1RA2V').find_all('li') if meanings is None: return None definitions = [] for m in",
"[x for x in phonetic_symbols[1].strings] output['phonetic_symbol'] = phonetic_symbols_text[1] print(output['phonetic_symbol']) meanings = raw_text.find(name='ul', class_='Mean_part__1RA2V').find_all('li')",
"pandas as pd from crawler import MyDict class MyEnglishDict(MyDict): def __init__(self, url): super(MyEnglishDict,",
"'__main__': df = pd.DataFrame(columns=[\"Word\", \"Audio\", \"Meaning\", \"Example\", \"Source\"]) dictionary = MyEnglishDict(\"http://www.iciba.com/word?w=\") while True:",
"sub_definitions = [lexical_category] for d in raw_definitions: sub_definitions.append(d.text) definitions.append(' '.join(sub_definitions)) output['definitions'] = '\\n'.join(definitions)",
"unknown_word == '886': empty = input(\"将要替代上次记录的结果,按回车继续...\") df.to_csv('./save_recode_english.csv', index=False, header=False, encoding='utf-8_sig') break result =",
"'886': empty = input(\"将要替代上次记录的结果,按回车继续...\") df.to_csv('./save_recode_english.csv', index=False, header=False, encoding='utf-8_sig') break result = dictionary.lookup(unknown_word) if",
"df = df.append([{'Word': unknown_word, \"Audio\": result['phonetic_symbol'], \"Meaning\": result['definitions'], \"Example\": sentence, \"Source\": source}], ignore_index=True)",
"if __name__ == '__main__': df = pd.DataFrame(columns=[\"Word\", \"Audio\", \"Meaning\", \"Example\", \"Source\"]) dictionary =",
"def __init__(self, url): super(MyEnglishDict, self).__init__(url) def lookup(self, word): output = {} raw_text =",
"index=False, header=False, encoding='utf-8_sig') break result = dictionary.lookup(unknown_word) if result is None: print(\"找不到单词TAT\") continue",
"raw_text.find(name='ul', class_='Mean_part__1RA2V').find_all('li') if meanings is None: return None definitions = [] for m",
"print(output['definitions']) return output if __name__ == '__main__': df = pd.DataFrame(columns=[\"Word\", \"Audio\", \"Meaning\", \"Example\",",
"meanings: lexical_category = m.find('i').string raw_definitions = m.find_all('span') sub_definitions = [lexical_category] for d in",
"= self.get_web_result(self.url, word) phonetic_symbols = raw_text.find(name='ul', class_='Mean_symbols__5dQX7') if phonetic_symbols is None: return None",
"for d in raw_definitions: sub_definitions.append(d.text) definitions.append(' '.join(sub_definitions)) output['definitions'] = '\\n'.join(definitions) print(output['definitions']) return output",
"unknown_word = input(\"请输入查询的单词/输入‘886’离开:\") if unknown_word == '886': empty = input(\"将要替代上次记录的结果,按回车继续...\") df.to_csv('./save_recode_english.csv', index=False, header=False,",
"empty = input(\"将要替代上次记录的结果,按回车继续...\") df.to_csv('./save_recode_english.csv', index=False, header=False, encoding='utf-8_sig') break result = dictionary.lookup(unknown_word) if result",
"= phonetic_symbols_text[1] print(output['phonetic_symbol']) meanings = raw_text.find(name='ul', class_='Mean_part__1RA2V').find_all('li') if meanings is None: return None",
"if unknown_word == '886': empty = input(\"将要替代上次记录的结果,按回车继续...\") df.to_csv('./save_recode_english.csv', index=False, header=False, encoding='utf-8_sig') break result",
"dictionary = MyEnglishDict(\"http://www.iciba.com/word?w=\") while True: print(\"//--------------------------------------\") unknown_word = input(\"请输入查询的单词/输入‘886’离开:\") if unknown_word == '886':",
"= [] for m in meanings: lexical_category = m.find('i').string raw_definitions = m.find_all('span') sub_definitions",
"in raw_definitions: sub_definitions.append(d.text) definitions.append(' '.join(sub_definitions)) output['definitions'] = '\\n'.join(definitions) print(output['definitions']) return output if __name__",
"[lexical_category] for d in raw_definitions: sub_definitions.append(d.text) definitions.append(' '.join(sub_definitions)) output['definitions'] = '\\n'.join(definitions) print(output['definitions']) return",
"None definitions = [] for m in meanings: lexical_category = m.find('i').string raw_definitions =",
"output['definitions'] = '\\n'.join(definitions) print(output['definitions']) return output if __name__ == '__main__': df = pd.DataFrame(columns=[\"Word\",",
"sentence = input(\"输入例句/输入'N'不保存:\") if sentence != 'N': source = input(\"输入例句来源(可选):\") df = df.append([{'Word':",
"return None definitions = [] for m in meanings: lexical_category = m.find('i').string raw_definitions",
"\"Audio\", \"Meaning\", \"Example\", \"Source\"]) dictionary = MyEnglishDict(\"http://www.iciba.com/word?w=\") while True: print(\"//--------------------------------------\") unknown_word = input(\"请输入查询的单词/输入‘886’离开:\")",
"True: print(\"//--------------------------------------\") unknown_word = input(\"请输入查询的单词/输入‘886’离开:\") if unknown_word == '886': empty = input(\"将要替代上次记录的结果,按回车继续...\") df.to_csv('./save_recode_english.csv',",
"== '__main__': df = pd.DataFrame(columns=[\"Word\", \"Audio\", \"Meaning\", \"Example\", \"Source\"]) dictionary = MyEnglishDict(\"http://www.iciba.com/word?w=\") while",
"return None phonetic_symbols_text = [x for x in phonetic_symbols[1].strings] output['phonetic_symbol'] = phonetic_symbols_text[1] print(output['phonetic_symbol'])",
"\"Source\"]) dictionary = MyEnglishDict(\"http://www.iciba.com/word?w=\") while True: print(\"//--------------------------------------\") unknown_word = input(\"请输入查询的单词/输入‘886’离开:\") if unknown_word ==",
"import pandas as pd from crawler import MyDict class MyEnglishDict(MyDict): def __init__(self, url):",
"== '886': empty = input(\"将要替代上次记录的结果,按回车继续...\") df.to_csv('./save_recode_english.csv', index=False, header=False, encoding='utf-8_sig') break result = dictionary.lookup(unknown_word)",
"m in meanings: lexical_category = m.find('i').string raw_definitions = m.find_all('span') sub_definitions = [lexical_category] for",
"= phonetic_symbols.find_all('li') if len(phonetic_symbols) < 2: return None phonetic_symbols_text = [x for x",
"for x in phonetic_symbols[1].strings] output['phonetic_symbol'] = phonetic_symbols_text[1] print(output['phonetic_symbol']) meanings = raw_text.find(name='ul', class_='Mean_part__1RA2V').find_all('li') if",
"self.get_web_result(self.url, word) phonetic_symbols = raw_text.find(name='ul', class_='Mean_symbols__5dQX7') if phonetic_symbols is None: return None phonetic_symbols",
"phonetic_symbols = phonetic_symbols.find_all('li') if len(phonetic_symbols) < 2: return None phonetic_symbols_text = [x for",
"if sentence != 'N': source = input(\"输入例句来源(可选):\") df = df.append([{'Word': unknown_word, \"Audio\": result['phonetic_symbol'],",
"if meanings is None: return None definitions = [] for m in meanings:",
"df.to_csv('./save_recode_english.csv', index=False, header=False, encoding='utf-8_sig') break result = dictionary.lookup(unknown_word) if result is None: print(\"找不到单词TAT\")",
"phonetic_symbols.find_all('li') if len(phonetic_symbols) < 2: return None phonetic_symbols_text = [x for x in",
"MyEnglishDict(\"http://www.iciba.com/word?w=\") while True: print(\"//--------------------------------------\") unknown_word = input(\"请输入查询的单词/输入‘886’离开:\") if unknown_word == '886': empty =",
"crawler import MyDict class MyEnglishDict(MyDict): def __init__(self, url): super(MyEnglishDict, self).__init__(url) def lookup(self, word):",
"!= 'N': source = input(\"输入例句来源(可选):\") df = df.append([{'Word': unknown_word, \"Audio\": result['phonetic_symbol'], \"Meaning\": result['definitions'],",
"= '\\n'.join(definitions) print(output['definitions']) return output if __name__ == '__main__': df = pd.DataFrame(columns=[\"Word\", \"Audio\",",
"None: print(\"找不到单词TAT\") continue sentence = input(\"输入例句/输入'N'不保存:\") if sentence != 'N': source = input(\"输入例句来源(可选):\")",
"< 2: return None phonetic_symbols_text = [x for x in phonetic_symbols[1].strings] output['phonetic_symbol'] =",
"raw_text = self.get_web_result(self.url, word) phonetic_symbols = raw_text.find(name='ul', class_='Mean_symbols__5dQX7') if phonetic_symbols is None: return",
"x in phonetic_symbols[1].strings] output['phonetic_symbol'] = phonetic_symbols_text[1] print(output['phonetic_symbol']) meanings = raw_text.find(name='ul', class_='Mean_part__1RA2V').find_all('li') if meanings",
"input(\"输入例句来源(可选):\") df = df.append([{'Word': unknown_word, \"Audio\": result['phonetic_symbol'], \"Meaning\": result['definitions'], \"Example\": sentence, \"Source\": source}],",
"raw_definitions: sub_definitions.append(d.text) definitions.append(' '.join(sub_definitions)) output['definitions'] = '\\n'.join(definitions) print(output['definitions']) return output if __name__ ==",
"source = input(\"输入例句来源(可选):\") df = df.append([{'Word': unknown_word, \"Audio\": result['phonetic_symbol'], \"Meaning\": result['definitions'], \"Example\": sentence,",
"def lookup(self, word): output = {} raw_text = self.get_web_result(self.url, word) phonetic_symbols = raw_text.find(name='ul',",
"2: return None phonetic_symbols_text = [x for x in phonetic_symbols[1].strings] output['phonetic_symbol'] = phonetic_symbols_text[1]",
"= dictionary.lookup(unknown_word) if result is None: print(\"找不到单词TAT\") continue sentence = input(\"输入例句/输入'N'不保存:\") if sentence",
"definitions = [] for m in meanings: lexical_category = m.find('i').string raw_definitions = m.find_all('span')",
"header=False, encoding='utf-8_sig') break result = dictionary.lookup(unknown_word) if result is None: print(\"找不到单词TAT\") continue sentence",
"input(\"请输入查询的单词/输入‘886’离开:\") if unknown_word == '886': empty = input(\"将要替代上次记录的结果,按回车继续...\") df.to_csv('./save_recode_english.csv', index=False, header=False, encoding='utf-8_sig') break",
"break result = dictionary.lookup(unknown_word) if result is None: print(\"找不到单词TAT\") continue sentence = input(\"输入例句/输入'N'不保存:\")",
"phonetic_symbols_text[1] print(output['phonetic_symbol']) meanings = raw_text.find(name='ul', class_='Mean_part__1RA2V').find_all('li') if meanings is None: return None definitions",
"[] for m in meanings: lexical_category = m.find('i').string raw_definitions = m.find_all('span') sub_definitions =",
"from crawler import MyDict class MyEnglishDict(MyDict): def __init__(self, url): super(MyEnglishDict, self).__init__(url) def lookup(self,",
"MyDict class MyEnglishDict(MyDict): def __init__(self, url): super(MyEnglishDict, self).__init__(url) def lookup(self, word): output =",
"phonetic_symbols = raw_text.find(name='ul', class_='Mean_symbols__5dQX7') if phonetic_symbols is None: return None phonetic_symbols = phonetic_symbols.find_all('li')",
"return output if __name__ == '__main__': df = pd.DataFrame(columns=[\"Word\", \"Audio\", \"Meaning\", \"Example\", \"Source\"])",
"super(MyEnglishDict, self).__init__(url) def lookup(self, word): output = {} raw_text = self.get_web_result(self.url, word) phonetic_symbols",
"{} raw_text = self.get_web_result(self.url, word) phonetic_symbols = raw_text.find(name='ul', class_='Mean_symbols__5dQX7') if phonetic_symbols is None:",
"is None: print(\"找不到单词TAT\") continue sentence = input(\"输入例句/输入'N'不保存:\") if sentence != 'N': source ="
] |
[
"locale import time def read_api_key(path): \"\"\"read api key from given path\"\"\" path =",
"key found at given path: \" + path) with open(path) as f: return",
"def set_locale_de(): \"\"\"set the current locale to German or de_DE.utf8 (depending on the",
"setting locale and getting well formated time\"\"\" import os import platform import locale",
"f: return f.readline().strip() def set_locale_de(): \"\"\"set the current locale to German or de_DE.utf8",
"os.path.abspath(path) if not os.path.exists(path): raise ValueError(\"no key found at given path: \" +",
"the current locale to German or de_DE.utf8 (depending on the os)\"\"\" try: if",
"try: if platform.system() == \"Windows\": locale.setlocale(locale.LC_ALL, \"German\") else: locale.setlocale(locale.LC_ALL, \"de_DE.utf8\") except locale.Error: pass",
"if platform.system() == \"Windows\": locale.setlocale(locale.LC_ALL, \"German\") else: locale.setlocale(locale.LC_ALL, \"de_DE.utf8\") except locale.Error: pass def",
"locale.setlocale(locale.LC_ALL, \"German\") else: locale.setlocale(locale.LC_ALL, \"de_DE.utf8\") except locale.Error: pass def get_time_human_readable(): \"\"\" returns well",
"open(path) as f: return f.readline().strip() def set_locale_de(): \"\"\"set the current locale to German",
"locale and getting well formated time\"\"\" import os import platform import locale import",
"os)\"\"\" try: if platform.system() == \"Windows\": locale.setlocale(locale.LC_ALL, \"German\") else: locale.setlocale(locale.LC_ALL, \"de_DE.utf8\") except locale.Error:",
"(depending on the os)\"\"\" try: if platform.system() == \"Windows\": locale.setlocale(locale.LC_ALL, \"German\") else: locale.setlocale(locale.LC_ALL,",
"api key from given path\"\"\" path = os.path.abspath(path) if not os.path.exists(path): raise ValueError(\"no",
"current locale to German or de_DE.utf8 (depending on the os)\"\"\" try: if platform.system()",
"\" + path) with open(path) as f: return f.readline().strip() def set_locale_de(): \"\"\"set the",
"raise ValueError(\"no key found at given path: \" + path) with open(path) as",
"import locale import time def read_api_key(path): \"\"\"read api key from given path\"\"\" path",
"platform.system() == \"Windows\": locale.setlocale(locale.LC_ALL, \"German\") else: locale.setlocale(locale.LC_ALL, \"de_DE.utf8\") except locale.Error: pass def get_time_human_readable():",
"returns well formated time string. for example: Donnerstag, 21:00 \"\"\" return time.strftime(\"%A, %H:%M\")",
"def get_time_human_readable(): \"\"\" returns well formated time string. for example: Donnerstag, 21:00 \"\"\"",
"\"\"\" returns well formated time string. for example: Donnerstag, 21:00 \"\"\" return time.strftime(\"%A,",
"+ path) with open(path) as f: return f.readline().strip() def set_locale_de(): \"\"\"set the current",
"pass def get_time_human_readable(): \"\"\" returns well formated time string. for example: Donnerstag, 21:00",
"os import platform import locale import time def read_api_key(path): \"\"\"read api key from",
"at given path: \" + path) with open(path) as f: return f.readline().strip() def",
"path\"\"\" path = os.path.abspath(path) if not os.path.exists(path): raise ValueError(\"no key found at given",
"for setting locale and getting well formated time\"\"\" import os import platform import",
"read_api_key(path): \"\"\"read api key from given path\"\"\" path = os.path.abspath(path) if not os.path.exists(path):",
"time def read_api_key(path): \"\"\"read api key from given path\"\"\" path = os.path.abspath(path) if",
"path) with open(path) as f: return f.readline().strip() def set_locale_de(): \"\"\"set the current locale",
"found at given path: \" + path) with open(path) as f: return f.readline().strip()",
"time\"\"\" import os import platform import locale import time def read_api_key(path): \"\"\"read api",
"\"\"\"read api key from given path\"\"\" path = os.path.abspath(path) if not os.path.exists(path): raise",
"== \"Windows\": locale.setlocale(locale.LC_ALL, \"German\") else: locale.setlocale(locale.LC_ALL, \"de_DE.utf8\") except locale.Error: pass def get_time_human_readable(): \"\"\"",
"<filename>weatherstation/misc/utils.py \"\"\"utils for setting locale and getting well formated time\"\"\" import os import",
"path: \" + path) with open(path) as f: return f.readline().strip() def set_locale_de(): \"\"\"set",
"\"Windows\": locale.setlocale(locale.LC_ALL, \"German\") else: locale.setlocale(locale.LC_ALL, \"de_DE.utf8\") except locale.Error: pass def get_time_human_readable(): \"\"\" returns",
"path = os.path.abspath(path) if not os.path.exists(path): raise ValueError(\"no key found at given path:",
"locale to German or de_DE.utf8 (depending on the os)\"\"\" try: if platform.system() ==",
"given path: \" + path) with open(path) as f: return f.readline().strip() def set_locale_de():",
"given path\"\"\" path = os.path.abspath(path) if not os.path.exists(path): raise ValueError(\"no key found at",
"the os)\"\"\" try: if platform.system() == \"Windows\": locale.setlocale(locale.LC_ALL, \"German\") else: locale.setlocale(locale.LC_ALL, \"de_DE.utf8\") except",
"with open(path) as f: return f.readline().strip() def set_locale_de(): \"\"\"set the current locale to",
"get_time_human_readable(): \"\"\" returns well formated time string. for example: Donnerstag, 21:00 \"\"\" return",
"\"\"\"utils for setting locale and getting well formated time\"\"\" import os import platform",
"f.readline().strip() def set_locale_de(): \"\"\"set the current locale to German or de_DE.utf8 (depending on",
"os.path.exists(path): raise ValueError(\"no key found at given path: \" + path) with open(path)",
"if not os.path.exists(path): raise ValueError(\"no key found at given path: \" + path)",
"return f.readline().strip() def set_locale_de(): \"\"\"set the current locale to German or de_DE.utf8 (depending",
"import os import platform import locale import time def read_api_key(path): \"\"\"read api key",
"well formated time\"\"\" import os import platform import locale import time def read_api_key(path):",
"to German or de_DE.utf8 (depending on the os)\"\"\" try: if platform.system() == \"Windows\":",
"key from given path\"\"\" path = os.path.abspath(path) if not os.path.exists(path): raise ValueError(\"no key",
"locale.Error: pass def get_time_human_readable(): \"\"\" returns well formated time string. for example: Donnerstag,",
"or de_DE.utf8 (depending on the os)\"\"\" try: if platform.system() == \"Windows\": locale.setlocale(locale.LC_ALL, \"German\")",
"else: locale.setlocale(locale.LC_ALL, \"de_DE.utf8\") except locale.Error: pass def get_time_human_readable(): \"\"\" returns well formated time",
"on the os)\"\"\" try: if platform.system() == \"Windows\": locale.setlocale(locale.LC_ALL, \"German\") else: locale.setlocale(locale.LC_ALL, \"de_DE.utf8\")",
"getting well formated time\"\"\" import os import platform import locale import time def",
"def read_api_key(path): \"\"\"read api key from given path\"\"\" path = os.path.abspath(path) if not",
"= os.path.abspath(path) if not os.path.exists(path): raise ValueError(\"no key found at given path: \"",
"formated time\"\"\" import os import platform import locale import time def read_api_key(path): \"\"\"read",
"\"de_DE.utf8\") except locale.Error: pass def get_time_human_readable(): \"\"\" returns well formated time string. for",
"and getting well formated time\"\"\" import os import platform import locale import time",
"set_locale_de(): \"\"\"set the current locale to German or de_DE.utf8 (depending on the os)\"\"\"",
"import platform import locale import time def read_api_key(path): \"\"\"read api key from given",
"except locale.Error: pass def get_time_human_readable(): \"\"\" returns well formated time string. for example:",
"de_DE.utf8 (depending on the os)\"\"\" try: if platform.system() == \"Windows\": locale.setlocale(locale.LC_ALL, \"German\") else:",
"not os.path.exists(path): raise ValueError(\"no key found at given path: \" + path) with",
"as f: return f.readline().strip() def set_locale_de(): \"\"\"set the current locale to German or",
"\"German\") else: locale.setlocale(locale.LC_ALL, \"de_DE.utf8\") except locale.Error: pass def get_time_human_readable(): \"\"\" returns well formated",
"German or de_DE.utf8 (depending on the os)\"\"\" try: if platform.system() == \"Windows\": locale.setlocale(locale.LC_ALL,",
"platform import locale import time def read_api_key(path): \"\"\"read api key from given path\"\"\"",
"locale.setlocale(locale.LC_ALL, \"de_DE.utf8\") except locale.Error: pass def get_time_human_readable(): \"\"\" returns well formated time string.",
"ValueError(\"no key found at given path: \" + path) with open(path) as f:",
"import time def read_api_key(path): \"\"\"read api key from given path\"\"\" path = os.path.abspath(path)",
"from given path\"\"\" path = os.path.abspath(path) if not os.path.exists(path): raise ValueError(\"no key found",
"\"\"\"set the current locale to German or de_DE.utf8 (depending on the os)\"\"\" try:"
] |
[
"= f.behaviour(\"largest interval\") l,r = float(I.args[0]), float(I.args[1]) for f in functions: I =",
"record of the graphs graphed? this can be done by just keeping the",
"make_graph(self, f): I = f.behaviour(\"largest interval\") ps = float(I.args[0]) pe = float(I.args[1]) t",
"= float(I.args[0]) pe = float(I.args[1]) t = np.arange(ps, pe, 0.01) self.ax.plot(t, f.eval_np(t)) def",
"sp ''' A lot of problems need to be resolved: 1)Can we keep",
"np.arange(l,r,.01) for f in functions: self.ax.plot(t,f.eval_np(t)) def make_secent(self,f,x1,x2): I = f.behaviour(\"largest interval\") ps",
"from mpl_toolkits.axes_grid.axislines import SubplotZero import numpy as np import cyllene.f_functionclass as f_funct import",
"self.ax.plot(np.array([x]), np.array([y]), 'ro') def zoom_y(self, f, I): self.zoom_x(I) self.zoom_y(f.range(I)) def zoom_x(self,I): ps =",
"arrays ? 2)we need to be able to deal with poles of functions",
"= functions[0] I = f.behaviour(\"largest interval\") l,r = float(I.args[0]), float(I.args[1]) for f in",
"in [\"xzero\",\"yzero\"]: self.ax.axis[direction].set_axisline_style(\"-|>\") self.ax.axis[direction].set_visible(True) for direction in [\"left\",\"right\",\"bottom\",\"top\"]: self.ax.axis[direction].set_visible(False) def make_graph(self, f): I",
"sp.Interval(l,r) t = np.arange(l,r,.01) for f in functions: self.ax.plot(t,f.eval_np(t)) def make_secent(self,f,x1,x2): I =",
"= float(I.args[0]) pe = float(I.args[1]) self.ax.set_xlim(ps,pe) def zoom_y(self,I): ps = float(I.args[0]) pe =",
"zoom_y(self, f, I): self.zoom_x(I) self.zoom_y(f.range(I)) def zoom_x(self,I): ps = float(I.args[0]) pe = float(I.args[1])",
"= float(I.args[1]) t = np.arange(ps, pe, 0.01) sec = f.secent_line(x1,x2) self.ax.plot(t, sec.eval_np(t)) self.plot_point(x1,",
"self.ax.plot(t, sec.eval_np(t)) self.plot_point(x1, sec.eval_np(x1)) self.plot_point(x2,sec.eval_np(x2)) def make_tangent(self,f,x): I = f.behaviour(\"largest interval\") ps =",
"0.01) sec = f.secent_line(x1,x2) self.ax.plot(t, sec.eval_np(t)) self.plot_point(x1, sec.eval_np(x1)) self.plot_point(x2,sec.eval_np(x2)) def make_tangent(self,f,x): I =",
"= SubplotZero(self.fig,111) self.fig.add_subplot(self.ax) for direction in [\"xzero\",\"yzero\"]: self.ax.axis[direction].set_axisline_style(\"-|>\") self.ax.axis[direction].set_visible(True) for direction in [\"left\",\"right\",\"bottom\",\"top\"]:",
"direction in [\"left\",\"right\",\"bottom\",\"top\"]: self.ax.axis[direction].set_visible(False) def make_graph(self, f): I = f.behaviour(\"largest interval\") ps =",
"of problems need to be resolved: 1)Can we keep a record of the",
"self.zoom_x(I) self.zoom_y(f.range(I)) def zoom_x(self,I): ps = float(I.args[0]) pe = float(I.args[1]) self.ax.set_xlim(ps,pe) def zoom_y(self,I):",
"= float(I.args[0]) pe = float(I.args[1]) t = np.arange(ps, pe, 0.01) sec = f.secent_line(x1,x2)",
"self.fig = plt.figure(1) self.ax = SubplotZero(self.fig,111) self.fig.add_subplot(self.ax) for direction in [\"xzero\",\"yzero\"]: self.ax.axis[direction].set_axisline_style(\"-|>\") self.ax.axis[direction].set_visible(True)",
"ps = float(I.args[0]) pe = float(I.args[1]) t = np.arange(ps, pe, 0.01) self.ax.plot(t, f.eval_np(t))",
"np.arange(ps, pe, 0.01) tan = f.tangent_line(x) self.ax.plot(t, tan.eval_np(t)) self.plot_point(x, tan.eval_np(x)) def plot_point(self, x,",
"the graphs graphed? this can be done by just keeping the numpy arrays",
"-1, 1 ...etc) ''' class graph(): def __init__(self): self.fig = plt.figure(1) self.ax =",
"= f.secent_line(x1,x2) self.ax.plot(t, sec.eval_np(t)) self.plot_point(x1, sec.eval_np(x1)) self.plot_point(x2,sec.eval_np(x2)) def make_tangent(self,f,x): I = f.behaviour(\"largest interval\")",
"keep a record of the graphs graphed? this can be done by just",
"= float(I.args[1]) self.ax.set_xlim(ps,pe) def zoom_y(self,I): ps = float(I.args[0]) pe = float(I.args[1]) self.ax.set_ylim(ps,pe) def",
"l,r = min(l,float(I.args[0])), max(r,float(I.args[1])) else: l,r = float(Interval.args[0]), float(Interval.args[1]) self.Interval = sp.Interval(l,r) t",
"be able to deal with poles of functions ( for example 1/x at",
"to deal with poles of functions ( for example 1/x at x =",
"ps = float(I.args[0]) pe = float(I.args[1]) self.ax.set_xlim(ps,pe) def zoom_y(self,I): ps = float(I.args[0]) pe",
"I = f.behaviour(\"largest interval\") l,r = float(I.args[0]), float(I.args[1]) for f in functions: I",
"= f.tangent_line(x) self.ax.plot(t, tan.eval_np(t)) self.plot_point(x, tan.eval_np(x)) def plot_point(self, x, y): self.ax.plot(np.array([x]), np.array([y]), 'ro')",
"self.plot_point(x2,sec.eval_np(x2)) def make_tangent(self,f,x): I = f.behaviour(\"largest interval\") ps = float(I.args[0]) pe = float(I.args[1])",
"f = functions[0] I = f.behaviour(\"largest interval\") l,r = float(I.args[0]), float(I.args[1]) for f",
"functions ( for example 1/x at x = 0, 1/(x^2-1) at x =",
"direction in [\"xzero\",\"yzero\"]: self.ax.axis[direction].set_axisline_style(\"-|>\") self.ax.axis[direction].set_visible(True) for direction in [\"left\",\"right\",\"bottom\",\"top\"]: self.ax.axis[direction].set_visible(False) def make_graph(self, f):",
"= np.arange(l,r,.01) for f in functions: self.ax.plot(t,f.eval_np(t)) def make_secent(self,f,x1,x2): I = f.behaviour(\"largest interval\")",
"pe, 0.01) sec = f.secent_line(x1,x2) self.ax.plot(t, sec.eval_np(t)) self.plot_point(x1, sec.eval_np(x1)) self.plot_point(x2,sec.eval_np(x2)) def make_tangent(self,f,x): I",
"for example 1/x at x = 0, 1/(x^2-1) at x = -1, 1",
"float(I.args[1]) t = np.arange(ps, pe, 0.01) tan = f.tangent_line(x) self.ax.plot(t, tan.eval_np(t)) self.plot_point(x, tan.eval_np(x))",
"float(I.args[1]) t = np.arange(ps, pe, 0.01) sec = f.secent_line(x1,x2) self.ax.plot(t, sec.eval_np(t)) self.plot_point(x1, sec.eval_np(x1))",
"need to be able to deal with poles of functions ( for example",
"keeping the numpy arrays ? 2)we need to be able to deal with",
"as plt from mpl_toolkits.axes_grid.axislines import SubplotZero import numpy as np import cyllene.f_functionclass as",
"np.arange(ps, pe, 0.01) sec = f.secent_line(x1,x2) self.ax.plot(t, sec.eval_np(t)) self.plot_point(x1, sec.eval_np(x1)) self.plot_point(x2,sec.eval_np(x2)) def make_tangent(self,f,x):",
"f.eval_np(t)) def make_graphs(self, *functions,Interval=None): if(Interval == None): f = functions[0] I = f.behaviour(\"largest",
"pe = float(I.args[1]) self.ax.set_xlim(ps,pe) def zoom_y(self,I): ps = float(I.args[0]) pe = float(I.args[1]) self.ax.set_ylim(ps,pe)",
"t = np.arange(ps, pe, 0.01) sec = f.secent_line(x1,x2) self.ax.plot(t, sec.eval_np(t)) self.plot_point(x1, sec.eval_np(x1)) self.plot_point(x2,sec.eval_np(x2))",
"pe = float(I.args[1]) t = np.arange(ps, pe, 0.01) tan = f.tangent_line(x) self.ax.plot(t, tan.eval_np(t))",
"sympy as sp ''' A lot of problems need to be resolved: 1)Can",
"f, I): self.zoom_x(I) self.zoom_y(f.range(I)) def zoom_x(self,I): ps = float(I.args[0]) pe = float(I.args[1]) self.ax.set_xlim(ps,pe)",
"interval\") ps = float(I.args[0]) pe = float(I.args[1]) t = np.arange(ps, pe, 0.01) sec",
"f.behaviour(\"largest interval\") l,r = float(I.args[0]), float(I.args[1]) for f in functions: I = f.behaviour(\"largest",
"interval\") l,r = float(I.args[0]), float(I.args[1]) for f in functions: I = f.behaviour(\"largest interval\")",
"resolved: 1)Can we keep a record of the graphs graphed? this can be",
"I = f.behaviour(\"largest interval\") ps = float(I.args[0]) pe = float(I.args[1]) t = np.arange(ps,",
"= -1, 1 ...etc) ''' class graph(): def __init__(self): self.fig = plt.figure(1) self.ax",
"def plot_point(self, x, y): self.ax.plot(np.array([x]), np.array([y]), 'ro') def zoom_y(self, f, I): self.zoom_x(I) self.zoom_y(f.range(I))",
"matplotlib.pyplot as plt from mpl_toolkits.axes_grid.axislines import SubplotZero import numpy as np import cyllene.f_functionclass",
"f.behaviour(\"largest interval\") l,r = min(l,float(I.args[0])), max(r,float(I.args[1])) else: l,r = float(Interval.args[0]), float(Interval.args[1]) self.Interval =",
"l,r = float(Interval.args[0]), float(Interval.args[1]) self.Interval = sp.Interval(l,r) t = np.arange(l,r,.01) for f in",
"self.ax.plot(t,f.eval_np(t)) def make_secent(self,f,x1,x2): I = f.behaviour(\"largest interval\") ps = float(I.args[0]) pe = float(I.args[1])",
"to be resolved: 1)Can we keep a record of the graphs graphed? this",
"tan.eval_np(x)) def plot_point(self, x, y): self.ax.plot(np.array([x]), np.array([y]), 'ro') def zoom_y(self, f, I): self.zoom_x(I)",
"self.ax.axis[direction].set_visible(True) for direction in [\"left\",\"right\",\"bottom\",\"top\"]: self.ax.axis[direction].set_visible(False) def make_graph(self, f): I = f.behaviour(\"largest interval\")",
"with poles of functions ( for example 1/x at x = 0, 1/(x^2-1)",
"*functions,Interval=None): if(Interval == None): f = functions[0] I = f.behaviour(\"largest interval\") l,r =",
"functions: self.ax.plot(t,f.eval_np(t)) def make_secent(self,f,x1,x2): I = f.behaviour(\"largest interval\") ps = float(I.args[0]) pe =",
"tan = f.tangent_line(x) self.ax.plot(t, tan.eval_np(t)) self.plot_point(x, tan.eval_np(x)) def plot_point(self, x, y): self.ax.plot(np.array([x]), np.array([y]),",
"= float(I.args[1]) t = np.arange(ps, pe, 0.01) tan = f.tangent_line(x) self.ax.plot(t, tan.eval_np(t)) self.plot_point(x,",
"float(I.args[0]) pe = float(I.args[1]) t = np.arange(ps, pe, 0.01) sec = f.secent_line(x1,x2) self.ax.plot(t,",
"of the graphs graphed? this can be done by just keeping the numpy",
"x, y): self.ax.plot(np.array([x]), np.array([y]), 'ro') def zoom_y(self, f, I): self.zoom_x(I) self.zoom_y(f.range(I)) def zoom_x(self,I):",
"self.ax.plot(t, f.eval_np(t)) def make_graphs(self, *functions,Interval=None): if(Interval == None): f = functions[0] I =",
"self.Interval = sp.Interval(l,r) t = np.arange(l,r,.01) for f in functions: self.ax.plot(t,f.eval_np(t)) def make_secent(self,f,x1,x2):",
"0, 1/(x^2-1) at x = -1, 1 ...etc) ''' class graph(): def __init__(self):",
"mpl_toolkits.axes_grid.axislines import SubplotZero import numpy as np import cyllene.f_functionclass as f_funct import sympy",
"tan.eval_np(t)) self.plot_point(x, tan.eval_np(x)) def plot_point(self, x, y): self.ax.plot(np.array([x]), np.array([y]), 'ro') def zoom_y(self, f,",
"def make_tangent(self,f,x): I = f.behaviour(\"largest interval\") ps = float(I.args[0]) pe = float(I.args[1]) t",
"f.behaviour(\"largest interval\") ps = float(I.args[0]) pe = float(I.args[1]) t = np.arange(ps, pe, 0.01)",
"deal with poles of functions ( for example 1/x at x = 0,",
"= float(I.args[1]) t = np.arange(ps, pe, 0.01) self.ax.plot(t, f.eval_np(t)) def make_graphs(self, *functions,Interval=None): if(Interval",
"we keep a record of the graphs graphed? this can be done by",
"= min(l,float(I.args[0])), max(r,float(I.args[1])) else: l,r = float(Interval.args[0]), float(Interval.args[1]) self.Interval = sp.Interval(l,r) t =",
"f in functions: self.ax.plot(t,f.eval_np(t)) def make_secent(self,f,x1,x2): I = f.behaviour(\"largest interval\") ps = float(I.args[0])",
"def make_secent(self,f,x1,x2): I = f.behaviour(\"largest interval\") ps = float(I.args[0]) pe = float(I.args[1]) t",
"...etc) ''' class graph(): def __init__(self): self.fig = plt.figure(1) self.ax = SubplotZero(self.fig,111) self.fig.add_subplot(self.ax)",
"self.zoom_y(f.range(I)) def zoom_x(self,I): ps = float(I.args[0]) pe = float(I.args[1]) self.ax.set_xlim(ps,pe) def zoom_y(self,I): ps",
"zoom_x(self,I): ps = float(I.args[0]) pe = float(I.args[1]) self.ax.set_xlim(ps,pe) def zoom_y(self,I): ps = float(I.args[0])",
"f in functions: I = f.behaviour(\"largest interval\") l,r = min(l,float(I.args[0])), max(r,float(I.args[1])) else: l,r",
"float(I.args[0]), float(I.args[1]) for f in functions: I = f.behaviour(\"largest interval\") l,r = min(l,float(I.args[0])),",
"I = f.behaviour(\"largest interval\") l,r = min(l,float(I.args[0])), max(r,float(I.args[1])) else: l,r = float(Interval.args[0]), float(Interval.args[1])",
"in functions: self.ax.plot(t,f.eval_np(t)) def make_secent(self,f,x1,x2): I = f.behaviour(\"largest interval\") ps = float(I.args[0]) pe",
"graphs graphed? this can be done by just keeping the numpy arrays ?",
"t = np.arange(l,r,.01) for f in functions: self.ax.plot(t,f.eval_np(t)) def make_secent(self,f,x1,x2): I = f.behaviour(\"largest",
"for f in functions: self.ax.plot(t,f.eval_np(t)) def make_secent(self,f,x1,x2): I = f.behaviour(\"largest interval\") ps =",
"the numpy arrays ? 2)we need to be able to deal with poles",
"import SubplotZero import numpy as np import cyllene.f_functionclass as f_funct import sympy as",
"= float(I.args[0]), float(I.args[1]) for f in functions: I = f.behaviour(\"largest interval\") l,r =",
"min(l,float(I.args[0])), max(r,float(I.args[1])) else: l,r = float(Interval.args[0]), float(Interval.args[1]) self.Interval = sp.Interval(l,r) t = np.arange(l,r,.01)",
"A lot of problems need to be resolved: 1)Can we keep a record",
"cyllene.f_functionclass as f_funct import sympy as sp ''' A lot of problems need",
"plot_point(self, x, y): self.ax.plot(np.array([x]), np.array([y]), 'ro') def zoom_y(self, f, I): self.zoom_x(I) self.zoom_y(f.range(I)) def",
"= float(I.args[0]) pe = float(I.args[1]) t = np.arange(ps, pe, 0.01) tan = f.tangent_line(x)",
"functions: I = f.behaviour(\"largest interval\") l,r = min(l,float(I.args[0])), max(r,float(I.args[1])) else: l,r = float(Interval.args[0]),",
"? 2)we need to be able to deal with poles of functions (",
"ps = float(I.args[0]) pe = float(I.args[1]) t = np.arange(ps, pe, 0.01) sec =",
"as f_funct import sympy as sp ''' A lot of problems need to",
"= np.arange(ps, pe, 0.01) tan = f.tangent_line(x) self.ax.plot(t, tan.eval_np(t)) self.plot_point(x, tan.eval_np(x)) def plot_point(self,",
"x = 0, 1/(x^2-1) at x = -1, 1 ...etc) ''' class graph():",
"f.tangent_line(x) self.ax.plot(t, tan.eval_np(t)) self.plot_point(x, tan.eval_np(x)) def plot_point(self, x, y): self.ax.plot(np.array([x]), np.array([y]), 'ro') def",
"SubplotZero import numpy as np import cyllene.f_functionclass as f_funct import sympy as sp",
"np import cyllene.f_functionclass as f_funct import sympy as sp ''' A lot of",
"( for example 1/x at x = 0, 1/(x^2-1) at x = -1,",
"max(r,float(I.args[1])) else: l,r = float(Interval.args[0]), float(Interval.args[1]) self.Interval = sp.Interval(l,r) t = np.arange(l,r,.01) for",
"functions[0] I = f.behaviour(\"largest interval\") l,r = float(I.args[0]), float(I.args[1]) for f in functions:",
"= np.arange(ps, pe, 0.01) sec = f.secent_line(x1,x2) self.ax.plot(t, sec.eval_np(t)) self.plot_point(x1, sec.eval_np(x1)) self.plot_point(x2,sec.eval_np(x2)) def",
"self.fig.add_subplot(self.ax) for direction in [\"xzero\",\"yzero\"]: self.ax.axis[direction].set_axisline_style(\"-|>\") self.ax.axis[direction].set_visible(True) for direction in [\"left\",\"right\",\"bottom\",\"top\"]: self.ax.axis[direction].set_visible(False) def",
"as sp ''' A lot of problems need to be resolved: 1)Can we",
"''' A lot of problems need to be resolved: 1)Can we keep a",
"for f in functions: I = f.behaviour(\"largest interval\") l,r = min(l,float(I.args[0])), max(r,float(I.args[1])) else:",
"interval\") l,r = min(l,float(I.args[0])), max(r,float(I.args[1])) else: l,r = float(Interval.args[0]), float(Interval.args[1]) self.Interval = sp.Interval(l,r)",
"sec.eval_np(x1)) self.plot_point(x2,sec.eval_np(x2)) def make_tangent(self,f,x): I = f.behaviour(\"largest interval\") ps = float(I.args[0]) pe =",
"def zoom_y(self,I): ps = float(I.args[0]) pe = float(I.args[1]) self.ax.set_ylim(ps,pe) def show(self): return self.fig",
"0.01) tan = f.tangent_line(x) self.ax.plot(t, tan.eval_np(t)) self.plot_point(x, tan.eval_np(x)) def plot_point(self, x, y): self.ax.plot(np.array([x]),",
"can be done by just keeping the numpy arrays ? 2)we need to",
"float(I.args[1]) self.ax.set_xlim(ps,pe) def zoom_y(self,I): ps = float(I.args[0]) pe = float(I.args[1]) self.ax.set_ylim(ps,pe) def show(self):",
"''' class graph(): def __init__(self): self.fig = plt.figure(1) self.ax = SubplotZero(self.fig,111) self.fig.add_subplot(self.ax) for",
"problems need to be resolved: 1)Can we keep a record of the graphs",
"= np.arange(ps, pe, 0.01) self.ax.plot(t, f.eval_np(t)) def make_graphs(self, *functions,Interval=None): if(Interval == None): f",
"np.array([y]), 'ro') def zoom_y(self, f, I): self.zoom_x(I) self.zoom_y(f.range(I)) def zoom_x(self,I): ps = float(I.args[0])",
"class graph(): def __init__(self): self.fig = plt.figure(1) self.ax = SubplotZero(self.fig,111) self.fig.add_subplot(self.ax) for direction",
"pe, 0.01) self.ax.plot(t, f.eval_np(t)) def make_graphs(self, *functions,Interval=None): if(Interval == None): f = functions[0]",
"float(I.args[0]) pe = float(I.args[1]) t = np.arange(ps, pe, 0.01) self.ax.plot(t, f.eval_np(t)) def make_graphs(self,",
"I): self.zoom_x(I) self.zoom_y(f.range(I)) def zoom_x(self,I): ps = float(I.args[0]) pe = float(I.args[1]) self.ax.set_xlim(ps,pe) def",
"None): f = functions[0] I = f.behaviour(\"largest interval\") l,r = float(I.args[0]), float(I.args[1]) for",
"plt from mpl_toolkits.axes_grid.axislines import SubplotZero import numpy as np import cyllene.f_functionclass as f_funct",
"def zoom_y(self, f, I): self.zoom_x(I) self.zoom_y(f.range(I)) def zoom_x(self,I): ps = float(I.args[0]) pe =",
"interval\") ps = float(I.args[0]) pe = float(I.args[1]) t = np.arange(ps, pe, 0.01) tan",
"else: l,r = float(Interval.args[0]), float(Interval.args[1]) self.Interval = sp.Interval(l,r) t = np.arange(l,r,.01) for f",
"= f.behaviour(\"largest interval\") ps = float(I.args[0]) pe = float(I.args[1]) t = np.arange(ps, pe,",
"= f.behaviour(\"largest interval\") l,r = min(l,float(I.args[0])), max(r,float(I.args[1])) else: l,r = float(Interval.args[0]), float(Interval.args[1]) self.Interval",
"self.ax = SubplotZero(self.fig,111) self.fig.add_subplot(self.ax) for direction in [\"xzero\",\"yzero\"]: self.ax.axis[direction].set_axisline_style(\"-|>\") self.ax.axis[direction].set_visible(True) for direction in",
"done by just keeping the numpy arrays ? 2)we need to be able",
"plt.figure(1) self.ax = SubplotZero(self.fig,111) self.fig.add_subplot(self.ax) for direction in [\"xzero\",\"yzero\"]: self.ax.axis[direction].set_axisline_style(\"-|>\") self.ax.axis[direction].set_visible(True) for direction",
"a record of the graphs graphed? this can be done by just keeping",
"be resolved: 1)Can we keep a record of the graphs graphed? this can",
"import sympy as sp ''' A lot of problems need to be resolved:",
"make_tangent(self,f,x): I = f.behaviour(\"largest interval\") ps = float(I.args[0]) pe = float(I.args[1]) t =",
"y): self.ax.plot(np.array([x]), np.array([y]), 'ro') def zoom_y(self, f, I): self.zoom_x(I) self.zoom_y(f.range(I)) def zoom_x(self,I): ps",
"= float(Interval.args[0]), float(Interval.args[1]) self.Interval = sp.Interval(l,r) t = np.arange(l,r,.01) for f in functions:",
"= plt.figure(1) self.ax = SubplotZero(self.fig,111) self.fig.add_subplot(self.ax) for direction in [\"xzero\",\"yzero\"]: self.ax.axis[direction].set_axisline_style(\"-|>\") self.ax.axis[direction].set_visible(True) for",
"pe = float(I.args[1]) t = np.arange(ps, pe, 0.01) self.ax.plot(t, f.eval_np(t)) def make_graphs(self, *functions,Interval=None):",
"graph(): def __init__(self): self.fig = plt.figure(1) self.ax = SubplotZero(self.fig,111) self.fig.add_subplot(self.ax) for direction in",
"if(Interval == None): f = functions[0] I = f.behaviour(\"largest interval\") l,r = float(I.args[0]),",
"def __init__(self): self.fig = plt.figure(1) self.ax = SubplotZero(self.fig,111) self.fig.add_subplot(self.ax) for direction in [\"xzero\",\"yzero\"]:",
"sec = f.secent_line(x1,x2) self.ax.plot(t, sec.eval_np(t)) self.plot_point(x1, sec.eval_np(x1)) self.plot_point(x2,sec.eval_np(x2)) def make_tangent(self,f,x): I = f.behaviour(\"largest",
"example 1/x at x = 0, 1/(x^2-1) at x = -1, 1 ...etc)",
"pe = float(I.args[1]) t = np.arange(ps, pe, 0.01) sec = f.secent_line(x1,x2) self.ax.plot(t, sec.eval_np(t))",
"numpy arrays ? 2)we need to be able to deal with poles of",
"import matplotlib.pyplot as plt from mpl_toolkits.axes_grid.axislines import SubplotZero import numpy as np import",
"as np import cyllene.f_functionclass as f_funct import sympy as sp ''' A lot",
"import numpy as np import cyllene.f_functionclass as f_funct import sympy as sp '''",
"1/(x^2-1) at x = -1, 1 ...etc) ''' class graph(): def __init__(self): self.fig",
"1)Can we keep a record of the graphs graphed? this can be done",
"self.plot_point(x1, sec.eval_np(x1)) self.plot_point(x2,sec.eval_np(x2)) def make_tangent(self,f,x): I = f.behaviour(\"largest interval\") ps = float(I.args[0]) pe",
"for direction in [\"xzero\",\"yzero\"]: self.ax.axis[direction].set_axisline_style(\"-|>\") self.ax.axis[direction].set_visible(True) for direction in [\"left\",\"right\",\"bottom\",\"top\"]: self.ax.axis[direction].set_visible(False) def make_graph(self,",
"for direction in [\"left\",\"right\",\"bottom\",\"top\"]: self.ax.axis[direction].set_visible(False) def make_graph(self, f): I = f.behaviour(\"largest interval\") ps",
"self.ax.set_xlim(ps,pe) def zoom_y(self,I): ps = float(I.args[0]) pe = float(I.args[1]) self.ax.set_ylim(ps,pe) def show(self): return",
"need to be resolved: 1)Can we keep a record of the graphs graphed?",
"graphed? this can be done by just keeping the numpy arrays ? 2)we",
"[\"xzero\",\"yzero\"]: self.ax.axis[direction].set_axisline_style(\"-|>\") self.ax.axis[direction].set_visible(True) for direction in [\"left\",\"right\",\"bottom\",\"top\"]: self.ax.axis[direction].set_visible(False) def make_graph(self, f): I =",
"just keeping the numpy arrays ? 2)we need to be able to deal",
"in [\"left\",\"right\",\"bottom\",\"top\"]: self.ax.axis[direction].set_visible(False) def make_graph(self, f): I = f.behaviour(\"largest interval\") ps = float(I.args[0])",
"1 ...etc) ''' class graph(): def __init__(self): self.fig = plt.figure(1) self.ax = SubplotZero(self.fig,111)",
"interval\") ps = float(I.args[0]) pe = float(I.args[1]) t = np.arange(ps, pe, 0.01) self.ax.plot(t,",
"t = np.arange(ps, pe, 0.01) self.ax.plot(t, f.eval_np(t)) def make_graphs(self, *functions,Interval=None): if(Interval == None):",
"def zoom_x(self,I): ps = float(I.args[0]) pe = float(I.args[1]) self.ax.set_xlim(ps,pe) def zoom_y(self,I): ps =",
"= 0, 1/(x^2-1) at x = -1, 1 ...etc) ''' class graph(): def",
"to be able to deal with poles of functions ( for example 1/x",
"f): I = f.behaviour(\"largest interval\") ps = float(I.args[0]) pe = float(I.args[1]) t =",
"float(Interval.args[1]) self.Interval = sp.Interval(l,r) t = np.arange(l,r,.01) for f in functions: self.ax.plot(t,f.eval_np(t)) def",
"def make_graphs(self, *functions,Interval=None): if(Interval == None): f = functions[0] I = f.behaviour(\"largest interval\")",
"float(Interval.args[0]), float(Interval.args[1]) self.Interval = sp.Interval(l,r) t = np.arange(l,r,.01) for f in functions: self.ax.plot(t,f.eval_np(t))",
"1/x at x = 0, 1/(x^2-1) at x = -1, 1 ...etc) '''",
"be done by just keeping the numpy arrays ? 2)we need to be",
"l,r = float(I.args[0]), float(I.args[1]) for f in functions: I = f.behaviour(\"largest interval\") l,r",
"f.secent_line(x1,x2) self.ax.plot(t, sec.eval_np(t)) self.plot_point(x1, sec.eval_np(x1)) self.plot_point(x2,sec.eval_np(x2)) def make_tangent(self,f,x): I = f.behaviour(\"largest interval\") ps",
"float(I.args[0]) pe = float(I.args[1]) t = np.arange(ps, pe, 0.01) tan = f.tangent_line(x) self.ax.plot(t,",
"this can be done by just keeping the numpy arrays ? 2)we need",
"in functions: I = f.behaviour(\"largest interval\") l,r = min(l,float(I.args[0])), max(r,float(I.args[1])) else: l,r =",
"float(I.args[0]) pe = float(I.args[1]) self.ax.set_xlim(ps,pe) def zoom_y(self,I): ps = float(I.args[0]) pe = float(I.args[1])",
"def make_graph(self, f): I = f.behaviour(\"largest interval\") ps = float(I.args[0]) pe = float(I.args[1])",
"self.ax.axis[direction].set_axisline_style(\"-|>\") self.ax.axis[direction].set_visible(True) for direction in [\"left\",\"right\",\"bottom\",\"top\"]: self.ax.axis[direction].set_visible(False) def make_graph(self, f): I = f.behaviour(\"largest",
"f_funct import sympy as sp ''' A lot of problems need to be",
"at x = -1, 1 ...etc) ''' class graph(): def __init__(self): self.fig =",
"x = -1, 1 ...etc) ''' class graph(): def __init__(self): self.fig = plt.figure(1)",
"at x = 0, 1/(x^2-1) at x = -1, 1 ...etc) ''' class",
"numpy as np import cyllene.f_functionclass as f_funct import sympy as sp ''' A",
"t = np.arange(ps, pe, 0.01) tan = f.tangent_line(x) self.ax.plot(t, tan.eval_np(t)) self.plot_point(x, tan.eval_np(x)) def",
"make_secent(self,f,x1,x2): I = f.behaviour(\"largest interval\") ps = float(I.args[0]) pe = float(I.args[1]) t =",
"self.ax.plot(t, tan.eval_np(t)) self.plot_point(x, tan.eval_np(x)) def plot_point(self, x, y): self.ax.plot(np.array([x]), np.array([y]), 'ro') def zoom_y(self,",
"pe, 0.01) tan = f.tangent_line(x) self.ax.plot(t, tan.eval_np(t)) self.plot_point(x, tan.eval_np(x)) def plot_point(self, x, y):",
"'ro') def zoom_y(self, f, I): self.zoom_x(I) self.zoom_y(f.range(I)) def zoom_x(self,I): ps = float(I.args[0]) pe",
"import cyllene.f_functionclass as f_funct import sympy as sp ''' A lot of problems",
"__init__(self): self.fig = plt.figure(1) self.ax = SubplotZero(self.fig,111) self.fig.add_subplot(self.ax) for direction in [\"xzero\",\"yzero\"]: self.ax.axis[direction].set_axisline_style(\"-|>\")",
"self.ax.axis[direction].set_visible(False) def make_graph(self, f): I = f.behaviour(\"largest interval\") ps = float(I.args[0]) pe =",
"make_graphs(self, *functions,Interval=None): if(Interval == None): f = functions[0] I = f.behaviour(\"largest interval\") l,r",
"float(I.args[1]) t = np.arange(ps, pe, 0.01) self.ax.plot(t, f.eval_np(t)) def make_graphs(self, *functions,Interval=None): if(Interval ==",
"0.01) self.ax.plot(t, f.eval_np(t)) def make_graphs(self, *functions,Interval=None): if(Interval == None): f = functions[0] I",
"float(I.args[1]) for f in functions: I = f.behaviour(\"largest interval\") l,r = min(l,float(I.args[0])), max(r,float(I.args[1]))",
"== None): f = functions[0] I = f.behaviour(\"largest interval\") l,r = float(I.args[0]), float(I.args[1])",
"lot of problems need to be resolved: 1)Can we keep a record of",
"sec.eval_np(t)) self.plot_point(x1, sec.eval_np(x1)) self.plot_point(x2,sec.eval_np(x2)) def make_tangent(self,f,x): I = f.behaviour(\"largest interval\") ps = float(I.args[0])",
"of functions ( for example 1/x at x = 0, 1/(x^2-1) at x",
"[\"left\",\"right\",\"bottom\",\"top\"]: self.ax.axis[direction].set_visible(False) def make_graph(self, f): I = f.behaviour(\"largest interval\") ps = float(I.args[0]) pe",
"np.arange(ps, pe, 0.01) self.ax.plot(t, f.eval_np(t)) def make_graphs(self, *functions,Interval=None): if(Interval == None): f =",
"ps = float(I.args[0]) pe = float(I.args[1]) t = np.arange(ps, pe, 0.01) tan =",
"2)we need to be able to deal with poles of functions ( for",
"self.plot_point(x, tan.eval_np(x)) def plot_point(self, x, y): self.ax.plot(np.array([x]), np.array([y]), 'ro') def zoom_y(self, f, I):",
"poles of functions ( for example 1/x at x = 0, 1/(x^2-1) at",
"= sp.Interval(l,r) t = np.arange(l,r,.01) for f in functions: self.ax.plot(t,f.eval_np(t)) def make_secent(self,f,x1,x2): I",
"SubplotZero(self.fig,111) self.fig.add_subplot(self.ax) for direction in [\"xzero\",\"yzero\"]: self.ax.axis[direction].set_axisline_style(\"-|>\") self.ax.axis[direction].set_visible(True) for direction in [\"left\",\"right\",\"bottom\",\"top\"]: self.ax.axis[direction].set_visible(False)",
"by just keeping the numpy arrays ? 2)we need to be able to",
"able to deal with poles of functions ( for example 1/x at x"
] |
[
"peso if peso < menor: menor = peso #saida print(f'O maior peso lido",
"float(input(f'Peso da 1ª pessoa: ')) if i == 0: maior = menor =",
"pessoa: ')) if i == 0: maior = menor = peso else: if",
"if i == 0: maior = menor = peso else: if peso >",
"print(f'O maior peso lido foi de {maior:.2f}Kg') print(f'O menor peso lido foi de",
"peso > maior: maior = peso if peso < menor: menor = peso",
"& processamento for i in range(0, 5): peso = float(input(f'Peso da 1ª pessoa:",
"peso = float(input(f'Peso da 1ª pessoa: ')) if i == 0: maior =",
"> maior: maior = peso if peso < menor: menor = peso #saida",
"range(0, 5): peso = float(input(f'Peso da 1ª pessoa: ')) if i == 0:",
"if peso > maior: maior = peso if peso < menor: menor =",
"menor = peso else: if peso > maior: maior = peso if peso",
"<reponame>PedroHPAlmeida/exercicios-Python-CEV #entrada & processamento for i in range(0, 5): peso = float(input(f'Peso da",
"0: maior = menor = peso else: if peso > maior: maior =",
"= peso if peso < menor: menor = peso #saida print(f'O maior peso",
"in range(0, 5): peso = float(input(f'Peso da 1ª pessoa: ')) if i ==",
"menor: menor = peso #saida print(f'O maior peso lido foi de {maior:.2f}Kg') print(f'O",
"maior peso lido foi de {maior:.2f}Kg') print(f'O menor peso lido foi de {menor:.2f}Kg')",
"maior = peso if peso < menor: menor = peso #saida print(f'O maior",
"= menor = peso else: if peso > maior: maior = peso if",
"= float(input(f'Peso da 1ª pessoa: ')) if i == 0: maior = menor",
"1ª pessoa: ')) if i == 0: maior = menor = peso else:",
"= peso else: if peso > maior: maior = peso if peso <",
"if peso < menor: menor = peso #saida print(f'O maior peso lido foi",
"else: if peso > maior: maior = peso if peso < menor: menor",
"')) if i == 0: maior = menor = peso else: if peso",
"#entrada & processamento for i in range(0, 5): peso = float(input(f'Peso da 1ª",
"= peso #saida print(f'O maior peso lido foi de {maior:.2f}Kg') print(f'O menor peso",
"#saida print(f'O maior peso lido foi de {maior:.2f}Kg') print(f'O menor peso lido foi",
"5): peso = float(input(f'Peso da 1ª pessoa: ')) if i == 0: maior",
"i == 0: maior = menor = peso else: if peso > maior:",
"for i in range(0, 5): peso = float(input(f'Peso da 1ª pessoa: ')) if",
"da 1ª pessoa: ')) if i == 0: maior = menor = peso",
"peso else: if peso > maior: maior = peso if peso < menor:",
"menor = peso #saida print(f'O maior peso lido foi de {maior:.2f}Kg') print(f'O menor",
"== 0: maior = menor = peso else: if peso > maior: maior",
"peso < menor: menor = peso #saida print(f'O maior peso lido foi de",
"< menor: menor = peso #saida print(f'O maior peso lido foi de {maior:.2f}Kg')",
"processamento for i in range(0, 5): peso = float(input(f'Peso da 1ª pessoa: '))",
"peso #saida print(f'O maior peso lido foi de {maior:.2f}Kg') print(f'O menor peso lido",
"i in range(0, 5): peso = float(input(f'Peso da 1ª pessoa: ')) if i",
"maior = menor = peso else: if peso > maior: maior = peso",
"maior: maior = peso if peso < menor: menor = peso #saida print(f'O"
] |
[
"supplied') return json_data # -------- Handled by denzel container -------- def load_model(): \"\"\"",
"to API-caller :rtype: dict \"\"\" # return a dictionary that will be parsed",
"validity of an API request content :param json_data: Parsed JSON accepted from API",
"accepted from API call :type json_data: dict :return: Data for the the process",
"return the loaded model object def process(model, json_data): \"\"\" Process the json_data passed",
"verify_input to model ready data :param model: Loaded object from load_model function :param",
"to model ready data :param model: Loaded object from load_model function :param json_data:",
"\"\"\" Predicts and prepares the answer for the API-caller :param model: Loaded object",
"def process(model, json_data): \"\"\" Process the json_data passed from verify_input to model ready",
"dict \"\"\" # return a dictionary that will be parsed to JSON and",
"the responses to if 'callback_uri' not in json_data: raise ValueError('callback_uri not supplied') return",
"\"\"\" Process the json_data passed from verify_input to model ready data :param model:",
"-------- def load_model(): \"\"\" Load model and its assets to memory :return: Model,",
"be used by the predict and process functions \"\"\" return # return the",
"a dictionary that will be parsed to JSON and sent back to API-caller",
"answer for the API-caller :param model: Loaded object from load_model function :param data:",
"and its assets to memory :return: Model, will be used by the predict",
"API request content :param json_data: Parsed JSON accepted from API call :type json_data:",
"of an API request content :param json_data: Parsed JSON accepted from API call",
"Load model and its assets to memory :return: Model, will be used by",
"# callback_uri is needed to sent the responses to if 'callback_uri' not in",
"\"\"\" return # return the loaded model object def process(model, json_data): \"\"\" Process",
"for the API-caller :param model: Loaded object from load_model function :param data: Data",
"and prepares the answer for the API-caller :param model: Loaded object from load_model",
":param data: Data from process function :return: Response to API-caller :rtype: dict \"\"\"",
"not in json_data: raise ValueError('callback_uri not supplied') return json_data # -------- Handled by",
"will be used by the predict and process functions \"\"\" return # return",
"json_data passed from verify_input to model ready data :param model: Loaded object from",
":param json_data: Data from the verify_input function :return: Model ready data \"\"\" #",
"to memory :return: Model, will be used by the predict and process functions",
"the validity of an API request content :param json_data: Parsed JSON accepted from",
"API-caller :rtype: dict \"\"\" # return a dictionary that will be parsed to",
"used by the predict and process functions \"\"\" return # return the loaded",
"return def predict(model, data): \"\"\" Predicts and prepares the answer for the API-caller",
"Parsed JSON accepted from API call :type json_data: dict :return: Data for the",
"model and its assets to memory :return: Model, will be used by the",
"function :return: Response to API-caller :rtype: dict \"\"\" # return a dictionary that",
"json_data: dict :return: Data for the the process function \"\"\" # callback_uri is",
":return: Model, will be used by the predict and process functions \"\"\" return",
"the json_data passed from verify_input to model ready data :param model: Loaded object",
"model: Loaded object from load_model function :param data: Data from process function :return:",
"\"\"\" # return model ready data return def predict(model, data): \"\"\" Predicts and",
"process function \"\"\" # callback_uri is needed to sent the responses to if",
":return: Model ready data \"\"\" # return model ready data return def predict(model,",
"def predict(model, data): \"\"\" Predicts and prepares the answer for the API-caller :param",
"Handled by denzel container -------- def load_model(): \"\"\" Load model and its assets",
"needed to sent the responses to if 'callback_uri' not in json_data: raise ValueError('callback_uri",
"object def process(model, json_data): \"\"\" Process the json_data passed from verify_input to model",
"by denzel container -------- def load_model(): \"\"\" Load model and its assets to",
"object from load_model function :param data: Data from process function :return: Response to",
"loaded model object def process(model, json_data): \"\"\" Process the json_data passed from verify_input",
"dict :return: Data for the the process function \"\"\" # callback_uri is needed",
"its assets to memory :return: Model, will be used by the predict and",
"the API-caller :param model: Loaded object from load_model function :param data: Data from",
"is needed to sent the responses to if 'callback_uri' not in json_data: raise",
":return: Data for the the process function \"\"\" # callback_uri is needed to",
"data return def predict(model, data): \"\"\" Predicts and prepares the answer for the",
"raise ValueError('callback_uri not supplied') return json_data # -------- Handled by denzel container --------",
"# -------- Handled by denzel container -------- def load_model(): \"\"\" Load model and",
"Data from process function :return: Response to API-caller :rtype: dict \"\"\" # return",
"functions \"\"\" return # return the loaded model object def process(model, json_data): \"\"\"",
"by api container -------- def verify_input(json_data): \"\"\" Verifies the validity of an API",
"ready data :param model: Loaded object from load_model function :param json_data: Data from",
"function \"\"\" # callback_uri is needed to sent the responses to if 'callback_uri'",
"def verify_input(json_data): \"\"\" Verifies the validity of an API request content :param json_data:",
"predict(model, data): \"\"\" Predicts and prepares the answer for the API-caller :param model:",
":param model: Loaded object from load_model function :param data: Data from process function",
"the process function \"\"\" # callback_uri is needed to sent the responses to",
"model: Loaded object from load_model function :param json_data: Data from the verify_input function",
"the the process function \"\"\" # callback_uri is needed to sent the responses",
"json_data): \"\"\" Process the json_data passed from verify_input to model ready data :param",
"return json_data # -------- Handled by denzel container -------- def load_model(): \"\"\" Load",
"container -------- def load_model(): \"\"\" Load model and its assets to memory :return:",
"an API request content :param json_data: Parsed JSON accepted from API call :type",
":rtype: dict \"\"\" # return a dictionary that will be parsed to JSON",
"load_model(): \"\"\" Load model and its assets to memory :return: Model, will be",
"data \"\"\" # return model ready data return def predict(model, data): \"\"\" Predicts",
"container -------- def verify_input(json_data): \"\"\" Verifies the validity of an API request content",
"memory :return: Model, will be used by the predict and process functions \"\"\"",
"from load_model function :param data: Data from process function :return: Response to API-caller",
"\"\"\" Load model and its assets to memory :return: Model, will be used",
"# return model ready data return def predict(model, data): \"\"\" Predicts and prepares",
"Response to API-caller :rtype: dict \"\"\" # return a dictionary that will be",
":param json_data: Parsed JSON accepted from API call :type json_data: dict :return: Data",
"json_data: raise ValueError('callback_uri not supplied') return json_data # -------- Handled by denzel container",
"Handled by api container -------- def verify_input(json_data): \"\"\" Verifies the validity of an",
"responses to if 'callback_uri' not in json_data: raise ValueError('callback_uri not supplied') return json_data",
"and process functions \"\"\" return # return the loaded model object def process(model,",
"for the the process function \"\"\" # callback_uri is needed to sent the",
"load_model function :param json_data: Data from the verify_input function :return: Model ready data",
"json_data: Data from the verify_input function :return: Model ready data \"\"\" # return",
"verify_input(json_data): \"\"\" Verifies the validity of an API request content :param json_data: Parsed",
"data): \"\"\" Predicts and prepares the answer for the API-caller :param model: Loaded",
"the answer for the API-caller :param model: Loaded object from load_model function :param",
"ready data return def predict(model, data): \"\"\" Predicts and prepares the answer for",
"from API call :type json_data: dict :return: Data for the the process function",
"ready data \"\"\" # return model ready data return def predict(model, data): \"\"\"",
"to sent the responses to if 'callback_uri' not in json_data: raise ValueError('callback_uri not",
"Model, will be used by the predict and process functions \"\"\" return #",
"json_data: Parsed JSON accepted from API call :type json_data: dict :return: Data for",
"function :param data: Data from process function :return: Response to API-caller :rtype: dict",
"API call :type json_data: dict :return: Data for the the process function \"\"\"",
"call :type json_data: dict :return: Data for the the process function \"\"\" #",
"'callback_uri' not in json_data: raise ValueError('callback_uri not supplied') return json_data # -------- Handled",
"-------- def verify_input(json_data): \"\"\" Verifies the validity of an API request content :param",
"from verify_input to model ready data :param model: Loaded object from load_model function",
"process functions \"\"\" return # return the loaded model object def process(model, json_data):",
"from the verify_input function :return: Model ready data \"\"\" # return model ready",
"the loaded model object def process(model, json_data): \"\"\" Process the json_data passed from",
"object from load_model function :param json_data: Data from the verify_input function :return: Model",
"data: Data from process function :return: Response to API-caller :rtype: dict \"\"\" #",
"# -------- Handled by api container -------- def verify_input(json_data): \"\"\" Verifies the validity",
"JSON accepted from API call :type json_data: dict :return: Data for the the",
"return model ready data return def predict(model, data): \"\"\" Predicts and prepares the",
"in json_data: raise ValueError('callback_uri not supplied') return json_data # -------- Handled by denzel",
"Data from the verify_input function :return: Model ready data \"\"\" # return model",
"model object def process(model, json_data): \"\"\" Process the json_data passed from verify_input to",
"prepares the answer for the API-caller :param model: Loaded object from load_model function",
"request content :param json_data: Parsed JSON accepted from API call :type json_data: dict",
"process(model, json_data): \"\"\" Process the json_data passed from verify_input to model ready data",
"data :param model: Loaded object from load_model function :param json_data: Data from the",
"function :return: Model ready data \"\"\" # return model ready data return def",
"from load_model function :param json_data: Data from the verify_input function :return: Model ready",
"<filename>src/denzel/app/logic/pipeline.py # -------- Handled by api container -------- def verify_input(json_data): \"\"\" Verifies the",
"denzel container -------- def load_model(): \"\"\" Load model and its assets to memory",
"content :param json_data: Parsed JSON accepted from API call :type json_data: dict :return:",
"\"\"\" # callback_uri is needed to sent the responses to if 'callback_uri' not",
"# return a dictionary that will be parsed to JSON and sent back",
"-------- Handled by denzel container -------- def load_model(): \"\"\" Load model and its",
"passed from verify_input to model ready data :param model: Loaded object from load_model",
"Model ready data \"\"\" # return model ready data return def predict(model, data):",
"sent the responses to if 'callback_uri' not in json_data: raise ValueError('callback_uri not supplied')",
":return: Response to API-caller :rtype: dict \"\"\" # return a dictionary that will",
"json_data # -------- Handled by denzel container -------- def load_model(): \"\"\" Load model",
"predict and process functions \"\"\" return # return the loaded model object def",
"return a dictionary that will be parsed to JSON and sent back to",
"load_model function :param data: Data from process function :return: Response to API-caller :rtype:",
"api container -------- def verify_input(json_data): \"\"\" Verifies the validity of an API request",
"not supplied') return json_data # -------- Handled by denzel container -------- def load_model():",
"by the predict and process functions \"\"\" return # return the loaded model",
"-------- Handled by api container -------- def verify_input(json_data): \"\"\" Verifies the validity of",
"to if 'callback_uri' not in json_data: raise ValueError('callback_uri not supplied') return json_data #",
"the predict and process functions \"\"\" return # return the loaded model object",
"\"\"\" Verifies the validity of an API request content :param json_data: Parsed JSON",
"Data for the the process function \"\"\" # callback_uri is needed to sent",
"dictionary that will be parsed to JSON and sent back to API-caller return",
":type json_data: dict :return: Data for the the process function \"\"\" # callback_uri",
"function :param json_data: Data from the verify_input function :return: Model ready data \"\"\"",
"ValueError('callback_uri not supplied') return json_data # -------- Handled by denzel container -------- def",
":param model: Loaded object from load_model function :param json_data: Data from the verify_input",
"assets to memory :return: Model, will be used by the predict and process",
"Predicts and prepares the answer for the API-caller :param model: Loaded object from",
"if 'callback_uri' not in json_data: raise ValueError('callback_uri not supplied') return json_data # --------",
"the verify_input function :return: Model ready data \"\"\" # return model ready data",
"API-caller :param model: Loaded object from load_model function :param data: Data from process",
"Loaded object from load_model function :param json_data: Data from the verify_input function :return:",
"model ready data :param model: Loaded object from load_model function :param json_data: Data",
"return # return the loaded model object def process(model, json_data): \"\"\" Process the",
"\"\"\" # return a dictionary that will be parsed to JSON and sent",
"model ready data return def predict(model, data): \"\"\" Predicts and prepares the answer",
"that will be parsed to JSON and sent back to API-caller return {}",
"from process function :return: Response to API-caller :rtype: dict \"\"\" # return a",
"# return the loaded model object def process(model, json_data): \"\"\" Process the json_data",
"verify_input function :return: Model ready data \"\"\" # return model ready data return",
"Verifies the validity of an API request content :param json_data: Parsed JSON accepted",
"Loaded object from load_model function :param data: Data from process function :return: Response",
"process function :return: Response to API-caller :rtype: dict \"\"\" # return a dictionary",
"callback_uri is needed to sent the responses to if 'callback_uri' not in json_data:",
"Process the json_data passed from verify_input to model ready data :param model: Loaded",
"def load_model(): \"\"\" Load model and its assets to memory :return: Model, will"
] |
[
"Y_train, X_test, Y_test = sc_utils.load_data() X_train, Y_train, X_val, Y_val, X_test, Y_test, tokenizer =",
"str(test_accuracy * 100) + \"%\") # Test model on my own texts reviews",
"\"This movie is bad. I don't like it it all. It's terrible.\", \"I",
"#model = model_factory.create_train_emb_rnn_model(embedding_matrix, INPUT_LENGTH) model.summary() # Train model model.fit(X_train, Y_train, batch_size=200, epochs=30) #",
"seen it many times and it's still awesome.\", \"I don't think this movie",
"\"Negative\" if pred[2][0] < 0.5 else \"Positive\" print(sentiment_str + \" on the third",
"= 100 # Prepare data X_train, Y_train, X_test, Y_test = sc_utils.load_data() X_train, Y_train,",
"the second text\") sentiment_str = \"Negative\" if pred[2][0] < 0.5 else \"Positive\" print(sentiment_str",
"sc_utils.create_embedding_matrix(tokenizer) print(\"X_train.shape: \" + str(X_train.shape)) print(\"Y_train.shape: \" + str(Y_train.shape)) print(\"X_val.shape: \" + str(X_val.shape))",
"= \"Negative\" if pred[2][0] < 0.5 else \"Positive\" print(sentiment_str + \" on the",
"str(X_train.shape)) print(\"Y_train.shape: \" + str(Y_train.shape)) print(\"X_val.shape: \" + str(X_val.shape)) print(\"Y_val.shape: \" + str(Y_val.shape))",
"\"%\") # Evaluate model on test set test_loss, test_accuracy = model.evaluate(X_test, Y_test, verbose=0)",
"print(sentiment_str + \" on the second text\") sentiment_str = \"Negative\" if pred[2][0] <",
"is bad. I don't like it it all. It's terrible.\", \"I love this",
"Y_test, tokenizer = sc_utils.preprocess_data(X_train, Y_train, X_test, Y_test, INPUT_LENGTH) embedding_matrix = sc_utils.create_embedding_matrix(tokenizer) print(\"X_train.shape: \"",
"str(val_accuracy * 100) + \"%\") # Evaluate model on test set test_loss, test_accuracy",
"\" on the first text\") sentiment_str = \"Negative\" if pred[1][0] < 0.5 else",
"+ \"%\") # Evaluate model on test set test_loss, test_accuracy = model.evaluate(X_test, Y_test,",
"own texts reviews = [ \"This movie is bad. I don't like it",
"INPUT_LENGTH) #model = model_factory.create_train_emb_rnn_model(embedding_matrix, INPUT_LENGTH) model.summary() # Train model model.fit(X_train, Y_train, batch_size=200, epochs=30)",
"epochs=30) # Evaluate model on validation set val_loss, val_accuracy = model.evaluate(X_val, Y_val, verbose=0)",
"pred = model.predict(reviews) print(pred) print(\"The model predicts:\") sentiment_str = \"Negative\" if pred[0][0] <",
"0.5 else \"Positive\" print(sentiment_str + \" on the first text\") sentiment_str = \"Negative\"",
"my own texts:\") print(reviews) reviews = tokenizer.texts_to_sequences(reviews) reviews = pad_sequences(reviews, maxlen=INPUT_LENGTH, padding=\"post\") reviews",
"from keras.preprocessing.sequence import pad_sequences INPUT_LENGTH = 100 # Prepare data X_train, Y_train, X_test,",
"+ str(test_accuracy * 100) + \"%\") # Test model on my own texts",
"like it it all. It's terrible.\", \"I love this movie. I've seen it",
"all. It's terrible.\", \"I love this movie. I've seen it many times and",
"model on my own texts:\") print(reviews) reviews = tokenizer.texts_to_sequences(reviews) reviews = pad_sequences(reviews, maxlen=INPUT_LENGTH,",
"+ \" on the first text\") sentiment_str = \"Negative\" if pred[1][0] < 0.5",
"predicts:\") sentiment_str = \"Negative\" if pred[0][0] < 0.5 else \"Positive\" print(sentiment_str + \"",
"print(sentiment_str + \" on the first text\") sentiment_str = \"Negative\" if pred[1][0] <",
"Y_train, X_test, Y_test, INPUT_LENGTH) embedding_matrix = sc_utils.create_embedding_matrix(tokenizer) print(\"X_train.shape: \" + str(X_train.shape)) print(\"Y_train.shape: \"",
"Y_train, X_val, Y_val, X_test, Y_test, tokenizer = sc_utils.preprocess_data(X_train, Y_train, X_test, Y_test, INPUT_LENGTH) embedding_matrix",
"test set: \" + str(test_accuracy * 100) + \"%\") # Test model on",
"sc_utils.load_data() X_train, Y_train, X_val, Y_val, X_test, Y_test, tokenizer = sc_utils.preprocess_data(X_train, Y_train, X_test, Y_test,",
"validation set: \" + str(val_accuracy * 100) + \"%\") # Evaluate model on",
"\" + str(Y_train.shape)) print(\"X_val.shape: \" + str(X_val.shape)) print(\"Y_val.shape: \" + str(Y_val.shape)) print(\"X_test.shape: \"",
"test_loss, test_accuracy = model.evaluate(X_test, Y_test, verbose=0) print(\"Accuracy on test set: \" + str(test_accuracy",
"model.evaluate(X_test, Y_test, verbose=0) print(\"Accuracy on test set: \" + str(test_accuracy * 100) +",
"verbose=0) print(\"Accuracy on test set: \" + str(test_accuracy * 100) + \"%\") #",
"it it all. It's terrible.\", \"I love this movie. I've seen it many",
"= \"Negative\" if pred[0][0] < 0.5 else \"Positive\" print(sentiment_str + \" on the",
"bad as most people say. It's actually pretty good.\" ] print(\"Testing model on",
"first text\") sentiment_str = \"Negative\" if pred[1][0] < 0.5 else \"Positive\" print(sentiment_str +",
"awesome.\", \"I don't think this movie is as bad as most people say.",
"model = model_factory.create_rnn_model(embedding_matrix, INPUT_LENGTH) #model = model_factory.create_bidir_rnn_model(embedding_matrix, INPUT_LENGTH) #model = model_factory.create_train_emb_rnn_model(embedding_matrix, INPUT_LENGTH) model.summary()",
"if pred[1][0] < 0.5 else \"Positive\" print(sentiment_str + \" on the second text\")",
"reviews = np.array(reviews) pred = model.predict(reviews) print(pred) print(\"The model predicts:\") sentiment_str = \"Negative\"",
"str(Y_test.shape)) print(\"embedding_matrix.shape: \" + str(embedding_matrix.shape)) # Create model #model = model_factory.create_baseline_model(embedding_matrix, INPUT_LENGTH) model",
"embedding_matrix = sc_utils.create_embedding_matrix(tokenizer) print(\"X_train.shape: \" + str(X_train.shape)) print(\"Y_train.shape: \" + str(Y_train.shape)) print(\"X_val.shape: \"",
"else \"Positive\" print(sentiment_str + \" on the second text\") sentiment_str = \"Negative\" if",
"on my own texts reviews = [ \"This movie is bad. I don't",
"print(reviews) reviews = tokenizer.texts_to_sequences(reviews) reviews = pad_sequences(reviews, maxlen=INPUT_LENGTH, padding=\"post\") reviews = np.array(reviews) pred",
"set val_loss, val_accuracy = model.evaluate(X_val, Y_val, verbose=0) print(\"Accuracy on validation set: \" +",
"print(\"Testing model on my own texts:\") print(reviews) reviews = tokenizer.texts_to_sequences(reviews) reviews = pad_sequences(reviews,",
"Y_test = sc_utils.load_data() X_train, Y_train, X_val, Y_val, X_test, Y_test, tokenizer = sc_utils.preprocess_data(X_train, Y_train,",
"print(\"X_test.shape: \" + str(X_test.shape)) print(\"Y_test.shape: \" + str(Y_test.shape)) print(\"embedding_matrix.shape: \" + str(embedding_matrix.shape)) #",
"= model_factory.create_train_emb_rnn_model(embedding_matrix, INPUT_LENGTH) model.summary() # Train model model.fit(X_train, Y_train, batch_size=200, epochs=30) # Evaluate",
"import numpy as np from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences INPUT_LENGTH",
"INPUT_LENGTH) model = model_factory.create_rnn_model(embedding_matrix, INPUT_LENGTH) #model = model_factory.create_bidir_rnn_model(embedding_matrix, INPUT_LENGTH) #model = model_factory.create_train_emb_rnn_model(embedding_matrix, INPUT_LENGTH)",
"+ str(X_train.shape)) print(\"Y_train.shape: \" + str(Y_train.shape)) print(\"X_val.shape: \" + str(X_val.shape)) print(\"Y_val.shape: \" +",
"# Create model #model = model_factory.create_baseline_model(embedding_matrix, INPUT_LENGTH) model = model_factory.create_rnn_model(embedding_matrix, INPUT_LENGTH) #model =",
"say. It's actually pretty good.\" ] print(\"Testing model on my own texts:\") print(reviews)",
"print(\"The model predicts:\") sentiment_str = \"Negative\" if pred[0][0] < 0.5 else \"Positive\" print(sentiment_str",
"= [ \"This movie is bad. I don't like it it all. It's",
"X_val, Y_val, X_test, Y_test, tokenizer = sc_utils.preprocess_data(X_train, Y_train, X_test, Y_test, INPUT_LENGTH) embedding_matrix =",
"sentiment_str = \"Negative\" if pred[2][0] < 0.5 else \"Positive\" print(sentiment_str + \" on",
"= model_factory.create_rnn_model(embedding_matrix, INPUT_LENGTH) #model = model_factory.create_bidir_rnn_model(embedding_matrix, INPUT_LENGTH) #model = model_factory.create_train_emb_rnn_model(embedding_matrix, INPUT_LENGTH) model.summary() #",
"str(X_val.shape)) print(\"Y_val.shape: \" + str(Y_val.shape)) print(\"X_test.shape: \" + str(X_test.shape)) print(\"Y_test.shape: \" + str(Y_test.shape))",
"+ str(val_accuracy * 100) + \"%\") # Evaluate model on test set test_loss,",
"= tokenizer.texts_to_sequences(reviews) reviews = pad_sequences(reviews, maxlen=INPUT_LENGTH, padding=\"post\") reviews = np.array(reviews) pred = model.predict(reviews)",
"it's still awesome.\", \"I don't think this movie is as bad as most",
"str(Y_val.shape)) print(\"X_test.shape: \" + str(X_test.shape)) print(\"Y_test.shape: \" + str(Y_test.shape)) print(\"embedding_matrix.shape: \" + str(embedding_matrix.shape))",
"sentiment_str = \"Negative\" if pred[0][0] < 0.5 else \"Positive\" print(sentiment_str + \" on",
"Y_train, batch_size=200, epochs=30) # Evaluate model on validation set val_loss, val_accuracy = model.evaluate(X_val,",
"as most people say. It's actually pretty good.\" ] print(\"Testing model on my",
"print(\"Y_val.shape: \" + str(Y_val.shape)) print(\"X_test.shape: \" + str(X_test.shape)) print(\"Y_test.shape: \" + str(Y_test.shape)) print(\"embedding_matrix.shape:",
"+ str(Y_test.shape)) print(\"embedding_matrix.shape: \" + str(embedding_matrix.shape)) # Create model #model = model_factory.create_baseline_model(embedding_matrix, INPUT_LENGTH)",
"np.array(reviews) pred = model.predict(reviews) print(pred) print(\"The model predicts:\") sentiment_str = \"Negative\" if pred[0][0]",
"reviews = [ \"This movie is bad. I don't like it it all.",
"reviews = tokenizer.texts_to_sequences(reviews) reviews = pad_sequences(reviews, maxlen=INPUT_LENGTH, padding=\"post\") reviews = np.array(reviews) pred =",
"terrible.\", \"I love this movie. I've seen it many times and it's still",
"sc_utils import model_factory import numpy as np from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence",
"+ str(X_test.shape)) print(\"Y_test.shape: \" + str(Y_test.shape)) print(\"embedding_matrix.shape: \" + str(embedding_matrix.shape)) # Create model",
"= model.evaluate(X_test, Y_test, verbose=0) print(\"Accuracy on test set: \" + str(test_accuracy * 100)",
"this movie is as bad as most people say. It's actually pretty good.\"",
"model_factory.create_bidir_rnn_model(embedding_matrix, INPUT_LENGTH) #model = model_factory.create_train_emb_rnn_model(embedding_matrix, INPUT_LENGTH) model.summary() # Train model model.fit(X_train, Y_train, batch_size=200,",
"Test model on my own texts reviews = [ \"This movie is bad.",
"model on test set test_loss, test_accuracy = model.evaluate(X_test, Y_test, verbose=0) print(\"Accuracy on test",
"sentiment_str = \"Negative\" if pred[1][0] < 0.5 else \"Positive\" print(sentiment_str + \" on",
"\"Negative\" if pred[0][0] < 0.5 else \"Positive\" print(sentiment_str + \" on the first",
"if pred[0][0] < 0.5 else \"Positive\" print(sentiment_str + \" on the first text\")",
"sc_utils.preprocess_data(X_train, Y_train, X_test, Y_test, INPUT_LENGTH) embedding_matrix = sc_utils.create_embedding_matrix(tokenizer) print(\"X_train.shape: \" + str(X_train.shape)) print(\"Y_train.shape:",
"model_factory.create_train_emb_rnn_model(embedding_matrix, INPUT_LENGTH) model.summary() # Train model model.fit(X_train, Y_train, batch_size=200, epochs=30) # Evaluate model",
"= model_factory.create_bidir_rnn_model(embedding_matrix, INPUT_LENGTH) #model = model_factory.create_train_emb_rnn_model(embedding_matrix, INPUT_LENGTH) model.summary() # Train model model.fit(X_train, Y_train,",
"import model_factory import numpy as np from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import",
"[ \"This movie is bad. I don't like it it all. It's terrible.\",",
"set test_loss, test_accuracy = model.evaluate(X_test, Y_test, verbose=0) print(\"Accuracy on test set: \" +",
"print(\"Accuracy on test set: \" + str(test_accuracy * 100) + \"%\") # Test",
"on validation set: \" + str(val_accuracy * 100) + \"%\") # Evaluate model",
"verbose=0) print(\"Accuracy on validation set: \" + str(val_accuracy * 100) + \"%\") #",
"set: \" + str(test_accuracy * 100) + \"%\") # Test model on my",
"+ \"%\") # Test model on my own texts reviews = [ \"This",
"# Prepare data X_train, Y_train, X_test, Y_test = sc_utils.load_data() X_train, Y_train, X_val, Y_val,",
"own texts:\") print(reviews) reviews = tokenizer.texts_to_sequences(reviews) reviews = pad_sequences(reviews, maxlen=INPUT_LENGTH, padding=\"post\") reviews =",
"# Test model on my own texts reviews = [ \"This movie is",
"str(X_test.shape)) print(\"Y_test.shape: \" + str(Y_test.shape)) print(\"embedding_matrix.shape: \" + str(embedding_matrix.shape)) # Create model #model",
"X_train, Y_train, X_val, Y_val, X_test, Y_test, tokenizer = sc_utils.preprocess_data(X_train, Y_train, X_test, Y_test, INPUT_LENGTH)",
"validation set val_loss, val_accuracy = model.evaluate(X_val, Y_val, verbose=0) print(\"Accuracy on validation set: \"",
"numpy as np from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences INPUT_LENGTH =",
"INPUT_LENGTH) model.summary() # Train model model.fit(X_train, Y_train, batch_size=200, epochs=30) # Evaluate model on",
"Y_val, verbose=0) print(\"Accuracy on validation set: \" + str(val_accuracy * 100) + \"%\")",
"Evaluate model on test set test_loss, test_accuracy = model.evaluate(X_test, Y_test, verbose=0) print(\"Accuracy on",
"on test set test_loss, test_accuracy = model.evaluate(X_test, Y_test, verbose=0) print(\"Accuracy on test set:",
"test_accuracy = model.evaluate(X_test, Y_test, verbose=0) print(\"Accuracy on test set: \" + str(test_accuracy *",
"] print(\"Testing model on my own texts:\") print(reviews) reviews = tokenizer.texts_to_sequences(reviews) reviews =",
"X_test, Y_test, tokenizer = sc_utils.preprocess_data(X_train, Y_train, X_test, Y_test, INPUT_LENGTH) embedding_matrix = sc_utils.create_embedding_matrix(tokenizer) print(\"X_train.shape:",
"the first text\") sentiment_str = \"Negative\" if pred[1][0] < 0.5 else \"Positive\" print(sentiment_str",
"= sc_utils.preprocess_data(X_train, Y_train, X_test, Y_test, INPUT_LENGTH) embedding_matrix = sc_utils.create_embedding_matrix(tokenizer) print(\"X_train.shape: \" + str(X_train.shape))",
"INPUT_LENGTH) #model = model_factory.create_bidir_rnn_model(embedding_matrix, INPUT_LENGTH) #model = model_factory.create_train_emb_rnn_model(embedding_matrix, INPUT_LENGTH) model.summary() # Train model",
"bad. I don't like it it all. It's terrible.\", \"I love this movie.",
"pred[1][0] < 0.5 else \"Positive\" print(sentiment_str + \" on the second text\") sentiment_str",
"= pad_sequences(reviews, maxlen=INPUT_LENGTH, padding=\"post\") reviews = np.array(reviews) pred = model.predict(reviews) print(pred) print(\"The model",
"= model.predict(reviews) print(pred) print(\"The model predicts:\") sentiment_str = \"Negative\" if pred[0][0] < 0.5",
"pretty good.\" ] print(\"Testing model on my own texts:\") print(reviews) reviews = tokenizer.texts_to_sequences(reviews)",
"I don't like it it all. It's terrible.\", \"I love this movie. I've",
"tokenizer.texts_to_sequences(reviews) reviews = pad_sequences(reviews, maxlen=INPUT_LENGTH, padding=\"post\") reviews = np.array(reviews) pred = model.predict(reviews) print(pred)",
"texts reviews = [ \"This movie is bad. I don't like it it",
"print(\"Accuracy on validation set: \" + str(val_accuracy * 100) + \"%\") # Evaluate",
"# Evaluate model on validation set val_loss, val_accuracy = model.evaluate(X_val, Y_val, verbose=0) print(\"Accuracy",
"\" on the second text\") sentiment_str = \"Negative\" if pred[2][0] < 0.5 else",
"tokenizer = sc_utils.preprocess_data(X_train, Y_train, X_test, Y_test, INPUT_LENGTH) embedding_matrix = sc_utils.create_embedding_matrix(tokenizer) print(\"X_train.shape: \" +",
"movie is as bad as most people say. It's actually pretty good.\" ]",
"keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences INPUT_LENGTH = 100 # Prepare data",
"set: \" + str(val_accuracy * 100) + \"%\") # Evaluate model on test",
"I've seen it many times and it's still awesome.\", \"I don't think this",
"model.fit(X_train, Y_train, batch_size=200, epochs=30) # Evaluate model on validation set val_loss, val_accuracy =",
"X_test, Y_test, INPUT_LENGTH) embedding_matrix = sc_utils.create_embedding_matrix(tokenizer) print(\"X_train.shape: \" + str(X_train.shape)) print(\"Y_train.shape: \" +",
"pad_sequences INPUT_LENGTH = 100 # Prepare data X_train, Y_train, X_test, Y_test = sc_utils.load_data()",
"many times and it's still awesome.\", \"I don't think this movie is as",
"str(Y_train.shape)) print(\"X_val.shape: \" + str(X_val.shape)) print(\"Y_val.shape: \" + str(Y_val.shape)) print(\"X_test.shape: \" + str(X_test.shape))",
"on the first text\") sentiment_str = \"Negative\" if pred[1][0] < 0.5 else \"Positive\"",
"good.\" ] print(\"Testing model on my own texts:\") print(reviews) reviews = tokenizer.texts_to_sequences(reviews) reviews",
"print(\"Y_train.shape: \" + str(Y_train.shape)) print(\"X_val.shape: \" + str(X_val.shape)) print(\"Y_val.shape: \" + str(Y_val.shape)) print(\"X_test.shape:",
"model on my own texts reviews = [ \"This movie is bad. I",
"+ str(embedding_matrix.shape)) # Create model #model = model_factory.create_baseline_model(embedding_matrix, INPUT_LENGTH) model = model_factory.create_rnn_model(embedding_matrix, INPUT_LENGTH)",
"= sc_utils.create_embedding_matrix(tokenizer) print(\"X_train.shape: \" + str(X_train.shape)) print(\"Y_train.shape: \" + str(Y_train.shape)) print(\"X_val.shape: \" +",
"love this movie. I've seen it many times and it's still awesome.\", \"I",
"times and it's still awesome.\", \"I don't think this movie is as bad",
"+ str(Y_train.shape)) print(\"X_val.shape: \" + str(X_val.shape)) print(\"Y_val.shape: \" + str(Y_val.shape)) print(\"X_test.shape: \" +",
"\" + str(Y_test.shape)) print(\"embedding_matrix.shape: \" + str(embedding_matrix.shape)) # Create model #model = model_factory.create_baseline_model(embedding_matrix,",
"+ \" on the second text\") sentiment_str = \"Negative\" if pred[2][0] < 0.5",
"pred[0][0] < 0.5 else \"Positive\" print(sentiment_str + \" on the first text\") sentiment_str",
"if pred[2][0] < 0.5 else \"Positive\" print(sentiment_str + \" on the third text\")",
"= sc_utils.load_data() X_train, Y_train, X_val, Y_val, X_test, Y_test, tokenizer = sc_utils.preprocess_data(X_train, Y_train, X_test,",
"Y_test, verbose=0) print(\"Accuracy on test set: \" + str(test_accuracy * 100) + \"%\")",
"batch_size=200, epochs=30) # Evaluate model on validation set val_loss, val_accuracy = model.evaluate(X_val, Y_val,",
"don't like it it all. It's terrible.\", \"I love this movie. I've seen",
"print(\"Y_test.shape: \" + str(Y_test.shape)) print(\"embedding_matrix.shape: \" + str(embedding_matrix.shape)) # Create model #model =",
"import sc_utils import model_factory import numpy as np from keras.preprocessing.text import Tokenizer from",
"model_factory.create_rnn_model(embedding_matrix, INPUT_LENGTH) #model = model_factory.create_bidir_rnn_model(embedding_matrix, INPUT_LENGTH) #model = model_factory.create_train_emb_rnn_model(embedding_matrix, INPUT_LENGTH) model.summary() # Train",
"as np from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences INPUT_LENGTH = 100",
"actually pretty good.\" ] print(\"Testing model on my own texts:\") print(reviews) reviews =",
"as bad as most people say. It's actually pretty good.\" ] print(\"Testing model",
"on validation set val_loss, val_accuracy = model.evaluate(X_val, Y_val, verbose=0) print(\"Accuracy on validation set:",
"it all. It's terrible.\", \"I love this movie. I've seen it many times",
"think this movie is as bad as most people say. It's actually pretty",
"100) + \"%\") # Evaluate model on test set test_loss, test_accuracy = model.evaluate(X_test,",
"# Train model model.fit(X_train, Y_train, batch_size=200, epochs=30) # Evaluate model on validation set",
"val_loss, val_accuracy = model.evaluate(X_val, Y_val, verbose=0) print(\"Accuracy on validation set: \" + str(val_accuracy",
"model.summary() # Train model model.fit(X_train, Y_train, batch_size=200, epochs=30) # Evaluate model on validation",
"most people say. It's actually pretty good.\" ] print(\"Testing model on my own",
"this movie. I've seen it many times and it's still awesome.\", \"I don't",
"second text\") sentiment_str = \"Negative\" if pred[2][0] < 0.5 else \"Positive\" print(sentiment_str +",
"#model = model_factory.create_bidir_rnn_model(embedding_matrix, INPUT_LENGTH) #model = model_factory.create_train_emb_rnn_model(embedding_matrix, INPUT_LENGTH) model.summary() # Train model model.fit(X_train,",
"\"%\") # Test model on my own texts reviews = [ \"This movie",
"still awesome.\", \"I don't think this movie is as bad as most people",
"on test set: \" + str(test_accuracy * 100) + \"%\") # Test model",
"\" + str(X_val.shape)) print(\"Y_val.shape: \" + str(Y_val.shape)) print(\"X_test.shape: \" + str(X_test.shape)) print(\"Y_test.shape: \"",
"movie is bad. I don't like it it all. It's terrible.\", \"I love",
"is as bad as most people say. It's actually pretty good.\" ] print(\"Testing",
"texts:\") print(reviews) reviews = tokenizer.texts_to_sequences(reviews) reviews = pad_sequences(reviews, maxlen=INPUT_LENGTH, padding=\"post\") reviews = np.array(reviews)",
"model.predict(reviews) print(pred) print(\"The model predicts:\") sentiment_str = \"Negative\" if pred[0][0] < 0.5 else",
"\"Negative\" if pred[1][0] < 0.5 else \"Positive\" print(sentiment_str + \" on the second",
"Y_test, INPUT_LENGTH) embedding_matrix = sc_utils.create_embedding_matrix(tokenizer) print(\"X_train.shape: \" + str(X_train.shape)) print(\"Y_train.shape: \" + str(Y_train.shape))",
"test set test_loss, test_accuracy = model.evaluate(X_test, Y_test, verbose=0) print(\"Accuracy on test set: \"",
"#model = model_factory.create_baseline_model(embedding_matrix, INPUT_LENGTH) model = model_factory.create_rnn_model(embedding_matrix, INPUT_LENGTH) #model = model_factory.create_bidir_rnn_model(embedding_matrix, INPUT_LENGTH) #model",
"model predicts:\") sentiment_str = \"Negative\" if pred[0][0] < 0.5 else \"Positive\" print(sentiment_str +",
"INPUT_LENGTH) embedding_matrix = sc_utils.create_embedding_matrix(tokenizer) print(\"X_train.shape: \" + str(X_train.shape)) print(\"Y_train.shape: \" + str(Y_train.shape)) print(\"X_val.shape:",
"my own texts reviews = [ \"This movie is bad. I don't like",
"It's terrible.\", \"I love this movie. I've seen it many times and it's",
"< 0.5 else \"Positive\" print(sentiment_str + \" on the second text\") sentiment_str =",
"\" + str(X_test.shape)) print(\"Y_test.shape: \" + str(Y_test.shape)) print(\"embedding_matrix.shape: \" + str(embedding_matrix.shape)) # Create",
"= \"Negative\" if pred[1][0] < 0.5 else \"Positive\" print(sentiment_str + \" on the",
"INPUT_LENGTH = 100 # Prepare data X_train, Y_train, X_test, Y_test = sc_utils.load_data() X_train,",
"Evaluate model on validation set val_loss, val_accuracy = model.evaluate(X_val, Y_val, verbose=0) print(\"Accuracy on",
"100) + \"%\") # Test model on my own texts reviews = [",
"X_train, Y_train, X_test, Y_test = sc_utils.load_data() X_train, Y_train, X_val, Y_val, X_test, Y_test, tokenizer",
"model.evaluate(X_val, Y_val, verbose=0) print(\"Accuracy on validation set: \" + str(val_accuracy * 100) +",
"on my own texts:\") print(reviews) reviews = tokenizer.texts_to_sequences(reviews) reviews = pad_sequences(reviews, maxlen=INPUT_LENGTH, padding=\"post\")",
"on the second text\") sentiment_str = \"Negative\" if pred[2][0] < 0.5 else \"Positive\"",
"= model_factory.create_baseline_model(embedding_matrix, INPUT_LENGTH) model = model_factory.create_rnn_model(embedding_matrix, INPUT_LENGTH) #model = model_factory.create_bidir_rnn_model(embedding_matrix, INPUT_LENGTH) #model =",
"* 100) + \"%\") # Evaluate model on test set test_loss, test_accuracy =",
"model_factory.create_baseline_model(embedding_matrix, INPUT_LENGTH) model = model_factory.create_rnn_model(embedding_matrix, INPUT_LENGTH) #model = model_factory.create_bidir_rnn_model(embedding_matrix, INPUT_LENGTH) #model = model_factory.create_train_emb_rnn_model(embedding_matrix,",
"str(embedding_matrix.shape)) # Create model #model = model_factory.create_baseline_model(embedding_matrix, INPUT_LENGTH) model = model_factory.create_rnn_model(embedding_matrix, INPUT_LENGTH) #model",
"It's actually pretty good.\" ] print(\"Testing model on my own texts:\") print(reviews) reviews",
"maxlen=INPUT_LENGTH, padding=\"post\") reviews = np.array(reviews) pred = model.predict(reviews) print(pred) print(\"The model predicts:\") sentiment_str",
"keras.preprocessing.sequence import pad_sequences INPUT_LENGTH = 100 # Prepare data X_train, Y_train, X_test, Y_test",
"padding=\"post\") reviews = np.array(reviews) pred = model.predict(reviews) print(pred) print(\"The model predicts:\") sentiment_str =",
"print(pred) print(\"The model predicts:\") sentiment_str = \"Negative\" if pred[0][0] < 0.5 else \"Positive\"",
"val_accuracy = model.evaluate(X_val, Y_val, verbose=0) print(\"Accuracy on validation set: \" + str(val_accuracy *",
"model model.fit(X_train, Y_train, batch_size=200, epochs=30) # Evaluate model on validation set val_loss, val_accuracy",
"don't think this movie is as bad as most people say. It's actually",
"print(\"X_train.shape: \" + str(X_train.shape)) print(\"Y_train.shape: \" + str(Y_train.shape)) print(\"X_val.shape: \" + str(X_val.shape)) print(\"Y_val.shape:",
"\" + str(test_accuracy * 100) + \"%\") # Test model on my own",
"\"Positive\" print(sentiment_str + \" on the first text\") sentiment_str = \"Negative\" if pred[1][0]",
"Tokenizer from keras.preprocessing.sequence import pad_sequences INPUT_LENGTH = 100 # Prepare data X_train, Y_train,",
"X_test, Y_test = sc_utils.load_data() X_train, Y_train, X_val, Y_val, X_test, Y_test, tokenizer = sc_utils.preprocess_data(X_train,",
"Create model #model = model_factory.create_baseline_model(embedding_matrix, INPUT_LENGTH) model = model_factory.create_rnn_model(embedding_matrix, INPUT_LENGTH) #model = model_factory.create_bidir_rnn_model(embedding_matrix,",
"\"Positive\" print(sentiment_str + \" on the second text\") sentiment_str = \"Negative\" if pred[2][0]",
"Train model model.fit(X_train, Y_train, batch_size=200, epochs=30) # Evaluate model on validation set val_loss,",
"Y_val, X_test, Y_test, tokenizer = sc_utils.preprocess_data(X_train, Y_train, X_test, Y_test, INPUT_LENGTH) embedding_matrix = sc_utils.create_embedding_matrix(tokenizer)",
"= np.array(reviews) pred = model.predict(reviews) print(pred) print(\"The model predicts:\") sentiment_str = \"Negative\" if",
"100 # Prepare data X_train, Y_train, X_test, Y_test = sc_utils.load_data() X_train, Y_train, X_val,",
"< 0.5 else \"Positive\" print(sentiment_str + \" on the first text\") sentiment_str =",
"text\") sentiment_str = \"Negative\" if pred[2][0] < 0.5 else \"Positive\" print(sentiment_str + \"",
"text\") sentiment_str = \"Negative\" if pred[1][0] < 0.5 else \"Positive\" print(sentiment_str + \"",
"print(\"X_val.shape: \" + str(X_val.shape)) print(\"Y_val.shape: \" + str(Y_val.shape)) print(\"X_test.shape: \" + str(X_test.shape)) print(\"Y_test.shape:",
"model on validation set val_loss, val_accuracy = model.evaluate(X_val, Y_val, verbose=0) print(\"Accuracy on validation",
"movie. I've seen it many times and it's still awesome.\", \"I don't think",
"print(\"embedding_matrix.shape: \" + str(embedding_matrix.shape)) # Create model #model = model_factory.create_baseline_model(embedding_matrix, INPUT_LENGTH) model =",
"\" + str(val_accuracy * 100) + \"%\") # Evaluate model on test set",
"\"I don't think this movie is as bad as most people say. It's",
"reviews = pad_sequences(reviews, maxlen=INPUT_LENGTH, padding=\"post\") reviews = np.array(reviews) pred = model.predict(reviews) print(pred) print(\"The",
"= model.evaluate(X_val, Y_val, verbose=0) print(\"Accuracy on validation set: \" + str(val_accuracy * 100)",
"\" + str(Y_val.shape)) print(\"X_test.shape: \" + str(X_test.shape)) print(\"Y_test.shape: \" + str(Y_test.shape)) print(\"embedding_matrix.shape: \"",
"np from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences INPUT_LENGTH = 100 #",
"it many times and it's still awesome.\", \"I don't think this movie is",
"data X_train, Y_train, X_test, Y_test = sc_utils.load_data() X_train, Y_train, X_val, Y_val, X_test, Y_test,",
"import pad_sequences INPUT_LENGTH = 100 # Prepare data X_train, Y_train, X_test, Y_test =",
"\" + str(X_train.shape)) print(\"Y_train.shape: \" + str(Y_train.shape)) print(\"X_val.shape: \" + str(X_val.shape)) print(\"Y_val.shape: \"",
"\"I love this movie. I've seen it many times and it's still awesome.\",",
"pad_sequences(reviews, maxlen=INPUT_LENGTH, padding=\"post\") reviews = np.array(reviews) pred = model.predict(reviews) print(pred) print(\"The model predicts:\")",
"people say. It's actually pretty good.\" ] print(\"Testing model on my own texts:\")",
"0.5 else \"Positive\" print(sentiment_str + \" on the second text\") sentiment_str = \"Negative\"",
"# Evaluate model on test set test_loss, test_accuracy = model.evaluate(X_test, Y_test, verbose=0) print(\"Accuracy",
"* 100) + \"%\") # Test model on my own texts reviews =",
"model_factory import numpy as np from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences",
"+ str(Y_val.shape)) print(\"X_test.shape: \" + str(X_test.shape)) print(\"Y_test.shape: \" + str(Y_test.shape)) print(\"embedding_matrix.shape: \" +",
"from keras.preprocessing.text import Tokenizer from keras.preprocessing.sequence import pad_sequences INPUT_LENGTH = 100 # Prepare",
"Prepare data X_train, Y_train, X_test, Y_test = sc_utils.load_data() X_train, Y_train, X_val, Y_val, X_test,",
"model #model = model_factory.create_baseline_model(embedding_matrix, INPUT_LENGTH) model = model_factory.create_rnn_model(embedding_matrix, INPUT_LENGTH) #model = model_factory.create_bidir_rnn_model(embedding_matrix, INPUT_LENGTH)",
"import Tokenizer from keras.preprocessing.sequence import pad_sequences INPUT_LENGTH = 100 # Prepare data X_train,",
"+ str(X_val.shape)) print(\"Y_val.shape: \" + str(Y_val.shape)) print(\"X_test.shape: \" + str(X_test.shape)) print(\"Y_test.shape: \" +",
"else \"Positive\" print(sentiment_str + \" on the first text\") sentiment_str = \"Negative\" if",
"\" + str(embedding_matrix.shape)) # Create model #model = model_factory.create_baseline_model(embedding_matrix, INPUT_LENGTH) model = model_factory.create_rnn_model(embedding_matrix,",
"and it's still awesome.\", \"I don't think this movie is as bad as"
] |
[] |
[
"#in #that #way: ') print('Submodule is created.') utils.channels_stuff.set_new_channel(channel_name, subreddit=subreddit_name, tags=tags.lower()) print(channel_name.lower()) print('Run the",
"= input('Channel name: ') tags = input('#Tags #in #that #way: ') print('Submodule is",
"subreddit=subreddit_name, tags=tags.lower()) print(channel_name.lower()) print('Run the bot for the first time.') run_script(channel_name) print('Done.') if",
"subreddit_name = input('Subreddit name: ') channel_name = input('Channel name: ') tags = input('#Tags",
"utils.channels_stuff def run_script(channel): os.system('python supplier.py --sub ' + channel.lower()) def med_fashioned_way(): subreddit_name =",
"import os import utils.channels_stuff def run_script(channel): os.system('python supplier.py --sub ' + channel.lower()) def",
"input('#Tags #in #that #way: ') print('Submodule is created.') utils.channels_stuff.set_new_channel(channel_name, subreddit=subreddit_name, tags=tags.lower()) print(channel_name.lower()) print('Run",
"input('Subreddit name: ') channel_name = input('Channel name: ') tags = input('#Tags #in #that",
"') print('Submodule is created.') utils.channels_stuff.set_new_channel(channel_name, subreddit=subreddit_name, tags=tags.lower()) print(channel_name.lower()) print('Run the bot for the",
"#encoding:utf-8 import os import utils.channels_stuff def run_script(channel): os.system('python supplier.py --sub ' + channel.lower())",
"os.system('python supplier.py --sub ' + channel.lower()) def med_fashioned_way(): subreddit_name = input('Subreddit name: ')",
"') tags = input('#Tags #in #that #way: ') print('Submodule is created.') utils.channels_stuff.set_new_channel(channel_name, subreddit=subreddit_name,",
"') channel_name = input('Channel name: ') tags = input('#Tags #in #that #way: ')",
"import utils.channels_stuff def run_script(channel): os.system('python supplier.py --sub ' + channel.lower()) def med_fashioned_way(): subreddit_name",
"supplier.py --sub ' + channel.lower()) def med_fashioned_way(): subreddit_name = input('Subreddit name: ') channel_name",
"print(channel_name.lower()) print('Run the bot for the first time.') run_script(channel_name) print('Done.') if __name__ ==",
"print('Submodule is created.') utils.channels_stuff.set_new_channel(channel_name, subreddit=subreddit_name, tags=tags.lower()) print(channel_name.lower()) print('Run the bot for the first",
"input('Channel name: ') tags = input('#Tags #in #that #way: ') print('Submodule is created.')",
"= input('#Tags #in #that #way: ') print('Submodule is created.') utils.channels_stuff.set_new_channel(channel_name, subreddit=subreddit_name, tags=tags.lower()) print(channel_name.lower())",
"is created.') utils.channels_stuff.set_new_channel(channel_name, subreddit=subreddit_name, tags=tags.lower()) print(channel_name.lower()) print('Run the bot for the first time.')",
"tags=tags.lower()) print(channel_name.lower()) print('Run the bot for the first time.') run_script(channel_name) print('Done.') if __name__",
"the bot for the first time.') run_script(channel_name) print('Done.') if __name__ == '__main__': med_fashioned_way()",
"#that #way: ') print('Submodule is created.') utils.channels_stuff.set_new_channel(channel_name, subreddit=subreddit_name, tags=tags.lower()) print(channel_name.lower()) print('Run the bot",
"#way: ') print('Submodule is created.') utils.channels_stuff.set_new_channel(channel_name, subreddit=subreddit_name, tags=tags.lower()) print(channel_name.lower()) print('Run the bot for",
"tags = input('#Tags #in #that #way: ') print('Submodule is created.') utils.channels_stuff.set_new_channel(channel_name, subreddit=subreddit_name, tags=tags.lower())",
"created.') utils.channels_stuff.set_new_channel(channel_name, subreddit=subreddit_name, tags=tags.lower()) print(channel_name.lower()) print('Run the bot for the first time.') run_script(channel_name)",
"channel.lower()) def med_fashioned_way(): subreddit_name = input('Subreddit name: ') channel_name = input('Channel name: ')",
"--sub ' + channel.lower()) def med_fashioned_way(): subreddit_name = input('Subreddit name: ') channel_name =",
"os import utils.channels_stuff def run_script(channel): os.system('python supplier.py --sub ' + channel.lower()) def med_fashioned_way():",
"channel_name = input('Channel name: ') tags = input('#Tags #in #that #way: ') print('Submodule",
"name: ') channel_name = input('Channel name: ') tags = input('#Tags #in #that #way:",
"print('Run the bot for the first time.') run_script(channel_name) print('Done.') if __name__ == '__main__':",
"' + channel.lower()) def med_fashioned_way(): subreddit_name = input('Subreddit name: ') channel_name = input('Channel",
"+ channel.lower()) def med_fashioned_way(): subreddit_name = input('Subreddit name: ') channel_name = input('Channel name:",
"def med_fashioned_way(): subreddit_name = input('Subreddit name: ') channel_name = input('Channel name: ') tags",
"= input('Subreddit name: ') channel_name = input('Channel name: ') tags = input('#Tags #in",
"name: ') tags = input('#Tags #in #that #way: ') print('Submodule is created.') utils.channels_stuff.set_new_channel(channel_name,",
"run_script(channel): os.system('python supplier.py --sub ' + channel.lower()) def med_fashioned_way(): subreddit_name = input('Subreddit name:",
"def run_script(channel): os.system('python supplier.py --sub ' + channel.lower()) def med_fashioned_way(): subreddit_name = input('Subreddit",
"utils.channels_stuff.set_new_channel(channel_name, subreddit=subreddit_name, tags=tags.lower()) print(channel_name.lower()) print('Run the bot for the first time.') run_script(channel_name) print('Done.')",
"med_fashioned_way(): subreddit_name = input('Subreddit name: ') channel_name = input('Channel name: ') tags ="
] |
[
"pass def supp_fitness(self): # pylint: disable=no-self-use return 0.0 def set_theta(self, theta): raise NotImplementedError()",
"pylint: disable=no-self-use frame = pickle.dumps((args, kwargs)) return [frame] @classmethod def deserialize(cls, frames): args,",
"License. #You may obtain a copy of the License at the root directory",
"kwargs)) return [frame] @classmethod def deserialize(cls, frames): args, kwargs = pickle.loads(frames[0]) return cls(*args,",
"return 0.0 def set_theta(self, theta): raise NotImplementedError() def _serialize(self, *args, **kwargs): # pylint:",
"project. # #See the License for the specific language governing permissions and #limitations",
"seed(self, seed): pass def act(self, states): raise NotImplementedError() def reset(self): pass def supp_fitness(self):",
"Uber Technologies, Inc. # #Licensed under the Uber Non-Commercial License (the \"License\"); #you",
"= False def seed(self, seed): pass def act(self, states): raise NotImplementedError() def reset(self):",
"Inc. # #Licensed under the Uber Non-Commercial License (the \"License\"); #you may not",
"language governing permissions and #limitations under the License. import pickle class Policy: needs_stats",
"raise NotImplementedError() def reset(self): pass def supp_fitness(self): # pylint: disable=no-self-use return 0.0 def",
"def act(self, states): raise NotImplementedError() def reset(self): pass def supp_fitness(self): # pylint: disable=no-self-use",
"pickle class Policy: needs_stats = False def seed(self, seed): pass def act(self, states):",
"of the License at the root directory of this project. # #See the",
"the root directory of this project. # #See the License for the specific",
"obtain a copy of the License at the root directory of this project.",
"#you may not use this file except in compliance with the License. #You",
"this project. # #See the License for the specific language governing permissions and",
"in compliance with the License. #You may obtain a copy of the License",
"(the \"License\"); #you may not use this file except in compliance with the",
"pass def act(self, states): raise NotImplementedError() def reset(self): pass def supp_fitness(self): # pylint:",
"\"License\"); #you may not use this file except in compliance with the License.",
"= pickle.dumps((args, kwargs)) return [frame] @classmethod def deserialize(cls, frames): args, kwargs = pickle.loads(frames[0])",
"Policy: needs_stats = False def seed(self, seed): pass def act(self, states): raise NotImplementedError()",
"under the Uber Non-Commercial License (the \"License\"); #you may not use this file",
"of this project. # #See the License for the specific language governing permissions",
"supp_fitness(self): # pylint: disable=no-self-use return 0.0 def set_theta(self, theta): raise NotImplementedError() def _serialize(self,",
"import pickle class Policy: needs_stats = False def seed(self, seed): pass def act(self,",
"# pylint: disable=no-self-use return 0.0 def set_theta(self, theta): raise NotImplementedError() def _serialize(self, *args,",
"NotImplementedError() def reset(self): pass def supp_fitness(self): # pylint: disable=no-self-use return 0.0 def set_theta(self,",
"frame = pickle.dumps((args, kwargs)) return [frame] @classmethod def deserialize(cls, frames): args, kwargs =",
"may not use this file except in compliance with the License. #You may",
"License. import pickle class Policy: needs_stats = False def seed(self, seed): pass def",
"License for the specific language governing permissions and #limitations under the License. import",
"the License at the root directory of this project. # #See the License",
"under the License. import pickle class Policy: needs_stats = False def seed(self, seed):",
"def reset(self): pass def supp_fitness(self): # pylint: disable=no-self-use return 0.0 def set_theta(self, theta):",
"a copy of the License at the root directory of this project. #",
"for the specific language governing permissions and #limitations under the License. import pickle",
"except in compliance with the License. #You may obtain a copy of the",
"specific language governing permissions and #limitations under the License. import pickle class Policy:",
"theta): raise NotImplementedError() def _serialize(self, *args, **kwargs): # pylint: disable=no-self-use frame = pickle.dumps((args,",
"with the License. #You may obtain a copy of the License at the",
"this file except in compliance with the License. #You may obtain a copy",
"the License. #You may obtain a copy of the License at the root",
"return [frame] @classmethod def deserialize(cls, frames): args, kwargs = pickle.loads(frames[0]) return cls(*args, **kwargs)",
"at the root directory of this project. # #See the License for the",
"#limitations under the License. import pickle class Policy: needs_stats = False def seed(self,",
"# #See the License for the specific language governing permissions and #limitations under",
"use this file except in compliance with the License. #You may obtain a",
"raise NotImplementedError() def _serialize(self, *args, **kwargs): # pylint: disable=no-self-use frame = pickle.dumps((args, kwargs))",
"#Licensed under the Uber Non-Commercial License (the \"License\"); #you may not use this",
"#See the License for the specific language governing permissions and #limitations under the",
"pylint: disable=no-self-use return 0.0 def set_theta(self, theta): raise NotImplementedError() def _serialize(self, *args, **kwargs):",
"not use this file except in compliance with the License. #You may obtain",
"compliance with the License. #You may obtain a copy of the License at",
"*args, **kwargs): # pylint: disable=no-self-use frame = pickle.dumps((args, kwargs)) return [frame] @classmethod def",
"# #Licensed under the Uber Non-Commercial License (the \"License\"); #you may not use",
"(c) 2019 Uber Technologies, Inc. # #Licensed under the Uber Non-Commercial License (the",
"**kwargs): # pylint: disable=no-self-use frame = pickle.dumps((args, kwargs)) return [frame] @classmethod def deserialize(cls,",
"Non-Commercial License (the \"License\"); #you may not use this file except in compliance",
"set_theta(self, theta): raise NotImplementedError() def _serialize(self, *args, **kwargs): # pylint: disable=no-self-use frame =",
"seed): pass def act(self, states): raise NotImplementedError() def reset(self): pass def supp_fitness(self): #",
"False def seed(self, seed): pass def act(self, states): raise NotImplementedError() def reset(self): pass",
"reset(self): pass def supp_fitness(self): # pylint: disable=no-self-use return 0.0 def set_theta(self, theta): raise",
"pickle.dumps((args, kwargs)) return [frame] @classmethod def deserialize(cls, frames): args, kwargs = pickle.loads(frames[0]) return",
"governing permissions and #limitations under the License. import pickle class Policy: needs_stats =",
"0.0 def set_theta(self, theta): raise NotImplementedError() def _serialize(self, *args, **kwargs): # pylint: disable=no-self-use",
"License at the root directory of this project. # #See the License for",
"def _serialize(self, *args, **kwargs): # pylint: disable=no-self-use frame = pickle.dumps((args, kwargs)) return [frame]",
"the License. import pickle class Policy: needs_stats = False def seed(self, seed): pass",
"Uber Non-Commercial License (the \"License\"); #you may not use this file except in",
"act(self, states): raise NotImplementedError() def reset(self): pass def supp_fitness(self): # pylint: disable=no-self-use return",
"permissions and #limitations under the License. import pickle class Policy: needs_stats = False",
"disable=no-self-use frame = pickle.dumps((args, kwargs)) return [frame] @classmethod def deserialize(cls, frames): args, kwargs",
"disable=no-self-use return 0.0 def set_theta(self, theta): raise NotImplementedError() def _serialize(self, *args, **kwargs): #",
"License (the \"License\"); #you may not use this file except in compliance with",
"def seed(self, seed): pass def act(self, states): raise NotImplementedError() def reset(self): pass def",
"the License for the specific language governing permissions and #limitations under the License.",
"2019 Uber Technologies, Inc. # #Licensed under the Uber Non-Commercial License (the \"License\");",
"# pylint: disable=no-self-use frame = pickle.dumps((args, kwargs)) return [frame] @classmethod def deserialize(cls, frames):",
"and #limitations under the License. import pickle class Policy: needs_stats = False def",
"NotImplementedError() def _serialize(self, *args, **kwargs): # pylint: disable=no-self-use frame = pickle.dumps((args, kwargs)) return",
"may obtain a copy of the License at the root directory of this",
"class Policy: needs_stats = False def seed(self, seed): pass def act(self, states): raise",
"the specific language governing permissions and #limitations under the License. import pickle class",
"file except in compliance with the License. #You may obtain a copy of",
"_serialize(self, *args, **kwargs): # pylint: disable=no-self-use frame = pickle.dumps((args, kwargs)) return [frame] @classmethod",
"copy of the License at the root directory of this project. # #See",
"the Uber Non-Commercial License (the \"License\"); #you may not use this file except",
"def supp_fitness(self): # pylint: disable=no-self-use return 0.0 def set_theta(self, theta): raise NotImplementedError() def",
"#Copyright (c) 2019 Uber Technologies, Inc. # #Licensed under the Uber Non-Commercial License",
"root directory of this project. # #See the License for the specific language",
"#You may obtain a copy of the License at the root directory of",
"states): raise NotImplementedError() def reset(self): pass def supp_fitness(self): # pylint: disable=no-self-use return 0.0",
"directory of this project. # #See the License for the specific language governing",
"def set_theta(self, theta): raise NotImplementedError() def _serialize(self, *args, **kwargs): # pylint: disable=no-self-use frame",
"needs_stats = False def seed(self, seed): pass def act(self, states): raise NotImplementedError() def",
"Technologies, Inc. # #Licensed under the Uber Non-Commercial License (the \"License\"); #you may"
] |
[
"py_client.modules.{module} import endpoints from .common import create_login_model from .mock import mock_post class {classname}(unittest.TestCase):",
"ResponseStatus from ....utils.decoders import build_loader, datetime_decoder __all__ = ['{classname}RequestModel', '{classname}ResponseModel'] class {classname}RequestModel(BaseModel): \\\"\\\"\\\"",
"}}) \"\"\" METHOD = \"\"\" def {name}(self, model: {model}RequestModel, key: str = None)",
"not None if response.stat == ResponseStatus.OK: # check pass else: assert response.emsg is",
"datetime from ....common.enums import ResponseStatus from ....utils.decoders import build_loader, datetime_decoder __all__ = ['{classname}RequestModel',",
"response_json = self._run_request(model, endpoints.{endpoint}, key) # convert the request to response model return",
"class Config: \\\"\\\"\\\"model configuration\\\"\\\"\\\" json_loads = build_loader({{ \\\"request_time\\\": datetime_decoder() }}) \"\"\" METHOD =",
"from unittest.mock import MagicMock from py_client import Client, ResponseStatus from py_client.models import LoginResponseModel",
"os import json import unittest from unittest.mock import MagicMock from py_client import Client,",
"not None assert response.stat is not None if response.stat == ResponseStatus.OK: # check",
"should be parsed properly'): assert response is not None assert response.stat is not",
"{name} endpoint \\\"\\\"\\\" uid: str \\\"\\\"\\\"The user id of the login user\\\"\\\"\\\" class",
"mock methods self.post_mock = MagicMock(wraps=mock_post) self.client.{module}.post = self.post_mock self.client.users.login = MagicMock(return_value=LoginResponseModel(susertoken='<PASSWORD>')) # login",
". import endpoints from .models import * class {classname}DataSource(NorenRestDataSource): \\\"\\\"\\\" Datasource for handling",
"success. Uses the token in the state if not passed explicitly. Returns: {model}ResponseModel:",
"= self._run_request(model, endpoints.{endpoint}, key) # convert the request to response model return {model}ResponseModel.parse_raw(response_json)",
"setUp(self) -> None: self.client = Client(os.getenv('API_URL'), os.getenv('SOCKET_URL')) # mock methods self.post_mock = MagicMock(wraps=mock_post)",
"build_loader, datetime_decoder __all__ = ['{classname}RequestModel', '{classname}ResponseModel'] class {classname}RequestModel(BaseModel): \\\"\\\"\\\" The request model for",
"= self.post_mock self.client.users.login = MagicMock(return_value=LoginResponseModel(susertoken='<PASSWORD>')) # login self.credentials = create_login_model() self.token = self.client.login(self.credentials).susertoken",
"build_loader({{ \\\"request_time\\\": datetime_decoder() }}) \"\"\" METHOD = \"\"\" def {name}(self, model: {model}RequestModel, key:",
"check pass else: assert response.emsg is not None assert type(response.emsg) == str \"\"\"",
"NorenRestDataSource from . import endpoints from .models import * class {classname}DataSource(NorenRestDataSource): \\\"\\\"\\\" Datasource",
"pydantic import BaseModel from datetime import datetime from ....common.enums import ResponseStatus from ....utils.decoders",
"\\\"\\\"\\\" {description} Args: model ({model}RequestModel): The data to be send as {model}RequestModel. key",
"\\\"\\\"\\\"The {name} success or failure status\\\"\\\"\\\" request_time: Optional[datetime] \\\"\\\"\\\"It will be present only",
"= MagicMock(wraps=mock_post) self.client.{module}.post = self.post_mock self.client.users.login = MagicMock(return_value=LoginResponseModel(susertoken='<PASSWORD>')) # login self.credentials = create_login_model()",
"Returns: {model}ResponseModel: The response as {model}ResponseModel. \\\"\\\"\\\" response_json = self._run_request(model, endpoints.{endpoint}, key) #",
"import json import unittest from unittest.mock import MagicMock from py_client import Client, ResponseStatus",
"Config: \\\"\\\"\\\"model configuration\\\"\\\"\\\" json_loads = build_loader({{ \\\"request_time\\\": datetime_decoder() }}) \"\"\" METHOD = \"\"\"",
"as constants \\\"\\\"\\\" # add your endpoints here \"\"\" INIT = \"\"\" \\\"\\\"\\\"",
"message if the request failed\\\"\\\"\\\" class Config: \\\"\\\"\\\"model configuration\\\"\\\"\\\" json_loads = build_loader({{ \\\"request_time\\\":",
"module \\\"\\\"\\\" # import your models here \"\"\" MODEL = \"\"\" \\\"\\\"\\\" Request",
"None if response.stat == ResponseStatus.OK: # check pass else: assert response.emsg is not",
"on login success. Uses the token in the state if not passed explicitly.",
"pass \"\"\" ENDPOINTS = \"\"\" \\\"\\\"\\\" API endpoint paths stored as constants \\\"\\\"\\\"",
"only on successful response.\\\"\\\"\\\" emsg: Optional[str] \\\"\\\"\\\"Error message if the request failed\\\"\\\"\\\" class",
"from datetime import datetime from ....common.enums import ResponseStatus from ....utils.decoders import build_loader, datetime_decoder",
"expected_body) with self.subTest('response should be parsed properly'): assert response is not None assert",
"= {model}RequestModel(...) response = self.client.{module}.{name}(model) with self.subTest('request should be called with proper data'):",
"response.stat == ResponseStatus.OK: # check pass else: assert response.emsg is not None assert",
"state if not passed explicitly. Returns: {model}ResponseModel: The response as {model}ResponseModel. \\\"\\\"\\\" response_json",
"\"\"\" MODEL = \"\"\" \\\"\\\"\\\" Request and response models for {name} request \\\"\\\"\\\"",
"test_{name}(self): model = {model}RequestModel(...) response = self.client.{module}.{name}(model) with self.subTest('request should be called with",
"\"\"\" ENDPOINTS = \"\"\" \\\"\\\"\\\" API endpoint paths stored as constants \\\"\\\"\\\" #",
"class {classname}DataSource(NorenRestDataSource): \\\"\\\"\\\" Datasource for handling {module} operations \\\"\\\"\\\" pass \"\"\" ENDPOINTS =",
"module \\\"\\\"\\\" from .datasource import * from .models import * \"\"\" MODELS_INIT =",
"MagicMock(return_value=LoginResponseModel(susertoken='<PASSWORD>')) # login self.credentials = create_login_model() self.token = self.client.login(self.credentials).susertoken assert self.token is not",
"['{classname}RequestModel', '{classname}ResponseModel'] class {classname}RequestModel(BaseModel): \\\"\\\"\\\" The request model for {name} endpoint \\\"\\\"\\\" uid:",
"operations \\\"\\\"\\\" from ...utils.datasources import NorenRestDataSource from . import endpoints from .models import",
"MagicMock(wraps=mock_post) self.client.{module}.post = self.post_mock self.client.users.login = MagicMock(return_value=LoginResponseModel(susertoken='<PASSWORD>')) # login self.credentials = create_login_model() self.token",
"= None) -> {model}ResponseModel: \\\"\\\"\\\" {description} Args: model ({model}RequestModel): The data to be",
"\"\"\" TEST_SUITE = \"\"\" import os import json import unittest from unittest.mock import",
"\\\"\\\"\\\" API endpoint paths stored as constants \\\"\\\"\\\" # add your endpoints here",
"failed\\\"\\\"\\\" class Config: \\\"\\\"\\\"model configuration\\\"\\\"\\\" json_loads = build_loader({{ \\\"request_time\\\": datetime_decoder() }}) \"\"\" METHOD",
"Request and response models for {name} request \\\"\\\"\\\" from typing import Optional from",
"# add your endpoints here \"\"\" INIT = \"\"\" \\\"\\\"\\\" The {module} module",
"key (str, optional): The key obtained on login success. Uses the token in",
"and response models for {module} module \\\"\\\"\\\" # import your models here \"\"\"",
"add your endpoints here \"\"\" INIT = \"\"\" \\\"\\\"\\\" The {module} module \\\"\\\"\\\"",
"from .common import create_login_model from .mock import mock_post class {classname}(unittest.TestCase): \\\"\\\"\\\" Test {name}",
"}} expected_body = f'jData={{json.dumps(expected_data)}}&jKey={{self.token}}' self.post_mock.assert_called_with(endpoints.{endpoint}, expected_body) with self.subTest('response should be parsed properly'): assert",
"failure status\\\"\\\"\\\" request_time: Optional[datetime] \\\"\\\"\\\"It will be present only on successful response.\\\"\\\"\\\" emsg:",
"import BaseModel from datetime import datetime from ....common.enums import ResponseStatus from ....utils.decoders import",
"Datasource for handling {module} operations \\\"\\\"\\\" from ...utils.datasources import NorenRestDataSource from . import",
"handling {module} operations \\\"\\\"\\\" from ...utils.datasources import NorenRestDataSource from . import endpoints from",
"response model return {model}ResponseModel.parse_raw(response_json) \"\"\" TEST_SUITE = \"\"\" import os import json import",
"# mock methods self.post_mock = MagicMock(wraps=mock_post) self.client.{module}.post = self.post_mock self.client.users.login = MagicMock(return_value=LoginResponseModel(susertoken='<PASSWORD>')) #",
"{model}ResponseModel: The response as {model}ResponseModel. \\\"\\\"\\\" response_json = self._run_request(model, endpoints.{endpoint}, key) # convert",
"\\\"\\\"\\\" from typing import Optional from pydantic import BaseModel from datetime import datetime",
"\\\"\\\"\\\" response_json = self._run_request(model, endpoints.{endpoint}, key) # convert the request to response model",
"Test {name} module \\\"\\\"\\\" def setUp(self) -> None: self.client = Client(os.getenv('API_URL'), os.getenv('SOCKET_URL')) #",
"key) # convert the request to response model return {model}ResponseModel.parse_raw(response_json) \"\"\" TEST_SUITE =",
"= \"\"\" \\\"\\\"\\\" The request and response models for {module} module \\\"\\\"\\\" #",
"Datasource for handling {module} operations \\\"\\\"\\\" pass \"\"\" ENDPOINTS = \"\"\" \\\"\\\"\\\" API",
"= MagicMock(return_value=LoginResponseModel(susertoken='<PASSWORD>')) # login self.credentials = create_login_model() self.token = self.client.login(self.credentials).susertoken assert self.token is",
"uid: str \\\"\\\"\\\"The user id of the login user\\\"\\\"\\\" class {classname}ResponseModel(BaseModel): \\\"\\\"\\\" The",
"\\\"\\\"\\\"The user id of the login user\\\"\\\"\\\" class {classname}ResponseModel(BaseModel): \\\"\\\"\\\" The response model",
"request_time: Optional[datetime] \\\"\\\"\\\"It will be present only on successful response.\\\"\\\"\\\" emsg: Optional[str] \\\"\\\"\\\"Error",
"{model}RequestModel. key (str, optional): The key obtained on login success. Uses the token",
".mock import mock_post class {classname}(unittest.TestCase): \\\"\\\"\\\" Test {name} module \\\"\\\"\\\" def setUp(self) ->",
"\"\"\" MODELS_INIT = \"\"\" \\\"\\\"\\\" The request and response models for {module} module",
".models import * class {classname}DataSource(NorenRestDataSource): \\\"\\\"\\\" Datasource for handling {module} operations \\\"\\\"\\\" pass",
"obtained on login success. Uses the token in the state if not passed",
"\\\"\\\"\\\" The response model for {name} endpoint \\\"\\\"\\\" stat: ResponseStatus \\\"\\\"\\\"The {name} success",
"from py_client import Client, ResponseStatus from py_client.models import LoginResponseModel from py_client.modules.{module}.models import *",
"will be present only on successful response.\\\"\\\"\\\" emsg: Optional[str] \\\"\\\"\\\"Error message if the",
"\"\"\" \\\"\\\"\\\" The {module} module \\\"\\\"\\\" from .datasource import * from .models import",
"the login user\\\"\\\"\\\" class {classname}ResponseModel(BaseModel): \\\"\\\"\\\" The response model for {name} endpoint \\\"\\\"\\\"",
"if the request failed\\\"\\\"\\\" class Config: \\\"\\\"\\\"model configuration\\\"\\\"\\\" json_loads = build_loader({{ \\\"request_time\\\": datetime_decoder()",
"The response as {model}ResponseModel. \\\"\\\"\\\" response_json = self._run_request(model, endpoints.{endpoint}, key) # convert the",
"on successful response.\\\"\\\"\\\" emsg: Optional[str] \\\"\\\"\\\"Error message if the request failed\\\"\\\"\\\" class Config:",
"not passed explicitly. Returns: {model}ResponseModel: The response as {model}ResponseModel. \\\"\\\"\\\" response_json = self._run_request(model,",
"from pydantic import BaseModel from datetime import datetime from ....common.enums import ResponseStatus from",
"....common.enums import ResponseStatus from ....utils.decoders import build_loader, datetime_decoder __all__ = ['{classname}RequestModel', '{classname}ResponseModel'] class",
"emsg: Optional[str] \\\"\\\"\\\"Error message if the request failed\\\"\\\"\\\" class Config: \\\"\\\"\\\"model configuration\\\"\\\"\\\" json_loads",
"import * \"\"\" MODELS_INIT = \"\"\" \\\"\\\"\\\" The request and response models for",
"endpoints from .common import create_login_model from .mock import mock_post class {classname}(unittest.TestCase): \\\"\\\"\\\" Test",
"model: {model}RequestModel, key: str = None) -> {model}ResponseModel: \\\"\\\"\\\" {description} Args: model ({model}RequestModel):",
"py_client.models import LoginResponseModel from py_client.modules.{module}.models import * from py_client.modules.{module} import endpoints from .common",
"py_client.modules.{module}.models import * from py_client.modules.{module} import endpoints from .common import create_login_model from .mock",
"paths stored as constants \\\"\\\"\\\" # add your endpoints here \"\"\" INIT =",
"for handling {module} operations \\\"\\\"\\\" from ...utils.datasources import NorenRestDataSource from . import endpoints",
"INIT = \"\"\" \\\"\\\"\\\" The {module} module \\\"\\\"\\\" from .datasource import * from",
"import MagicMock from py_client import Client, ResponseStatus from py_client.models import LoginResponseModel from py_client.modules.{module}.models",
"return {model}ResponseModel.parse_raw(response_json) \"\"\" TEST_SUITE = \"\"\" import os import json import unittest from",
"\\\"\\\"\\\" Test {name} module \\\"\\\"\\\" def setUp(self) -> None: self.client = Client(os.getenv('API_URL'), os.getenv('SOCKET_URL'))",
"def setUp(self) -> None: self.client = Client(os.getenv('API_URL'), os.getenv('SOCKET_URL')) # mock methods self.post_mock =",
"{model}ResponseModel: \\\"\\\"\\\" {description} Args: model ({model}RequestModel): The data to be send as {model}RequestModel.",
"TEST_CASE = \"\"\" def test_{name}(self): model = {model}RequestModel(...) response = self.client.{module}.{name}(model) with self.subTest('request",
"\"\"\" \\\"\\\"\\\" Request and response models for {name} request \\\"\\\"\\\" from typing import",
"Args: model ({model}RequestModel): The data to be send as {model}RequestModel. key (str, optional):",
"login user\\\"\\\"\\\" class {classname}ResponseModel(BaseModel): \\\"\\\"\\\" The response model for {name} endpoint \\\"\\\"\\\" stat:",
"BaseModel from datetime import datetime from ....common.enums import ResponseStatus from ....utils.decoders import build_loader,",
"response model for {name} endpoint \\\"\\\"\\\" stat: ResponseStatus \\\"\\\"\\\"The {name} success or failure",
"stat: ResponseStatus \\\"\\\"\\\"The {name} success or failure status\\\"\\\"\\\" request_time: Optional[datetime] \\\"\\\"\\\"It will be",
"with proper data'): expected_data = {{ ... }} expected_body = f'jData={{json.dumps(expected_data)}}&jKey={{self.token}}' self.post_mock.assert_called_with(endpoints.{endpoint}, expected_body)",
"response.\\\"\\\"\\\" emsg: Optional[str] \\\"\\\"\\\"Error message if the request failed\\\"\\\"\\\" class Config: \\\"\\\"\\\"model configuration\\\"\\\"\\\"",
"= self.client.login(self.credentials).susertoken assert self.token is not None \"\"\" TEST_CASE = \"\"\" def test_{name}(self):",
"{model}ResponseModel. \\\"\\\"\\\" response_json = self._run_request(model, endpoints.{endpoint}, key) # convert the request to response",
"\\\"\\\"\\\" # import your models here \"\"\" MODEL = \"\"\" \\\"\\\"\\\" Request and",
"assert response.stat is not None if response.stat == ResponseStatus.OK: # check pass else:",
"import endpoints from .common import create_login_model from .mock import mock_post class {classname}(unittest.TestCase): \\\"\\\"\\\"",
"... }} expected_body = f'jData={{json.dumps(expected_data)}}&jKey={{self.token}}' self.post_mock.assert_called_with(endpoints.{endpoint}, expected_body) with self.subTest('response should be parsed properly'):",
"create_login_model from .mock import mock_post class {classname}(unittest.TestCase): \\\"\\\"\\\" Test {name} module \\\"\\\"\\\" def",
"ResponseStatus \\\"\\\"\\\"The {name} success or failure status\\\"\\\"\\\" request_time: Optional[datetime] \\\"\\\"\\\"It will be present",
"{name} endpoint \\\"\\\"\\\" stat: ResponseStatus \\\"\\\"\\\"The {name} success or failure status\\\"\\\"\\\" request_time: Optional[datetime]",
"send as {model}RequestModel. key (str, optional): The key obtained on login success. Uses",
"= \"\"\" \\\"\\\"\\\" Request and response models for {name} request \\\"\\\"\\\" from typing",
"= ['{classname}RequestModel', '{classname}ResponseModel'] class {classname}RequestModel(BaseModel): \\\"\\\"\\\" The request model for {name} endpoint \\\"\\\"\\\"",
"= \"\"\" \\\"\\\"\\\" API endpoint paths stored as constants \\\"\\\"\\\" # add your",
"py_client import Client, ResponseStatus from py_client.models import LoginResponseModel from py_client.modules.{module}.models import * from",
"* class {classname}DataSource(NorenRestDataSource): \\\"\\\"\\\" Datasource for handling {module} operations \\\"\\\"\\\" pass \"\"\" ENDPOINTS",
"success or failure status\\\"\\\"\\\" request_time: Optional[datetime] \\\"\\\"\\\"It will be present only on successful",
".models import * \"\"\" MODELS_INIT = \"\"\" \\\"\\\"\\\" The request and response models",
"import Client, ResponseStatus from py_client.models import LoginResponseModel from py_client.modules.{module}.models import * from py_client.modules.{module}",
"str = None) -> {model}ResponseModel: \\\"\\\"\\\" {description} Args: model ({model}RequestModel): The data to",
"The data to be send as {model}RequestModel. key (str, optional): The key obtained",
"import unittest from unittest.mock import MagicMock from py_client import Client, ResponseStatus from py_client.models",
"Optional[str] \\\"\\\"\\\"Error message if the request failed\\\"\\\"\\\" class Config: \\\"\\\"\\\"model configuration\\\"\\\"\\\" json_loads =",
"handling {module} operations \\\"\\\"\\\" pass \"\"\" ENDPOINTS = \"\"\" \\\"\\\"\\\" API endpoint paths",
"None: self.client = Client(os.getenv('API_URL'), os.getenv('SOCKET_URL')) # mock methods self.post_mock = MagicMock(wraps=mock_post) self.client.{module}.post =",
"{name} module \\\"\\\"\\\" def setUp(self) -> None: self.client = Client(os.getenv('API_URL'), os.getenv('SOCKET_URL')) # mock",
"import datetime from ....common.enums import ResponseStatus from ....utils.decoders import build_loader, datetime_decoder __all__ =",
"datetime import datetime from ....common.enums import ResponseStatus from ....utils.decoders import build_loader, datetime_decoder __all__",
"import ResponseStatus from ....utils.decoders import build_loader, datetime_decoder __all__ = ['{classname}RequestModel', '{classname}ResponseModel'] class {classname}RequestModel(BaseModel):",
"is not None \"\"\" TEST_CASE = \"\"\" def test_{name}(self): model = {model}RequestModel(...) response",
"expected_data = {{ ... }} expected_body = f'jData={{json.dumps(expected_data)}}&jKey={{self.token}}' self.post_mock.assert_called_with(endpoints.{endpoint}, expected_body) with self.subTest('response should",
"self.client = Client(os.getenv('API_URL'), os.getenv('SOCKET_URL')) # mock methods self.post_mock = MagicMock(wraps=mock_post) self.client.{module}.post = self.post_mock",
"the token in the state if not passed explicitly. Returns: {model}ResponseModel: The response",
"from . import endpoints from .models import * class {classname}DataSource(NorenRestDataSource): \\\"\\\"\\\" Datasource for",
"or failure status\\\"\\\"\\\" request_time: Optional[datetime] \\\"\\\"\\\"It will be present only on successful response.\\\"\\\"\\\"",
"if not passed explicitly. Returns: {model}ResponseModel: The response as {model}ResponseModel. \\\"\\\"\\\" response_json =",
"....utils.decoders import build_loader, datetime_decoder __all__ = ['{classname}RequestModel', '{classname}ResponseModel'] class {classname}RequestModel(BaseModel): \\\"\\\"\\\" The request",
"operations \\\"\\\"\\\" pass \"\"\" ENDPOINTS = \"\"\" \\\"\\\"\\\" API endpoint paths stored as",
"called with proper data'): expected_data = {{ ... }} expected_body = f'jData={{json.dumps(expected_data)}}&jKey={{self.token}}' self.post_mock.assert_called_with(endpoints.{endpoint},",
"be parsed properly'): assert response is not None assert response.stat is not None",
"# check pass else: assert response.emsg is not None assert type(response.emsg) == str",
"for {module} module \\\"\\\"\\\" # import your models here \"\"\" MODEL = \"\"\"",
"json_loads = build_loader({{ \\\"request_time\\\": datetime_decoder() }}) \"\"\" METHOD = \"\"\" def {name}(self, model:",
"{classname}ResponseModel(BaseModel): \\\"\\\"\\\" The response model for {name} endpoint \\\"\\\"\\\" stat: ResponseStatus \\\"\\\"\\\"The {name}",
"key obtained on login success. Uses the token in the state if not",
"for {name} endpoint \\\"\\\"\\\" uid: str \\\"\\\"\\\"The user id of the login user\\\"\\\"\\\"",
"self.subTest('request should be called with proper data'): expected_data = {{ ... }} expected_body",
"\"\"\" \\\"\\\"\\\" The request and response models for {module} module \\\"\\\"\\\" # import",
"response as {model}ResponseModel. \\\"\\\"\\\" response_json = self._run_request(model, endpoints.{endpoint}, key) # convert the request",
"\"\"\" \\\"\\\"\\\" API endpoint paths stored as constants \\\"\\\"\\\" # add your endpoints",
"\\\"\\\"\\\" The {module} module \\\"\\\"\\\" from .datasource import * from .models import *",
"import your models here \"\"\" MODEL = \"\"\" \\\"\\\"\\\" Request and response models",
"(str, optional): The key obtained on login success. Uses the token in the",
"# login self.credentials = create_login_model() self.token = self.client.login(self.credentials).susertoken assert self.token is not None",
"# import your models here \"\"\" MODEL = \"\"\" \\\"\\\"\\\" Request and response",
"import mock_post class {classname}(unittest.TestCase): \\\"\\\"\\\" Test {name} module \\\"\\\"\\\" def setUp(self) -> None:",
"endpoints from .models import * class {classname}DataSource(NorenRestDataSource): \\\"\\\"\\\" Datasource for handling {module} operations",
"= \"\"\" def {name}(self, model: {model}RequestModel, key: str = None) -> {model}ResponseModel: \\\"\\\"\\\"",
"{classname}RequestModel(BaseModel): \\\"\\\"\\\" The request model for {name} endpoint \\\"\\\"\\\" uid: str \\\"\\\"\\\"The user",
"\\\"\\\"\\\"model configuration\\\"\\\"\\\" json_loads = build_loader({{ \\\"request_time\\\": datetime_decoder() }}) \"\"\" METHOD = \"\"\" def",
"response models for {name} request \\\"\\\"\\\" from typing import Optional from pydantic import",
"import NorenRestDataSource from . import endpoints from .models import * class {classname}DataSource(NorenRestDataSource): \\\"\\\"\\\"",
"import LoginResponseModel from py_client.modules.{module}.models import * from py_client.modules.{module} import endpoints from .common import",
"self.credentials = create_login_model() self.token = self.client.login(self.credentials).susertoken assert self.token is not None \"\"\" TEST_CASE",
"= \"\"\" \\\"\\\"\\\" The {module} module \\\"\\\"\\\" from .datasource import * from .models",
"response models for {module} module \\\"\\\"\\\" # import your models here \"\"\" MODEL",
"import create_login_model from .mock import mock_post class {classname}(unittest.TestCase): \\\"\\\"\\\" Test {name} module \\\"\\\"\\\"",
"of the login user\\\"\\\"\\\" class {classname}ResponseModel(BaseModel): \\\"\\\"\\\" The response model for {name} endpoint",
"Optional[datetime] \\\"\\\"\\\"It will be present only on successful response.\\\"\\\"\\\" emsg: Optional[str] \\\"\\\"\\\"Error message",
"\\\"\\\"\\\"It will be present only on successful response.\\\"\\\"\\\" emsg: Optional[str] \\\"\\\"\\\"Error message if",
"ResponseStatus from py_client.models import LoginResponseModel from py_client.modules.{module}.models import * from py_client.modules.{module} import endpoints",
"Optional from pydantic import BaseModel from datetime import datetime from ....common.enums import ResponseStatus",
"is not None if response.stat == ResponseStatus.OK: # check pass else: assert response.emsg",
"from .models import * \"\"\" MODELS_INIT = \"\"\" \\\"\\\"\\\" The request and response",
"({model}RequestModel): The data to be send as {model}RequestModel. key (str, optional): The key",
"ResponseStatus.OK: # check pass else: assert response.emsg is not None assert type(response.emsg) ==",
"model ({model}RequestModel): The data to be send as {model}RequestModel. key (str, optional): The",
"json import unittest from unittest.mock import MagicMock from py_client import Client, ResponseStatus from",
"endpoints.{endpoint}, key) # convert the request to response model return {model}ResponseModel.parse_raw(response_json) \"\"\" TEST_SUITE",
"status\\\"\\\"\\\" request_time: Optional[datetime] \\\"\\\"\\\"It will be present only on successful response.\\\"\\\"\\\" emsg: Optional[str]",
"-> None: self.client = Client(os.getenv('API_URL'), os.getenv('SOCKET_URL')) # mock methods self.post_mock = MagicMock(wraps=mock_post) self.client.{module}.post",
"\\\"\\\"\\\" pass \"\"\" ENDPOINTS = \"\"\" \\\"\\\"\\\" API endpoint paths stored as constants",
"your models here \"\"\" MODEL = \"\"\" \\\"\\\"\\\" Request and response models for",
"from .models import * class {classname}DataSource(NorenRestDataSource): \\\"\\\"\\\" Datasource for handling {module} operations \\\"\\\"\\\"",
"* from py_client.modules.{module} import endpoints from .common import create_login_model from .mock import mock_post",
"str \\\"\\\"\\\"The user id of the login user\\\"\\\"\\\" class {classname}ResponseModel(BaseModel): \\\"\\\"\\\" The response",
"{name}(self, model: {model}RequestModel, key: str = None) -> {model}ResponseModel: \\\"\\\"\\\" {description} Args: model",
"mock_post class {classname}(unittest.TestCase): \\\"\\\"\\\" Test {name} module \\\"\\\"\\\" def setUp(self) -> None: self.client",
"def test_{name}(self): model = {model}RequestModel(...) response = self.client.{module}.{name}(model) with self.subTest('request should be called",
"be send as {model}RequestModel. key (str, optional): The key obtained on login success.",
"{name} request \\\"\\\"\\\" from typing import Optional from pydantic import BaseModel from datetime",
"token in the state if not passed explicitly. Returns: {model}ResponseModel: The response as",
"{model}ResponseModel.parse_raw(response_json) \"\"\" TEST_SUITE = \"\"\" import os import json import unittest from unittest.mock",
"parsed properly'): assert response is not None assert response.stat is not None if",
"{module} module \\\"\\\"\\\" from .datasource import * from .models import * \"\"\" MODELS_INIT",
"\\\"\\\"\\\" The request model for {name} endpoint \\\"\\\"\\\" uid: str \\\"\\\"\\\"The user id",
".datasource import * from .models import * \"\"\" MODELS_INIT = \"\"\" \\\"\\\"\\\" The",
"should be called with proper data'): expected_data = {{ ... }} expected_body =",
"methods self.post_mock = MagicMock(wraps=mock_post) self.client.{module}.post = self.post_mock self.client.users.login = MagicMock(return_value=LoginResponseModel(susertoken='<PASSWORD>')) # login self.credentials",
"if response.stat == ResponseStatus.OK: # check pass else: assert response.emsg is not None",
"be present only on successful response.\\\"\\\"\\\" emsg: Optional[str] \\\"\\\"\\\"Error message if the request",
"\"\"\" \\\"\\\"\\\" Datasource for handling {module} operations \\\"\\\"\\\" from ...utils.datasources import NorenRestDataSource from",
"create_login_model() self.token = self.client.login(self.credentials).susertoken assert self.token is not None \"\"\" TEST_CASE = \"\"\"",
"The key obtained on login success. Uses the token in the state if",
"{module} operations \\\"\\\"\\\" from ...utils.datasources import NorenRestDataSource from . import endpoints from .models",
"{description} Args: model ({model}RequestModel): The data to be send as {model}RequestModel. key (str,",
"model return {model}ResponseModel.parse_raw(response_json) \"\"\" TEST_SUITE = \"\"\" import os import json import unittest",
"'{classname}ResponseModel'] class {classname}RequestModel(BaseModel): \\\"\\\"\\\" The request model for {name} endpoint \\\"\\\"\\\" uid: str",
"self.client.users.login = MagicMock(return_value=LoginResponseModel(susertoken='<PASSWORD>')) # login self.credentials = create_login_model() self.token = self.client.login(self.credentials).susertoken assert self.token",
"\\\"\\\"\\\" Datasource for handling {module} operations \\\"\\\"\\\" pass \"\"\" ENDPOINTS = \"\"\" \\\"\\\"\\\"",
"{module} operations \\\"\\\"\\\" pass \"\"\" ENDPOINTS = \"\"\" \\\"\\\"\\\" API endpoint paths stored",
"ENDPOINTS = \"\"\" \\\"\\\"\\\" API endpoint paths stored as constants \\\"\\\"\\\" # add",
"typing import Optional from pydantic import BaseModel from datetime import datetime from ....common.enums",
"for {name} request \\\"\\\"\\\" from typing import Optional from pydantic import BaseModel from",
"passed explicitly. Returns: {model}ResponseModel: The response as {model}ResponseModel. \\\"\\\"\\\" response_json = self._run_request(model, endpoints.{endpoint},",
"Uses the token in the state if not passed explicitly. Returns: {model}ResponseModel: The",
"\\\"\\\"\\\" Request and response models for {name} request \\\"\\\"\\\" from typing import Optional",
"self.client.{module}.post = self.post_mock self.client.users.login = MagicMock(return_value=LoginResponseModel(susertoken='<PASSWORD>')) # login self.credentials = create_login_model() self.token =",
"module \\\"\\\"\\\" def setUp(self) -> None: self.client = Client(os.getenv('API_URL'), os.getenv('SOCKET_URL')) # mock methods",
"\\\"\\\"\\\" stat: ResponseStatus \\\"\\\"\\\"The {name} success or failure status\\\"\\\"\\\" request_time: Optional[datetime] \\\"\\\"\\\"It will",
"MODELS_INIT = \"\"\" \\\"\\\"\\\" The request and response models for {module} module \\\"\\\"\\\"",
"{module} module \\\"\\\"\\\" # import your models here \"\"\" MODEL = \"\"\" \\\"\\\"\\\"",
"f'jData={{json.dumps(expected_data)}}&jKey={{self.token}}' self.post_mock.assert_called_with(endpoints.{endpoint}, expected_body) with self.subTest('response should be parsed properly'): assert response is not",
"= build_loader({{ \\\"request_time\\\": datetime_decoder() }}) \"\"\" METHOD = \"\"\" def {name}(self, model: {model}RequestModel,",
"DATASOURCE = \"\"\" \\\"\\\"\\\" Datasource for handling {module} operations \\\"\\\"\\\" from ...utils.datasources import",
"= create_login_model() self.token = self.client.login(self.credentials).susertoken assert self.token is not None \"\"\" TEST_CASE =",
"datetime_decoder __all__ = ['{classname}RequestModel', '{classname}ResponseModel'] class {classname}RequestModel(BaseModel): \\\"\\\"\\\" The request model for {name}",
"is not None assert response.stat is not None if response.stat == ResponseStatus.OK: #",
"assert self.token is not None \"\"\" TEST_CASE = \"\"\" def test_{name}(self): model =",
"None \"\"\" TEST_CASE = \"\"\" def test_{name}(self): model = {model}RequestModel(...) response = self.client.{module}.{name}(model)",
"\"\"\" def test_{name}(self): model = {model}RequestModel(...) response = self.client.{module}.{name}(model) with self.subTest('request should be",
"optional): The key obtained on login success. Uses the token in the state",
"login success. Uses the token in the state if not passed explicitly. Returns:",
"response = self.client.{module}.{name}(model) with self.subTest('request should be called with proper data'): expected_data =",
"{model}RequestModel, key: str = None) -> {model}ResponseModel: \\\"\\\"\\\" {description} Args: model ({model}RequestModel): The",
"stored as constants \\\"\\\"\\\" # add your endpoints here \"\"\" INIT = \"\"\"",
"from ....common.enums import ResponseStatus from ....utils.decoders import build_loader, datetime_decoder __all__ = ['{classname}RequestModel', '{classname}ResponseModel']",
".common import create_login_model from .mock import mock_post class {classname}(unittest.TestCase): \\\"\\\"\\\" Test {name} module",
"request model for {name} endpoint \\\"\\\"\\\" uid: str \\\"\\\"\\\"The user id of the",
"= \"\"\" import os import json import unittest from unittest.mock import MagicMock from",
"= \"\"\" def test_{name}(self): model = {model}RequestModel(...) response = self.client.{module}.{name}(model) with self.subTest('request should",
"\\\"request_time\\\": datetime_decoder() }}) \"\"\" METHOD = \"\"\" def {name}(self, model: {model}RequestModel, key: str",
"response.stat is not None if response.stat == ResponseStatus.OK: # check pass else: assert",
"request to response model return {model}ResponseModel.parse_raw(response_json) \"\"\" TEST_SUITE = \"\"\" import os import",
"{{ ... }} expected_body = f'jData={{json.dumps(expected_data)}}&jKey={{self.token}}' self.post_mock.assert_called_with(endpoints.{endpoint}, expected_body) with self.subTest('response should be parsed",
"models for {name} request \\\"\\\"\\\" from typing import Optional from pydantic import BaseModel",
"Client, ResponseStatus from py_client.models import LoginResponseModel from py_client.modules.{module}.models import * from py_client.modules.{module} import",
"here \"\"\" MODEL = \"\"\" \\\"\\\"\\\" Request and response models for {name} request",
"self.post_mock self.client.users.login = MagicMock(return_value=LoginResponseModel(susertoken='<PASSWORD>')) # login self.credentials = create_login_model() self.token = self.client.login(self.credentials).susertoken assert",
"...utils.datasources import NorenRestDataSource from . import endpoints from .models import * class {classname}DataSource(NorenRestDataSource):",
"Client(os.getenv('API_URL'), os.getenv('SOCKET_URL')) # mock methods self.post_mock = MagicMock(wraps=mock_post) self.client.{module}.post = self.post_mock self.client.users.login =",
"TEST_SUITE = \"\"\" import os import json import unittest from unittest.mock import MagicMock",
"self.client.login(self.credentials).susertoken assert self.token is not None \"\"\" TEST_CASE = \"\"\" def test_{name}(self): model",
"\"\"\" INIT = \"\"\" \\\"\\\"\\\" The {module} module \\\"\\\"\\\" from .datasource import *",
"as {model}ResponseModel. \\\"\\\"\\\" response_json = self._run_request(model, endpoints.{endpoint}, key) # convert the request to",
"import os import json import unittest from unittest.mock import MagicMock from py_client import",
"\\\"\\\"\\\" # add your endpoints here \"\"\" INIT = \"\"\" \\\"\\\"\\\" The {module}",
"__all__ = ['{classname}RequestModel', '{classname}ResponseModel'] class {classname}RequestModel(BaseModel): \\\"\\\"\\\" The request model for {name} endpoint",
"from ...utils.datasources import NorenRestDataSource from . import endpoints from .models import * class",
"proper data'): expected_data = {{ ... }} expected_body = f'jData={{json.dumps(expected_data)}}&jKey={{self.token}}' self.post_mock.assert_called_with(endpoints.{endpoint}, expected_body) with",
"\\\"\\\"\\\" uid: str \\\"\\\"\\\"The user id of the login user\\\"\\\"\\\" class {classname}ResponseModel(BaseModel): \\\"\\\"\\\"",
"\\\"\\\"\\\" def setUp(self) -> None: self.client = Client(os.getenv('API_URL'), os.getenv('SOCKET_URL')) # mock methods self.post_mock",
"the request failed\\\"\\\"\\\" class Config: \\\"\\\"\\\"model configuration\\\"\\\"\\\" json_loads = build_loader({{ \\\"request_time\\\": datetime_decoder() }})",
"to response model return {model}ResponseModel.parse_raw(response_json) \"\"\" TEST_SUITE = \"\"\" import os import json",
"\"\"\" TEST_CASE = \"\"\" def test_{name}(self): model = {model}RequestModel(...) response = self.client.{module}.{name}(model) with",
"def {name}(self, model: {model}RequestModel, key: str = None) -> {model}ResponseModel: \\\"\\\"\\\" {description} Args:",
"convert the request to response model return {model}ResponseModel.parse_raw(response_json) \"\"\" TEST_SUITE = \"\"\" import",
"import * class {classname}DataSource(NorenRestDataSource): \\\"\\\"\\\" Datasource for handling {module} operations \\\"\\\"\\\" pass \"\"\"",
"unittest.mock import MagicMock from py_client import Client, ResponseStatus from py_client.models import LoginResponseModel from",
"= self.client.{module}.{name}(model) with self.subTest('request should be called with proper data'): expected_data = {{",
"as {model}RequestModel. key (str, optional): The key obtained on login success. Uses the",
"os.getenv('SOCKET_URL')) # mock methods self.post_mock = MagicMock(wraps=mock_post) self.client.{module}.post = self.post_mock self.client.users.login = MagicMock(return_value=LoginResponseModel(susertoken='<PASSWORD>'))",
"\"\"\" def {name}(self, model: {model}RequestModel, key: str = None) -> {model}ResponseModel: \\\"\\\"\\\" {description}",
"configuration\\\"\\\"\\\" json_loads = build_loader({{ \\\"request_time\\\": datetime_decoder() }}) \"\"\" METHOD = \"\"\" def {name}(self,",
"request \\\"\\\"\\\" from typing import Optional from pydantic import BaseModel from datetime import",
"present only on successful response.\\\"\\\"\\\" emsg: Optional[str] \\\"\\\"\\\"Error message if the request failed\\\"\\\"\\\"",
"self.token is not None \"\"\" TEST_CASE = \"\"\" def test_{name}(self): model = {model}RequestModel(...)",
"from ....utils.decoders import build_loader, datetime_decoder __all__ = ['{classname}RequestModel', '{classname}ResponseModel'] class {classname}RequestModel(BaseModel): \\\"\\\"\\\" The",
"from py_client.modules.{module} import endpoints from .common import create_login_model from .mock import mock_post class",
"from typing import Optional from pydantic import BaseModel from datetime import datetime from",
"and response models for {name} request \\\"\\\"\\\" from typing import Optional from pydantic",
"not None \"\"\" TEST_CASE = \"\"\" def test_{name}(self): model = {model}RequestModel(...) response =",
"import * from .models import * \"\"\" MODELS_INIT = \"\"\" \\\"\\\"\\\" The request",
"request failed\\\"\\\"\\\" class Config: \\\"\\\"\\\"model configuration\\\"\\\"\\\" json_loads = build_loader({{ \\\"request_time\\\": datetime_decoder() }}) \"\"\"",
"your endpoints here \"\"\" INIT = \"\"\" \\\"\\\"\\\" The {module} module \\\"\\\"\\\" from",
"user\\\"\\\"\\\" class {classname}ResponseModel(BaseModel): \\\"\\\"\\\" The response model for {name} endpoint \\\"\\\"\\\" stat: ResponseStatus",
"to be send as {model}RequestModel. key (str, optional): The key obtained on login",
"response is not None assert response.stat is not None if response.stat == ResponseStatus.OK:",
"{model}RequestModel(...) response = self.client.{module}.{name}(model) with self.subTest('request should be called with proper data'): expected_data",
"constants \\\"\\\"\\\" # add your endpoints here \"\"\" INIT = \"\"\" \\\"\\\"\\\" The",
"LoginResponseModel from py_client.modules.{module}.models import * from py_client.modules.{module} import endpoints from .common import create_login_model",
"= Client(os.getenv('API_URL'), os.getenv('SOCKET_URL')) # mock methods self.post_mock = MagicMock(wraps=mock_post) self.client.{module}.post = self.post_mock self.client.users.login",
"from .mock import mock_post class {classname}(unittest.TestCase): \\\"\\\"\\\" Test {name} module \\\"\\\"\\\" def setUp(self)",
"successful response.\\\"\\\"\\\" emsg: Optional[str] \\\"\\\"\\\"Error message if the request failed\\\"\\\"\\\" class Config: \\\"\\\"\\\"model",
"-> {model}ResponseModel: \\\"\\\"\\\" {description} Args: model ({model}RequestModel): The data to be send as",
"endpoint \\\"\\\"\\\" uid: str \\\"\\\"\\\"The user id of the login user\\\"\\\"\\\" class {classname}ResponseModel(BaseModel):",
"for {name} endpoint \\\"\\\"\\\" stat: ResponseStatus \\\"\\\"\\\"The {name} success or failure status\\\"\\\"\\\" request_time:",
"key: str = None) -> {model}ResponseModel: \\\"\\\"\\\" {description} Args: model ({model}RequestModel): The data",
"here \"\"\" INIT = \"\"\" \\\"\\\"\\\" The {module} module \\\"\\\"\\\" from .datasource import",
"class {classname}RequestModel(BaseModel): \\\"\\\"\\\" The request model for {name} endpoint \\\"\\\"\\\" uid: str \\\"\\\"\\\"The",
"endpoints here \"\"\" INIT = \"\"\" \\\"\\\"\\\" The {module} module \\\"\\\"\\\" from .datasource",
"API endpoint paths stored as constants \\\"\\\"\\\" # add your endpoints here \"\"\"",
"The request model for {name} endpoint \\\"\\\"\\\" uid: str \\\"\\\"\\\"The user id of",
"class {classname}(unittest.TestCase): \\\"\\\"\\\" Test {name} module \\\"\\\"\\\" def setUp(self) -> None: self.client =",
"expected_body = f'jData={{json.dumps(expected_data)}}&jKey={{self.token}}' self.post_mock.assert_called_with(endpoints.{endpoint}, expected_body) with self.subTest('response should be parsed properly'): assert response",
"= \"\"\" \\\"\\\"\\\" Datasource for handling {module} operations \\\"\\\"\\\" from ...utils.datasources import NorenRestDataSource",
"== ResponseStatus.OK: # check pass else: assert response.emsg is not None assert type(response.emsg)",
"self.post_mock.assert_called_with(endpoints.{endpoint}, expected_body) with self.subTest('response should be parsed properly'): assert response is not None",
"data to be send as {model}RequestModel. key (str, optional): The key obtained on",
"import endpoints from .models import * class {classname}DataSource(NorenRestDataSource): \\\"\\\"\\\" Datasource for handling {module}",
"\\\"\\\"\\\" Datasource for handling {module} operations \\\"\\\"\\\" from ...utils.datasources import NorenRestDataSource from .",
"endpoint \\\"\\\"\\\" stat: ResponseStatus \\\"\\\"\\\"The {name} success or failure status\\\"\\\"\\\" request_time: Optional[datetime] \\\"\\\"\\\"It",
"login self.credentials = create_login_model() self.token = self.client.login(self.credentials).susertoken assert self.token is not None \"\"\"",
"MODEL = \"\"\" \\\"\\\"\\\" Request and response models for {name} request \\\"\\\"\\\" from",
"\\\"\\\"\\\" from .datasource import * from .models import * \"\"\" MODELS_INIT = \"\"\"",
"self.post_mock = MagicMock(wraps=mock_post) self.client.{module}.post = self.post_mock self.client.users.login = MagicMock(return_value=LoginResponseModel(susertoken='<PASSWORD>')) # login self.credentials =",
"MagicMock from py_client import Client, ResponseStatus from py_client.models import LoginResponseModel from py_client.modules.{module}.models import",
"# convert the request to response model return {model}ResponseModel.parse_raw(response_json) \"\"\" TEST_SUITE = \"\"\"",
"\"\"\" import os import json import unittest from unittest.mock import MagicMock from py_client",
"\\\"\\\"\\\" from ...utils.datasources import NorenRestDataSource from . import endpoints from .models import *",
"datetime_decoder() }}) \"\"\" METHOD = \"\"\" def {name}(self, model: {model}RequestModel, key: str =",
"None) -> {model}ResponseModel: \\\"\\\"\\\" {description} Args: model ({model}RequestModel): The data to be send",
"unittest from unittest.mock import MagicMock from py_client import Client, ResponseStatus from py_client.models import",
"id of the login user\\\"\\\"\\\" class {classname}ResponseModel(BaseModel): \\\"\\\"\\\" The response model for {name}",
"* \"\"\" MODELS_INIT = \"\"\" \\\"\\\"\\\" The request and response models for {module}",
"data'): expected_data = {{ ... }} expected_body = f'jData={{json.dumps(expected_data)}}&jKey={{self.token}}' self.post_mock.assert_called_with(endpoints.{endpoint}, expected_body) with self.subTest('response",
"= {{ ... }} expected_body = f'jData={{json.dumps(expected_data)}}&jKey={{self.token}}' self.post_mock.assert_called_with(endpoints.{endpoint}, expected_body) with self.subTest('response should be",
"model = {model}RequestModel(...) response = self.client.{module}.{name}(model) with self.subTest('request should be called with proper",
"self.client.{module}.{name}(model) with self.subTest('request should be called with proper data'): expected_data = {{ ...",
"explicitly. Returns: {model}ResponseModel: The response as {model}ResponseModel. \\\"\\\"\\\" response_json = self._run_request(model, endpoints.{endpoint}, key)",
"\"\"\" METHOD = \"\"\" def {name}(self, model: {model}RequestModel, key: str = None) ->",
"{name} success or failure status\\\"\\\"\\\" request_time: Optional[datetime] \\\"\\\"\\\"It will be present only on",
"in the state if not passed explicitly. Returns: {model}ResponseModel: The response as {model}ResponseModel.",
"The {module} module \\\"\\\"\\\" from .datasource import * from .models import * \"\"\"",
"import build_loader, datetime_decoder __all__ = ['{classname}RequestModel', '{classname}ResponseModel'] class {classname}RequestModel(BaseModel): \\\"\\\"\\\" The request model",
"endpoint paths stored as constants \\\"\\\"\\\" # add your endpoints here \"\"\" INIT",
"self.token = self.client.login(self.credentials).susertoken assert self.token is not None \"\"\" TEST_CASE = \"\"\" def",
"{classname}DataSource(NorenRestDataSource): \\\"\\\"\\\" Datasource for handling {module} operations \\\"\\\"\\\" pass \"\"\" ENDPOINTS = \"\"\"",
"assert response is not None assert response.stat is not None if response.stat ==",
"= f'jData={{json.dumps(expected_data)}}&jKey={{self.token}}' self.post_mock.assert_called_with(endpoints.{endpoint}, expected_body) with self.subTest('response should be parsed properly'): assert response is",
"request and response models for {module} module \\\"\\\"\\\" # import your models here",
"from .datasource import * from .models import * \"\"\" MODELS_INIT = \"\"\" \\\"\\\"\\\"",
"* from .models import * \"\"\" MODELS_INIT = \"\"\" \\\"\\\"\\\" The request and",
"import * from py_client.modules.{module} import endpoints from .common import create_login_model from .mock import",
"with self.subTest('response should be parsed properly'): assert response is not None assert response.stat",
"None assert response.stat is not None if response.stat == ResponseStatus.OK: # check pass",
"\\\"\\\"\\\" The request and response models for {module} module \\\"\\\"\\\" # import your",
"with self.subTest('request should be called with proper data'): expected_data = {{ ... }}",
"be called with proper data'): expected_data = {{ ... }} expected_body = f'jData={{json.dumps(expected_data)}}&jKey={{self.token}}'",
"properly'): assert response is not None assert response.stat is not None if response.stat",
"self._run_request(model, endpoints.{endpoint}, key) # convert the request to response model return {model}ResponseModel.parse_raw(response_json) \"\"\"",
"model for {name} endpoint \\\"\\\"\\\" uid: str \\\"\\\"\\\"The user id of the login",
"\\\"\\\"\\\"Error message if the request failed\\\"\\\"\\\" class Config: \\\"\\\"\\\"model configuration\\\"\\\"\\\" json_loads = build_loader({{",
"models for {module} module \\\"\\\"\\\" # import your models here \"\"\" MODEL =",
"{classname}(unittest.TestCase): \\\"\\\"\\\" Test {name} module \\\"\\\"\\\" def setUp(self) -> None: self.client = Client(os.getenv('API_URL'),",
"user id of the login user\\\"\\\"\\\" class {classname}ResponseModel(BaseModel): \\\"\\\"\\\" The response model for",
"the state if not passed explicitly. Returns: {model}ResponseModel: The response as {model}ResponseModel. \\\"\\\"\\\"",
"class {classname}ResponseModel(BaseModel): \\\"\\\"\\\" The response model for {name} endpoint \\\"\\\"\\\" stat: ResponseStatus \\\"\\\"\\\"The",
"The response model for {name} endpoint \\\"\\\"\\\" stat: ResponseStatus \\\"\\\"\\\"The {name} success or",
"models here \"\"\" MODEL = \"\"\" \\\"\\\"\\\" Request and response models for {name}",
"METHOD = \"\"\" def {name}(self, model: {model}RequestModel, key: str = None) -> {model}ResponseModel:",
"the request to response model return {model}ResponseModel.parse_raw(response_json) \"\"\" TEST_SUITE = \"\"\" import os",
"model for {name} endpoint \\\"\\\"\\\" stat: ResponseStatus \\\"\\\"\\\"The {name} success or failure status\\\"\\\"\\\"",
"The request and response models for {module} module \\\"\\\"\\\" # import your models",
"from py_client.models import LoginResponseModel from py_client.modules.{module}.models import * from py_client.modules.{module} import endpoints from",
"import Optional from pydantic import BaseModel from datetime import datetime from ....common.enums import",
"for handling {module} operations \\\"\\\"\\\" pass \"\"\" ENDPOINTS = \"\"\" \\\"\\\"\\\" API endpoint",
"self.subTest('response should be parsed properly'): assert response is not None assert response.stat is",
"from py_client.modules.{module}.models import * from py_client.modules.{module} import endpoints from .common import create_login_model from"
] |
[
"raise Exception(raw) return out.get('local') def start(self): self['container'].run(self['cmd']) class MasterModel(BaseModel): def salt_key_raw(self, *args): command",
"salt_key(self, *args): return json.loads(self.salt_key_raw(*args)) def salt_key_accept(self, minion_id): return self.salt_key_raw('-a', minion_id, '-y') def salt(self,",
"self['config']['client'].exec_inspect(cmd_exec_id).get('Pid', None) container_pid = self._get_container_pid(pid) self.run('kill -9 {0}'.format(container_pid)) @retry() def run(self, command, stream=False):",
"-l quiet\".format( minion_id, salt_command, ' '.join(args)) data = self['container'].run(command) return load_json(data) def salt_run(self,",
"'roster' content = {} for item in self['container']['config']['salt_config']['roster']: content[item['config']['name']] = { \"host\": item[\"ip\"],",
"container_pid = None if pid: with open('/proc/{0}/status'.format(pid), 'rb') as _file: contents = _file.read()",
"content.split('\\n'): match = re.match('([a-zA-Z]+)\\s*=\\s*(\\d+)', line) if match: info.update([[match.group(1), int(match.group(2))]]) return info def get_os_release(self):",
"= \"salt-run {0} {1} --output=json -l quiet\".format( command, ' '.join(args)) data = self['container'].run(docker_command)",
"['salt-key'] command.extend(args) command.append('--output=json') return self['container'].run(' '.join(command)) def salt_key(self, *args): return json.loads(self.salt_key_raw(*args)) def salt_key_accept(self,",
"self['container']['config']['salt_config']['root'] / 'roster' content = {} for item in self['container']['config']['salt_config']['roster']: content[item['config']['name']] = {",
"filter( lambda it: len(it) == 2, [it.replace('\"', '').strip().split('=') for it in content.split('\\n')] )",
"stream=False): cmd_exec = self['config']['client'].exec_create(self['config']['name'], cmd=command, stderr=False) return cmd_exec['Id'], self['config']['client'].exec_start(cmd_exec['Id'], stream=stream) def get_suse_release(self): info",
"pid from {0}\".format(pid)) return container_pid def kill(self, cmd_exec_id): pid = self['config']['client'].exec_inspect(cmd_exec_id).get('Pid', None) container_pid",
"salt_command, ' '.join(args) ) raw = self['container'].run(command) try: out = json.loads(raw or '{}')",
"def salt_call(self, salt_command, *args): command = \"salt-call {0} {1} --output=json -l quiet\".format( salt_command,",
"*args): docker_command = \"salt-run {0} {1} --output=json -l quiet\".format( command, ' '.join(args)) data",
"item in self['container']['config']['salt_config']['roster']: content[item['config']['name']] = { \"host\": item[\"ip\"], \"user\": item['ssh_config']['user'], \"password\": item['ssh_config']['password'] }",
"== 2, [it.replace('\"', '').strip().split('=') for it in content.split('\\n')] ) ) def connect(self): for",
"return container_pid def kill(self, cmd_exec_id): pid = self['config']['client'].exec_inspect(cmd_exec_id).get('Pid', None) container_pid = self._get_container_pid(pid) self.run('kill",
"obtain container pid from {0}\".format(pid)) return container_pid def kill(self, cmd_exec_id): pid = self['config']['client'].exec_inspect(cmd_exec_id).get('Pid',",
"for item in self['config']['networking_config']['EndpointsConfig'].keys(): self['config']['client'].connect_container_to_network(self['config']['name'], item) def disconnect(self): for item in self['config']['networking_config']['EndpointsConfig'].keys(): self['config']['client'].disconnect_container_from_network(self['config']['name'],",
"--passwd {0} {1} {{0}}\".format( target['ssh_config']['password'], target_id) data = self['container'].run(SSH.format(cmd)) return load_json(data)[target_id] def update_roster(self):",
"--output=json -l quiet\".format( command, ' '.join(args)) data = self['container'].run(docker_command) return load_json(data) def salt_ssh(self,",
"MasterModel(BaseModel): def salt_key_raw(self, *args): command = ['salt-key'] command.extend(args) command.append('--output=json') return self['container'].run(' '.join(command)) def",
"self['config']['client'].exec_create(self['config']['name'], cmd=command, stderr=False) return cmd_exec['Id'], self['config']['client'].exec_start(cmd_exec['Id'], stream=stream) def get_suse_release(self): info = dict() content",
"{0}'.format(container_pid)) @retry() def run(self, command, stream=False): return self['config']['client'].run( self['config']['name'], command, stream=stream) @retry() def",
"self['config']['networking_config']['EndpointsConfig'].keys(): self['config']['client'].disconnect_container_from_network(self['config']['name'], item) def remove(self): self['config']['client'].stop(self['config']['name']) self['config']['client'].remove_container( self['config']['name'], v=True) class BaseModel(dict): def salt_call(self,",
"len(it) == 2, [it.replace('\"', '').strip().split('=') for it in content.split('\\n')] ) ) def connect(self):",
"self.salt_key_raw('-a', minion_id, '-y') def salt(self, minion_id, salt_command, *args): command = \"salt {0} {1}",
"@retry() def check_run(self, command, stream=False): cmd_exec = self['config']['client'].exec_create(self['config']['name'], cmd=command, stderr=False) return cmd_exec['Id'], self['config']['client'].exec_start(cmd_exec['Id'],",
"class MasterModel(BaseModel): def salt_key_raw(self, *args): command = ['salt-key'] command.extend(args) command.append('--output=json') return self['container'].run(' '.join(command))",
"= self.run('cat /etc/os-release') return dict( filter( lambda it: len(it) == 2, [it.replace('\"', '').strip().split('=')",
"stream=stream) def get_suse_release(self): info = dict() content = self.run('cat /etc/SuSE-release') for line in",
"{{0}}\".format( target['ssh_config']['password'], target_id) data = self['container'].run(SSH.format(cmd)) return load_json(data)[target_id] def update_roster(self): roster = self['container']['config']['salt_config']['root']",
"= self['container'].run(SSH.format(cmd)) return load_json(data)[target_id] def update_roster(self): roster = self['container']['config']['salt_config']['root'] / 'roster' content =",
"lambda it: len(it) == 2, [it.replace('\"', '').strip().split('=') for it in content.split('\\n')] ) )",
"content = {} for item in self['container']['config']['salt_config']['roster']: content[item['config']['name']] = { \"host\": item[\"ip\"], \"user\":",
"container_pid = self._get_container_pid(pid) self.run('kill -9 {0}'.format(container_pid)) @retry() def run(self, command, stream=False): return self['config']['client'].run(",
"item in self['config']['networking_config']['EndpointsConfig'].keys(): self['config']['client'].disconnect_container_from_network(self['config']['name'], item) def remove(self): self['config']['client'].stop(self['config']['name']) self['config']['client'].remove_container( self['config']['name'], v=True) class BaseModel(dict):",
"import logging import six import subprocess from .utils import retry, load_json logger =",
"raw = self['container'].run(command) try: out = json.loads(raw or '{}') except ValueError: raise Exception(raw)",
"re.match('([a-zA-Z]+)\\s*=\\s*(\\d+)', line) if match: info.update([[match.group(1), int(match.group(2))]]) return info def get_os_release(self): content = self.run('cat",
"salt_command, *args): command = \"salt-call {0} {1} --output=json -l quiet\".format( salt_command, ' '.join(args)",
"_file.read() try: container_pid = re.search(\"NSpid.+{0}.+\".format(pid), contents).group().split('\\t')[-1] except: logger.warning(\"Unable to obtain container pid from",
"quiet\".format( command, ' '.join(args)) data = self['container'].run(docker_command) return load_json(data) def salt_ssh(self, target, cmd):",
"self['container'].run(command) try: out = json.loads(raw or '{}') except ValueError: raise Exception(raw) return out.get('local')",
"= ['salt-key'] command.extend(args) command.append('--output=json') return self['container'].run(' '.join(command)) def salt_key(self, *args): return json.loads(self.salt_key_raw(*args)) def",
"if pid: with open('/proc/{0}/status'.format(pid), 'rb') as _file: contents = _file.read() try: container_pid =",
"roster = self['container']['config']['salt_config']['root'] / 'roster' content = {} for item in self['container']['config']['salt_config']['roster']: content[item['config']['name']]",
"logging.getLogger(__name__) logger.setLevel(logging.INFO) class ContainerModel(dict): def _get_container_pid(self, pid): container_pid = None if pid: with",
"run(self, command, stream=False): return self['config']['client'].run( self['config']['name'], command, stream=stream) @retry() def check_run(self, command, stream=False):",
"return self['config']['client'].run( self['config']['name'], command, stream=stream) @retry() def check_run(self, command, stream=False): cmd_exec = self['config']['client'].exec_create(self['config']['name'],",
"remove(self): self['config']['client'].stop(self['config']['name']) self['config']['client'].remove_container( self['config']['name'], v=True) class BaseModel(dict): def salt_call(self, salt_command, *args): command =",
"= self['container']['config']['salt_config']['roster'] target_id = target['config']['name'] SSH = \"salt-ssh -l quiet -i --out json",
"self.run('cat /etc/SuSE-release') for line in content.split('\\n'): match = re.match('([a-zA-Z]+)\\s*=\\s*(\\d+)', line) if match: info.update([[match.group(1),",
"item) def remove(self): self['config']['client'].stop(self['config']['name']) self['config']['client'].remove_container( self['config']['name'], v=True) class BaseModel(dict): def salt_call(self, salt_command, *args):",
"return self['container'].run(' '.join(command)) def salt_key(self, *args): return json.loads(self.salt_key_raw(*args)) def salt_key_accept(self, minion_id): return self.salt_key_raw('-a',",
") ) def connect(self): for item in self['config']['networking_config']['EndpointsConfig'].keys(): self['config']['client'].connect_container_to_network(self['config']['name'], item) def disconnect(self): for",
"= re.search(\"NSpid.+{0}.+\".format(pid), contents).group().split('\\t')[-1] except: logger.warning(\"Unable to obtain container pid from {0}\".format(pid)) return container_pid",
"minion_id, salt_command, *args): command = \"salt {0} {1} --output=json -l quiet\".format( minion_id, salt_command,",
"self.run('kill -9 {0}'.format(container_pid)) @retry() def run(self, command, stream=False): return self['config']['client'].run( self['config']['name'], command, stream=stream)",
"self.run('cat /etc/os-release') return dict( filter( lambda it: len(it) == 2, [it.replace('\"', '').strip().split('=') for",
"target_id) data = self['container'].run(SSH.format(cmd)) return load_json(data)[target_id] def update_roster(self): roster = self['container']['config']['salt_config']['root'] / 'roster'",
"open('/proc/{0}/status'.format(pid), 'rb') as _file: contents = _file.read() try: container_pid = re.search(\"NSpid.+{0}.+\".format(pid), contents).group().split('\\t')[-1] except:",
"import tarfile import logging import six import subprocess from .utils import retry, load_json",
"disconnect(self): for item in self['config']['networking_config']['EndpointsConfig'].keys(): self['config']['client'].disconnect_container_from_network(self['config']['name'], item) def remove(self): self['config']['client'].stop(self['config']['name']) self['config']['client'].remove_container( self['config']['name'], v=True)",
"yaml import tarfile import logging import six import subprocess from .utils import retry,",
"try: out = json.loads(raw or '{}') except ValueError: raise Exception(raw) return out.get('local') def",
"/etc/os-release') return dict( filter( lambda it: len(it) == 2, [it.replace('\"', '').strip().split('=') for it",
"load_json(data)[target_id] def update_roster(self): roster = self['container']['config']['salt_config']['root'] / 'roster' content = {} for item",
"if match: info.update([[match.group(1), int(match.group(2))]]) return info def get_os_release(self): content = self.run('cat /etc/os-release') return",
"= {} for item in self['container']['config']['salt_config']['roster']: content[item['config']['name']] = { \"host\": item[\"ip\"], \"user\": item['ssh_config']['user'],",
"info.update([[match.group(1), int(match.group(2))]]) return info def get_os_release(self): content = self.run('cat /etc/os-release') return dict( filter(",
"load_json logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) class ContainerModel(dict): def _get_container_pid(self, pid): container_pid = None",
"target, cmd): roster = self['container']['config']['salt_config']['roster'] target_id = target['config']['name'] SSH = \"salt-ssh -l quiet",
"self['container'].run(SSH.format(cmd)) return load_json(data)[target_id] def update_roster(self): roster = self['container']['config']['salt_config']['root'] / 'roster' content = {}",
"quiet -i --out json --key-deploy --passwd {0} {1} {{0}}\".format( target['ssh_config']['password'], target_id) data =",
"= json.loads(raw or '{}') except ValueError: raise Exception(raw) return out.get('local') def start(self): self['container'].run(self['cmd'])",
"\"salt-call {0} {1} --output=json -l quiet\".format( salt_command, ' '.join(args) ) raw = self['container'].run(command)",
"= dict() content = self.run('cat /etc/SuSE-release') for line in content.split('\\n'): match = re.match('([a-zA-Z]+)\\s*=\\s*(\\d+)',",
"match = re.match('([a-zA-Z]+)\\s*=\\s*(\\d+)', line) if match: info.update([[match.group(1), int(match.group(2))]]) return info def get_os_release(self): content",
"for line in content.split('\\n'): match = re.match('([a-zA-Z]+)\\s*=\\s*(\\d+)', line) if match: info.update([[match.group(1), int(match.group(2))]]) return",
"self['config']['networking_config']['EndpointsConfig'].keys(): self['config']['client'].connect_container_to_network(self['config']['name'], item) def disconnect(self): for item in self['config']['networking_config']['EndpointsConfig'].keys(): self['config']['client'].disconnect_container_from_network(self['config']['name'], item) def remove(self):",
"-i --out json --key-deploy --passwd {0} {1} {{0}}\".format( target['ssh_config']['password'], target_id) data = self['container'].run(SSH.format(cmd))",
"try: container_pid = re.search(\"NSpid.+{0}.+\".format(pid), contents).group().split('\\t')[-1] except: logger.warning(\"Unable to obtain container pid from {0}\".format(pid))",
"command, stream=False): return self['config']['client'].run( self['config']['name'], command, stream=stream) @retry() def check_run(self, command, stream=False): cmd_exec",
"contents).group().split('\\t')[-1] except: logger.warning(\"Unable to obtain container pid from {0}\".format(pid)) return container_pid def kill(self,",
"' '.join(args)) data = self['container'].run(command) return load_json(data) def salt_run(self, command, *args): docker_command =",
"'{}') except ValueError: raise Exception(raw) return out.get('local') def start(self): self['container'].run(self['cmd']) class MasterModel(BaseModel): def",
"target['ssh_config']['password'], target_id) data = self['container'].run(SSH.format(cmd)) return load_json(data)[target_id] def update_roster(self): roster = self['container']['config']['salt_config']['root'] /",
"= \"salt {0} {1} --output=json -l quiet\".format( minion_id, salt_command, ' '.join(args)) data =",
"json import yaml import tarfile import logging import six import subprocess from .utils",
"six import subprocess from .utils import retry, load_json logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) class",
"--output=json -l quiet\".format( salt_command, ' '.join(args) ) raw = self['container'].run(command) try: out =",
"logger.setLevel(logging.INFO) class ContainerModel(dict): def _get_container_pid(self, pid): container_pid = None if pid: with open('/proc/{0}/status'.format(pid),",
"'.join(command)) def salt_key(self, *args): return json.loads(self.salt_key_raw(*args)) def salt_key_accept(self, minion_id): return self.salt_key_raw('-a', minion_id, '-y')",
"minion_id, salt_command, ' '.join(args)) data = self['container'].run(command) return load_json(data) def salt_run(self, command, *args):",
"'-y') def salt(self, minion_id, salt_command, *args): command = \"salt {0} {1} --output=json -l",
"-9 {0}'.format(container_pid)) @retry() def run(self, command, stream=False): return self['config']['client'].run( self['config']['name'], command, stream=stream) @retry()",
"logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) class ContainerModel(dict): def _get_container_pid(self, pid): container_pid = None if",
"target_id = target['config']['name'] SSH = \"salt-ssh -l quiet -i --out json --key-deploy --passwd",
"None if pid: with open('/proc/{0}/status'.format(pid), 'rb') as _file: contents = _file.read() try: container_pid",
"container_pid def kill(self, cmd_exec_id): pid = self['config']['client'].exec_inspect(cmd_exec_id).get('Pid', None) container_pid = self._get_container_pid(pid) self.run('kill -9",
"\"user\": item['ssh_config']['user'], \"password\": item['ssh_config']['password'] } roster.write(yaml.safe_dump(content, default_flow_style=False)) self['container']['config']['client'].copy_to(self, roster.strpath, '/etc/salt/') class MinionModel(BaseModel): def",
"--out json --key-deploy --passwd {0} {1} {{0}}\".format( target['ssh_config']['password'], target_id) data = self['container'].run(SSH.format(cmd)) return",
"*args): command = ['salt-key'] command.extend(args) command.append('--output=json') return self['container'].run(' '.join(command)) def salt_key(self, *args): return",
"def connect(self): for item in self['config']['networking_config']['EndpointsConfig'].keys(): self['config']['client'].connect_container_to_network(self['config']['name'], item) def disconnect(self): for item in",
"command = \"salt {0} {1} --output=json -l quiet\".format( minion_id, salt_command, ' '.join(args)) data",
"self['container'].run(' '.join(command)) def salt_key(self, *args): return json.loads(self.salt_key_raw(*args)) def salt_key_accept(self, minion_id): return self.salt_key_raw('-a', minion_id,",
"as _file: contents = _file.read() try: container_pid = re.search(\"NSpid.+{0}.+\".format(pid), contents).group().split('\\t')[-1] except: logger.warning(\"Unable to",
"' '.join(args)) data = self['container'].run(docker_command) return load_json(data) def salt_ssh(self, target, cmd): roster =",
"stderr=False) return cmd_exec['Id'], self['config']['client'].exec_start(cmd_exec['Id'], stream=stream) def get_suse_release(self): info = dict() content = self.run('cat",
"*args): return json.loads(self.salt_key_raw(*args)) def salt_key_accept(self, minion_id): return self.salt_key_raw('-a', minion_id, '-y') def salt(self, minion_id,",
"logger.warning(\"Unable to obtain container pid from {0}\".format(pid)) return container_pid def kill(self, cmd_exec_id): pid",
"{0} {1} --output=json -l quiet\".format( salt_command, ' '.join(args) ) raw = self['container'].run(command) try:",
") raw = self['container'].run(command) try: out = json.loads(raw or '{}') except ValueError: raise",
"return dict( filter( lambda it: len(it) == 2, [it.replace('\"', '').strip().split('=') for it in",
"quiet\".format( minion_id, salt_command, ' '.join(args)) data = self['container'].run(command) return load_json(data) def salt_run(self, command,",
"subprocess from .utils import retry, load_json logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) class ContainerModel(dict): def",
"out.get('local') def start(self): self['container'].run(self['cmd']) class MasterModel(BaseModel): def salt_key_raw(self, *args): command = ['salt-key'] command.extend(args)",
"content[item['config']['name']] = { \"host\": item[\"ip\"], \"user\": item['ssh_config']['user'], \"password\": item['ssh_config']['password'] } roster.write(yaml.safe_dump(content, default_flow_style=False)) self['container']['config']['client'].copy_to(self,",
"get_suse_release(self): info = dict() content = self.run('cat /etc/SuSE-release') for line in content.split('\\n'): match",
"docker_command = \"salt-run {0} {1} --output=json -l quiet\".format( command, ' '.join(args)) data =",
"{0} {1} {{0}}\".format( target['ssh_config']['password'], target_id) data = self['container'].run(SSH.format(cmd)) return load_json(data)[target_id] def update_roster(self): roster",
"salt(self, minion_id, salt_command, *args): command = \"salt {0} {1} --output=json -l quiet\".format( minion_id,",
"it: len(it) == 2, [it.replace('\"', '').strip().split('=') for it in content.split('\\n')] ) ) def",
"{0} {1} --output=json -l quiet\".format( minion_id, salt_command, ' '.join(args)) data = self['container'].run(command) return",
"self['config']['client'].stop(self['config']['name']) self['config']['client'].remove_container( self['config']['name'], v=True) class BaseModel(dict): def salt_call(self, salt_command, *args): command = \"salt-call",
"line in content.split('\\n'): match = re.match('([a-zA-Z]+)\\s*=\\s*(\\d+)', line) if match: info.update([[match.group(1), int(match.group(2))]]) return info",
"salt_command, *args): command = \"salt {0} {1} --output=json -l quiet\".format( minion_id, salt_command, '",
"*args): command = \"salt {0} {1} --output=json -l quiet\".format( minion_id, salt_command, ' '.join(args))",
"cmd_exec = self['config']['client'].exec_create(self['config']['name'], cmd=command, stderr=False) return cmd_exec['Id'], self['config']['client'].exec_start(cmd_exec['Id'], stream=stream) def get_suse_release(self): info =",
"= self.run('cat /etc/SuSE-release') for line in content.split('\\n'): match = re.match('([a-zA-Z]+)\\s*=\\s*(\\d+)', line) if match:",
"= self['config']['client'].exec_inspect(cmd_exec_id).get('Pid', None) container_pid = self._get_container_pid(pid) self.run('kill -9 {0}'.format(container_pid)) @retry() def run(self, command,",
"item) def disconnect(self): for item in self['config']['networking_config']['EndpointsConfig'].keys(): self['config']['client'].disconnect_container_from_network(self['config']['name'], item) def remove(self): self['config']['client'].stop(self['config']['name']) self['config']['client'].remove_container(",
"'.join(args)) data = self['container'].run(docker_command) return load_json(data) def salt_ssh(self, target, cmd): roster = self['container']['config']['salt_config']['roster']",
"self['container'].run(docker_command) return load_json(data) def salt_ssh(self, target, cmd): roster = self['container']['config']['salt_config']['roster'] target_id = target['config']['name']",
"salt_command, ' '.join(args)) data = self['container'].run(command) return load_json(data) def salt_run(self, command, *args): docker_command",
"def get_os_release(self): content = self.run('cat /etc/os-release') return dict( filter( lambda it: len(it) ==",
"-l quiet -i --out json --key-deploy --passwd {0} {1} {{0}}\".format( target['ssh_config']['password'], target_id) data",
"self['container']['config']['salt_config']['roster'] target_id = target['config']['name'] SSH = \"salt-ssh -l quiet -i --out json --key-deploy",
"SSH = \"salt-ssh -l quiet -i --out json --key-deploy --passwd {0} {1} {{0}}\".format(",
"data = self['container'].run(docker_command) return load_json(data) def salt_ssh(self, target, cmd): roster = self['container']['config']['salt_config']['roster'] target_id",
"-l quiet\".format( command, ' '.join(args)) data = self['container'].run(docker_command) return load_json(data) def salt_ssh(self, target,",
"<filename>saltcontainers/models.py import re import json import yaml import tarfile import logging import six",
"self._get_container_pid(pid) self.run('kill -9 {0}'.format(container_pid)) @retry() def run(self, command, stream=False): return self['config']['client'].run( self['config']['name'], command,",
"'.join(args)) data = self['container'].run(command) return load_json(data) def salt_run(self, command, *args): docker_command = \"salt-run",
"ValueError: raise Exception(raw) return out.get('local') def start(self): self['container'].run(self['cmd']) class MasterModel(BaseModel): def salt_key_raw(self, *args):",
"import json import yaml import tarfile import logging import six import subprocess from",
"import six import subprocess from .utils import retry, load_json logger = logging.getLogger(__name__) logger.setLevel(logging.INFO)",
"= self['config']['client'].exec_create(self['config']['name'], cmd=command, stderr=False) return cmd_exec['Id'], self['config']['client'].exec_start(cmd_exec['Id'], stream=stream) def get_suse_release(self): info = dict()",
"def update_roster(self): roster = self['container']['config']['salt_config']['root'] / 'roster' content = {} for item in",
"match: info.update([[match.group(1), int(match.group(2))]]) return info def get_os_release(self): content = self.run('cat /etc/os-release') return dict(",
"def salt_key_raw(self, *args): command = ['salt-key'] command.extend(args) command.append('--output=json') return self['container'].run(' '.join(command)) def salt_key(self,",
"tarfile import logging import six import subprocess from .utils import retry, load_json logger",
"--key-deploy --passwd {0} {1} {{0}}\".format( target['ssh_config']['password'], target_id) data = self['container'].run(SSH.format(cmd)) return load_json(data)[target_id] def",
"def start(self): self['container'].run(self['cmd']) class MasterModel(BaseModel): def salt_key_raw(self, *args): command = ['salt-key'] command.extend(args) command.append('--output=json')",
"import re import json import yaml import tarfile import logging import six import",
"\"password\": item['ssh_config']['password'] } roster.write(yaml.safe_dump(content, default_flow_style=False)) self['container']['config']['client'].copy_to(self, roster.strpath, '/etc/salt/') class MinionModel(BaseModel): def stop(self): self['container'].run('pkill",
"= self['container']['config']['salt_config']['root'] / 'roster' content = {} for item in self['container']['config']['salt_config']['roster']: content[item['config']['name']] =",
"line) if match: info.update([[match.group(1), int(match.group(2))]]) return info def get_os_release(self): content = self.run('cat /etc/os-release')",
"for it in content.split('\\n')] ) ) def connect(self): for item in self['config']['networking_config']['EndpointsConfig'].keys(): self['config']['client'].connect_container_to_network(self['config']['name'],",
"stream=False): return self['config']['client'].run( self['config']['name'], command, stream=stream) @retry() def check_run(self, command, stream=False): cmd_exec =",
"def salt_key(self, *args): return json.loads(self.salt_key_raw(*args)) def salt_key_accept(self, minion_id): return self.salt_key_raw('-a', minion_id, '-y') def",
"def salt_run(self, command, *args): docker_command = \"salt-run {0} {1} --output=json -l quiet\".format( command,",
"/ 'roster' content = {} for item in self['container']['config']['salt_config']['roster']: content[item['config']['name']] = { \"host\":",
"\"salt-run {0} {1} --output=json -l quiet\".format( command, ' '.join(args)) data = self['container'].run(docker_command) return",
"_get_container_pid(self, pid): container_pid = None if pid: with open('/proc/{0}/status'.format(pid), 'rb') as _file: contents",
"v=True) class BaseModel(dict): def salt_call(self, salt_command, *args): command = \"salt-call {0} {1} --output=json",
"item in self['config']['networking_config']['EndpointsConfig'].keys(): self['config']['client'].connect_container_to_network(self['config']['name'], item) def disconnect(self): for item in self['config']['networking_config']['EndpointsConfig'].keys(): self['config']['client'].disconnect_container_from_network(self['config']['name'], item)",
"{} for item in self['container']['config']['salt_config']['roster']: content[item['config']['name']] = { \"host\": item[\"ip\"], \"user\": item['ssh_config']['user'], \"password\":",
"\"salt {0} {1} --output=json -l quiet\".format( minion_id, salt_command, ' '.join(args)) data = self['container'].run(command)",
"data = self['container'].run(command) return load_json(data) def salt_run(self, command, *args): docker_command = \"salt-run {0}",
"self['container'].run(self['cmd']) class MasterModel(BaseModel): def salt_key_raw(self, *args): command = ['salt-key'] command.extend(args) command.append('--output=json') return self['container'].run('",
"json.loads(raw or '{}') except ValueError: raise Exception(raw) return out.get('local') def start(self): self['container'].run(self['cmd']) class",
"content = self.run('cat /etc/os-release') return dict( filter( lambda it: len(it) == 2, [it.replace('\"',",
"def disconnect(self): for item in self['config']['networking_config']['EndpointsConfig'].keys(): self['config']['client'].disconnect_container_from_network(self['config']['name'], item) def remove(self): self['config']['client'].stop(self['config']['name']) self['config']['client'].remove_container( self['config']['name'],",
"None) container_pid = self._get_container_pid(pid) self.run('kill -9 {0}'.format(container_pid)) @retry() def run(self, command, stream=False): return",
"update_roster(self): roster = self['container']['config']['salt_config']['root'] / 'roster' content = {} for item in self['container']['config']['salt_config']['roster']:",
"to obtain container pid from {0}\".format(pid)) return container_pid def kill(self, cmd_exec_id): pid =",
"dict() content = self.run('cat /etc/SuSE-release') for line in content.split('\\n'): match = re.match('([a-zA-Z]+)\\s*=\\s*(\\d+)', line)",
"command.append('--output=json') return self['container'].run(' '.join(command)) def salt_key(self, *args): return json.loads(self.salt_key_raw(*args)) def salt_key_accept(self, minion_id): return",
"= \"salt-ssh -l quiet -i --out json --key-deploy --passwd {0} {1} {{0}}\".format( target['ssh_config']['password'],",
"command = ['salt-key'] command.extend(args) command.append('--output=json') return self['container'].run(' '.join(command)) def salt_key(self, *args): return json.loads(self.salt_key_raw(*args))",
"import subprocess from .utils import retry, load_json logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) class ContainerModel(dict):",
"BaseModel(dict): def salt_call(self, salt_command, *args): command = \"salt-call {0} {1} --output=json -l quiet\".format(",
"return cmd_exec['Id'], self['config']['client'].exec_start(cmd_exec['Id'], stream=stream) def get_suse_release(self): info = dict() content = self.run('cat /etc/SuSE-release')",
"it in content.split('\\n')] ) ) def connect(self): for item in self['config']['networking_config']['EndpointsConfig'].keys(): self['config']['client'].connect_container_to_network(self['config']['name'], item)",
"connect(self): for item in self['config']['networking_config']['EndpointsConfig'].keys(): self['config']['client'].connect_container_to_network(self['config']['name'], item) def disconnect(self): for item in self['config']['networking_config']['EndpointsConfig'].keys():",
"for item in self['config']['networking_config']['EndpointsConfig'].keys(): self['config']['client'].disconnect_container_from_network(self['config']['name'], item) def remove(self): self['config']['client'].stop(self['config']['name']) self['config']['client'].remove_container( self['config']['name'], v=True) class",
"command, stream=stream) @retry() def check_run(self, command, stream=False): cmd_exec = self['config']['client'].exec_create(self['config']['name'], cmd=command, stderr=False) return",
"class ContainerModel(dict): def _get_container_pid(self, pid): container_pid = None if pid: with open('/proc/{0}/status'.format(pid), 'rb')",
"item['ssh_config']['password'] } roster.write(yaml.safe_dump(content, default_flow_style=False)) self['container']['config']['client'].copy_to(self, roster.strpath, '/etc/salt/') class MinionModel(BaseModel): def stop(self): self['container'].run('pkill salt-minion')",
"start(self): self['container'].run(self['cmd']) class MasterModel(BaseModel): def salt_key_raw(self, *args): command = ['salt-key'] command.extend(args) command.append('--output=json') return",
"data = self['container'].run(SSH.format(cmd)) return load_json(data)[target_id] def update_roster(self): roster = self['container']['config']['salt_config']['root'] / 'roster' content",
"return load_json(data)[target_id] def update_roster(self): roster = self['container']['config']['salt_config']['root'] / 'roster' content = {} for",
"logging import six import subprocess from .utils import retry, load_json logger = logging.getLogger(__name__)",
"{1} --output=json -l quiet\".format( salt_command, ' '.join(args) ) raw = self['container'].run(command) try: out",
"return json.loads(self.salt_key_raw(*args)) def salt_key_accept(self, minion_id): return self.salt_key_raw('-a', minion_id, '-y') def salt(self, minion_id, salt_command,",
"get_os_release(self): content = self.run('cat /etc/os-release') return dict( filter( lambda it: len(it) == 2,",
"in self['config']['networking_config']['EndpointsConfig'].keys(): self['config']['client'].disconnect_container_from_network(self['config']['name'], item) def remove(self): self['config']['client'].stop(self['config']['name']) self['config']['client'].remove_container( self['config']['name'], v=True) class BaseModel(dict): def",
"self['config']['name'], command, stream=stream) @retry() def check_run(self, command, stream=False): cmd_exec = self['config']['client'].exec_create(self['config']['name'], cmd=command, stderr=False)",
"{0} {1} --output=json -l quiet\".format( command, ' '.join(args)) data = self['container'].run(docker_command) return load_json(data)",
"retry, load_json logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) class ContainerModel(dict): def _get_container_pid(self, pid): container_pid =",
"= target['config']['name'] SSH = \"salt-ssh -l quiet -i --out json --key-deploy --passwd {0}",
") def connect(self): for item in self['config']['networking_config']['EndpointsConfig'].keys(): self['config']['client'].connect_container_to_network(self['config']['name'], item) def disconnect(self): for item",
"= self['container'].run(docker_command) return load_json(data) def salt_ssh(self, target, cmd): roster = self['container']['config']['salt_config']['roster'] target_id =",
"in self['container']['config']['salt_config']['roster']: content[item['config']['name']] = { \"host\": item[\"ip\"], \"user\": item['ssh_config']['user'], \"password\": item['ssh_config']['password'] } roster.write(yaml.safe_dump(content,",
"json.loads(self.salt_key_raw(*args)) def salt_key_accept(self, minion_id): return self.salt_key_raw('-a', minion_id, '-y') def salt(self, minion_id, salt_command, *args):",
"class BaseModel(dict): def salt_call(self, salt_command, *args): command = \"salt-call {0} {1} --output=json -l",
"def _get_container_pid(self, pid): container_pid = None if pid: with open('/proc/{0}/status'.format(pid), 'rb') as _file:",
"command, *args): docker_command = \"salt-run {0} {1} --output=json -l quiet\".format( command, ' '.join(args))",
"minion_id): return self.salt_key_raw('-a', minion_id, '-y') def salt(self, minion_id, salt_command, *args): command = \"salt",
"= logging.getLogger(__name__) logger.setLevel(logging.INFO) class ContainerModel(dict): def _get_container_pid(self, pid): container_pid = None if pid:",
"content.split('\\n')] ) ) def connect(self): for item in self['config']['networking_config']['EndpointsConfig'].keys(): self['config']['client'].connect_container_to_network(self['config']['name'], item) def disconnect(self):",
"load_json(data) def salt_run(self, command, *args): docker_command = \"salt-run {0} {1} --output=json -l quiet\".format(",
"self['container']['config']['salt_config']['roster']: content[item['config']['name']] = { \"host\": item[\"ip\"], \"user\": item['ssh_config']['user'], \"password\": item['ssh_config']['password'] } roster.write(yaml.safe_dump(content, default_flow_style=False))",
"for item in self['container']['config']['salt_config']['roster']: content[item['config']['name']] = { \"host\": item[\"ip\"], \"user\": item['ssh_config']['user'], \"password\": item['ssh_config']['password']",
"[it.replace('\"', '').strip().split('=') for it in content.split('\\n')] ) ) def connect(self): for item in",
"def check_run(self, command, stream=False): cmd_exec = self['config']['client'].exec_create(self['config']['name'], cmd=command, stderr=False) return cmd_exec['Id'], self['config']['client'].exec_start(cmd_exec['Id'], stream=stream)",
"salt_call(self, salt_command, *args): command = \"salt-call {0} {1} --output=json -l quiet\".format( salt_command, '",
"= self['container'].run(command) return load_json(data) def salt_run(self, command, *args): docker_command = \"salt-run {0} {1}",
"return load_json(data) def salt_run(self, command, *args): docker_command = \"salt-run {0} {1} --output=json -l",
"from {0}\".format(pid)) return container_pid def kill(self, cmd_exec_id): pid = self['config']['client'].exec_inspect(cmd_exec_id).get('Pid', None) container_pid =",
"def salt_ssh(self, target, cmd): roster = self['container']['config']['salt_config']['roster'] target_id = target['config']['name'] SSH = \"salt-ssh",
"@retry() def run(self, command, stream=False): return self['config']['client'].run( self['config']['name'], command, stream=stream) @retry() def check_run(self,",
"{ \"host\": item[\"ip\"], \"user\": item['ssh_config']['user'], \"password\": item['ssh_config']['password'] } roster.write(yaml.safe_dump(content, default_flow_style=False)) self['container']['config']['client'].copy_to(self, roster.strpath, '/etc/salt/')",
".utils import retry, load_json logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) class ContainerModel(dict): def _get_container_pid(self, pid):",
"minion_id, '-y') def salt(self, minion_id, salt_command, *args): command = \"salt {0} {1} --output=json",
"from .utils import retry, load_json logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) class ContainerModel(dict): def _get_container_pid(self,",
"re.search(\"NSpid.+{0}.+\".format(pid), contents).group().split('\\t')[-1] except: logger.warning(\"Unable to obtain container pid from {0}\".format(pid)) return container_pid def",
"except ValueError: raise Exception(raw) return out.get('local') def start(self): self['container'].run(self['cmd']) class MasterModel(BaseModel): def salt_key_raw(self,",
"out = json.loads(raw or '{}') except ValueError: raise Exception(raw) return out.get('local') def start(self):",
"content = self.run('cat /etc/SuSE-release') for line in content.split('\\n'): match = re.match('([a-zA-Z]+)\\s*=\\s*(\\d+)', line) if",
"item[\"ip\"], \"user\": item['ssh_config']['user'], \"password\": item['ssh_config']['password'] } roster.write(yaml.safe_dump(content, default_flow_style=False)) self['container']['config']['client'].copy_to(self, roster.strpath, '/etc/salt/') class MinionModel(BaseModel):",
"salt_run(self, command, *args): docker_command = \"salt-run {0} {1} --output=json -l quiet\".format( command, '",
"cmd): roster = self['container']['config']['salt_config']['roster'] target_id = target['config']['name'] SSH = \"salt-ssh -l quiet -i",
"'rb') as _file: contents = _file.read() try: container_pid = re.search(\"NSpid.+{0}.+\".format(pid), contents).group().split('\\t')[-1] except: logger.warning(\"Unable",
"= self._get_container_pid(pid) self.run('kill -9 {0}'.format(container_pid)) @retry() def run(self, command, stream=False): return self['config']['client'].run( self['config']['name'],",
"self['config']['client'].exec_start(cmd_exec['Id'], stream=stream) def get_suse_release(self): info = dict() content = self.run('cat /etc/SuSE-release') for line",
"return load_json(data) def salt_ssh(self, target, cmd): roster = self['container']['config']['salt_config']['roster'] target_id = target['config']['name'] SSH",
"{1} --output=json -l quiet\".format( minion_id, salt_command, ' '.join(args)) data = self['container'].run(command) return load_json(data)",
"{1} --output=json -l quiet\".format( command, ' '.join(args)) data = self['container'].run(docker_command) return load_json(data) def",
"salt_key_accept(self, minion_id): return self.salt_key_raw('-a', minion_id, '-y') def salt(self, minion_id, salt_command, *args): command =",
"'').strip().split('=') for it in content.split('\\n')] ) ) def connect(self): for item in self['config']['networking_config']['EndpointsConfig'].keys():",
"= self['container'].run(command) try: out = json.loads(raw or '{}') except ValueError: raise Exception(raw) return",
"cmd_exec_id): pid = self['config']['client'].exec_inspect(cmd_exec_id).get('Pid', None) container_pid = self._get_container_pid(pid) self.run('kill -9 {0}'.format(container_pid)) @retry() def",
"return info def get_os_release(self): content = self.run('cat /etc/os-release') return dict( filter( lambda it:",
"' '.join(args) ) raw = self['container'].run(command) try: out = json.loads(raw or '{}') except",
"command, ' '.join(args)) data = self['container'].run(docker_command) return load_json(data) def salt_ssh(self, target, cmd): roster",
"target['config']['name'] SSH = \"salt-ssh -l quiet -i --out json --key-deploy --passwd {0} {1}",
"{0}\".format(pid)) return container_pid def kill(self, cmd_exec_id): pid = self['config']['client'].exec_inspect(cmd_exec_id).get('Pid', None) container_pid = self._get_container_pid(pid)",
"--output=json -l quiet\".format( minion_id, salt_command, ' '.join(args)) data = self['container'].run(command) return load_json(data) def",
"container_pid = re.search(\"NSpid.+{0}.+\".format(pid), contents).group().split('\\t')[-1] except: logger.warning(\"Unable to obtain container pid from {0}\".format(pid)) return",
"kill(self, cmd_exec_id): pid = self['config']['client'].exec_inspect(cmd_exec_id).get('Pid', None) container_pid = self._get_container_pid(pid) self.run('kill -9 {0}'.format(container_pid)) @retry()",
"roster = self['container']['config']['salt_config']['roster'] target_id = target['config']['name'] SSH = \"salt-ssh -l quiet -i --out",
"self['config']['client'].remove_container( self['config']['name'], v=True) class BaseModel(dict): def salt_call(self, salt_command, *args): command = \"salt-call {0}",
"load_json(data) def salt_ssh(self, target, cmd): roster = self['container']['config']['salt_config']['roster'] target_id = target['config']['name'] SSH =",
"cmd=command, stderr=False) return cmd_exec['Id'], self['config']['client'].exec_start(cmd_exec['Id'], stream=stream) def get_suse_release(self): info = dict() content =",
"-l quiet\".format( salt_command, ' '.join(args) ) raw = self['container'].run(command) try: out = json.loads(raw",
"salt_ssh(self, target, cmd): roster = self['container']['config']['salt_config']['roster'] target_id = target['config']['name'] SSH = \"salt-ssh -l",
"= None if pid: with open('/proc/{0}/status'.format(pid), 'rb') as _file: contents = _file.read() try:",
"self['config']['name'], v=True) class BaseModel(dict): def salt_call(self, salt_command, *args): command = \"salt-call {0} {1}",
"command = \"salt-call {0} {1} --output=json -l quiet\".format( salt_command, ' '.join(args) ) raw",
"command.extend(args) command.append('--output=json') return self['container'].run(' '.join(command)) def salt_key(self, *args): return json.loads(self.salt_key_raw(*args)) def salt_key_accept(self, minion_id):",
"pid: with open('/proc/{0}/status'.format(pid), 'rb') as _file: contents = _file.read() try: container_pid = re.search(\"NSpid.+{0}.+\".format(pid),",
"def get_suse_release(self): info = dict() content = self.run('cat /etc/SuSE-release') for line in content.split('\\n'):",
"_file: contents = _file.read() try: container_pid = re.search(\"NSpid.+{0}.+\".format(pid), contents).group().split('\\t')[-1] except: logger.warning(\"Unable to obtain",
"\"host\": item[\"ip\"], \"user\": item['ssh_config']['user'], \"password\": item['ssh_config']['password'] } roster.write(yaml.safe_dump(content, default_flow_style=False)) self['container']['config']['client'].copy_to(self, roster.strpath, '/etc/salt/') class",
"def salt_key_accept(self, minion_id): return self.salt_key_raw('-a', minion_id, '-y') def salt(self, minion_id, salt_command, *args): command",
"import retry, load_json logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) class ContainerModel(dict): def _get_container_pid(self, pid): container_pid",
"info def get_os_release(self): content = self.run('cat /etc/os-release') return dict( filter( lambda it: len(it)",
"quiet\".format( salt_command, ' '.join(args) ) raw = self['container'].run(command) try: out = json.loads(raw or",
"\"salt-ssh -l quiet -i --out json --key-deploy --passwd {0} {1} {{0}}\".format( target['ssh_config']['password'], target_id)",
"Exception(raw) return out.get('local') def start(self): self['container'].run(self['cmd']) class MasterModel(BaseModel): def salt_key_raw(self, *args): command =",
"def kill(self, cmd_exec_id): pid = self['config']['client'].exec_inspect(cmd_exec_id).get('Pid', None) container_pid = self._get_container_pid(pid) self.run('kill -9 {0}'.format(container_pid))",
"{1} {{0}}\".format( target['ssh_config']['password'], target_id) data = self['container'].run(SSH.format(cmd)) return load_json(data)[target_id] def update_roster(self): roster =",
"in content.split('\\n'): match = re.match('([a-zA-Z]+)\\s*=\\s*(\\d+)', line) if match: info.update([[match.group(1), int(match.group(2))]]) return info def",
"pid): container_pid = None if pid: with open('/proc/{0}/status'.format(pid), 'rb') as _file: contents =",
"in content.split('\\n')] ) ) def connect(self): for item in self['config']['networking_config']['EndpointsConfig'].keys(): self['config']['client'].connect_container_to_network(self['config']['name'], item) def",
"cmd_exec['Id'], self['config']['client'].exec_start(cmd_exec['Id'], stream=stream) def get_suse_release(self): info = dict() content = self.run('cat /etc/SuSE-release') for",
"check_run(self, command, stream=False): cmd_exec = self['config']['client'].exec_create(self['config']['name'], cmd=command, stderr=False) return cmd_exec['Id'], self['config']['client'].exec_start(cmd_exec['Id'], stream=stream) def",
"salt_key_raw(self, *args): command = ['salt-key'] command.extend(args) command.append('--output=json') return self['container'].run(' '.join(command)) def salt_key(self, *args):",
"def run(self, command, stream=False): return self['config']['client'].run( self['config']['name'], command, stream=stream) @retry() def check_run(self, command,",
"re import json import yaml import tarfile import logging import six import subprocess",
"self['container'].run(command) return load_json(data) def salt_run(self, command, *args): docker_command = \"salt-run {0} {1} --output=json",
"def remove(self): self['config']['client'].stop(self['config']['name']) self['config']['client'].remove_container( self['config']['name'], v=True) class BaseModel(dict): def salt_call(self, salt_command, *args): command",
"stream=stream) @retry() def check_run(self, command, stream=False): cmd_exec = self['config']['client'].exec_create(self['config']['name'], cmd=command, stderr=False) return cmd_exec['Id'],",
"int(match.group(2))]]) return info def get_os_release(self): content = self.run('cat /etc/os-release') return dict( filter( lambda",
"container pid from {0}\".format(pid)) return container_pid def kill(self, cmd_exec_id): pid = self['config']['client'].exec_inspect(cmd_exec_id).get('Pid', None)",
"/etc/SuSE-release') for line in content.split('\\n'): match = re.match('([a-zA-Z]+)\\s*=\\s*(\\d+)', line) if match: info.update([[match.group(1), int(match.group(2))]])",
"= \"salt-call {0} {1} --output=json -l quiet\".format( salt_command, ' '.join(args) ) raw =",
"return self.salt_key_raw('-a', minion_id, '-y') def salt(self, minion_id, salt_command, *args): command = \"salt {0}",
"ContainerModel(dict): def _get_container_pid(self, pid): container_pid = None if pid: with open('/proc/{0}/status'.format(pid), 'rb') as",
"contents = _file.read() try: container_pid = re.search(\"NSpid.+{0}.+\".format(pid), contents).group().split('\\t')[-1] except: logger.warning(\"Unable to obtain container",
"info = dict() content = self.run('cat /etc/SuSE-release') for line in content.split('\\n'): match =",
"self['config']['client'].disconnect_container_from_network(self['config']['name'], item) def remove(self): self['config']['client'].stop(self['config']['name']) self['config']['client'].remove_container( self['config']['name'], v=True) class BaseModel(dict): def salt_call(self, salt_command,",
"= _file.read() try: container_pid = re.search(\"NSpid.+{0}.+\".format(pid), contents).group().split('\\t')[-1] except: logger.warning(\"Unable to obtain container pid",
"item['ssh_config']['user'], \"password\": item['ssh_config']['password'] } roster.write(yaml.safe_dump(content, default_flow_style=False)) self['container']['config']['client'].copy_to(self, roster.strpath, '/etc/salt/') class MinionModel(BaseModel): def stop(self):",
"return out.get('local') def start(self): self['container'].run(self['cmd']) class MasterModel(BaseModel): def salt_key_raw(self, *args): command = ['salt-key']",
"json --key-deploy --passwd {0} {1} {{0}}\".format( target['ssh_config']['password'], target_id) data = self['container'].run(SSH.format(cmd)) return load_json(data)[target_id]",
"except: logger.warning(\"Unable to obtain container pid from {0}\".format(pid)) return container_pid def kill(self, cmd_exec_id):",
"or '{}') except ValueError: raise Exception(raw) return out.get('local') def start(self): self['container'].run(self['cmd']) class MasterModel(BaseModel):",
"def salt(self, minion_id, salt_command, *args): command = \"salt {0} {1} --output=json -l quiet\".format(",
"pid = self['config']['client'].exec_inspect(cmd_exec_id).get('Pid', None) container_pid = self._get_container_pid(pid) self.run('kill -9 {0}'.format(container_pid)) @retry() def run(self,",
"2, [it.replace('\"', '').strip().split('=') for it in content.split('\\n')] ) ) def connect(self): for item",
"in self['config']['networking_config']['EndpointsConfig'].keys(): self['config']['client'].connect_container_to_network(self['config']['name'], item) def disconnect(self): for item in self['config']['networking_config']['EndpointsConfig'].keys(): self['config']['client'].disconnect_container_from_network(self['config']['name'], item) def",
"self['config']['client'].connect_container_to_network(self['config']['name'], item) def disconnect(self): for item in self['config']['networking_config']['EndpointsConfig'].keys(): self['config']['client'].disconnect_container_from_network(self['config']['name'], item) def remove(self): self['config']['client'].stop(self['config']['name'])",
"'.join(args) ) raw = self['container'].run(command) try: out = json.loads(raw or '{}') except ValueError:",
"with open('/proc/{0}/status'.format(pid), 'rb') as _file: contents = _file.read() try: container_pid = re.search(\"NSpid.+{0}.+\".format(pid), contents).group().split('\\t')[-1]",
"= { \"host\": item[\"ip\"], \"user\": item['ssh_config']['user'], \"password\": item['ssh_config']['password'] } roster.write(yaml.safe_dump(content, default_flow_style=False)) self['container']['config']['client'].copy_to(self, roster.strpath,",
"*args): command = \"salt-call {0} {1} --output=json -l quiet\".format( salt_command, ' '.join(args) )",
"import yaml import tarfile import logging import six import subprocess from .utils import",
"self['config']['client'].run( self['config']['name'], command, stream=stream) @retry() def check_run(self, command, stream=False): cmd_exec = self['config']['client'].exec_create(self['config']['name'], cmd=command,",
"= re.match('([a-zA-Z]+)\\s*=\\s*(\\d+)', line) if match: info.update([[match.group(1), int(match.group(2))]]) return info def get_os_release(self): content =",
"command, stream=False): cmd_exec = self['config']['client'].exec_create(self['config']['name'], cmd=command, stderr=False) return cmd_exec['Id'], self['config']['client'].exec_start(cmd_exec['Id'], stream=stream) def get_suse_release(self):",
"dict( filter( lambda it: len(it) == 2, [it.replace('\"', '').strip().split('=') for it in content.split('\\n')]"
] |
[
"history.events expect = [10, 20, 30] self.assertEqual(expect, result) def test_general_case(self): clicks = rx.Stream()",
"rx.Stream() result = rx.scan_reset_emit_seed( clicks, lambda a, i: a + i, reset=indices) history",
"[] super().__init__() def notify(self, value): self.events.append(value) class TestRx(unittest.TestCase): def test_combine_streams(self): clicks = rx.Stream()",
"lambda a, i: a + i, reset=indices) history = History() result.register(history) indices.emit(10) indices.emit(20)",
"clicks.emit(+0) indices.emit(30) clicks.emit(+1) result = history.events expect = [20, 31] self.assertEqual(expect, result) def",
"= history.events expect = [10, 11, 10, 20, 21, 30, 29] self.assertEqual(expect, result)",
"import rx class History(rx.Stream): def __init__(self): self.events = [] super().__init__() def notify(self, value):",
"= History() result.register(history) indices.emit(10) indices.emit(20) clicks.emit(+0) indices.emit(30) clicks.emit(+1) result = history.events expect =",
"rx class History(rx.Stream): def __init__(self): self.events = [] super().__init__() def notify(self, value): self.events.append(value)",
"value): self.events.append(value) class TestRx(unittest.TestCase): def test_combine_streams(self): clicks = rx.Stream() indices = rx.Stream() result",
"result = history.events expect = [20, 31] self.assertEqual(expect, result) def test_combine_streams_with_seed_values(self): clicks =",
"history = History() result.register(history) indices.emit(10) clicks.emit(1) clicks.emit(-1) indices.emit(20) clicks.emit(1) indices.emit(30) clicks.emit(-1) result =",
"31] self.assertEqual(expect, result) def test_combine_streams_with_seed_values(self): clicks = rx.Stream() indices = rx.Stream() result =",
"indices.emit(20) clicks.emit(+0) indices.emit(30) clicks.emit(+1) result = history.events expect = [20, 31] self.assertEqual(expect, result)",
"class History(rx.Stream): def __init__(self): self.events = [] super().__init__() def notify(self, value): self.events.append(value) class",
"History(rx.Stream): def __init__(self): self.events = [] super().__init__() def notify(self, value): self.events.append(value) class TestRx(unittest.TestCase):",
"a + i, reset=indices) history = History() result.register(history) indices.emit(10) clicks.emit(1) clicks.emit(-1) indices.emit(20) clicks.emit(1)",
"i: a + i, reset=indices) history = History() result.register(history) indices.emit(10) indices.emit(20) clicks.emit(+0) indices.emit(30)",
"self.assertEqual(expect, result) def test_combine_streams_with_seed_values(self): clicks = rx.Stream() indices = rx.Stream() result = rx.scan_reset_emit_seed(",
"self.assertEqual(expect, result) def test_general_case(self): clicks = rx.Stream() indices = rx.Stream() result = rx.scan_reset_emit_seed(",
"self.events = [] super().__init__() def notify(self, value): self.events.append(value) class TestRx(unittest.TestCase): def test_combine_streams(self): clicks",
"result.register(history) indices.emit(10) indices.emit(20) clicks.emit(+0) indices.emit(30) clicks.emit(+1) result = history.events expect = [20, 31]",
"i: a + i, reset=indices) history = History() result.register(history) indices.emit(10) indices.emit(20) indices.emit(30) result",
"result.register(history) indices.emit(10) clicks.emit(1) clicks.emit(-1) indices.emit(20) clicks.emit(1) indices.emit(30) clicks.emit(-1) result = history.events expect =",
"indices.emit(30) clicks.emit(+1) result = history.events expect = [20, 31] self.assertEqual(expect, result) def test_combine_streams_with_seed_values(self):",
"i: a + i, reset=indices) history = History() result.register(history) indices.emit(10) clicks.emit(1) clicks.emit(-1) indices.emit(20)",
"def test_combine_streams_with_seed_values(self): clicks = rx.Stream() indices = rx.Stream() result = rx.scan_reset_emit_seed( clicks, lambda",
"= history.events expect = [10, 20, 30] self.assertEqual(expect, result) def test_general_case(self): clicks =",
"def test_combine_streams(self): clicks = rx.Stream() indices = rx.Stream() result = rx.scan_reset( clicks, accumulator=lambda",
"= [20, 31] self.assertEqual(expect, result) def test_combine_streams_with_seed_values(self): clicks = rx.Stream() indices = rx.Stream()",
"+ i, reset=indices) history = History() result.register(history) indices.emit(10) indices.emit(20) indices.emit(30) result = history.events",
"rx.Stream() result = rx.scan_reset( clicks, accumulator=lambda a, i: a + i, reset=indices) history",
"indices.emit(20) indices.emit(30) result = history.events expect = [10, 20, 30] self.assertEqual(expect, result) def",
"clicks = rx.Stream() indices = rx.Stream() result = rx.scan_reset( clicks, accumulator=lambda a, i:",
"__init__(self): self.events = [] super().__init__() def notify(self, value): self.events.append(value) class TestRx(unittest.TestCase): def test_combine_streams(self):",
"clicks, accumulator=lambda a, i: a + i, reset=indices) history = History() result.register(history) indices.emit(10)",
"result = rx.scan_reset( clicks, accumulator=lambda a, i: a + i, reset=indices) history =",
"= [10, 20, 30] self.assertEqual(expect, result) def test_general_case(self): clicks = rx.Stream() indices =",
"clicks.emit(-1) result = history.events expect = [10, 11, 10, 20, 21, 30, 29]",
"super().__init__() def notify(self, value): self.events.append(value) class TestRx(unittest.TestCase): def test_combine_streams(self): clicks = rx.Stream() indices",
"history = History() result.register(history) indices.emit(10) indices.emit(20) clicks.emit(+0) indices.emit(30) clicks.emit(+1) result = history.events expect",
"rx.scan_reset_emit_seed( clicks, lambda a, i: a + i, reset=indices) history = History() result.register(history)",
"notify(self, value): self.events.append(value) class TestRx(unittest.TestCase): def test_combine_streams(self): clicks = rx.Stream() indices = rx.Stream()",
"reset=indices) history = History() result.register(history) indices.emit(10) indices.emit(20) clicks.emit(+0) indices.emit(30) clicks.emit(+1) result = history.events",
"a, i: a + i, reset=indices) history = History() result.register(history) indices.emit(10) clicks.emit(1) clicks.emit(-1)",
"i, reset=indices) history = History() result.register(history) indices.emit(10) clicks.emit(1) clicks.emit(-1) indices.emit(20) clicks.emit(1) indices.emit(30) clicks.emit(-1)",
"= History() result.register(history) indices.emit(10) indices.emit(20) indices.emit(30) result = history.events expect = [10, 20,",
"result = history.events expect = [10, 11, 10, 20, 21, 30, 29] self.assertEqual(expect,",
"def __init__(self): self.events = [] super().__init__() def notify(self, value): self.events.append(value) class TestRx(unittest.TestCase): def",
"result) def test_general_case(self): clicks = rx.Stream() indices = rx.Stream() result = rx.scan_reset_emit_seed( clicks,",
"unittest import rx class History(rx.Stream): def __init__(self): self.events = [] super().__init__() def notify(self,",
"class TestRx(unittest.TestCase): def test_combine_streams(self): clicks = rx.Stream() indices = rx.Stream() result = rx.scan_reset(",
"indices.emit(30) result = history.events expect = [10, 20, 30] self.assertEqual(expect, result) def test_general_case(self):",
"expect = [20, 31] self.assertEqual(expect, result) def test_combine_streams_with_seed_values(self): clicks = rx.Stream() indices =",
"indices.emit(20) clicks.emit(1) indices.emit(30) clicks.emit(-1) result = history.events expect = [10, 11, 10, 20,",
"clicks.emit(+1) result = history.events expect = [20, 31] self.assertEqual(expect, result) def test_combine_streams_with_seed_values(self): clicks",
"= history.events expect = [20, 31] self.assertEqual(expect, result) def test_combine_streams_with_seed_values(self): clicks = rx.Stream()",
"History() result.register(history) indices.emit(10) clicks.emit(1) clicks.emit(-1) indices.emit(20) clicks.emit(1) indices.emit(30) clicks.emit(-1) result = history.events expect",
"+ i, reset=indices) history = History() result.register(history) indices.emit(10) clicks.emit(1) clicks.emit(-1) indices.emit(20) clicks.emit(1) indices.emit(30)",
"20, 30] self.assertEqual(expect, result) def test_general_case(self): clicks = rx.Stream() indices = rx.Stream() result",
"i, reset=indices) history = History() result.register(history) indices.emit(10) indices.emit(20) clicks.emit(+0) indices.emit(30) clicks.emit(+1) result =",
"expect = [10, 20, 30] self.assertEqual(expect, result) def test_general_case(self): clicks = rx.Stream() indices",
"indices = rx.Stream() result = rx.scan_reset_emit_seed( clicks, lambda a, i: a + i,",
"History() result.register(history) indices.emit(10) indices.emit(20) indices.emit(30) result = history.events expect = [10, 20, 30]",
"= History() result.register(history) indices.emit(10) clicks.emit(1) clicks.emit(-1) indices.emit(20) clicks.emit(1) indices.emit(30) clicks.emit(-1) result = history.events",
"indices.emit(10) indices.emit(20) clicks.emit(+0) indices.emit(30) clicks.emit(+1) result = history.events expect = [20, 31] self.assertEqual(expect,",
"rx.Stream() indices = rx.Stream() result = rx.scan_reset_emit_seed( clicks, lambda a, i: a +",
"= rx.scan_reset( clicks, accumulator=lambda a, i: a + i, reset=indices) history = History()",
"test_general_case(self): clicks = rx.Stream() indices = rx.Stream() result = rx.scan_reset_emit_seed( clicks, lambda a,",
"def notify(self, value): self.events.append(value) class TestRx(unittest.TestCase): def test_combine_streams(self): clicks = rx.Stream() indices =",
"indices.emit(10) indices.emit(20) indices.emit(30) result = history.events expect = [10, 20, 30] self.assertEqual(expect, result)",
"= [] super().__init__() def notify(self, value): self.events.append(value) class TestRx(unittest.TestCase): def test_combine_streams(self): clicks =",
"= rx.scan_reset_emit_seed( clicks, lambda a, i: a + i, reset=indices) history = History()",
"= rx.Stream() result = rx.scan_reset( clicks, accumulator=lambda a, i: a + i, reset=indices)",
"import unittest import rx class History(rx.Stream): def __init__(self): self.events = [] super().__init__() def",
"history = History() result.register(history) indices.emit(10) indices.emit(20) indices.emit(30) result = history.events expect = [10,",
"a + i, reset=indices) history = History() result.register(history) indices.emit(10) indices.emit(20) indices.emit(30) result =",
"test_combine_streams_with_seed_values(self): clicks = rx.Stream() indices = rx.Stream() result = rx.scan_reset_emit_seed( clicks, lambda a,",
"[20, 31] self.assertEqual(expect, result) def test_combine_streams_with_seed_values(self): clicks = rx.Stream() indices = rx.Stream() result",
"clicks.emit(-1) indices.emit(20) clicks.emit(1) indices.emit(30) clicks.emit(-1) result = history.events expect = [10, 11, 10,",
"clicks = rx.Stream() indices = rx.Stream() result = rx.scan_reset_emit_seed( clicks, lambda a, i:",
"indices = rx.Stream() result = rx.scan_reset( clicks, accumulator=lambda a, i: a + i,",
"result = rx.scan_reset_emit_seed( clicks, lambda a, i: a + i, reset=indices) history =",
"= rx.Stream() indices = rx.Stream() result = rx.scan_reset( clicks, accumulator=lambda a, i: a",
"clicks.emit(1) indices.emit(30) clicks.emit(-1) result = history.events expect = [10, 11, 10, 20, 21,",
"a + i, reset=indices) history = History() result.register(history) indices.emit(10) indices.emit(20) clicks.emit(+0) indices.emit(30) clicks.emit(+1)",
"= rx.Stream() indices = rx.Stream() result = rx.scan_reset_emit_seed( clicks, lambda a, i: a",
"rx.Stream() indices = rx.Stream() result = rx.scan_reset( clicks, accumulator=lambda a, i: a +",
"self.events.append(value) class TestRx(unittest.TestCase): def test_combine_streams(self): clicks = rx.Stream() indices = rx.Stream() result =",
"reset=indices) history = History() result.register(history) indices.emit(10) indices.emit(20) indices.emit(30) result = history.events expect =",
"History() result.register(history) indices.emit(10) indices.emit(20) clicks.emit(+0) indices.emit(30) clicks.emit(+1) result = history.events expect = [20,",
"result = history.events expect = [10, 20, 30] self.assertEqual(expect, result) def test_general_case(self): clicks",
"lambda a, i: a + i, reset=indices) history = History() result.register(history) indices.emit(10) clicks.emit(1)",
"reset=indices) history = History() result.register(history) indices.emit(10) clicks.emit(1) clicks.emit(-1) indices.emit(20) clicks.emit(1) indices.emit(30) clicks.emit(-1) result",
"rx.scan_reset( clicks, accumulator=lambda a, i: a + i, reset=indices) history = History() result.register(history)",
"test_combine_streams(self): clicks = rx.Stream() indices = rx.Stream() result = rx.scan_reset( clicks, accumulator=lambda a,",
"def test_general_case(self): clicks = rx.Stream() indices = rx.Stream() result = rx.scan_reset_emit_seed( clicks, lambda",
"30] self.assertEqual(expect, result) def test_general_case(self): clicks = rx.Stream() indices = rx.Stream() result =",
"a, i: a + i, reset=indices) history = History() result.register(history) indices.emit(10) indices.emit(20) indices.emit(30)",
"indices.emit(30) clicks.emit(-1) result = history.events expect = [10, 11, 10, 20, 21, 30,",
"result) def test_combine_streams_with_seed_values(self): clicks = rx.Stream() indices = rx.Stream() result = rx.scan_reset_emit_seed( clicks,",
"accumulator=lambda a, i: a + i, reset=indices) history = History() result.register(history) indices.emit(10) indices.emit(20)",
"history.events expect = [20, 31] self.assertEqual(expect, result) def test_combine_streams_with_seed_values(self): clicks = rx.Stream() indices",
"indices.emit(10) clicks.emit(1) clicks.emit(-1) indices.emit(20) clicks.emit(1) indices.emit(30) clicks.emit(-1) result = history.events expect = [10,",
"a, i: a + i, reset=indices) history = History() result.register(history) indices.emit(10) indices.emit(20) clicks.emit(+0)",
"+ i, reset=indices) history = History() result.register(history) indices.emit(10) indices.emit(20) clicks.emit(+0) indices.emit(30) clicks.emit(+1) result",
"[10, 20, 30] self.assertEqual(expect, result) def test_general_case(self): clicks = rx.Stream() indices = rx.Stream()",
"result.register(history) indices.emit(10) indices.emit(20) indices.emit(30) result = history.events expect = [10, 20, 30] self.assertEqual(expect,",
"clicks, lambda a, i: a + i, reset=indices) history = History() result.register(history) indices.emit(10)",
"i, reset=indices) history = History() result.register(history) indices.emit(10) indices.emit(20) indices.emit(30) result = history.events expect",
"clicks.emit(1) clicks.emit(-1) indices.emit(20) clicks.emit(1) indices.emit(30) clicks.emit(-1) result = history.events expect = [10, 11,",
"= rx.Stream() result = rx.scan_reset_emit_seed( clicks, lambda a, i: a + i, reset=indices)",
"TestRx(unittest.TestCase): def test_combine_streams(self): clicks = rx.Stream() indices = rx.Stream() result = rx.scan_reset( clicks,"
] |